@polos/sdk 0.2.0 → 0.2.1
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/dist/index.cjs +44 -29
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +26 -4
- package/dist/index.d.ts +26 -4
- package/dist/index.js +44 -29
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/registry.ts","../src/runtime/execution-context.ts","../src/middleware/hook.ts","../src/core/workflow.ts","../src/runtime/orchestrator-client.ts","../src/execution-handle.ts","../src/client.ts","../src/core/tool.ts","../src/llm/types.ts","../src/llm/llm.ts","../src/middleware/guardrail.ts","../src/utils/retry.ts","../src/core/step.ts","../src/middleware/hook-executor.ts","../src/middleware/guardrail-executor.ts","../src/llm/generate.ts","../src/llm/stream.ts","../src/agents/stop-conditions.ts","../src/utils/logger.ts","../src/memory/tokens.ts","../src/memory/compaction.ts","../src/agents/stream.ts","../src/agents/stream-result.ts","../src/agents/agent.ts","../src/runtime/worker-server.ts","../src/utils/serializer.ts","../src/core/state.ts","../node_modules/@opentelemetry/core/src/trace/suppress-tracing.ts","../node_modules/@opentelemetry/core/src/internal/validators.ts","../node_modules/@opentelemetry/core/src/trace/TraceState.ts","../node_modules/@opentelemetry/core/src/trace/W3CTraceContextPropagator.ts","../src/features/tracing.ts","../src/utils/tracing.ts","../src/runtime/executor.ts","../src/execution/output.ts","../src/execution/docker.ts","../src/execution/local.ts","../src/execution/sandbox.ts","../src/execution/sandbox-manager.ts","../src/runtime/worker.ts","../src/polos.ts","../src/runtime/queue.ts","../src/runtime/batch.ts","../src/types/agent.ts","../src/tools/ask-user.ts","../src/tools/web-search.ts","../src/execution/security.ts","../src/execution/tools/exec.ts","../src/execution/tools/path-approval.ts","../src/execution/tools/read.ts","../src/execution/tools/write.ts","../src/execution/tools/edit.ts","../src/execution/tools/glob.ts","../src/execution/tools/grep.ts","../src/execution/sandbox-tools.ts","../src/channels/slack.ts"],"names":["AsyncLocalStorage","options","path","resolve","toJSONSchema","jsonSchema","Output","generateText","streamText","randomUUID","maxTokens","maxSteps","executedTool","hasText","appendFileSync","context","logger","Fastify","createContextKey","TraceState","W3CTraceContextPropagator","trace","isSpanContextValid","TraceFlags","SpanStatusCode","randomBytes","BasicTracerProvider","BatchSpanProcessor","AsyncLocalStorageContextManager","otelContext","otelTrace","spawn","fs","relative","DEFAULT_TIMEOUT_SECONDS","DEFAULT_MAX_OUTPUT_CHARS","path2","stat","fs2","path3","os","fs3","GuardrailResult","z"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAWO,IAAM,qBAAA,GAAN,cAAoC,KAAA,CAAM;AAAA,EAC/C,YAA4B,UAAA,EAAoB;AAC9C,IAAA,KAAA,CAAM,CAAA,oBAAA,EAAuB,UAAU,CAAA,CAAE,CAAA;AADf,IAAA,IAAA,CAAA,UAAA,GAAA,UAAA;AAE1B,IAAA,IAAA,CAAK,IAAA,GAAO,uBAAA;AAAA,EACd;AACF;AAKO,IAAM,sBAAA,GAAN,cAAqC,KAAA,CAAM;AAAA,EAChD,YAA4B,UAAA,EAAoB;AAC9C,IAAA,KAAA,CAAM,CAAA,6BAAA,EAAgC,UAAU,CAAA,CAAE,CAAA;AADxB,IAAA,IAAA,CAAA,UAAA,GAAA,UAAA;AAE1B,IAAA,IAAA,CAAK,IAAA,GAAO,wBAAA;AAAA,EACd;AACF;AA+CO,SAAS,sBAAA,GAA2C;AACzD,EAAA,MAAM,SAAA,uBAAgB,GAAA,EAAsB;AAE5C,EAAA,OAAO;AAAA,IACL,SAAS,QAAA,EAA0B;AACjC,MAAA,SAAA,CAAU,GAAA,CAAI,QAAA,CAAS,EAAA,EAAI,QAAQ,CAAA;AAAA,IACrC,CAAA;AAAA,IAEA,IAAI,UAAA,EAA8B;AAChC,MAAA,MAAM,QAAA,GAAW,SAAA,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AA;AAAA,YACX,IAAA,EAAM,EAAE,IAAA,EAAM,YAAA,EAAc,MAAM,QAAA,EAAS;AAAA,YAC3C,KAAA,EAAO,QAAA;AAAA,YACP,KAAA,EAAO;AAAA,WACT;AAAA,UACA;AAAA,YACE,IAAA,EAAM,QAAA;AAAA,YACN,IAAA,EAAM,EAAE,IAAA,EAAM,YAAA,EAAc,MAAM,cAAA,EAAe;AAAA,YACjD,KAAK,CAAA,CAAE;AAAA;AACT;AACF,OACD,CAAA;AAAA,IACH,CAAA,MAAO;AACL,MAAA,MAAA,CAAO,IAAA,CAAK;AAAA,QACV,IAAA,EAAM,SAAA;AAAA,QACN,QAAA,EAAU;AAAA,UACR;AAAA,YACE,IAAA,EAAM,QAAA;AAAA,YACN,IAAA,EAAM,EAAE,IAAA,EAAM,YAAA,EAAc,MAAM,SAAA,EAAU;AAAA,YAC5C,KAAK,CAAA,CAAE,WAAA;AAAA,YACP,KAAA,EAAO;AAAA;AACT;AACF,OACD,CAAA;AAAA,IACH;AAEA,IAAA,OAAO,MAAA;AAAA,EACT;AAAA,EAEQ,iBAAiB,CAAA,EAAiC;AACxD,IAAA,MAAM,SAAS,CAAA,CAAE,UAAA;AACjB,IAAA,IAAI,CAAC,MAAA,IAAU,MAAA,CAAO,MAAA,KAAW,GAAG,OAAO,KAAA;AAC3C,IAAA,OAAO,MAAA,CAAO,IAAA,CAAK,CAAC,CAAA,KAAM,CAAA,CAAE,KAAK,CAAA,KAAM,UAAA,IAAc,CAAA,CAAE,MAAM,CAAA,KAAM,SAAS,CAAA;AAAA,EAC9E;AACF","file":"index.cjs","sourcesContent":["/**\n * Workflow registry for tracking registered workflows.\n *\n * Used by Worker to find workflows to execute based on workflow ID.\n */\n\nimport type { Workflow } from '../types/workflow.js';\n\n/**\n * Error thrown when a workflow is not found in the registry.\n */\nexport class WorkflowNotFoundError extends Error {\n constructor(public readonly workflowId: string) {\n super(`Workflow not found: ${workflowId}`);\n this.name = 'WorkflowNotFoundError';\n }\n}\n\n/**\n * Error thrown when attempting to register a duplicate workflow.\n */\nexport class DuplicateWorkflowError extends Error {\n constructor(public readonly workflowId: string) {\n super(`Workflow already registered: ${workflowId}`);\n this.name = 'DuplicateWorkflowError';\n }\n}\n\n/**\n * Workflow registry interface.\n */\nexport interface WorkflowRegistry {\n /**\n * Register a workflow. If a workflow with the same ID is already\n * registered, it is silently replaced.\n */\n register(workflow: Workflow): void;\n\n /**\n * Get a workflow by ID.\n * @throws WorkflowNotFoundError if workflow is not found\n */\n get(workflowId: string): Workflow;\n\n /**\n * Check if a workflow is registered.\n */\n has(workflowId: string): boolean;\n\n /**\n * Get all registered workflows.\n */\n getAll(): Workflow[];\n\n /**\n * Get all workflow IDs.\n */\n getIds(): string[];\n\n /**\n * Remove a workflow from the registry.\n */\n remove(workflowId: string): boolean;\n\n /**\n * Clear all workflows from the registry.\n */\n clear(): void;\n}\n\n/**\n * Create a workflow registry.\n */\nexport function createWorkflowRegistry(): WorkflowRegistry {\n const workflows = new Map<string, Workflow>();\n\n return {\n register(workflow: Workflow): void {\n workflows.set(workflow.id, workflow);\n },\n\n get(workflowId: string): Workflow {\n const workflow = workflows.get(workflowId);\n if (!workflow) {\n throw new WorkflowNotFoundError(workflowId);\n }\n return workflow;\n },\n\n has(workflowId: string): boolean {\n return workflows.has(workflowId);\n },\n\n getAll(): Workflow[] {\n return Array.from(workflows.values());\n },\n\n getIds(): string[] {\n return Array.from(workflows.keys());\n },\n\n remove(workflowId: string): boolean {\n return workflows.delete(workflowId);\n },\n\n clear(): void {\n workflows.clear();\n },\n };\n}\n\n/**\n * Global workflow registry instance.\n * Uses globalThis so that ESM and CJS entry points share the same singleton\n * (avoids the dual-package hazard when both dist/index.js and dist/index.cjs\n * are loaded in the same process, e.g. via tsx).\n */\nconst REGISTRY_KEY = '__polos_global_registry__';\nexport const globalRegistry: WorkflowRegistry = ((globalThis as Record<string, unknown>)[\n REGISTRY_KEY\n] ??= createWorkflowRegistry()) as WorkflowRegistry;\n","/**\n * Execution context tracking using AsyncLocalStorage.\n *\n * Matches Python's _execution_context ContextVar in core/workflow.py.\n * Used to detect when code is running inside a workflow execution,\n * so that PolosClient methods can throw if misused from within a workflow.\n */\n\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport type { OrchestratorClient } from './orchestrator-client.js';\nimport type { SandboxManager } from '../execution/sandbox-manager.js';\n\n/**\n * Data stored in the execution context.\n */\nexport interface ExecutionContextData {\n executionId: string;\n workflowId: string;\n /** Root execution ID — stable across sub-workflows, used by sandbox tools for cache key. */\n rootExecutionId?: string | undefined;\n /** Session ID — used by sandbox tools to scope sandboxes. */\n sessionId?: string | undefined;\n /** Sandbox manager — injected by worker for managed sandbox lifecycle. */\n sandboxManager?: SandboxManager | undefined;\n /** Orchestrator client — needed by agents for conversation history. */\n orchestratorClient?: OrchestratorClient | undefined;\n /** OTel span context from current span (typed as unknown since @opentelemetry/api is optional). */\n _otelSpanContext?: unknown;\n /** Hex trace ID for the current span. */\n _otelTraceId?: string | undefined;\n /** Hex span ID for the current span. */\n _otelSpanId?: string | undefined;\n}\n\n/**\n * AsyncLocalStorage instance for tracking whether we're inside a workflow execution.\n * Matches Python's `_execution_context: ContextVar[dict | None]`.\n */\nconst executionContextStorage = new AsyncLocalStorage<ExecutionContextData>();\n\n/**\n * Run a function within an execution context.\n * Used by the executor to mark that workflow handler code is running.\n */\nexport function runInExecutionContext<T>(data: ExecutionContextData, fn: () => T): T {\n return executionContextStorage.run(data, fn);\n}\n\n/**\n * Check if we're currently inside a workflow execution.\n * Returns the context data if inside, undefined otherwise.\n */\nexport function getExecutionContext(): ExecutionContextData | undefined {\n return executionContextStorage.getStore();\n}\n\n/**\n * Assert that we're NOT inside a workflow execution.\n * Throws RuntimeError if called from within a workflow handler.\n *\n * Matches Python's pattern:\n * if _execution_context.get() is not None:\n * raise RuntimeError(\"... cannot be called from within a workflow ...\")\n */\nexport function assertNotInExecutionContext(methodName: string, alternative: string): void {\n const ctx = getExecutionContext();\n if (ctx !== undefined) {\n throw new Error(\n `${methodName} cannot be called from within a workflow or agent. ` +\n `Use ${alternative} to call workflows from within workflows.`\n );\n }\n}\n","/**\n * Lifecycle hooks for workflow and agent execution.\n *\n * Hooks allow intercepting and modifying workflow execution at key points.\n */\n\nimport type { WorkflowContext } from '../core/context.js';\n\n/**\n * Context passed to hooks during execution.\n */\nexport interface HookContext<TPayload = unknown> {\n /** Workflow ID (matching Python HookContext.workflow_id) */\n workflowId: string;\n /** Session ID (matching Python HookContext.session_id) */\n sessionId?: string | undefined;\n /** User ID (matching Python HookContext.user_id) */\n userId?: string | undefined;\n /** Current payload (may be modified by previous hooks) */\n currentPayload: TPayload;\n /** Current output (may be modified by previous hooks, only in onEnd) */\n // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents -- needed for exactOptionalPropertyTypes\n currentOutput?: unknown | undefined;\n /** Hook execution phase */\n phase: 'onStart' | 'onEnd';\n}\n\n/**\n * Result from a hook execution.\n */\nexport interface HookResultType {\n /** Whether to continue execution */\n continue: boolean;\n /** Error message if hook failed (matching Python HookResult.error_message) */\n error?: string | undefined;\n /** Modified payload (matching Python HookResult.modified_payload) */\n // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents -- needed for exactOptionalPropertyTypes\n modifiedPayload?: unknown | undefined;\n /** Modified output (matching Python HookResult.modified_output, only in onEnd) */\n // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents -- needed for exactOptionalPropertyTypes\n modifiedOutput?: unknown | undefined;\n}\n\n/**\n * Hook function type for workflow lifecycle events.\n */\nexport type HookHandler<TPayload = unknown, TState = unknown> = (\n ctx: WorkflowContext<TState>,\n hookCtx: HookContext<TPayload>\n) => Promise<HookResultType>;\n\n/**\n * Hook definition with optional metadata.\n */\nexport interface Hook<TPayload = unknown, TState = unknown> {\n /** Hook handler function */\n handler: HookHandler<TPayload, TState>;\n /** Optional hook name for debugging/tracing */\n name?: string | undefined;\n /** Optional hook description */\n description?: string | undefined;\n}\n\n/**\n * Options for defining a hook.\n */\nexport interface DefineHookOptions {\n /** Hook name for debugging/tracing */\n name?: string | undefined;\n /** Hook description */\n description?: string | undefined;\n}\n\n/**\n * Helper for creating hook results.\n */\nexport const HookResult = {\n /** Continue execution without modifications */\n continue: (): HookResultType => ({ continue: true }),\n\n /**\n * Continue execution with modifications.\n *\n * @example\n * ```typescript\n * return HookResult.continueWith({\n * modifiedPayload: {\n * ...hookCtx.currentPayload,\n * timestamp: Date.now(),\n * },\n * });\n * ```\n */\n continueWith: (options: {\n modifiedPayload?: unknown;\n modifiedOutput?: unknown;\n }): HookResultType => {\n const result: HookResultType = { continue: true };\n if (options.modifiedPayload !== undefined) {\n result.modifiedPayload = options.modifiedPayload;\n }\n if (options.modifiedOutput !== undefined) {\n result.modifiedOutput = options.modifiedOutput;\n }\n return result;\n },\n\n /**\n * Stop execution with an error.\n *\n * @example\n * ```typescript\n * if (!hookCtx.currentPayload.userId) {\n * return HookResult.fail('userId is required');\n * }\n * ```\n */\n fail: (error: string): HookResultType => ({\n continue: false,\n error,\n }),\n};\n\n/**\n * Define a hook for workflow lifecycle events.\n *\n * @example\n * ```typescript\n * const loggingHook = defineHook(async (ctx, hookCtx) => {\n * console.log(`Starting workflow: ${ctx.workflowId}`);\n * console.log(`Payload: ${JSON.stringify(hookCtx.currentPayload)}`);\n * return HookResult.continue();\n * });\n *\n * const validationHook = defineHook(\n * async (ctx, hookCtx) => {\n * if (!hookCtx.currentPayload.userId) {\n * return HookResult.fail('userId is required');\n * }\n * return HookResult.continue();\n * },\n * { name: 'validation-hook', description: 'Validates required fields' }\n * );\n * ```\n */\nexport function defineHook<TPayload = unknown, TState = unknown>(\n handler: HookHandler<TPayload, TState>,\n options?: DefineHookOptions\n): Hook<TPayload, TState> {\n return {\n handler,\n name: options?.name,\n description: options?.description,\n };\n}\n\n/**\n * Type guard to check if a value is a Hook object.\n */\nexport function isHook<TPayload = unknown, TState = unknown>(\n value: unknown\n): value is Hook<TPayload, TState> {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'handler' in value &&\n typeof (value as Hook).handler === 'function'\n );\n}\n\n/**\n * Normalize a hook handler or Hook object to a Hook.\n */\nexport function normalizeHook<TPayload = unknown, TState = unknown>(\n hookOrHandler: Hook<TPayload, TState> | HookHandler<TPayload, TState>\n): Hook<TPayload, TState> {\n if (isHook<TPayload, TState>(hookOrHandler)) {\n return hookOrHandler;\n }\n return { handler: hookOrHandler };\n}\n\n/**\n * Normalize an array of hooks or handlers.\n */\nexport function normalizeHooks<TPayload = unknown, TState = unknown>(\n hooks:\n | Hook<TPayload, TState>\n | HookHandler<TPayload, TState>\n | (Hook<TPayload, TState> | HookHandler<TPayload, TState>)[]\n | undefined\n): Hook<TPayload, TState>[] {\n if (hooks === undefined) {\n return [];\n }\n\n if (Array.isArray(hooks)) {\n return hooks.map((h) => normalizeHook(h));\n }\n\n return [normalizeHook(hooks)];\n}\n","/**\n * Workflow definition and creation.\n *\n * Provides the defineWorkflow function for creating typed, durable workflows.\n */\n\nimport type { ZodType } from 'zod';\nimport type { WorkflowContext } from './context.js';\nimport type { Channel } from '../channels/channel.js';\nimport { globalRegistry } from './registry.js';\nimport { assertNotInExecutionContext } from '../runtime/execution-context.js';\n\n// Re-export hook types from middleware (single source of truth)\nexport type {\n HookContext,\n HookResultType,\n HookHandler,\n Hook,\n DefineHookOptions,\n} from '../middleware/hook.js';\nexport {\n HookResult,\n defineHook,\n isHook,\n normalizeHook,\n normalizeHooks,\n} from '../middleware/hook.js';\n\n// Import types needed for WorkflowConfig\nimport type { HookHandler, Hook as HookObject } from '../middleware/hook.js';\n\n/**\n * Queue configuration for workflow execution.\n */\nexport interface QueueConfig {\n /** Queue name */\n name: string;\n /** Maximum concurrent executions in this queue */\n concurrencyLimit?: number | undefined;\n}\n\n/**\n * Schedule configuration for workflows.\n */\nexport interface ScheduleConfig {\n /** Cron expression (e.g., '0 8 * * *') */\n cron: string;\n /** Timezone for the schedule (e.g., 'America/New_York') */\n timezone?: string | undefined;\n}\n\n/**\n * Configuration for defining a workflow.\n */\nexport interface WorkflowConfig<TPayload = unknown, TState = unknown, TResult = unknown> {\n /** Unique workflow identifier */\n id: string;\n /** Description for team coordination */\n description?: string | undefined;\n /** Workflow type: \"workflow\", \"agent\", or \"tool\" (default: \"workflow\") */\n workflowType?: string | undefined;\n /** Queue assignment (string name or full config) */\n queue?: string | QueueConfig | undefined;\n /** Schedule for automatic execution. Set to true (without a cron) to mark as dynamically schedulable via client.schedules.create(). */\n schedule?: string | ScheduleConfig | boolean | undefined;\n /** Event topic that triggers this workflow */\n triggerOnEvent?: string | undefined;\n /** Batch size for event-triggered workflows */\n batchSize?: number | undefined;\n /** Batch timeout in seconds for event-triggered workflows */\n batchTimeoutSeconds?: number | undefined;\n /** Zod schema for payload validation */\n payloadSchema?: ZodType<TPayload> | undefined;\n /** Zod schema for state validation and defaults */\n stateSchema?: ZodType<TState> | undefined;\n /** Zod schema for output/result validation */\n outputSchema?: ZodType<TResult> | undefined;\n /** Hook(s) to run before workflow execution (bare function or Hook object) */\n onStart?:\n | HookHandler<TPayload, TState>\n | HookObject<TPayload, TState>\n | (HookHandler<TPayload, TState> | HookObject<TPayload, TState>)[]\n | undefined;\n /** Hook(s) to run after workflow completion (bare function or Hook object) */\n onEnd?:\n | HookHandler<TPayload, TState>\n | HookObject<TPayload, TState>\n | (HookHandler<TPayload, TState> | HookObject<TPayload, TState>)[]\n | undefined;\n /** Notification channels for suspend events. Overrides Worker-level channels. */\n channels?: Channel[] | undefined;\n}\n\n/**\n * Workflow handler function type.\n */\nexport type WorkflowHandler<TPayload, TState, TResult> = (\n ctx: WorkflowContext<TState>,\n payload: TPayload\n) => Promise<TResult>;\n\n/**\n * Handle to a running or completed workflow execution.\n */\nexport interface WorkflowHandle<TResult> {\n /** Execution identifier */\n executionId: string;\n /** Get the current status of the workflow */\n getStatus(): Promise<WorkflowStatus<TResult>>;\n /** Wait for the workflow to complete and return result */\n waitForResult(options?: { timeout?: number }): Promise<TResult>;\n /** Cancel the workflow execution */\n cancel(): Promise<void>;\n}\n\n/**\n * Status of a workflow execution.\n */\nexport interface WorkflowStatus<TResult> {\n status: 'queued' | 'running' | 'completed' | 'failed' | 'cancelled';\n result?: TResult | undefined;\n error?: string | undefined;\n createdAt: Date;\n completedAt?: Date | undefined;\n}\n\n/**\n * Minimal client interface for workflow.run() and workflow.invoke().\n * PolosClient satisfies this interface structurally.\n */\nexport interface WorkflowRunClient {\n invoke(\n workflow: string,\n payload?: unknown,\n options?: {\n initialState?: Record<string, unknown>;\n sessionId?: string;\n userId?: string;\n queueName?: string;\n concurrencyKey?: string;\n runTimeoutSeconds?: number;\n }\n ): Promise<{ getResult(timeout?: number): Promise<unknown> }>;\n}\n\n/**\n * Options for workflow.run().\n */\nexport interface WorkflowRunOptions {\n /** Timeout in seconds (default: 600) */\n timeout?: number | undefined;\n /** Initial state for the workflow */\n initialState?: Record<string, unknown> | undefined;\n /** Session ID */\n sessionId?: string | undefined;\n /** User ID */\n userId?: string | undefined;\n /** Queue name override */\n queueName?: string | undefined;\n /** Concurrency key for per-tenant queuing */\n concurrencyKey?: string | undefined;\n}\n\n/**\n * Workflow instance with configuration and handler.\n */\nexport interface Workflow<TPayload = unknown, TState = unknown, TResult = unknown> {\n /** Workflow identifier */\n readonly id: string;\n /** Description for team coordination */\n readonly description?: string | undefined;\n /** Workflow configuration */\n readonly config: WorkflowConfig<TPayload, TState, TResult>;\n /** Workflow handler function */\n readonly handler: WorkflowHandler<TPayload, TState, TResult>;\n /** Payload schema (if provided) */\n readonly payloadSchema?: ZodType<TPayload> | undefined;\n /** State schema (if provided) */\n readonly stateSchema?: ZodType<TState> | undefined;\n /** Output schema (if provided) */\n readonly outputSchema?: ZodType<TResult> | undefined;\n /**\n * Run workflow and wait for result (invoke + poll until complete).\n * Cannot be called from within a workflow; use step.invokeAndWait() instead.\n * Matches Python's workflow.run().\n */\n // Method syntax enables bivariant checking so AgentWorkflow can override with specific types\n run(client: WorkflowRunClient, payload: TPayload, options?: WorkflowRunOptions): Promise<TResult>;\n}\n\n/**\n * Infer payload type from a workflow.\n */\nexport type InferPayload<T> = T extends Workflow<infer P> ? P : never;\n\n/**\n * Infer state type from a workflow.\n */\nexport type InferState<T> = T extends Workflow<unknown, infer S> ? S : never;\n\n/**\n * Infer result type from a workflow.\n */\nexport type InferResult<T> = T extends Workflow<unknown, unknown, infer R> ? R : never;\n\n/**\n * Options for defineWorkflow.\n */\nexport interface DefineWorkflowOptions {\n /** Whether to auto-register the workflow in the global registry (default: true) */\n autoRegister?: boolean | undefined;\n}\n\n/**\n * Define a workflow with typed payload, state, and result.\n *\n * @example\n * ```typescript\n * import { defineWorkflow } from '@polos/sdk';\n * import { z } from 'zod';\n *\n * const myWorkflow = defineWorkflow({\n * id: 'my-workflow',\n * payloadSchema: z.object({ userId: z.string() }),\n * stateSchema: z.object({ count: z.number().default(0) }),\n * }, async (ctx, payload) => {\n * ctx.state.count += 1;\n * return { userId: payload.userId, count: ctx.state.count };\n * });\n * ```\n */\n/**\n * Validate that a cron expression uses minute granularity (5 fields), not second granularity (6 fields).\n * @internal\n */\nexport function validateCronGranularity(cron: string): void {\n const fields = cron.trim().split(/\\s+/);\n if (fields.length > 5) {\n throw new Error(\n `Cron expression \"${cron}\" appears to use second-level granularity (${String(fields.length)} fields). ` +\n 'Only minute-level granularity is supported (5 fields: min hour dom month dow).'\n );\n }\n}\n\nexport function defineWorkflow<TPayload = unknown, TState = unknown, TResult = unknown>(\n config: WorkflowConfig<TPayload, TState, TResult>,\n handler: WorkflowHandler<TPayload, TState, TResult>,\n options?: DefineWorkflowOptions\n): Workflow<TPayload, TState, TResult> {\n // Validate cron granularity if schedule is provided (skip boolean-only schedule)\n if (config.schedule && config.schedule !== true) {\n const cron = typeof config.schedule === 'string' ? config.schedule : config.schedule.cron;\n validateCronGranularity(cron);\n }\n\n const workflow: Workflow<TPayload, TState, TResult> = {\n id: config.id,\n description: config.description,\n config,\n handler,\n payloadSchema: config.payloadSchema,\n stateSchema: config.stateSchema,\n outputSchema: config.outputSchema,\n run: async (client, payload, options) => {\n assertNotInExecutionContext('workflow.run()', 'step.invokeAndWait()');\n const invokeOpts: Record<string, unknown> = {};\n if (options?.initialState !== undefined) invokeOpts['initialState'] = options.initialState;\n if (options?.sessionId !== undefined) invokeOpts['sessionId'] = options.sessionId;\n if (options?.userId !== undefined) invokeOpts['userId'] = options.userId;\n if (options?.queueName !== undefined) invokeOpts['queueName'] = options.queueName;\n if (options?.concurrencyKey !== undefined)\n invokeOpts['concurrencyKey'] = options.concurrencyKey;\n if (options?.timeout !== undefined)\n invokeOpts['runTimeoutSeconds'] = Math.ceil(options.timeout);\n const handle = await client.invoke(config.id, payload, invokeOpts);\n const result = await handle.getResult(options?.timeout ?? 600);\n return result as TResult;\n },\n };\n\n // Auto-register by default\n if (options?.autoRegister !== false) {\n globalRegistry.register(workflow as Workflow);\n }\n\n return workflow;\n}\n","/**\n * HTTP client for orchestrator API communication.\n */\n\nimport type {\n RegisterWorkerRequest,\n RegisterWorkerResponse,\n RegisterDeploymentRequest,\n RegisterWorkflowsRequest,\n RegisterQueuesRequest,\n RegisterAgentRequest,\n RegisterDeploymentWorkflowRequest,\n RegisterToolRequest,\n HeartbeatResponse,\n CompleteExecutionRequest,\n FailExecutionRequest,\n ConfirmCancellationRequest,\n StoreStepOutputRequest,\n StepOutput,\n SetWaitingRequest,\n PublishEventRequest,\n PublishEventResponse,\n StreamEventsParams,\n InvokeWorkflowRequest,\n InvokeWorkflowResponse,\n GetExecutionResponse,\n BatchInvokeWorkflowsRequest,\n BatchInvokeWorkflowsResponse,\n CreateScheduleRequest,\n CreateScheduleResponse,\n AddConversationHistoryRequest,\n GetConversationHistoryParams,\n ConversationMessage,\n SessionMemoryResponse,\n PutSessionMemoryRequest,\n GetActiveWorkersResponse,\n} from './orchestrator-types.js';\n\nimport type { StreamEvent } from '../types/events.js';\n\n/**\n * Configuration for OrchestratorClient.\n */\nexport interface OrchestratorClientConfig {\n /** Orchestrator API URL */\n apiUrl: string;\n /** API key for authentication */\n apiKey: string;\n /** Project ID */\n projectId: string;\n /** Request timeout in milliseconds (default: 30000) */\n timeout?: number | undefined;\n /** Max retries for failed requests (default: 3) */\n maxRetries?: number | undefined;\n}\n\n/**\n * Error thrown when orchestrator API request fails.\n */\nexport class OrchestratorApiError extends Error {\n constructor(\n message: string,\n public readonly statusCode: number,\n public readonly response?: unknown\n ) {\n super(message);\n this.name = 'OrchestratorApiError';\n }\n}\n\n/**\n * HTTP client for communicating with the Polos orchestrator.\n */\nexport class OrchestratorClient {\n private readonly apiUrl: string;\n private readonly apiKey: string;\n private readonly projectId: string;\n private readonly timeout: number;\n private readonly maxRetries: number;\n\n constructor(config: OrchestratorClientConfig) {\n this.apiUrl = config.apiUrl.replace(/\\/$/, ''); // Remove trailing slash\n this.apiKey = config.apiKey;\n this.projectId = config.projectId;\n this.timeout = config.timeout ?? 30000;\n this.maxRetries = config.maxRetries ?? 3;\n }\n\n /**\n * Get the API URL.\n */\n getApiUrl(): string {\n return this.apiUrl;\n }\n\n /**\n * Get the project ID.\n */\n getProjectId(): string {\n return this.projectId;\n }\n\n /**\n * Get default headers for API requests.\n */\n private getHeaders(workerId?: string): Record<string, string> {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.apiKey}`,\n 'X-Project-ID': this.projectId,\n };\n if (workerId) {\n headers['X-Worker-ID'] = workerId;\n }\n return headers;\n }\n\n /**\n * Make an HTTP request with retry logic.\n */\n private async request<T>(\n method: string,\n path: string,\n options?: {\n body?: unknown;\n workerId?: string;\n retries?: number;\n }\n ): Promise<T> {\n const url = `${this.apiUrl}${path}`;\n const retries = options?.retries ?? this.maxRetries;\n let lastError: Error | undefined;\n\n for (let attempt = 0; attempt <= retries; attempt++) {\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => {\n controller.abort();\n }, this.timeout);\n\n const fetchOptions: RequestInit = {\n method,\n headers: this.getHeaders(options?.workerId),\n signal: controller.signal,\n };\n if (options?.body) {\n fetchOptions.body = JSON.stringify(options.body);\n }\n const response = await fetch(url, fetchOptions);\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n const errorBody = await response.text().catch(() => '');\n let errorData: unknown;\n try {\n errorData = JSON.parse(errorBody);\n } catch {\n errorData = errorBody;\n }\n\n // Don't retry on 4xx errors (except 429)\n if (response.status >= 400 && response.status < 500 && response.status !== 429) {\n throw new OrchestratorApiError(\n `Request failed: ${String(response.status)} ${response.statusText}`,\n response.status,\n errorData\n );\n }\n\n throw new OrchestratorApiError(\n `Request failed: ${String(response.status)} ${response.statusText}`,\n response.status,\n errorData\n );\n }\n\n // Handle empty responses\n const text = await response.text();\n if (!text) {\n return undefined as T;\n }\n\n return JSON.parse(text) as T;\n } catch (error) {\n lastError = error instanceof Error ? error : new Error(String(error));\n\n // Don't retry on non-retryable errors\n if (\n error instanceof OrchestratorApiError &&\n error.statusCode < 500 &&\n error.statusCode !== 429\n ) {\n throw error;\n }\n\n // Wait before retry with exponential backoff\n if (attempt < retries) {\n const delay = Math.min(1000 * Math.pow(2, attempt), 16000);\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n }\n }\n\n throw lastError ?? new Error('Request failed after retries');\n }\n\n // ==================== Worker Lifecycle ====================\n\n /**\n * Register a worker with the orchestrator.\n */\n async registerWorker(request: RegisterWorkerRequest): Promise<RegisterWorkerResponse> {\n return this.request<RegisterWorkerResponse>('POST', '/api/v1/workers/register', {\n body: {\n deployment_id: request.deploymentId,\n project_id: request.projectId,\n mode: request.mode,\n capabilities: {\n runtime: request.capabilities.runtime,\n agent_ids: request.capabilities.agentIds,\n tool_ids: request.capabilities.toolIds,\n workflow_ids: request.capabilities.workflowIds,\n },\n max_concurrent_executions: request.maxConcurrentExecutions,\n push_endpoint_url: request.pushEndpointUrl,\n },\n });\n }\n\n /**\n * Get active worker IDs for the current project.\n * Uses the X-Project-ID header already set on all requests.\n */\n async getActiveWorkerIds(): Promise<string[]> {\n const response = await this.request<GetActiveWorkersResponse>('GET', '/api/v1/workers/active');\n return response.worker_ids;\n }\n\n /**\n * Register a deployment.\n */\n async registerDeployment(request: RegisterDeploymentRequest): Promise<void> {\n await this.request<undefined>('POST', '/api/v1/workers/deployments', {\n body: {\n deployment_id: request.deploymentId,\n },\n });\n }\n\n /**\n * Register workflows for a deployment.\n */\n async registerWorkflows(deploymentId: string, request: RegisterWorkflowsRequest): Promise<void> {\n await this.request<undefined>('POST', `/api/v1/workers/deployments/${deploymentId}/workflows`, {\n body: {\n workflows: request.workflows.map((w) => ({\n workflow_id: w.workflowId,\n queue_name: w.queueName,\n is_event_triggered: w.isEventTriggered,\n event_topic: w.eventTopic,\n batch_size: w.batchSize,\n is_scheduled: w.isScheduled,\n schedule: w.schedule,\n schedule_timezone: w.scheduleTimezone,\n })),\n },\n });\n }\n\n /**\n * Register queues.\n */\n async registerQueues(request: RegisterQueuesRequest): Promise<void> {\n await this.request<undefined>('POST', '/api/v1/workers/queues', {\n body: {\n deployment_id: request.deploymentId,\n queues: request.queues.map((q) => ({\n name: q.name,\n concurrency_limit: q.concurrencyLimit,\n })),\n },\n });\n }\n\n /**\n * Register a tool definition with the orchestrator.\n */\n async registerTool(request: RegisterToolRequest): Promise<void> {\n const body: Record<string, unknown> = {\n id: request.id,\n deployment_id: request.deploymentId,\n tool_type: request.toolType,\n description: request.description,\n parameters: request.parameters,\n };\n if (request.metadata !== undefined) {\n body['metadata'] = request.metadata;\n }\n\n await this.request<undefined>('POST', '/api/v1/tools/register', { body });\n }\n\n /**\n * Register an agent definition with the orchestrator.\n * Matches Python _register_agents() POST to /api/v1/agents/register.\n */\n async registerAgent(request: RegisterAgentRequest): Promise<void> {\n const body: Record<string, unknown> = {\n id: request.id,\n deployment_id: request.deploymentId,\n provider: request.provider,\n model: request.model,\n };\n if (request.systemPrompt !== undefined) body['system_prompt'] = request.systemPrompt;\n if (request.tools !== undefined) body['tools'] = request.tools;\n if (request.temperature !== undefined) body['temperature'] = request.temperature;\n if (request.maxOutputTokens !== undefined) body['max_output_tokens'] = request.maxOutputTokens;\n if (request.metadata !== undefined) body['metadata'] = request.metadata;\n\n await this.request<undefined>('POST', '/api/v1/agents/register', { body });\n }\n\n /**\n * Register a single workflow/agent/tool in deployment_workflows table.\n * Matches Python _register_deployment_workflow().\n */\n async registerDeploymentWorkflow(\n deploymentId: string,\n request: RegisterDeploymentWorkflowRequest\n ): Promise<void> {\n await this.request<undefined>('POST', `/api/v1/workers/deployments/${deploymentId}/workflows`, {\n body: {\n workflow_id: request.workflowId,\n workflow_type: request.workflowType,\n trigger_on_event: request.triggerOnEvent ?? false,\n scheduled: request.scheduled ?? false,\n },\n });\n }\n\n /**\n * Mark worker as online.\n */\n async markOnline(workerId: string): Promise<void> {\n await this.request<undefined>('POST', `/api/v1/workers/${workerId}/online`, {\n workerId,\n });\n }\n\n /**\n * Send heartbeat.\n */\n async sendHeartbeat(workerId: string): Promise<HeartbeatResponse> {\n return this.request<HeartbeatResponse>('POST', `/api/v1/workers/${workerId}/heartbeat`, {\n workerId,\n body: {},\n });\n }\n\n // ==================== Execution Reporting ====================\n\n /**\n * Complete an execution successfully.\n */\n async completeExecution(executionId: string, request: CompleteExecutionRequest): Promise<void> {\n await this.request<undefined>('POST', `/internal/executions/${executionId}/complete`, {\n workerId: request.workerId,\n body: {\n result: request.result,\n worker_id: request.workerId,\n output_schema_name: request.outputSchemaName,\n final_state: request.finalState,\n },\n });\n }\n\n /**\n * Fail an execution.\n */\n async failExecution(executionId: string, request: FailExecutionRequest): Promise<void> {\n await this.request<undefined>('POST', `/internal/executions/${executionId}/fail`, {\n workerId: request.workerId,\n body: {\n error: request.error,\n worker_id: request.workerId,\n stack: request.stack,\n retryable: request.retryable,\n final_state: request.finalState,\n },\n });\n }\n\n /**\n * Confirm cancellation of an execution.\n */\n async confirmCancellation(\n executionId: string,\n request: ConfirmCancellationRequest\n ): Promise<void> {\n await this.request<undefined>(\n 'POST',\n `/internal/executions/${executionId}/confirm-cancellation`,\n {\n workerId: request.workerId,\n body: {\n worker_id: request.workerId,\n },\n }\n );\n }\n\n // ==================== Step Persistence ====================\n\n /**\n * Store a step output.\n */\n async storeStepOutput(\n executionId: string,\n request: StoreStepOutputRequest,\n workerId?: string\n ): Promise<void> {\n const body: Record<string, unknown> = {\n step_key: request.stepKey,\n };\n if (request.outputs !== undefined) body['outputs'] = request.outputs;\n if (request.error !== undefined) body['error'] = request.error;\n if (request.success !== undefined) body['success'] = request.success;\n if (request.sourceExecutionId !== undefined)\n body['source_execution_id'] = request.sourceExecutionId;\n if (request.outputSchemaName !== undefined)\n body['output_schema_name'] = request.outputSchemaName;\n\n const options: { body: unknown; workerId?: string } = { body };\n if (workerId !== undefined) options.workerId = workerId;\n\n await this.request<undefined>('POST', `/internal/executions/${executionId}/steps`, options);\n }\n\n /**\n * Get a specific step output.\n */\n async getStepOutput(\n executionId: string,\n stepKey: string,\n workerId: string\n ): Promise<StepOutput | null> {\n try {\n const response = await this.request<{\n step_key: string;\n outputs: unknown;\n completed_at: string;\n success?: boolean;\n error?: unknown;\n output_schema_name?: string;\n source_execution_id?: string;\n }>('GET', `/internal/executions/${executionId}/steps/${encodeURIComponent(stepKey)}`, {\n workerId,\n });\n return {\n stepKey: response.step_key,\n outputs: response.outputs,\n completedAt: response.completed_at,\n success: response.success,\n error: response.error,\n outputSchemaName: response.output_schema_name,\n sourceExecutionId: response.source_execution_id,\n };\n } catch (error) {\n if (error instanceof OrchestratorApiError && error.statusCode === 404) {\n return null;\n }\n throw error;\n }\n }\n\n /**\n * Get all step outputs for an execution.\n */\n async getAllStepOutputs(executionId: string, workerId: string): Promise<StepOutput[]> {\n const response = await this.request<{\n steps: {\n step_key: string;\n outputs: unknown;\n completed_at: string;\n success?: boolean;\n error?: unknown;\n output_schema_name?: string;\n source_execution_id?: string;\n }[];\n }>('GET', `/internal/executions/${executionId}/steps`, { workerId });\n return response.steps.map((s) => ({\n stepKey: s.step_key,\n outputs: s.outputs,\n completedAt: s.completed_at,\n success: s.success,\n error: s.error,\n outputSchemaName: s.output_schema_name,\n sourceExecutionId: s.source_execution_id,\n }));\n }\n\n // ==================== Wait/Suspend ====================\n\n /**\n * Set execution to waiting state.\n */\n async setWaiting(\n executionId: string,\n request: SetWaitingRequest,\n workerId?: string\n ): Promise<void> {\n const options: { body: unknown; workerId?: string } = {\n body: {\n step_key: request.stepKey,\n wait_type: request.waitType,\n wait_until: request.waitUntil,\n wait_topic: request.waitTopic,\n expires_at: request.expiresAt,\n },\n };\n if (workerId !== undefined) options.workerId = workerId;\n\n await this.request<undefined>('POST', `/internal/executions/${executionId}/wait`, options);\n }\n\n // ==================== Events ====================\n\n /**\n * Publish events. Returns sequence IDs.\n */\n async publishEvent(request: PublishEventRequest): Promise<PublishEventResponse> {\n const body: Record<string, unknown> = {\n topic: request.topic,\n events: request.events.map((e) => {\n const entry: Record<string, unknown> = { data: e.data };\n if (e.eventType !== undefined) entry['event_type'] = e.eventType;\n return entry;\n }),\n };\n if (request.executionId !== undefined) body['execution_id'] = request.executionId;\n if (request.rootExecutionId !== undefined) body['root_execution_id'] = request.rootExecutionId;\n\n return this.request<PublishEventResponse>('POST', '/api/v1/events/publish', {\n body,\n });\n }\n\n /**\n * Stream events via SSE. Matching Python's _stream().\n */\n async *streamEvents(params: StreamEventsParams): AsyncGenerator<StreamEvent> {\n const queryParams = new URLSearchParams();\n queryParams.set('project_id', this.projectId);\n\n if (params.workflowRunId) {\n if (!params.workflowId) {\n throw new Error('workflowId must be provided when workflowRunId is provided');\n }\n queryParams.set('workflow_id', params.workflowId);\n queryParams.set('workflow_run_id', params.workflowRunId);\n } else if (params.topic) {\n queryParams.set('topic', params.topic);\n } else {\n throw new Error('Either topic or workflowRunId must be provided');\n }\n\n if (params.lastSequenceId !== undefined) {\n queryParams.set('last_sequence_id', String(params.lastSequenceId));\n } else if (params.lastTimestamp !== undefined) {\n queryParams.set('last_timestamp', params.lastTimestamp);\n } else {\n queryParams.set('last_timestamp', new Date().toISOString());\n }\n\n const url = `${this.apiUrl}/api/v1/events/stream?${queryParams.toString()}`;\n const headers = this.getHeaders();\n\n const response = await fetch(url, {\n method: 'GET',\n headers,\n });\n\n if (!response.ok) {\n throw new OrchestratorApiError(\n `Stream request failed: ${String(response.status)} ${response.statusText}`,\n response.status\n );\n }\n\n if (!response.body) {\n return;\n }\n\n const reader = response.body.getReader() as ReadableStreamDefaultReader<Uint8Array>;\n const decoder = new TextDecoder();\n let buffer = '';\n let currentEventData: string | null = null;\n\n try {\n for (;;) {\n const result = await reader.read();\n if (result.done) break;\n\n buffer += decoder.decode(result.value, { stream: true });\n const lines = buffer.split('\\n');\n // Keep the last partial line in the buffer\n buffer = lines.pop() ?? '';\n\n for (const rawLine of lines) {\n const line = rawLine.replace(/\\r$/, '');\n\n // Empty line indicates end of event\n if (!line) {\n if (currentEventData) {\n try {\n const eventDict = JSON.parse(currentEventData) as Record<string, unknown>;\n const data = eventDict['data'];\n const streamEvent: StreamEvent = {\n id: eventDict['id'] as string,\n sequenceId: eventDict['sequence_id'] as number,\n topic: eventDict['topic'] as string,\n eventType: eventDict['event_type'] as string | undefined,\n data: (typeof data === 'object' && data !== null ? data : {}) as Record<\n string,\n unknown\n >,\n createdAt: eventDict['created_at'] as string | undefined,\n };\n yield streamEvent;\n } catch {\n // Skip invalid events\n }\n currentEventData = null;\n }\n continue;\n }\n\n // SSE format: data: {...}\n if (line.startsWith('data: ')) {\n currentEventData = line.slice(6);\n }\n // Skip keepalive messages and comments\n }\n }\n } finally {\n await reader.cancel();\n reader.releaseLock();\n }\n }\n\n // ==================== Workflow Invocation ====================\n\n /**\n * Invoke a workflow.\n */\n async invokeWorkflow(\n workflowId: string,\n request: InvokeWorkflowRequest\n ): Promise<InvokeWorkflowResponse> {\n const body: Record<string, unknown> = {\n payload: request.payload,\n };\n if (request.stepKey !== undefined) body['step_key'] = request.stepKey;\n if (request.deploymentId !== undefined) body['deployment_id'] = request.deploymentId;\n if (request.parentExecutionId !== undefined)\n body['parent_execution_id'] = request.parentExecutionId;\n if (request.rootExecutionId !== undefined) body['root_execution_id'] = request.rootExecutionId;\n if (request.rootWorkflowId !== undefined) body['root_workflow_id'] = request.rootWorkflowId;\n if (request.queueName !== undefined) body['queue_name'] = request.queueName;\n if (request.queueConcurrencyLimit !== undefined)\n body['queue_concurrency_limit'] = request.queueConcurrencyLimit;\n if (request.concurrencyKey !== undefined) body['concurrency_key'] = request.concurrencyKey;\n if (request.waitForSubworkflow !== undefined)\n body['wait_for_subworkflow'] = request.waitForSubworkflow;\n if (request.batchId !== undefined) body['batch_id'] = request.batchId;\n if (request.sessionId !== undefined) body['session_id'] = request.sessionId;\n if (request.userId !== undefined) body['user_id'] = request.userId;\n if (request.otelTraceparent !== undefined) body['otel_traceparent'] = request.otelTraceparent;\n if (request.initialState !== undefined) body['initial_state'] = request.initialState;\n if (request.runTimeoutSeconds !== undefined)\n body['run_timeout_seconds'] = request.runTimeoutSeconds;\n if (request.channelContext !== undefined)\n body['channel_context'] = {\n channel_id: request.channelContext.channelId,\n source: request.channelContext.source,\n };\n\n return this.request<InvokeWorkflowResponse>('POST', `/api/v1/workflows/${workflowId}/run`, {\n body,\n });\n }\n\n /**\n * Invoke multiple workflows in a single batch.\n */\n async batchInvokeWorkflows(\n request: BatchInvokeWorkflowsRequest\n ): Promise<BatchInvokeWorkflowsResponse> {\n const body: Record<string, unknown> = {\n workflows: request.workflows.map((w) => {\n const entry: Record<string, unknown> = {\n workflow_id: w.workflowId,\n payload: w.payload,\n };\n if (w.queueName !== undefined) entry['queue_name'] = w.queueName;\n if (w.concurrencyKey !== undefined) entry['concurrency_key'] = w.concurrencyKey;\n if (w.queueConcurrencyLimit !== undefined)\n entry['queue_concurrency_limit'] = w.queueConcurrencyLimit;\n if (w.initialState !== undefined) entry['initial_state'] = w.initialState;\n if (w.runTimeoutSeconds !== undefined) entry['run_timeout_seconds'] = w.runTimeoutSeconds;\n return entry;\n }),\n };\n if (request.deploymentId !== undefined) body['deployment_id'] = request.deploymentId;\n if (request.sessionId !== undefined) body['session_id'] = request.sessionId;\n if (request.userId !== undefined) body['user_id'] = request.userId;\n if (request.stepKey !== undefined) body['step_key'] = request.stepKey;\n if (request.parentExecutionId !== undefined)\n body['parent_execution_id'] = request.parentExecutionId;\n if (request.rootExecutionId !== undefined) body['root_execution_id'] = request.rootExecutionId;\n if (request.rootWorkflowId !== undefined) body['root_workflow_id'] = request.rootWorkflowId;\n if (request.waitForSubworkflow !== undefined)\n body['wait_for_subworkflow'] = request.waitForSubworkflow;\n if (request.otelTraceparent !== undefined) body['otel_traceparent'] = request.otelTraceparent;\n\n return this.request<BatchInvokeWorkflowsResponse>('POST', '/api/v1/workflows/batch_run', {\n body,\n });\n }\n\n /**\n * Get execution status.\n */\n async getExecution(executionId: string): Promise<GetExecutionResponse> {\n return this.request<GetExecutionResponse>('GET', `/api/v1/executions/${executionId}`);\n }\n\n /**\n * Poll for execution result.\n */\n async waitForExecution(\n executionId: string,\n options?: { timeout?: number; pollInterval?: number }\n ): Promise<GetExecutionResponse> {\n const timeout = options?.timeout ?? 300000; // 5 minutes default\n const pollInterval = options?.pollInterval ?? 1000;\n const startTime = Date.now();\n\n while (Date.now() - startTime < timeout) {\n const execution = await this.getExecution(executionId);\n\n if (\n execution.status === 'completed' ||\n execution.status === 'failed' ||\n execution.status === 'cancelled'\n ) {\n return execution;\n }\n\n await new Promise((resolve) => setTimeout(resolve, pollInterval));\n }\n\n throw new Error(`Execution ${executionId} timed out after ${String(timeout)}ms`);\n }\n\n /**\n * Cancel an execution.\n */\n async cancelExecution(executionId: string): Promise<void> {\n await this.request<undefined>('POST', `/api/v1/executions/${executionId}/cancel`);\n }\n\n /**\n * Update execution's otel_span_id (used when workflow is paused via WaitException).\n */\n async updateExecutionOtelSpanId(\n executionId: string,\n otelSpanId: string | undefined\n ): Promise<void> {\n await this.request<undefined>('PUT', `/internal/executions/${executionId}/otel-span-id`, {\n body: { otel_span_id: otelSpanId ?? null },\n });\n }\n\n // ==================== Conversation History ====================\n\n /**\n * Add a message to conversation history.\n * POST /internal/conversation/{conversationId}/add\n */\n async addConversationHistory(\n conversationId: string,\n request: AddConversationHistoryRequest\n ): Promise<void> {\n const encoded = encodeURIComponent(conversationId);\n const body: Record<string, unknown> = {\n agent_id: request.agentId,\n role: request.role,\n content: request.content,\n conversation_history_limit: request.conversationHistoryLimit ?? 10,\n };\n if (request.agentRunId !== undefined) body['agent_run_id'] = request.agentRunId;\n\n await this.request<undefined>('POST', `/internal/conversation/${encoded}/add`, {\n body,\n });\n }\n\n /**\n * Get conversation history for a conversation.\n * GET /api/v1/conversation/{conversationId}/get\n */\n async getConversationHistory(\n conversationId: string,\n params: GetConversationHistoryParams\n ): Promise<ConversationMessage[]> {\n const encoded = encodeURIComponent(conversationId);\n const queryParams = new URLSearchParams();\n queryParams.set('agent_id', params.agentId);\n if (params.deploymentId !== undefined) queryParams.set('deployment_id', params.deploymentId);\n if (params.limit !== undefined) queryParams.set('limit', String(params.limit));\n\n const response = await this.request<{ messages?: ConversationMessage[] }>(\n 'GET',\n `/api/v1/conversation/${encoded}/get?${queryParams.toString()}`\n );\n return response.messages ?? [];\n }\n\n // ==================== Session Memory ====================\n\n /**\n * Get session memory (summary + metadata).\n * GET /internal/session/{sessionId}/memory\n */\n async getSessionMemory(sessionId: string): Promise<SessionMemoryResponse> {\n const encoded = encodeURIComponent(sessionId);\n return this.request<SessionMemoryResponse>('GET', `/internal/session/${encoded}/memory`);\n }\n\n /**\n * Store session memory (summary + messages).\n * PUT /internal/session/{sessionId}/memory\n */\n async putSessionMemory(sessionId: string, request: PutSessionMemoryRequest): Promise<void> {\n const encoded = encodeURIComponent(sessionId);\n await this.request<undefined>('PUT', `/internal/session/${encoded}/memory`, {\n body: {\n summary: request.summary,\n messages: request.messages,\n },\n });\n }\n\n // ==================== Schedules ====================\n\n /**\n * Create or update a schedule. Returns schedule_id.\n */\n async createSchedule(request: CreateScheduleRequest): Promise<CreateScheduleResponse> {\n return this.request<CreateScheduleResponse>('POST', '/api/v1/schedules', {\n body: {\n workflow_id: request.workflowId,\n cron: request.cron,\n timezone: request.timezone,\n key: request.key,\n },\n });\n }\n}\n","/**\n * ExecutionHandle - Represents a workflow execution that can be monitored and managed.\n *\n * Mirrors Python's ExecutionHandle class. Unlike Python (where get/cancel take a client arg),\n * the TS version stores the OrchestratorClient internally for a cleaner API.\n */\n\nimport type { OrchestratorClient } from './runtime/orchestrator-client.js';\nimport type { GetExecutionResponse } from './runtime/orchestrator-types.js';\n\n/**\n * Fields used to construct an ExecutionHandle.\n */\nexport interface ExecutionHandleFields {\n id: string;\n workflowId: string;\n createdAt?: string | undefined;\n parentExecutionId?: string | undefined;\n rootWorkflowId: string;\n rootExecutionId: string;\n sessionId?: string | undefined;\n userId?: string | undefined;\n stepKey?: string | undefined;\n}\n\n/**\n * Handle for a workflow execution that allows monitoring and management.\n */\nexport class ExecutionHandle {\n /** Execution ID */\n readonly id: string;\n /** Workflow ID */\n readonly workflowId: string;\n /** When the execution was created */\n readonly createdAt: string | undefined;\n /** Parent execution ID (if invoked from another workflow) */\n readonly parentExecutionId: string | undefined;\n /** Root workflow ID */\n readonly rootWorkflowId: string;\n /** Root execution ID */\n readonly rootExecutionId: string;\n /** Session ID */\n readonly sessionId: string | undefined;\n /** User ID */\n readonly userId: string | undefined;\n /** Step key (if invoked from a step) */\n readonly stepKey: string | undefined;\n\n private readonly orchestratorClient: OrchestratorClient;\n\n constructor(fields: ExecutionHandleFields, orchestratorClient: OrchestratorClient) {\n this.id = fields.id;\n this.workflowId = fields.workflowId;\n this.createdAt = fields.createdAt;\n this.parentExecutionId = fields.parentExecutionId;\n this.rootWorkflowId = fields.rootWorkflowId;\n this.rootExecutionId = fields.rootExecutionId;\n this.sessionId = fields.sessionId;\n this.userId = fields.userId;\n this.stepKey = fields.stepKey;\n this.orchestratorClient = orchestratorClient;\n }\n\n /**\n * Get the current execution status and details.\n */\n async get(): Promise<GetExecutionResponse> {\n return this.orchestratorClient.getExecution(this.id);\n }\n\n /**\n * Cancel the execution if it's still queued or running.\n *\n * @returns true if cancellation was successful, false on error\n */\n async cancel(): Promise<boolean> {\n try {\n await this.orchestratorClient.cancelExecution(this.id);\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Poll until the execution completes and return the result.\n * Matches Python ExecutionHandle.get_result().\n *\n * @param timeout - Maximum time to wait in seconds (default: 600)\n * @returns The execution result\n * @throws Error if execution fails, is cancelled, or times out\n */\n async getResult(timeout = 600): Promise<unknown> {\n const startTime = Date.now();\n const pollInterval = 500;\n let done = false;\n while (!done) {\n const exec = await this.get();\n if (exec.status === 'completed') return exec.result;\n if (exec.status === 'failed') throw new Error(exec.error ?? 'Execution failed');\n if (exec.status === 'cancelled') throw new Error('Execution cancelled');\n if (Date.now() - startTime > timeout * 1000) {\n done = true;\n } else {\n await new Promise((r) => setTimeout(r, pollInterval));\n }\n }\n throw new Error(`Timed out after ${String(timeout)}s`);\n }\n\n /**\n * Convert the handle to a plain object (excluding undefined fields).\n */\n toDict(): Record<string, unknown> {\n const result: Record<string, unknown> = {\n id: this.id,\n workflowId: this.workflowId,\n rootWorkflowId: this.rootWorkflowId,\n rootExecutionId: this.rootExecutionId,\n };\n if (this.createdAt !== undefined) result['createdAt'] = this.createdAt;\n if (this.parentExecutionId !== undefined) result['parentExecutionId'] = this.parentExecutionId;\n if (this.sessionId !== undefined) result['sessionId'] = this.sessionId;\n if (this.userId !== undefined) result['userId'] = this.userId;\n if (this.stepKey !== undefined) result['stepKey'] = this.stepKey;\n return result;\n }\n}\n","/**\n * PolosClient - Central entry point for interacting with the Polos orchestrator.\n *\n * The client stores configuration and provides methods for invoking workflows,\n * publishing events, and managing schedules.\n */\n\nimport type { Workflow, EventData, StreamEvent } from './types/index.js';\nimport { validateCronGranularity } from './core/workflow.js';\nimport { OrchestratorClient } from './runtime/orchestrator-client.js';\nimport type { GetExecutionResponse } from './runtime/orchestrator-types.js';\nimport { ExecutionHandle } from './execution-handle.js';\nimport { assertNotInExecutionContext } from './runtime/execution-context.js';\n\n/**\n * Configuration options for PolosClient.\n */\nexport interface PolosClientConfig {\n /** Orchestrator API URL */\n apiUrl: string;\n /** API key for authentication */\n apiKey: string;\n /** Project ID */\n projectId: string;\n /** Deployment ID for routing workflows to specific workers */\n deploymentId?: string;\n /** Maximum concurrent workflow executions (default: 100) */\n maxConcurrentWorkflows?: number;\n}\n\n/**\n * Options for invoking a workflow via PolosClient.\n */\nexport interface ClientInvokeOptions {\n /** Queue name override */\n queueName?: string | undefined;\n /** Concurrency limit for queue */\n queueConcurrencyLimit?: number | undefined;\n /** Concurrency key for per-tenant queuing */\n concurrencyKey?: string | undefined;\n /** Session ID */\n sessionId?: string | undefined;\n /** User ID */\n userId?: string | undefined;\n /** Initial state dictionary */\n initialState?: Record<string, unknown> | undefined;\n /** Timeout in seconds for the execution */\n runTimeoutSeconds?: number | undefined;\n /** Parent execution ID (when invoked from another workflow) */\n parentExecutionId?: string | undefined;\n /** Root workflow ID */\n rootWorkflowId?: string | undefined;\n /** Root execution ID */\n rootExecutionId?: string | undefined;\n /** Step key (when invoked from a step) */\n stepKey?: string | undefined;\n /** Channel context for bidirectional channels (e.g., originating Slack thread) */\n channelContext?: { channelId: string; source: Record<string, unknown> } | undefined;\n}\n\n/**\n * Input for batch workflow invocation via PolosClient.\n */\nexport interface ClientBatchWorkflowInput {\n /** Workflow to invoke (string ID or Workflow object) */\n workflow: string | Workflow;\n /** Payload for this invocation */\n payload?: unknown;\n /** Queue name override */\n queueName?: string | undefined;\n /** Concurrency key */\n concurrencyKey?: string | undefined;\n /** Concurrency limit for queue */\n queueConcurrencyLimit?: number | undefined;\n /** Initial state dictionary */\n initialState?: Record<string, unknown> | undefined;\n /** Timeout in seconds for the execution */\n runTimeoutSeconds?: number | undefined;\n}\n\n/**\n * Payload passed to scheduled workflows.\n * Matches Python SchedulePayload.\n */\nexport interface SchedulePayload {\n /** When this workflow was scheduled to run */\n timestamp: string;\n /** When this schedule last ran (null if first run) */\n lastTimestamp: string | null;\n /** Timezone of the schedule */\n timezone: string;\n /** Unique identifier for this schedule */\n scheduleId: string;\n /** User ID or custom identifier for the schedule */\n key: string;\n /** Next scheduled run time */\n upcoming: string;\n}\n\n/**\n * Events API accessed via client.events.\n * Matches Python sdk/python/polos/features/events.py function signatures.\n */\nexport interface EventsApi {\n /**\n * Publish a single event to a topic. Returns the sequence ID.\n * Matches Python publish().\n */\n publish(\n topic: string,\n eventData: EventData,\n executionId?: string,\n rootExecutionId?: string\n ): Promise<number>;\n\n /**\n * Publish a batch of events to a single topic. Returns list of sequence IDs.\n * Matches Python batch_publish().\n */\n batchPublish(\n topic: string,\n events: EventData[],\n executionId?: string,\n rootExecutionId?: string\n ): Promise<number[]>;\n\n /**\n * Stream events from a topic using Server-Sent Events (SSE).\n * Matches Python stream_topic().\n */\n streamTopic(\n topic: string,\n lastSequenceId?: number,\n lastTimestamp?: Date\n ): AsyncIterable<StreamEvent>;\n\n /**\n * Stream events from a workflow run using Server-Sent Events (SSE).\n * Automatically stops when it receives a finish event with matching execution ID.\n * Matches Python stream_workflow().\n */\n streamWorkflow(\n workflowId: string,\n workflowRunId: string,\n lastSequenceId?: number,\n lastTimestamp?: Date\n ): AsyncIterable<StreamEvent>;\n}\n\n/**\n * Schedules API accessed via client.schedules.\n * Matches Python sdk/python/polos/features/schedules.py.\n */\nexport interface SchedulesApi {\n /**\n * Create or update a schedule for a workflow.\n * If a schedule with the same workflow and key already exists, it will be updated.\n * Matches Python schedules.create().\n *\n * @param workflow - Workflow ID to schedule\n * @param cron - Cron expression (e.g., \"0 8 * * *\" for 8 AM daily)\n * @param timezone - Timezone for the schedule (default: \"UTC\")\n * @param key - Key for per-user/per-entity schedules (default: \"global\")\n * @returns schedule_id: Unique identifier for the schedule\n */\n create(workflow: string, cron: string, timezone?: string, key?: string): Promise<string>;\n}\n\n/**\n * PolosClient - The main client for interacting with Polos orchestrator.\n *\n * @example\n * ```typescript\n * import { PolosClient, defineWorkflow } from '@polos/sdk';\n *\n * const client = new PolosClient({\n * apiUrl: 'https://api.polos.dev',\n * apiKey: 'your-api-key',\n * projectId: 'your-project',\n * deploymentId: 'my-deployment', // optional, can also use POLOS_DEPLOYMENT_ID env var\n * });\n *\n * // Invoke a workflow\n * const handle = await client.invoke(myWorkflow, { data: 'value' });\n *\n * // Run and wait for result\n * const result = await client.run(myWorkflow, { data: 'value' });\n * ```\n */\n/** Internal config type with defaults applied but deploymentId remaining optional */\ntype ResolvedPolosClientConfig = Required<Omit<PolosClientConfig, 'deploymentId'>> & {\n deploymentId: string | undefined;\n};\n\n/** Resolve a workflow-or-string to its ID */\nfunction resolveWorkflowId(workflow: string | Workflow): string {\n return typeof workflow === 'string' ? workflow : workflow.id;\n}\n\nexport class PolosClient {\n private readonly config: ResolvedPolosClientConfig;\n private readonly orchestratorClient: OrchestratorClient;\n\n /**\n * Events API for publishing and subscribing to events.\n */\n public readonly events: EventsApi;\n\n /**\n * Schedules API for managing workflow schedules.\n */\n public readonly schedules: SchedulesApi;\n\n constructor(config: PolosClientConfig) {\n this.config = {\n maxConcurrentWorkflows: 100,\n ...config,\n // Use provided deploymentId or fall back to environment variable\n deploymentId: config.deploymentId ?? process.env['POLOS_DEPLOYMENT_ID'],\n };\n\n this.orchestratorClient = new OrchestratorClient({\n apiUrl: this.config.apiUrl,\n apiKey: this.config.apiKey,\n projectId: this.config.projectId,\n });\n\n // Initialize sub-APIs\n this.events = this.createEventsApi();\n this.schedules = this.createSchedulesApi();\n }\n\n /**\n * Create a PolosClient from environment variables.\n *\n * Reads from:\n * - POLOS_API_URL\n * - POLOS_API_KEY\n * - POLOS_PROJECT_ID\n * - POLOS_DEPLOYMENT_ID (optional)\n * - POLOS_MAX_CONCURRENT_WORKFLOWS (optional)\n *\n * @throws Error if required environment variables are missing\n */\n static fromEnv(): PolosClient {\n const apiUrl = process.env['POLOS_API_URL'];\n const apiKey = process.env['POLOS_API_KEY'];\n const projectId = process.env['POLOS_PROJECT_ID'];\n const deploymentId = process.env['POLOS_DEPLOYMENT_ID'];\n\n if (!apiUrl) {\n throw new Error('POLOS_API_URL environment variable is required');\n }\n if (!apiKey) {\n throw new Error('POLOS_API_KEY environment variable is required');\n }\n if (!projectId) {\n throw new Error('POLOS_PROJECT_ID environment variable is required');\n }\n\n const config: PolosClientConfig = {\n apiUrl,\n apiKey,\n projectId,\n ...(deploymentId && { deploymentId }),\n };\n\n const maxConcurrent = process.env['POLOS_MAX_CONCURRENT_WORKFLOWS'];\n if (maxConcurrent) {\n const parsed = parseInt(maxConcurrent, 10);\n if (!isNaN(parsed)) {\n config.maxConcurrentWorkflows = parsed;\n }\n }\n\n return new PolosClient(config);\n }\n\n /**\n * Get the client configuration.\n */\n getConfig(): Readonly<ResolvedPolosClientConfig> {\n return this.config;\n }\n\n /**\n * Get the underlying OrchestratorClient for advanced use.\n */\n getOrchestratorClient(): OrchestratorClient {\n return this.orchestratorClient;\n }\n\n /**\n * Invoke a workflow (fire and forget).\n *\n * @param workflow - The workflow to invoke (string ID or Workflow object)\n * @param payload - Payload to pass to the workflow\n * @param options - Optional invocation options\n * @returns An ExecutionHandle to track the workflow execution\n */\n async invoke(\n workflow: string | Workflow,\n payload?: unknown,\n options?: ClientInvokeOptions\n ): Promise<ExecutionHandle> {\n assertNotInExecutionContext('client.invoke()', 'step.invoke()');\n const workflowId = resolveWorkflowId(workflow);\n\n const response = await this.orchestratorClient.invokeWorkflow(workflowId, {\n workflowId,\n payload,\n deploymentId: this.config.deploymentId,\n queueName: options?.queueName,\n queueConcurrencyLimit: options?.queueConcurrencyLimit,\n concurrencyKey: options?.concurrencyKey,\n sessionId: options?.sessionId,\n userId: options?.userId,\n initialState: options?.initialState,\n runTimeoutSeconds: options?.runTimeoutSeconds,\n parentExecutionId: options?.parentExecutionId,\n rootExecutionId: options?.rootExecutionId,\n stepKey: options?.stepKey,\n channelContext: options?.channelContext,\n });\n\n return new ExecutionHandle(\n {\n id: response.execution_id,\n workflowId,\n createdAt: response.created_at,\n parentExecutionId: options?.parentExecutionId,\n rootWorkflowId: options?.rootWorkflowId ?? workflowId,\n rootExecutionId: options?.rootExecutionId ?? response.execution_id,\n sessionId: options?.sessionId,\n userId: options?.userId,\n stepKey: options?.stepKey,\n },\n this.orchestratorClient\n );\n }\n\n /**\n * Invoke multiple workflows in batch (fire and forget).\n *\n * @param items - Array of workflow invocations\n * @param options - Optional batch-level options\n * @returns Array of ExecutionHandles to track executions\n */\n async batchInvoke(\n items: ClientBatchWorkflowInput[],\n options?: {\n sessionId?: string;\n userId?: string;\n parentExecutionId?: string;\n rootWorkflowId?: string;\n rootExecutionId?: string;\n stepKey?: string;\n waitForSubworkflow?: boolean;\n }\n ): Promise<ExecutionHandle[]> {\n assertNotInExecutionContext('client.batchInvoke()', 'step.batchInvoke()');\n if (items.length === 0) {\n return [];\n }\n\n const response = await this.orchestratorClient.batchInvokeWorkflows({\n workflows: items.map((item) => ({\n workflowId: resolveWorkflowId(item.workflow),\n payload: item.payload,\n queueName: item.queueName,\n concurrencyKey: item.concurrencyKey,\n queueConcurrencyLimit: item.queueConcurrencyLimit,\n initialState: item.initialState,\n runTimeoutSeconds: item.runTimeoutSeconds,\n })),\n deploymentId: this.config.deploymentId,\n sessionId: options?.sessionId,\n userId: options?.userId,\n parentExecutionId: options?.parentExecutionId,\n rootExecutionId: options?.rootExecutionId,\n stepKey: options?.stepKey,\n waitForSubworkflow: options?.waitForSubworkflow,\n });\n\n return response.executions.map((exec, i) => {\n const item = items[i];\n if (item === undefined) {\n throw new Error('item is undefined');\n }\n const wfId = resolveWorkflowId(item.workflow);\n return new ExecutionHandle(\n {\n id: exec.execution_id,\n workflowId: wfId,\n createdAt: exec.created_at,\n parentExecutionId: options?.parentExecutionId,\n rootWorkflowId: options?.rootWorkflowId ?? wfId,\n rootExecutionId: options?.rootExecutionId ?? exec.execution_id,\n sessionId: options?.sessionId,\n userId: options?.userId,\n stepKey: options?.stepKey,\n },\n this.orchestratorClient\n );\n });\n }\n\n /**\n * Resume a suspended execution by publishing a resume event.\n *\n * @param suspendWorkflowId - The workflow ID of the suspended execution\n * @param suspendExecutionId - The execution ID of the suspended execution\n * @param suspendStepKey - The step key that was used in suspend()\n * @param data - Data to pass in the resume event\n */\n async resume(\n suspendWorkflowId: string,\n suspendExecutionId: string,\n suspendStepKey: string,\n data: unknown\n ): Promise<void> {\n const topic = `workflow/${suspendWorkflowId}/${suspendExecutionId}`;\n\n await this.orchestratorClient.publishEvent({\n topic,\n events: [{ eventType: `resume_${suspendStepKey}`, data }],\n });\n }\n\n /**\n * Get execution details.\n *\n * @param executionId - The execution ID to look up\n * @returns Execution details\n */\n async getExecution(executionId: string): Promise<GetExecutionResponse> {\n return this.orchestratorClient.getExecution(executionId);\n }\n\n /**\n * Cancel an execution by its ID.\n *\n * @param executionId - The execution ID to cancel\n * @returns true if cancellation was successful, false on error\n */\n async cancelExecution(executionId: string): Promise<boolean> {\n try {\n await this.orchestratorClient.cancelExecution(executionId);\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Create the events sub-API.\n * Matches Python sdk/python/polos/features/events.py.\n */\n private createEventsApi(): EventsApi {\n const orchestratorClient = this.orchestratorClient;\n\n return {\n publish: async (\n topic: string,\n eventData: EventData,\n executionId?: string,\n rootExecutionId?: string\n ): Promise<number> => {\n const sequenceIds = await this.events.batchPublish(\n topic,\n [eventData],\n executionId,\n rootExecutionId\n );\n return sequenceIds[0] ?? 0;\n },\n\n batchPublish: async (\n topic: string,\n events: EventData[],\n executionId?: string,\n rootExecutionId?: string\n ): Promise<number[]> => {\n if (events.length === 0) {\n return [];\n }\n\n const response = await orchestratorClient.publishEvent({\n topic,\n events: events.map((e) => {\n const entry: { eventType?: string; data: unknown } = { data: e.data };\n if (e.eventType !== undefined) entry.eventType = e.eventType;\n return entry;\n }),\n executionId,\n rootExecutionId,\n });\n\n return response.sequence_ids;\n },\n\n streamTopic: (\n topic: string,\n lastSequenceId?: number,\n lastTimestamp?: Date\n ): AsyncIterable<StreamEvent> => {\n return orchestratorClient.streamEvents({\n topic,\n lastSequenceId,\n lastTimestamp: lastTimestamp?.toISOString(),\n });\n },\n\n streamWorkflow: (\n workflowId: string,\n workflowRunId: string,\n lastSequenceId?: number,\n lastTimestamp?: Date\n ): AsyncIterable<StreamEvent> => {\n // Wrap with finish-event detection matching Python's stream_workflow()\n async function* streamWithFinishCheck() {\n for await (const event of orchestratorClient.streamEvents({\n workflowId,\n workflowRunId,\n lastSequenceId,\n lastTimestamp: lastTimestamp?.toISOString(),\n })) {\n yield event;\n\n // Check for finish event with matching execution_id\n if (\n event.eventType === 'workflow_finish' ||\n event.eventType === 'agent_finish' ||\n event.eventType === 'tool_finish'\n ) {\n const metadata = event.data['_metadata'];\n if (metadata && typeof metadata === 'object' && !Array.isArray(metadata)) {\n const metadataRecord = metadata as Record<string, unknown>;\n if (metadataRecord['execution_id'] === workflowRunId) {\n return;\n }\n }\n }\n }\n }\n\n return streamWithFinishCheck();\n },\n };\n }\n\n /**\n * Create the schedules sub-API.\n * Matches Python sdk/python/polos/features/schedules.py.\n */\n private createSchedulesApi(): SchedulesApi {\n const orchestratorClient = this.orchestratorClient;\n\n return {\n create: async (\n workflow: string,\n cron: string,\n timezone = 'UTC',\n key = 'global'\n ): Promise<string> => {\n validateCronGranularity(cron);\n const response = await orchestratorClient.createSchedule({\n workflowId: workflow,\n cron,\n timezone,\n key,\n });\n return response.schedule_id;\n },\n };\n }\n}\n","/**\n * Tool definition and creation.\n *\n * Provides the defineTool function for creating typed tools that can be\n * exposed to LLMs. Tools are workflows with workflowType: 'tool' plus\n * LLM-specific metadata (description, JSON schema parameters).\n */\n\nimport { type ZodType, toJSONSchema } from 'zod';\nimport type { Channel } from '../channels/channel.js';\nimport type { WorkflowContext } from './context.js';\nimport type { QueueConfig, WorkflowHandler, Workflow } from './workflow.js';\nimport { defineWorkflow } from './workflow.js';\nimport type { HookHandler, Hook as HookObject } from '../middleware/hook.js';\n\n// ── Tool approval ────────────────────────────────────────────────────\n\nexport type ToolApproval = 'always' | 'none';\n\n// ── LLM tool definition ──────────────────────────────────────────────\n\n/**\n * LLM tool definition format (OpenAI/Anthropic compatible).\n */\nexport interface LlmToolDefinition {\n type: 'function';\n function: {\n name: string;\n description: string;\n parameters: Record<string, unknown>;\n };\n}\n\n// ── DefineToolConfig ─────────────────────────────────────────────────\n\n/**\n * Configuration for defineTool().\n */\nexport interface DefineToolConfig<TInput = unknown, TOutput = unknown, TState = unknown> {\n /** Unique tool identifier */\n id: string;\n /** Tool description shown to LLMs */\n description: string;\n /** Zod schema for input validation (optional — some tools take no input) */\n inputSchema?: ZodType<TInput> | undefined;\n /** Zod schema for output validation */\n outputSchema?: ZodType<TOutput> | undefined;\n /** Zod schema for state validation and defaults */\n stateSchema?: ZodType<TState> | undefined;\n /** Queue assignment */\n queue?: string | QueueConfig | undefined;\n /** Hook(s) to run before tool execution */\n onStart?:\n | HookHandler<TInput, TState>\n | HookObject<TInput, TState>\n | (HookHandler<TInput, TState> | HookObject<TInput, TState>)[]\n | undefined;\n /** Hook(s) to run after tool completion */\n onEnd?:\n | HookHandler<TInput, TState>\n | HookObject<TInput, TState>\n | (HookHandler<TInput, TState> | HookObject<TInput, TState>)[]\n | undefined;\n /** Whether to auto-register in the global workflow registry (default: true) */\n autoRegister?: boolean | undefined;\n /** Require human approval before tool execution. @default undefined (no approval) */\n approval?: ToolApproval | undefined;\n /** Notification channels for suspend events. Overrides Worker-level channels. */\n channels?: Channel[] | undefined;\n}\n\n// ── ToolWorkflow ─────────────────────────────────────────────────────\n\n/**\n * A Workflow with tool-specific LLM metadata.\n *\n * Extends the base Workflow interface with fields needed for LLM tool\n * integration: description, JSON schema parameters, and methods for\n * generating LLM-compatible tool definitions.\n */\nexport interface ToolWorkflow<\n TInput = unknown,\n TOutput = unknown,\n TState = unknown,\n> extends Workflow<TInput, TState, TOutput> {\n /** Tool description shown to LLMs */\n readonly toolDescription: string;\n /** JSON schema for tool parameters */\n readonly toolParameters: Record<string, unknown>;\n /** Generate an LLM-compatible tool definition */\n toLlmToolDefinition(): LlmToolDefinition;\n /** Get the tool type (default: \"default\") */\n getToolType(): string;\n /** Get additional tool metadata (default: undefined) */\n getToolMetadata(): Record<string, unknown> | undefined;\n}\n\n// ── isToolWorkflow ───────────────────────────────────────────────────\n\n/**\n * Type guard: checks whether a Workflow is a ToolWorkflow.\n */\nexport function isToolWorkflow(workflow: Workflow): workflow is ToolWorkflow {\n return workflow.config.workflowType === 'tool';\n}\n\n// ── Tool approval resume data ────────────────────────────────────────\n\ninterface ToolApprovalResumeData {\n data?: { approved?: boolean; feedback?: string };\n}\n\n// ── defineTool ───────────────────────────────────────────────────────\n\n/**\n * Define a tool — a workflow with `workflowType: 'tool'` plus LLM metadata.\n *\n * @example\n * ```typescript\n * import { defineTool } from '@polos/sdk';\n * import { z } from 'zod';\n *\n * const searchKb = defineTool({\n * id: 'search-kb',\n * description: 'Search the knowledge base',\n * inputSchema: z.object({\n * query: z.string().describe('Search query'),\n * limit: z.number().optional().describe('Max results'),\n * }),\n * }, async (ctx, input) => {\n * const results = await ctx.step.run('search', () => db.search(input.query));\n * return { results };\n * });\n *\n * // Get LLM tool definition\n * const toolDef = searchKb.toLlmToolDefinition();\n *\n * // Execute via client\n * const result = await client.run(searchKb, { query: 'test' });\n * ```\n */\nexport function defineTool<TInput = unknown, TOutput = unknown, TState = unknown>(\n config: DefineToolConfig<TInput, TOutput, TState>,\n handler: (ctx: WorkflowContext<TState>, input: TInput) => Promise<TOutput>\n): ToolWorkflow<TInput, TOutput, TState> {\n // Derive JSON schema parameters from inputSchema\n const toolParameters: Record<string, unknown> = config.inputSchema\n ? (() => {\n const { $schema: _, ...rest } = toJSONSchema(config.inputSchema) as Record<string, unknown>;\n return rest;\n })()\n : { type: 'object', properties: {} };\n\n // Wrap handler with approval gate when configured\n const effectiveHandler: typeof handler =\n config.approval === 'always'\n ? async (ctx, input) => {\n const approvalId = await ctx.step.uuid('_approval_id');\n const response = await ctx.step.suspend<Record<string, unknown>, ToolApprovalResumeData>(\n `approve_${config.id}_${approvalId}`,\n {\n data: {\n _form: {\n title: `Approve tool: ${config.id}`,\n description: `The agent wants to use the \"${config.id}\" tool.`,\n fields: [\n {\n key: 'approved',\n type: 'boolean',\n label: 'Approve this tool call?',\n required: true,\n default: false,\n },\n {\n key: 'feedback',\n type: 'textarea',\n label: 'Feedback for the agent (optional)',\n description: 'If rejecting, tell the agent what to do instead.',\n required: false,\n },\n ],\n context: { tool: config.id, input },\n },\n _source: 'tool_approval',\n _tool: config.id,\n },\n }\n );\n\n if (response.data?.approved !== true) {\n const feedback = response.data?.feedback;\n throw new Error(\n `Tool \"${config.id}\" was rejected by the user.${feedback ? ` Feedback: ${feedback}` : ''}`\n );\n }\n\n return handler(ctx, input);\n }\n : handler;\n\n // Create the underlying workflow\n const workflow = defineWorkflow<TInput, TState, TOutput>(\n {\n id: config.id,\n description: config.description,\n workflowType: 'tool',\n payloadSchema: config.inputSchema,\n stateSchema: config.stateSchema,\n outputSchema: config.outputSchema,\n queue: config.queue,\n onStart: config.onStart,\n onEnd: config.onEnd,\n channels: config.channels,\n },\n effectiveHandler as WorkflowHandler<TInput, TState, TOutput>,\n config.autoRegister === undefined ? undefined : { autoRegister: config.autoRegister }\n );\n\n // Extend with tool-specific fields\n const toolWorkflow: ToolWorkflow<TInput, TOutput, TState> = Object.assign(workflow, {\n toolDescription: config.description,\n toolParameters,\n toLlmToolDefinition(): LlmToolDefinition {\n return {\n type: 'function' as const,\n function: {\n name: config.id,\n description: config.description,\n parameters: toolParameters,\n },\n };\n },\n getToolType(): string {\n return 'default';\n },\n getToolMetadata(): Record<string, unknown> | undefined {\n return undefined;\n },\n });\n\n return toolWorkflow;\n}\n","/**\n * LLM types and conversion utilities.\n *\n * All wire-format types use snake_case to match Python for cross-language compatibility.\n */\n\nimport type { ModelMessage as CoreMessage, LanguageModel } from 'ai';\nimport { jsonSchema } from 'ai';\nimport type { LlmToolDefinition } from '../core/tool.js';\nimport type { ToolCall } from '../types/llm.js';\nimport type { Guardrail } from '../middleware/guardrail.js';\n\n/**\n * Extract modelId from a LanguageModel (which may be a string or model object).\n */\nexport function getModelId(model: LanguageModel): string {\n return typeof model === 'string' ? model : model.modelId;\n}\n\n/**\n * Extract provider from a LanguageModel (which may be a string or model object).\n */\nexport function getModelProvider(model: LanguageModel): string {\n if (typeof model === 'string') {\n // For string model IDs like \"anthropic/claude-3\", extract provider prefix\n const slashIdx = model.indexOf('/');\n return slashIdx >= 0 ? model.slice(0, slashIdx) : 'unknown';\n }\n return model.provider;\n}\n\n// ── Wire-format types ────────────────────────\n\n/**\n * Token usage statistics\n */\nexport interface LLMUsage {\n input_tokens: number;\n output_tokens: number;\n total_tokens: number;\n cache_read_input_tokens?: number | undefined;\n cache_creation_input_tokens?: number | undefined;\n}\n\n/**\n * A tool call made by the LLM\n */\nexport interface LLMToolCall {\n id: string;\n type: 'function';\n call_id: string;\n function: { name: string; arguments: string };\n}\n\n/**\n * Result from a tool execution\n */\nexport interface LLMToolResult {\n type: 'function_call_output';\n call_id: string;\n name: string;\n output: unknown;\n}\n\n/**\n * Response from a non-streaming LLM generation\n */\nexport interface LLMResponse {\n content: string | null;\n usage: LLMUsage | null;\n tool_calls: LLMToolCall[] | null;\n raw_output: unknown[] | null;\n model: string | null;\n stop_reason: string | null;\n}\n\n/**\n * Stream event types (matching Python exactly).\n */\nexport type LLMStreamEvent =\n | { type: 'text_delta'; data: { content: string } }\n | { type: 'tool_call'; data: { tool_call: LLMToolCall } }\n | {\n type: 'done';\n data: { usage: LLMUsage; raw_output: unknown[]; model: string; stop_reason: string | null };\n }\n | { type: 'error'; data: { error: string } };\n\n/**\n * Options for LLM.generate() and LLM.stream().\n */\nexport interface LLMGenerateOptions {\n /** Conversation messages */\n messages: CoreMessage[];\n /** System prompt */\n system?: string | undefined;\n /** Tools available to the LLM */\n tools?: LlmToolDefinition[] | undefined;\n /** Tool results from previous tool calls */\n tool_results?: LLMToolResult[] | undefined;\n /** Temperature for randomness */\n temperature?: number | undefined;\n /** Maximum tokens to generate */\n maxTokens?: number | undefined;\n /** Top-p sampling parameter */\n topP?: number | undefined;\n /** Zod schema for structured output (passed to Vercel AI SDK Output.object()) */\n outputSchema?: unknown;\n}\n\n/**\n * Payload for llmGenerate() — adds guardrail and agent step fields.\n */\nexport interface LLMGeneratePayload extends LLMGenerateOptions {\n /** Agent step number for step key naming */\n agent_step: number;\n /** Guardrails to apply after generation */\n guardrails?: Guardrail[] | undefined;\n /** Maximum guardrail retries (default: 2) */\n guardrail_max_retries?: number | undefined;\n}\n\n/**\n * Result from llmGenerate() — extends LLMResponse with execution metadata.\n */\nexport interface LLMGenerateResult extends LLMResponse {\n /** Agent run ID (from workflow context) */\n agent_run_id?: string | undefined;\n /** Execution status */\n status?: string | undefined;\n}\n\n/**\n * Payload for llmStream().\n */\nexport interface LLMStreamPayload extends LLMGenerateOptions {\n /** Agent step number for step key naming */\n agent_step: number;\n}\n\n// ── Conversion functions ───────────────────────────────────────────────\n\n/**\n * Convert LlmToolDefinition[] (OpenAI format) to Vercel AI SDK tool format.\n */\nexport function convertToolsToVercel(\n tools: LlmToolDefinition[] | undefined\n): Record<string, { description: string; inputSchema: ReturnType<typeof jsonSchema> }> | undefined {\n if (!tools || tools.length === 0) return undefined;\n\n const result: Record<\n string,\n { description: string; inputSchema: ReturnType<typeof jsonSchema> }\n > = {};\n for (const tool of tools) {\n result[tool.function.name] = {\n description: tool.function.description,\n inputSchema: jsonSchema(tool.function.parameters),\n };\n }\n return result;\n}\n\n/**\n * Convert Python tool results to Vercel CoreMessage[] with role 'tool'.\n */\nexport function convertToolResultsToMessages(\n toolResults: LLMToolResult[] | undefined\n): CoreMessage[] {\n if (!toolResults || toolResults.length === 0) return [];\n\n return toolResults.map(\n (tr): CoreMessage => ({\n role: 'tool' as const,\n content: [\n {\n type: 'tool-result' as const,\n toolCallId: tr.call_id,\n toolName: tr.name,\n output:\n typeof tr.output === 'string'\n ? { type: 'text' as const, value: tr.output }\n : // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment -- coerce unknown tool output to JSON ToolResultOutput\n { type: 'json' as const, value: tr.output as any },\n },\n ],\n })\n );\n}\n\n/**\n * Convert a Vercel AI SDK tool call to Python LLMToolCall format.\n */\nexport function convertVercelToolCallToPython(tc: {\n toolCallId: string;\n toolName: string;\n input: unknown;\n}): LLMToolCall {\n return {\n id: tc.toolCallId,\n type: 'function',\n call_id: tc.toolCallId,\n function: {\n name: tc.toolName,\n arguments: typeof tc.input === 'string' ? tc.input : JSON.stringify(tc.input),\n },\n };\n}\n\n/**\n * Convert Python LLMToolCall to middleware ToolCall format (for guardrails).\n */\nexport function convertPythonToolCallToMiddleware(tc: LLMToolCall): ToolCall {\n let args: unknown;\n try {\n args = JSON.parse(tc.function.arguments);\n } catch {\n args = tc.function.arguments;\n }\n return {\n id: tc.call_id,\n name: tc.function.name,\n args,\n };\n}\n\n/**\n * Convert middleware ToolCall back to Python LLMToolCall format.\n */\nexport function convertMiddlewareToolCallToPython(tc: ToolCall): LLMToolCall {\n return {\n id: tc.id,\n type: 'function',\n call_id: tc.id,\n function: {\n name: tc.name,\n arguments: typeof tc.args === 'string' ? tc.args : JSON.stringify(tc.args),\n },\n };\n}\n\n/**\n * Convert Vercel AI SDK usage to Python LLMUsage format.\n */\nexport function convertVercelUsageToPython(usage: {\n inputTokens: number | undefined;\n outputTokens: number | undefined;\n totalTokens?: number | undefined;\n inputTokenDetails?: {\n cacheReadTokens?: number | undefined;\n cacheWriteTokens?: number | undefined;\n };\n}): LLMUsage {\n const input = usage.inputTokens ?? 0;\n const output = usage.outputTokens ?? 0;\n const result: LLMUsage = {\n input_tokens: input,\n output_tokens: output,\n total_tokens: usage.totalTokens ?? input + output,\n };\n if (usage.inputTokenDetails?.cacheReadTokens != null) {\n result.cache_read_input_tokens = usage.inputTokenDetails.cacheReadTokens;\n }\n if (usage.inputTokenDetails?.cacheWriteTokens != null) {\n result.cache_creation_input_tokens = usage.inputTokenDetails.cacheWriteTokens;\n }\n return result;\n}\n\n/**\n * Convert Vercel finish reason (kebab-case) to Python format (snake_case).\n */\nexport function convertFinishReason(reason: string | undefined): string | null {\n if (!reason) return null;\n switch (reason) {\n case 'tool-calls':\n return 'tool_calls';\n case 'content-filter':\n return 'content_filter';\n default:\n return reason;\n }\n}\n","/**\n * LLM class wrapping Vercel AI SDK LanguageModel.\n *\n * Provides Python-compatible generate() and stream() methods\n * without durability or guardrails (use llmGenerate/llmStream for those).\n */\n\nimport { generateText, streamText, Output } from 'ai';\nimport type { ModelMessage as CoreMessage, LanguageModel } from 'ai';\nimport type { ZodType } from 'zod';\nimport type { LLMGenerateOptions, LLMResponse, LLMStreamEvent, LLMToolCall } from './types.js';\nimport {\n convertToolsToVercel,\n convertToolResultsToMessages,\n convertVercelToolCallToPython,\n convertVercelUsageToPython,\n convertFinishReason,\n getModelId,\n getModelProvider,\n} from './types.js';\n\n/** Cache breakpoint marker for Anthropic prompt caching. */\nexport const ANTHROPIC_CACHE_BREAKPOINT = {\n anthropic: { cacheControl: { type: 'ephemeral' as const } },\n};\n\n/** Check whether a LanguageModel is an Anthropic model. */\nexport function isAnthropicModel(model: LanguageModel): boolean {\n return getModelProvider(model).startsWith('anthropic');\n}\n\n/**\n * Remove all existing cache control markers from the args object (in-place).\n *\n * Must be called before applying fresh breakpoints so that stale markers\n * from previous agent loop iterations don't accumulate and exceed\n * Anthropic's 4-block limit.\n */\nfunction stripAnthropicCacheControl(args: Record<string, unknown>): void {\n // Strip from system prompt\n const system = args['system'];\n if (system && typeof system === 'object' && 'providerOptions' in system) {\n delete (system as Record<string, unknown>)['providerOptions'];\n }\n\n // Strip from tools\n const tools = args['tools'] as Record<string, Record<string, unknown>> | undefined;\n if (tools) {\n for (const name of Object.keys(tools)) {\n delete tools[name]?.['providerOptions'];\n }\n }\n\n // Strip from messages\n const messages = args['messages'] as Record<string, unknown>[] | undefined;\n if (messages) {\n for (const msg of messages) {\n delete msg['providerOptions'];\n }\n }\n}\n\n/**\n * Add Anthropic prompt-caching breakpoints to the args object (in-place).\n *\n * Marks the system prompt, the last tool, and the last message with\n * `providerOptions: { anthropic: { cacheControl: { type: 'ephemeral' } } }`\n * so the @ai-sdk/anthropic provider can enable prompt caching.\n * Strips any existing markers first to stay within the 4-block limit.\n */\nexport function applyAnthropicCacheControl(\n args: Record<string, unknown>,\n model: LanguageModel\n): void {\n if (!isAnthropicModel(model)) return;\n\n stripAnthropicCacheControl(args);\n\n // 1. System prompt: convert string to SystemModelMessage with cache control\n if (typeof args['system'] === 'string') {\n args['system'] = {\n role: 'system',\n content: args['system'],\n providerOptions: ANTHROPIC_CACHE_BREAKPOINT,\n };\n }\n\n // 2. Tools: add cache control to the last tool\n const tools = args['tools'] as Record<string, Record<string, unknown>> | undefined;\n if (tools) {\n const toolNames = Object.keys(tools);\n if (toolNames.length > 0) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const lastToolName = toolNames[toolNames.length - 1]!;\n tools[lastToolName] = {\n ...tools[lastToolName],\n providerOptions: ANTHROPIC_CACHE_BREAKPOINT,\n };\n }\n }\n\n // 3. Last message: add cache control to the last message\n const messages = args['messages'] as Record<string, unknown>[] | undefined;\n if (messages && messages.length > 0) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const lastMsg = messages[messages.length - 1]!;\n messages[messages.length - 1] = {\n ...lastMsg,\n providerOptions: ANTHROPIC_CACHE_BREAKPOINT,\n };\n }\n}\n\n/**\n * Build args object for generateText/streamText, only including defined properties\n * to satisfy exactOptionalPropertyTypes.\n */\nfunction buildGenerateArgs(\n model: LanguageModel,\n messages: CoreMessage[],\n options: LLMGenerateOptions\n): Record<string, unknown> {\n const args: Record<string, unknown> = { model, messages };\n const tools = convertToolsToVercel(options.tools);\n if (options.system !== undefined) args['system'] = options.system;\n if (tools !== undefined) args['tools'] = tools;\n if (options.temperature !== undefined) args['temperature'] = options.temperature;\n if (options.maxTokens !== undefined) args['maxTokens'] = options.maxTokens;\n if (options.topP !== undefined) args['topP'] = options.topP;\n if (options.outputSchema) {\n args['experimental_output'] = Output.object({ schema: options.outputSchema as ZodType });\n }\n applyAnthropicCacheControl(args, model);\n return args;\n}\n\n/**\n * LLM wraps a Vercel AI SDK LanguageModel to provide Python-compatible\n * generate() and stream() methods.\n *\n * @example\n * ```typescript\n * import { LLM } from '@polos/sdk';\n * import { anthropic } from '@ai-sdk/anthropic';\n *\n * const llm = new LLM({ model: anthropic('claude-sonnet-4-20250514') });\n * const response = await llm.generate({\n * messages: [{ role: 'user', content: 'Hello!' }],\n * });\n * console.log(response.content);\n * ```\n */\nexport class LLM {\n readonly model: LanguageModel;\n\n constructor(options: { model: LanguageModel }) {\n this.model = options.model;\n }\n\n /**\n * Generate a response (non-streaming).\n *\n * Returns an LLMResponse in Python-compatible format.\n */\n async generate(options: LLMGenerateOptions): Promise<LLMResponse> {\n const messages = [...options.messages, ...convertToolResultsToMessages(options.tool_results)];\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-explicit-any -- conditionally built args to satisfy exactOptionalPropertyTypes\n const result = await generateText(buildGenerateArgs(this.model, messages, options) as any);\n\n const toolCalls: LLMToolCall[] | null =\n result.toolCalls.length > 0\n ? result.toolCalls.map((tc) => convertVercelToolCallToPython(tc))\n : null;\n\n return {\n content: result.text || null,\n usage: convertVercelUsageToPython(result.totalUsage),\n tool_calls: toolCalls,\n raw_output: [...result.response.messages],\n model: getModelId(this.model),\n stop_reason: convertFinishReason(result.finishReason),\n };\n }\n\n /**\n * Stream a response.\n *\n * Yields LLMStreamEvents in Python-compatible format.\n */\n async *stream(options: LLMGenerateOptions): AsyncGenerator<LLMStreamEvent> {\n const messages = [...options.messages, ...convertToolResultsToMessages(options.tool_results)];\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-explicit-any -- conditionally built args to satisfy exactOptionalPropertyTypes\n const result = streamText(buildGenerateArgs(this.model, messages, options) as any);\n\n let finishUsage:\n | {\n inputTokens: number | undefined;\n outputTokens: number | undefined;\n totalTokens?: number | undefined;\n inputTokenDetails?: {\n cacheReadTokens?: number | undefined;\n cacheWriteTokens?: number | undefined;\n };\n }\n | undefined;\n let finishReason: string | undefined;\n\n for await (const part of result.fullStream) {\n switch (part.type) {\n case 'text-delta':\n yield { type: 'text_delta', data: { content: part.text } };\n break;\n case 'tool-call':\n yield {\n type: 'tool_call',\n data: { tool_call: convertVercelToolCallToPython(part) },\n };\n break;\n case 'finish':\n finishUsage = part.totalUsage;\n finishReason = part.finishReason;\n break;\n case 'error':\n yield {\n type: 'error',\n data: {\n error: part.error instanceof Error ? part.error.message : String(part.error),\n },\n };\n break;\n // Ignore all other part types (reasoning, step-start, step-finish, etc.)\n default:\n break;\n }\n }\n\n // After stream completes, get the full response messages for raw_output\n // (matching generate() which returns result.response.messages)\n const fullResponse = await result.response;\n const rawOutput = [...fullResponse.messages];\n\n yield {\n type: 'done',\n data: {\n usage: finishUsage\n ? convertVercelUsageToPython(finishUsage)\n : { input_tokens: 0, output_tokens: 0, total_tokens: 0 },\n raw_output: rawOutput,\n model: getModelId(this.model),\n stop_reason: convertFinishReason(finishReason),\n },\n };\n }\n}\n","/**\n * Guardrails for validating and transforming LLM outputs.\n *\n * Guardrails are executed after each LLM generation to validate\n * the output and optionally modify it before continuing.\n */\n\nimport type { WorkflowContext } from '../core/context.js';\nimport type { CoreMessage, ToolCall } from '../types/llm.js';\n\n/**\n * Context passed to guardrails during execution.\n */\nexport interface GuardrailContext {\n /** Text content from LLM (if any) */\n content?: string | undefined;\n /** Tool calls from LLM (if any) */\n toolCalls: ToolCall[];\n /** Messages so far in the conversation */\n messages: CoreMessage[];\n /** Number of guardrail retries so far */\n retryCount: number;\n /** Maximum allowed retries */\n maxRetries: number;\n}\n\n/**\n * Result from a guardrail execution.\n */\nexport interface GuardrailResultType {\n /** Whether to continue execution */\n continue: boolean;\n /** Error message if guardrail failed */\n error?: string | undefined;\n /** Modified content to use instead */\n modifiedContent?: string | undefined;\n /** Modified tool calls to use instead */\n modifiedToolCalls?: ToolCall[] | undefined;\n /** Whether to retry the LLM call */\n retry?: boolean | undefined;\n /** Custom feedback to include in retry prompt */\n retryFeedback?: string | undefined;\n}\n\n/**\n * Guardrail handler function type.\n */\nexport type GuardrailHandler<TState = unknown> = (\n ctx: WorkflowContext<TState>,\n guardrailCtx: GuardrailContext\n) => Promise<GuardrailResultType>;\n\n/**\n * Guardrail definition with optional metadata.\n */\nexport interface Guardrail<TState = unknown> {\n /** Guardrail handler function */\n handler: GuardrailHandler<TState>;\n /** Optional guardrail name for debugging/tracing */\n name?: string | undefined;\n /** Optional guardrail description */\n description?: string | undefined;\n /** Priority (lower numbers run first, default: 0) */\n priority?: number | undefined;\n}\n\n/**\n * Options for defining a guardrail.\n */\nexport interface DefineGuardrailOptions {\n /** Guardrail name for debugging/tracing */\n name?: string | undefined;\n /** Guardrail description */\n description?: string | undefined;\n /** Priority (lower numbers run first, default: 0) */\n priority?: number | undefined;\n}\n\n/**\n * Helper for creating guardrail results.\n */\nexport const GuardrailResult = {\n /**\n * Continue execution without modifications.\n *\n * @example\n * ```typescript\n * if (isContentSafe(guardrailCtx.content)) {\n * return GuardrailResult.continue();\n * }\n * ```\n */\n continue: (): GuardrailResultType => ({ continue: true }),\n\n /**\n * Continue execution with modifications.\n *\n * @example\n * ```typescript\n * const sanitized = sanitizeContent(guardrailCtx.content);\n * return GuardrailResult.continueWith({\n * modifiedContent: sanitized,\n * });\n * ```\n */\n continueWith: (options: {\n modifiedContent?: string;\n modifiedToolCalls?: ToolCall[];\n }): GuardrailResultType => {\n const result: GuardrailResultType = { continue: true };\n if (options.modifiedContent !== undefined) {\n result.modifiedContent = options.modifiedContent;\n }\n if (options.modifiedToolCalls !== undefined) {\n result.modifiedToolCalls = options.modifiedToolCalls;\n }\n return result;\n },\n\n /**\n * Stop execution with an error.\n *\n * @example\n * ```typescript\n * if (containsHarmfulContent(guardrailCtx.content)) {\n * return GuardrailResult.fail('Content contains harmful material');\n * }\n * ```\n */\n fail: (error: string): GuardrailResultType => ({\n continue: false,\n error,\n }),\n\n /**\n * Retry the LLM call with optional feedback.\n *\n * This will trigger a new LLM generation with the provided feedback\n * included in the context. The retry count will be incremented.\n *\n * @example\n * ```typescript\n * if (!isValidFormat(guardrailCtx.content)) {\n * return GuardrailResult.retry(\n * 'Please format your response as valid JSON with the required fields.'\n * );\n * }\n * ```\n */\n retry: (feedback?: string): GuardrailResultType => ({\n continue: false,\n retry: true,\n retryFeedback: feedback,\n }),\n};\n\n/**\n * Define a guardrail for validating LLM outputs.\n *\n * @example\n * ```typescript\n * // Content filter guardrail\n * const contentFilter = defineGuardrail(\n * async (ctx, guardrailCtx) => {\n * const content = guardrailCtx.content;\n *\n * if (!content) {\n * return GuardrailResult.fail('No content generated');\n * }\n *\n * if (containsInappropriateContent(content)) {\n * return GuardrailResult.fail('Content contains inappropriate material');\n * }\n *\n * const sanitized = sanitizeContent(content);\n * return GuardrailResult.continueWith({ modifiedContent: sanitized });\n * },\n * { name: 'content-filter', priority: 10 }\n * );\n *\n * // Tool validator guardrail\n * const toolValidator = defineGuardrail(async (ctx, guardrailCtx) => {\n * for (const call of guardrailCtx.toolCalls) {\n * if (call.name === 'dangerous-tool' && !ctx.state.isAdmin) {\n * return GuardrailResult.fail('Unauthorized tool access');\n * }\n * }\n * return GuardrailResult.continue();\n * });\n * ```\n */\nexport function defineGuardrail<TState = unknown>(\n handler: GuardrailHandler<TState>,\n options?: DefineGuardrailOptions\n): Guardrail<TState> {\n return {\n handler,\n name: options?.name,\n description: options?.description,\n priority: options?.priority ?? 0,\n };\n}\n\n/**\n * Type guard to check if a value is a Guardrail object.\n */\nexport function isGuardrail<TState = unknown>(value: unknown): value is Guardrail<TState> {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'handler' in value &&\n typeof (value as Guardrail).handler === 'function'\n );\n}\n\n/**\n * Normalize a guardrail handler or Guardrail object to a Guardrail.\n */\nexport function normalizeGuardrail<TState = unknown>(\n guardrailOrHandler: Guardrail<TState> | GuardrailHandler<TState>\n): Guardrail<TState> {\n if (isGuardrail<TState>(guardrailOrHandler)) {\n return guardrailOrHandler;\n }\n return { handler: guardrailOrHandler };\n}\n\n/**\n * Normalize and sort an array of guardrails by priority.\n */\nexport function normalizeGuardrails<TState = unknown>(\n guardrails: (Guardrail<TState> | GuardrailHandler<TState>)[] | undefined\n): Guardrail<TState>[] {\n if (guardrails === undefined) {\n return [];\n }\n\n return guardrails\n .map((g) => normalizeGuardrail(g))\n .sort((a, b) => (a.priority ?? 0) - (b.priority ?? 0));\n}\n","/**\n * Exponential backoff retry utilities.\n */\n\nexport interface RetryOptions {\n /** Maximum number of retry attempts (default: 3) */\n maxRetries?: number;\n /** Initial delay in milliseconds (default: 1000) */\n baseDelay?: number;\n /** Maximum delay in milliseconds (default: 30000) */\n maxDelay?: number;\n /** Multiplier for exponential backoff (default: 2) */\n backoffMultiplier?: number;\n /** Add random jitter to delays (default: true) */\n jitter?: boolean;\n /** Function to determine if error is retryable (default: all errors) */\n isRetryable?: (error: unknown) => boolean;\n /** Callback called before each retry */\n onRetry?: (error: unknown, attempt: number, delay: number) => void;\n}\n\nconst DEFAULT_OPTIONS: Required<Omit<RetryOptions, 'onRetry' | 'isRetryable'>> = {\n maxRetries: 3,\n baseDelay: 1000,\n maxDelay: 30000,\n backoffMultiplier: 2,\n jitter: true,\n};\n\n/**\n * Calculate delay for a given attempt with exponential backoff.\n */\nexport function calculateDelay(\n attempt: number,\n options: Pick<RetryOptions, 'baseDelay' | 'maxDelay' | 'backoffMultiplier' | 'jitter'>\n): number {\n const { baseDelay = 1000, maxDelay = 30000, backoffMultiplier = 2, jitter = true } = options;\n\n // Exponential backoff: baseDelay * (multiplier ^ attempt)\n let delay = baseDelay * Math.pow(backoffMultiplier, attempt);\n\n // Cap at maxDelay\n delay = Math.min(delay, maxDelay);\n\n // Add jitter (±25%)\n if (jitter) {\n const jitterRange = delay * 0.25;\n delay = delay - jitterRange + Math.random() * jitterRange * 2;\n }\n\n return Math.round(delay);\n}\n\n/**\n * Sleep for a given duration.\n */\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Execute a function with exponential backoff retry.\n *\n * @example\n * ```typescript\n * const result = await retry(\n * () => fetchData(),\n * {\n * maxRetries: 3,\n * baseDelay: 1000,\n * isRetryable: (err) => err instanceof NetworkError,\n * }\n * );\n * ```\n */\nexport async function retry<T>(fn: () => T | Promise<T>, options: RetryOptions = {}): Promise<T> {\n const opts = { ...DEFAULT_OPTIONS, ...options };\n let lastError: unknown;\n\n for (let attempt = 0; attempt <= opts.maxRetries; attempt++) {\n try {\n return await fn();\n } catch (error) {\n lastError = error;\n\n // Check if we should retry\n if (attempt >= opts.maxRetries) {\n break;\n }\n\n // Check if error is retryable\n if (opts.isRetryable && !opts.isRetryable(error)) {\n break;\n }\n\n // Calculate delay and wait\n const delay = calculateDelay(attempt, opts);\n\n // Call onRetry callback\n opts.onRetry?.(error, attempt + 1, delay);\n\n await sleep(delay);\n }\n }\n\n throw lastError;\n}\n\n/**\n * Create a retry wrapper with preset options.\n *\n * @example\n * ```typescript\n * const retryWithBackoff = createRetry({ maxRetries: 5 });\n * const result = await retryWithBackoff(() => fetchData());\n * ```\n */\nexport function createRetry(defaultOptions: RetryOptions) {\n return <T>(fn: () => T | Promise<T>, options?: RetryOptions): Promise<T> => {\n return retry(fn, { ...defaultOptions, ...options });\n };\n}\n","/**\n * StepHelper implementation.\n *\n * Provides durable operations within workflows including step execution,\n * workflow invocation, waiting, and event publishing.\n *\n */\n\nimport { randomUUID } from 'node:crypto';\nimport type { Workflow, WorkflowHandle, WorkflowStatus } from '../types/workflow.js';\nimport { retry, type RetryOptions } from '../utils/retry.js';\n\n/**\n * Error thrown when a step execution fails.\n */\nexport class StepExecutionError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'StepExecutionError';\n }\n}\n\n/**\n * Internal error thrown when workflow execution must pause to wait.\n * @internal\n */\nexport class WaitError extends Error {\n /** Discriminator for runtime checks (survives minification unlike instanceof). */\n readonly __isWaitError = true as const;\n /** Structured data about the wait. */\n readonly waitData: Record<string, unknown>;\n\n constructor(reason: string, waitData?: Record<string, unknown>) {\n super(reason);\n this.name = 'WaitError';\n this.waitData = waitData ?? {};\n }\n}\n\n/**\n * Type guard for WaitError — works across module boundaries and minification.\n * @internal\n */\nexport function isWaitError(error: unknown): error is WaitError {\n return (\n error instanceof WaitError ||\n (typeof error === 'object' &&\n error !== null &&\n '__isWaitError' in error &&\n (error as Record<string, unknown>)['__isWaitError'] === true)\n );\n}\n\n/**\n * Options for step execution.\n */\nexport interface StepOptions {\n /** Maximum retry attempts (default: 2) */\n maxRetries?: number | undefined;\n /** Initial delay for exponential backoff in ms (default: 1000) */\n baseDelay?: number | undefined;\n /** Maximum delay for exponential backoff in ms (default: 10000) */\n maxDelay?: number | undefined;\n /** Input data to record in the trace span (for observability) */\n input?: unknown;\n}\n\n/**\n * Options for invoking another workflow.\n */\nexport interface InvokeOptions {\n /** Concurrency key for rate limiting */\n concurrencyKey?: string | undefined;\n /** Initial state for the sub-workflow */\n initialState?: Record<string, unknown> | undefined;\n /** Queue name to run the sub-workflow on */\n queue?: string | undefined;\n /** Timeout in seconds for the sub-workflow execution */\n runTimeoutSeconds?: number | undefined;\n}\n\n/**\n * Options for waiting a duration.\n */\nexport interface WaitForOptions {\n /** Seconds to wait */\n seconds?: number | undefined;\n /** Minutes to wait */\n minutes?: number | undefined;\n /** Hours to wait */\n hours?: number | undefined;\n /** Days to wait */\n days?: number | undefined;\n /** Weeks to wait */\n weeks?: number | undefined;\n}\n\n/**\n * Options for waiting on an event.\n */\nexport interface WaitForEventOptions {\n /** Event topic to wait on */\n topic: string;\n /** Timeout in seconds */\n timeout?: number | undefined;\n}\n\n/**\n * Options for publishing an event.\n */\nexport interface PublishEventOptions {\n /** Event topic */\n topic: string;\n /** Event type */\n type?: string | undefined;\n /** Event data */\n data: unknown;\n}\n\n/**\n * Options for suspending workflow execution.\n */\nexport interface SuspendOptions<T = unknown> {\n /** Data to include in the suspension */\n data?: T | undefined;\n /** Timeout in seconds before auto-resuming */\n timeout?: number | undefined;\n}\n\n/**\n * Options for resuming a suspended workflow.\n */\nexport interface ResumeOptions {\n /** The step key used in the original suspend() call */\n suspendStepKey: string;\n /** The root execution ID of the suspended execution */\n suspendExecutionId: string;\n /** The root workflow ID of the suspended execution */\n suspendWorkflowId: string;\n /** Data to pass in the resume event */\n data: unknown;\n}\n\n/**\n * Input for batch workflow invocation.\n */\nexport interface BatchWorkflowInput {\n /** Workflow to invoke (ID string or Workflow object) */\n workflow: string | Workflow;\n /** Payload for this invocation */\n payload: unknown;\n /** Initial state for the sub-workflow */\n initialState?: Record<string, unknown> | undefined;\n /** Timeout in seconds for the sub-workflow execution */\n runTimeoutSeconds?: number | undefined;\n}\n\n/**\n * Result of a single workflow in a batch invocation.\n * Matches Python BatchStepResult.\n */\nexport interface BatchStepResult<T = unknown> {\n /** The workflow ID that was invoked */\n workflowId: string;\n /** Whether the workflow completed successfully */\n success: boolean;\n /** The result from the workflow (if successful) */\n result: T | null;\n /** Error message (if failed) */\n error: string | null;\n}\n\n/**\n * Configuration for agent invocation.\n * Matches Python AgentRunConfig.\n *\n * Created by AgentWorkflow.withInput(). Used by step.agentInvoke(),\n * step.batchAgentInvoke(), and the standalone batchAgentInvoke().\n */\nexport class AgentRunConfig {\n /** The agent workflow */\n readonly agent: Workflow;\n /** Input for the agent (string message or message array) */\n readonly input: string | Record<string, unknown>[];\n /** Session ID */\n readonly sessionId: string | undefined;\n /** User ID */\n readonly userId: string | undefined;\n /** Whether to stream the response */\n readonly streaming: boolean;\n /** Initial state for the agent workflow */\n readonly initialState: Record<string, unknown> | undefined;\n /** Timeout in seconds for execution */\n readonly runTimeoutSeconds: number | undefined;\n /** Additional fields to include in the payload */\n readonly kwargs: Record<string, unknown>;\n\n constructor(options: {\n agent: Workflow;\n input: string | Record<string, unknown>[];\n sessionId?: string;\n userId?: string;\n streaming?: boolean;\n initialState?: Record<string, unknown>;\n runTimeoutSeconds?: number;\n kwargs?: Record<string, unknown>;\n }) {\n this.agent = options.agent;\n this.input = options.input;\n this.sessionId = options.sessionId;\n this.userId = options.userId;\n this.streaming = options.streaming ?? false;\n this.initialState = options.initialState;\n this.runTimeoutSeconds = options.runTimeoutSeconds;\n this.kwargs = options.kwargs ?? {};\n }\n}\n\n/**\n * Step execution result stored for replay.\n */\nexport interface StepResult<T = unknown> {\n /** Step key */\n key: string;\n /** Result value */\n value: T;\n /** When the step completed */\n completedAt: Date;\n}\n\n/**\n * Internal step store interface for caching step results.\n */\nexport interface StepStore {\n /** Get a cached step result */\n\n get<T>(key: string): StepResult<T> | undefined;\n /** Store a step result */\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters -- T is used for input type inference\n set<T>(key: string, value: T): void;\n /** Check if a step has been executed */\n has(key: string): boolean;\n}\n\n/**\n * Create an in-memory step store.\n */\nexport function createStepStore(): StepStore {\n const results = new Map<string, StepResult>();\n\n return {\n get<T>(key: string): StepResult<T> | undefined {\n return results.get(key) as StepResult<T> | undefined;\n },\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters -- T is used for input type inference\n set<T>(key: string, value: T): void {\n results.set(key, {\n key,\n value,\n completedAt: new Date(),\n });\n },\n has(key: string): boolean {\n return results.has(key);\n },\n };\n}\n\n/**\n * StepHelper provides durable operations within workflows.\n */\nexport interface StepHelper {\n /**\n * Execute a function as a durable step.\n * Results are cached and replayed on retry.\n */\n run<T>(key: string, fn: () => T | Promise<T>, options?: StepOptions): Promise<T>;\n\n /**\n * Invoke another workflow (fire and forget).\n */\n invoke<TPayload = unknown, TResult = unknown>(\n key: string,\n workflow: string | Workflow<TPayload, unknown, TResult>,\n payload: TPayload,\n options?: InvokeOptions\n ): Promise<WorkflowHandle<TResult>>;\n\n /**\n * Invoke another workflow and wait for result.\n */\n invokeAndWait<TPayload = unknown, TResult = unknown>(\n key: string,\n workflow: string | Workflow<TPayload, unknown, TResult>,\n payload: TPayload,\n options?: InvokeOptions\n ): Promise<TResult>;\n\n /**\n * Invoke multiple workflows in batch.\n */\n batchInvoke(key: string, items: BatchWorkflowInput[]): Promise<WorkflowHandle<unknown>[]>;\n\n /**\n * Invoke multiple workflows and wait for all results.\n */\n batchInvokeAndWait<T>(key: string, items: BatchWorkflowInput[]): Promise<BatchStepResult<T>[]>;\n\n /**\n * Wait for a time duration.\n */\n waitFor(key: string, options: WaitForOptions): Promise<void>;\n\n /**\n * Wait until a specific date/time.\n */\n waitUntil(key: string, date: Date): Promise<void>;\n\n /**\n * Wait for an event on a topic.\n */\n waitForEvent<T>(key: string, options: WaitForEventOptions): Promise<T>;\n\n /**\n * Publish an event to a topic.\n */\n publishEvent(key: string, options: PublishEventOptions): Promise<void>;\n\n /**\n * Publish an event on the current workflow's topic.\n */\n publishWorkflowEvent(key: string, options: { data: unknown; type?: string }): Promise<void>;\n\n /**\n * Suspend workflow execution and wait for external resume.\n */\n suspend<T = unknown, R = unknown>(key: string, options?: SuspendOptions<T>): Promise<R>;\n\n /**\n * Resume a suspended execution by publishing a resume event.\n */\n resume(key: string, options: ResumeOptions): Promise<void>;\n\n /**\n * Generate a durable UUID (persisted via step key).\n */\n uuid(key: string): Promise<string>;\n\n /**\n * Get current timestamp in milliseconds (persisted via step key).\n */\n now(key: string): Promise<number>;\n\n /**\n * Generate a durable random number between 0 and 1 (persisted via step key).\n */\n random(key: string): Promise<number>;\n\n /**\n * Invoke an agent workflow (fire and forget).\n */\n agentInvoke(key: string, config: AgentRunConfig): Promise<WorkflowHandle<unknown>>;\n\n /**\n * Invoke an agent workflow and wait for result.\n */\n agentInvokeAndWait(key: string, config: AgentRunConfig): Promise<unknown>;\n\n /**\n * Invoke multiple agent workflows in batch (fire and forget).\n */\n batchAgentInvoke(key: string, configs: AgentRunConfig[]): Promise<WorkflowHandle<unknown>[]>;\n\n /**\n * Invoke multiple agent workflows in batch and wait for all results.\n */\n batchAgentInvokeAndWait<T>(key: string, configs: AgentRunConfig[]): Promise<BatchStepResult<T>[]>;\n\n /**\n * Create a custom traced span around an async operation.\n */\n trace<T>(\n name: string,\n fn: (span: unknown) => Promise<T>,\n attributes?: Record<string, string | number | boolean>\n ): Promise<T>;\n}\n\n/**\n * Options for creating a StepHelper.\n */\nexport interface CreateStepHelperOptions {\n /** Step store for caching results */\n store: StepStore;\n}\n\n/**\n * Create a local StepHelper instance (for testing / local execution).\n * The real orchestrator-backed implementation is in runtime/executor.ts.\n */\nexport function createStepHelper(options: CreateStepHelperOptions): StepHelper {\n const { store } = options;\n\n return {\n async run<T>(key: string, fn: () => T | Promise<T>, stepOptions?: StepOptions): Promise<T> {\n // Check if step result is cached\n const cached = store.get<T>(key);\n if (cached) {\n return cached.value;\n }\n\n // Execute with retry\n const retryOptions: RetryOptions = {\n maxRetries: stepOptions?.maxRetries ?? 2,\n baseDelay: stepOptions?.baseDelay ?? 1000,\n maxDelay: stepOptions?.maxDelay ?? 10000,\n };\n\n try {\n const result = await retry(fn, retryOptions);\n store.set(key, result);\n return result;\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n throw new StepExecutionError(\n `Step execution failed after ${String(retryOptions.maxRetries)} retries: ${errorMessage}`\n );\n }\n },\n\n // eslint-disable-next-line @typescript-eslint/require-await -- stub implementation\n async invoke<TPayload, TResult>(\n key: string,\n _workflow: string | Workflow<TPayload, unknown, TResult>,\n _payload: TPayload,\n _options?: InvokeOptions\n ): Promise<WorkflowHandle<TResult>> {\n const cached = store.get<WorkflowHandle<TResult>>(key);\n if (cached) {\n return cached.value;\n }\n\n // Local stub — no orchestrator\n const executionId = randomUUID();\n const handle: WorkflowHandle<TResult> = {\n executionId,\n // eslint-disable-next-line @typescript-eslint/require-await -- stub\n getStatus: async (): Promise<WorkflowStatus<TResult>> => ({\n status: 'queued',\n createdAt: new Date(),\n }),\n // eslint-disable-next-line @typescript-eslint/require-await -- stub\n waitForResult: async (): Promise<TResult> => {\n throw new Error('Orchestrator client not configured');\n },\n // eslint-disable-next-line @typescript-eslint/require-await -- stub\n cancel: async (): Promise<void> => {\n throw new Error('Orchestrator client not configured');\n },\n };\n\n store.set(key, handle);\n return handle;\n },\n\n // eslint-disable-next-line @typescript-eslint/require-await -- stub throws WaitError\n async invokeAndWait<TPayload, TResult>(\n key: string,\n workflow: string | Workflow<TPayload, unknown, TResult>,\n _payload: TPayload,\n _options?: InvokeOptions\n ): Promise<TResult> {\n // Check cache (matching Python: _invoke with wait_for_subworkflow=True returns cached result)\n const cached = store.get<TResult>(key);\n if (cached) {\n return cached.value;\n }\n\n // Local stub — no orchestrator. Throw WaitError (matching Python WaitException).\n const workflowId = typeof workflow === 'string' ? workflow : workflow.id;\n throw new WaitError(`Waiting for sub-workflow '${workflowId}' to complete`, { workflowId });\n },\n\n async batchInvoke(\n key: string,\n items: BatchWorkflowInput[]\n ): Promise<WorkflowHandle<unknown>[]> {\n const cached = store.get<WorkflowHandle<unknown>[]>(key);\n if (cached) {\n return cached.value;\n }\n\n const handles: WorkflowHandle<unknown>[] = [];\n for (const [index, item] of items.entries()) {\n const handle = await this.invoke(`${key}:${String(index)}`, item.workflow, item.payload);\n handles.push(handle);\n }\n\n store.set(key, handles);\n return handles;\n },\n\n // eslint-disable-next-line @typescript-eslint/require-await -- stub throws WaitError\n async batchInvokeAndWait<T>(\n key: string,\n items: BatchWorkflowInput[]\n ): Promise<BatchStepResult<T>[]> {\n if (items.length === 0) return [];\n\n // Check cache (matching Python: _check_existing_step → reconstruct results)\n const cached = store.get<BatchStepResult<T>[]>(key);\n if (cached) {\n return cached.value;\n }\n\n // Local stub — no orchestrator. Throw WaitError (matching Python WaitException).\n const workflowIds = items\n .map((item) => (typeof item.workflow === 'string' ? item.workflow : item.workflow.id))\n .join(', ');\n throw new WaitError(`Waiting for sub-workflows [${workflowIds}] to complete`, {\n workflowIds: workflowIds.split(', '),\n });\n },\n\n async waitFor(key: string, options: WaitForOptions): Promise<void> {\n const cached = store.get(key);\n if (cached) return;\n\n let totalSeconds = 0;\n if (options.seconds) totalSeconds += options.seconds;\n if (options.minutes) totalSeconds += options.minutes * 60;\n if (options.hours) totalSeconds += options.hours * 3600;\n if (options.days) totalSeconds += options.days * 86400;\n if (options.weeks) totalSeconds += options.weeks * 604800;\n\n const totalMs = totalSeconds * 1000;\n await new Promise((resolve) => setTimeout(resolve, totalMs));\n store.set(key, { wait_until: new Date(Date.now() + totalMs).toISOString() });\n },\n\n async waitUntil(key: string, date: Date): Promise<void> {\n const cached = store.get(key);\n if (cached) return;\n\n const now = Date.now();\n const waitMs = Math.max(0, date.getTime() - now);\n await new Promise((resolve) => setTimeout(resolve, waitMs));\n store.set(key, { wait_until: date.toISOString() });\n },\n\n // eslint-disable-next-line @typescript-eslint/require-await -- stub implementation\n async waitForEvent<T>(key: string, eventOptions: WaitForEventOptions): Promise<T> {\n const cached = store.get<T>(key);\n if (cached) {\n return cached.value;\n }\n throw new Error(`waitForEvent not implemented locally: ${eventOptions.topic}`);\n },\n\n // eslint-disable-next-line @typescript-eslint/require-await -- stub implementation\n async publishEvent(key: string, _options: PublishEventOptions): Promise<void> {\n if (store.has(key)) return;\n store.set(key, null);\n },\n\n async publishWorkflowEvent(\n key: string,\n options: { data: unknown; type?: string }\n ): Promise<void> {\n // Local stub — no workflow topic available\n return this.publishEvent(key, { topic: 'local', ...options });\n },\n\n // eslint-disable-next-line @typescript-eslint/require-await -- stub implementation\n async suspend<T, R>(key: string, _options?: SuspendOptions<T>): Promise<R> {\n const cached = store.get<R>(key);\n if (cached) {\n return cached.value;\n }\n throw new Error('suspend not implemented locally');\n },\n\n async resume(key: string, options: ResumeOptions): Promise<void> {\n const topic = `workflow/${options.suspendWorkflowId}/${options.suspendExecutionId}`;\n return this.publishEvent(key, {\n topic,\n type: `resume_${options.suspendStepKey}`,\n data: options.data,\n });\n },\n\n // eslint-disable-next-line @typescript-eslint/require-await -- stub implementation\n async uuid(key: string): Promise<string> {\n const cached = store.get<string>(key);\n if (cached) {\n return cached.value;\n }\n const generated = randomUUID();\n store.set(key, generated);\n return generated;\n },\n\n // eslint-disable-next-line @typescript-eslint/require-await -- stub implementation\n async now(key: string): Promise<number> {\n const cached = store.get<number>(key);\n if (cached) {\n return cached.value;\n }\n const timestamp = Date.now();\n store.set(key, timestamp);\n return timestamp;\n },\n\n // eslint-disable-next-line @typescript-eslint/require-await -- stub implementation\n async random(key: string): Promise<number> {\n const cached = store.get<number>(key);\n if (cached) {\n return cached.value;\n }\n const value = Math.random();\n store.set(key, value);\n return value;\n },\n\n // --- Agent invoke stubs (local — delegates to invoke/batchInvoke) ---\n // Matches Python step.py agent_invoke / batch_agent_invoke etc.\n\n async agentInvoke(key: string, config: AgentRunConfig): Promise<WorkflowHandle<unknown>> {\n const payload = {\n input: config.input,\n streaming: config.streaming,\n session_id: undefined as string | undefined,\n user_id: undefined as string | undefined,\n ...config.kwargs,\n };\n return this.invoke(key, config.agent, payload);\n },\n\n async agentInvokeAndWait(key: string, config: AgentRunConfig): Promise<unknown> {\n const payload = {\n input: config.input,\n streaming: config.streaming,\n session_id: undefined as string | undefined,\n user_id: undefined as string | undefined,\n ...config.kwargs,\n };\n return this.invokeAndWait(key, config.agent, payload);\n },\n\n async batchAgentInvoke(\n key: string,\n configs: AgentRunConfig[]\n ): Promise<WorkflowHandle<unknown>[]> {\n const items: BatchWorkflowInput[] = configs.map((config) => ({\n workflow: config.agent,\n payload: {\n input: config.input,\n streaming: config.streaming,\n session_id: undefined as string | undefined,\n user_id: undefined as string | undefined,\n ...config.kwargs,\n },\n initialState: config.initialState,\n runTimeoutSeconds: config.runTimeoutSeconds,\n }));\n return this.batchInvoke(key, items);\n },\n\n async batchAgentInvokeAndWait<T>(\n key: string,\n configs: AgentRunConfig[]\n ): Promise<BatchStepResult<T>[]> {\n const items: BatchWorkflowInput[] = configs.map((config) => ({\n workflow: config.agent,\n payload: {\n input: config.input,\n streaming: config.streaming,\n session_id: undefined as string | undefined,\n user_id: undefined as string | undefined,\n ...config.kwargs,\n },\n initialState: config.initialState,\n runTimeoutSeconds: config.runTimeoutSeconds,\n }));\n return this.batchInvokeAndWait<T>(key, items);\n },\n\n async trace<T>(\n _name: string,\n fn: (span: unknown) => Promise<T>,\n _attributes?: Record<string, string | number | boolean>\n ): Promise<T> {\n return fn(undefined);\n },\n };\n}\n","/**\n * Hook execution engine.\n *\n * Handles sequential execution of hooks with durable step-based execution,\n * payload/output modification, and result aggregation.\n *\n * Matches Python sdk/python/polos/middleware/hook_executor.py.\n */\n\nimport type { WorkflowContext } from '../core/context.js';\nimport type { Hook, HookContext, HookResultType } from './hook.js';\nimport { normalizeHooks } from './hook.js';\n\n/**\n * Error thrown when a hook fails.\n */\nexport class HookExecutionError extends Error {\n constructor(\n message: string,\n public readonly hookName: string | undefined,\n public readonly phase: 'onStart' | 'onEnd',\n public override readonly cause?: Error\n ) {\n super(message, { cause });\n this.name = 'HookExecutionError';\n }\n}\n\n/**\n * Result from executing a chain of hooks.\n */\nexport interface HookChainResult<TPayload> {\n /** Whether all hooks passed */\n success: boolean;\n /** Final payload after all modifications */\n payload: TPayload;\n /** Final output after all modifications (for onEnd hooks) */\n // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents -- needed for exactOptionalPropertyTypes\n output?: unknown | undefined;\n /** Error message if a hook failed */\n error?: string | undefined;\n /** Name of the hook that failed (if any) */\n failedHook?: string | undefined;\n /** Number of hooks executed */\n hooksExecuted: number;\n}\n\n/**\n * Options for hook execution.\n */\nexport interface ExecuteHooksOptions<TPayload> {\n /** The workflow context (must have step for durable execution) */\n ctx: WorkflowContext;\n /** Hook chain name for durable step key naming (e.g., \"on_start\", \"on_end\").\n * Matching Python execute_hooks hook_name parameter. */\n hookName: string;\n /** Payload to pass to hooks */\n payload: TPayload;\n /** Workflow output (for onEnd hooks, matching Python HookContext.current_output) */\n // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents -- needed for exactOptionalPropertyTypes\n output?: unknown | undefined;\n /** Execution phase */\n phase: 'onStart' | 'onEnd';\n}\n\n/**\n * Get a unique identifier for a hook function.\n * Matching Python _get_function_identifier.\n */\nfunction getHookIdentifier(\n hook: { name?: string | undefined; handler: { name: string } },\n index: number\n): string {\n if (hook.name) {\n return hook.name;\n }\n if (hook.handler.name && hook.handler.name !== '') {\n return hook.handler.name;\n }\n return `hook_${String(index)}`;\n}\n\n/**\n * Execute a chain of hooks sequentially with durable execution.\n *\n * Each hook is executed via ctx.step.run() for durability — results are\n * cached and replayed on retry. Matching Python execute_hooks().\n *\n * Hooks are executed in order. If a hook returns `continue: false`,\n * execution stops and the error is returned. Payload and output\n * modifications from each hook are passed to the next hook.\n */\nexport async function executeHookChain<TPayload, TState>(\n hooks:\n | Hook<TPayload, TState>\n | Hook<TPayload, TState>[]\n | ((ctx: WorkflowContext<TState>, hookCtx: HookContext<TPayload>) => Promise<HookResultType>)\n | ((ctx: WorkflowContext<TState>, hookCtx: HookContext<TPayload>) => Promise<HookResultType>)[]\n | undefined,\n options: ExecuteHooksOptions<TPayload>\n): Promise<HookChainResult<TPayload>> {\n const { ctx, hookName, payload, phase, output } = options;\n const normalizedHooks = normalizeHooks(hooks);\n\n if (normalizedHooks.length === 0) {\n return {\n success: true,\n payload,\n output,\n hooksExecuted: 0,\n };\n }\n\n let currentPayload = payload;\n let currentOutput = output;\n let hooksExecuted = 0;\n\n for (const [index, hook] of normalizedHooks.entries()) {\n const funcId = getHookIdentifier(hook, index);\n\n const hookCtx: HookContext<TPayload> = {\n workflowId: ctx.workflowId,\n sessionId: ctx.sessionId,\n userId: ctx.userId,\n currentPayload,\n currentOutput,\n phase,\n };\n\n try {\n // Execute hook durably via step.run (matching Python: ctx.step.run(...))\n const result = await ctx.step.run<HookResultType>(\n `${hookName}.${funcId}.${String(index)}`,\n () => hook.handler(ctx as WorkflowContext<TState>, hookCtx),\n { input: { payload: currentPayload, output: currentOutput, phase } }\n );\n hooksExecuted++;\n\n if (!result.continue) {\n return {\n success: false,\n payload: currentPayload,\n output: currentOutput,\n error: result.error ?? 'Hook execution stopped',\n failedHook: hook.name,\n hooksExecuted,\n };\n }\n\n // Apply payload modifications (matching Python: modified_payload.update(...))\n if (result.modifiedPayload !== undefined) {\n currentPayload = result.modifiedPayload as TPayload;\n }\n\n // Apply output modifications (matching Python: modified_output.update(...))\n if (result.modifiedOutput !== undefined) {\n currentOutput = result.modifiedOutput;\n }\n } catch (err) {\n hooksExecuted++;\n const errorMessage = err instanceof Error ? err.message : String(err);\n\n return {\n success: false,\n payload: currentPayload,\n output: currentOutput,\n error: `Hook${hook.name ? ` '${hook.name}'` : ''} threw an error: ${errorMessage}`,\n failedHook: hook.name,\n hooksExecuted,\n };\n }\n }\n\n return {\n success: true,\n payload: currentPayload,\n output: currentOutput,\n hooksExecuted,\n };\n}\n\n/**\n * Execute hooks and throw if any hook fails.\n *\n * Convenience wrapper around `executeHookChain` that throws\n * a `HookExecutionError` if any hook fails.\n *\n * @returns The final payload after all hook modifications\n * @throws HookExecutionError if any hook fails\n */\nexport async function executeHooksOrThrow<TPayload, TState>(\n hooks:\n | Hook<TPayload, TState>\n | Hook<TPayload, TState>[]\n | ((ctx: WorkflowContext<TState>, hookCtx: HookContext<TPayload>) => Promise<HookResultType>)\n | ((ctx: WorkflowContext<TState>, hookCtx: HookContext<TPayload>) => Promise<HookResultType>)[]\n | undefined,\n options: ExecuteHooksOptions<TPayload>\n): Promise<TPayload> {\n const result = await executeHookChain(hooks, options);\n\n if (!result.success) {\n throw new HookExecutionError(\n result.error ?? 'Hook execution failed',\n result.failedHook,\n options.phase\n );\n }\n\n return result.payload;\n}\n\n/**\n * Create a composite hook from multiple hooks.\n *\n * The composite hook executes all provided hooks in sequence and\n * returns the combined result.\n */\nexport function composeHooks<TPayload = unknown, TState = unknown>(\n hooks: Hook<TPayload, TState>[]\n): Hook<TPayload, TState> {\n return {\n name: `composed(${hooks.map((h) => h.name ?? 'anonymous').join(', ')})`,\n handler: async (ctx, hookCtx) => {\n const result = await executeHookChain(hooks, {\n ctx: ctx as WorkflowContext,\n hookName: 'composed',\n payload: hookCtx.currentPayload,\n phase: hookCtx.phase,\n output: hookCtx.currentOutput,\n });\n\n if (!result.success) {\n return {\n continue: false,\n error: result.error,\n };\n }\n\n return {\n continue: true,\n modifiedPayload: result.payload,\n modifiedOutput: result.output,\n };\n },\n };\n}\n\n/**\n * Create a hook that only runs if a condition is met.\n */\nexport function conditionalHook<TPayload = unknown, TState = unknown>(\n condition: (\n ctx: WorkflowContext<TState>,\n hookCtx: HookContext<TPayload>\n ) => boolean | Promise<boolean>,\n hook: Hook<TPayload, TState>\n): Hook<TPayload, TState> {\n return {\n name: `conditional(${hook.name ?? 'anonymous'})`,\n handler: async (ctx, hookCtx) => {\n const shouldRun = await condition(ctx, hookCtx);\n\n if (!shouldRun) {\n return { continue: true };\n }\n\n return hook.handler(ctx, hookCtx);\n },\n };\n}\n","/**\n * Guardrail execution engine.\n *\n * Handles sequential execution of guardrails with durable step-based execution,\n * content/tool modification, and result aggregation.\n *\n * Matches Python sdk/python/polos/middleware/guardrail_executor.py.\n */\n\nimport type { WorkflowContext } from '../core/context.js';\nimport type { ToolCall } from '../types/llm.js';\nimport type { Guardrail, GuardrailContext, GuardrailResultType } from './guardrail.js';\nimport { normalizeGuardrails } from './guardrail.js';\n\n/**\n * Error thrown when a guardrail fails.\n */\nexport class GuardrailError extends Error {\n constructor(\n message: string,\n public readonly guardrailName: string | undefined,\n public override readonly cause?: Error\n ) {\n super(message, { cause });\n this.name = 'GuardrailError';\n }\n}\n\n/**\n * Result from executing a chain of guardrails.\n */\nexport interface GuardrailChainResult {\n /** Whether all guardrails passed */\n success: boolean;\n /** Final content after all modifications */\n content?: string | undefined;\n /** Final tool calls after all modifications */\n toolCalls: ToolCall[];\n /** Error message if a guardrail failed */\n error?: string | undefined;\n /** Name of the guardrail that failed (if any) */\n failedGuardrail?: string | undefined;\n /** Number of guardrails executed */\n guardrailsExecuted: number;\n}\n\n/**\n * Options for guardrail execution.\n */\nexport interface ExecuteGuardrailsOptions {\n /** The workflow context (must have step for durable execution) */\n ctx: WorkflowContext;\n /** Guardrail chain name for durable step key naming (e.g., \"1.guardrail\").\n * Matching Python execute_guardrails guardrail_name parameter. */\n guardrailName: string;\n /** Text content from LLM */\n content?: string | undefined;\n /** Tool calls from LLM */\n toolCalls: ToolCall[];\n}\n\n/**\n * Get a unique identifier for a guardrail.\n * Matching Python _get_guardrail_identifier.\n */\nfunction getGuardrailIdentifier(guardrail: { name?: string | undefined }, index: number): string {\n if (guardrail.name) {\n return guardrail.name;\n }\n return `guardrail_${String(index)}`;\n}\n\n/**\n * Execute a chain of guardrails sequentially with durable execution.\n *\n * Each guardrail is executed via ctx.step.run() for durability — results are\n * cached and replayed on retry. Matching Python execute_guardrails().\n *\n * Guardrails are executed in priority order. If a guardrail returns\n * `continue: false`, execution stops and the error is returned.\n * Content and tool call modifications are accumulated sequentially.\n *\n * @example\n * ```typescript\n * const result = await executeGuardrailChain(\n * [contentFilter, toolValidator],\n * {\n * ctx: workflowContext,\n * guardrailName: '1.guardrail',\n * content: 'LLM response text',\n * toolCalls: [],\n * }\n * );\n *\n * if (!result.success) {\n * throw new Error(result.error);\n * }\n *\n * // Use the potentially modified content/tools\n * const finalContent = result.content;\n * const finalToolCalls = result.toolCalls;\n * ```\n */\nexport async function executeGuardrailChain<TState>(\n guardrails:\n | (\n | Guardrail<TState>\n | ((\n ctx: WorkflowContext<TState>,\n guardrailCtx: GuardrailContext\n ) => Promise<GuardrailResultType>)\n )[]\n | undefined,\n options: ExecuteGuardrailsOptions\n): Promise<GuardrailChainResult> {\n const { ctx, guardrailName } = options;\n const normalizedGuardrails = normalizeGuardrails(guardrails);\n\n let content = options.content;\n let toolCalls = [...options.toolCalls];\n\n if (normalizedGuardrails.length === 0) {\n return {\n success: true,\n content,\n toolCalls,\n guardrailsExecuted: 0,\n };\n }\n\n let guardrailsExecuted = 0;\n\n for (const [index, guardrail] of normalizedGuardrails.entries()) {\n const funcId = getGuardrailIdentifier(guardrail, index);\n\n // Update context with accumulated modifications (matching Python)\n const guardrailCtx: GuardrailContext = {\n content,\n toolCalls,\n messages: [],\n retryCount: 0,\n maxRetries: 0,\n };\n\n try {\n // Execute guardrail durably via step.run (matching Python: ctx.step.run(...))\n const result = await ctx.step.run<GuardrailResultType>(\n `${guardrailName}.${funcId}.${String(index)}`,\n () => guardrail.handler(ctx as WorkflowContext<TState>, guardrailCtx),\n { input: { content, toolCalls } }\n );\n guardrailsExecuted++;\n\n if (!result.continue) {\n return {\n success: false,\n content,\n toolCalls,\n error: result.error ?? 'Guardrail validation failed',\n failedGuardrail: guardrail.name,\n guardrailsExecuted,\n };\n }\n\n // Apply modifications (matching Python)\n if (result.modifiedContent !== undefined) {\n content = result.modifiedContent;\n }\n if (result.modifiedToolCalls !== undefined) {\n toolCalls = result.modifiedToolCalls;\n }\n } catch (err) {\n guardrailsExecuted++;\n const errorMessage = err instanceof Error ? err.message : String(err);\n\n return {\n success: false,\n content,\n toolCalls,\n error: `Guardrail${guardrail.name ? ` '${guardrail.name}'` : ''} threw an error: ${errorMessage}`,\n failedGuardrail: guardrail.name,\n guardrailsExecuted,\n };\n }\n }\n\n return {\n success: true,\n content,\n toolCalls,\n guardrailsExecuted,\n };\n}\n\n/**\n * Execute guardrails and throw if any guardrail fails.\n *\n * Convenience wrapper around `executeGuardrailChain` that throws\n * a `GuardrailError` if any guardrail fails.\n *\n * @returns The result with final content and tool calls\n * @throws GuardrailError if any guardrail fails\n */\nexport async function executeGuardrailsOrThrow<TState>(\n guardrails:\n | (\n | Guardrail<TState>\n | ((\n ctx: WorkflowContext<TState>,\n guardrailCtx: GuardrailContext\n ) => Promise<GuardrailResultType>)\n )[]\n | undefined,\n options: ExecuteGuardrailsOptions\n): Promise<GuardrailChainResult> {\n const result = await executeGuardrailChain(guardrails, options);\n\n if (!result.success) {\n throw new GuardrailError(result.error ?? 'Guardrail execution failed', result.failedGuardrail);\n }\n\n return result;\n}\n\n/**\n * Create a composite guardrail from multiple guardrails.\n *\n * The composite guardrail executes all provided guardrails in sequence\n * (by priority) and returns the combined result.\n *\n * @example\n * ```typescript\n * const allGuardrails = composeGuardrails([\n * contentFilter,\n * toolValidator,\n * formatChecker,\n * ]);\n *\n * const agent = defineAgent({\n * guardrails: [allGuardrails],\n * });\n * ```\n */\nexport function composeGuardrails<TState = unknown>(\n guardrails: Guardrail<TState>[]\n): Guardrail<TState> {\n return {\n name: `composed(${guardrails.map((g) => g.name ?? 'anonymous').join(', ')})`,\n handler: async (ctx, guardrailCtx) => {\n const result = await executeGuardrailChain(guardrails, {\n ctx: ctx as WorkflowContext,\n guardrailName: 'composed',\n content: guardrailCtx.content,\n toolCalls: guardrailCtx.toolCalls,\n });\n\n if (!result.success) {\n return {\n continue: false,\n error: result.error,\n };\n }\n\n return {\n continue: true,\n modifiedContent: result.content,\n modifiedToolCalls: result.toolCalls,\n };\n },\n };\n}\n","/**\n * Durable LLM generation with guardrail support.\n *\n * Matches Python _llm_generate exactly: wraps LLM.generate() in ctx.step.run()\n * for durability and runs guardrails with retry on failure.\n */\n\nimport type { WorkflowContext } from '../core/context.js';\nimport type { CoreMessage } from '../types/llm.js';\nimport { executeGuardrailChain } from '../middleware/guardrail-executor.js';\nimport type { LLM } from './llm.js';\nimport type { LLMGeneratePayload, LLMGenerateResult } from './types.js';\nimport { convertPythonToolCallToMiddleware, convertMiddlewareToolCallToPython } from './types.js';\n\n/**\n * Durable LLM generation with guardrail support.\n *\n * Matches Python _llm_generate exactly:\n * - Step key is `llm_generate:{agent_step}` (same key across retries, matching Python)\n * - Each guardrail is executed as a durable step via ctx.step.run()\n * - On guardrail failure, appends feedback as user message and retries\n * - On guardrail success, applies content/tool_call modifications\n *\n * @example\n * ```typescript\n * const result = await llmGenerate(ctx, llm, {\n * messages: [{ role: 'user', content: 'Hello' }],\n * agent_step: 1,\n * guardrails: [myGuardrail],\n * guardrail_max_retries: 2,\n * });\n * ```\n */\nexport async function llmGenerate(\n ctx: WorkflowContext,\n llm: LLM,\n payload: LLMGeneratePayload\n): Promise<LLMGenerateResult> {\n const {\n agent_step,\n guardrails,\n guardrail_max_retries: maxRetries = 2,\n ...generateOptions\n } = payload;\n\n const workingMessages: CoreMessage[] = [...generateOptions.messages];\n\n // Step key matches Python: `llm_generate:{agent_step}` (no retry count)\n const stepKey = `llm_generate:${String(agent_step)}`;\n\n let guardrailRetryCount = 0;\n\n // Guardrail retry loop (matching Python: while guardrail_retry_count <= guardrail_max_retries)\n while (guardrailRetryCount <= maxRetries) {\n // Build the LLM call options\n const llmCallOptions = {\n ...generateOptions,\n messages: workingMessages,\n };\n\n // Call LLM via step.run() for durable execution\n const response = await ctx.step.run(stepKey, () => llm.generate(llmCallOptions), {\n input: {\n kwargs: {\n messages: workingMessages,\n system: generateOptions.system,\n tools: generateOptions.tools,\n temperature: generateOptions.temperature,\n maxTokens: generateOptions.maxTokens,\n },\n },\n });\n\n // Build result (matching Python llm_result dict)\n const llmResult: LLMGenerateResult = {\n agent_run_id: ctx.executionId,\n status: 'completed',\n content: response.content,\n tool_calls: response.tool_calls,\n usage: response.usage,\n raw_output: response.raw_output,\n model: response.model,\n stop_reason: response.stop_reason,\n };\n\n // If no guardrails, return immediately (matching Python: if not guardrails: return llm_result)\n if (!guardrails || guardrails.length === 0) {\n return llmResult;\n }\n\n // Execute guardrails on the LLM result (matching Python execute_guardrails)\n // Convert tool calls to middleware format\n const middlewareToolCalls = (llmResult.tool_calls ?? []).map(convertPythonToolCallToMiddleware);\n\n // Use the shared executeGuardrailChain (each guardrail runs as a durable step)\n const guardrailChainResult = await executeGuardrailChain(guardrails, {\n ctx,\n guardrailName: `${String(agent_step)}.guardrail`,\n content: llmResult.content ?? undefined,\n toolCalls: middlewareToolCalls,\n });\n\n // Check guardrail result (matching Python: if guardrail_result.action == HookAction.FAIL)\n if (!guardrailChainResult.success) {\n // Guardrail failed - check if we can retry\n const guardrailErrorMessage = guardrailChainResult.error ?? 'Guardrail validation failed';\n\n if (guardrailRetryCount >= maxRetries) {\n // Exhausted retries - raise exception (matching Python)\n throw new Error(\n `Guardrail failed after ${String(maxRetries)} retries. Last error: ${guardrailErrorMessage}`\n );\n }\n\n // Add feedback to messages for retry (matching Python: messages.append({\"role\": \"user\", ...}))\n const feedbackMessage =\n `Previous attempt failed guardrail validation: ${guardrailErrorMessage}. ` +\n `Please revise your response accordingly.`;\n workingMessages.push({ role: 'user', content: feedbackMessage });\n guardrailRetryCount++;\n continue; // Retry LLM generation\n }\n\n // CONTINUE - all guardrails passed, apply accumulated modifications (matching Python)\n // Python always applies modified_content/modified_tool_calls when not None/empty\n if (guardrailChainResult.content !== undefined) {\n llmResult.content = guardrailChainResult.content ?? null;\n }\n // Always apply tool calls from chain result (matching Python: modified_tool_calls is\n // always a list, and `is not None` is always True, so Python always applies).\n // This ensures guardrails that remove tool calls (set to []) are respected.\n const modifiedToolCalls = guardrailChainResult.toolCalls.map(convertMiddlewareToolCallToPython);\n llmResult.tool_calls = modifiedToolCalls.length > 0 ? modifiedToolCalls : null;\n\n return llmResult;\n }\n\n // Should not reach here, but just in case (matching Python)\n throw new Error(`Failed to generate valid response after ${String(maxRetries)} retries`);\n}\n","/**\n * Durable LLM streaming with event publishing.\n *\n * Matches Python _llm_stream: streams LLM output inside ctx.step.run()\n * and publishes events directly (not via durable step execution).\n */\n\nimport type { WorkflowContext } from '../core/context.js';\nimport type { EventData } from '../types/events.js';\nimport type { LLM } from './llm.js';\nimport type { LLMGenerateResult, LLMStreamPayload, LLMToolCall, LLMUsage } from './types.js';\nimport { getModelId } from './types.js';\n\n/**\n * Function signature for publishing events directly (not via step system).\n * Matches Python's `publish_event(client, topic, event_data)` pattern.\n */\nexport type PublishEventFn = (topic: string, eventData: EventData) => Promise<void>;\n\n/**\n * Durable LLM streaming with event publishing.\n *\n * Wraps the streaming operation in ctx.step.run() for durability.\n * Events are published directly via the provided publishEvent function,\n * bypassing the step system (matching Python's direct publish_event calls).\n *\n * @param ctx - Workflow context for durability and metadata\n * @param llm - LLM instance to stream from\n * @param payload - Stream payload with messages, tools, agent_step, etc.\n * @param publishEvent - Function to publish events directly (e.g. from PolosClient or OrchestratorClient)\n *\n * @example\n * ```typescript\n * const result = await llmStream(ctx, llm, {\n * messages: [{ role: 'user', content: 'Tell me a story' }],\n * agent_step: 1,\n * }, async (topic, eventData) => {\n * await client.events.publish(topic, eventData);\n * });\n * ```\n */\nexport async function llmStream(\n ctx: WorkflowContext,\n llm: LLM,\n payload: LLMStreamPayload,\n publishEvent: PublishEventFn\n): Promise<LLMGenerateResult> {\n const { agent_step, ...generateOptions } = payload;\n\n const topic = `workflow/${ctx.rootWorkflowId}/${ctx.rootExecutionId}`;\n const stepKey = `llm_stream:${String(agent_step)}`;\n\n const result = await ctx.step.run(\n stepKey,\n async () => {\n // Publish stream_start event directly (not via step)\n await publishEvent(topic, {\n eventType: 'stream_start',\n data: { step: agent_step },\n });\n\n let accumulatedContent = '';\n const accumulatedToolCalls: LLMToolCall[] = [];\n let finalUsage: LLMUsage = { input_tokens: 0, output_tokens: 0, total_tokens: 0 };\n let finalModel = getModelId(llm.model);\n let finalStopReason: string | null = null;\n let finalRawOutput: unknown[] | null = null;\n let chunkIndex = 0;\n\n for await (const event of llm.stream(generateOptions)) {\n switch (event.type) {\n case 'text_delta': {\n accumulatedContent += event.data.content;\n await publishEvent(topic, {\n eventType: 'text_delta',\n data: {\n step: agent_step,\n chunk_index: chunkIndex,\n content: event.data.content,\n _metadata: {\n execution_id: ctx.executionId,\n workflow_id: ctx.workflowId,\n },\n },\n });\n chunkIndex++;\n break;\n }\n case 'tool_call': {\n accumulatedToolCalls.push(event.data.tool_call);\n await publishEvent(topic, {\n eventType: 'tool_call',\n data: {\n step: agent_step,\n chunk_index: chunkIndex,\n tool_call: event.data.tool_call,\n _metadata: {\n execution_id: ctx.executionId,\n workflow_id: ctx.workflowId,\n },\n },\n });\n chunkIndex++;\n break;\n }\n case 'done': {\n finalUsage = event.data.usage;\n finalModel = event.data.model;\n finalStopReason = event.data.stop_reason;\n finalRawOutput = event.data.raw_output;\n break;\n }\n case 'error': {\n throw new Error(`LLM stream error: ${event.data.error}`);\n }\n }\n }\n\n return {\n content: accumulatedContent || null,\n usage: finalUsage,\n tool_calls: accumulatedToolCalls.length > 0 ? accumulatedToolCalls : null,\n raw_output: finalRawOutput,\n model: finalModel,\n stop_reason: finalStopReason,\n agent_run_id: ctx.executionId,\n status: 'completed',\n } satisfies LLMGenerateResult;\n },\n {\n input: {\n kwargs: {\n messages: generateOptions.messages,\n system: generateOptions.system,\n tools: generateOptions.tools,\n temperature: generateOptions.temperature,\n maxTokens: generateOptions.maxTokens,\n },\n },\n }\n );\n\n return result;\n}\n","/**\n * Stop conditions for agents.\n *\n * Stop conditions allow you to define when an agent should stop executing.\n * Stop conditions execute durably within workflow context using step.run().\n *\n * Matches Python sdk/python/polos/agents/stop_conditions.py.\n */\n\nimport type { LLMToolCall, LLMUsage } from '../llm/types.js';\n\n// ── Types ────────────────────────────────────────────────────────────\n\n/**\n * Information about a tool result within a step.\n * Matches Python ToolResult Pydantic model.\n */\nexport interface ToolResultInfo {\n tool_name?: string | undefined;\n status?: string | undefined;\n result?: unknown;\n result_schema?: string | undefined;\n tool_call_id?: string | undefined;\n tool_call_call_id?: string | undefined;\n}\n\n/**\n * A single step in agent execution.\n * Matches Python Step Pydantic model.\n */\nexport interface StepInfo {\n step: number;\n content: string | null;\n tool_calls: LLMToolCall[];\n tool_results: ToolResultInfo[];\n usage: LLMUsage | null;\n raw_output: unknown;\n}\n\n/**\n * Context available to stop conditions.\n * Matches Python StopConditionContext Pydantic model.\n */\nexport interface StopConditionContext {\n steps: StepInfo[];\n agent_id?: string | undefined;\n agent_run_id?: string | undefined;\n}\n\n/**\n * A stop condition function that receives context and returns whether to stop.\n */\nexport interface StopCondition {\n (ctx: StopConditionContext): boolean | Promise<boolean>;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type -- metadata for identification\n __stop_condition_fn__?: Function | undefined;\n __stop_condition_name__?: string | undefined;\n}\n\n// ── stopCondition decorator ──────────────────────────────────────────\n\n/**\n * Decorator for stop condition functions.\n *\n * Stop conditions take `ctx: StopConditionContext` as the first parameter\n * and optionally a config object as the second parameter.\n * They return a boolean (true to stop, false to continue).\n *\n * When the decorated function has a config parameter, calling it with config\n * returns a configured callable that captures the config.\n *\n * Matches Python @stop_condition decorator.\n *\n * @example\n * ```typescript\n * // Simple stop condition (no config)\n * const alwaysStop = stopCondition(\n * (ctx: StopConditionContext) => true\n * );\n *\n * // With config\n * const maxTokens = stopCondition(\n * (ctx: StopConditionContext, config: { limit: number }) => {\n * const total = ctx.steps.reduce((sum, s) => sum + (s.usage?.total_tokens ?? 0), 0);\n * return total >= config.limit;\n * }\n * );\n * // Use: maxTokens({ limit: 1000 })\n * ```\n */\n/**\n * A stop condition factory — produces StopCondition callables when given config.\n */\nexport interface StopConditionFactory<TConfig> {\n (config: TConfig): StopCondition;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type -- metadata for identification\n __stop_condition_fn__: Function;\n __stop_condition_name__: string;\n}\n\nexport function stopCondition<TConfig>(\n fn: (ctx: StopConditionContext, config: TConfig) => boolean | Promise<boolean>\n): StopConditionFactory<TConfig>;\nexport function stopCondition(\n fn: (ctx: StopConditionContext) => boolean | Promise<boolean>\n): StopCondition;\nexport function stopCondition<TConfig = void>(\n fn: (ctx: StopConditionContext, config?: TConfig) => boolean | Promise<boolean>\n): StopCondition | StopConditionFactory<TConfig> {\n // Check function arity to determine if config is needed\n const hasConfig = fn.length >= 2;\n\n if (hasConfig) {\n // Returns a factory that takes config and returns a configured StopCondition\n const factory: StopConditionFactory<TConfig> = Object.assign(\n (config: TConfig): StopCondition => {\n const configuredFn = Object.assign(\n (ctx: StopConditionContext): boolean | Promise<boolean> => fn(ctx, config),\n {\n __stop_condition_fn__: fn as Function, // eslint-disable-line @typescript-eslint/no-unsafe-function-type\n __stop_condition_name__: fn.name || 'anonymous',\n }\n );\n return configuredFn;\n },\n {\n __stop_condition_fn__: fn as Function, // eslint-disable-line @typescript-eslint/no-unsafe-function-type\n __stop_condition_name__: fn.name || 'anonymous',\n }\n );\n return factory;\n }\n\n // No config — the function itself is the stop condition\n const wrapper: StopCondition = Object.assign(\n (ctx: StopConditionContext): boolean | Promise<boolean> => fn(ctx),\n {\n __stop_condition_fn__: fn as Function, // eslint-disable-line @typescript-eslint/no-unsafe-function-type\n __stop_condition_name__: fn.name || 'anonymous',\n }\n );\n return wrapper;\n}\n\n// ── Built-in stop conditions ─────────────────────────────────────────\n\n/**\n * Stop when total tokens exceed limit.\n * Matches Python max_tokens stop condition.\n *\n * @example\n * ```typescript\n * defineAgent({\n * stopConditions: [maxTokens({ limit: 1000 })],\n * });\n * ```\n */\nexport const maxTokens = stopCondition(function maxTokens(\n ctx: StopConditionContext,\n config: { limit: number }\n): boolean {\n let total = 0;\n for (const step of ctx.steps) {\n if (step.usage) {\n total += step.usage.total_tokens;\n }\n }\n return total >= config.limit;\n});\n\n/**\n * Stop when number of steps reaches count.\n * Matches Python max_steps stop condition.\n *\n * @example\n * ```typescript\n * defineAgent({\n * stopConditions: [maxSteps({ count: 10 })],\n * });\n * // Or with default count of 5:\n * defineAgent({\n * stopConditions: [maxSteps({ count: 5 })],\n * });\n * ```\n */\nexport const maxSteps = stopCondition(function maxSteps(\n ctx: StopConditionContext,\n config: { count: number }\n): boolean {\n return ctx.steps.length >= config.count;\n});\n\n/**\n * Stop when all specified tools have been executed.\n * Matches Python executed_tool stop condition.\n *\n * @example\n * ```typescript\n * defineAgent({\n * stopConditions: [executedTool({ toolNames: ['get_weather', 'search'] })],\n * });\n * ```\n */\nexport const executedTool = stopCondition(function executedTool(\n ctx: StopConditionContext,\n config: { toolNames: string[] }\n): boolean {\n const required = new Set(config.toolNames);\n if (required.size === 0) return false;\n\n const executed = new Set<string>();\n for (const step of ctx.steps) {\n for (const toolCall of step.tool_calls) {\n executed.add(toolCall.function.name);\n }\n }\n\n for (const name of required) {\n if (!executed.has(name)) return false;\n }\n return true;\n});\n\n/**\n * Stop when all specified texts are found in response content.\n * Matches Python has_text stop condition.\n *\n * @example\n * ```typescript\n * defineAgent({\n * stopConditions: [hasText({ texts: ['done', 'complete'] })],\n * });\n * ```\n */\nexport const hasText = stopCondition(function hasText(\n ctx: StopConditionContext,\n config: { texts: string[] }\n): boolean {\n if (config.texts.length === 0) return false;\n\n const combined: string[] = [];\n for (const step of ctx.steps) {\n if (step.content) {\n combined.push(step.content);\n }\n }\n const fullText = combined.join(' ');\n\n return config.texts.every((t) => fullText.includes(t));\n});\n","/**\n * Simple structured logging utility.\n */\n\nimport { appendFileSync } from 'node:fs';\n\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error';\n\nconst LOG_LEVELS: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n};\n\nexport type LogContext = Record<string, unknown>;\n\nexport interface LogEntry {\n level: LogLevel;\n message: string;\n timestamp: string;\n context?: LogContext | undefined;\n}\n\nexport interface LoggerOptions {\n /** Minimum log level to output (default: 'info') */\n level?: LogLevel | undefined;\n /** Logger name/prefix */\n name?: string | undefined;\n /** Custom log handler */\n handler?: ((entry: LogEntry) => void) | undefined;\n}\n\nexport interface ConfigureLoggingOptions {\n /** Custom log handler for all SDK loggers */\n handler?: ((entry: LogEntry) => void) | undefined;\n /** Path to a log file. SDK logs will be appended to this file instead of stdout. */\n file?: string | undefined;\n}\n\n/**\n * Console log handler.\n */\nfunction consoleHandler(entry: LogEntry): void {\n const prefix = `[${entry.timestamp}] ${entry.level.toUpperCase()}`;\n const message = entry.context\n ? `${prefix}: ${entry.message} ${JSON.stringify(entry.context)}`\n : `${prefix}: ${entry.message}`;\n\n switch (entry.level) {\n case 'debug':\n console.debug(message);\n break;\n case 'info':\n console.info(message);\n break;\n case 'warn':\n console.warn(message);\n break;\n case 'error':\n console.error(message);\n break;\n }\n}\n\n/**\n * The active global handler. All SDK loggers created with the default handler\n * delegate to this, so calling `configureLogging()` retroactively redirects them.\n */\nlet _activeHandler: (entry: LogEntry) => void = consoleHandler;\n\n/**\n * Default handler that delegates to the mutable `_activeHandler`.\n * This is the handler captured by module-level loggers at import time.\n */\nfunction defaultHandler(entry: LogEntry): void {\n _activeHandler(entry);\n}\n\n/**\n * Configure logging for all SDK loggers globally.\n *\n * @example\n * ```typescript\n * // Redirect all SDK logs to a file\n * configureLogging({ file: 'polos.log' });\n *\n * // Use a custom handler\n * configureLogging({ handler: (entry) => myLogger.log(entry) });\n * ```\n */\nexport function configureLogging(options: ConfigureLoggingOptions): void {\n if (options.handler) {\n _activeHandler = options.handler;\n } else if (options.file) {\n const filePath = options.file;\n _activeHandler = (entry: LogEntry) => {\n const prefix = `[${entry.timestamp}] ${entry.level.toUpperCase()}`;\n const line = entry.context\n ? `${prefix}: ${entry.message} ${JSON.stringify(entry.context)}\\n`\n : `${prefix}: ${entry.message}\\n`;\n appendFileSync(filePath, line);\n };\n }\n}\n\n/**\n * Create a logger instance.\n *\n * @example\n * ```typescript\n * const logger = createLogger({ name: 'workflow', level: 'debug' });\n * logger.info('Workflow started', { workflowId: '123' });\n * logger.error('Workflow failed', { error: err.message });\n * ```\n */\nexport function createLogger(options: LoggerOptions = {}) {\n const { level = 'info', name, handler = defaultHandler } = options;\n const minLevel = LOG_LEVELS[level];\n\n function log(logLevel: LogLevel, message: string, context?: LogContext): void {\n if (LOG_LEVELS[logLevel] < minLevel) {\n return;\n }\n\n const entry: LogEntry = {\n level: logLevel,\n message: name ? `[${name}] ${message}` : message,\n timestamp: new Date().toISOString(),\n context,\n };\n\n handler(entry);\n }\n\n return {\n debug: (message: string, context?: LogContext) => {\n log('debug', message, context);\n },\n info: (message: string, context?: LogContext) => {\n log('info', message, context);\n },\n warn: (message: string, context?: LogContext) => {\n log('warn', message, context);\n },\n error: (message: string, context?: LogContext) => {\n log('error', message, context);\n },\n\n /** Create a child logger with additional context */\n child: (childOptions: LoggerOptions) => {\n let childName: string | undefined;\n if (name && childOptions.name) {\n childName = `${name}:${childOptions.name}`;\n } else {\n childName = childOptions.name ?? name;\n }\n return createLogger({\n level,\n handler,\n ...childOptions,\n name: childName,\n });\n },\n };\n}\n\nexport type Logger = ReturnType<typeof createLogger>;\n\n/**\n * Global SDK logger instance.\n * Log level can be configured via POLOS_LOG_LEVEL environment variable.\n */\nconst envLogLevel = process.env['POLOS_LOG_LEVEL'];\nexport const logger = createLogger({\n name: 'polos',\n level: (envLogLevel as LogLevel | undefined) ?? 'info',\n});\n","/**\n * Token estimation utilities for session compaction.\n *\n * Uses a simple heuristic: ~4 characters per token.\n */\n\nimport type { ConversationMessage } from '../runtime/orchestrator-types.js';\n\n/**\n * Estimate token count for a string using the ~4 chars/token heuristic.\n */\nexport function estimateTokens(text: string): number {\n return Math.ceil(text.length / 4);\n}\n\n/**\n * Estimate token count for a single conversation message.\n */\nexport function estimateMessageTokens(message: ConversationMessage): number {\n const content = message.content;\n if (typeof content === 'string') {\n return estimateTokens(content);\n }\n try {\n return estimateTokens(JSON.stringify(content));\n } catch {\n return 0;\n }\n}\n\n/**\n * Estimate total token count for an array of conversation messages.\n */\nexport function estimateMessagesTokens(messages: ConversationMessage[]): number {\n let total = 0;\n for (const msg of messages) {\n total += estimateMessageTokens(msg);\n }\n return total;\n}\n","/**\n * Core session compaction logic.\n *\n * Compacts older conversation messages into a rolling summary via an LLM call,\n * keeping the last N recent messages verbatim.\n */\n\nimport { generateText } from 'ai';\nimport type { ConversationMessage } from '../runtime/orchestrator-types.js';\nimport type { NormalizedCompactionConfig, CompactionResult } from './types.js';\nimport { estimateTokens, estimateMessagesTokens } from './tokens.js';\nimport { createLogger } from '../utils/logger.js';\n\nconst logger = createLogger({ name: 'memory-compaction' });\n\n// ── Constants ────────────────────────────────────────────────────────\n\nexport const COMPACTION_PROMPT = `You are summarizing a conversation between a user and an AI assistant.\n\nYour goal: someone reading only this summary should be able to continue the conversation without the user having to repeat themselves.\n\nCapture:\n- What the user is trying to accomplish (their goal, problem, or question)\n- Key facts, context, or constraints the user shared (personal details, preferences, requirements, deadlines)\n- Decisions made or conclusions reached\n- Recommendations given and whether the user accepted, rejected, or is still considering them\n- Any specific artifacts produced (code, files, plans, drafts, lists — include names and key details)\n- Open threads — anything unresolved, in progress, or that the user said they'd come back to\n- The current state of the conversation (where things left off)\n\nExisting summary (if any):\n{existing_summary}\n\nNew messages to fold into the summary:\n{messages_to_fold}\n\nWrite a concise summary in short paragraphs grouped by topic. Not bullet points — narrative that flows.\nBe factual and specific. No pleasantries, no meta-commentary, no \"the user and assistant discussed...\"\nWrite as if taking notes for a colleague who needs to pick up this conversation.`;\n\nexport const SUMMARY_USER_PREFIX = '[Prior conversation summary]\\n';\nexport const SUMMARY_ASSISTANT_ACK = 'Understood, I have context from our earlier conversation.';\n\n// ── Helpers ──────────────────────────────────────────────────────────\n\n/**\n * Build the user/assistant summary pair to inject at the start of conversation.\n */\nexport function buildSummaryMessages(summary: string): [ConversationMessage, ConversationMessage] {\n return [\n { role: 'user', content: SUMMARY_USER_PREFIX + summary },\n { role: 'assistant', content: SUMMARY_ASSISTANT_ACK },\n ];\n}\n\n/**\n * Detect whether messages[index] and messages[index+1] form a summary pair.\n */\nexport function isSummaryPair(messages: ConversationMessage[], index: number): boolean {\n if (index + 1 >= messages.length) return false;\n const userMsg = messages[index];\n const assistantMsg = messages[index + 1];\n if (!userMsg || !assistantMsg) return false;\n if (userMsg.role !== 'user' || assistantMsg.role !== 'assistant') return false;\n const userContent = typeof userMsg.content === 'string' ? userMsg.content : '';\n const assistantContent = typeof assistantMsg.content === 'string' ? assistantMsg.content : '';\n return userContent.startsWith(SUMMARY_USER_PREFIX) && assistantContent === SUMMARY_ASSISTANT_ACK;\n}\n\n/**\n * Format messages as text for inclusion in the compaction prompt.\n */\nfunction formatMessagesForPrompt(messages: ConversationMessage[]): string {\n return messages\n .map((m) => {\n const content = typeof m.content === 'string' ? m.content : JSON.stringify(m.content);\n return `${m.role}: ${content}`;\n })\n .join('\\n\\n');\n}\n\n// ── Main function ────────────────────────────────────────────────────\n\n/**\n * Compact conversation messages if they exceed the token budget.\n *\n * 1. Estimate total tokens of all messages\n * 2. If under maxConversationTokens -> return as-is (no-op)\n * 3. Otherwise:\n * - Find summary pair at start (if present)\n * - Determine messages to fold (between summary pair and last minRecentMessages)\n * - Call compaction model to generate summary\n * - If summary exceeds maxSummaryTokens, re-summarize\n * - Replace folded messages + old summary pair with new summary pair\n * 4. On failure -> log warning, fall back to naive truncation\n */\nexport async function compactIfNeeded(\n messages: ConversationMessage[],\n currentSummary: string | null,\n config: NormalizedCompactionConfig\n): Promise<CompactionResult> {\n const totalTokens = estimateMessagesTokens(messages);\n\n // Under budget — no-op\n if (totalTokens <= config.maxConversationTokens) {\n return {\n compacted: false,\n messages,\n summary: currentSummary,\n summaryTokens: currentSummary ? estimateTokens(currentSummary) : 0,\n totalTurns: messages.length,\n };\n }\n\n // Determine summary pair boundaries\n let summaryPairEnd = 0;\n if (messages.length >= 2 && isSummaryPair(messages, 0)) {\n summaryPairEnd = 2;\n }\n\n // Messages available for folding: everything between summary pair and recent window\n const recentStart = Math.max(summaryPairEnd, messages.length - config.minRecentMessages);\n\n // Nothing to fold\n if (recentStart <= summaryPairEnd) {\n return {\n compacted: false,\n messages,\n summary: currentSummary,\n summaryTokens: currentSummary ? estimateTokens(currentSummary) : 0,\n totalTurns: messages.length,\n };\n }\n\n const messagesToFold = messages.slice(summaryPairEnd, recentStart);\n const recentMessages = messages.slice(recentStart);\n\n // Nothing to fold (e.g., single message)\n if (messagesToFold.length === 0) {\n return {\n compacted: false,\n messages,\n summary: currentSummary,\n summaryTokens: currentSummary ? estimateTokens(currentSummary) : 0,\n totalTurns: messages.length,\n };\n }\n\n try {\n // Build the compaction prompt\n const existingSummary = currentSummary ?? '(none)';\n const foldedText = formatMessagesForPrompt(messagesToFold);\n const prompt = COMPACTION_PROMPT.replace('{existing_summary}', existingSummary).replace(\n '{messages_to_fold}',\n foldedText\n );\n\n // Call compaction model\n let summary = await callCompactionModel(config, prompt);\n\n // Re-summarize if summary is too long\n if (estimateTokens(summary) > config.maxSummaryTokens) {\n const reSummarizePrompt = COMPACTION_PROMPT.replace('{existing_summary}', '(none)').replace(\n '{messages_to_fold}',\n `The following is a summary that needs to be shortened:\\n\\n${summary}`\n );\n summary = await callCompactionModel(config, reSummarizePrompt);\n }\n\n // Build new messages array: [summary pair] + [recent messages]\n const [summaryUser, summaryAssistant] = buildSummaryMessages(summary);\n const newMessages: ConversationMessage[] = [summaryUser, summaryAssistant, ...recentMessages];\n\n return {\n compacted: true,\n messages: newMessages,\n summary,\n summaryTokens: estimateTokens(summary),\n totalTurns: messages.length,\n };\n } catch (err) {\n logger.warn('Compaction failed, falling back to naive truncation', { error: String(err) });\n\n // Fallback: keep last minRecentMessages\n const fallbackMessages = messages.slice(-config.minRecentMessages);\n return {\n compacted: true,\n messages: fallbackMessages,\n summary: currentSummary,\n summaryTokens: currentSummary ? estimateTokens(currentSummary) : 0,\n totalTurns: messages.length,\n };\n }\n}\n\n/**\n * Call the compaction model to generate a summary.\n */\nasync function callCompactionModel(\n config: NormalizedCompactionConfig,\n prompt: string\n): Promise<string> {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n const result = await generateText({\n model: config.compactionModel,\n messages: [{ role: 'user', content: prompt }],\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any);\n return result.text;\n}\n","/**\n * Agent stream function — core execution loop.\n *\n * Matches Python sdk/python/polos/agents/stream.py _agent_stream_function.\n * Orchestrates: LLM call → tool execution → stop condition evaluation → repeat.\n */\n\nimport type { ModelMessage as CoreMessage } from 'ai';\nimport type { WorkflowContext } from '../core/context.js';\nimport { globalRegistry } from '../core/registry.js';\nimport { isToolWorkflow } from '../core/tool.js';\nimport type { BatchWorkflowInput } from '../core/step.js';\nimport { executeHookChain } from '../middleware/hook-executor.js';\nimport { llmGenerate } from '../llm/generate.js';\nimport { llmStream } from '../llm/stream.js';\nimport type { LLM } from '../llm/llm.js';\nimport type { LLMToolCall, LLMUsage, LLMToolResult, LLMGenerateResult } from '../llm/types.js';\nimport { convertToolResultsToMessages } from '../llm/types.js';\nimport type { Guardrail } from '../middleware/guardrail.js';\nimport type { Hook } from '../middleware/hook.js';\nimport type { PublishEventFn } from '../llm/stream.js';\nimport { getExecutionContext } from '../runtime/execution-context.js';\nimport type {\n StopCondition,\n StopConditionContext,\n StepInfo,\n ToolResultInfo,\n} from './stop-conditions.js';\nimport { maxSteps as maxStepsFn } from './stop-conditions.js';\nimport type { LlmToolDefinition } from '../core/tool.js';\nimport { createLogger } from '../utils/logger.js';\nimport type { CompactionConfig, NormalizedCompactionConfig } from '../memory/types.js';\nimport type { ConversationMessage } from '../runtime/orchestrator-types.js';\nimport { compactIfNeeded, buildSummaryMessages, isSummaryPair } from '../memory/compaction.js';\n\nconst logger = createLogger({ name: 'agent-stream' });\n\n// ── Types ────────────────────────────────────────────────────────────\n\n/**\n * Agent configuration passed within the payload.\n * Matches Python agent_config dict structure.\n */\nexport interface AgentStreamConfig {\n system?: string | undefined;\n tools?: LlmToolDefinition[] | undefined;\n temperature?: number | undefined;\n maxOutputTokens?: number | undefined;\n}\n\n/**\n * Payload for agentStreamFunction.\n */\nexport interface AgentStreamPayload {\n agent_run_id: string;\n name: string;\n agent_config: AgentStreamConfig;\n input: string | Record<string, unknown>[];\n streaming: boolean;\n}\n\n/**\n * Definition of an agent for the stream function.\n */\nexport interface AgentDefinition {\n id: string;\n llm: LLM;\n tools: LlmToolDefinition[];\n stopConditions: StopCondition[];\n agentHooks: {\n onAgentStepStart: Hook[];\n onAgentStepEnd: Hook[];\n onToolStart: Hook[];\n onToolEnd: Hook[];\n };\n guardrails: Guardrail[];\n guardrailMaxRetries: number;\n /** Session compaction configuration — always enabled */\n compaction: CompactionConfig;\n outputSchema?: unknown;\n /** Original Zod schema for Vercel AI SDK structured output (Output.object()) */\n outputZodSchema?: unknown;\n}\n\n/**\n * Result from agent execution.\n * Matches Python AgentResult Pydantic model.\n */\nexport interface AgentStreamResult {\n agent_run_id: string;\n result: unknown;\n result_schema: string | null;\n tool_results: ToolResultInfo[];\n total_steps: number;\n usage: LLMUsage;\n}\n\n// ── Helper ───────────────────────────────────────────────────────────\n\nfunction serializeToolOutput(value: unknown): string {\n if (value === null || value === undefined) return 'null';\n if (typeof value === 'string') return value;\n try {\n return JSON.stringify(value);\n } catch {\n return 'null';\n }\n}\n\n// ── Main function ────────────────────────────────────────────────────\n\n/**\n * Core agent execution loop.\n *\n * Matches Python _agent_stream_function:\n * 1. Retrieve conversation history if enabled\n * 2. Build conversation messages\n * 3. Loop: LLM call → tool execution → stop condition check\n * 4. Store conversation history\n * 5. Return AgentResult\n */\nexport async function agentStreamFunction(\n ctx: WorkflowContext,\n payload: AgentStreamPayload,\n agentDef: AgentDefinition\n): Promise<AgentStreamResult> {\n const agentRunId = ctx.executionId;\n const agentConfig = payload.agent_config;\n const streaming = payload.streaming;\n const inputData = payload.input;\n\n // Result accumulator\n let finalInputTokens = 0;\n let finalOutputTokens = 0;\n let finalTotalTokens = 0;\n let finalCacheReadInputTokens = 0;\n let finalCacheCreationInputTokens = 0;\n let lastLlmResultContent: string | null = null;\n const allToolResults: ToolResultInfo[] = [];\n const steps: StepInfo[] = [];\n let endSteps = false;\n let checkedStructuredOutput = false;\n\n // ── Session compaction setup ──────────────────────────────────────\n // Normalize CompactionConfig -> NormalizedCompactionConfig\n let currentSummary: string | null = null;\n\n const normalizedCompaction: NormalizedCompactionConfig = {\n maxConversationTokens: agentDef.compaction.maxConversationTokens ?? 80000,\n maxSummaryTokens: agentDef.compaction.maxSummaryTokens ?? 20000,\n minRecentMessages: agentDef.compaction.minRecentMessages ?? 2,\n compactionModel: agentDef.compaction.compactionModel ?? agentDef.llm.model,\n enabled: agentDef.compaction.enabled ?? true,\n };\n\n // Build conversation messages — load prior session state first, then append current input\n let conversationMessages: unknown[] = [];\n\n // Load session memory (summary + uncompacted messages) if we have a sessionId\n if (ctx.sessionId) {\n const sessionId = ctx.sessionId;\n const loaded = await ctx.step.run('load_session_memory', async () => {\n const execCtx = getExecutionContext();\n if (!execCtx?.orchestratorClient) return null;\n try {\n const sessionMemory = await execCtx.orchestratorClient.getSessionMemory(sessionId);\n return {\n summary: sessionMemory.summary ?? null,\n messages: sessionMemory.messages,\n };\n } catch (err) {\n logger.warn('Failed to retrieve session memory', { error: String(err) });\n return null;\n }\n });\n\n if (loaded) {\n if (loaded.summary) {\n currentSummary = loaded.summary;\n const [summaryUser, summaryAssistant] = buildSummaryMessages(currentSummary);\n conversationMessages.push(summaryUser, summaryAssistant);\n }\n if (loaded.messages.length > 0) {\n conversationMessages.push(...loaded.messages);\n }\n }\n }\n\n // Add current input to conversation\n if (typeof inputData === 'string') {\n conversationMessages.push({ role: 'user', content: inputData });\n } else {\n conversationMessages.push(...inputData);\n }\n\n // Determine safety max_steps limit\n const stopConditions = agentDef.stopConditions;\n\n // Check if any stop condition is from maxSteps (matching Python exactly)\n let hasMaxStepsCondition = false;\n for (const sc of stopConditions) {\n if (sc.__stop_condition_fn__ === maxStepsFn.__stop_condition_fn__) {\n hasMaxStepsCondition = true;\n break;\n }\n }\n\n const safetyMaxSteps: number | null = hasMaxStepsCondition\n ? null\n : parseInt(process.env['POLOS_AGENT_MAX_STEPS'] ?? '20', 10);\n\n // Build publishEvent function for streaming\n const execCtxForPublish = getExecutionContext();\n const publishEvent: PublishEventFn = async (topic, eventData) => {\n if (execCtxForPublish?.orchestratorClient) {\n try {\n await execCtxForPublish.orchestratorClient.publishEvent({\n topic,\n events: [eventData],\n executionId: ctx.executionId,\n rootExecutionId: ctx.rootExecutionId,\n });\n } catch (err) {\n logger.warn('Failed to publish stream event', { error: String(err) });\n }\n }\n };\n\n // Main loop\n let agentStep = 1;\n\n while (!endSteps && (safetyMaxSteps === null || agentStep <= safetyMaxSteps)) {\n const currentIterationToolResults: LLMToolResult[] = [];\n\n // Execute on_agent_step_start hooks\n if (agentDef.agentHooks.onAgentStepStart.length > 0) {\n const hookResult = await executeHookChain(agentDef.agentHooks.onAgentStepStart, {\n ctx,\n hookName: `${String(agentStep)}.hook.on_agent_step_start`,\n payload: { step: agentStep, messages: conversationMessages },\n phase: 'onStart',\n });\n\n // Apply modifications\n if (typeof hookResult.payload === 'object' && 'messages' in hookResult.payload) {\n conversationMessages = (hookResult.payload as { messages: unknown[] }).messages;\n }\n\n if (!hookResult.success) {\n break;\n }\n }\n\n // Run compaction if needed (before LLM call)\n try {\n const compactionResult = await compactIfNeeded(\n conversationMessages as ConversationMessage[],\n currentSummary,\n normalizedCompaction\n );\n if (compactionResult.compacted) {\n conversationMessages = compactionResult.messages;\n currentSummary = compactionResult.summary;\n }\n } catch (err) {\n logger.warn('Compaction failed, continuing with uncompacted messages', {\n error: String(err),\n });\n }\n\n // Get guardrails from agent\n const guardrails = agentDef.guardrails;\n const guardrailMaxRetries = agentDef.guardrailMaxRetries;\n\n // Use llmGenerate if streaming=false OR guardrails are present (matching Python exactly)\n const useLlmGenerate = !streaming || guardrails.length > 0;\n\n let llmResult: LLMGenerateResult;\n\n // Only pass outputSchema when no tools are active (matching Python: response_format + tool use can conflict)\n const hasTools = agentConfig.tools !== undefined && agentConfig.tools.length > 0;\n const outputSchemaForLlm = !hasTools ? agentDef.outputZodSchema : undefined;\n\n if (useLlmGenerate) {\n llmResult = await llmGenerate(ctx, agentDef.llm, {\n messages: conversationMessages as CoreMessage[],\n system: agentConfig.system,\n tools: agentConfig.tools,\n temperature: agentConfig.temperature,\n maxTokens: agentConfig.maxOutputTokens,\n agent_step: agentStep,\n guardrails,\n guardrail_max_retries: guardrailMaxRetries,\n outputSchema: outputSchemaForLlm,\n });\n\n // If guardrails + streaming + content: publish one text_delta event (matching Python)\n if (guardrails.length > 0 && streaming && llmResult.content) {\n await ctx.step.publishEvent(`llm_generate:text_delta:${String(agentStep)}`, {\n topic: `workflow/${ctx.rootWorkflowId}/${ctx.rootExecutionId}`,\n type: 'text_delta',\n data: {\n step: agentStep,\n chunk_index: 1,\n content: llmResult.content,\n _metadata: {\n execution_id: agentRunId,\n workflow_id: ctx.workflowId,\n },\n },\n });\n }\n } else {\n // No guardrails - use streaming\n llmResult = await llmStream(\n ctx,\n agentDef.llm,\n {\n messages: conversationMessages as CoreMessage[],\n system: agentConfig.system,\n tools: agentConfig.tools,\n temperature: agentConfig.temperature,\n maxTokens: agentConfig.maxOutputTokens,\n agent_step: agentStep,\n outputSchema: outputSchemaForLlm,\n },\n publishEvent\n );\n }\n\n // Accumulate usage\n if (llmResult.usage) {\n finalInputTokens += llmResult.usage.input_tokens;\n finalOutputTokens += llmResult.usage.output_tokens;\n finalTotalTokens += llmResult.usage.total_tokens;\n if (llmResult.usage.cache_read_input_tokens != null) {\n finalCacheReadInputTokens += llmResult.usage.cache_read_input_tokens;\n }\n if (llmResult.usage.cache_creation_input_tokens != null) {\n finalCacheCreationInputTokens += llmResult.usage.cache_creation_input_tokens;\n }\n }\n\n lastLlmResultContent = llmResult.content;\n const toolCalls: LLMToolCall[] = llmResult.tool_calls ?? [];\n\n if (!llmResult.raw_output) {\n throw new Error(\n `LLM failed to generate output: agent_id=${agentDef.id}, agent_step=${String(agentStep)}`\n );\n }\n\n conversationMessages.push(...llmResult.raw_output);\n\n // Execute tools in batch\n const batchWorkflows: BatchWorkflowInput[] = [];\n const toolCallList: {\n tool_call_id: string;\n tool_call_call_id: string;\n tool_name: string;\n tool_call: LLMToolCall;\n }[] = [];\n\n let toolResultsRecordedList: ToolResultInfo[] = [];\n\n for (let idx = 0; idx < toolCalls.length; idx++) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- bounds checked by loop\n const toolCall = toolCalls[idx]!;\n\n if (!toolCall.function.name) {\n continue;\n }\n\n const toolName = toolCall.function.name;\n const toolArgsStr = toolCall.function.arguments;\n const toolCallId = toolCall.id;\n const toolCallCallId = toolCall.call_id;\n\n // Find the tool workflow in registry\n if (!globalRegistry.has(toolName)) {\n logger.warn(`Tool '${toolName}' not found in registry`);\n continue;\n }\n\n const toolWorkflow = globalRegistry.get(toolName);\n if (!isToolWorkflow(toolWorkflow)) {\n logger.warn(`Workflow '${toolName}' is not a tool workflow`);\n continue;\n }\n\n // Parse tool arguments\n let toolArgs: unknown;\n try {\n toolArgs = JSON.parse(toolArgsStr) as unknown;\n } catch {\n toolArgs = {};\n }\n\n // Execute on_tool_start hooks\n if (agentDef.agentHooks.onToolStart.length > 0) {\n const hookResult = await executeHookChain(agentDef.agentHooks.onToolStart, {\n ctx,\n hookName: `${String(agentStep)}.hook.on_tool_start.${String(idx)}`,\n payload: toolArgs,\n phase: 'onStart',\n });\n\n // Apply modifications\n if (hookResult.payload !== undefined) {\n toolArgs = hookResult.payload;\n }\n\n if (!hookResult.success) {\n throw new Error(hookResult.error ?? 'on_tool_start hook failed');\n }\n }\n\n // Add to batch\n batchWorkflows.push({ workflow: toolWorkflow, payload: toolArgs });\n toolCallList.push({\n tool_call_id: toolCallId,\n tool_call_call_id: toolCallCallId,\n tool_name: toolName,\n tool_call: toolCall,\n });\n }\n\n // Execute all tools in batch\n if (batchWorkflows.length > 0) {\n const batchResults = await ctx.step.batchInvokeAndWait(\n `execute_tools:step_${String(agentStep)}`,\n batchWorkflows\n );\n\n toolResultsRecordedList = [];\n\n for (let i = 0; i < batchResults.length; i++) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- bounds match batchResults\n const batchToolResult = batchResults[i]!;\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- bounds match batchResults\n const toolSpec = batchWorkflows[i]!;\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- bounds match batchResults\n const toolCallInfo = toolCallList[i]!;\n const toolName = toolCallInfo.tool_name;\n\n // Check success — convert errors to strings for the LLM (matching Python stream.py)\n const toolResult: unknown = batchToolResult.success\n ? batchToolResult.result\n : `Error: ${batchToolResult.error ?? 'unknown error'}`;\n const toolCallId = toolCallInfo.tool_call_id;\n const toolCallCallId = toolCallInfo.tool_call_call_id;\n\n // Execute on_tool_end hooks\n if (agentDef.agentHooks.onToolEnd.length > 0) {\n const hookResult = await executeHookChain(agentDef.agentHooks.onToolEnd, {\n ctx,\n hookName: `${String(agentStep)}.hook.on_tool_end.${String(i)}`,\n payload: toolSpec.payload,\n output: toolResult,\n phase: 'onEnd',\n });\n\n if (!hookResult.success) {\n throw new Error(hookResult.error ?? 'on_tool_end hook failed');\n }\n }\n\n // Serialize and add tool result to conversation for next iteration\n const toolJsonOutput = serializeToolOutput(toolResult);\n\n currentIterationToolResults.push({\n type: 'function_call_output',\n call_id: toolCallCallId,\n name: toolName,\n output: toolJsonOutput,\n });\n\n toolResultsRecordedList.push({\n tool_name: toolName,\n status: 'completed',\n result: toolResult,\n tool_call_id: toolCallId,\n tool_call_call_id: toolCallCallId,\n });\n }\n\n allToolResults.push(...toolResultsRecordedList);\n\n // Add tool results to conversation as role:'tool' messages\n // so the full conversation accumulates naturally\n const toolResultMessages = convertToolResultsToMessages(currentIterationToolResults);\n conversationMessages.push(...toolResultMessages);\n }\n\n // Build step record\n steps.push({\n step: agentStep,\n content: lastLlmResultContent,\n tool_calls: toolCalls,\n tool_results: toolResultsRecordedList,\n usage: llmResult.usage,\n raw_output: conversationMessages,\n });\n\n // Execute on_agent_step_end hooks\n if (agentDef.agentHooks.onAgentStepEnd.length > 0) {\n const hookResult = await executeHookChain(agentDef.agentHooks.onAgentStepEnd, {\n ctx,\n hookName: `${String(agentStep)}.hook.on_agent_step_end`,\n payload: { step: agentStep, messages: conversationMessages },\n output: steps[steps.length - 1],\n phase: 'onEnd',\n });\n\n // Apply modifications\n if (hookResult.output !== undefined) {\n steps[steps.length - 1] = hookResult.output as StepInfo;\n }\n\n if (!hookResult.success) {\n throw new Error(hookResult.error ?? 'on_agent_step_end hook failed');\n }\n }\n\n // No tool results, we're done\n if (currentIterationToolResults.length === 0) {\n endSteps = true;\n }\n\n // Evaluate stop conditions (if any)\n if (stopConditions.length > 0 && !endSteps) {\n const stopCtx: StopConditionContext = {\n steps: [...steps],\n agent_id: agentDef.id,\n agent_run_id: agentRunId,\n };\n\n for (let idx = 0; idx < stopConditions.length; idx++) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- bounds checked by loop\n const condition = stopConditions[idx]!;\n const funcName = condition.__stop_condition_name__ ?? 'unknown';\n\n const shouldStop = await ctx.step.run(\n `${String(agentStep)}.stop_condition.${funcName}.${String(idx)}`,\n () => condition(stopCtx),\n { input: stopCtx }\n );\n\n if (shouldStop) {\n endSteps = true;\n break;\n }\n }\n }\n\n // Structured output parsing (matching Python)\n if (endSteps && agentDef.outputSchema) {\n const parseResult = parseStructuredOutput(lastLlmResultContent, agentDef.outputSchema);\n\n if (checkedStructuredOutput && !parseResult.success) {\n throw new Error(\n `LLM failed to generate valid structured output: agent_id=${agentDef.id}, agent_step=${String(agentStep)}`\n );\n }\n\n checkedStructuredOutput = true;\n\n if (!parseResult.success) {\n // Reset and retry with fix prompt\n endSteps = false;\n\n const schemaJson = JSON.stringify(agentDef.outputSchema, null, 2);\n const fixPrompt =\n `The previous response was not valid JSON matching the ` +\n `required schema. Please reformat your response to be valid ` +\n `JSON that strictly conforms to this schema:\\n\\n${schemaJson}\\n\\n` +\n `Please provide ONLY valid JSON that matches the schema, ` +\n `with no additional text or formatting.`;\n conversationMessages.push({ role: 'user', content: fixPrompt });\n } else {\n lastLlmResultContent = parseResult.parsed as string | null;\n }\n }\n\n if (!endSteps) {\n agentStep++;\n }\n }\n\n // Store session memory (summary + uncompacted messages)\n if (ctx.sessionId) {\n const sessionId = ctx.sessionId;\n const execCtx = getExecutionContext();\n const orchestratorClient = execCtx?.orchestratorClient;\n if (orchestratorClient) {\n try {\n // Strip the summary pair from the front — only store real conversation messages\n const allMessages = conversationMessages as ConversationMessage[];\n const messagesStart = allMessages.length >= 2 && isSummaryPair(allMessages, 0) ? 2 : 0;\n const messagesToStore = allMessages.slice(messagesStart);\n\n const summaryToStore = currentSummary;\n await ctx.step.run(\n 'store_session_memory',\n async () => {\n await orchestratorClient.putSessionMemory(sessionId, {\n summary: summaryToStore,\n messages: messagesToStore,\n });\n },\n {\n input: {\n messageCount: messagesToStore.length,\n },\n }\n );\n } catch (err) {\n logger.warn('Failed to store session memory', { error: String(err) });\n }\n }\n }\n\n // Return AgentResult\n return {\n agent_run_id: agentRunId,\n result: lastLlmResultContent,\n result_schema: null,\n tool_results: allToolResults,\n total_steps: agentStep,\n usage: {\n input_tokens: finalInputTokens,\n output_tokens: finalOutputTokens,\n total_tokens: finalTotalTokens,\n ...(finalCacheReadInputTokens > 0 && { cache_read_input_tokens: finalCacheReadInputTokens }),\n ...(finalCacheCreationInputTokens > 0 && {\n cache_creation_input_tokens: finalCacheCreationInputTokens,\n }),\n },\n };\n}\n\n// ── Structured output parsing ────────────────────────────────────────\n\ninterface ParseResult {\n parsed: unknown;\n success: boolean;\n}\n\n/**\n * Strip markdown code fences (```json ... ``` or ``` ... ```) from LLM output.\n */\nfunction stripCodeFences(text: string): string {\n const trimmed = text.trim();\n // Match ```json ... ``` or ``` ... ``` (with optional language identifier)\n const match = /^```(?:\\w+)?\\s*\\n?([\\s\\S]*?)\\n?\\s*```$/.exec(trimmed);\n return match?.[1] ? match[1].trim() : trimmed;\n}\n\nfunction parseStructuredOutput(output: string | null, outputSchema: unknown): ParseResult {\n if (!output) {\n return { parsed: output, success: true };\n }\n\n try {\n const cleaned = stripCodeFences(output);\n const parsed: unknown = JSON.parse(cleaned);\n // If outputSchema is a Zod schema with parse method, validate\n if (typeof outputSchema === 'object' && outputSchema !== null && 'parse' in outputSchema) {\n const validated: unknown = (outputSchema as { parse: (v: unknown) => unknown }).parse(parsed);\n return { parsed: validated, success: true };\n }\n return { parsed, success: true };\n } catch (e) {\n logger.warn(`Failed to parse structured output: ${String(e)}`);\n return { parsed: output, success: false };\n }\n}\n","/**\n * StreamResult — wraps an ExecutionHandle + PolosClient to provide\n * streaming iteration over agent execution events.\n *\n * Matches Python sdk/python/polos/agents/agent.py StreamResult class.\n */\n\nimport type { ExecutionHandle } from '../execution-handle.js';\nimport type { PolosClient } from '../client.js';\nimport type { StreamEvent } from '../types/events.js';\nimport type { AgentStreamResult } from './stream.js';\n\n/**\n * Result from streaming an agent execution.\n * Provides async iterables for text chunks and full events,\n * plus methods to accumulate text or wait for the final result.\n */\nexport class StreamResult {\n /** Execution ID */\n readonly id: string;\n /** Workflow ID */\n readonly workflowId: string;\n /** When the execution was created */\n readonly createdAt: string | undefined;\n /** Root workflow ID */\n readonly rootWorkflowId: string;\n /** Root execution ID */\n readonly rootExecutionId: string;\n /** Session ID */\n readonly sessionId: string | undefined;\n /** User ID */\n readonly userId: string | undefined;\n /** Agent run ID (same as execution ID) */\n readonly agentRunId: string;\n /** Event topic for this execution */\n readonly topic: string;\n\n private readonly handle: ExecutionHandle;\n private readonly client: PolosClient;\n\n constructor(handle: ExecutionHandle, client: PolosClient) {\n this.handle = handle;\n this.client = client;\n\n this.id = handle.id;\n this.workflowId = handle.workflowId;\n this.createdAt = handle.createdAt;\n this.rootWorkflowId = handle.rootWorkflowId;\n this.rootExecutionId = handle.rootExecutionId;\n this.sessionId = handle.sessionId;\n this.userId = handle.userId;\n\n // Computed fields matching Python\n this.agentRunId = handle.id;\n this.topic = `workflow/${handle.rootWorkflowId}/${handle.rootExecutionId}`;\n }\n\n /**\n * Async iterable of all SSE events from the workflow execution.\n * Matches Python FullEventIterator.\n */\n get events(): AsyncIterable<StreamEvent> {\n const client = this.client;\n const rootWorkflowId = this.rootWorkflowId;\n const rootExecutionId = this.rootExecutionId;\n\n // Use root IDs matching Python StreamResult._stream_events()\n return client.events.streamWorkflow(rootWorkflowId, rootExecutionId);\n }\n\n /**\n * Async iterable of text chunks only (filtering for text_delta events).\n * Matches Python TextChunkIterator.\n */\n get textChunks(): AsyncIterable<string> {\n const events = this.events;\n\n async function* filterTextChunks() {\n for await (const event of events) {\n if (event.eventType === 'text_delta') {\n const content = event.data['content'];\n if (typeof content === 'string' && content.length > 0) {\n yield content;\n }\n }\n }\n }\n\n return filterTextChunks();\n }\n\n /**\n * Accumulate all text chunks into a single string.\n * Matches Python StreamResult.text().\n */\n async text(): Promise<string> {\n let accumulated = '';\n for await (const chunk of this.textChunks) {\n accumulated += chunk;\n }\n return accumulated;\n }\n\n /**\n * Stream events and return the final AgentStreamResult when agent_finish is received.\n * Matches Python StreamResult.result().\n */\n async result(): Promise<AgentStreamResult> {\n const rootExecutionId = this.rootExecutionId;\n\n for await (const event of this.events) {\n if (event.eventType === 'agent_finish') {\n const metadata = event.data['_metadata'];\n if (metadata && typeof metadata === 'object' && !Array.isArray(metadata)) {\n const metadataRecord = metadata as Record<string, unknown>;\n if (metadataRecord['execution_id'] === rootExecutionId) {\n return event.data as unknown as AgentStreamResult;\n }\n }\n }\n }\n\n // If the stream ends without an agent_finish event, fall back to polling\n return (await this.handle.getResult()) as AgentStreamResult;\n }\n\n /**\n * Get the current execution status and details.\n * Delegates to the underlying ExecutionHandle.\n */\n async get() {\n return this.handle.get();\n }\n}\n","/**\n * Agent definition — creates a Workflow with workflowType: 'agent'.\n *\n * Matches Python sdk/python/polos/agents/agent.py Agent class.\n * Follows the defineTool() pattern: defineAgent() creates a Workflow\n * extended with agent-specific properties.\n */\n\nimport type { LanguageModel } from 'ai';\nimport { type ZodType, toJSONSchema } from 'zod';\nimport type { Channel } from '../channels/channel.js';\nimport type { WorkflowContext } from '../core/context.js';\nimport type {\n QueueConfig,\n Workflow,\n WorkflowHandler,\n WorkflowRunClient,\n WorkflowRunOptions,\n} from '../core/workflow.js';\nimport { defineWorkflow } from '../core/workflow.js';\nimport type { ToolWorkflow, LlmToolDefinition } from '../core/tool.js';\nimport { LLM } from '../llm/llm.js';\nimport type { Hook, HookHandler, Hook as HookObject } from '../middleware/hook.js';\nimport { normalizeHooks } from '../middleware/hook.js';\nimport type { Guardrail, GuardrailHandler } from '../middleware/guardrail.js';\nimport { normalizeGuardrails } from '../middleware/guardrail.js';\nimport type { PolosClient } from '../client.js';\nimport { assertNotInExecutionContext } from '../runtime/execution-context.js';\nimport { AgentRunConfig } from '../core/step.js';\nimport type { StopCondition } from './stop-conditions.js';\nimport { agentStreamFunction } from './stream.js';\nimport type { AgentStreamPayload, AgentStreamResult } from './stream.js';\nimport type { CompactionConfig } from '../memory/types.js';\nimport { StreamResult } from './stream-result.js';\n\n// ── Types ────────────────────────────────────────────────────────────\n\n/** Union type for hook inputs — a handler function, Hook object, or array */\ntype HookOrHandler = HookHandler | HookObject | (HookHandler | HookObject)[];\n\n/**\n * Configuration for defineAgent().\n * Matches Python Agent.__init__ parameters.\n */\nexport interface DefineAgentConfig {\n /** Unique agent identifier */\n id: string;\n /** Vercel AI SDK model instance */\n model: LanguageModel;\n /** Agent description */\n description?: string | undefined;\n /** System prompt for the agent */\n systemPrompt?: string | undefined;\n /** Tools available to the agent (from defineTool()) */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n tools?: ToolWorkflow<any, any, any>[] | undefined;\n /** Temperature for LLM generation */\n temperature?: number | undefined;\n /** Maximum output tokens */\n maxOutputTokens?: number | undefined;\n /** Queue assignment for execution */\n queue?: string | QueueConfig | undefined;\n /** Conditions to stop agent execution */\n stopConditions?: StopCondition[] | undefined;\n /** Zod schema for structured output */\n outputSchema?: ZodType | undefined;\n /** Hook(s) to run before workflow execution */\n onStart?: HookOrHandler | undefined;\n /** Hook(s) to run after workflow completion */\n onEnd?: HookOrHandler | undefined;\n /** Hook(s) to run before each agent step */\n onAgentStepStart?: HookOrHandler | undefined;\n /** Hook(s) to run after each agent step */\n onAgentStepEnd?: HookOrHandler | undefined;\n /** Hook(s) to run before tool execution */\n onToolStart?: HookOrHandler | undefined;\n /** Hook(s) to run after tool completion */\n onToolEnd?: HookOrHandler | undefined;\n /** Guardrails for output validation */\n guardrails?: (Guardrail | GuardrailHandler)[] | undefined;\n /** Maximum guardrail retries (default: 2) */\n guardrailMaxRetries?: number | undefined;\n /** Session compaction configuration — always enabled with sensible defaults */\n compaction?: CompactionConfig | undefined;\n /** Publish text_delta and tool_call events to the workflow topic for all invocations */\n streamToWorkflow?: boolean | undefined;\n /** Notification channels for suspend events. Overrides Worker-level channels. */\n channels?: Channel[] | undefined;\n}\n\n/**\n * Payload for agent run() and stream() calls.\n * Contains the agent input and conversation context.\n */\nexport interface AgentRunPayload {\n /** Input for the agent (string message or message array) */\n input: string | Record<string, unknown>[];\n}\n\n/**\n * A Workflow extended with agent-specific properties.\n * Matches the ToolWorkflow pattern.\n */\nexport interface AgentWorkflow extends Workflow {\n /** Agent configuration */\n readonly agentConfig: DefineAgentConfig;\n /** LLM instance */\n readonly llm: LLM;\n /** Tool definitions for the LLM */\n readonly tools: LlmToolDefinition[];\n /** Stop conditions */\n readonly stopConditions: StopCondition[];\n /** Agent-specific hooks */\n readonly agentHooks: {\n onAgentStepStart: Hook[];\n onAgentStepEnd: Hook[];\n onToolStart: Hook[];\n onToolEnd: Hook[];\n };\n /** Guardrails */\n readonly guardrails: Guardrail[];\n\n /**\n * Invoke the agent with streaming, returning a StreamResult for\n * iterating over text chunks and events.\n * Cannot be called from within a workflow — use step.agentInvoke() instead.\n */\n stream(\n client: PolosClient,\n payload: AgentRunPayload,\n options?: WorkflowRunOptions\n ): Promise<StreamResult>;\n\n /**\n * Invoke the agent and wait for the final result.\n * Cannot be called from within a workflow — use step.agentInvokeAndWait() instead.\n */\n run(\n client: WorkflowRunClient,\n payload: AgentRunPayload,\n options?: WorkflowRunOptions\n ): Promise<AgentStreamResult>;\n\n /**\n * Prepare agent for batch execution with all run() params.\n * Returns an AgentRunConfig for use with batchAgentInvoke().\n * Matches Python Agent.with_input().\n */\n withInput(\n input: string | Record<string, unknown>[],\n options?: {\n sessionId?: string;\n userId?: string;\n initialState?: Record<string, unknown>;\n runTimeoutSeconds?: number;\n streaming?: boolean;\n kwargs?: Record<string, unknown>;\n }\n ): AgentRunConfig;\n}\n\n// ── isAgentWorkflow ──────────────────────────────────────────────────\n\n/**\n * Type guard: checks whether a Workflow is an AgentWorkflow.\n */\nexport function isAgentWorkflow(workflow: Workflow): workflow is AgentWorkflow {\n return workflow.config.workflowType === 'agent';\n}\n\n// ── defineAgent ──────────────────────────────────────────────────────\n\n/**\n * Define an agent — a workflow with `workflowType: 'agent'` plus LLM configuration.\n *\n * @example\n * ```typescript\n * import { defineAgent, defineTool, maxSteps } from '@polos/sdk';\n * import { openai } from '@ai-sdk/openai';\n *\n * const searchTool = defineTool({\n * id: 'search',\n * description: 'Search the knowledge base',\n * inputSchema: z.object({ query: z.string() }),\n * }, async (ctx, input) => {\n * return await db.search(input.query);\n * });\n *\n * const myAgent = defineAgent({\n * id: 'my-agent',\n * model: openai('gpt-4o'),\n * systemPrompt: 'You are a helpful assistant.',\n * tools: [searchTool],\n * stopConditions: [maxSteps({ count: 10 })],\n * });\n * ```\n */\nexport function defineAgent(config: DefineAgentConfig): AgentWorkflow {\n // Create LLM instance from model\n const llm = new LLM({ model: config.model });\n\n // Build tool definitions for the LLM\n const toolDefs: LlmToolDefinition[] = (config.tools ?? []).map((t) => t.toLlmToolDefinition());\n\n // Normalize hooks\n const agentHooks = {\n onAgentStepStart: normalizeHooks(config.onAgentStepStart),\n onAgentStepEnd: normalizeHooks(config.onAgentStepEnd),\n onToolStart: normalizeHooks(config.onToolStart),\n onToolEnd: normalizeHooks(config.onToolEnd),\n };\n\n // Normalize guardrails\n const guardrails = normalizeGuardrails(config.guardrails);\n\n // Validate and collect stop conditions\n const stopConditions: StopCondition[] = config.stopConditions ?? [];\n\n // Convert outputSchema to JSON schema if provided\n const outputSchemaJson = config.outputSchema\n ? (() => {\n const { $schema: _, ...rest } = toJSONSchema(config.outputSchema) as Record<\n string,\n unknown\n >;\n return rest;\n })()\n : undefined;\n\n // Create handler closure\n const handler: WorkflowHandler<unknown, unknown, AgentStreamResult> = async (\n ctx: WorkflowContext,\n payload: unknown\n ): Promise<AgentStreamResult> => {\n const p = payload as Record<string, unknown>;\n\n // Extract fields from payload (matching Python _agent_execute)\n const input = p['input'] as string | Record<string, unknown>[];\n const streamingFlag = p['streaming'] as boolean | undefined;\n\n // Build the stream payload\n const streamPayload: AgentStreamPayload = {\n agent_run_id: ctx.executionId,\n name: config.id,\n agent_config: {\n system: config.systemPrompt,\n tools: toolDefs.length > 0 ? toolDefs : undefined,\n temperature: config.temperature,\n maxOutputTokens: config.maxOutputTokens,\n },\n input,\n streaming: streamingFlag ?? config.streamToWorkflow ?? false,\n };\n\n // Call the core agent stream function\n return agentStreamFunction(ctx, streamPayload, {\n id: config.id,\n llm,\n tools: toolDefs,\n stopConditions,\n agentHooks,\n guardrails,\n guardrailMaxRetries: config.guardrailMaxRetries ?? 2,\n compaction: config.compaction ?? {},\n outputSchema: outputSchemaJson,\n outputZodSchema: config.outputSchema,\n });\n };\n\n // Create the underlying workflow\n const workflow = defineWorkflow(\n {\n id: config.id,\n description: config.description,\n workflowType: 'agent',\n queue: config.queue,\n onStart: config.onStart,\n onEnd: config.onEnd,\n channels: config.channels,\n },\n handler as WorkflowHandler<unknown, unknown, unknown>\n );\n\n // Extend with agent-specific fields (following defineTool pattern)\n const agentWorkflow: AgentWorkflow = Object.assign(workflow, {\n agentConfig: config,\n llm,\n tools: toolDefs,\n stopConditions,\n agentHooks,\n guardrails,\n\n async stream(\n client: PolosClient,\n payload: AgentRunPayload,\n options?: WorkflowRunOptions\n ): Promise<StreamResult> {\n assertNotInExecutionContext('agent.stream()', 'step.agentInvoke()');\n\n const orchPayload: Record<string, unknown> = {\n input: payload.input,\n streaming: true,\n };\n\n const invokeOpts: Record<string, unknown> = {};\n if (options?.sessionId !== undefined) invokeOpts['sessionId'] = options.sessionId;\n if (options?.userId !== undefined) invokeOpts['userId'] = options.userId;\n if (options?.initialState !== undefined) invokeOpts['initialState'] = options.initialState;\n if (options?.timeout !== undefined)\n invokeOpts['runTimeoutSeconds'] = Math.ceil(options.timeout);\n\n const handle = await client.invoke(agentWorkflow, orchPayload, invokeOpts);\n\n return new StreamResult(handle, client);\n },\n\n async run(\n client: WorkflowRunClient,\n payload: AgentRunPayload,\n options?: WorkflowRunOptions\n ): Promise<AgentStreamResult> {\n assertNotInExecutionContext('agent.run()', 'step.agentInvokeAndWait()');\n\n const orchPayload: Record<string, unknown> = {\n input: payload.input,\n streaming: false,\n };\n\n const invokeOpts: Record<string, unknown> = {};\n if (options?.sessionId !== undefined) invokeOpts['sessionId'] = options.sessionId;\n if (options?.userId !== undefined) invokeOpts['userId'] = options.userId;\n if (options?.initialState !== undefined) invokeOpts['initialState'] = options.initialState;\n if (options?.timeout !== undefined)\n invokeOpts['runTimeoutSeconds'] = Math.ceil(options.timeout);\n\n const handle = await client.invoke(agentWorkflow.id, orchPayload, invokeOpts);\n\n return (await handle.getResult(options?.timeout ?? 600)) as AgentStreamResult;\n },\n\n withInput(\n input: string | Record<string, unknown>[],\n options?: {\n sessionId?: string;\n userId?: string;\n initialState?: Record<string, unknown>;\n runTimeoutSeconds?: number;\n streaming?: boolean;\n kwargs?: Record<string, unknown>;\n }\n ): AgentRunConfig {\n return new AgentRunConfig({\n agent: agentWorkflow,\n input,\n ...(options?.sessionId !== undefined && { sessionId: options.sessionId }),\n ...(options?.userId !== undefined && { userId: options.userId }),\n ...(options?.streaming !== undefined && { streaming: options.streaming }),\n ...(options?.initialState !== undefined && { initialState: options.initialState }),\n ...(options?.runTimeoutSeconds !== undefined && {\n runTimeoutSeconds: options.runTimeoutSeconds,\n }),\n ...(options?.kwargs !== undefined && { kwargs: options.kwargs }),\n });\n },\n });\n\n return agentWorkflow;\n}\n","/**\n * Fastify server for push-based workers.\n *\n * Handles execution requests from the orchestrator in push mode.\n */\n\nimport Fastify, { type FastifyInstance, type FastifyReply, type FastifyRequest } from 'fastify';\nimport type { ExecuteRequest } from './orchestrator-types.js';\nimport { createLogger } from '../utils/logger.js';\n\nconst logger = createLogger({ name: 'worker-server' });\n\n/**\n * Execution data passed to the work handler.\n */\nexport interface WorkerExecutionData {\n executionId: string;\n workflowId: string;\n deploymentId: string;\n payload: unknown;\n parentExecutionId?: string | undefined;\n rootExecutionId?: string | undefined;\n rootWorkflowId?: string | undefined;\n stepKey?: string | undefined;\n retryCount: number;\n createdAt?: string | undefined;\n sessionId?: string | undefined;\n userId?: string | undefined;\n otelTraceparent?: string | undefined;\n otelSpanId?: string | undefined;\n initialState?: Record<string, unknown> | undefined;\n runTimeoutSeconds?: number | undefined;\n channelContext?: { channelId: string; source: Record<string, unknown> } | undefined;\n}\n\n/**\n * Callback for handling received work.\n */\nexport type OnWorkReceivedCallback = (data: WorkerExecutionData) => Promise<void>;\n\n/**\n * Callback for handling cancel requests.\n * Returns true if execution was found and cancelled, false otherwise.\n */\nexport type OnCancelRequestedCallback = (executionId: string) => Promise<boolean>;\n\n/**\n * Configuration for WorkerServer.\n */\nexport interface WorkerServerConfig {\n /** Worker ID (assigned by orchestrator) */\n workerId: string;\n /** Maximum concurrent workflows */\n maxConcurrentWorkflows: number;\n /** Callback when work is received from orchestrator */\n onWorkReceived: OnWorkReceivedCallback;\n /** Callback when cancel request is received */\n onCancelRequested?: OnCancelRequestedCallback | undefined;\n /** Port to listen on (default: 8000) */\n port?: number | undefined;\n /** Host to bind to (default: '0.0.0.0') */\n host?: string | undefined;\n /** Whether running in local mode (binds to 127.0.0.1) */\n localMode?: boolean | undefined;\n}\n\n/**\n * Fastify server that receives pushed work from the orchestrator.\n */\nexport class WorkerServer {\n private readonly app: FastifyInstance;\n private workerId: string;\n private readonly maxConcurrentWorkflows: number;\n private readonly onWorkReceived: OnWorkReceivedCallback;\n private readonly onCancelRequested: OnCancelRequestedCallback | undefined;\n private readonly port: number;\n private readonly host: string;\n private currentExecutionCount = 0;\n\n constructor(config: WorkerServerConfig) {\n this.workerId = config.workerId;\n this.maxConcurrentWorkflows = config.maxConcurrentWorkflows;\n this.onWorkReceived = config.onWorkReceived;\n this.onCancelRequested = config.onCancelRequested;\n this.port = config.port ?? 8000;\n this.host = config.localMode ? '127.0.0.1' : (config.host ?? '0.0.0.0');\n\n this.app = Fastify({\n logger: false, // We use our own logger\n });\n\n this.setupRoutes();\n }\n\n /**\n * Update the worker ID (used when re-registering).\n */\n updateWorkerId(newWorkerId: string): void {\n this.workerId = newWorkerId;\n }\n\n /**\n * Get current execution count.\n */\n getCurrentExecutionCount(): number {\n return this.currentExecutionCount;\n }\n\n /**\n * Setup Fastify routes.\n */\n private setupRoutes(): void {\n // POST /execute - Receive pushed work from orchestrator\n this.app.post('/execute', async (request: FastifyRequest, reply: FastifyReply) => {\n try {\n // Check if worker is at capacity\n if (this.currentExecutionCount >= this.maxConcurrentWorkflows) {\n return await reply.status(429).send({ error: 'Worker at capacity' });\n }\n\n const body = request.body as ExecuteRequest;\n\n // Validate worker ID\n if (body.worker_id !== this.workerId) {\n return await reply.status(400).send({ error: 'Worker ID mismatch' });\n }\n\n // Extract execution data from flat body (matches orchestrator PushWorkRequest)\n const executionId = body.execution_id;\n const workflowId = body.workflow_id;\n const payload = body.payload;\n\n logger.info(\n `POST /execute - execution_id=${executionId}, worker_id=${this.workerId}, ` +\n `workflow_id=${workflowId}, root_execution_id=${String(body.root_execution_id)}, ` +\n `root_workflow_id=${String(body.root_workflow_id)}, step_key=${String(body.step_key)}, ` +\n `session_id=${String(body.session_id)}, user_id=${String(body.user_id)}, ` +\n `retry_count=${String(body.retry_count)}`\n );\n\n // Build execution data\n const executionData: WorkerExecutionData = {\n executionId,\n workflowId,\n deploymentId: body.deployment_id ?? '',\n payload,\n parentExecutionId: body.parent_execution_id ?? undefined,\n rootExecutionId: body.root_execution_id ?? undefined,\n rootWorkflowId: body.root_workflow_id ?? undefined,\n stepKey: body.step_key ?? undefined,\n retryCount: body.retry_count,\n createdAt: body.created_at ?? undefined,\n sessionId: body.session_id ?? undefined,\n userId: body.user_id ?? undefined,\n otelTraceparent: body.otel_traceparent ?? undefined,\n otelSpanId: body.otel_span_id ?? undefined,\n initialState: body.initial_state ?? undefined,\n runTimeoutSeconds: body.run_timeout_seconds ?? undefined,\n channelContext: body.channel_context\n ? {\n channelId: body.channel_context['channel_id'] as string,\n source: body.channel_context['source'] as Record<string, unknown>,\n }\n : undefined,\n };\n\n // Increment execution count\n this.currentExecutionCount++;\n\n // Execute in background (don't await)\n void this.executeWithCleanup(executionData);\n\n // Return 200 OK immediately (work accepted)\n return await reply.status(200).send({ status: 'accepted', execution_id: executionId });\n } catch (error) {\n logger.error('Error handling /execute', { error: String(error) });\n return await reply.status(503).send({ error: String(error) });\n }\n });\n\n // POST /cancel/:executionId - Handle cancellation request\n this.app.post<{ Params: { executionId: string } }>(\n '/cancel/:executionId',\n async (request: FastifyRequest<{ Params: { executionId: string } }>, reply: FastifyReply) => {\n try {\n const { executionId } = request.params;\n\n // Get worker_id from header\n const workerId = request.headers['x-worker-id'] as string | undefined;\n if (!workerId) {\n return await reply.status(400).send({ error: 'Missing Worker ID in request headers' });\n }\n\n if (workerId !== this.workerId) {\n return await reply.status(400).send({ error: 'Worker ID mismatch' });\n }\n\n logger.info(`POST /cancel/${executionId}`);\n\n // Trigger cancellation\n if (this.onCancelRequested) {\n const found = await this.onCancelRequested(executionId);\n if (found) {\n return await reply.status(200).send({\n status: 'cancellation_requested',\n execution_id: executionId,\n });\n } else {\n return await reply.status(404).send({\n error: 'Execution not found or already completed',\n execution_id: executionId,\n });\n }\n } else {\n return await reply.status(503).send({ error: 'Cancel handler not configured' });\n }\n } catch (error) {\n logger.error('Error handling /cancel', { error: String(error) });\n return await reply.status(500).send({ error: String(error) });\n }\n }\n );\n\n // GET /health - Health check endpoint\n this.app.get('/health', async (_request: FastifyRequest, reply: FastifyReply) => {\n return reply.status(200).send({\n status: 'healthy',\n mode: 'push',\n current_executions: this.currentExecutionCount,\n max_concurrent_workflows: this.maxConcurrentWorkflows,\n });\n });\n }\n\n /**\n * Execute work with cleanup on completion.\n */\n private async executeWithCleanup(executionData: WorkerExecutionData): Promise<void> {\n try {\n await this.onWorkReceived(executionData);\n } catch (error) {\n // Errors are already handled in the callback\n // This just prevents unhandled promise rejection warnings\n logger.debug('Execution completed with error (already handled)', {\n executionId: executionData.executionId,\n error: String(error),\n });\n } finally {\n // Decrement execution count when done\n this.currentExecutionCount = Math.max(0, this.currentExecutionCount - 1);\n }\n }\n\n /**\n * Start the server.\n */\n async start(): Promise<void> {\n try {\n await this.app.listen({ port: this.port, host: this.host });\n logger.info(`Worker server listening on ${this.host}:${String(this.port)}`);\n } catch (error) {\n logger.error('Failed to start worker server', { error: String(error) });\n throw error;\n }\n }\n\n /**\n * Stop the server gracefully.\n */\n async stop(): Promise<void> {\n try {\n await this.app.close();\n logger.info('Worker server stopped');\n } catch (error) {\n logger.error('Error stopping worker server', { error: String(error) });\n }\n }\n}\n","/**\n * JSON serialization utilities with support for special types.\n */\n\n/**\n * Custom replacer for JSON.stringify that handles:\n * - Date objects -> ISO strings\n * - BigInt -> string with 'n' suffix\n * - undefined -> null (when in arrays)\n * - Map -> object with __type marker\n * - Set -> array with __type marker\n */\nexport function jsonReplacer(_key: string, value: unknown): unknown {\n if (value instanceof Date) {\n return { __type: 'Date', value: value.toISOString() };\n }\n if (typeof value === 'bigint') {\n return { __type: 'BigInt', value: value.toString() };\n }\n if (value instanceof Map) {\n return { __type: 'Map', value: Array.from(value.entries()) };\n }\n if (value instanceof Set) {\n return { __type: 'Set', value: Array.from(value) };\n }\n return value;\n}\n\n/**\n * Custom reviver for JSON.parse that restores:\n * - Date objects from ISO strings\n * - BigInt from string\n * - Map from entries\n * - Set from array\n */\nexport function jsonReviver(_key: string, value: unknown): unknown {\n if (value !== null && typeof value === 'object' && '__type' in value) {\n const typed = value as { __type: string; value: unknown };\n switch (typed.__type) {\n case 'Date':\n return new Date(typed.value as string);\n case 'BigInt':\n return BigInt(typed.value as string);\n case 'Map':\n return new Map(typed.value as [unknown, unknown][]);\n case 'Set':\n return new Set(typed.value as unknown[]);\n }\n }\n return value;\n}\n\n/**\n * Serialize a value to JSON string with support for special types.\n */\nexport function serialize(value: unknown): string {\n return JSON.stringify(value, jsonReplacer);\n}\n\n/**\n * Deserialize a JSON string with support for special types.\n */\n// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters -- T is used for return type inference by callers\nexport function deserialize<T = unknown>(json: string): T {\n return JSON.parse(json, jsonReviver) as T;\n}\n\n/**\n * Deep clone a value using JSON serialization.\n * Handles special types like Date, BigInt, Map, Set.\n */\nexport function deepClone<T>(value: T): T {\n return deserialize(serialize(value));\n}\n\n/**\n * Check if a value is JSON-serializable.\n */\nexport function isSerializable(value: unknown): boolean {\n try {\n serialize(value);\n return true;\n } catch {\n return false;\n }\n}\n","/**\n * State management for workflows.\n *\n * Handles state initialization, validation, and serialization using Zod schemas.\n */\n\nimport type { ZodType } from 'zod';\nimport { serialize, deserialize } from '../utils/serializer.js';\n\n/**\n * Maximum state size in bytes (1MB).\n */\nexport const MAX_STATE_SIZE = 1024 * 1024;\n\n/**\n * Error thrown when state validation fails.\n */\nexport class StateValidationError extends Error {\n constructor(\n message: string,\n public readonly issues: unknown[]\n ) {\n const issueDetails = issues\n .map((issue) => {\n if (issue && typeof issue === 'object') {\n const i = issue as Record<string, unknown>;\n const path = Array.isArray(i['path']) ? (i['path'] as unknown[]).join('.') : '';\n const msg = typeof i['message'] === 'string' ? i['message'] : '';\n return path ? `${path}: ${msg}` : msg;\n }\n return String(issue);\n })\n .join('; ');\n super(issueDetails ? `${message}: ${issueDetails}` : message);\n this.name = 'StateValidationError';\n }\n}\n\n/**\n * Error thrown when state exceeds size limit.\n */\nexport class StateSizeError extends Error {\n constructor(\n public readonly size: number,\n public readonly maxSize: number\n ) {\n super(`State size (${String(size)} bytes) exceeds maximum allowed (${String(maxSize)} bytes)`);\n this.name = 'StateSizeError';\n }\n}\n\n/**\n * Initialize state from a Zod schema.\n * Uses schema defaults to create the initial state.\n */\nexport function initializeState<TState>(schema: ZodType<TState>): TState {\n // Parse an empty object to get defaults\n const result = schema.safeParse({});\n\n if (!result.success) {\n // If parsing fails, try with undefined to trigger defaults\n const retryResult = schema.safeParse(undefined);\n if (!retryResult.success) {\n throw new StateValidationError(\n 'Failed to initialize state from schema defaults',\n retryResult.error.issues\n );\n }\n return retryResult.data;\n }\n\n return result.data;\n}\n\n/**\n * Validate state against a Zod schema.\n */\nexport function validateState<TState>(state: unknown, schema: ZodType<TState>): TState {\n const result = schema.safeParse(state);\n\n if (!result.success) {\n throw new StateValidationError('State validation failed', result.error.issues);\n }\n\n return result.data;\n}\n\n/**\n * Serialize state for persistence.\n * Validates size limit before returning.\n */\n// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters -- TState constraint is useful for callers\nexport function serializeState<TState>(state: TState): string {\n const serialized = serialize(state);\n const size = new TextEncoder().encode(serialized).length;\n\n if (size > MAX_STATE_SIZE) {\n throw new StateSizeError(size, MAX_STATE_SIZE);\n }\n\n return serialized;\n}\n\n/**\n * Deserialize state from storage.\n */\nexport function deserializeState<TState>(serialized: string, schema?: ZodType<TState>): TState {\n const state = deserialize<TState>(serialized);\n\n if (schema) {\n return validateState(state, schema);\n }\n\n return state;\n}\n\n/**\n * Merge partial state updates into existing state.\n */\nexport function mergeState<TState extends object>(\n currentState: TState,\n updates: Partial<TState>\n): TState {\n return {\n ...currentState,\n ...updates,\n };\n}\n\n/**\n * Create a deep clone of state.\n */\nexport function cloneState<TState>(state: TState): TState {\n return deserialize(serialize(state));\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context, createContextKey } from '@opentelemetry/api';\n\nconst SUPPRESS_TRACING_KEY = createContextKey(\n 'OpenTelemetry SDK Context Key SUPPRESS_TRACING'\n);\n\nexport function suppressTracing(context: Context): Context {\n return context.setValue(SUPPRESS_TRACING_KEY, true);\n}\n\nexport function unsuppressTracing(context: Context): Context {\n return context.deleteValue(SUPPRESS_TRACING_KEY);\n}\n\nexport function isTracingSuppressed(context: Context): boolean {\n return context.getValue(SUPPRESS_TRACING_KEY) === true;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst VALID_KEY_CHAR_RANGE = '[_0-9a-z-*/]';\nconst VALID_KEY = `[a-z]${VALID_KEY_CHAR_RANGE}{0,255}`;\nconst VALID_VENDOR_KEY = `[a-z0-9]${VALID_KEY_CHAR_RANGE}{0,240}@[a-z]${VALID_KEY_CHAR_RANGE}{0,13}`;\nconst VALID_KEY_REGEX = new RegExp(`^(?:${VALID_KEY}|${VALID_VENDOR_KEY})$`);\nconst VALID_VALUE_BASE_REGEX = /^[ -~]{0,255}[!-~]$/;\nconst INVALID_VALUE_COMMA_EQUAL_REGEX = /,|=/;\n\n/**\n * Key is opaque string up to 256 characters printable. It MUST begin with a\n * lowercase letter, and can only contain lowercase letters a-z, digits 0-9,\n * underscores _, dashes -, asterisks *, and forward slashes /.\n * For multi-tenant vendor scenarios, an at sign (@) can be used to prefix the\n * vendor name. Vendors SHOULD set the tenant ID at the beginning of the key.\n * see https://www.w3.org/TR/trace-context/#key\n */\nexport function validateKey(key: string): boolean {\n return VALID_KEY_REGEX.test(key);\n}\n\n/**\n * Value is opaque string up to 256 characters printable ASCII RFC0020\n * characters (i.e., the range 0x20 to 0x7E) except comma , and =.\n */\nexport function validateValue(value: string): boolean {\n return (\n VALID_VALUE_BASE_REGEX.test(value) &&\n !INVALID_VALUE_COMMA_EQUAL_REGEX.test(value)\n );\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as api from '@opentelemetry/api';\nimport { validateKey, validateValue } from '../internal/validators';\n\nconst MAX_TRACE_STATE_ITEMS = 32;\nconst MAX_TRACE_STATE_LEN = 512;\nconst LIST_MEMBERS_SEPARATOR = ',';\nconst LIST_MEMBER_KEY_VALUE_SPLITTER = '=';\n\n/**\n * TraceState must be a class and not a simple object type because of the spec\n * requirement (https://www.w3.org/TR/trace-context/#tracestate-field).\n *\n * Here is the list of allowed mutations:\n * - New key-value pair should be added into the beginning of the list\n * - The value of any key can be updated. Modified keys MUST be moved to the\n * beginning of the list.\n */\nexport class TraceState implements api.TraceState {\n private _internalState: Map<string, string> = new Map();\n\n constructor(rawTraceState?: string) {\n if (rawTraceState) this._parse(rawTraceState);\n }\n\n set(key: string, value: string): TraceState {\n // TODO: Benchmark the different approaches(map vs list) and\n // use the faster one.\n const traceState = this._clone();\n if (traceState._internalState.has(key)) {\n traceState._internalState.delete(key);\n }\n traceState._internalState.set(key, value);\n return traceState;\n }\n\n unset(key: string): TraceState {\n const traceState = this._clone();\n traceState._internalState.delete(key);\n return traceState;\n }\n\n get(key: string): string | undefined {\n return this._internalState.get(key);\n }\n\n serialize(): string {\n return this._keys()\n .reduce((agg: string[], key) => {\n agg.push(key + LIST_MEMBER_KEY_VALUE_SPLITTER + this.get(key));\n return agg;\n }, [])\n .join(LIST_MEMBERS_SEPARATOR);\n }\n\n private _parse(rawTraceState: string) {\n if (rawTraceState.length > MAX_TRACE_STATE_LEN) return;\n this._internalState = rawTraceState\n .split(LIST_MEMBERS_SEPARATOR)\n .reverse() // Store in reverse so new keys (.set(...)) will be placed at the beginning\n .reduce((agg: Map<string, string>, part: string) => {\n const listMember = part.trim(); // Optional Whitespace (OWS) handling\n const i = listMember.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER);\n if (i !== -1) {\n const key = listMember.slice(0, i);\n const value = listMember.slice(i + 1, part.length);\n if (validateKey(key) && validateValue(value)) {\n agg.set(key, value);\n } else {\n // TODO: Consider to add warning log\n }\n }\n return agg;\n }, new Map());\n\n // Because of the reverse() requirement, trunc must be done after map is created\n if (this._internalState.size > MAX_TRACE_STATE_ITEMS) {\n this._internalState = new Map(\n Array.from(this._internalState.entries())\n .reverse() // Use reverse same as original tracestate parse chain\n .slice(0, MAX_TRACE_STATE_ITEMS)\n );\n }\n }\n\n private _keys(): string[] {\n return Array.from(this._internalState.keys()).reverse();\n }\n\n private _clone(): TraceState {\n const traceState = new TraceState();\n traceState._internalState = new Map(this._internalState);\n return traceState;\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Context,\n isSpanContextValid,\n SpanContext,\n TextMapGetter,\n TextMapPropagator,\n TextMapSetter,\n trace,\n TraceFlags,\n} from '@opentelemetry/api';\nimport { isTracingSuppressed } from './suppress-tracing';\nimport { TraceState } from './TraceState';\n\nexport const TRACE_PARENT_HEADER = 'traceparent';\nexport const TRACE_STATE_HEADER = 'tracestate';\n\nconst VERSION = '00';\nconst VERSION_PART = '(?!ff)[\\\\da-f]{2}';\nconst TRACE_ID_PART = '(?![0]{32})[\\\\da-f]{32}';\nconst PARENT_ID_PART = '(?![0]{16})[\\\\da-f]{16}';\nconst FLAGS_PART = '[\\\\da-f]{2}';\nconst TRACE_PARENT_REGEX = new RegExp(\n `^\\\\s?(${VERSION_PART})-(${TRACE_ID_PART})-(${PARENT_ID_PART})-(${FLAGS_PART})(-.*)?\\\\s?$`\n);\n\n/**\n * Parses information from the [traceparent] span tag and converts it into {@link SpanContext}\n * @param traceParent - A meta property that comes from server.\n * It should be dynamically generated server side to have the server's request trace Id,\n * a parent span Id that was set on the server's request span,\n * and the trace flags to indicate the server's sampling decision\n * (01 = sampled, 00 = not sampled).\n * for example: '{version}-{traceId}-{spanId}-{sampleDecision}'\n * For more information see {@link https://www.w3.org/TR/trace-context/}\n */\nexport function parseTraceParent(traceParent: string): SpanContext | null {\n const match = TRACE_PARENT_REGEX.exec(traceParent);\n if (!match) return null;\n\n // According to the specification the implementation should be compatible\n // with future versions. If there are more parts, we only reject it if it's using version 00\n // See https://www.w3.org/TR/trace-context/#versioning-of-traceparent\n if (match[1] === '00' && match[5]) return null;\n\n return {\n traceId: match[2],\n spanId: match[3],\n traceFlags: parseInt(match[4], 16),\n };\n}\n\n/**\n * Propagates {@link SpanContext} through Trace Context format propagation.\n *\n * Based on the Trace Context specification:\n * https://www.w3.org/TR/trace-context/\n */\nexport class W3CTraceContextPropagator implements TextMapPropagator {\n inject(context: Context, carrier: unknown, setter: TextMapSetter): void {\n const spanContext = trace.getSpanContext(context);\n if (\n !spanContext ||\n isTracingSuppressed(context) ||\n !isSpanContextValid(spanContext)\n )\n return;\n\n const traceParent = `${VERSION}-${spanContext.traceId}-${\n spanContext.spanId\n }-0${Number(spanContext.traceFlags || TraceFlags.NONE).toString(16)}`;\n\n setter.set(carrier, TRACE_PARENT_HEADER, traceParent);\n if (spanContext.traceState) {\n setter.set(\n carrier,\n TRACE_STATE_HEADER,\n spanContext.traceState.serialize()\n );\n }\n }\n\n extract(context: Context, carrier: unknown, getter: TextMapGetter): Context {\n const traceParentHeader = getter.get(carrier, TRACE_PARENT_HEADER);\n if (!traceParentHeader) return context;\n const traceParent = Array.isArray(traceParentHeader)\n ? traceParentHeader[0]\n : traceParentHeader;\n if (typeof traceParent !== 'string') return context;\n const spanContext = parseTraceParent(traceParent);\n if (!spanContext) return context;\n\n spanContext.isRemote = true;\n\n const traceStateHeader = getter.get(carrier, TRACE_STATE_HEADER);\n if (traceStateHeader) {\n // If more than one `tracestate` header is found, we merge them into a\n // single header.\n const state = Array.isArray(traceStateHeader)\n ? traceStateHeader.join(',')\n : traceStateHeader;\n spanContext.traceState = new TraceState(\n typeof state === 'string' ? state : undefined\n );\n }\n return trace.setSpanContext(context, spanContext);\n }\n\n fields(): string[] {\n return [TRACE_PARENT_HEADER, TRACE_STATE_HEADER];\n }\n}\n","/**\n * OpenTelemetry tracing support for Polos workflows.\n */\n\nimport { randomBytes } from 'node:crypto';\nimport {\n type Context,\n type Span,\n type SpanContext,\n type TextMapGetter,\n type TextMapSetter,\n type Tracer,\n SpanStatusCode,\n context,\n trace,\n} from '@opentelemetry/api';\nimport {\n BasicTracerProvider,\n BatchSpanProcessor,\n type IdGenerator,\n type ReadableSpan,\n type SpanExporter,\n} from '@opentelemetry/sdk-trace-base';\nimport { type ExportResult, W3CTraceContextPropagator } from '@opentelemetry/core';\nimport { AsyncLocalStorageContextManager } from '@opentelemetry/context-async-hooks';\nimport { createLogger } from '../utils/logger.js';\n\nconst logger = createLogger({ name: 'tracing' });\n\n// Re-export types that consumers need\nexport { type Span, type SpanContext, type Context, SpanStatusCode };\n\n// ---------------------------------------------------------------------------\n// Module-level state\n// ---------------------------------------------------------------------------\n\nlet _tracerProvider: BasicTracerProvider | undefined;\nlet _tracer: Tracer | undefined;\nlet _propagator: W3CTraceContextPropagator | undefined;\nlet _initialized = false;\n\n// ---------------------------------------------------------------------------\n// Propagator\n// ---------------------------------------------------------------------------\n\n/**\n * Get the W3C trace context propagator (lazy singleton).\n */\nfunction getPropagator(): W3CTraceContextPropagator {\n _propagator ??= new W3CTraceContextPropagator();\n return _propagator;\n}\n\n/**\n * Simple carrier getter for extracting traceparent from a plain object.\n */\nconst mapGetter: TextMapGetter<Record<string, string>> = {\n get(carrier, key) {\n return carrier[key];\n },\n keys(carrier) {\n return Object.keys(carrier);\n },\n};\n\n/**\n * Simple carrier setter for injecting traceparent into a plain object.\n */\nconst mapSetter: TextMapSetter<Record<string, string>> = {\n set(carrier, key, value) {\n carrier[key] = value;\n },\n};\n\n// ---------------------------------------------------------------------------\n// DatabaseSpanExporter\n// ---------------------------------------------------------------------------\n\n/**\n * Configuration for initializing OpenTelemetry.\n */\nexport interface OtelConfig {\n apiUrl: string;\n apiKey: string;\n projectId: string;\n}\n\n/**\n * Custom span exporter that stores spans to the database via the orchestrator API.\n */\nclass DatabaseSpanExporter implements SpanExporter {\n private readonly apiUrl: string;\n private readonly apiKey: string;\n private readonly projectId: string;\n\n constructor(config: OtelConfig) {\n this.apiUrl = config.apiUrl.replace(/\\/$/, '');\n this.apiKey = config.apiKey;\n this.projectId = config.projectId;\n }\n\n export(spans: ReadableSpan[], resultCallback: (result: ExportResult) => void): void {\n if (spans.length === 0) {\n resultCallback({ code: 0 }); // SUCCESS\n return;\n }\n\n const spanDataList = spans.map((span) => this.spanToDict(span));\n const url = `${this.apiUrl}/internal/spans/batch`;\n\n fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.apiKey}`,\n 'X-Project-ID': this.projectId,\n },\n body: JSON.stringify({ spans: spanDataList }),\n })\n .then((response) => {\n if (!response.ok) {\n logger.warn(`Failed to export spans: HTTP ${String(response.status)}`);\n resultCallback({ code: 1 }); // FAILURE\n } else {\n resultCallback({ code: 0 }); // SUCCESS\n }\n })\n .catch((err: unknown) => {\n logger.warn(`Failed to export spans: ${String(err)}`);\n resultCallback({ code: 1 }); // FAILURE\n });\n }\n\n shutdown(): Promise<void> {\n return Promise.resolve();\n }\n\n forceFlush(): Promise<void> {\n return Promise.resolve();\n }\n\n /**\n * Convert a ReadableSpan to the database dict format/\n */\n private spanToDict(span: ReadableSpan): Record<string, unknown> {\n const spanCtx = span.spanContext();\n const traceId = spanCtx.traceId;\n const spanId = spanCtx.spanId;\n\n // Parent span ID\n let parentSpanId: string | null = null;\n if (span.parentSpanId) {\n parentSpanId = span.parentSpanId;\n }\n\n // Extract attributes, separating input/output/error/state\n const attributes: Record<string, string | null> = {};\n let inputData: unknown = null;\n let outputData: unknown = null;\n let initialState: unknown = null;\n let finalState: unknown = null;\n let errorFromAttributes: unknown = null;\n\n for (const [key, value] of Object.entries(span.attributes)) {\n if (INPUT_KEYS.has(key) && value != null) {\n inputData = tryParseJson(value);\n } else if (OUTPUT_KEYS.has(key) && value != null) {\n outputData = tryParseJson(value);\n } else if (ERROR_KEYS.has(key) && value != null) {\n errorFromAttributes = tryParseJson(value);\n } else if (INITIAL_STATE_KEYS.has(key) && value != null) {\n initialState = tryParseJson(value);\n } else if (FINAL_STATE_KEYS.has(key) && value != null) {\n finalState = tryParseJson(value);\n } else {\n attributes[key] = value != null ? String(value) : null;\n }\n }\n\n // Extract events\n const eventsData: Record<string, unknown>[] = [];\n for (const event of span.events) {\n const eventName = event.name;\n const eventTimestamp = formatHrTime(event.time);\n\n const eventAttributes: Record<string, string | null> = {};\n if (event.attributes) {\n for (const [key, value] of Object.entries(event.attributes)) {\n eventAttributes[key] = value != null ? String(value) : null;\n }\n }\n\n eventsData.push({\n name: eventName,\n timestamp: eventTimestamp,\n attributes: Object.keys(eventAttributes).length > 0 ? eventAttributes : null,\n });\n }\n\n // Status and error\n let errorData: unknown = null;\n if (errorFromAttributes) {\n errorData = errorFromAttributes;\n } else if (span.status.code === SpanStatusCode.ERROR) {\n errorData = {\n message: span.status.message ?? 'Unknown error',\n error_type: 'Error',\n };\n }\n\n // Timestamps\n const startedAt = formatHrTime(span.startTime);\n const endedAt = formatHrTime(span.endTime);\n\n // Span type\n let spanType = 'custom';\n const name = span.name;\n if (name.startsWith('workflow.')) {\n spanType = 'workflow';\n } else if (name.startsWith('agent.')) {\n spanType = 'agent';\n } else if (name.startsWith('tool.')) {\n spanType = 'tool';\n } else if (name.startsWith('step.')) {\n spanType = 'step';\n } else if (attributes['span_type']) {\n spanType = attributes['span_type'];\n }\n\n return {\n trace_id: traceId,\n span_id: spanId,\n parent_span_id: parentSpanId,\n name,\n span_type: spanType,\n attributes: Object.keys(attributes).length > 0 ? attributes : null,\n events: eventsData.length > 0 ? eventsData : null,\n input: inputData,\n output: outputData,\n error: errorData,\n initial_state: initialState,\n final_state: finalState,\n started_at: startedAt,\n ended_at: endedAt,\n };\n }\n}\n\n// ---------------------------------------------------------------------------\n// Span attribute key sets\n// ---------------------------------------------------------------------------\n\nconst INPUT_KEYS = new Set([\n 'step.input',\n 'workflow.input',\n 'agent.input',\n 'tool.input',\n 'llm.input',\n]);\nconst OUTPUT_KEYS = new Set([\n 'step.output',\n 'workflow.output',\n 'agent.output',\n 'tool.output',\n 'llm.output',\n]);\nconst ERROR_KEYS = new Set([\n 'step.error',\n 'workflow.error',\n 'agent.error',\n 'tool.error',\n 'llm.error',\n]);\nconst INITIAL_STATE_KEYS = new Set([\n 'workflow.initial_state',\n 'agent.initial_state',\n 'tool.initial_state',\n]);\nconst FINAL_STATE_KEYS = new Set(['workflow.final_state', 'agent.final_state', 'tool.final_state']);\n\nfunction tryParseJson(value: unknown): unknown {\n if (typeof value !== 'string') return null;\n try {\n return JSON.parse(value) as unknown;\n } catch {\n return null;\n }\n}\n\n/**\n * Format OTel HrTime ([seconds, nanoseconds]) to ISO string.\n */\nfunction formatHrTime(hrTime: unknown): string | null {\n if (hrTime == null) return null;\n if (Array.isArray(hrTime) && hrTime.length === 2) {\n const ms = (hrTime[0] as number) * 1000 + (hrTime[1] as number) / 1e6;\n return new Date(ms).toISOString();\n }\n if (typeof hrTime === 'number') {\n if (hrTime > 1e15) {\n return new Date(hrTime / 1e6).toISOString();\n }\n return new Date(hrTime).toISOString();\n }\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// DeterministicTraceIdGenerator\n// ---------------------------------------------------------------------------\n\nconst TRACE_ID_SYMBOL = Symbol.for('polos.trace_id');\n\n/**\n * ID generator that uses deterministic trace IDs from context when available.\n * Falls back to random IDs.\n */\nclass DeterministicTraceIdGenerator implements IdGenerator {\n generateTraceId(): string {\n // Check active OTel context for deterministic trace ID\n try {\n const currentContext = context.active();\n const deterministicId = currentContext.getValue(TRACE_ID_SYMBOL);\n if (typeof deterministicId === 'string') {\n return deterministicId;\n }\n } catch {\n // fall through to random\n }\n return randomHex(32);\n }\n\n generateSpanId(): string {\n return randomHex(16);\n }\n}\n\nfunction randomHex(length: number): string {\n return randomBytes(length / 2).toString('hex');\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Initialize OpenTelemetry with database exporter.\n */\nexport function initializeOtel(config: OtelConfig): void {\n if (_initialized) return;\n\n try {\n // Check if enabled\n if (process.env['POLOS_OTEL_ENABLED']?.toLowerCase() === 'false') {\n logger.info('OpenTelemetry disabled via POLOS_OTEL_ENABLED=false');\n return;\n }\n\n // Create tracer provider with deterministic ID generator and database exporter\n const dbExporter = new DatabaseSpanExporter(config);\n _tracerProvider = new BasicTracerProvider({\n idGenerator: new DeterministicTraceIdGenerator(),\n spanProcessors: [new BatchSpanProcessor(dbExporter)],\n });\n\n // Register as global with AsyncLocalStorage context manager\n // Required for DeterministicTraceIdGenerator to read trace ID from context\n _tracerProvider.register({\n contextManager: new AsyncLocalStorageContextManager(),\n });\n\n // Get tracer\n const serviceName = process.env['POLOS_OTEL_SERVICE_NAME'] ?? 'polos';\n _tracer = trace.getTracer(serviceName);\n _initialized = true;\n\n logger.info('OpenTelemetry initialized with database exporter');\n } catch (e) {\n logger.warn(`Failed to initialize OpenTelemetry: ${String(e)}. Tracing disabled.`);\n _tracer = undefined;\n }\n}\n\n/**\n * Get the tracer instance. Returns undefined if OTel is not initialized.\n */\nexport function getTracer(): Tracer | undefined {\n return _tracer;\n}\n\n/**\n * Flush pending spans and shut down the OpenTelemetry tracer provider.\n *\n * Must be called during worker shutdown before the process exits so that\n * the BatchSpanProcessor exports any remaining spans.\n */\nexport async function shutdownOtel(): Promise<void> {\n if (!_tracerProvider) return;\n\n try {\n await _tracerProvider.forceFlush();\n await _tracerProvider.shutdown();\n } catch (e) {\n logger.warn(`Error during OpenTelemetry shutdown: ${String(e)}`);\n } finally {\n _tracerProvider = undefined;\n _tracer = undefined;\n _initialized = false;\n }\n}\n\n/**\n * Get the current span from OTel context.\n */\nexport function getCurrentSpan(): Span | undefined {\n return trace.getSpan(context.active());\n}\n\n/**\n * Extract traceparent string from a span using W3C propagator.\n */\nexport function extractTraceparent(span: Span): string | undefined {\n try {\n const prop = getPropagator();\n const carrier: Record<string, string> = {};\n\n // Create a context with the span and inject traceparent into carrier\n const ctx = trace.setSpan(context.active(), span);\n prop.inject(ctx, carrier, mapSetter);\n\n return carrier['traceparent'] ?? undefined;\n } catch (e) {\n logger.warn(`Failed to extract traceparent: ${String(e)}`);\n return undefined;\n }\n}\n\n/**\n * Create OTel context from a W3C traceparent string (for sub-workflows).\n */\nexport function createContextFromTraceparent(traceparent: string): Context | undefined {\n if (!traceparent) return undefined;\n\n try {\n const prop = getPropagator();\n const carrier: Record<string, string> = { traceparent };\n const extractedContext = prop.extract(context.active(), carrier, mapGetter);\n\n return extractedContext;\n } catch (e) {\n logger.warn(`Failed to create context from traceparent '${traceparent}': ${String(e)}`);\n return undefined;\n }\n}\n\n/**\n * Create OTel context with a deterministic trace ID (for root workflows).\n * The DeterministicTraceIdGenerator reads this from the context.\n */\nexport function createContextWithTraceId(traceIdHex: string): Context | undefined {\n try {\n const ctx = context.active();\n return ctx.setValue(TRACE_ID_SYMBOL, traceIdHex);\n } catch (e) {\n logger.warn(`Failed to create context with trace ID: ${String(e)}`);\n return undefined;\n }\n}\n\n/**\n * Generate a deterministic trace ID (32-char hex) from a UUID execution ID.\n */\nexport function generateTraceIdFromExecutionId(executionId: string): string {\n const hexStr = executionId.replace(/-/g, '');\n if (hexStr.length !== 32) {\n throw new Error(`Invalid execution_id format: ${executionId}`);\n }\n return hexStr;\n}\n\n/**\n * Format a Date to ISO string.\n */\nexport function formatTimestamp(date: Date): string {\n return date.toISOString();\n}\n\n/**\n * Check if OpenTelemetry has been initialized.\n */\nexport function isOtelAvailable(): boolean {\n return _initialized;\n}\n","/**\n * Span context utilities for ExecutionContextData.\n *\n * Matches Python's utils/tracing.py. Manages the integration between\n * Polos execution context (AsyncLocalStorage) and OTel span contexts.\n */\n\nimport { type Context, type SpanContext, trace, context as otelContext } from '@opentelemetry/api';\nimport type { ExecutionContextData } from '../runtime/execution-context.js';\n\n/**\n * Get parent OTel context from execution context.\n * Wraps the stored SpanContext in a NonRecordingSpan and sets it in an OTel Context,\n * suitable for passing as `context` to `tracer.startSpan(name, opts, context)`.\n */\nexport function getParentSpanContextFromExecutionContext(\n execContext: ExecutionContextData | undefined\n): Context | undefined {\n if (!execContext) return undefined;\n\n const parentSpanContext = execContext._otelSpanContext as SpanContext | undefined;\n if (!parentSpanContext) return undefined;\n\n // Wrap SpanContext in NonRecordingSpan → set in OTel Context\n const parentSpan = trace.wrapSpanContext(parentSpanContext);\n return trace.setSpan(otelContext.active(), parentSpan);\n}\n\n/**\n * Get raw span context from execution context.\n */\nexport function getSpanContextFromExecutionContext(\n execContext: ExecutionContextData | undefined\n): SpanContext | undefined {\n if (!execContext) return undefined;\n return execContext._otelSpanContext as SpanContext | undefined;\n}\n\n/**\n * Store span context in execution context along with formatted trace ID and span ID.\n */\nexport function setSpanContextInExecutionContext(\n execContext: ExecutionContextData | undefined,\n spanContext: SpanContext | undefined\n): void {\n if (!execContext) return;\n\n execContext._otelSpanContext = spanContext;\n if (spanContext != null) {\n execContext._otelTraceId = spanContext.traceId;\n execContext._otelSpanId = spanContext.spanId;\n }\n}\n","/**\n * Workflow executor - handles execution of workflows with proper context setup.\n *\n * The createOrchestratorStepHelper function.\n */\n\nimport { randomUUID } from 'node:crypto';\nimport type { ZodType } from 'zod';\nimport type { Workflow } from '../core/workflow.js';\nimport type { WorkflowContext, AgentContext } from '../core/context.js';\nimport type { AgentWorkflow } from '../agents/agent.js';\nimport type {\n StepHelper,\n StepOptions,\n InvokeOptions,\n WaitForOptions,\n WaitForEventOptions,\n PublishEventOptions,\n SuspendOptions,\n ResumeOptions,\n BatchWorkflowInput,\n BatchStepResult,\n} from '../core/step.js';\nimport type { AgentRunConfig } from '../core/step.js';\nimport { StepExecutionError, WaitError, isWaitError } from '../core/step.js';\nimport type { WorkflowHandle, WorkflowStatus } from '../core/workflow.js';\nimport type { OrchestratorClient } from './orchestrator-client.js';\nimport type { ExecutionContext, StepOutput, BatchWorkflowEntry } from './orchestrator-types.js';\nimport type { Channel, ChannelContext, SuspendNotification } from '../channels/channel.js';\nimport { executeHookChain } from '../middleware/hook-executor.js';\nimport { normalizeHooks } from '../middleware/hook.js';\nimport { initializeState, validateState, serializeState } from '../core/state.js';\nimport { retry, type RetryOptions } from '../utils/retry.js';\nimport { createLogger } from '../utils/logger.js';\nimport { getModelId, getModelProvider } from '../llm/types.js';\nimport { runInExecutionContext, getExecutionContext } from './execution-context.js';\nimport type { SandboxManager } from '../execution/sandbox-manager.js';\nimport {\n type Span,\n type SpanContext,\n type Context,\n context as otelContext,\n trace as otelTrace,\n} from '@opentelemetry/api';\nimport {\n getTracer,\n extractTraceparent,\n createContextFromTraceparent,\n createContextWithTraceId,\n generateTraceIdFromExecutionId,\n} from '../features/tracing.js';\nimport {\n getParentSpanContextFromExecutionContext,\n getSpanContextFromExecutionContext,\n setSpanContextInExecutionContext,\n} from '../utils/tracing.js';\n\nconst logger = createLogger({ name: 'executor' });\n\n/**\n * Options for executing a workflow.\n */\nexport interface ExecuteWorkflowOptions {\n /** The workflow to execute */\n workflow: Workflow;\n /** Payload for the workflow */\n payload: unknown;\n /** Execution context from orchestrator */\n context: ExecutionContext;\n /** Orchestrator client for API calls */\n orchestratorClient: OrchestratorClient;\n /** Worker ID */\n workerId: string;\n /** Abort signal for cancellation */\n abortSignal?: AbortSignal | undefined;\n /** Notification channels for suspend events */\n channels?: Channel[] | undefined;\n /** Sandbox manager for managed sandbox lifecycle */\n sandboxManager?: SandboxManager | undefined;\n /** Originating channel context for bidirectional channels */\n channelContext?: { channelId: string; source: Record<string, unknown> } | undefined;\n}\n\n/**\n * Result of workflow execution.\n */\nexport interface ExecutionResult {\n /** Whether execution succeeded */\n success: boolean;\n /** Result value (if success) */\n // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents -- needed for exactOptionalPropertyTypes\n result?: unknown | undefined;\n /** Error message (if failure) */\n error?: string | undefined;\n /** Stack trace (if failure) */\n stack?: string | undefined;\n /** Whether the error is retryable */\n retryable?: boolean | undefined;\n /** Whether the execution is paused/waiting (WaitError was thrown) */\n waiting?: boolean | undefined;\n /** Final state after execution */\n finalState?: Record<string, unknown> | undefined;\n}\n\n/**\n * Create a WorkflowHandle for a sub-workflow execution.\n */\nfunction createWorkflowHandle<TResult>(\n orchestratorClient: OrchestratorClient,\n executionId: string\n): WorkflowHandle<TResult> {\n return {\n executionId,\n async getStatus(): Promise<WorkflowStatus<TResult>> {\n const exec = await orchestratorClient.getExecution(executionId);\n return {\n status:\n exec.status === 'completed'\n ? 'completed'\n : exec.status === 'failed'\n ? 'failed'\n : exec.status === 'cancelled'\n ? 'cancelled'\n : exec.status === 'running' || exec.status === 'claimed'\n ? 'running'\n : 'queued',\n result: exec.result as TResult | undefined,\n error: exec.error,\n createdAt: new Date(exec.created_at),\n completedAt: exec.completed_at ? new Date(exec.completed_at) : undefined,\n };\n },\n async waitForResult(opts?: { timeout?: number }): Promise<TResult> {\n const waitOptions = opts?.timeout !== undefined ? { timeout: opts.timeout } : undefined;\n const exec = await orchestratorClient.waitForExecution(executionId, waitOptions);\n if (exec.status === 'failed') {\n throw new Error(exec.error ?? 'Workflow execution failed');\n }\n if (exec.status === 'cancelled') {\n throw new Error('Workflow execution cancelled');\n }\n return exec.result as TResult;\n },\n async cancel(): Promise<void> {\n await orchestratorClient.cancelExecution(executionId);\n },\n };\n}\n\n/**\n * Context info passed to the step helper for sub-workflow invocations.\n */\ninterface StepExecutionContext {\n workflowId: string;\n executionId: string;\n deploymentId: string;\n sessionId?: string | undefined;\n userId?: string | undefined;\n rootExecutionId: string;\n rootWorkflowId: string;\n otelTraceparent?: string | undefined;\n}\n\n/**\n * Create a StepHelper backed by the orchestrator.\n */\nfunction createOrchestratorStepHelper(\n orchestratorClient: OrchestratorClient,\n cachedSteps: Map<string, StepOutput>,\n execCtx: StepExecutionContext,\n workerId: string,\n abortSignal?: AbortSignal,\n channels?: Channel[],\n channelContext?: { channelId: string; source: Record<string, unknown> }\n): StepHelper {\n // --- Abort check ---\n const checkAborted = (): void => {\n if (abortSignal?.aborted) {\n throw new Error('Execution cancelled');\n }\n };\n\n /** Check for existing step output. */\n const checkExistingStep = (key: string): StepOutput | undefined => {\n return cachedSteps.get(key);\n };\n\n /** Handle existing step output — return cached result or throw on failure. */\n const handleExistingStep = (existing: StepOutput): unknown => {\n if (existing.success !== false) {\n return existing.outputs;\n }\n const error = existing.error;\n let errorMessage: string;\n if (typeof error === 'object' && error !== null) {\n const msg = (error as Record<string, unknown>)['message'];\n errorMessage = typeof msg === 'string' ? msg : 'Step execution failed';\n } else if (typeof error === 'string') {\n errorMessage = error;\n } else {\n errorMessage = 'Step execution failed';\n }\n throw new StepExecutionError(errorMessage);\n };\n\n /** Save step output on success. */\n const saveStepOutput = async (\n key: string,\n result: unknown,\n sourceExecutionId?: string\n ): Promise<void> => {\n // Cache locally\n cachedSteps.set(key, {\n stepKey: key,\n outputs: result,\n completedAt: new Date().toISOString(),\n success: true,\n });\n\n // Persist to orchestrator\n await orchestratorClient.storeStepOutput(\n execCtx.executionId,\n {\n stepKey: key,\n outputs: result,\n success: true,\n sourceExecutionId,\n },\n workerId\n );\n };\n\n /** Save step output with error. */\n const saveStepOutputWithError = async (key: string, error: string): Promise<void> => {\n cachedSteps.set(key, {\n stepKey: key,\n outputs: undefined,\n completedAt: new Date().toISOString(),\n success: false,\n error: { message: error },\n });\n\n await orchestratorClient.storeStepOutput(\n execCtx.executionId,\n {\n stepKey: key,\n error: { message: error },\n success: false,\n },\n workerId\n );\n };\n\n /** Publish step event fire-and-forget. */\n const publishStepEvent = (\n eventType: string,\n stepKey: string,\n stepType: string,\n inputParams: Record<string, unknown>\n ): void => {\n const topic = `workflow/${execCtx.rootWorkflowId}/${execCtx.rootExecutionId}`;\n orchestratorClient\n .publishEvent({\n topic,\n events: [\n {\n eventType,\n data: {\n step_key: stepKey,\n step_type: stepType,\n data: inputParams,\n _metadata: {\n execution_id: execCtx.executionId,\n workflow_id: execCtx.workflowId,\n },\n },\n },\n ],\n executionId: execCtx.executionId,\n rootExecutionId: execCtx.rootExecutionId,\n })\n .catch((err: unknown) => {\n logger.warn('Failed to publish step event', { error: String(err) });\n });\n };\n\n // --- Shared invoke helper ---\n\n const _invoke = async (\n key: string,\n workflow: string | Workflow,\n payload: unknown,\n options?: InvokeOptions & { waitForSubworkflow?: boolean }\n ): Promise<[unknown, boolean]> => {\n const workflowId = typeof workflow === 'string' ? workflow : workflow.id;\n\n // Check for existing step output\n const existing = checkExistingStep(key);\n if (existing) {\n const result = handleExistingStep(existing);\n return [result, true];\n }\n\n // Invoke workflow via orchestrator\n const response = await orchestratorClient.invokeWorkflow(workflowId, {\n workflowId,\n payload,\n deploymentId: execCtx.deploymentId,\n parentExecutionId: execCtx.executionId,\n rootExecutionId: execCtx.rootExecutionId,\n rootWorkflowId: execCtx.rootWorkflowId,\n sessionId: execCtx.sessionId,\n userId: execCtx.userId,\n stepKey: options?.waitForSubworkflow ? key : undefined,\n concurrencyKey: options?.concurrencyKey,\n queueName: options?.queue,\n otelTraceparent: getCurrentTraceparent(),\n waitForSubworkflow: options?.waitForSubworkflow ?? false,\n initialState: options?.initialState,\n runTimeoutSeconds: options?.runTimeoutSeconds,\n });\n\n if (options?.waitForSubworkflow) {\n // No need to save — orchestrator saves step output on sub-workflow completion\n return [undefined, false];\n } else {\n // Save serializable handle data\n const handleData = {\n id: response.execution_id,\n workflow_id: workflowId,\n created_at: response.created_at,\n parent_execution_id: execCtx.executionId,\n root_workflow_id: execCtx.rootWorkflowId,\n root_execution_id: execCtx.rootExecutionId,\n session_id: execCtx.sessionId,\n user_id: execCtx.userId,\n };\n await saveStepOutput(key, handleData);\n return [handleData, false];\n }\n };\n\n /** Add a span event on the current span from execution context. */\n const addSpanEventFromExecutionContext = (\n eventName: string,\n eventAttributes: Record<string, string>\n ): void => {\n try {\n const activeSpan = otelTrace.getSpan(otelContext.active());\n if (activeSpan) {\n activeSpan.addEvent(eventName, eventAttributes);\n }\n } catch {\n // ignore — no active span\n }\n };\n\n /** Get the current traceparent, preferring the active span's context. */\n const getCurrentTraceparent = (): string | undefined => {\n const currentExecCtx = getExecutionContext();\n if (currentExecCtx?._otelSpanContext) {\n try {\n const currentSpan = otelTrace.wrapSpanContext(\n currentExecCtx._otelSpanContext as SpanContext\n );\n const tp = extractTraceparent(currentSpan);\n if (tp) return tp;\n } catch {\n // fallback\n }\n }\n return execCtx.otelTraceparent;\n };\n\n // --- StepHelper implementation ---\n\n return {\n async run<T>(key: string, fn: () => T | Promise<T>, options?: StepOptions): Promise<T> {\n checkAborted();\n\n const existing = checkExistingStep(key);\n if (existing) {\n return handleExistingStep(existing) as T;\n }\n\n const retryOpts: RetryOptions = {\n maxRetries: options?.maxRetries ?? 2,\n baseDelay: options?.baseDelay ?? 1000,\n maxDelay: options?.maxDelay ?? 10000,\n };\n\n // Publish step_start event\n publishStepEvent('step_start', key, 'run', {\n max_retries: retryOpts.maxRetries ?? 2,\n base_delay: retryOpts.baseDelay ?? 1000,\n max_delay: retryOpts.maxDelay ?? 10000,\n });\n\n // Create step span\n const tracer = getTracer();\n let span: Span | undefined;\n let oldSpanContext: SpanContext | undefined;\n const execContextData = getExecutionContext();\n\n if (tracer) {\n const parentContext = getParentSpanContextFromExecutionContext(execContextData);\n span = tracer.startSpan(\n `step.${key}`,\n {\n attributes: { 'step.key': key, 'step.type': 'run' },\n },\n parentContext\n );\n oldSpanContext = getSpanContextFromExecutionContext(execContextData);\n setSpanContextInExecutionContext(execContextData, span.spanContext());\n\n // Record step input if provided\n if (options?.input !== undefined) {\n try {\n span.setAttribute('step.input', JSON.stringify(options.input));\n } catch {\n /* ignore */\n }\n }\n }\n\n try {\n const result = await retry(fn, retryOpts);\n\n // Publish step_finish event (fire-and-forget)\n publishStepEvent('step_finish', key, 'run', {});\n\n // Save step output on success\n await saveStepOutput(key, result);\n\n if (span) {\n span.setStatus({ code: 1 /* OK */ });\n try {\n span.setAttribute('step.output', JSON.stringify(result));\n } catch {\n /* ignore */\n }\n span.setAttribute('step.status', 'completed');\n }\n\n return result;\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n const errorStack = error instanceof Error ? error.stack : undefined;\n\n logger.error(\n `Step '${key}' failed after ${String(retryOpts.maxRetries)} retries: ${errorMessage}`,\n {\n stepKey: key,\n error: errorMessage,\n stack: errorStack,\n }\n );\n\n if (span) {\n span.setStatus({ code: 2 /* ERROR */, message: errorMessage });\n if (error instanceof Error) {\n span.recordException(error);\n }\n span.setAttribute('step.status', 'failed');\n try {\n span.setAttribute('step.error', JSON.stringify({ message: errorMessage }));\n } catch {\n /* ignore */\n }\n }\n\n // Save error to step output\n await saveStepOutputWithError(key, errorMessage);\n\n throw new StepExecutionError(\n `Step execution failed after ${String(retryOpts.maxRetries)} retries: ${errorMessage}`\n );\n } finally {\n if (span) {\n setSpanContextInExecutionContext(execContextData, oldSpanContext);\n span.end();\n }\n }\n },\n\n async invoke<TPayload, TResult>(\n key: string,\n workflow: string | Workflow<TPayload, unknown, TResult>,\n payload: TPayload,\n options?: InvokeOptions\n ): Promise<WorkflowHandle<TResult>> {\n checkAborted();\n const workflowIdOrStr = typeof workflow === 'string' ? workflow : workflow.id;\n const [result] = await _invoke(key, workflowIdOrStr, payload, {\n ...options,\n waitForSubworkflow: false,\n });\n // result is serializable handle data { id, workflow_id, ... }\n const handleData = result as { id: string };\n return createWorkflowHandle<TResult>(orchestratorClient, handleData.id);\n },\n\n async invokeAndWait<TPayload, TResult>(\n key: string,\n workflow: string | Workflow<TPayload, unknown, TResult>,\n payload: TPayload,\n options?: InvokeOptions\n ): Promise<TResult> {\n checkAborted();\n const workflowId = typeof workflow === 'string' ? workflow : workflow.id;\n const [result, found] = await _invoke(key, workflowId, payload, {\n ...options,\n waitForSubworkflow: true,\n });\n if (found) {\n return result as TResult;\n }\n throw new WaitError(`Waiting for sub-workflow ${workflowId} to complete`, { workflowId });\n },\n\n async batchInvoke(\n key: string,\n items: BatchWorkflowInput[]\n ): Promise<WorkflowHandle<unknown>[]> {\n checkAborted();\n\n if (items.length === 0) return [];\n\n // Check for existing step output\n const existing = checkExistingStep(key);\n if (existing) {\n const cachedData = handleExistingStep(existing) as { id: string }[];\n return cachedData.map((d) => createWorkflowHandle<unknown>(orchestratorClient, d.id));\n }\n\n // Build batch request\n const workflows: BatchWorkflowEntry[] = items.map((item) => {\n const workflowId = typeof item.workflow === 'string' ? item.workflow : item.workflow.id;\n const entry: BatchWorkflowEntry = {\n workflowId,\n payload: item.payload,\n initialState: item.initialState,\n runTimeoutSeconds: item.runTimeoutSeconds,\n };\n // Extract queue info from Workflow config if available\n if (typeof item.workflow !== 'string') {\n const config = item.workflow.config;\n if (typeof config.queue === 'string') {\n entry.queueName = config.queue;\n } else if (config.queue) {\n entry.queueName = config.queue.name;\n entry.queueConcurrencyLimit = config.queue.concurrencyLimit;\n }\n }\n return entry;\n });\n\n const response = await orchestratorClient.batchInvokeWorkflows({\n workflows,\n deploymentId: execCtx.deploymentId,\n parentExecutionId: execCtx.executionId,\n rootExecutionId: execCtx.rootExecutionId,\n rootWorkflowId: execCtx.rootWorkflowId,\n sessionId: execCtx.sessionId,\n userId: execCtx.userId,\n waitForSubworkflow: false,\n otelTraceparent: getCurrentTraceparent(),\n });\n\n // Save serializable handle data\n const handleData = response.executions.map((exec, i) => {\n const item = items[i];\n const wf = item?.workflow;\n const wfId = typeof wf === 'string' ? wf : wf?.id;\n return {\n id: exec.execution_id,\n workflow_id: wfId,\n created_at: exec.created_at,\n parent_execution_id: execCtx.executionId,\n root_workflow_id: execCtx.rootWorkflowId,\n root_execution_id: execCtx.rootExecutionId,\n session_id: execCtx.sessionId,\n user_id: execCtx.userId,\n };\n });\n\n await saveStepOutput(key, handleData);\n return handleData.map((d) => createWorkflowHandle<unknown>(orchestratorClient, d.id));\n },\n\n async batchInvokeAndWait<T>(\n key: string,\n items: BatchWorkflowInput[]\n ): Promise<BatchStepResult<T>[]> {\n checkAborted();\n\n if (items.length === 0) return [];\n\n // Check for existing step output (matching Python batch_invoke_and_wait:\n // try handleExistingStep, fall back to raw outputs on error — because\n // the step-level success may be false when sub-workflows fail, even\n // though individual items carry their own success/error fields).\n const existing = checkExistingStep(key);\n if (existing) {\n let raw: unknown;\n try {\n raw = handleExistingStep(existing);\n } catch {\n raw = existing.outputs;\n }\n\n // The orchestrator stores batch results as [{workflow_id, success, result, error}, ...].\n // Preserve the wrapper (matching Python BatchStepResult) so callers can check success/error.\n if (Array.isArray(raw)) {\n return raw.map((item: unknown): BatchStepResult<T> => {\n if (item && typeof item === 'object' && 'success' in item) {\n const rec = item as Record<string, unknown>;\n return {\n workflowId: typeof rec['workflow_id'] === 'string' ? rec['workflow_id'] : '',\n success: rec['success'] === true,\n result: (rec['result'] ?? null) as T | null,\n error: typeof rec['error'] === 'string' ? rec['error'] : null,\n };\n }\n // Fallback: treat raw item as a successful result\n return { workflowId: '', success: true, result: item as T, error: null };\n });\n }\n return (raw as T[]).map((r) => ({ workflowId: '', success: true, result: r, error: null }));\n }\n\n // Build batch request with waitForSubworkflow=true\n const workflows: BatchWorkflowEntry[] = items.map((item) => {\n const workflowId = typeof item.workflow === 'string' ? item.workflow : item.workflow.id;\n const entry: BatchWorkflowEntry = {\n workflowId,\n payload: item.payload,\n initialState: item.initialState,\n runTimeoutSeconds: item.runTimeoutSeconds,\n };\n if (typeof item.workflow !== 'string') {\n const config = item.workflow.config;\n if (typeof config.queue === 'string') {\n entry.queueName = config.queue;\n } else if (config.queue) {\n entry.queueName = config.queue.name;\n entry.queueConcurrencyLimit = config.queue.concurrencyLimit;\n }\n }\n return entry;\n });\n\n await orchestratorClient.batchInvokeWorkflows({\n workflows,\n deploymentId: execCtx.deploymentId,\n parentExecutionId: execCtx.executionId,\n rootExecutionId: execCtx.rootExecutionId,\n rootWorkflowId: execCtx.rootWorkflowId,\n stepKey: key,\n sessionId: execCtx.sessionId,\n userId: execCtx.userId,\n waitForSubworkflow: true,\n otelTraceparent: getCurrentTraceparent(),\n });\n\n // Pause execution — orchestrator resumes when all sub-workflows complete\n const workflowIds = items\n .map((item) => (typeof item.workflow === 'string' ? item.workflow : item.workflow.id))\n .join(', ');\n throw new WaitError(`Waiting for sub-workflows [${workflowIds}] to complete`, {\n workflowIds: workflowIds.split(', '),\n });\n },\n\n async waitFor(key: string, options: WaitForOptions): Promise<void> {\n checkAborted();\n\n const existing = checkExistingStep(key);\n if (existing) {\n handleExistingStep(existing);\n return;\n }\n\n // Calculate total wait seconds\n let totalSeconds = 0;\n if (options.seconds) totalSeconds += options.seconds;\n if (options.minutes) totalSeconds += options.minutes * 60;\n if (options.hours) totalSeconds += options.hours * 3600;\n if (options.days) totalSeconds += options.days * 86400;\n if (options.weeks) totalSeconds += options.weeks * 604800;\n\n if (totalSeconds <= 0) {\n await saveStepOutputWithError(key, 'Wait duration must be positive');\n throw new StepExecutionError('Wait duration must be positive');\n }\n\n const waitUntil = new Date(Date.now() + totalSeconds * 1000);\n\n // Add span event\n addSpanEventFromExecutionContext('step.wait_for', {\n 'step.key': key,\n 'wait.seconds': String(totalSeconds),\n 'wait.until': waitUntil.toISOString(),\n });\n\n // Get wait threshold\n const waitThreshold = Number(process.env['POLOS_WAIT_THRESHOLD_SECONDS'] ?? '10');\n\n if (totalSeconds <= waitThreshold) {\n // Short wait — sleep locally\n await new Promise((resolve) => setTimeout(resolve, totalSeconds * 1000));\n await saveStepOutput(key, { wait_until: waitUntil.toISOString() });\n return;\n }\n\n // Long wait — pause execution via orchestrator\n await orchestratorClient.setWaiting(\n execCtx.executionId,\n {\n stepKey: key,\n waitType: 'time',\n waitUntil: waitUntil.toISOString(),\n },\n workerId\n );\n\n throw new WaitError(`Waiting until ${waitUntil.toISOString()}`, {\n waitUntil: waitUntil.toISOString(),\n });\n },\n\n async waitUntil(key: string, date: Date): Promise<void> {\n checkAborted();\n\n const existing = checkExistingStep(key);\n if (existing) {\n handleExistingStep(existing);\n return;\n }\n\n const now = Date.now();\n const waitSeconds = (date.getTime() - now) / 1000;\n\n if (waitSeconds < 0) {\n await saveStepOutputWithError(key, `Wait date ${date.toISOString()} is in the past`);\n throw new StepExecutionError(`Wait date ${date.toISOString()} is in the past`);\n }\n\n // Add span event\n addSpanEventFromExecutionContext('step.wait_until', {\n 'step.key': key,\n 'wait.until': date.toISOString(),\n });\n\n const waitThreshold = Number(process.env['POLOS_WAIT_THRESHOLD_SECONDS'] ?? '10');\n\n if (waitSeconds <= waitThreshold) {\n // Short wait — sleep locally\n await new Promise((resolve) => setTimeout(resolve, waitSeconds * 1000));\n await saveStepOutput(key, { wait_until: date.toISOString() });\n return;\n }\n\n // Long wait — pause execution via orchestrator\n await orchestratorClient.setWaiting(\n execCtx.executionId,\n {\n stepKey: key,\n waitType: 'time',\n waitUntil: date.toISOString(),\n },\n workerId\n );\n\n throw new WaitError(`Waiting until ${date.toISOString()}`, { waitUntil: date.toISOString() });\n },\n\n async waitForEvent<T>(key: string, options: WaitForEventOptions): Promise<T> {\n checkAborted();\n\n const existing = checkExistingStep(key);\n if (existing) {\n return handleExistingStep(existing) as T;\n }\n\n // Add span event\n const eventAttrs: Record<string, string> = {\n 'step.key': key,\n 'wait.topic': options.topic,\n };\n if (options.timeout !== undefined) {\n eventAttrs['wait.timeout_seconds'] = String(options.timeout);\n }\n addSpanEventFromExecutionContext('step.wait_for_event', eventAttrs);\n\n // Calculate expires_at if timeout provided (timeout is in seconds)\n const expiresAt =\n options.timeout !== undefined\n ? new Date(Date.now() + options.timeout * 1000).toISOString()\n : undefined;\n\n // Set waiting state\n await orchestratorClient.setWaiting(\n execCtx.executionId,\n {\n stepKey: key,\n waitType: 'event',\n waitTopic: options.topic,\n waitUntil: expiresAt,\n expiresAt,\n },\n workerId\n );\n\n throw new WaitError(`Waiting for event on topic: ${options.topic}`, { topic: options.topic });\n },\n\n async publishEvent(key: string, options: PublishEventOptions): Promise<void> {\n checkAborted();\n\n const existing = checkExistingStep(key);\n if (existing) {\n handleExistingStep(existing);\n return;\n }\n\n await orchestratorClient.publishEvent({\n topic: options.topic,\n events: [\n {\n eventType: options.type,\n data: options.data,\n },\n ],\n executionId: execCtx.executionId,\n rootExecutionId: execCtx.rootExecutionId,\n });\n\n // Save with null result\n await saveStepOutput(key, null);\n },\n\n async publishWorkflowEvent(\n key: string,\n options: { data: unknown; type?: string }\n ): Promise<void> {\n const topic = `workflow/${execCtx.rootWorkflowId}/${execCtx.rootExecutionId}`;\n // Delegate to publishEvent\n return this.publishEvent(key, { topic, ...options });\n },\n\n async suspend<T, R>(key: string, options?: SuspendOptions<T>): Promise<R> {\n checkAborted();\n\n const existing = checkExistingStep(key);\n if (existing) {\n return handleExistingStep(existing) as R;\n }\n\n // Publish suspend event on workflow topic\n const topic = `workflow/${execCtx.rootWorkflowId}/${execCtx.rootExecutionId}`;\n const approvalUrl = `${orchestratorClient.getApiUrl()}/approve/${execCtx.rootExecutionId}/${key}`;\n const eventData =\n options?.data != null && typeof options.data === 'object' && !Array.isArray(options.data)\n ? { ...(options.data as Record<string, unknown>), _approval_url: approvalUrl }\n : { _original: options?.data, _approval_url: approvalUrl };\n await orchestratorClient.publishEvent({\n topic,\n events: [\n {\n eventType: `suspend_${key}`,\n data: eventData,\n },\n ],\n executionId: execCtx.executionId,\n rootExecutionId: execCtx.rootExecutionId,\n });\n\n // Calculate expires_at (timeout is in seconds)\n const expiresAt =\n options?.timeout !== undefined\n ? new Date(Date.now() + options.timeout * 1000).toISOString()\n : undefined;\n\n // Set waiting state\n await orchestratorClient.setWaiting(\n execCtx.executionId,\n {\n stepKey: key,\n waitType: 'suspend',\n waitTopic: topic,\n waitUntil: expiresAt,\n expiresAt,\n },\n workerId\n );\n\n // Notify channels — after state is persisted, before pausing execution\n if (channels?.length) {\n const eventRecord = eventData as Record<string, unknown>;\n const formData = eventRecord['_form'] as Record<string, unknown> | undefined;\n const notifyConfig = eventRecord['_notify'] as Record<string, unknown> | undefined;\n\n const titleVal = formData?.['title'] as string | undefined;\n const notifyMessage = notifyConfig?.['message'] as string | undefined;\n const formDescription = formData?.['description'] as string | undefined;\n const descriptionVal = notifyMessage ?? formDescription;\n const sourceVal = eventRecord['_source'] as string | undefined;\n const toolVal = eventRecord['_tool'] as string | undefined;\n const contextVal = formData?.['context'] as Record<string, unknown> | undefined;\n const formFieldsVal = formData?.['fields'] as Record<string, unknown>[] | undefined;\n const expiresAtVal = (formData?.['expiresAt'] ?? formData?.['expires_at']) as\n | string\n | undefined;\n\n const notification: SuspendNotification = {\n workflowId: execCtx.rootWorkflowId,\n executionId: execCtx.rootExecutionId,\n stepKey: key,\n approvalUrl,\n };\n if (titleVal !== undefined) notification.title = titleVal;\n if (descriptionVal !== undefined) notification.description = descriptionVal;\n if (sourceVal !== undefined) notification.source = sourceVal;\n if (toolVal !== undefined) notification.tool = toolVal;\n if (contextVal !== undefined) notification.context = contextVal;\n if (formFieldsVal !== undefined) notification.formFields = formFieldsVal;\n if (expiresAtVal !== undefined) notification.expiresAt = expiresAtVal;\n if (channelContext !== undefined) {\n notification.channelContext = channelContext as ChannelContext;\n }\n\n // Fire all notifications concurrently — failures logged, never block suspend\n await Promise.allSettled(\n channels.map(async (ch) => {\n try {\n // Per-channel overrides: merge _notify.[channelId] overrides\n // + inject channelContext.source for matching channel\n let overrides = notifyConfig?.[ch.id] as Record<string, unknown> | undefined;\n if (ch.id === channelContext?.channelId) {\n overrides = { ...channelContext.source, ...overrides };\n }\n const n =\n overrides !== undefined\n ? { ...notification, channelOverrides: overrides }\n : notification;\n await ch.notify(n);\n } catch (err) {\n logger.warn(`Channel ${ch.id} notification failed`, { error: String(err) });\n }\n })\n );\n }\n\n throw new WaitError(`Waiting for resume event: ${topic}`, { topic });\n },\n\n async resume(key: string, options: ResumeOptions): Promise<void> {\n const topic = `workflow/${options.suspendWorkflowId}/${options.suspendExecutionId}`;\n // Delegate to publishEvent\n return this.publishEvent(key, {\n topic,\n type: `resume_${options.suspendStepKey}`,\n data: options.data,\n });\n },\n\n async uuid(key: string): Promise<string> {\n const existing = checkExistingStep(key);\n if (existing) {\n return handleExistingStep(existing) as string;\n }\n\n const generatedUuid = randomUUID();\n await saveStepOutput(key, generatedUuid);\n return generatedUuid;\n },\n\n async now(key: string): Promise<number> {\n const existing = checkExistingStep(key);\n if (existing) {\n return existing.outputs as number;\n }\n\n const timestamp = Date.now();\n await saveStepOutput(key, timestamp);\n return timestamp;\n },\n\n async random(key: string): Promise<number> {\n const existing = checkExistingStep(key);\n if (existing) {\n return handleExistingStep(existing) as number;\n }\n\n const randomValue = Math.random();\n await saveStepOutput(key, randomValue);\n return randomValue;\n },\n\n async agentInvoke(key: string, config: AgentRunConfig): Promise<WorkflowHandle<unknown>> {\n checkAborted();\n\n const payload: Record<string, unknown> = {\n input: config.input,\n streaming: config.streaming,\n session_id: execCtx.sessionId,\n user_id: execCtx.userId,\n ...config.kwargs,\n };\n\n const [result] = await _invoke(key, config.agent, payload, {\n initialState: config.initialState,\n waitForSubworkflow: false,\n runTimeoutSeconds: config.runTimeoutSeconds,\n });\n\n const handleData = result as { id: string };\n return createWorkflowHandle<unknown>(orchestratorClient, handleData.id);\n },\n\n async agentInvokeAndWait(key: string, config: AgentRunConfig): Promise<unknown> {\n checkAborted();\n\n const payload: Record<string, unknown> = {\n input: config.input,\n streaming: config.streaming,\n session_id: execCtx.sessionId,\n user_id: execCtx.userId,\n ...config.kwargs,\n };\n\n const [result, found] = await _invoke(key, config.agent, payload, {\n initialState: config.initialState,\n waitForSubworkflow: true,\n runTimeoutSeconds: config.runTimeoutSeconds,\n });\n\n if (found) {\n // Step output is already deserialized JSON.\n return result;\n }\n\n throw new WaitError(`Waiting for agent workflow '${config.agent.id}' to complete`, {\n agentId: config.agent.id,\n });\n },\n\n async batchAgentInvoke(\n key: string,\n configs: AgentRunConfig[]\n ): Promise<WorkflowHandle<unknown>[]> {\n checkAborted();\n\n const workflows: BatchWorkflowInput[] = configs.map((config) => ({\n workflow: config.agent,\n payload: {\n input: config.input,\n streaming: config.streaming,\n session_id: execCtx.sessionId,\n user_id: execCtx.userId,\n ...config.kwargs,\n },\n initialState: config.initialState,\n runTimeoutSeconds: config.runTimeoutSeconds,\n }));\n\n // Delegate to batchInvoke\n return this.batchInvoke(key, workflows);\n },\n\n async batchAgentInvokeAndWait<T>(\n key: string,\n configs: AgentRunConfig[]\n ): Promise<BatchStepResult<T>[]> {\n checkAborted();\n\n const workflows: BatchWorkflowInput[] = configs.map((config) => ({\n workflow: config.agent,\n payload: {\n input: config.input,\n streaming: config.streaming,\n session_id: execCtx.sessionId,\n user_id: execCtx.userId,\n ...config.kwargs,\n },\n initialState: config.initialState,\n runTimeoutSeconds: config.runTimeoutSeconds,\n }));\n\n // Delegate to batchInvokeAndWait\n return this.batchInvokeAndWait<T>(key, workflows);\n },\n\n async trace<T>(\n name: string,\n fn: (span: unknown) => Promise<T>,\n attributes?: Record<string, string | number | boolean>\n ): Promise<T> {\n const tracer = getTracer();\n if (!tracer) return fn(undefined);\n\n const execContextData = getExecutionContext();\n const parentContext = getParentSpanContextFromExecutionContext(execContextData);\n const spanOpts = attributes ? { attributes } : {};\n const span = tracer.startSpan(name, spanOpts, parentContext);\n\n const oldSpanContext = getSpanContextFromExecutionContext(execContextData);\n setSpanContextInExecutionContext(execContextData, span.spanContext());\n\n try {\n const result = await fn(span);\n span.setStatus({ code: 1 /* OK */ });\n return result;\n } catch (e) {\n span.setStatus({ code: 2 /* ERROR */, message: String(e) });\n if (e instanceof Error) {\n span.recordException(e);\n }\n throw e;\n } finally {\n setSpanContextInExecutionContext(execContextData, oldSpanContext);\n span.end();\n }\n },\n };\n}\n\n/**\n * Execute a workflow.\n *\n * 1. Loads cached step outputs for replay\n * 2. Initializes state\n * 3. Sets up tracing context\n * 4. Publishes start event\n * 5. Executes onStart hooks\n * 6. Calls the workflow handler\n * 7. Executes onEnd hooks\n * 8. Publishes finish event\n * 9. Returns (result, finalState)\n */\nexport async function executeWorkflow(options: ExecuteWorkflowOptions): Promise<ExecutionResult> {\n const {\n workflow,\n payload,\n context,\n orchestratorClient,\n workerId,\n abortSignal,\n channels,\n sandboxManager,\n channelContext,\n } = options;\n\n let state: Record<string, unknown> = {};\n let validatedPayload = payload;\n\n // Determine workflow type from config (default: \"workflow\")\n const workflowType = workflow.config.workflowType ?? 'workflow';\n\n try {\n // Load cached step outputs for replay\n const cachedSteps = new Map<string, StepOutput>();\n try {\n const stepOutputs = await orchestratorClient.getAllStepOutputs(context.executionId, workerId);\n for (const output of stepOutputs) {\n cachedSteps.set(output.stepKey, output);\n }\n if (stepOutputs.length > 0) {\n logger.info(`Loaded ${String(stepOutputs.length)} cached step outputs for replay`);\n }\n } catch (err) {\n logger.warn('Failed to load cached step outputs', { error: String(err) });\n }\n\n // Initialize state\n if (context.initialState) {\n state = context.initialState;\n } else if (workflow.stateSchema) {\n state = initializeState(workflow.stateSchema as ZodType<Record<string, unknown>>);\n }\n\n // Validate payload if schema provided\n if (workflow.payloadSchema) {\n try {\n validatedPayload = validateState(payload, workflow.payloadSchema);\n } catch (err) {\n logger.error(`Payload validation failed for workflow \"${workflow.id}\"`, {\n payload: JSON.stringify(payload).slice(0, 500),\n error: String(err),\n });\n throw err;\n }\n }\n\n // Compute effective root IDs\n const rootExecutionId = context.rootExecutionId ?? context.executionId;\n const rootWorkflowId = context.rootWorkflowId ?? workflow.id;\n\n // Create step helper\n const step = createOrchestratorStepHelper(\n orchestratorClient,\n cachedSteps,\n {\n workflowId: workflow.id,\n executionId: context.executionId,\n deploymentId: context.deploymentId,\n sessionId: context.sessionId,\n userId: context.userId,\n rootExecutionId,\n rootWorkflowId,\n otelTraceparent: context.otelTraceparent,\n },\n workerId,\n abortSignal,\n channels,\n channelContext\n );\n\n // Create workflow context\n let ctx: WorkflowContext<Record<string, unknown>>;\n\n if (workflowType === 'agent') {\n // Build AgentContext for agents\n const agentWf = workflow as AgentWorkflow;\n const agentCtx: AgentContext<Record<string, unknown>> = {\n workflowId: workflow.id,\n executionId: context.executionId,\n deploymentId: context.deploymentId,\n sessionId: context.sessionId,\n userId: context.userId,\n parentExecutionId: context.parentExecutionId,\n rootExecutionId,\n rootWorkflowId,\n retryCount: context.retryCount,\n createdAt: context.createdAt,\n workflowType,\n otelTraceparent: context.otelTraceparent,\n otelSpanId: context.otelSpanId,\n state,\n step,\n agentId: workflow.id,\n model: getModelId(agentWf.llm.model),\n provider: getModelProvider(agentWf.llm.model),\n systemPrompt: agentWf.agentConfig.systemPrompt,\n tools: agentWf.tools,\n temperature: agentWf.agentConfig.temperature,\n maxTokens: agentWf.agentConfig.maxOutputTokens,\n };\n ctx = agentCtx;\n } else {\n // WorkflowContext for regular workflows and tools\n ctx = {\n workflowId: workflow.id,\n executionId: context.executionId,\n deploymentId: context.deploymentId,\n sessionId: context.sessionId,\n userId: context.userId,\n parentExecutionId: context.parentExecutionId,\n rootExecutionId,\n rootWorkflowId,\n retryCount: context.retryCount,\n createdAt: context.createdAt,\n workflowType,\n otelTraceparent: context.otelTraceparent,\n otelSpanId: context.otelSpanId,\n state,\n step,\n };\n }\n\n // --- Set up OpenTelemetry tracing ---\n const tracer = getTracer();\n let span: Span | undefined;\n const isRootWorkflow = !context.parentExecutionId;\n\n if (tracer) {\n const spanName = `${workflowType}.${workflow.id}`;\n\n // Build span attributes\n const spanAttributes: Record<string, string | number> = {\n [`${workflowType}.id`]: workflow.id,\n [`${workflowType}.execution_id`]: context.executionId,\n [`${workflowType}.root_execution_id`]: rootExecutionId,\n [`${workflowType}.deployment_id`]: context.deploymentId,\n [`${workflowType}.type`]: workflowType,\n [`${workflowType}.retry_count`]: context.retryCount,\n };\n if (context.parentExecutionId) {\n spanAttributes[`${workflowType}.parent_execution_id`] = context.parentExecutionId;\n }\n if (context.sessionId) {\n spanAttributes[`${workflowType}.session_id`] = context.sessionId;\n }\n if (context.userId) {\n spanAttributes[`${workflowType}.user_id`] = context.userId;\n }\n if (context.otelSpanId) {\n spanAttributes[`${workflowType}.previous_span_id`] = context.otelSpanId;\n }\n\n // Determine parent context\n let otelParentContext: Context | undefined;\n if (context.otelTraceparent) {\n // Sub-workflow: extract parent from traceparent\n otelParentContext = createContextFromTraceparent(context.otelTraceparent);\n } else {\n // Root workflow: deterministic trace ID\n const traceIdHex = generateTraceIdFromExecutionId(rootExecutionId);\n otelParentContext = createContextWithTraceId(traceIdHex);\n }\n\n // For root workflows, activate context so IdGenerator reads trace ID\n if (isRootWorkflow && otelParentContext) {\n // Use context.with to make the deterministic trace ID available\n span = otelContext.with(otelParentContext, () => {\n return tracer.startSpan(spanName, { attributes: spanAttributes }, otelParentContext);\n });\n } else {\n span = tracer.startSpan(spanName, { attributes: spanAttributes }, otelParentContext);\n }\n }\n\n // Topic for workflow events\n const topic = `workflow/${ctx.rootWorkflowId}/${ctx.rootExecutionId}`;\n\n // Set input and initial state on span\n if (span) {\n try {\n span.setAttribute(`${workflowType}.input`, JSON.stringify(validatedPayload));\n } catch {\n /* ignore */\n }\n try {\n span.setAttribute(`${workflowType}.initial_state`, JSON.stringify(state));\n } catch {\n /* ignore */\n }\n\n // Add resumed event if this is a resumed workflow\n if (context.otelSpanId) {\n span.addEvent(`${workflowType}.resumed`);\n }\n }\n\n // Build execution context data with span context so hooks and handler\n // can create properly-parented OTel spans via getExecutionContext().\n const spanCtx = span?.spanContext();\n const execContextData = {\n executionId: context.executionId,\n workflowId: workflow.id,\n rootExecutionId,\n sessionId: context.sessionId,\n sandboxManager,\n orchestratorClient,\n _otelSpanContext: spanCtx,\n _otelTraceId: spanCtx?.traceId,\n _otelSpanId: spanCtx?.spanId,\n };\n\n try {\n // Run everything (hooks + handler) within execution context so that\n // ctx.step.run() inside hooks creates spans with the correct trace ID.\n return await runInExecutionContext(execContextData, async () => {\n // Publish start event\n await step.publishEvent('publish_start', {\n topic,\n type: `${workflowType}_start`,\n data: {\n payload: validatedPayload,\n _metadata: {\n execution_id: ctx.executionId,\n workflow_id: ctx.workflowId,\n },\n },\n });\n\n // Execute onStart hooks\n if (workflow.config.onStart) {\n const hookResult = await executeHookChain(normalizeHooks(workflow.config.onStart), {\n ctx,\n hookName: 'on_start',\n payload: validatedPayload,\n phase: 'onStart',\n });\n\n if (!hookResult.success) {\n if (span) {\n span.setStatus({\n code: 2 /* ERROR */,\n message: hookResult.error ?? 'onStart hook failed',\n });\n span.setAttribute(`${workflowType}.status`, 'failed');\n }\n return {\n success: false,\n error: hookResult.error ?? 'onStart hook failed',\n retryable: false,\n finalState: state,\n };\n }\n\n // Apply modified payload\n validatedPayload = hookResult.payload;\n }\n\n // Check for cancellation\n if (abortSignal?.aborted) {\n if (span) {\n span.setStatus({ code: 2 /* ERROR */, message: 'Execution cancelled' });\n span.setAttribute(`${workflowType}.status`, 'cancelled');\n }\n return {\n success: false,\n error: 'Execution cancelled',\n retryable: false,\n finalState: state,\n };\n }\n\n // Execute workflow handler\n const result = await workflow.handler(ctx, validatedPayload);\n\n // Extract final state\n if (workflow.stateSchema) {\n state = validateState(\n ctx.state,\n workflow.stateSchema as ZodType<Record<string, unknown>>\n );\n } else {\n state = ctx.state;\n }\n\n // Execute onEnd hooks\n let finalResult: unknown = result;\n if (workflow.config.onEnd) {\n const hookResult = await executeHookChain(normalizeHooks(workflow.config.onEnd), {\n ctx,\n hookName: 'on_end',\n payload: validatedPayload,\n output: result,\n phase: 'onEnd',\n });\n\n if (!hookResult.success) {\n if (span) {\n span.setStatus({\n code: 2 /* ERROR */,\n message: hookResult.error ?? 'onEnd hook failed',\n });\n span.setAttribute(`${workflowType}.status`, 'failed');\n }\n return {\n success: false,\n error: hookResult.error ?? 'onEnd hook failed',\n retryable: false,\n finalState: state,\n };\n }\n\n // Apply modified output\n if (hookResult.output !== undefined) {\n finalResult = hookResult.output;\n }\n }\n\n // Publish finish event\n await step.publishEvent('publish_finish', {\n topic,\n type: `${workflowType}_finish`,\n data: {\n result: finalResult,\n _metadata: {\n execution_id: ctx.executionId,\n workflow_id: ctx.workflowId,\n },\n },\n });\n\n // Success span attributes\n if (span) {\n span.setStatus({ code: 1 /* OK */ });\n span.setAttribute(`${workflowType}.status`, 'completed');\n try {\n span.setAttribute(`${workflowType}.output`, JSON.stringify(finalResult));\n } catch {\n /* ignore */\n }\n try {\n const resultStr = JSON.stringify(finalResult);\n span.setAttribute(`${workflowType}.result_size`, resultStr.length);\n } catch {\n /* ignore */\n }\n try {\n span.setAttribute(`${workflowType}.final_state`, JSON.stringify(state));\n } catch {\n /* ignore */\n }\n }\n\n return {\n success: true,\n result: finalResult,\n finalState: state,\n };\n }); // end runInExecutionContext\n } catch (error) {\n // WaitError — execution is paused, not a failure\n if (isWaitError(error)) {\n if (span) {\n span.setStatus({ code: 1 /* OK */ });\n span.setAttribute(`${workflowType}.status`, 'waiting');\n span.addEvent(`${workflowType}.waiting`, { reason: error.message });\n\n // Save span ID for resume linkage\n const spanContext = span.spanContext();\n if (spanContext.spanId) {\n try {\n await orchestratorClient.updateExecutionOtelSpanId(\n context.executionId,\n spanContext.spanId\n );\n } catch (e) {\n logger.warn(`Failed to update otel_span_id: ${String(e)}`);\n }\n }\n }\n\n return {\n success: false,\n waiting: true,\n error: error.message,\n retryable: false,\n finalState: state,\n };\n }\n\n const errorMessage = error instanceof Error ? error.message : String(error);\n const stack = error instanceof Error ? error.stack : undefined;\n\n // Check if cancelled\n if (errorMessage === 'Execution cancelled' || abortSignal?.aborted) {\n if (span) {\n span.setStatus({ code: 2 /* ERROR */, message: 'Execution cancelled' });\n span.setAttribute(`${workflowType}.status`, 'cancelled');\n }\n return {\n success: false,\n error: 'Execution cancelled',\n retryable: false,\n finalState: state,\n };\n }\n\n logger.error(`${workflowType} '${workflow.id}' execution failed: ${errorMessage}`, {\n workflowId: workflow.id,\n executionId: context.executionId,\n workflowType,\n error: errorMessage,\n stack,\n });\n\n // Error span attributes\n if (span) {\n span.setStatus({ code: 2 /* ERROR */, message: errorMessage });\n if (error instanceof Error) {\n span.recordException(error);\n }\n span.setAttribute(`${workflowType}.status`, 'failed');\n try {\n span.setAttribute(\n `${workflowType}.error`,\n JSON.stringify({ message: errorMessage, stack })\n );\n } catch {\n /* ignore */\n }\n }\n\n // StepExecutionError and \"tool\" workflows are not retryable\n const retryable =\n !(error instanceof StepExecutionError) && workflow.config.workflowType !== 'tool';\n\n return {\n success: false,\n error: errorMessage,\n stack,\n retryable,\n finalState: state,\n };\n } finally {\n if (span) {\n span.end();\n }\n }\n } catch (error) {\n // Outer catch for errors before span creation (step loading, state init, etc.)\n if (isWaitError(error)) {\n return {\n success: false,\n waiting: true,\n error: error.message,\n retryable: false,\n finalState: state,\n };\n }\n\n const errorMessage = error instanceof Error ? error.message : String(error);\n const stack = error instanceof Error ? error.stack : undefined;\n\n if (errorMessage === 'Execution cancelled' || abortSignal?.aborted) {\n return {\n success: false,\n error: 'Execution cancelled',\n retryable: false,\n finalState: state,\n };\n }\n\n logger.error(\n `${workflow.config.workflowType ?? 'workflow'} '${workflow.id}' execution failed: ${errorMessage}`,\n {\n workflowId: workflow.id,\n executionId: context.executionId,\n workflowType: workflow.config.workflowType ?? 'workflow',\n error: errorMessage,\n stack,\n }\n );\n\n const retryable =\n !(error instanceof StepExecutionError) && workflow.config.workflowType !== 'tool';\n\n return {\n success: false,\n error: errorMessage,\n stack,\n retryable,\n finalState: state,\n };\n }\n}\n\n/**\n * Serialize the final state for persistence.\n */\nexport function serializeFinalState(state: Record<string, unknown>): string {\n return serializeState(state);\n}\n","/**\n * Output utilities for the execution framework.\n *\n * Provides functions for truncating large outputs, detecting binary content,\n * parsing grep output, and stripping ANSI escape codes.\n */\n\nimport type { GrepMatch } from './types.js';\n\n/** Default maximum output characters */\nconst DEFAULT_MAX_CHARS = 100_000;\n\n/** Head portion of truncated output (20% of max) */\nconst HEAD_RATIO = 0.2;\n\n/**\n * Truncate output that exceeds the maximum character limit.\n *\n * Keeps the first 20K characters (head) and last 80K characters (tail)\n * of a 100K max, with a truncation message in between.\n */\nexport function truncateOutput(\n output: string,\n maxChars?: number\n): { text: string; truncated: boolean } {\n const max = maxChars ?? DEFAULT_MAX_CHARS;\n if (output.length <= max) {\n return { text: output, truncated: false };\n }\n\n const headSize = Math.floor(max * HEAD_RATIO);\n const tailSize = max - headSize;\n const omitted = output.length - headSize - tailSize;\n\n const head = output.slice(0, headSize);\n const tail = output.slice(-tailSize);\n const text = `${head}\\n\\n--- truncated ${String(omitted)} characters ---\\n\\n${tail}`;\n\n return { text, truncated: true };\n}\n\n/**\n * Detect binary content by checking for null bytes in the first 8KB.\n */\nexport function isBinary(buffer: Buffer): boolean {\n const checkLength = Math.min(buffer.length, 8192);\n for (let i = 0; i < checkLength; i++) {\n if (buffer[i] === 0) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Parse `grep -rn` output into structured GrepMatch objects.\n *\n * Expected format: `filepath:linenum:matched text`\n */\nexport function parseGrepOutput(output: string): GrepMatch[] {\n if (!output.trim()) {\n return [];\n }\n\n const matches: GrepMatch[] = [];\n const lines = output.split('\\n');\n\n for (const line of lines) {\n if (!line) continue;\n\n // Match format: path:line:text\n const match = /^(.+?):(\\d+):(.*)$/.exec(line);\n if (match?.[1] && match[2] && match[3] !== undefined) {\n matches.push({ path: match[1], line: parseInt(match[2], 10), text: match[3] });\n }\n }\n\n return matches;\n}\n\n/**\n * Strip ANSI escape codes from text.\n */\nexport function stripAnsi(text: string): string {\n // Matches all ANSI escape sequences\n // eslint-disable-next-line no-control-regex\n return text.replace(/\\x1b\\[[0-9;]*[a-zA-Z]/g, '');\n}\n","/**\n * Docker execution environment.\n *\n * Runs commands inside a Docker container and accesses files via bind mount\n * for optimal performance. The container runs `sleep infinity` and commands\n * are executed via `docker exec`.\n */\n\nimport { spawn } from 'node:child_process';\nimport * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { randomUUID } from 'node:crypto';\nimport type {\n ExecutionEnvironment,\n ExecOptions,\n ExecResult,\n GlobOptions,\n GrepOptions,\n GrepMatch,\n EnvironmentInfo,\n DockerEnvironmentConfig,\n} from './types.js';\nimport { truncateOutput, isBinary, parseGrepOutput, stripAnsi } from './output.js';\n\n/** Default container working directory */\nconst DEFAULT_CONTAINER_WORKDIR = '/workspace';\n\n/** Default command timeout in seconds */\nconst DEFAULT_TIMEOUT_SECONDS = 300;\n\n/** Default maximum output characters */\nconst DEFAULT_MAX_OUTPUT_CHARS = 100_000;\n\n/**\n * Execute a command via child_process.spawn and capture output.\n * @internal\n */\nfunction spawnCommand(\n command: string,\n args: string[],\n options?: { timeout?: number | undefined; stdin?: string | undefined }\n): Promise<{ exitCode: number; stdout: string; stderr: string }> {\n return new Promise((resolve, reject) => {\n let settled = false;\n const settle = (fn: () => void) => {\n if (!settled) {\n settled = true;\n fn();\n }\n };\n\n const proc = spawn(command, args, { stdio: ['pipe', 'pipe', 'pipe'] });\n\n let stdout = '';\n let stderr = '';\n let killed = false;\n\n proc.stdout.on('data', (data: Buffer) => {\n stdout += data.toString();\n });\n\n proc.stderr.on('data', (data: Buffer) => {\n stderr += data.toString();\n });\n\n // Guard against stream errors leaving the promise unresolved\n proc.stdin.on('error', () => {\n // Ignore stdin errors — the process may have exited before we finished writing.\n // The 'close' event will still fire and resolve the promise.\n });\n proc.stdout.on('error', () => {\n /* noop */\n });\n proc.stderr.on('error', () => {\n /* noop */\n });\n\n const timeoutMs = (options?.timeout ?? DEFAULT_TIMEOUT_SECONDS) * 1000;\n const timer = setTimeout(() => {\n killed = true;\n proc.kill('SIGKILL');\n }, timeoutMs);\n\n proc.on('close', (code) => {\n clearTimeout(timer);\n settle(() => {\n if (killed) {\n resolve({\n exitCode: 137,\n stdout,\n stderr: stderr + '\\n[Process killed: timeout exceeded]',\n });\n } else {\n resolve({ exitCode: code ?? 1, stdout, stderr });\n }\n });\n });\n\n proc.on('error', (err) => {\n clearTimeout(timer);\n settle(() => {\n reject(err);\n });\n });\n\n if (options?.stdin) {\n proc.stdin.write(options.stdin, () => {\n proc.stdin.end();\n });\n } else {\n proc.stdin.end();\n }\n });\n}\n\n/**\n * Docker-based execution environment.\n *\n * Creates a persistent Docker container with a bind-mounted workspace.\n * Commands run inside the container via `docker exec`, while file\n * operations use the host filesystem through the bind mount for speed.\n */\nexport class DockerEnvironment implements ExecutionEnvironment {\n readonly type = 'docker' as const;\n\n private containerId: string | null = null;\n private containerName: string;\n private readonly config: DockerEnvironmentConfig;\n private readonly containerWorkdir: string;\n private readonly maxOutputChars: number;\n\n constructor(config: DockerEnvironmentConfig, maxOutputChars?: number) {\n this.config = config;\n this.containerWorkdir = config.containerWorkdir ?? DEFAULT_CONTAINER_WORKDIR;\n this.containerName = `polos-sandbox-${randomUUID().slice(0, 8)}`;\n this.maxOutputChars = maxOutputChars ?? DEFAULT_MAX_OUTPUT_CHARS;\n }\n\n /**\n * Get the container name (useful for health checking and identification).\n */\n getContainerName(): string {\n return this.containerName;\n }\n\n async initialize(labels?: Record<string, string>): Promise<void> {\n const args = [\n 'run',\n '-d',\n '--name',\n this.containerName,\n '-v',\n `${this.config.workspaceDir}:${this.containerWorkdir}:rw`,\n '-w',\n this.containerWorkdir,\n ];\n\n if (this.config.memory) {\n args.push('--memory', this.config.memory);\n }\n if (this.config.cpus) {\n args.push('--cpus', this.config.cpus);\n }\n args.push('--network', this.config.network ?? 'none');\n\n if (this.config.env) {\n for (const [key, value] of Object.entries(this.config.env)) {\n args.push('-e', `${key}=${value}`);\n }\n }\n\n if (labels) {\n for (const [key, value] of Object.entries(labels)) {\n args.push('--label', `${key}=${value}`);\n }\n }\n\n args.push(this.config.image, 'sleep', 'infinity');\n\n const result = await spawnCommand('docker', args, { timeout: 60 });\n if (result.exitCode !== 0) {\n throw new Error(`Failed to create Docker container: ${result.stderr.trim()}`);\n }\n this.containerId = result.stdout.trim().slice(0, 12);\n\n // Run setup command if provided\n if (this.config.setupCommand) {\n const setupResult = await this.exec(this.config.setupCommand);\n if (setupResult.exitCode !== 0) {\n throw new Error(\n `Setup command failed (exit ${String(setupResult.exitCode)}): ${setupResult.stderr.trim()}`\n );\n }\n }\n }\n\n async exec(command: string, opts?: ExecOptions): Promise<ExecResult> {\n this.assertInitialized();\n\n // Only use -i (interactive/keep-stdin-open) when stdin data is provided.\n // Without stdin data, -i can cause docker exec to hang waiting for EOF.\n const args = opts?.stdin ? ['exec', '-i'] : ['exec'];\n\n // Set working directory\n const cwd = opts?.cwd ?? this.containerWorkdir;\n args.push('-w', cwd);\n\n // Set environment variables\n if (opts?.env) {\n for (const [key, value] of Object.entries(opts.env)) {\n args.push('-e', `${key}=${value}`);\n }\n }\n\n args.push(this.containerName, 'sh', '-c', command);\n\n const timeout = opts?.timeout ?? DEFAULT_TIMEOUT_SECONDS;\n const start = Date.now();\n\n const result = await spawnCommand('docker', args, {\n timeout,\n stdin: opts?.stdin,\n });\n\n const durationMs = Date.now() - start;\n const { text: stdout, truncated: stdoutTruncated } = truncateOutput(\n stripAnsi(result.stdout),\n this.maxOutputChars\n );\n const { text: stderr } = truncateOutput(stripAnsi(result.stderr), this.maxOutputChars);\n\n return {\n exitCode: result.exitCode,\n stdout,\n stderr,\n durationMs,\n truncated: stdoutTruncated,\n };\n }\n\n async readFile(filePath: string): Promise<string> {\n const hostPath = this.toHostPath(filePath);\n const buffer = await fs.readFile(hostPath);\n if (isBinary(buffer)) {\n throw new Error(`Cannot read binary file: ${filePath}`);\n }\n return buffer.toString('utf-8');\n }\n\n async writeFile(filePath: string, content: string): Promise<void> {\n const hostPath = this.toHostPath(filePath);\n await fs.mkdir(path.dirname(hostPath), { recursive: true });\n await fs.writeFile(hostPath, content, 'utf-8');\n }\n\n async fileExists(filePath: string): Promise<boolean> {\n const hostPath = this.toHostPath(filePath);\n try {\n await fs.access(hostPath);\n return true;\n } catch {\n return false;\n }\n }\n\n async glob(pattern: string, opts?: GlobOptions): Promise<string[]> {\n const cwd = opts?.cwd ?? this.containerWorkdir;\n let command = `find ${cwd} -type f -name '${pattern}'`;\n\n if (opts?.ignore) {\n for (const ignore of opts.ignore) {\n command += ` ! -path '${ignore}'`;\n }\n }\n\n command += ' 2>/dev/null | sort | head -1000';\n\n const result = await this.exec(command);\n if (!result.stdout.trim()) return [];\n\n return result.stdout.trim().split('\\n').filter(Boolean);\n }\n\n async grep(pattern: string, opts?: GrepOptions): Promise<GrepMatch[]> {\n const cwd = opts?.cwd ?? this.containerWorkdir;\n const maxResults = opts?.maxResults ?? 100;\n\n let command = 'grep -rn';\n\n if (opts?.contextLines !== undefined) {\n command += ` -C ${String(opts.contextLines)}`;\n }\n\n if (opts?.include) {\n for (const inc of opts.include) {\n command += ` --include='${inc}'`;\n }\n }\n\n // Use -- to separate pattern from paths, escape single quotes in pattern\n const escapedPattern = pattern.replace(/'/g, \"'\\\\''\");\n command += ` -- '${escapedPattern}' ${cwd}`;\n command += ` 2>/dev/null | head -${String(maxResults)}`;\n\n const result = await this.exec(command);\n return parseGrepOutput(result.stdout);\n }\n\n async destroy(): Promise<void> {\n if (!this.containerId) return;\n try {\n await spawnCommand('docker', ['rm', '-f', this.containerName], { timeout: 30 });\n } finally {\n this.containerId = null;\n }\n }\n\n getCwd(): string {\n return this.containerWorkdir;\n }\n\n getInfo(): EnvironmentInfo {\n return {\n type: 'docker',\n cwd: this.containerWorkdir,\n sandboxId: this.containerId ?? undefined,\n };\n }\n\n /**\n * Translate a container path to the corresponding host filesystem path.\n * Validates the path stays within the workspace to prevent traversal.\n */\n toHostPath(containerPath: string): string {\n // Resolve relative to container workdir\n const resolved = path.posix.resolve(this.containerWorkdir, containerPath);\n\n // Ensure the resolved path is within the container workdir\n if (!resolved.startsWith(this.containerWorkdir)) {\n throw new Error(`Path traversal detected: \"${containerPath}\" resolves outside workspace`);\n }\n\n // Translate to host path\n const relative = path.posix.relative(this.containerWorkdir, resolved);\n return path.join(this.config.workspaceDir, relative);\n }\n\n /**\n * Translate a host filesystem path to the corresponding container path.\n */\n toContainerPath(hostPath: string): string {\n const resolved = path.resolve(hostPath);\n\n if (!resolved.startsWith(this.config.workspaceDir)) {\n throw new Error(\n `Path outside workspace: \"${hostPath}\" is not within \"${this.config.workspaceDir}\"`\n );\n }\n\n const relative = path.relative(this.config.workspaceDir, resolved);\n return path.posix.join(this.containerWorkdir, relative);\n }\n\n private assertInitialized(): void {\n if (!this.containerId) {\n throw new Error('Docker environment not initialized. Call initialize() first.');\n }\n }\n}\n","/**\n * Local execution environment.\n *\n * Runs commands and accesses files directly on the host machine.\n * Optionally restricts file operations to a specified directory\n * and blocks symlink traversal when path restriction is active.\n */\n\nimport { spawn } from 'node:child_process';\nimport * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport type {\n ExecutionEnvironment,\n ExecOptions,\n ExecResult,\n GlobOptions,\n GrepOptions,\n GrepMatch,\n EnvironmentInfo,\n LocalEnvironmentConfig,\n} from './types.js';\nimport { truncateOutput, isBinary, parseGrepOutput, stripAnsi } from './output.js';\n\n/** Default command timeout in seconds */\nconst DEFAULT_TIMEOUT_SECONDS = 300;\n\n/** Default maximum output characters */\nconst DEFAULT_MAX_OUTPUT_CHARS = 100_000;\n\n/**\n * Execute a shell command via child_process.spawn.\n * @internal\n */\nfunction spawnLocal(\n command: string,\n options: {\n cwd?: string | undefined;\n env?: Record<string, string> | undefined;\n timeout?: number | undefined;\n stdin?: string | undefined;\n }\n): Promise<{ exitCode: number; stdout: string; stderr: string }> {\n return new Promise((resolve, reject) => {\n let settled = false;\n const settle = (fn: () => void) => {\n if (!settled) {\n settled = true;\n fn();\n }\n };\n\n const proc = spawn('sh', ['-c', command], {\n cwd: options.cwd,\n env: options.env ? { ...process.env, ...options.env } : undefined,\n stdio: ['pipe', 'pipe', 'pipe'],\n });\n\n let stdout = '';\n let stderr = '';\n let killed = false;\n\n proc.stdout.on('data', (data: Buffer) => {\n stdout += data.toString();\n });\n\n proc.stderr.on('data', (data: Buffer) => {\n stderr += data.toString();\n });\n\n // Guard against stream errors leaving the promise unresolved\n proc.stdin.on('error', () => {\n /* noop */\n });\n proc.stdout.on('error', () => {\n /* noop */\n });\n proc.stderr.on('error', () => {\n /* noop */\n });\n\n const timeoutMs = (options.timeout ?? DEFAULT_TIMEOUT_SECONDS) * 1000;\n const timer = setTimeout(() => {\n killed = true;\n proc.kill('SIGKILL');\n }, timeoutMs);\n\n proc.on('close', (code) => {\n clearTimeout(timer);\n settle(() => {\n if (killed) {\n resolve({\n exitCode: 137,\n stdout,\n stderr: stderr + '\\n[Process killed: timeout exceeded]',\n });\n } else {\n resolve({ exitCode: code ?? 1, stdout, stderr });\n }\n });\n });\n\n proc.on('error', (err) => {\n clearTimeout(timer);\n settle(() => {\n reject(err);\n });\n });\n\n if (options.stdin) {\n proc.stdin.write(options.stdin, () => {\n proc.stdin.end();\n });\n } else {\n proc.stdin.end();\n }\n });\n}\n\n/**\n * Local execution environment.\n *\n * Executes commands and file operations directly on the host.\n * When `pathRestriction` is configured, file operations are restricted\n * to the specified directory and symlink traversal is blocked.\n */\nexport class LocalEnvironment implements ExecutionEnvironment {\n readonly type = 'local' as const;\n\n private readonly config: LocalEnvironmentConfig;\n private readonly cwd: string;\n private readonly maxOutputChars: number;\n\n constructor(config?: LocalEnvironmentConfig, maxOutputChars?: number) {\n this.config = config ?? {};\n this.cwd = path.resolve(config?.cwd ?? process.cwd());\n this.maxOutputChars = maxOutputChars ?? DEFAULT_MAX_OUTPUT_CHARS;\n }\n\n async initialize(): Promise<void> {\n // Validate that the working directory exists\n try {\n const stat = await fs.stat(this.cwd);\n if (!stat.isDirectory()) {\n throw new Error(`Working directory is not a directory: ${this.cwd}`);\n }\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n throw new Error(`Working directory does not exist: ${this.cwd}`);\n }\n throw err;\n }\n }\n\n async exec(command: string, opts?: ExecOptions): Promise<ExecResult> {\n const cwd = opts?.cwd ? this.resolvePath(opts.cwd) : this.cwd;\n const timeout = opts?.timeout ?? DEFAULT_TIMEOUT_SECONDS;\n const start = Date.now();\n\n const result = await spawnLocal(command, {\n cwd,\n env: opts?.env,\n timeout,\n stdin: opts?.stdin,\n });\n\n const durationMs = Date.now() - start;\n const { text: stdout, truncated: stdoutTruncated } = truncateOutput(\n stripAnsi(result.stdout),\n this.maxOutputChars\n );\n const { text: stderr } = truncateOutput(stripAnsi(result.stderr), this.maxOutputChars);\n\n return {\n exitCode: result.exitCode,\n stdout,\n stderr,\n durationMs,\n truncated: stdoutTruncated,\n };\n }\n\n async readFile(filePath: string): Promise<string> {\n const resolved = this.resolvePath(filePath);\n // Path restriction for reads is handled at the tool layer (approval gate).\n // Symlink traversal is still blocked at the environment level.\n await this.assertNotSymlink(resolved);\n\n const buffer = await fs.readFile(resolved);\n if (isBinary(buffer)) {\n throw new Error(`Cannot read binary file: ${filePath}`);\n }\n return buffer.toString('utf-8');\n }\n\n async writeFile(filePath: string, content: string): Promise<void> {\n const resolved = this.resolvePath(filePath);\n this.assertPathSafe(resolved);\n\n const parentDir = path.dirname(resolved);\n await fs.mkdir(parentDir, { recursive: true });\n await fs.writeFile(resolved, content, 'utf-8');\n }\n\n async fileExists(filePath: string): Promise<boolean> {\n const resolved = this.resolvePath(filePath);\n try {\n await fs.access(resolved);\n return true;\n } catch {\n return false;\n }\n }\n\n async glob(pattern: string, opts?: GlobOptions): Promise<string[]> {\n const cwd = opts?.cwd ? this.resolvePath(opts.cwd) : this.cwd;\n\n let command = `find ${cwd} -type f -name '${pattern}'`;\n\n if (opts?.ignore) {\n for (const ignore of opts.ignore) {\n command += ` ! -path '${ignore}'`;\n }\n }\n\n command += ' 2>/dev/null | sort | head -1000';\n\n const result = await this.exec(command);\n if (!result.stdout.trim()) return [];\n\n return result.stdout.trim().split('\\n').filter(Boolean);\n }\n\n async grep(pattern: string, opts?: GrepOptions): Promise<GrepMatch[]> {\n const cwd = opts?.cwd ? this.resolvePath(opts.cwd) : this.cwd;\n const maxResults = opts?.maxResults ?? 100;\n\n let command = 'grep -rn';\n\n if (opts?.contextLines !== undefined) {\n command += ` -C ${String(opts.contextLines)}`;\n }\n\n if (opts?.include) {\n for (const inc of opts.include) {\n command += ` --include='${inc}'`;\n }\n }\n\n // Escape single quotes in pattern, use -- to separate pattern from paths\n const escapedPattern = pattern.replace(/'/g, \"'\\\\''\");\n command += ` -- '${escapedPattern}' ${cwd}`;\n command += ` 2>/dev/null | head -${String(maxResults)}`;\n\n const result = await this.exec(command);\n return parseGrepOutput(result.stdout);\n }\n\n async destroy(): Promise<void> {\n // No-op — local environment has no resources to clean up\n }\n\n getCwd(): string {\n return this.cwd;\n }\n\n getInfo(): EnvironmentInfo {\n return {\n type: 'local',\n cwd: this.cwd,\n };\n }\n\n /**\n * Resolve a path relative to the working directory.\n */\n private resolvePath(p: string): string {\n return path.resolve(this.cwd, p);\n }\n\n /**\n * Assert that a resolved path stays within the path restriction.\n * No-op when path restriction is not configured.\n */\n private assertPathSafe(resolvedPath: string): void {\n if (!this.config.pathRestriction) return;\n\n const restriction = path.resolve(this.config.pathRestriction);\n if (resolvedPath !== restriction && !resolvedPath.startsWith(restriction + '/')) {\n throw new Error(`Path traversal detected: \"${resolvedPath}\" is outside of \"${restriction}\"`);\n }\n }\n\n /**\n * Assert that a path is not a symbolic link.\n * Only enforced when path restriction is configured.\n */\n private async assertNotSymlink(resolvedPath: string): Promise<void> {\n if (!this.config.pathRestriction) return;\n\n try {\n const stat = await fs.lstat(resolvedPath);\n if (stat.isSymbolicLink()) {\n throw new Error(\n `Symbolic link detected: \"${resolvedPath}\". Symlinks are blocked when pathRestriction is set.`\n );\n }\n } catch (err) {\n // File doesn't exist — that's fine, let readFile handle the ENOENT\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return;\n throw err;\n }\n }\n}\n","/**\n * Managed sandbox — wraps an ExecutionEnvironment with identity,\n * lifecycle tracking, and crash recovery.\n */\n\nimport { randomUUID } from 'node:crypto';\nimport * as fs from 'node:fs/promises';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\nimport type { ExecutionEnvironment, SandboxConfig, SandboxScope } from './types.js';\nimport { DockerEnvironment } from './docker.js';\nimport { LocalEnvironment } from './local.js';\nimport { createLogger } from '../utils/logger.js';\n\nconst logger = createLogger({ name: 'sandbox' });\n\n/** Default base directory for sandbox workspaces. */\nconst DEFAULT_WORKSPACES_DIR = path.join(os.homedir(), '.polos', 'workspaces');\n\n/** Environment variable to override the base workspaces directory. */\nconst WORKSPACES_DIR_ENV = 'POLOS_WORKSPACES_DIR';\n\n/**\n * A managed sandbox wrapping an ExecutionEnvironment.\n */\nexport interface Sandbox {\n readonly id: string;\n readonly scope: SandboxScope;\n readonly config: SandboxConfig;\n readonly workerId: string;\n readonly sessionId?: string | undefined;\n readonly activeExecutionIds: ReadonlySet<string>;\n readonly initialized: boolean;\n readonly destroyed: boolean;\n readonly lastActivityAt: Date;\n\n /** Get or lazily initialize the environment. Updates lastActivityAt. */\n getEnvironment(): Promise<ExecutionEnvironment>;\n\n /** Record that an execution is using this sandbox. */\n attachExecution(executionId: string): void;\n\n /** Record that an execution is done with this sandbox. */\n detachExecution(executionId: string): void;\n\n /** Destroy the sandbox. Safe to call multiple times. */\n destroy(): Promise<void>;\n\n /** Recreate after container crash. Filesystem survives via bind mount. */\n recreate(): Promise<void>;\n}\n\n/** Health check debounce interval in milliseconds. */\nconst HEALTH_CHECK_DEBOUNCE_MS = 30_000;\n\n/**\n * Concrete implementation of the Sandbox interface.\n */\nexport class ManagedSandbox implements Sandbox {\n readonly id: string;\n readonly scope: SandboxScope;\n readonly config: SandboxConfig;\n private _workerId: string;\n readonly projectId: string;\n readonly sessionId?: string | undefined;\n private readonly _activeExecutionIds = new Set<string>();\n private _lastActivityAt = new Date();\n private _destroyed = false;\n\n private _env: ExecutionEnvironment | null = null;\n private _envPromise: Promise<ExecutionEnvironment> | null = null;\n private _lastHealthCheckAt = 0;\n\n constructor(config: SandboxConfig, workerId: string, projectId: string, sessionId?: string) {\n this.id = config.id ?? `sandbox-${randomUUID().slice(0, 8)}`;\n this.scope = config.scope ?? 'execution';\n this.config = config;\n this._workerId = workerId;\n this.projectId = projectId;\n this.sessionId = sessionId;\n }\n\n get workerId(): string {\n return this._workerId;\n }\n\n get activeExecutionIds(): ReadonlySet<string> {\n return this._activeExecutionIds;\n }\n\n get initialized(): boolean {\n return this._env !== null;\n }\n\n get destroyed(): boolean {\n return this._destroyed;\n }\n\n get lastActivityAt(): Date {\n return this._lastActivityAt;\n }\n\n async getEnvironment(): Promise<ExecutionEnvironment> {\n if (this._destroyed) {\n throw new Error(`Sandbox ${this.id} has been destroyed`);\n }\n\n this._lastActivityAt = new Date();\n\n // If environment exists, optionally health-check\n if (this._env) {\n await this._healthCheck();\n return this._env;\n }\n\n // Coalesce concurrent init calls\n if (this._envPromise) {\n return this._envPromise;\n }\n\n this._envPromise = this._initializeEnvironment();\n try {\n const env = await this._envPromise;\n this._env = env;\n return env;\n } catch (err) {\n this._envPromise = null;\n throw err;\n }\n }\n\n attachExecution(executionId: string): void {\n this._activeExecutionIds.add(executionId);\n }\n\n detachExecution(executionId: string): void {\n this._activeExecutionIds.delete(executionId);\n }\n\n async destroy(): Promise<void> {\n if (this._destroyed) return;\n this._destroyed = true;\n\n if (this._env) {\n try {\n await this._env.destroy();\n } catch (err) {\n logger.warn(`Failed to destroy environment for sandbox ${this.id}`, {\n error: String(err),\n });\n }\n this._env = null;\n this._envPromise = null;\n }\n }\n\n async recreate(): Promise<void> {\n logger.info(`Recreating sandbox ${this.id}`);\n\n // Best-effort destroy old env\n if (this._env) {\n try {\n await this._env.destroy();\n } catch {\n // Container may already be gone\n }\n }\n\n this._env = null;\n this._envPromise = null;\n this._destroyed = false;\n this._lastHealthCheckAt = 0;\n\n // Next getEnvironment() call will re-initialize\n }\n\n /**\n * Create the execution environment based on config.\n */\n /**\n * Compute the default workspace directory for Docker.\n * Uses `POLOS_WORKSPACES_DIR/{projectId}/{sessionId || sandboxId}`.\n */\n private _getDefaultWorkspaceDir(): string {\n const base = process.env[WORKSPACES_DIR_ENV] ?? DEFAULT_WORKSPACES_DIR;\n const leaf = this.sessionId ?? this.id;\n return path.join(base, this.projectId, leaf);\n }\n\n private async _initializeEnvironment(): Promise<ExecutionEnvironment> {\n const envType = this.config.env ?? 'docker';\n\n switch (envType) {\n case 'docker': {\n const workspaceDir = this.config.docker?.workspaceDir ?? this._getDefaultWorkspaceDir();\n\n const dockerConfig = {\n image: 'node:20-slim',\n ...this.config.docker,\n workspaceDir,\n };\n\n // Ensure workspace directory exists on host before bind-mounting\n await fs.mkdir(workspaceDir, { recursive: true });\n\n const env = new DockerEnvironment(dockerConfig, this.config.exec?.maxOutputChars);\n\n // Build labels for lifecycle management and orphan detection\n const labels: Record<string, string> = {\n 'polos.managed': 'true',\n 'polos.sandbox-id': this.id,\n 'polos.worker-id': this._workerId,\n };\n if (this.sessionId) {\n labels['polos.session-id'] = this.sessionId;\n }\n\n await env.initialize(labels);\n return env;\n }\n case 'local': {\n const localCwd = this.config.local?.cwd ?? this._getDefaultWorkspaceDir();\n await fs.mkdir(localCwd, { recursive: true });\n // Default pathRestriction to cwd; set to false to explicitly disable\n const pathRestriction =\n this.config.local?.pathRestriction === false\n ? undefined\n : (this.config.local?.pathRestriction ?? localCwd);\n const localConfig = { ...this.config.local, cwd: localCwd, pathRestriction };\n const env = new LocalEnvironment(localConfig, this.config.exec?.maxOutputChars);\n await env.initialize();\n return env;\n }\n case 'e2b':\n throw new Error('E2B environment is not yet implemented.');\n default:\n throw new Error(`Unknown environment type: ${String(envType)}`);\n }\n }\n\n /**\n * Health check with 30s debounce. Only probes Docker containers.\n */\n private async _healthCheck(): Promise<void> {\n if (!this._env) return;\n if (this._env.type !== 'docker') return;\n\n const now = Date.now();\n if (now - this._lastHealthCheckAt < HEALTH_CHECK_DEBOUNCE_MS) {\n return;\n }\n\n this._lastHealthCheckAt = now;\n\n try {\n await this._env.exec('true', { timeout: 5 });\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n if (msg.includes('No such container') || msg.includes('is not running')) {\n logger.warn(`Container for sandbox ${this.id} is dead, recreating`, { error: msg });\n await this.recreate();\n // Re-initialize immediately so caller gets a working env\n await this.getEnvironment();\n }\n // Other errors (e.g., timeout) — don't recreate, let the actual tool call fail\n }\n }\n}\n","/**\n * SandboxManager — manages sandbox creation, reuse, auto-cleanup,\n * and orphan detection. Lives on the Worker.\n */\n\nimport { spawn } from 'node:child_process';\nimport type { SandboxConfig } from './types.js';\nimport { ManagedSandbox, type Sandbox } from './sandbox.js';\nimport { createLogger } from '../utils/logger.js';\nimport type { OrchestratorClient } from '../runtime/orchestrator-client.js';\n\nconst logger = createLogger({ name: 'sandbox-manager' });\n\n/** Default idle sweep interval: 10 minutes. */\nconst DEFAULT_SWEEP_INTERVAL_MS = 10 * 60 * 1000;\n\n/** Default idle destroy timeout: 1 hour. */\nconst DEFAULT_IDLE_TIMEOUT = '1h';\n\n/** Grace period before removing orphan containers (30 minutes). */\nconst ORPHAN_GRACE_PERIOD_MS = 30 * 60 * 1000;\n\n/**\n * Parse a human-readable duration string to milliseconds.\n * Supports: '30m', '1h', '24h', '3d', '7d'.\n */\nexport function parseDuration(str: string): number {\n const match = /^(\\d+(?:\\.\\d+)?)\\s*(m|h|d)$/.exec(str.trim());\n if (!match) {\n throw new Error(`Invalid duration: \"${str}\". Expected format: \"1h\", \"24h\", \"3d\", etc.`);\n }\n const value = parseFloat(match[1] ?? '0');\n const unit = match[2] ?? 'h';\n\n switch (unit) {\n case 'm':\n return value * 60 * 1000;\n case 'h':\n return value * 60 * 60 * 1000;\n case 'd':\n return value * 24 * 60 * 60 * 1000;\n default:\n throw new Error(`Unknown duration unit: \"${unit}\"`);\n }\n}\n\n/**\n * Manages sandbox lifecycle across executions.\n */\nexport class SandboxManager {\n private _workerId: string;\n private _projectId: string;\n private readonly _orchestratorClient: OrchestratorClient | undefined;\n private readonly sandboxes = new Map<string, ManagedSandbox>();\n private readonly sessionSandboxes = new Map<string, ManagedSandbox>();\n private readonly sessionCreationLocks = new Map<string, Promise<Sandbox>>();\n private sweepTimer: ReturnType<typeof setInterval> | null = null;\n\n constructor(workerId: string, projectId: string, orchestratorClient?: OrchestratorClient) {\n this._workerId = workerId;\n this._projectId = projectId;\n this._orchestratorClient = orchestratorClient;\n }\n\n /**\n * Update the worker ID (called after registration or re-registration).\n */\n setWorkerId(workerId: string): void {\n this._workerId = workerId;\n }\n\n /**\n * Create or retrieve a sandbox.\n *\n * - Session-scoped: returns existing sandbox for the session if available.\n * - Execution-scoped: always creates a new sandbox.\n */\n async getOrCreateSandbox(\n config: SandboxConfig,\n ctx: { executionId: string; sessionId?: string | undefined }\n ): Promise<Sandbox> {\n const scope = config.scope ?? 'execution';\n\n if (scope === 'session') {\n if (!ctx.sessionId) {\n throw new Error('sessionId is required for session-scoped sandboxes');\n }\n\n // Check for existing sandbox\n const existing = this.sessionSandboxes.get(ctx.sessionId);\n if (existing && !existing.destroyed) {\n existing.attachExecution(ctx.executionId);\n return existing;\n }\n\n // Serialize concurrent creation for the same session\n const existingLock = this.sessionCreationLocks.get(ctx.sessionId);\n if (existingLock) {\n const sandbox = await existingLock;\n sandbox.attachExecution(ctx.executionId);\n return sandbox;\n }\n\n // Register the lock as an unresolved promise BEFORE starting creation.\n // This ensures a concurrent caller arriving between here and the resolve\n // will find the lock and wait, even if _createSessionSandbox becomes async.\n let resolveLock!: (value: Sandbox) => void;\n let rejectLock!: (reason: unknown) => void;\n const lockPromise = new Promise<Sandbox>((resolve, reject) => {\n resolveLock = resolve;\n rejectLock = reject;\n });\n this.sessionCreationLocks.set(ctx.sessionId, lockPromise);\n\n try {\n const sandbox = this._createSessionSandbox(config, ctx.executionId, ctx.sessionId);\n resolveLock(sandbox);\n return sandbox;\n } catch (err) {\n rejectLock(err);\n throw err;\n } finally {\n this.sessionCreationLocks.delete(ctx.sessionId);\n }\n }\n\n // Execution-scoped: always new\n return this._createExecutionSandbox(config, ctx.executionId);\n }\n\n /**\n * Notify that an execution completed. Triggers cleanup for execution-scoped sandboxes.\n */\n async onExecutionComplete(executionId: string): Promise<void> {\n for (const [sandboxId, sandbox] of this.sandboxes) {\n if (!sandbox.activeExecutionIds.has(executionId)) continue;\n\n sandbox.detachExecution(executionId);\n\n // Execution-scoped sandboxes are 1:1 with executions — destroy immediately.\n // Session-scoped sandboxes survive; they're cleaned up by the idle sweep.\n if (sandbox.scope === 'execution') {\n await this._destroyAndRemove(sandboxId, sandbox);\n }\n }\n }\n\n /**\n * Destroy a specific sandbox by ID.\n */\n async destroySandbox(sandboxId: string): Promise<void> {\n const sandbox = this.sandboxes.get(sandboxId);\n if (sandbox) {\n await this._destroyAndRemove(sandboxId, sandbox);\n }\n }\n\n /**\n * Destroy all managed sandboxes. Called during worker shutdown.\n */\n async destroyAll(): Promise<void> {\n const entries = Array.from(this.sandboxes.entries());\n await Promise.allSettled(\n entries.map(async ([id, sandbox]) => {\n try {\n await sandbox.destroy();\n } catch (err) {\n logger.warn(`Failed to destroy sandbox ${id}`, { error: String(err) });\n }\n })\n );\n this.sandboxes.clear();\n this.sessionSandboxes.clear();\n }\n\n /**\n * Start periodic sweep. Each cycle:\n * 1. Destroys own sandboxes idle past their idleDestroyTimeout.\n * 2. Removes orphan Docker containers from dead workers (orchestrator-based).\n */\n startSweep(intervalMs: number = DEFAULT_SWEEP_INTERVAL_MS): void {\n this.stopSweep();\n this.sweepTimer = setInterval(() => {\n void this._sweep();\n }, intervalMs);\n // Don't keep process alive just for the sweep\n this.sweepTimer.unref();\n }\n\n /**\n * Stop the periodic sweep.\n */\n stopSweep(): void {\n if (this.sweepTimer) {\n clearInterval(this.sweepTimer);\n this.sweepTimer = null;\n }\n }\n\n /**\n * Lookup a sandbox by ID.\n */\n getSandbox(sandboxId: string): Sandbox | undefined {\n return this.sandboxes.get(sandboxId);\n }\n\n /**\n * Lookup a session sandbox by session ID.\n */\n getSessionSandbox(sessionId: string): Sandbox | undefined {\n return this.sessionSandboxes.get(sessionId);\n }\n\n // ── Private helpers ─────────────────────────────────────────────────\n\n private _createExecutionSandbox(config: SandboxConfig, executionId: string): Sandbox {\n const sandbox = new ManagedSandbox(config, this._workerId, this._projectId);\n sandbox.attachExecution(executionId);\n this.sandboxes.set(sandbox.id, sandbox);\n return sandbox;\n }\n\n private _createSessionSandbox(\n config: SandboxConfig,\n executionId: string,\n sessionId: string\n ): Sandbox {\n const sandbox = new ManagedSandbox(config, this._workerId, this._projectId, sessionId);\n sandbox.attachExecution(executionId);\n this.sandboxes.set(sandbox.id, sandbox);\n this.sessionSandboxes.set(sessionId, sandbox);\n return sandbox;\n }\n\n private async _destroyAndRemove(sandboxId: string, sandbox: ManagedSandbox): Promise<void> {\n await sandbox.destroy();\n this.sandboxes.delete(sandboxId);\n\n if (sandbox.sessionId) {\n const current = this.sessionSandboxes.get(sandbox.sessionId);\n if (current === sandbox) {\n this.sessionSandboxes.delete(sandbox.sessionId);\n }\n }\n }\n\n /**\n * Unified sweep: Phase 1 cleans own idle sandboxes, Phase 2 cleans orphan containers.\n */\n private async _sweep(): Promise<void> {\n // Phase 1: Sweep own idle sandboxes (in-memory lastActivityAt)\n await this._sweepIdleSandboxes();\n\n // Phase 2: Sweep orphan containers from dead workers\n await this._sweepOrphanContainers();\n }\n\n /**\n * Phase 1: Destroy own sandboxes that have been idle past their timeout.\n */\n private async _sweepIdleSandboxes(): Promise<void> {\n const now = Date.now();\n\n for (const [sandboxId, sandbox] of this.sandboxes) {\n // Use lastActivityAt as the sole signal. It's updated on every\n // getEnvironment() call (i.e., every tool invocation). If nothing has\n // touched this sandbox for longer than the timeout, it's dead —\n // regardless of scope or what activeExecutionIds claims.\n //\n // This handles two failure modes:\n // 1. Execution-scoped sandboxes orphaned by crashes (onExecutionComplete never called)\n // 2. Stale activeExecutionIds from executions that crashed without detaching\n const timeoutStr = sandbox.config.idleDestroyTimeout ?? DEFAULT_IDLE_TIMEOUT;\n const timeoutMs = parseDuration(timeoutStr);\n const idleMs = now - sandbox.lastActivityAt.getTime();\n\n if (idleMs > timeoutMs) {\n logger.info(\n `Destroying idle sandbox ${sandboxId} (scope=${sandbox.scope}, ` +\n `session=${sandbox.sessionId ?? 'none'}, idle ${String(Math.round(idleMs / 1000))}s)`\n );\n try {\n await this._destroyAndRemove(sandboxId, sandbox);\n } catch (err) {\n logger.warn(`Failed to destroy idle sandbox ${sandboxId}`, { error: String(err) });\n }\n }\n }\n }\n\n /**\n * Phase 2: Remove Docker containers from dead workers.\n *\n * Queries the orchestrator for active worker IDs, lists all polos-managed\n * Docker containers, and removes any whose worker-id is not in the active set\n * AND whose age exceeds ORPHAN_GRACE_PERIOD_MS.\n *\n * If the orchestrator is unavailable, this phase is skipped entirely.\n */\n private async _sweepOrphanContainers(): Promise<void> {\n if (!this._orchestratorClient) return;\n\n let activeWorkerIds: Set<string>;\n try {\n const ids = await this._orchestratorClient.getActiveWorkerIds();\n activeWorkerIds = new Set(ids);\n } catch (err) {\n logger.warn('Failed to query active workers, skipping orphan cleanup', {\n error: String(err),\n });\n return;\n }\n\n try {\n const result = await spawnSimple('docker', [\n 'ps',\n '-a',\n '--filter',\n 'label=polos.managed=true',\n '--format',\n '{{.Names}}\\t{{.Label \"polos.worker-id\"}}\\t{{.CreatedAt}}',\n ]);\n\n if (result.exitCode !== 0 || !result.stdout.trim()) return;\n\n const now = Date.now();\n const lines = result.stdout.trim().split('\\n').filter(Boolean);\n for (const line of lines) {\n const [name, workerId, createdAt] = line.split('\\t');\n if (!name || !workerId) continue;\n\n // Skip containers belonging to active workers\n if (activeWorkerIds.has(workerId)) continue;\n\n // Skip containers younger than the grace period to avoid TOCTOU races\n const containerAge = now - new Date(createdAt ?? '').getTime();\n if (isNaN(containerAge) || containerAge < ORPHAN_GRACE_PERIOD_MS) continue;\n\n logger.info(`Removing orphaned container: ${name} (worker: ${workerId})`);\n try {\n await spawnSimple('docker', ['rm', '-f', name]);\n } catch (err) {\n logger.warn(`Failed to remove orphaned container ${name}`, { error: String(err) });\n }\n }\n } catch (err) {\n logger.warn('Failed to sweep orphan containers', { error: String(err) });\n }\n }\n}\n\n/**\n * Simple spawn helper for manager-level docker commands.\n */\nfunction spawnSimple(\n command: string,\n args: string[]\n): Promise<{ exitCode: number; stdout: string; stderr: string }> {\n return new Promise((resolve, reject) => {\n const proc = spawn(command, args, { stdio: ['pipe', 'pipe', 'pipe'] });\n let stdout = '';\n let stderr = '';\n\n proc.stdout.on('data', (data: Buffer) => {\n stdout += data.toString();\n });\n proc.stderr.on('data', (data: Buffer) => {\n stderr += data.toString();\n });\n proc.on('close', (code) => {\n resolve({ exitCode: code ?? 1, stdout, stderr });\n });\n proc.on('error', reject);\n });\n}\n","/**\n * Worker class for executing Polos workflows.\n *\n * The worker:\n * 1. Registers with the orchestrator (creates/replaces deployment)\n * 2. Registers all workflow definitions in deployment_workflows table\n * 3. Receives workflows via push mode and executes them\n */\n\nimport type { Workflow } from '../core/workflow.js';\nimport { isToolWorkflow, type ToolWorkflow } from '../core/tool.js';\nimport { isAgentWorkflow, type AgentWorkflow } from '../agents/agent.js';\nimport type { Channel, ChannelContext, ChannelOutputMode } from '../channels/channel.js';\nimport type { StreamEvent } from '../types/events.js';\nimport { globalRegistry } from '../core/registry.js';\nimport { StepExecutionError } from '../core/step.js';\nimport type {\n RegisterWorkerRequest,\n QueueRegistration,\n ExecutionContext,\n} from './orchestrator-types.js';\nimport {\n OrchestratorClient,\n OrchestratorApiError,\n type OrchestratorClientConfig,\n} from './orchestrator-client.js';\nimport { WorkerServer, type WorkerExecutionData } from './worker-server.js';\nimport { executeWorkflow, serializeFinalState, type ExecutionResult } from './executor.js';\nimport { SandboxManager } from '../execution/sandbox-manager.js';\nimport { createLogger } from '../utils/logger.js';\nimport { initializeOtel, shutdownOtel } from '../features/tracing.js';\nimport { getModelId, getModelProvider } from '../llm/types.js';\n\nconst logger = createLogger({ name: 'worker' });\n\n/**\n * Configuration for the Worker.\n */\nexport interface WorkerConfig {\n /** Polos orchestrator API URL */\n apiUrl: string;\n /** API key for authentication */\n apiKey: string;\n /** Project ID */\n projectId: string;\n /** Deployment ID (unique identifier for this deployment) */\n deploymentId: string;\n /** Workflows to register and execute */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n workflows?: Workflow<any, any, any>[] | undefined;\n /** Maximum concurrent workflow executions (default: 100) */\n maxConcurrentWorkflows?: number | undefined;\n /** Worker server URL for push mode (default: http://localhost:8000) */\n workerServerUrl?: string | undefined;\n /** Port for the worker server (default: 8000) */\n port?: number | undefined;\n /** Whether running in local mode (binds to 127.0.0.1) */\n localMode?: boolean | undefined;\n /** Request timeout in milliseconds (default: 30000) */\n timeout?: number | undefined;\n /** Default notification channels for suspend events (e.g., Slack, Discord) */\n channels?: Channel[] | undefined;\n}\n\n/**\n * Worker state.\n */\ntype WorkerState = 'stopped' | 'starting' | 'running' | 'stopping';\n\n/**\n * Worker for executing Polos workflows.\n *\n * @example\n * ```typescript\n * import { Worker, defineWorkflow } from '@polos/sdk';\n * import { z } from 'zod';\n *\n * const myWorkflow = defineWorkflow({\n * id: 'my-workflow',\n * payloadSchema: z.object({ message: z.string() }),\n * }, async (ctx, payload) => {\n * return { received: payload.message };\n * });\n *\n * const worker = new Worker({\n * apiUrl: 'http://localhost:8080',\n * apiKey: process.env.POLOS_API_KEY!,\n * projectId: 'my-project',\n * deploymentId: 'my-deployment',\n * workflows: [myWorkflow],\n * });\n *\n * await worker.run();\n * ```\n */\nexport class Worker {\n private readonly config: WorkerConfig;\n private readonly orchestratorClient: OrchestratorClient;\n private readonly workflowRegistry = new Map<string, Workflow>();\n private readonly channels: Channel[];\n private readonly maxConcurrentWorkflows: number;\n private readonly workerServerUrl: string;\n private readonly port: number;\n\n /** Sandbox manager for managed sandbox lifecycle. */\n readonly sandboxManager: SandboxManager;\n\n private workerId: string | null = null;\n private workerServer: WorkerServer | null = null;\n private state: WorkerState = 'stopped';\n private heartbeatInterval: ReturnType<typeof setInterval> | null = null;\n private activeExecutions = new Map<string, { abortController: AbortController }>();\n private signalHandler: (() => void) | null = null;\n\n constructor(config: WorkerConfig) {\n this.config = config;\n this.channels = config.channels ?? [];\n this.maxConcurrentWorkflows = config.maxConcurrentWorkflows ?? 100;\n this.workerServerUrl =\n config.workerServerUrl ?? `http://localhost:${String(config.port ?? 8000)}`;\n this.port = config.port ?? 8000;\n\n // Create orchestrator client\n const clientConfig: OrchestratorClientConfig = {\n apiUrl: config.apiUrl,\n apiKey: config.apiKey,\n projectId: config.projectId,\n timeout: config.timeout,\n };\n this.orchestratorClient = new OrchestratorClient(clientConfig);\n\n this.sandboxManager = new SandboxManager('', config.projectId, this.orchestratorClient);\n\n // Register workflows\n if (config.workflows) {\n for (const workflow of config.workflows) {\n this.workflowRegistry.set(workflow.id, workflow);\n }\n }\n }\n\n /**\n * Get the worker ID (assigned by orchestrator after registration).\n */\n getWorkerId(): string | null {\n return this.workerId;\n }\n\n /**\n * Get the worker ID, throwing if not registered.\n */\n private getWorkerIdOrThrow(): string {\n if (!this.workerId) {\n throw new Error('Worker not registered');\n }\n return this.workerId;\n }\n\n /**\n * Get the current worker state.\n */\n getState(): WorkerState {\n return this.state;\n }\n\n /**\n * Get registered workflow IDs.\n */\n getWorkflowIds(): string[] {\n return Array.from(this.workflowRegistry.keys());\n }\n\n /**\n * Run the worker (blocks until shutdown).\n */\n async run(): Promise<void> {\n if (this.state !== 'stopped') {\n throw new Error(`Cannot start worker: current state is ${this.state}`);\n }\n\n try {\n await this.registerAll();\n await this.runServer();\n } catch (error) {\n this.state = 'stopped';\n logger.error('Failed to start worker', { error: String(error) });\n throw error;\n }\n }\n\n /**\n * Phase 1: Initialize tracing and register with orchestrator.\n * @internal\n */\n async registerAll(): Promise<void> {\n this.state = 'starting';\n\n logger.info('Starting worker...');\n logger.info(`Deployment ID: ${this.config.deploymentId}`);\n logger.info(`Orchestrator: ${this.config.apiUrl}`);\n logger.info(`Workflows: ${Array.from(this.workflowRegistry.keys()).join(', ')}`);\n\n // Initialize OpenTelemetry tracing\n initializeOtel({\n apiUrl: this.config.apiUrl,\n apiKey: this.config.apiKey,\n projectId: this.config.projectId,\n });\n\n // Step 1: Register worker with orchestrator\n await this.register();\n\n // Initialize sandbox manager with assigned worker ID\n this.sandboxManager.setWorkerId(this.getWorkerIdOrThrow());\n this.sandboxManager.startSweep();\n\n // Step 2: Register deployment\n await this.registerDeployment();\n\n // Step 3: Register agents, tools, and workflows\n await this.registerAgents();\n await this.registerTools();\n await this.registerWorkflows();\n\n // Step 4: Register queues (non-fatal)\n try {\n await this.registerQueues();\n } catch (error) {\n logger.warn('Failed to register queues', { error: String(error) });\n }\n\n // Step 5: Mark worker as online (non-fatal)\n try {\n await this.markOnline();\n } catch (error) {\n logger.warn('Failed to mark worker as online', { error: String(error) });\n }\n }\n\n /**\n * Phase 2: Start worker server, heartbeat, and signal handlers (blocks until shutdown).\n * @internal\n */\n async runServer(): Promise<void> {\n // Setup worker server\n await this.setupWorkerServer();\n\n // Start heartbeat loop\n this.startHeartbeat();\n\n this.state = 'running';\n logger.info('Worker is running');\n\n // Register signal handlers for graceful shutdown\n const signalHandler = (): void => {\n void this.shutdown();\n };\n process.on('SIGINT', signalHandler);\n process.on('SIGTERM', signalHandler);\n this.signalHandler = signalHandler;\n\n // Keep running until shutdown is called\n await new Promise<void>((resolve) => {\n const checkState = (): void => {\n if (this.state === 'stopping' || this.state === 'stopped') {\n resolve();\n } else {\n setTimeout(checkState, 100);\n }\n };\n checkState();\n });\n }\n\n /**\n * Gracefully shutdown the worker.\n */\n async shutdown(): Promise<void> {\n if (this.state === 'stopped' || this.state === 'stopping') {\n logger.warn(`Cannot shutdown worker: current state is ${this.state}`);\n return;\n }\n\n this.state = 'stopping';\n logger.info('Shutting down worker...');\n\n // Remove signal handlers\n if (this.signalHandler) {\n process.removeListener('SIGINT', this.signalHandler);\n process.removeListener('SIGTERM', this.signalHandler);\n this.signalHandler = null;\n }\n\n // Stop heartbeat\n if (this.heartbeatInterval) {\n clearInterval(this.heartbeatInterval);\n this.heartbeatInterval = null;\n }\n\n // Cancel all active executions\n for (const [executionId, execution] of this.activeExecutions) {\n logger.info(`Cancelling execution: ${executionId}`);\n execution.abortController.abort();\n }\n\n // Wait for executions to complete (with timeout)\n const waitTimeout = 30000; // 30 seconds\n const waitStart = Date.now();\n while (this.activeExecutions.size > 0 && Date.now() - waitStart < waitTimeout) {\n await new Promise((resolve) => setTimeout(resolve, 100));\n }\n\n if (this.activeExecutions.size > 0) {\n logger.warn(`${String(this.activeExecutions.size)} executions did not complete in time`);\n }\n\n // Destroy all managed sandboxes\n this.sandboxManager.stopSweep();\n try {\n await this.sandboxManager.destroyAll();\n } catch (err) {\n logger.warn('Failed to destroy sandboxes during shutdown', { error: String(err) });\n }\n\n // Stop worker server\n if (this.workerServer) {\n await this.workerServer.stop();\n this.workerServer = null;\n }\n\n // Flush pending spans before marking as stopped\n await shutdownOtel();\n\n this.state = 'stopped';\n logger.info('Worker shutdown complete');\n }\n\n /**\n * Register worker with orchestrator.\n */\n private async register(): Promise<void> {\n logger.info('Registering worker with orchestrator...');\n\n const request: RegisterWorkerRequest = {\n deploymentId: this.config.deploymentId,\n projectId: this.config.projectId,\n mode: 'push',\n capabilities: {\n runtime: 'typescript',\n agentIds: this.getAgentIds(),\n toolIds: this.getToolIds(),\n workflowIds: Array.from(this.workflowRegistry.keys()),\n },\n maxConcurrentExecutions: this.maxConcurrentWorkflows,\n pushEndpointUrl: this.workerServerUrl,\n };\n\n const response = await this.orchestratorClient.registerWorker(request);\n this.workerId = response.worker_id;\n\n logger.info(`Registered worker: ${this.workerId}`);\n }\n\n /**\n * Register deployment with orchestrator.\n */\n private async registerDeployment(): Promise<void> {\n logger.info('Registering deployment...');\n\n await this.orchestratorClient.registerDeployment({\n deploymentId: this.config.deploymentId,\n });\n\n logger.info(`Deployment registered: ${this.config.deploymentId}`);\n }\n\n /**\n * Get agent IDs from registered workflows.\n */\n private getAgentIds(): string[] {\n const agentIds: string[] = [];\n for (const workflow of this.workflowRegistry.values()) {\n if (isAgentWorkflow(workflow)) {\n agentIds.push(workflow.id);\n }\n }\n return agentIds;\n }\n\n /**\n * Get tool IDs from registered workflows.\n */\n private getToolIds(): string[] {\n const toolIds: string[] = [];\n for (const workflow of this.workflowRegistry.values()) {\n if (isToolWorkflow(workflow)) {\n toolIds.push(workflow.id);\n }\n }\n return toolIds;\n }\n\n /**\n * Register agent definitions with orchestrator.\n */\n private async registerAgents(): Promise<void> {\n const agents: AgentWorkflow[] = [];\n for (const workflow of this.workflowRegistry.values()) {\n if (isAgentWorkflow(workflow)) {\n agents.push(workflow);\n }\n }\n\n if (agents.length === 0) {\n return;\n }\n\n logger.info(`Registering ${String(agents.length)} agent(s)...`);\n\n for (const agent of agents) {\n // Build tool definitions for the agent\n const toolsJson = agent.tools.length > 0 ? agent.tools : undefined;\n\n // Build metadata\n const metadata: Record<string, unknown> = {};\n\n // Add stop condition function names\n if (agent.stopConditions.length > 0) {\n const stopConditionNames: string[] = [];\n for (const sc of agent.stopConditions) {\n if (sc.__stop_condition_name__) {\n stopConditionNames.push(sc.__stop_condition_name__);\n } else if (sc.name) {\n stopConditionNames.push(sc.name);\n } else {\n stopConditionNames.push('anonymous');\n }\n }\n metadata['stop_conditions'] = stopConditionNames;\n }\n\n // Add guardrail info\n if (agent.guardrails.length > 0) {\n const guardrailInfo: { type: string; name: string }[] = [];\n for (const gr of agent.guardrails) {\n const name = gr.name ?? 'anonymous';\n guardrailInfo.push({ type: 'function', name });\n }\n metadata['guardrails'] = guardrailInfo;\n }\n\n // Register agent definition with orchestrator\n await this.orchestratorClient.registerAgent({\n id: agent.id,\n deploymentId: this.config.deploymentId,\n provider: getModelProvider(agent.llm.model),\n model: getModelId(agent.llm.model),\n systemPrompt: agent.agentConfig.systemPrompt,\n tools: toolsJson,\n temperature: agent.agentConfig.temperature,\n maxOutputTokens: agent.agentConfig.maxOutputTokens,\n metadata: Object.keys(metadata).length > 0 ? metadata : null,\n });\n\n // Register in deployment_workflows\n await this.orchestratorClient.registerDeploymentWorkflow(this.config.deploymentId, {\n workflowId: agent.id,\n workflowType: 'agent',\n });\n\n logger.debug(`Registered agent: ${agent.id}`);\n }\n\n logger.info('Agents registered');\n }\n\n /**\n * Register tool definitions with orchestrator.\n */\n private async registerTools(): Promise<void> {\n const tools: ToolWorkflow[] = [];\n for (const workflow of this.workflowRegistry.values()) {\n if (isToolWorkflow(workflow)) {\n tools.push(workflow);\n }\n }\n\n if (tools.length === 0) {\n return;\n }\n\n logger.info(`Registering ${String(tools.length)} tool(s)...`);\n\n for (const tool of tools) {\n await this.orchestratorClient.registerTool({\n id: tool.id,\n deploymentId: this.config.deploymentId,\n toolType: tool.getToolType(),\n description: tool.toolDescription,\n parameters: tool.toolParameters,\n metadata: tool.getToolMetadata(),\n });\n\n // Register in deployment_workflows\n await this.orchestratorClient.registerDeploymentWorkflow(this.config.deploymentId, {\n workflowId: tool.id,\n workflowType: 'tool',\n });\n\n logger.debug(`Registered tool: ${tool.id} (type: ${tool.getToolType()})`);\n }\n\n logger.info('Tools registered');\n }\n\n /**\n * Register workflows with orchestrator.\n */\n private async registerWorkflows(): Promise<void> {\n // Filter to pure workflows only (not agents or tools)\n const pureWorkflows: Workflow[] = [];\n for (const workflow of this.workflowRegistry.values()) {\n if (!isAgentWorkflow(workflow) && !isToolWorkflow(workflow)) {\n pureWorkflows.push(workflow);\n }\n }\n\n if (pureWorkflows.length === 0) {\n logger.info('No workflows to register');\n return;\n }\n\n logger.info(`Registering ${String(pureWorkflows.length)} workflow(s)...`);\n\n for (const workflow of pureWorkflows) {\n const config = workflow.config;\n\n await this.orchestratorClient.registerDeploymentWorkflow(this.config.deploymentId, {\n workflowId: workflow.id,\n workflowType: 'workflow',\n triggerOnEvent: config.triggerOnEvent !== undefined ? true : undefined,\n scheduled: config.schedule !== undefined ? true : undefined,\n });\n\n logger.debug(`Registered workflow: ${workflow.id}`);\n }\n\n logger.info('Workflows registered');\n }\n\n /**\n * Helper to extract queue name and concurrency limit from a workflow config.\n */\n private getQueueInfo(workflow: Workflow): {\n queueName: string;\n concurrencyLimit: number | undefined;\n } {\n const config = workflow.config;\n let queueName: string;\n let concurrencyLimit: number | undefined;\n\n if (typeof config.queue === 'string') {\n queueName = config.queue;\n } else if (config.queue) {\n queueName = config.queue.name;\n concurrencyLimit = config.queue.concurrencyLimit;\n } else {\n queueName = workflow.id;\n }\n\n return { queueName, concurrencyLimit };\n }\n\n /**\n * Helper to merge a queue into the queues map with most-restrictive concurrency.\n */\n private mergeQueue(\n queues: Map<string, number | undefined>,\n queueName: string,\n concurrencyLimit: number | undefined\n ): void {\n if (queues.has(queueName)) {\n const existing = queues.get(queueName);\n if (concurrencyLimit !== undefined && existing !== undefined) {\n queues.set(queueName, Math.min(existing, concurrencyLimit));\n } else if (concurrencyLimit !== undefined) {\n queues.set(queueName, concurrencyLimit);\n }\n } else {\n queues.set(queueName, concurrencyLimit);\n }\n }\n\n /**\n * Register queues with orchestrator.\n */\n private async registerQueues(): Promise<void> {\n const queues = new Map<string, number | undefined>();\n\n // Collect from pure workflows (skip scheduled, skip agents/tools)\n for (const workflow of this.workflowRegistry.values()) {\n if (isAgentWorkflow(workflow) || isToolWorkflow(workflow)) {\n continue;\n }\n\n // Skip scheduled workflows — they get their own queues registered separately\n const config = workflow.config;\n const isSchedulable = config.schedule !== undefined;\n if (isSchedulable) {\n continue;\n }\n\n const { queueName, concurrencyLimit } = this.getQueueInfo(workflow);\n this.mergeQueue(queues, queueName, concurrencyLimit);\n }\n\n // Collect from agents\n for (const workflow of this.workflowRegistry.values()) {\n if (!isAgentWorkflow(workflow)) {\n continue;\n }\n const { queueName, concurrencyLimit } = this.getQueueInfo(workflow);\n this.mergeQueue(queues, queueName, concurrencyLimit);\n }\n\n // Collect from tools\n for (const workflow of this.workflowRegistry.values()) {\n if (!isToolWorkflow(workflow)) {\n continue;\n }\n const { queueName, concurrencyLimit } = this.getQueueInfo(workflow);\n this.mergeQueue(queues, queueName, concurrencyLimit);\n }\n\n if (queues.size === 0) {\n logger.info('No queues to register');\n return;\n }\n\n const queueList: QueueRegistration[] = Array.from(queues.entries()).map(\n ([name, concurrencyLimit]) => ({\n name,\n concurrencyLimit,\n })\n );\n\n await this.orchestratorClient.registerQueues({\n deploymentId: this.config.deploymentId,\n queues: queueList,\n });\n\n logger.info(`Registered ${String(queues.size)} queue(s)`);\n }\n\n /**\n * Mark worker as online.\n */\n private async markOnline(): Promise<void> {\n if (!this.workerId) {\n throw new Error('Worker not registered');\n }\n\n await this.orchestratorClient.markOnline(this.workerId);\n logger.info('Worker marked as online');\n }\n\n /**\n * Setup worker server for push mode.\n */\n private async setupWorkerServer(): Promise<void> {\n if (!this.workerId) {\n throw new Error('Worker not registered');\n }\n\n this.workerServer = new WorkerServer({\n workerId: this.workerId,\n maxConcurrentWorkflows: this.maxConcurrentWorkflows,\n onWorkReceived: (data) => this.handleWorkReceived(data),\n onCancelRequested: (executionId) => this.handleCancelRequested(executionId),\n port: this.port,\n localMode: this.config.localMode,\n });\n\n await this.workerServer.start();\n }\n\n /**\n * Start heartbeat loop.\n */\n private startHeartbeat(): void {\n this.heartbeatInterval = setInterval(() => {\n void this.sendHeartbeat();\n }, 30000); // 30 seconds\n }\n\n /**\n * Send heartbeat to orchestrator.\n */\n private async sendHeartbeat(): Promise<void> {\n if (!this.workerId) {\n return;\n }\n\n try {\n const response = await this.orchestratorClient.sendHeartbeat(this.workerId);\n\n if (response.re_register) {\n logger.info('Orchestrator requested re-registration');\n await this.reRegister();\n }\n } catch (error) {\n logger.warn('Heartbeat failed', { error: String(error) });\n }\n }\n\n /**\n * Re-register worker, deployment, workflows, and queues.\n */\n private async reRegister(): Promise<void> {\n try {\n await this.register();\n await this.registerDeployment();\n await this.registerAgents();\n await this.registerTools();\n await this.registerWorkflows();\n await this.registerQueues();\n await this.markOnline();\n\n // Update worker server with new worker ID\n if (this.workerServer && this.workerId) {\n this.workerServer.updateWorkerId(this.workerId);\n }\n\n // Update sandbox manager with new worker ID\n if (this.workerId) {\n this.sandboxManager.setWorkerId(this.workerId);\n }\n\n logger.info('Re-registration complete');\n } catch (error) {\n logger.error('Re-registration failed', { error: String(error) });\n }\n }\n\n /**\n * Handle work received from orchestrator.\n */\n private async handleWorkReceived(data: WorkerExecutionData): Promise<void> {\n const { executionId, workflowId } = data;\n\n // Find workflow (check local registry first, then global registry)\n let workflow = this.workflowRegistry.get(workflowId);\n if (!workflow && globalRegistry.has(workflowId)) {\n workflow = globalRegistry.get(workflowId);\n }\n if (!workflow) {\n logger.error(`Workflow not found: ${workflowId}`);\n await this.reportFailure(executionId, `Workflow not found: ${workflowId}`, false);\n return;\n }\n\n // Create abort controller for cancellation\n const abortController = new AbortController();\n this.activeExecutions.set(executionId, { abortController });\n\n // Enforce per-execution timeout\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n if (data.runTimeoutSeconds) {\n timeoutId = setTimeout(() => {\n logger.warn(`Execution ${executionId} timed out after ${String(data.runTimeoutSeconds)}s`);\n abortController.abort();\n }, data.runTimeoutSeconds * 1000);\n }\n\n let result: ExecutionResult | undefined;\n let retryableFailure = true;\n\n try {\n // Build execution context\n const context: ExecutionContext = {\n executionId,\n deploymentId: data.deploymentId,\n parentExecutionId: data.parentExecutionId,\n rootExecutionId: data.rootExecutionId,\n rootWorkflowId: data.rootWorkflowId,\n retryCount: data.retryCount,\n sessionId: data.sessionId,\n userId: data.userId,\n otelTraceparent: data.otelTraceparent,\n otelSpanId: data.otelSpanId,\n initialState: data.initialState,\n runTimeoutSeconds: data.runTimeoutSeconds,\n createdAt: data.createdAt,\n channelContext: data.channelContext,\n };\n\n // Resolve channels: workflow-level overrides channelContext overrides worker-level\n const hasWorkflowChannels = workflow.config.channels !== undefined;\n const resolvedChannels = workflow.config.channels ?? this.channels;\n\n // Execute workflow\n result = await executeWorkflow({\n workflow,\n payload: data.payload,\n context,\n orchestratorClient: this.orchestratorClient,\n workerId: this.getWorkerIdOrThrow(),\n abortSignal: abortController.signal,\n channels: resolvedChannels,\n sandboxManager: this.sandboxManager,\n channelContext: hasWorkflowChannels ? undefined : data.channelContext,\n });\n\n // Start channel bridge for output streaming (always uses channelContext, independent of channel resolution)\n if (data.channelContext) {\n this.startChannelBridge(executionId, workflowId, data.channelContext, workflow);\n }\n\n // Handle result\n await this.handleExecutionResult(executionId, workflowId, context, result);\n // Cancelled and successful executions are not retryable.\n // For non-waiting failures reported via result (not thrown), check result.retryable.\n retryableFailure = !result.success && !result.waiting && (result.retryable ?? true);\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n const stack = error instanceof Error ? error.stack : undefined;\n\n // StepExecutionError and \"tool\" workflows are not retryable\n const retryable =\n !(error instanceof StepExecutionError) && workflow.config.workflowType !== 'tool';\n\n retryableFailure = retryable;\n logger.error(`Execution failed: ${executionId}`, { error: errorMessage, stack });\n await this.reportFailure(executionId, errorMessage, retryable, stack);\n } finally {\n if (timeoutId) clearTimeout(timeoutId);\n this.activeExecutions.delete(executionId);\n\n // Notify sandbox manager — but NOT if execution is suspended (waiting)\n // or if the failure is retryable (orchestrator will re-dispatch).\n if (!result?.waiting && !retryableFailure) {\n try {\n await this.sandboxManager.onExecutionComplete(executionId);\n } catch (err) {\n logger.warn('Failed to notify sandbox manager of execution completion', {\n executionId,\n error: String(err),\n });\n }\n }\n }\n }\n\n /**\n * Handle execution result.\n */\n private async handleExecutionResult(\n executionId: string,\n workflowId: string,\n context: ExecutionContext,\n result: ExecutionResult\n ): Promise<void> {\n if (result.success) {\n await this.reportSuccess(executionId, result.result, result.finalState);\n } else if (result.waiting) {\n // Workflow is waiting (WaitError) - don't report as failure\n logger.debug(`Execution ${executionId} is waiting: ${result.error ?? 'unknown'}`);\n } else if (result.error === 'Execution cancelled') {\n await this.emitCancellationEvent(executionId, workflowId, context);\n await this.confirmCancellation(executionId);\n } else {\n await this.reportFailure(\n executionId,\n result.error ?? 'Unknown error',\n result.retryable ?? true,\n result.stack,\n result.finalState\n );\n }\n }\n\n /**\n * Handle cancel request from orchestrator.\n */\n // eslint-disable-next-line @typescript-eslint/require-await -- interface requires async\n private async handleCancelRequested(executionId: string): Promise<boolean> {\n const execution = this.activeExecutions.get(executionId);\n if (execution) {\n execution.abortController.abort();\n return true;\n }\n return false;\n }\n\n /**\n * Report successful execution.\n */\n private async reportSuccess(\n executionId: string,\n result: unknown,\n finalState?: Record<string, unknown>\n ): Promise<void> {\n try {\n await this.orchestratorClient.completeExecution(executionId, {\n result,\n workerId: this.getWorkerIdOrThrow(),\n finalState: finalState\n ? (JSON.parse(serializeFinalState(finalState)) as Record<string, unknown>)\n : undefined,\n });\n logger.debug(`Reported success: ${executionId}`);\n } catch (error) {\n if (error instanceof OrchestratorApiError && error.statusCode === 409) {\n logger.debug(`Execution ${executionId} was reassigned, ignoring completion`);\n return;\n }\n logger.error(`Failed to report success: ${executionId}`, { error: String(error) });\n }\n }\n\n /**\n * Report failed execution.\n */\n private async reportFailure(\n executionId: string,\n error: string,\n retryable: boolean,\n stack?: string,\n finalState?: Record<string, unknown>\n ): Promise<void> {\n try {\n await this.orchestratorClient.failExecution(executionId, {\n error,\n workerId: this.getWorkerIdOrThrow(),\n stack,\n retryable,\n finalState: finalState\n ? (JSON.parse(serializeFinalState(finalState)) as Record<string, unknown>)\n : undefined,\n });\n logger.debug(`Reported failure: ${executionId}`);\n } catch (err) {\n if (err instanceof OrchestratorApiError && err.statusCode === 409) {\n logger.debug(`Execution ${executionId} was reassigned, ignoring failure report`);\n return;\n }\n logger.error(`Failed to report failure: ${executionId}`, { error: String(err) });\n }\n }\n\n /**\n * Emit a cancellation event so UI/streaming clients are notified.\n */\n private async emitCancellationEvent(\n executionId: string,\n workflowId: string,\n context: ExecutionContext\n ): Promise<void> {\n try {\n const rootExecutionId = context.rootExecutionId ?? executionId;\n const rootWorkflowId = context.rootWorkflowId ?? workflowId;\n const topic = `workflow/${rootWorkflowId}/${rootExecutionId}`;\n await this.orchestratorClient.publishEvent({\n topic,\n events: [\n {\n eventType: 'workflow_cancel',\n data: { _metadata: { execution_id: executionId, workflow_id: workflowId } },\n },\n ],\n executionId,\n rootExecutionId: context.rootExecutionId,\n });\n } catch (error) {\n logger.error(`Failed to emit cancellation event for ${executionId}`, {\n error: String(error),\n });\n }\n }\n\n /**\n * Confirm cancellation.\n */\n private async confirmCancellation(executionId: string): Promise<void> {\n try {\n await this.orchestratorClient.confirmCancellation(executionId, {\n workerId: this.getWorkerIdOrThrow(),\n });\n logger.debug(`Confirmed cancellation: ${executionId}`);\n } catch (error) {\n if (error instanceof OrchestratorApiError && error.statusCode === 409) {\n logger.debug(`Execution ${executionId} was reassigned, ignoring cancellation confirmation`);\n return;\n }\n logger.error(`Failed to confirm cancellation: ${executionId}`, { error: String(error) });\n }\n }\n\n /**\n * Start a channel bridge that streams execution events back to the originating channel.\n */\n private startChannelBridge(\n executionId: string,\n workflowId: string,\n channelCtx: { channelId: string; source: Record<string, unknown> },\n workflow: Workflow\n ): void {\n const channel = this.channels.find((ch) => ch.id === channelCtx.channelId);\n if (!channel?.sendOutput) return;\n\n const outputMode: ChannelOutputMode =\n ((workflow.config as unknown as Record<string, unknown>)['channelOutputMode'] as\n | ChannelOutputMode\n | undefined) ??\n channel.outputMode ??\n 'per_step';\n if (outputMode === 'none') return;\n\n const execution = this.activeExecutions.get(executionId);\n if (!execution) return;\n\n const rootExecutionId = execution.abortController.signal.aborted ? executionId : executionId;\n const rootWorkflowId = workflowId;\n\n void (async () => {\n try {\n const stream = this.orchestratorClient.streamEvents({\n workflowId: rootWorkflowId,\n workflowRunId: rootExecutionId,\n });\n for await (const event of stream) {\n if (execution.abortController.signal.aborted) break;\n if (shouldForwardEvent(event, outputMode)) {\n await channel.sendOutput?.(channelCtx as ChannelContext, event);\n }\n }\n } catch (err) {\n logger.warn('Channel bridge error', { error: String(err), executionId });\n }\n })();\n }\n}\n\n/**\n * Determine whether an event should be forwarded based on the output mode.\n */\nfunction shouldForwardEvent(event: StreamEvent, mode: ChannelOutputMode): boolean {\n const eventType = event.eventType;\n if (mode === 'per_step') {\n return (\n eventType === 'text_delta' ||\n eventType === 'tool_call' ||\n eventType === 'step_finish' ||\n eventType === 'workflow_finish' ||\n eventType === 'agent_finish'\n );\n }\n if (mode === 'final') {\n return eventType === 'workflow_finish' || eventType === 'agent_finish';\n }\n return false;\n}\n","/**\n * Unified Polos class that combines PolosClient (submit/stream work) and Worker\n * (receive/execute work) into a single object.\n */\n\nimport {\n PolosClient,\n type EventsApi,\n type SchedulesApi,\n type ClientInvokeOptions,\n type ClientBatchWorkflowInput,\n} from './client.js';\nimport { Worker } from './runtime/worker.js';\nimport type { Workflow, WorkflowRunClient } from './core/workflow.js';\nimport type { Channel } from './channels/channel.js';\nimport { globalRegistry } from './core/registry.js';\nimport type { ExecutionHandle } from './execution-handle.js';\nimport type { GetExecutionResponse } from './runtime/orchestrator-types.js';\nimport { createLogger, configureLogging } from './utils/logger.js';\n\nconst logger = createLogger({ name: 'polos' });\n\n/**\n * Configuration for the unified Polos class.\n * All fields are optional — defaults come from environment variables.\n */\nexport interface PolosConfig {\n /** Project ID (default: POLOS_PROJECT_ID env var) */\n projectId?: string | undefined;\n /** Orchestrator API URL (default: POLOS_API_URL or http://localhost:8080) */\n apiUrl?: string | undefined;\n /** API key (default: POLOS_API_KEY env var) */\n apiKey?: string | undefined;\n /** Deployment ID (default: POLOS_DEPLOYMENT_ID or \"default\") */\n deploymentId?: string | undefined;\n /** Worker server port (default: 8000) */\n port?: number | undefined;\n /** Maximum concurrent workflow executions */\n maxConcurrentWorkflows?: number | undefined;\n /** Notification channels for suspend events */\n channels?: Channel[] | undefined;\n /** Path to a log file. When set, SDK logs are written here instead of stdout. */\n logFile?: string | undefined;\n}\n\n/**\n * Unified Polos client + worker.\n *\n * @example\n * ```typescript\n * import { Polos, defineAgent } from '@polos/sdk';\n * import { openai } from '@ai-sdk/openai';\n *\n * const agent = defineAgent({\n * id: 'weather',\n * model: openai('gpt-4o'),\n * systemPrompt: 'You are a weather assistant.',\n * });\n *\n * const polos = new Polos();\n * await polos.start();\n * const result = await agent.run(polos, { input: \"What's the weather?\" });\n * await polos.stop();\n * ```\n */\nexport class Polos implements WorkflowRunClient {\n private readonly client: PolosClient;\n private readonly worker: Worker;\n private started = false;\n private serverPromise: Promise<void> | null = null;\n\n /**\n * Events API for publishing and subscribing to events.\n */\n public readonly events: EventsApi;\n\n /**\n * Schedules API for managing workflow schedules.\n */\n public readonly schedules: SchedulesApi;\n\n constructor(config: PolosConfig = {}) {\n // Redirect SDK logs to file if requested\n if (config.logFile) {\n configureLogging({ file: config.logFile });\n }\n\n const projectId = config.projectId ?? process.env['POLOS_PROJECT_ID'] ?? '';\n const apiUrl = config.apiUrl ?? process.env['POLOS_API_URL'] ?? 'http://localhost:8080';\n const apiKey = config.apiKey ?? process.env['POLOS_API_KEY'] ?? '';\n const deploymentId = config.deploymentId ?? process.env['POLOS_DEPLOYMENT_ID'] ?? 'default';\n const port =\n config.port ??\n (process.env['POLOS_WORKER_PORT'] ? Number(process.env['POLOS_WORKER_PORT']) : 8000);\n\n // Create client\n this.client = new PolosClient({\n projectId,\n apiUrl,\n apiKey,\n deploymentId,\n });\n\n // Discover workflows from globalRegistry — they auto-register\n // when defined with defineAgent(), defineTool(), defineWorkflow().\n const workflows: Workflow[] = globalRegistry.getAll();\n\n // Create worker\n this.worker = new Worker({\n apiUrl,\n apiKey,\n projectId,\n deploymentId,\n workflows,\n maxConcurrentWorkflows: config.maxConcurrentWorkflows,\n port,\n localMode: true,\n channels: config.channels,\n });\n\n // Expose APIs from client\n this.events = this.client.events;\n this.schedules = this.client.schedules;\n }\n\n /**\n * Start the worker in background (non-blocking).\n *\n * Registers with orchestrator, starts worker server, begins heartbeat.\n * Returns once registration is complete so the caller can immediately\n * invoke workflows.\n */\n async start(): Promise<void> {\n if (this.started) {\n return;\n }\n\n // Phase 1: register (blocking — must complete before we return)\n await this.worker.registerAll();\n this.started = true;\n\n // Phase 2: start server in background (non-blocking)\n this.serverPromise = this.worker.runServer().catch((err: unknown) => {\n logger.error('Worker server error', { error: String(err) });\n });\n\n logger.info('Polos started');\n }\n\n /**\n * Start the worker and block until shutdown signal (SIGINT/SIGTERM).\n *\n * This is the deployment mode — equivalent to Worker.run().\n * Use for servers, Kubernetes, Docker, etc.\n */\n async serve(): Promise<void> {\n await this.start();\n if (this.serverPromise) {\n await this.serverPromise;\n }\n }\n\n /**\n * Gracefully stop the worker and clean up.\n */\n async stop(): Promise<void> {\n if (!this.started) {\n return;\n }\n\n await this.worker.shutdown();\n\n if (this.serverPromise) {\n // Wait for server to finish shutting down\n await this.serverPromise;\n this.serverPromise = null;\n }\n\n this.started = false;\n logger.info('Polos stopped');\n }\n\n /**\n * Get the underlying PolosClient.\n * Needed for APIs that require PolosClient explicitly (e.g., agent.stream()).\n */\n getClient(): PolosClient {\n return this.client;\n }\n\n // ── WorkflowRunClient interface ──\n\n /**\n * Invoke a workflow (fire and forget).\n */\n async invoke(\n workflow: string | Workflow,\n payload?: unknown,\n options?: ClientInvokeOptions\n ): Promise<ExecutionHandle> {\n return this.client.invoke(workflow, payload, options);\n }\n\n /**\n * Invoke multiple workflows in batch.\n */\n async batchInvoke(\n items: ClientBatchWorkflowInput[],\n options?: {\n sessionId?: string;\n userId?: string;\n parentExecutionId?: string;\n rootWorkflowId?: string;\n rootExecutionId?: string;\n stepKey?: string;\n waitForSubworkflow?: boolean;\n }\n ): Promise<ExecutionHandle[]> {\n return this.client.batchInvoke(items, options);\n }\n\n /**\n * Resume a suspended execution.\n */\n async resume(\n suspendWorkflowId: string,\n suspendExecutionId: string,\n suspendStepKey: string,\n data: unknown\n ): Promise<void> {\n return this.client.resume(suspendWorkflowId, suspendExecutionId, suspendStepKey, data);\n }\n\n /**\n * Get execution details.\n */\n async getExecution(executionId: string): Promise<GetExecutionResponse> {\n return this.client.getExecution(executionId);\n }\n\n /**\n * Cancel an execution.\n */\n async cancelExecution(executionId: string): Promise<boolean> {\n return this.client.cancelExecution(executionId);\n }\n}\n","/**\n * Queue configuration for workflow execution.\n *\n * Queues control concurrency and ordering of workflow executions.\n */\n\n/**\n * Options for creating a Queue.\n */\nexport interface QueueOptions {\n /** Maximum concurrent executions in this queue */\n concurrencyLimit?: number | undefined;\n}\n\n/**\n * Queue class for named execution queues.\n *\n * @example\n * ```typescript\n * import { Queue, defineWorkflow } from '@polos/sdk';\n *\n * const dbQueue = new Queue('database-ops', { concurrencyLimit: 5 });\n *\n * const dbWorkflow = defineWorkflow({\n * id: 'db-operation',\n * queue: dbQueue,\n * }, async (ctx, payload) => {\n * // ...\n * });\n * ```\n */\nexport class Queue {\n /** Queue name */\n readonly name: string;\n\n /** Maximum concurrent executions (undefined = no limit) */\n readonly concurrencyLimit?: number | undefined;\n\n constructor(name: string, options?: QueueOptions) {\n this.name = name;\n this.concurrencyLimit = options?.concurrencyLimit;\n }\n\n /**\n * Convert to queue configuration object.\n */\n toConfig(): QueueConfig {\n const config: QueueConfig = { name: this.name };\n if (this.concurrencyLimit !== undefined) {\n config.concurrencyLimit = this.concurrencyLimit;\n }\n return config;\n }\n}\n\n/**\n * Queue configuration object (used in workflow config).\n */\nexport interface QueueConfig {\n /** Queue name */\n name: string;\n /** Maximum concurrent executions */\n concurrencyLimit?: number | undefined;\n}\n\n/**\n * Normalize queue configuration from various input formats.\n */\nexport function normalizeQueueConfig(\n queue: string | Queue | QueueConfig | undefined\n): QueueConfig | undefined {\n if (queue === undefined) {\n return undefined;\n }\n\n if (typeof queue === 'string') {\n return { name: queue };\n }\n\n if (queue instanceof Queue) {\n return queue.toConfig();\n }\n\n return queue;\n}\n\n/**\n * Default queue name.\n */\nexport const DEFAULT_QUEUE = 'default';\n\n/**\n * Get the queue name from various input formats.\n */\nexport function getQueueName(queue: string | Queue | QueueConfig | undefined): string {\n if (queue === undefined) {\n return DEFAULT_QUEUE;\n }\n\n if (typeof queue === 'string') {\n return queue;\n }\n\n if (queue instanceof Queue) {\n return queue.name;\n }\n\n return queue.name;\n}\n","/**\n * Batch workflow triggering utilities.\n *\n * Matches Python sdk/python/polos/runtime/batch.py.\n */\n\nimport type { PolosClient, ClientBatchWorkflowInput } from '../client.js';\nimport type { ExecutionHandle } from '../execution-handle.js';\nimport { AgentRunConfig } from '../core/step.js';\nimport { assertNotInExecutionContext } from './execution-context.js';\n\n// Re-export AgentRunConfig so existing imports from this module still work\nexport { AgentRunConfig };\n\n/**\n * Invoke multiple different workflows in a single batch and return handles immediately.\n *\n * This function cannot be called from within a workflow or agent.\n * Use step.batchInvoke() to call workflows from within workflows.\n *\n * Matches Python batch_invoke().\n */\nexport async function batchInvoke(\n client: PolosClient,\n workflows: ClientBatchWorkflowInput[],\n sessionId?: string,\n userId?: string\n): Promise<ExecutionHandle[]> {\n assertNotInExecutionContext('batchInvoke()', 'step.batchInvoke()');\n\n return client.batchInvoke(workflows, {\n ...(sessionId !== undefined && { sessionId }),\n ...(userId !== undefined && { userId }),\n });\n}\n\n/**\n * Invoke multiple agents in parallel and return execution handles.\n *\n * This helper is intended for use with agent.withInput(), which returns\n * AgentRunConfig instances.\n *\n * Matches Python batch_agent_invoke().\n *\n * @example\n * ```typescript\n * const handles = await batchAgentInvoke(client, [\n * grammarAgent.withInput(\"Check this\"),\n * toneAgent.withInput(\"Check this too\"),\n * ]);\n * ```\n */\nexport async function batchAgentInvoke(\n client: PolosClient,\n agents: AgentRunConfig[]\n): Promise<ExecutionHandle[]> {\n const workflows: ClientBatchWorkflowInput[] = agents.map((config) => ({\n workflow: config.agent,\n payload: {\n input: config.input,\n streaming: config.streaming,\n session_id: config.sessionId,\n user_id: config.userId,\n ...config.kwargs,\n },\n initialState: config.initialState,\n runTimeoutSeconds: config.runTimeoutSeconds,\n }));\n\n return batchInvoke(client, workflows);\n}\n","/**\n * Agent-related type definitions.\n *\n * Note: Core agent implementation types (StopCondition, StopConditionContext,\n * StepInfo, ToolResultInfo, AgentWorkflow, DefineAgentConfig) are defined in\n * src/agents/ and exported from there. This file contains supplementary types\n * used by the public API (Guardrail, Agent, AgentStream, etc.) and placeholder\n * types for future client-side features.\n */\n\nimport type { LanguageModel, ModelMessage } from 'ai';\n\n// Backwards-compat alias: CoreMessage was renamed to ModelMessage in ai v6\ntype CoreMessage = ModelMessage;\nimport type { ZodType } from 'zod';\nimport type { WorkflowContext, QueueConfig, Hook } from './workflow.js';\nimport type { TokenUsage, ToolCall } from './llm.js';\n\n/**\n * Tool definition with Zod schemas for input/output.\n */\nexport interface Tool<TInput = unknown, TOutput = unknown> {\n /** Unique tool identifier */\n id: string;\n /** Tool description (shown to LLM) */\n description: string;\n /** Zod schema for input validation */\n inputSchema: ZodType<TInput>;\n /** Zod schema for output validation */\n outputSchema: ZodType<TOutput>;\n /** Tool handler function */\n handler: ToolHandler<TInput, TOutput>;\n}\n\n/**\n * Tool handler function type.\n */\nexport type ToolHandler<TInput, TOutput> = (\n ctx: WorkflowContext,\n input: TInput\n) => Promise<TOutput>;\n\n/**\n * Configuration for defining a tool.\n */\nexport interface ToolConfig<TInput = unknown, TOutput = unknown> {\n /** Unique tool identifier */\n id: string;\n /** Tool description (shown to LLM) */\n description: string;\n /** Zod schema for input validation */\n inputSchema: ZodType<TInput>;\n /** Zod schema for output validation */\n outputSchema: ZodType<TOutput>;\n}\n\n/**\n * Guardrail function type for validating LLM outputs.\n */\nexport type Guardrail = (\n ctx: WorkflowContext,\n guardrailCtx: GuardrailContext\n) => Promise<GuardrailResult>;\n\n/**\n * Context passed to guardrails.\n */\nexport interface GuardrailContext {\n /** Text content from LLM (if any) */\n content?: string;\n /** Tool calls from LLM (if any) */\n toolCalls: ToolCall[];\n /** Messages so far in the conversation */\n messages: CoreMessage[];\n}\n\n/**\n * Result from a guardrail execution.\n */\nexport interface GuardrailResult {\n /** Whether to continue execution */\n continue: boolean;\n /** Error message if guardrail failed */\n error?: string;\n /** Modified content to use instead */\n modifiedContent?: string;\n /** Modified tool calls to use instead */\n modifiedToolCalls?: ToolCall[];\n}\n\nexport const GuardrailResult = {\n /** Continue execution without modifications */\n continue: (): GuardrailResult => ({ continue: true }),\n\n /** Continue execution with modifications */\n continueWith: (options: {\n modifiedContent?: string;\n modifiedToolCalls?: ToolCall[];\n }): GuardrailResult => {\n const result: GuardrailResult = { continue: true };\n if (options.modifiedContent !== undefined) {\n result.modifiedContent = options.modifiedContent;\n }\n if (options.modifiedToolCalls !== undefined) {\n result.modifiedToolCalls = options.modifiedToolCalls;\n }\n return result;\n },\n\n /** Stop execution with an error */\n fail: (error: string): GuardrailResult => ({\n continue: false,\n error,\n }),\n};\n\n/**\n * Configuration for defining an agent (placeholder for client-side usage).\n */\nexport interface AgentConfig<TOutput = string, TState = unknown> {\n /** Unique agent identifier */\n id: string;\n /** Vercel AI SDK model instance */\n model: LanguageModel;\n /** System prompt for the agent */\n systemPrompt: string;\n /** Tools available to the agent */\n tools?: Tool[];\n\n /** LLM generation configuration */\n temperature?: number;\n maxTokens?: number;\n topP?: number;\n\n /** Queue assignment for execution */\n queue?: string | QueueConfig;\n\n /** Zod schema for structured output */\n outputSchema?: ZodType<TOutput>;\n\n /** Lifecycle hooks */\n onStart?: Hook<string, TState>;\n onEnd?: Hook<string, TState>;\n onAgentStepStart?: Hook<string, TState>;\n onAgentStepEnd?: Hook<string, TState>;\n onToolStart?: Hook<string, TState>;\n onToolEnd?: Hook<string, TState>;\n\n /** Guardrails for output validation */\n guardrails?: Guardrail[];\n /** Max retries when guardrail fails */\n guardrailMaxRetries?: number;\n}\n\n/**\n * Result from running an agent (client-side).\n */\nexport interface AgentResult<TOutput = string> {\n /** Agent output (typed if outputSchema provided) */\n output: TOutput;\n /** All messages in the conversation */\n messages: CoreMessage[];\n /** Token usage statistics */\n usage: TokenUsage;\n /** Steps executed by the agent */\n steps: AgentStep[];\n}\n\n/**\n * A single step in agent execution (client-side view).\n */\nexport interface AgentStep {\n /** Type of step */\n type: 'thinking' | 'tool_call' | 'tool_result' | 'text';\n /** Text content (for thinking/text steps) */\n content?: string;\n /** Tool name (for tool_call/tool_result steps) */\n toolName?: string;\n /** Tool input (for tool_call steps) */\n toolInput?: unknown;\n /** Tool output (for tool_result steps) */\n toolOutput?: unknown;\n /** Token usage for this step */\n usage?: TokenUsage;\n /** When this step occurred */\n timestamp: Date;\n}\n\n/**\n * Agent instance with run/stream methods.\n */\nexport interface Agent<TOutput = string, TState = unknown> {\n /** Agent identifier */\n id: string;\n /** Agent configuration */\n config: AgentConfig<TOutput, TState>;\n\n /**\n * Run the agent with a user message and wait for result.\n */\n run(message: string, options?: AgentRunOptions): Promise<AgentResult<TOutput>>;\n\n /**\n * Run the agent and stream the response.\n */\n stream(message: string, options?: AgentRunOptions): Promise<AgentStream<TOutput>>;\n}\n\n/**\n * Options for running an agent.\n */\nexport interface AgentRunOptions {\n /** Initial conversation messages */\n messages?: CoreMessage[];\n /** Timeout in milliseconds */\n timeout?: number;\n /** Initial state */\n initialState?: unknown;\n}\n\n/**\n * Stream of agent events.\n */\nexport interface AgentStream<TOutput = string> extends AsyncIterable<AgentStreamEvent> {\n /** Async iterable of text chunks only */\n textChunks: AsyncIterable<string>;\n\n /** Accumulate all text chunks into a single string */\n text(): Promise<string>;\n\n /** Wait for final result */\n result(): Promise<AgentResult<TOutput>>;\n}\n\n/**\n * Events emitted during agent streaming.\n * Matches Python's actual SSE event types.\n */\nexport type AgentStreamEvent =\n | { type: 'stream_start'; step: number }\n | { type: 'text_delta'; step: number; chunkIndex: number; content?: string }\n | { type: 'tool_call'; step: number; chunkIndex: number; toolCall?: unknown }\n | { type: 'agent_finish'; result: unknown };\n","/**\n * Ask-user tool — lets agents ask questions and receive answers from the user.\n *\n * Uses ctx.step.suspend() to pause the workflow, emit a suspend event with a\n * _form schema, and wait for the user to respond via client.resume(). Supports\n * both structured form fields and simple free-text responses.\n */\n\nimport { z } from 'zod';\nimport { defineTool } from '../core/tool.js';\nimport type { ToolWorkflow } from '../core/tool.js';\n\nconst askUserInputSchema = z.object({\n question: z.string().describe('The question to ask the user'),\n title: z.string().optional().describe('Short title for the question (shown as heading)'),\n fields: z\n .array(\n z.object({\n key: z.string().describe('Unique key for this field'),\n type: z.enum(['text', 'textarea', 'number', 'boolean', 'select']).describe('Field type'),\n label: z.string().describe('Label shown to user'),\n description: z.string().optional().describe('Help text for the field'),\n required: z.boolean().optional().describe('Whether this field is required'),\n options: z\n .array(\n z.object({\n label: z.string(),\n value: z.string(),\n })\n )\n .optional()\n .describe('Options for select fields'),\n })\n )\n .optional()\n .describe(\n 'Structured form fields for the response. If omitted, shows a single text response field.'\n ),\n});\n\n/**\n * Create the ask_user tool for agent-to-user communication.\n *\n * When an agent calls this tool, the workflow suspends and emits a suspend\n * event with a `_form` schema. The client handles the event, collects the\n * user's response, and resumes the workflow with the response data.\n *\n * @example\n * ```typescript\n * import { createAskUserTool } from '@polos/sdk';\n *\n * const askUser = createAskUserTool();\n * // Add to agent tools array\n * ```\n */\nexport function createAskUserTool(): ToolWorkflow {\n return defineTool(\n {\n id: 'ask_user',\n description:\n 'Ask the user a question and wait for their response. ' +\n 'Use this when you need clarification, a decision, or any input from the user. ' +\n 'You can define structured fields (text, select, boolean, etc.) ' +\n 'for specific response formats, or omit fields for a free-text response.',\n inputSchema: askUserInputSchema,\n },\n async (ctx, input) => {\n const fields = input.fields ?? [\n {\n key: 'response',\n type: 'textarea' as const,\n label: input.question,\n required: true,\n },\n ];\n\n const askId = await ctx.step.uuid('_ask_user_id');\n const response = await ctx.step.suspend(`ask_user_${askId}`, {\n data: {\n _form: {\n title: input.title ?? 'Agent Question',\n description: input.question,\n fields,\n },\n _source: 'ask_user',\n _tool: 'ask_user',\n },\n });\n\n return (response as Record<string, unknown> | undefined)?.['data'] ?? {};\n }\n ) as ToolWorkflow;\n}\n","/**\n * Web search tool — lets agents search the web for current information.\n *\n * Defaults to the Tavily Search API using raw fetch() (no additional\n * dependencies). Users can plug in any search provider via a custom\n * function.\n *\n * @example\n * ```typescript\n * import { createWebSearchTool } from '@polos/sdk';\n *\n * // Tavily with env var (TAVILY_API_KEY)\n * const webSearch = createWebSearchTool();\n *\n * // Custom provider\n * const webSearch = createWebSearchTool({\n * search: async (query, opts) => {\n * const res = await mySearchApi(query, opts.maxResults);\n * return { query, results: res.items };\n * },\n * });\n * ```\n */\n\nimport { z } from 'zod';\nimport { defineTool } from '../core/tool.js';\nimport type { ToolWorkflow, ToolApproval } from '../core/tool.js';\n\n// ── Result types (provider-agnostic) ─────────────────────────────────\n\n/** A single search result item. */\nexport interface WebSearchResultItem {\n title: string;\n url: string;\n /** Snippet or summary of the page content. */\n content: string;\n /** Relevance score, 0–1. */\n score?: number | undefined;\n /** Publication date in ISO 8601 format. */\n publishedDate?: string | undefined;\n}\n\n/** Full search result returned by the tool. */\nexport interface WebSearchResult {\n query: string;\n results: WebSearchResultItem[];\n /** AI-generated summary (Tavily feature). */\n answer?: string | undefined;\n}\n\n// ── Options passed to the search function ────────────────────────────\n\n/** Options forwarded to the search function at call time. */\nexport interface WebSearchOptions {\n maxResults: number;\n topic: 'general' | 'news';\n}\n\n// ── Custom provider interface ────────────────────────────────────────\n\n/** Signature for a custom search provider function. */\nexport type WebSearchFunction = (\n query: string,\n options: WebSearchOptions\n) => Promise<WebSearchResult>;\n\n// ── Configuration ────────────────────────────────────────────────────\n\n/** Tavily-specific configuration knobs. */\nexport interface TavilySearchConfig {\n /** Tavily API key. Falls back to the TAVILY_API_KEY environment variable. */\n apiKey?: string;\n /** Search depth. @default 'basic' */\n searchDepth?: 'basic' | 'advanced';\n /** Include an AI-generated answer in the response. @default true */\n includeAnswer?: boolean;\n /** Include raw page content in results. @default false */\n includeRawContent?: boolean;\n /** Tavily API base URL. @default 'https://api.tavily.com' */\n baseUrl?: string;\n}\n\n/** Configuration for createWebSearchTool(). */\nexport interface WebSearchToolConfig extends TavilySearchConfig {\n /** Custom search provider. When set, overrides the built-in Tavily implementation. */\n search?: WebSearchFunction;\n /** Default maximum results per query. @default 5 */\n maxResults?: number;\n /** Default topic filter. @default 'general' */\n topic?: 'general' | 'news';\n /** Tool identifier exposed to the LLM. @default 'web_search' */\n toolId?: string;\n /** Require human approval before execution. */\n approval?: ToolApproval;\n}\n\n// ── LLM-facing input schema ──────────────────────────────────────────\n\nconst webSearchInputSchema = z.object({\n query: z.string().describe('The search query'),\n maxResults: z.number().optional().describe('Maximum number of results to return'),\n topic: z\n .enum(['general', 'news'])\n .optional()\n .describe('Topic filter: general web search or news'),\n});\n\ntype WebSearchInput = z.infer<typeof webSearchInputSchema>;\n\n// ── Tavily implementation (internal) ─────────────────────────────────\n\ninterface TavilyResponse {\n query: string;\n answer?: string;\n results: {\n title: string;\n url: string;\n content: string;\n score?: number;\n published_date?: string;\n raw_content?: string;\n }[];\n}\n\nfunction createTavilySearchFn(config: TavilySearchConfig): WebSearchFunction {\n return async (query: string, options: WebSearchOptions): Promise<WebSearchResult> => {\n const apiKey = config.apiKey ?? process.env['TAVILY_API_KEY'];\n if (!apiKey) {\n throw new Error(\n 'Tavily API key is required. Provide it via the apiKey option or set the TAVILY_API_KEY environment variable.'\n );\n }\n\n const baseUrl = (config.baseUrl ?? 'https://api.tavily.com').replace(/\\/+$/, '');\n\n const body = {\n query,\n max_results: options.maxResults,\n search_depth: config.searchDepth ?? 'basic',\n include_answer: config.includeAnswer ?? true,\n include_raw_content: config.includeRawContent ?? false,\n topic: options.topic,\n };\n\n const response = await fetch(`${baseUrl}/search`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(body),\n });\n\n if (!response.ok) {\n let errorMessage: string;\n try {\n const errorBody = (await response.json()) as Record<string, unknown>;\n errorMessage =\n typeof errorBody['detail'] === 'string' ? errorBody['detail'] : JSON.stringify(errorBody);\n } catch {\n errorMessage = await response.text();\n }\n throw new Error(`Tavily API error (${String(response.status)}): ${errorMessage}`);\n }\n\n const data = (await response.json()) as TavilyResponse;\n\n return {\n query: data.query,\n answer: data.answer,\n results: data.results.map((r) => ({\n title: r.title,\n url: r.url,\n content: r.content,\n score: r.score,\n publishedDate: r.published_date,\n })),\n };\n };\n}\n\n// ── Factory ──────────────────────────────────────────────────────────\n\n/**\n * Create a web search tool for agent use.\n *\n * By default uses the Tavily Search API via raw fetch(). Pass a custom\n * `search` function to use any other provider.\n *\n * @example\n * ```typescript\n * // Tavily with env var\n * const webSearch = createWebSearchTool();\n *\n * // Tavily with explicit key\n * const webSearch = createWebSearchTool({ apiKey: 'tvly-xxx' });\n *\n * // Custom provider\n * const webSearch = createWebSearchTool({\n * search: async (query, opts) => {\n * const res = await myApi(query, opts.maxResults);\n * return { query, results: res.items };\n * },\n * });\n * ```\n */\nexport function createWebSearchTool(config?: WebSearchToolConfig): ToolWorkflow {\n const toolId = config?.toolId ?? 'web_search';\n const defaultMaxResults = config?.maxResults ?? 5;\n const defaultTopic = config?.topic ?? 'general';\n\n // Search function resolved lazily — custom provider or Tavily default.\n // For Tavily, the API key is resolved at call time (not factory time).\n const searchFn: WebSearchFunction = config?.search ?? createTavilySearchFn(config ?? {});\n\n return defineTool(\n {\n id: toolId,\n description:\n 'Search the web for current information. ' +\n 'Returns a list of relevant results with titles, URLs, and content snippets.',\n inputSchema: webSearchInputSchema,\n approval: config?.approval,\n },\n async (ctx, input: WebSearchInput) => {\n const options: WebSearchOptions = {\n maxResults: input.maxResults ?? defaultMaxResults,\n topic: input.topic ?? defaultTopic,\n };\n\n const result = await ctx.step.run('web_search', () => searchFn(input.query, options), {\n input: { query: input.query, options },\n });\n\n return result;\n }\n ) as ToolWorkflow;\n}\n","/**\n * Security utilities for the execution framework.\n *\n * Provides allowlist evaluation for command security and path safety\n * checks for file operations.\n */\n\nimport { resolve } from 'node:path';\n\n/**\n * Match a text string against a simple glob pattern.\n * Supports `*` as a wildcard that matches any sequence of characters.\n *\n * @param text - The text to match\n * @param pattern - Glob pattern with `*` wildcards\n * @returns Whether the text matches the pattern\n */\nexport function matchGlob(text: string, pattern: string): boolean {\n // Escape regex special chars except *, then convert * to .*\n const escaped = pattern.replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&');\n const regexStr = `^${escaped.replace(/\\*/g, '.*')}$`;\n return new RegExp(regexStr).test(text);\n}\n\n/**\n * Evaluate a command against an allowlist of glob patterns.\n *\n * Matches the full command string against each pattern.\n * Patterns support `*` wildcards (e.g., `node *`, `npm *`, `*`).\n *\n * @param command - The shell command to check\n * @param patterns - Array of glob patterns to match against\n * @returns Whether the command matches any pattern in the allowlist\n */\nexport function evaluateAllowlist(command: string, patterns: string[]): boolean {\n const trimmed = command.trim();\n return patterns.some((pattern) => matchGlob(trimmed, pattern));\n}\n\n/**\n * Check whether a resolved path stays within a restriction directory.\n *\n * @param resolvedPath - The fully resolved path to check\n * @param restriction - The base directory the path must stay within\n * @returns Whether the path is within the restriction\n */\nexport function isWithinRestriction(resolvedPath: string, restriction: string): boolean {\n const base = resolve(restriction);\n return resolvedPath === base || resolvedPath.startsWith(base + '/');\n}\n\n/**\n * Assert that a file path stays within a restriction directory.\n * Throws if path traversal is detected.\n *\n * @param filePath - The file path to check\n * @param restriction - The base directory paths must stay within\n * @throws Error if the resolved path escapes the restriction directory\n */\nexport function assertSafePath(filePath: string, restriction: string): void {\n const base = resolve(restriction);\n const resolved = resolve(base, filePath);\n\n if (!isWithinRestriction(resolved, base)) {\n throw new Error(`Path traversal detected: \"${filePath}\" resolves outside of \"${restriction}\"`);\n }\n}\n","/**\n * Exec tool — run shell commands inside the execution environment.\n */\n\nimport { z } from 'zod';\nimport { defineTool } from '../../core/tool.js';\nimport type { ToolWorkflow } from '../../core/tool.js';\nimport type { WorkflowContext } from '../../core/context.js';\nimport type { ExecutionEnvironment, ExecResult, ExecToolConfig } from '../types.js';\nimport { evaluateAllowlist } from '../security.js';\n\n/**\n * Resume data shape from the approval form.\n */\ninterface ApprovalResumeData {\n data?: {\n approved?: boolean;\n allow_always?: boolean;\n feedback?: string;\n };\n}\n\n/**\n * Suspend for user approval of a command.\n */\nasync function requestApproval(\n ctx: WorkflowContext,\n command: string,\n env: ExecutionEnvironment\n): Promise<{ approved: boolean; feedback?: string }> {\n const envInfo = env.getInfo();\n const approvalId = await ctx.step.uuid('_approval_id');\n const response = await ctx.step.suspend<Record<string, unknown>, ApprovalResumeData>(\n `approve_exec_${approvalId}`,\n {\n data: {\n _form: {\n title: 'Approve command execution',\n description: `The agent wants to run a shell command in the ${envInfo.type} environment.`,\n fields: [\n {\n key: 'approved',\n type: 'boolean',\n label: 'Approve this command?',\n required: true,\n default: false,\n },\n {\n key: 'allow_always',\n type: 'boolean',\n label: 'Always allow this command in the future?',\n required: false,\n default: false,\n },\n {\n key: 'feedback',\n type: 'textarea',\n label: 'Feedback for the agent (optional)',\n description: 'If rejecting, tell the agent what to do instead.',\n required: false,\n },\n ],\n context: {\n command,\n cwd: env.getCwd(),\n environment: envInfo.type,\n },\n },\n _source: 'exec_security',\n _tool: 'exec',\n },\n }\n );\n\n const feedback = response.data?.feedback;\n return {\n approved: response.data?.approved === true,\n ...(feedback ? { feedback } : {}),\n };\n}\n\n/**\n * Build a rejected ExecResult.\n * Includes user feedback in stderr so the agent can adjust its approach.\n */\nfunction rejectedResult(command: string, feedback?: string): ExecResult {\n let stderr = `Command rejected by user: ${command}`;\n if (feedback) {\n stderr += `\\nUser feedback: ${feedback}`;\n }\n return {\n exitCode: -1,\n stdout: '',\n stderr,\n durationMs: 0,\n truncated: false,\n };\n}\n\n/**\n * Create the exec tool for running shell commands.\n */\nexport function createExecTool(\n getEnv: () => Promise<ExecutionEnvironment>,\n config?: ExecToolConfig\n): ToolWorkflow {\n return defineTool(\n {\n id: 'exec',\n description:\n 'Execute a shell command in the sandbox environment. Returns stdout, stderr, and exit code. ' +\n 'Use this for running builds, tests, installing packages, or any shell operation.',\n inputSchema: z.object({\n command: z.string().describe('The shell command to execute'),\n cwd: z.string().optional().describe('Working directory for the command'),\n env: z.record(z.string(), z.string()).optional().describe('Environment variables to set'),\n timeout: z.number().optional().describe('Timeout in seconds (default: 300)'),\n }),\n },\n async (ctx, input) => {\n const env = await getEnv();\n\n if (config?.security === 'approval-always') {\n const result = await requestApproval(ctx, input.command, env);\n if (!result.approved) return rejectedResult(input.command, result.feedback);\n } else if (config?.security === 'allowlist') {\n if (!evaluateAllowlist(input.command, config.allowlist ?? [])) {\n const result = await requestApproval(ctx, input.command, env);\n if (!result.approved) return rejectedResult(input.command, result.feedback);\n }\n }\n // 'allow-always' or undefined → no check\n\n return env.exec(input.command, {\n cwd: input.cwd,\n env: input.env,\n timeout: input.timeout ?? config?.timeout,\n });\n }\n ) as ToolWorkflow;\n}\n","/**\n * Path-based approval for read-only sandbox tools.\n *\n * When pathRestriction is set, read-only tools (read, glob, grep) allow\n * operations within the restricted path without approval. Operations\n * outside the restriction suspend for user approval.\n */\n\nimport { resolve } from 'node:path';\nimport type { WorkflowContext } from '../../core/context.js';\nimport { isWithinRestriction } from '../security.js';\n\n/**\n * Configuration for path-restricted approval on read-only tools.\n */\nexport interface PathRestrictionConfig {\n /** Directory to allow without approval. Paths outside require approval. */\n pathRestriction: string;\n}\n\n/**\n * Resume data shape from the path approval form.\n */\ninterface PathApprovalResumeData {\n data?: { approved?: boolean; feedback?: string };\n}\n\n/**\n * Check whether a resolved path is within the restriction.\n */\nexport function isPathAllowed(resolvedPath: string, restriction: string): boolean {\n return isWithinRestriction(resolvedPath, resolve(restriction));\n}\n\n/**\n * Suspend for user approval when accessing a path outside the restriction.\n * Returns the approval result. Throws if rejected.\n */\nexport async function requirePathApproval(\n ctx: WorkflowContext,\n toolName: string,\n targetPath: string,\n restriction: string\n): Promise<void> {\n const approvalId = await ctx.step.uuid('_approval_id');\n const response = await ctx.step.suspend<Record<string, unknown>, PathApprovalResumeData>(\n `approve_${toolName}_${approvalId}`,\n {\n data: {\n _form: {\n title: `${toolName}: access outside workspace`,\n description: `The agent wants to ${toolName} a path outside the workspace.`,\n fields: [\n {\n key: 'approved',\n type: 'boolean',\n label: 'Allow this operation?',\n required: true,\n default: false,\n },\n {\n key: 'feedback',\n type: 'textarea',\n label: 'Feedback for the agent (optional)',\n description: 'If rejecting, tell the agent what to do instead.',\n required: false,\n },\n ],\n context: {\n tool: toolName,\n path: targetPath,\n restriction,\n },\n },\n _source: 'path_approval',\n _tool: toolName,\n },\n }\n );\n\n if (response.data?.approved !== true) {\n const feedback = response.data?.feedback;\n throw new Error(\n `Access to \"${targetPath}\" was rejected by the user.${feedback ? ` Feedback: ${feedback}` : ''}`\n );\n }\n}\n","/**\n * Read tool — read file contents from the execution environment.\n *\n * When pathRestriction is set, reads within the restriction proceed\n * without approval. Reads outside the restriction suspend for user approval.\n */\n\nimport { resolve } from 'node:path';\nimport { z } from 'zod';\nimport { defineTool } from '../../core/tool.js';\nimport type { ToolWorkflow } from '../../core/tool.js';\nimport type { ExecutionEnvironment } from '../types.js';\nimport type { PathRestrictionConfig } from './path-approval.js';\nimport { isPathAllowed, requirePathApproval } from './path-approval.js';\n\n/**\n * Create the read tool for reading file contents.\n */\nexport function createReadTool(\n getEnv: () => Promise<ExecutionEnvironment>,\n pathConfig?: PathRestrictionConfig\n): ToolWorkflow {\n return defineTool(\n {\n id: 'read',\n description:\n 'Read the contents of a file. Returns the file content as text. ' +\n 'Optionally specify offset (line number to start from, 0-based) and limit (number of lines).',\n inputSchema: z.object({\n path: z.string().describe('Path to the file to read'),\n offset: z.number().optional().describe('Line offset to start reading from (0-based)'),\n limit: z.number().optional().describe('Maximum number of lines to return'),\n }),\n },\n async (ctx, input) => {\n const env = await getEnv();\n\n // Check path restriction — approve if outside\n if (pathConfig?.pathRestriction) {\n const resolved = resolve(env.getCwd(), input.path);\n if (!isPathAllowed(resolved, pathConfig.pathRestriction)) {\n await requirePathApproval(ctx, 'read', resolved, pathConfig.pathRestriction);\n }\n }\n\n let content = await env.readFile(input.path);\n\n // Apply offset/limit if specified\n if (input.offset !== undefined || input.limit !== undefined) {\n const lines = content.split('\\n');\n const start = input.offset ?? 0;\n const end = input.limit !== undefined ? start + input.limit : lines.length;\n content = lines.slice(start, end).join('\\n');\n }\n\n return { content, path: input.path };\n }\n ) as ToolWorkflow;\n}\n","/**\n * Write tool — create or overwrite files in the execution environment.\n */\n\nimport { z } from 'zod';\nimport { defineTool } from '../../core/tool.js';\nimport type { ToolWorkflow, ToolApproval } from '../../core/tool.js';\nimport type { ExecutionEnvironment } from '../types.js';\n\n/**\n * Create the write tool for writing file contents.\n */\nexport function createWriteTool(\n getEnv: () => Promise<ExecutionEnvironment>,\n approval?: ToolApproval\n): ToolWorkflow {\n return defineTool(\n {\n id: 'write',\n description:\n 'Write content to a file. Creates the file if it does not exist, or overwrites it if it does. ' +\n 'Parent directories are created automatically.',\n inputSchema: z.object({\n path: z.string().describe('Path to the file to write'),\n content: z.string().describe('Content to write to the file'),\n }),\n approval,\n },\n async (_ctx, input) => {\n const env = await getEnv();\n await env.writeFile(input.path, input.content);\n return { success: true, path: input.path };\n }\n ) as ToolWorkflow;\n}\n","/**\n * Edit tool — find-and-replace text in files in the execution environment.\n */\n\nimport { z } from 'zod';\nimport { defineTool } from '../../core/tool.js';\nimport type { ToolWorkflow, ToolApproval } from '../../core/tool.js';\nimport type { ExecutionEnvironment } from '../types.js';\n\n/**\n * Create the edit tool for find-and-replace in files.\n */\nexport function createEditTool(\n getEnv: () => Promise<ExecutionEnvironment>,\n approval?: ToolApproval\n): ToolWorkflow {\n return defineTool(\n {\n id: 'edit',\n description:\n 'Edit a file by replacing an exact string match. The old_text must match exactly ' +\n '(including whitespace and indentation). Use this for precise code modifications.',\n inputSchema: z.object({\n path: z.string().describe('Path to the file to edit'),\n old_text: z.string().describe('Exact text to find and replace'),\n new_text: z.string().describe('Text to replace the old_text with'),\n }),\n approval,\n },\n async (_ctx, input) => {\n const env = await getEnv();\n const content = await env.readFile(input.path);\n\n if (!content.includes(input.old_text)) {\n throw new Error(\n `old_text not found in ${input.path}. Make sure the text matches exactly, ` +\n 'including whitespace and indentation.'\n );\n }\n\n const newContent = content.replace(input.old_text, input.new_text);\n await env.writeFile(input.path, newContent);\n\n return { success: true, path: input.path };\n }\n ) as ToolWorkflow;\n}\n","/**\n * Glob tool — find files by pattern in the execution environment.\n *\n * When pathRestriction is set, searches within the restriction proceed\n * without approval. Custom cwd outside the restriction suspends for approval.\n */\n\nimport { resolve } from 'node:path';\nimport { z } from 'zod';\nimport { defineTool } from '../../core/tool.js';\nimport type { ToolWorkflow } from '../../core/tool.js';\nimport type { ExecutionEnvironment } from '../types.js';\nimport type { PathRestrictionConfig } from './path-approval.js';\nimport { isPathAllowed, requirePathApproval } from './path-approval.js';\n\n/**\n * Create the glob tool for finding files by pattern.\n */\nexport function createGlobTool(\n getEnv: () => Promise<ExecutionEnvironment>,\n pathConfig?: PathRestrictionConfig\n): ToolWorkflow {\n return defineTool(\n {\n id: 'glob',\n description:\n 'Find files matching a glob pattern. Returns a list of file paths. ' +\n 'Use this to discover files in the project structure.',\n inputSchema: z.object({\n pattern: z.string().describe('Glob pattern to match (e.g., \"*.ts\", \"src/**/*.js\")'),\n cwd: z.string().optional().describe('Directory to search in'),\n ignore: z.array(z.string()).optional().describe('Patterns to exclude from results'),\n }),\n },\n async (ctx, input) => {\n const env = await getEnv();\n\n // Check path restriction on custom cwd\n if (pathConfig?.pathRestriction && input.cwd) {\n const resolved = resolve(env.getCwd(), input.cwd);\n if (!isPathAllowed(resolved, pathConfig.pathRestriction)) {\n await requirePathApproval(ctx, 'glob', resolved, pathConfig.pathRestriction);\n }\n }\n\n const files = await env.glob(input.pattern, {\n cwd: input.cwd,\n ignore: input.ignore,\n });\n return { files };\n }\n ) as ToolWorkflow;\n}\n","/**\n * Grep tool — search file contents by pattern in the execution environment.\n *\n * When pathRestriction is set, searches within the restriction proceed\n * without approval. Custom cwd outside the restriction suspends for approval.\n */\n\nimport { resolve } from 'node:path';\nimport { z } from 'zod';\nimport { defineTool } from '../../core/tool.js';\nimport type { ToolWorkflow } from '../../core/tool.js';\nimport type { ExecutionEnvironment } from '../types.js';\nimport type { PathRestrictionConfig } from './path-approval.js';\nimport { isPathAllowed, requirePathApproval } from './path-approval.js';\n\n/**\n * Create the grep tool for searching file contents.\n */\nexport function createGrepTool(\n getEnv: () => Promise<ExecutionEnvironment>,\n pathConfig?: PathRestrictionConfig\n): ToolWorkflow {\n return defineTool(\n {\n id: 'grep',\n description:\n 'Search file contents for a pattern using grep. Returns matching lines with file paths ' +\n 'and line numbers. Use this to find code patterns, references, or specific text.',\n inputSchema: z.object({\n pattern: z.string().describe('Search pattern (regex supported)'),\n cwd: z.string().optional().describe('Directory to search in'),\n include: z\n .array(z.string())\n .optional()\n .describe('File patterns to include (e.g., [\"*.ts\", \"*.js\"])'),\n maxResults: z\n .number()\n .optional()\n .describe('Maximum number of matches to return (default: 100)'),\n contextLines: z.number().optional().describe('Number of context lines around each match'),\n }),\n },\n async (ctx, input) => {\n const env = await getEnv();\n\n // Check path restriction on custom cwd\n if (pathConfig?.pathRestriction && input.cwd) {\n const resolved = resolve(env.getCwd(), input.cwd);\n if (!isPathAllowed(resolved, pathConfig.pathRestriction)) {\n await requirePathApproval(ctx, 'grep', resolved, pathConfig.pathRestriction);\n }\n }\n\n const matches = await env.grep(input.pattern, {\n cwd: input.cwd,\n include: input.include,\n maxResults: input.maxResults,\n contextLines: input.contextLines,\n });\n return { matches };\n }\n ) as ToolWorkflow;\n}\n","/**\n * Sandbox tools factory.\n *\n * Creates a set of tools (exec, read, write, edit, glob, grep) that share\n * a managed sandbox. The sandbox is created lazily on first tool use\n * via the SandboxManager injected through the execution context.\n *\n * @example\n * ```typescript\n * import { defineAgent, sandboxTools } from '@polos/sdk';\n *\n * // Per-execution (default) — sandbox dies when the workflow finishes\n * const agent = defineAgent({\n * id: 'solver',\n * tools: sandboxTools({\n * env: 'docker',\n * docker: { image: 'node:20', workspaceDir: '/path/to/project' },\n * }),\n * });\n *\n * // Per-session — sandbox lives across turns\n * const agent2 = defineAgent({\n * id: 'coder',\n * tools: sandboxTools({\n * scope: 'session',\n * env: 'docker',\n * docker: { image: 'node:20', workspaceDir: '/path/to/project' },\n * }),\n * });\n * ```\n */\n\nimport type { ToolWorkflow } from '../core/tool.js';\nimport type { ExecutionEnvironment, SandboxToolsConfig, ExecToolConfig } from './types.js';\nimport type { Sandbox } from './sandbox.js';\nimport { getExecutionContext } from '../runtime/execution-context.js';\nimport { createExecTool } from './tools/exec.js';\nimport { createReadTool } from './tools/read.js';\nimport { createWriteTool } from './tools/write.js';\nimport { createEditTool } from './tools/edit.js';\nimport { createGlobTool } from './tools/glob.js';\nimport { createGrepTool } from './tools/grep.js';\n\n/**\n * Create sandbox tools for AI agents.\n *\n * Returns an array of ToolWorkflow that can be passed directly to defineAgent().\n * All tools share a single managed sandbox that is lazily created on first use.\n * Lifecycle is managed by the SandboxManager — no manual cleanup needed.\n */\nexport function sandboxTools(config?: SandboxToolsConfig): ToolWorkflow[] {\n // Cache keyed by rootExecutionId so all tool sub-workflows within the same\n // agent run share one sandbox. Each tool call runs as a separate sub-workflow\n // with its own executionId, but rootExecutionId is stable across them.\n const sandboxCache = new Map<string, Sandbox>();\n\n async function getEnv(): Promise<ExecutionEnvironment> {\n const ctx = getExecutionContext();\n if (!ctx) {\n throw new Error(\n 'sandboxTools requires an execution context. ' +\n 'Ensure tools are called within a workflow execution.'\n );\n }\n\n const { executionId, rootExecutionId, sessionId, sandboxManager } = ctx;\n if (!sandboxManager) {\n throw new Error(\n 'No SandboxManager found in execution context. ' +\n 'Ensure the Worker is configured to inject sandboxManager.'\n );\n }\n\n // Use rootExecutionId as cache key so all tool calls in the same agent\n // run share one sandbox. Falls back to executionId for top-level workflows.\n const cacheKey = rootExecutionId ?? executionId;\n\n // Check cache first\n const cached = sandboxCache.get(cacheKey);\n if (cached && !cached.destroyed) {\n return cached.getEnvironment();\n }\n\n // Create or retrieve sandbox via manager\n const sandbox = await sandboxManager.getOrCreateSandbox(config ?? {}, {\n executionId: cacheKey,\n sessionId,\n });\n sandboxCache.set(cacheKey, sandbox);\n\n return sandbox.getEnvironment();\n }\n\n // Validate environment type eagerly\n const envType = config?.env ?? 'docker';\n if (envType === 'e2b') {\n throw new Error('E2B environment is not yet implemented.');\n }\n\n // For local mode, default exec security to 'approval-always' (no sandbox isolation)\n const effectiveExecConfig: ExecToolConfig | undefined =\n envType === 'local' && !config?.exec?.security\n ? { ...config?.exec, security: 'approval-always' }\n : config?.exec;\n\n // For local mode, default file-mutating tools (write, edit) to approval-always\n const fileApproval = config?.fileApproval ?? (envType === 'local' ? 'always' : undefined);\n\n // Path restriction for read-only tools (read, glob, grep) — approval gate\n const pathConfig = config?.local?.pathRestriction\n ? { pathRestriction: config.local.pathRestriction }\n : undefined;\n\n // Determine which tools to include\n const include = new Set(\n config?.tools ?? (['exec', 'read', 'write', 'edit', 'glob', 'grep'] as const)\n );\n\n const tools: ToolWorkflow[] = [];\n\n if (include.has('exec')) tools.push(createExecTool(getEnv, effectiveExecConfig));\n if (include.has('read')) tools.push(createReadTool(getEnv, pathConfig));\n if (include.has('write')) tools.push(createWriteTool(getEnv, fileApproval));\n if (include.has('edit')) tools.push(createEditTool(getEnv, fileApproval));\n if (include.has('glob')) tools.push(createGlobTool(getEnv, pathConfig));\n if (include.has('grep')) tools.push(createGrepTool(getEnv, pathConfig));\n\n return tools;\n}\n","/**\n * Slack channel implementation — sends a Block Kit message with a \"Respond\"\n * link button when an agent suspends.\n *\n * Uses native `fetch` (Node 18+) — no @slack/web-api dependency required.\n */\n\nimport type { Channel, ChannelContext, ChannelOutputMode, SuspendNotification } from './channel.js';\nimport type { StreamEvent } from '../types/events.js';\n\n/**\n * Configuration for the Slack notification channel.\n */\nexport interface SlackChannelConfig {\n /** Slack bot token (xoxb-...) */\n botToken: string;\n /** Default Slack channel for notifications (e.g., \"#agent-notifications\") */\n defaultChannel: string;\n /** Slack signing secret for verifying inbound webhooks */\n signingSecret?: string;\n}\n\n/** Minimal Slack Block Kit block type. */\ninterface SlackBlock {\n type: string;\n text?: { type: string; text: string };\n elements?: Record<string, unknown>[];\n}\n\n/**\n * Slack notification channel that posts Block Kit messages with a \"Respond\"\n * link button pointing to the approval page.\n */\nexport class SlackChannel implements Channel {\n readonly id = 'slack';\n readonly outputMode: ChannelOutputMode = 'per_step';\n private readonly config: SlackChannelConfig;\n\n constructor(config: SlackChannelConfig) {\n if (!config.botToken.startsWith('xoxb-')) {\n throw new Error(\n 'Invalid Slack bot token: must start with \"xoxb-\". ' +\n \"Use the Bot User OAuth Token from your Slack app's OAuth & Permissions page.\"\n );\n }\n this.config = config;\n }\n\n async notify(notification: SuspendNotification): Promise<void> {\n const overrides = notification.channelOverrides;\n const channel = (overrides?.['channel'] as string | undefined) ?? this.config.defaultChannel;\n const threadTs = overrides?.['thread_ts'] as string | undefined;\n const blocks = this.buildBlocks(notification);\n const text = notification.title ?? 'Agent needs your input';\n\n await this.postMessage(channel, threadTs, text, blocks);\n }\n\n async sendOutput(context: ChannelContext, event: StreamEvent): Promise<void> {\n const channel = context.source['channel'] as string;\n const threadTs = context.source['threadTs'] as string | undefined;\n if (!channel) return;\n\n const text = this.formatOutputEvent(event);\n if (!text) return;\n\n await this.postMessage(channel, threadTs, text);\n }\n\n private async postMessage(\n channel: string,\n threadTs: string | undefined,\n text: string,\n blocks?: SlackBlock[]\n ): Promise<void> {\n const body: Record<string, unknown> = { channel, text };\n if (threadTs) body['thread_ts'] = threadTs;\n if (blocks) body['blocks'] = blocks;\n\n const response = await fetch('https://slack.com/api/chat.postMessage', {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${this.config.botToken}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(body),\n });\n\n const data = (await response.json()) as { ok: boolean; error?: string };\n if (!data.ok) {\n throw new Error(`Slack API error: ${data.error ?? 'unknown'}`);\n }\n }\n\n private formatOutputEvent(event: StreamEvent): string | null {\n const eventType = event.eventType;\n\n if (eventType === 'workflow_finish' || eventType === 'agent_finish') {\n const metadata = event.data['_metadata'] as Record<string, unknown> | undefined;\n const result = event.data['result'];\n const error = event.data['error'] as string | undefined;\n const workflowId = metadata?.['workflow_id'] as string | undefined;\n if (error) {\n return `\\u274C *${workflowId ?? 'Workflow'} failed:* ${error}`;\n }\n const resultStr = typeof result === 'string' ? result : JSON.stringify(result, null, 2);\n if (resultStr) {\n return `\\u2705 *${workflowId ?? 'Workflow'} finished:*\\n${resultStr}`;\n }\n return `\\u2705 *${workflowId ?? 'Workflow'} finished*`;\n }\n\n if (eventType === 'tool_call') {\n const toolCall = event.data['tool_call'] as Record<string, unknown> | undefined;\n if (toolCall) {\n const fn = toolCall['function'] as Record<string, unknown> | undefined;\n const name = fn?.['name'] as string | undefined;\n if (name) {\n return `\\uD83D\\uDD27 Calling tool: \\`${name}\\``;\n }\n }\n return null;\n }\n\n if (eventType === 'step_finish') {\n const stepKey = event.data['step_key'] as string | undefined;\n const error = event.data['error'] as string | undefined;\n if (error) {\n return `\\u26A0\\uFE0F Step \\`${stepKey ?? 'unknown'}\\` failed: ${error}`;\n }\n return null;\n }\n\n // text_delta: skip individual deltas to avoid noise\n return null;\n }\n\n private buildBlocks(n: SuspendNotification): SlackBlock[] {\n const blocks: SlackBlock[] = [];\n\n // Header\n blocks.push({\n type: 'header',\n text: { type: 'plain_text', text: n.title ?? 'Agent needs your input' },\n });\n\n // Description\n if (n.description) {\n blocks.push({\n type: 'section',\n text: { type: 'mrkdwn', text: n.description },\n });\n }\n\n // Source/tool metadata\n if (n.source || n.tool) {\n const parts: string[] = [];\n if (n.source) parts.push(`*Source:* ${n.source}`);\n if (n.tool) parts.push(`*Tool:* \\`${n.tool}\\``);\n blocks.push({\n type: 'context',\n elements: [{ type: 'mrkdwn', text: parts.join(' | ') }],\n });\n }\n\n // Context data (tool arguments, etc.)\n if (n.context && Object.keys(n.context).length > 0) {\n const contextText = JSON.stringify(n.context, null, 2);\n blocks.push({\n type: 'section',\n text: { type: 'mrkdwn', text: '```' + contextText + '```' },\n });\n }\n\n // Expiry warning\n if (n.expiresAt) {\n blocks.push({\n type: 'context',\n elements: [{ type: 'mrkdwn', text: `Expires: ${n.expiresAt}` }],\n });\n }\n\n // Action buttons — inline Approve/Reject for simple approvals, link button otherwise\n if (this.isSimpleApproval(n)) {\n const approveValue = JSON.stringify({\n executionId: n.executionId,\n stepKey: n.stepKey,\n approved: true,\n });\n const rejectValue = JSON.stringify({\n executionId: n.executionId,\n stepKey: n.stepKey,\n approved: false,\n });\n blocks.push({\n type: 'actions',\n elements: [\n {\n type: 'button',\n action_id: 'polos_approve',\n text: { type: 'plain_text', text: 'Approve' },\n style: 'primary',\n value: approveValue,\n },\n {\n type: 'button',\n action_id: 'polos_reject',\n text: { type: 'plain_text', text: 'Reject' },\n style: 'danger',\n value: rejectValue,\n },\n {\n type: 'button',\n text: { type: 'plain_text', text: 'View Details' },\n url: n.approvalUrl,\n },\n ],\n });\n } else {\n blocks.push({\n type: 'actions',\n elements: [\n {\n type: 'button',\n text: { type: 'plain_text', text: 'Respond' },\n url: n.approvalUrl,\n style: 'primary',\n },\n ],\n });\n }\n\n return blocks;\n }\n\n private isSimpleApproval(n: SuspendNotification): boolean {\n const fields = n.formFields;\n if (!fields || fields.length === 0) return false;\n return fields.some((f) => f['key'] === 'approved' && f['type'] === 'boolean');\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/core/registry.ts","../src/runtime/execution-context.ts","../src/middleware/hook.ts","../src/core/workflow.ts","../src/runtime/orchestrator-client.ts","../src/execution-handle.ts","../src/client.ts","../src/core/tool.ts","../src/llm/types.ts","../src/llm/llm.ts","../src/middleware/guardrail.ts","../src/utils/retry.ts","../src/core/step.ts","../src/middleware/hook-executor.ts","../src/middleware/guardrail-executor.ts","../src/llm/generate.ts","../src/llm/stream.ts","../src/agents/stop-conditions.ts","../src/utils/logger.ts","../src/memory/tokens.ts","../src/memory/compaction.ts","../src/agents/stream.ts","../src/agents/stream-result.ts","../src/agents/agent.ts","../src/runtime/worker-server.ts","../src/utils/serializer.ts","../src/core/state.ts","../node_modules/@opentelemetry/core/src/trace/suppress-tracing.ts","../node_modules/@opentelemetry/core/src/internal/validators.ts","../node_modules/@opentelemetry/core/src/trace/TraceState.ts","../node_modules/@opentelemetry/core/src/trace/W3CTraceContextPropagator.ts","../src/features/tracing.ts","../src/utils/tracing.ts","../src/runtime/executor.ts","../src/execution/output.ts","../src/execution/docker.ts","../src/execution/local.ts","../src/execution/sandbox.ts","../src/execution/sandbox-manager.ts","../src/runtime/worker.ts","../src/polos.ts","../src/runtime/queue.ts","../src/runtime/batch.ts","../src/types/agent.ts","../src/tools/ask-user.ts","../src/tools/web-search.ts","../src/execution/security.ts","../src/execution/tools/exec.ts","../src/execution/tools/path-approval.ts","../src/execution/tools/read.ts","../src/execution/tools/write.ts","../src/execution/tools/edit.ts","../src/execution/tools/glob.ts","../src/execution/tools/grep.ts","../src/execution/sandbox-tools.ts","../src/channels/slack.ts"],"names":["AsyncLocalStorage","options","path","resolve","toJSONSchema","jsonSchema","Output","generateText","streamText","randomUUID","maxTokens","maxSteps","executedTool","hasText","appendFileSync","context","logger","Fastify","createContextKey","TraceState","W3CTraceContextPropagator","trace","isSpanContextValid","TraceFlags","SpanStatusCode","randomBytes","BasicTracerProvider","BatchSpanProcessor","AsyncLocalStorageContextManager","otelContext","otelTrace","spawn","fs","relative","DEFAULT_TIMEOUT_SECONDS","DEFAULT_MAX_OUTPUT_CHARS","path2","stat","fs2","path3","os","fs3","GuardrailResult","z"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAWO,IAAM,qBAAA,GAAN,cAAoC,KAAA,CAAM;AAAA,EAC/C,YAA4B,UAAA,EAAoB;AAC9C,IAAA,KAAA,CAAM,CAAA,oBAAA,EAAuB,UAAU,CAAA,CAAE,CAAA;AADf,IAAA,IAAA,CAAA,UAAA,GAAA,UAAA;AAE1B,IAAA,IAAA,CAAK,IAAA,GAAO,uBAAA;AAAA,EACd;AACF;AAKO,IAAM,sBAAA,GAAN,cAAqC,KAAA,CAAM;AAAA,EAChD,YAA4B,UAAA,EAAoB;AAC9C,IAAA,KAAA,CAAM,CAAA,6BAAA,EAAgC,UAAU,CAAA,CAAE,CAAA;AADxB,IAAA,IAAA,CAAA,UAAA,GAAA,UAAA;AAE1B,IAAA,IAAA,CAAK,IAAA,GAAO,wBAAA;AAAA,EACd;AACF;AA+CO,SAAS,sBAAA,GAA2C;AACzD,EAAA,MAAM,SAAA,u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Ac,MAAM,QAAA,EAAS;AAAA,YAC3C,KAAA,EAAO,QAAA;AAAA,YACP,KAAA,EAAO;AAAA,WACT;AAAA,UACA;AAAA,YACE,IAAA,EAAM,QAAA;AAAA,YACN,IAAA,EAAM,EAAE,IAAA,EAAM,YAAA,EAAc,MAAM,cAAA,EAAe;AAAA,YACjD,KAAK,CAAA,CAAE;AAAA;AACT;AACF,OACD,CAAA;AAAA,IACH,CAAA,MAAO;AACL,MAAA,MAAA,CAAO,IAAA,CAAK;AAAA,QACV,IAAA,EAAM,SAAA;AAAA,QACN,QAAA,EAAU;AAAA,UACR;AAAA,YACE,IAAA,EAAM,QAAA;AAAA,YACN,IAAA,EAAM,EAAE,IAAA,EAAM,YAAA,EAAc,MAAM,SAAA,EAAU;AAAA,YAC5C,KAAK,CAAA,CAAE,WAAA;AAAA,YACP,KAAA,EAAO;AAAA;AACT;AACF,OACD,CAAA;AAAA,IACH;AAEA,IAAA,OAAO,MAAA;AAAA,EACT;AAAA,EAEQ,iBAAiB,CAAA,EAAiC;AACxD,IAAA,MAAM,SAAS,CAAA,CAAE,UAAA;AACjB,IAAA,IAAI,CAAC,MAAA,IAAU,MAAA,CAAO,MAAA,KAAW,GAAG,OAAO,KAAA;AAC3C,IAAA,OAAO,MAAA,CAAO,IAAA,CAAK,CAAC,CAAA,KAAM,CAAA,CAAE,KAAK,CAAA,KAAM,UAAA,IAAc,CAAA,CAAE,MAAM,CAAA,KAAM,SAAS,CAAA;AAAA,EAC9E;AACF","file":"index.cjs","sourcesContent":["/**\n * Workflow registry for tracking registered workflows.\n *\n * Used by Worker to find workflows to execute based on workflow ID.\n */\n\nimport type { Workflow } from '../types/workflow.js';\n\n/**\n * Error thrown when a workflow is not found in the registry.\n */\nexport class WorkflowNotFoundError extends Error {\n constructor(public readonly workflowId: string) {\n super(`Workflow not found: ${workflowId}`);\n this.name = 'WorkflowNotFoundError';\n }\n}\n\n/**\n * Error thrown when attempting to register a duplicate workflow.\n */\nexport class DuplicateWorkflowError extends Error {\n constructor(public readonly workflowId: string) {\n super(`Workflow already registered: ${workflowId}`);\n this.name = 'DuplicateWorkflowError';\n }\n}\n\n/**\n * Workflow registry interface.\n */\nexport interface WorkflowRegistry {\n /**\n * Register a workflow. If a workflow with the same ID is already\n * registered, it is silently replaced.\n */\n register(workflow: Workflow): void;\n\n /**\n * Get a workflow by ID.\n * @throws WorkflowNotFoundError if workflow is not found\n */\n get(workflowId: string): Workflow;\n\n /**\n * Check if a workflow is registered.\n */\n has(workflowId: string): boolean;\n\n /**\n * Get all registered workflows.\n */\n getAll(): Workflow[];\n\n /**\n * Get all workflow IDs.\n */\n getIds(): string[];\n\n /**\n * Remove a workflow from the registry.\n */\n remove(workflowId: string): boolean;\n\n /**\n * Clear all workflows from the registry.\n */\n clear(): void;\n}\n\n/**\n * Create a workflow registry.\n */\nexport function createWorkflowRegistry(): WorkflowRegistry {\n const workflows = new Map<string, Workflow>();\n\n return {\n register(workflow: Workflow): void {\n workflows.set(workflow.id, workflow);\n },\n\n get(workflowId: string): Workflow {\n const workflow = workflows.get(workflowId);\n if (!workflow) {\n throw new WorkflowNotFoundError(workflowId);\n }\n return workflow;\n },\n\n has(workflowId: string): boolean {\n return workflows.has(workflowId);\n },\n\n getAll(): Workflow[] {\n return Array.from(workflows.values());\n },\n\n getIds(): string[] {\n return Array.from(workflows.keys());\n },\n\n remove(workflowId: string): boolean {\n return workflows.delete(workflowId);\n },\n\n clear(): void {\n workflows.clear();\n },\n };\n}\n\n/**\n * Global workflow registry instance.\n * Uses globalThis so that ESM and CJS entry points share the same singleton\n * (avoids the dual-package hazard when both dist/index.js and dist/index.cjs\n * are loaded in the same process, e.g. via tsx).\n */\nconst REGISTRY_KEY = '__polos_global_registry__';\nexport const globalRegistry: WorkflowRegistry = ((globalThis as Record<string, unknown>)[\n REGISTRY_KEY\n] ??= createWorkflowRegistry()) as WorkflowRegistry;\n","/**\n * Execution context tracking using AsyncLocalStorage.\n *\n * Matches Python's _execution_context ContextVar in core/workflow.py.\n * Used to detect when code is running inside a workflow execution,\n * so that PolosClient methods can throw if misused from within a workflow.\n */\n\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport type { OrchestratorClient } from './orchestrator-client.js';\nimport type { SandboxManager } from '../execution/sandbox-manager.js';\n\n/**\n * Data stored in the execution context.\n */\nexport interface ExecutionContextData {\n executionId: string;\n workflowId: string;\n /** Root execution ID — stable across sub-workflows, used by sandbox tools for cache key. */\n rootExecutionId?: string | undefined;\n /** Session ID — used by sandbox tools to scope sandboxes. */\n sessionId?: string | undefined;\n /** Sandbox manager — injected by worker for managed sandbox lifecycle. */\n sandboxManager?: SandboxManager | undefined;\n /** Orchestrator client — needed by agents for conversation history. */\n orchestratorClient?: OrchestratorClient | undefined;\n /** OTel span context from current span (typed as unknown since @opentelemetry/api is optional). */\n _otelSpanContext?: unknown;\n /** Hex trace ID for the current span. */\n _otelTraceId?: string | undefined;\n /** Hex span ID for the current span. */\n _otelSpanId?: string | undefined;\n}\n\n/**\n * AsyncLocalStorage instance for tracking whether we're inside a workflow execution.\n * Matches Python's `_execution_context: ContextVar[dict | None]`.\n */\nconst executionContextStorage = new AsyncLocalStorage<ExecutionContextData>();\n\n/**\n * Run a function within an execution context.\n * Used by the executor to mark that workflow handler code is running.\n */\nexport function runInExecutionContext<T>(data: ExecutionContextData, fn: () => T): T {\n return executionContextStorage.run(data, fn);\n}\n\n/**\n * Check if we're currently inside a workflow execution.\n * Returns the context data if inside, undefined otherwise.\n */\nexport function getExecutionContext(): ExecutionContextData | undefined {\n return executionContextStorage.getStore();\n}\n\n/**\n * Assert that we're NOT inside a workflow execution.\n * Throws RuntimeError if called from within a workflow handler.\n *\n * Matches Python's pattern:\n * if _execution_context.get() is not None:\n * raise RuntimeError(\"... cannot be called from within a workflow ...\")\n */\nexport function assertNotInExecutionContext(methodName: string, alternative: string): void {\n const ctx = getExecutionContext();\n if (ctx !== undefined) {\n throw new Error(\n `${methodName} cannot be called from within a workflow or agent. ` +\n `Use ${alternative} to call workflows from within workflows.`\n );\n }\n}\n","/**\n * Lifecycle hooks for workflow and agent execution.\n *\n * Hooks allow intercepting and modifying workflow execution at key points.\n */\n\nimport type { WorkflowContext } from '../core/context.js';\n\n/**\n * Context passed to hooks during execution.\n */\nexport interface HookContext<TPayload = unknown> {\n /** Workflow ID (matching Python HookContext.workflow_id) */\n workflowId: string;\n /** Session ID (matching Python HookContext.session_id) */\n sessionId?: string | undefined;\n /** User ID (matching Python HookContext.user_id) */\n userId?: string | undefined;\n /** Current payload (may be modified by previous hooks) */\n currentPayload: TPayload;\n /** Current output (may be modified by previous hooks, only in onEnd) */\n // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents -- needed for exactOptionalPropertyTypes\n currentOutput?: unknown | undefined;\n /** Hook execution phase */\n phase: 'onStart' | 'onEnd';\n}\n\n/**\n * Result from a hook execution.\n */\nexport interface HookResultType {\n /** Whether to continue execution */\n continue: boolean;\n /** Error message if hook failed (matching Python HookResult.error_message) */\n error?: string | undefined;\n /** Modified payload (matching Python HookResult.modified_payload) */\n // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents -- needed for exactOptionalPropertyTypes\n modifiedPayload?: unknown | undefined;\n /** Modified output (matching Python HookResult.modified_output, only in onEnd) */\n // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents -- needed for exactOptionalPropertyTypes\n modifiedOutput?: unknown | undefined;\n}\n\n/**\n * Hook function type for workflow lifecycle events.\n */\nexport type HookHandler<TPayload = unknown, TState = unknown> = (\n ctx: WorkflowContext<TState>,\n hookCtx: HookContext<TPayload>\n) => Promise<HookResultType>;\n\n/**\n * Hook definition with optional metadata.\n */\nexport interface Hook<TPayload = unknown, TState = unknown> {\n /** Hook handler function */\n handler: HookHandler<TPayload, TState>;\n /** Optional hook name for debugging/tracing */\n name?: string | undefined;\n /** Optional hook description */\n description?: string | undefined;\n}\n\n/**\n * Options for defining a hook.\n */\nexport interface DefineHookOptions {\n /** Hook name for debugging/tracing */\n name?: string | undefined;\n /** Hook description */\n description?: string | undefined;\n}\n\n/**\n * Helper for creating hook results.\n */\nexport const HookResult = {\n /** Continue execution without modifications */\n continue: (): HookResultType => ({ continue: true }),\n\n /**\n * Continue execution with modifications.\n *\n * @example\n * ```typescript\n * return HookResult.continueWith({\n * modifiedPayload: {\n * ...hookCtx.currentPayload,\n * timestamp: Date.now(),\n * },\n * });\n * ```\n */\n continueWith: (options: {\n modifiedPayload?: unknown;\n modifiedOutput?: unknown;\n }): HookResultType => {\n const result: HookResultType = { continue: true };\n if (options.modifiedPayload !== undefined) {\n result.modifiedPayload = options.modifiedPayload;\n }\n if (options.modifiedOutput !== undefined) {\n result.modifiedOutput = options.modifiedOutput;\n }\n return result;\n },\n\n /**\n * Stop execution with an error.\n *\n * @example\n * ```typescript\n * if (!hookCtx.currentPayload.userId) {\n * return HookResult.fail('userId is required');\n * }\n * ```\n */\n fail: (error: string): HookResultType => ({\n continue: false,\n error,\n }),\n};\n\n/**\n * Define a hook for workflow lifecycle events.\n *\n * @example\n * ```typescript\n * const loggingHook = defineHook(async (ctx, hookCtx) => {\n * console.log(`Starting workflow: ${ctx.workflowId}`);\n * console.log(`Payload: ${JSON.stringify(hookCtx.currentPayload)}`);\n * return HookResult.continue();\n * });\n *\n * const validationHook = defineHook(\n * async (ctx, hookCtx) => {\n * if (!hookCtx.currentPayload.userId) {\n * return HookResult.fail('userId is required');\n * }\n * return HookResult.continue();\n * },\n * { name: 'validation-hook', description: 'Validates required fields' }\n * );\n * ```\n */\nexport function defineHook<TPayload = unknown, TState = unknown>(\n handler: HookHandler<TPayload, TState>,\n options?: DefineHookOptions\n): Hook<TPayload, TState> {\n return {\n handler,\n name: options?.name,\n description: options?.description,\n };\n}\n\n/**\n * Type guard to check if a value is a Hook object.\n */\nexport function isHook<TPayload = unknown, TState = unknown>(\n value: unknown\n): value is Hook<TPayload, TState> {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'handler' in value &&\n typeof (value as Hook).handler === 'function'\n );\n}\n\n/**\n * Normalize a hook handler or Hook object to a Hook.\n */\nexport function normalizeHook<TPayload = unknown, TState = unknown>(\n hookOrHandler: Hook<TPayload, TState> | HookHandler<TPayload, TState>\n): Hook<TPayload, TState> {\n if (isHook<TPayload, TState>(hookOrHandler)) {\n return hookOrHandler;\n }\n return { handler: hookOrHandler };\n}\n\n/**\n * Normalize an array of hooks or handlers.\n */\nexport function normalizeHooks<TPayload = unknown, TState = unknown>(\n hooks:\n | Hook<TPayload, TState>\n | HookHandler<TPayload, TState>\n | (Hook<TPayload, TState> | HookHandler<TPayload, TState>)[]\n | undefined\n): Hook<TPayload, TState>[] {\n if (hooks === undefined) {\n return [];\n }\n\n if (Array.isArray(hooks)) {\n return hooks.map((h) => normalizeHook(h));\n }\n\n return [normalizeHook(hooks)];\n}\n","/**\n * Workflow definition and creation.\n *\n * Provides the defineWorkflow function for creating typed, durable workflows.\n */\n\nimport type { ZodType } from 'zod';\nimport type { WorkflowContext } from './context.js';\nimport type { Channel } from '../channels/channel.js';\nimport { globalRegistry } from './registry.js';\nimport { assertNotInExecutionContext } from '../runtime/execution-context.js';\n\n// Re-export hook types from middleware (single source of truth)\nexport type {\n HookContext,\n HookResultType,\n HookHandler,\n Hook,\n DefineHookOptions,\n} from '../middleware/hook.js';\nexport {\n HookResult,\n defineHook,\n isHook,\n normalizeHook,\n normalizeHooks,\n} from '../middleware/hook.js';\n\n// Import types needed for WorkflowConfig\nimport type { HookHandler, Hook as HookObject } from '../middleware/hook.js';\n\n/**\n * Queue configuration for workflow execution.\n */\nexport interface QueueConfig {\n /** Queue name */\n name: string;\n /** Maximum concurrent executions in this queue */\n concurrencyLimit?: number | undefined;\n}\n\n/**\n * Schedule configuration for workflows.\n */\nexport interface ScheduleConfig {\n /** Cron expression (e.g., '0 8 * * *') */\n cron: string;\n /** Timezone for the schedule (e.g., 'America/New_York') */\n timezone?: string | undefined;\n}\n\n/**\n * Configuration for defining a workflow.\n */\nexport interface WorkflowConfig<TPayload = unknown, TState = unknown, TResult = unknown> {\n /** Unique workflow identifier */\n id: string;\n /** Description for team coordination */\n description?: string | undefined;\n /** Workflow type: \"workflow\", \"agent\", or \"tool\" (default: \"workflow\") */\n workflowType?: string | undefined;\n /** Queue assignment (string name or full config) */\n queue?: string | QueueConfig | undefined;\n /** Schedule for automatic execution. Set to true (without a cron) to mark as dynamically schedulable via client.schedules.create(). */\n schedule?: string | ScheduleConfig | boolean | undefined;\n /** Event topic that triggers this workflow */\n triggerOnEvent?: string | undefined;\n /** Batch size for event-triggered workflows */\n batchSize?: number | undefined;\n /** Batch timeout in seconds for event-triggered workflows */\n batchTimeoutSeconds?: number | undefined;\n /** Zod schema for payload validation */\n payloadSchema?: ZodType<TPayload> | undefined;\n /** Zod schema for state validation and defaults */\n stateSchema?: ZodType<TState> | undefined;\n /** Zod schema for output/result validation */\n outputSchema?: ZodType<TResult> | undefined;\n /** Hook(s) to run before workflow execution (bare function or Hook object) */\n onStart?:\n | HookHandler<TPayload, TState>\n | HookObject<TPayload, TState>\n | (HookHandler<TPayload, TState> | HookObject<TPayload, TState>)[]\n | undefined;\n /** Hook(s) to run after workflow completion (bare function or Hook object) */\n onEnd?:\n | HookHandler<TPayload, TState>\n | HookObject<TPayload, TState>\n | (HookHandler<TPayload, TState> | HookObject<TPayload, TState>)[]\n | undefined;\n /** Notification channels for suspend events. Overrides Worker-level channels. */\n channels?: Channel[] | undefined;\n}\n\n/**\n * Workflow handler function type.\n */\nexport type WorkflowHandler<TPayload, TState, TResult> = (\n ctx: WorkflowContext<TState>,\n payload: TPayload\n) => Promise<TResult>;\n\n/**\n * Handle to a running or completed workflow execution.\n */\nexport interface WorkflowHandle<TResult> {\n /** Execution identifier */\n executionId: string;\n /** Get the current status of the workflow */\n getStatus(): Promise<WorkflowStatus<TResult>>;\n /** Wait for the workflow to complete and return result */\n waitForResult(options?: { timeout?: number }): Promise<TResult>;\n /** Cancel the workflow execution */\n cancel(): Promise<void>;\n}\n\n/**\n * Status of a workflow execution.\n */\nexport interface WorkflowStatus<TResult> {\n status: 'queued' | 'running' | 'completed' | 'failed' | 'cancelled';\n result?: TResult | undefined;\n error?: string | undefined;\n createdAt: Date;\n completedAt?: Date | undefined;\n}\n\n/**\n * Minimal client interface for workflow.run() and workflow.invoke().\n * PolosClient satisfies this interface structurally.\n */\nexport interface WorkflowRunClient {\n invoke(\n workflow: string,\n payload?: unknown,\n options?: {\n initialState?: Record<string, unknown>;\n sessionId?: string;\n userId?: string;\n queueName?: string;\n concurrencyKey?: string;\n runTimeoutSeconds?: number;\n }\n ): Promise<{ getResult(timeout?: number): Promise<unknown> }>;\n}\n\n/**\n * Options for workflow.run().\n */\nexport interface WorkflowRunOptions {\n /** Timeout in seconds (default: 600) */\n timeout?: number | undefined;\n /** Initial state for the workflow */\n initialState?: Record<string, unknown> | undefined;\n /** Session ID */\n sessionId?: string | undefined;\n /** User ID */\n userId?: string | undefined;\n /** Queue name override */\n queueName?: string | undefined;\n /** Concurrency key for per-tenant queuing */\n concurrencyKey?: string | undefined;\n}\n\n/**\n * Workflow instance with configuration and handler.\n */\nexport interface Workflow<TPayload = unknown, TState = unknown, TResult = unknown> {\n /** Workflow identifier */\n readonly id: string;\n /** Description for team coordination */\n readonly description?: string | undefined;\n /** Workflow configuration */\n readonly config: WorkflowConfig<TPayload, TState, TResult>;\n /** Workflow handler function */\n readonly handler: WorkflowHandler<TPayload, TState, TResult>;\n /** Payload schema (if provided) */\n readonly payloadSchema?: ZodType<TPayload> | undefined;\n /** State schema (if provided) */\n readonly stateSchema?: ZodType<TState> | undefined;\n /** Output schema (if provided) */\n readonly outputSchema?: ZodType<TResult> | undefined;\n /**\n * Run workflow and wait for result (invoke + poll until complete).\n * Cannot be called from within a workflow; use step.invokeAndWait() instead.\n * Matches Python's workflow.run().\n */\n // Method syntax enables bivariant checking so AgentWorkflow can override with specific types\n run(client: WorkflowRunClient, payload: TPayload, options?: WorkflowRunOptions): Promise<TResult>;\n}\n\n/**\n * Infer payload type from a workflow.\n */\nexport type InferPayload<T> = T extends Workflow<infer P> ? P : never;\n\n/**\n * Infer state type from a workflow.\n */\nexport type InferState<T> = T extends Workflow<unknown, infer S> ? S : never;\n\n/**\n * Infer result type from a workflow.\n */\nexport type InferResult<T> = T extends Workflow<unknown, unknown, infer R> ? R : never;\n\n/**\n * Options for defineWorkflow.\n */\nexport interface DefineWorkflowOptions {\n /** Whether to auto-register the workflow in the global registry (default: true) */\n autoRegister?: boolean | undefined;\n}\n\n/**\n * Define a workflow with typed payload, state, and result.\n *\n * @example\n * ```typescript\n * import { defineWorkflow } from '@polos/sdk';\n * import { z } from 'zod';\n *\n * const myWorkflow = defineWorkflow({\n * id: 'my-workflow',\n * payloadSchema: z.object({ userId: z.string() }),\n * stateSchema: z.object({ count: z.number().default(0) }),\n * }, async (ctx, payload) => {\n * ctx.state.count += 1;\n * return { userId: payload.userId, count: ctx.state.count };\n * });\n * ```\n */\n/**\n * Validate that a cron expression uses minute granularity (5 fields), not second granularity (6 fields).\n * @internal\n */\nexport function validateCronGranularity(cron: string): void {\n const fields = cron.trim().split(/\\s+/);\n if (fields.length > 5) {\n throw new Error(\n `Cron expression \"${cron}\" appears to use second-level granularity (${String(fields.length)} fields). ` +\n 'Only minute-level granularity is supported (5 fields: min hour dom month dow).'\n );\n }\n}\n\nexport function defineWorkflow<TPayload = unknown, TState = unknown, TResult = unknown>(\n config: WorkflowConfig<TPayload, TState, TResult>,\n handler: WorkflowHandler<TPayload, TState, TResult>,\n options?: DefineWorkflowOptions\n): Workflow<TPayload, TState, TResult> {\n // Validate cron granularity if schedule is provided (skip boolean-only schedule)\n if (config.schedule && config.schedule !== true) {\n const cron = typeof config.schedule === 'string' ? config.schedule : config.schedule.cron;\n validateCronGranularity(cron);\n }\n\n const workflow: Workflow<TPayload, TState, TResult> = {\n id: config.id,\n description: config.description,\n config,\n handler,\n payloadSchema: config.payloadSchema,\n stateSchema: config.stateSchema,\n outputSchema: config.outputSchema,\n run: async (client, payload, options) => {\n assertNotInExecutionContext('workflow.run()', 'step.invokeAndWait()');\n const invokeOpts: Record<string, unknown> = {};\n if (options?.initialState !== undefined) invokeOpts['initialState'] = options.initialState;\n if (options?.sessionId !== undefined) invokeOpts['sessionId'] = options.sessionId;\n if (options?.userId !== undefined) invokeOpts['userId'] = options.userId;\n if (options?.queueName !== undefined) invokeOpts['queueName'] = options.queueName;\n if (options?.concurrencyKey !== undefined)\n invokeOpts['concurrencyKey'] = options.concurrencyKey;\n if (options?.timeout !== undefined)\n invokeOpts['runTimeoutSeconds'] = Math.ceil(options.timeout);\n const handle = await client.invoke(config.id, payload, invokeOpts);\n const result = await handle.getResult(options?.timeout ?? 600);\n return result as TResult;\n },\n };\n\n // Auto-register by default\n if (options?.autoRegister !== false) {\n globalRegistry.register(workflow as Workflow);\n }\n\n return workflow;\n}\n","/**\n * HTTP client for orchestrator API communication.\n */\n\nimport type {\n RegisterWorkerRequest,\n RegisterWorkerResponse,\n RegisterDeploymentRequest,\n RegisterWorkflowsRequest,\n RegisterQueuesRequest,\n RegisterAgentRequest,\n RegisterDeploymentWorkflowRequest,\n RegisterToolRequest,\n HeartbeatResponse,\n CompleteExecutionRequest,\n FailExecutionRequest,\n ConfirmCancellationRequest,\n StoreStepOutputRequest,\n StepOutput,\n SetWaitingRequest,\n PublishEventRequest,\n PublishEventResponse,\n StreamEventsParams,\n InvokeWorkflowRequest,\n InvokeWorkflowResponse,\n GetExecutionResponse,\n BatchInvokeWorkflowsRequest,\n BatchInvokeWorkflowsResponse,\n CreateScheduleRequest,\n CreateScheduleResponse,\n AddConversationHistoryRequest,\n GetConversationHistoryParams,\n ConversationMessage,\n SessionMemoryResponse,\n PutSessionMemoryRequest,\n GetActiveWorkersResponse,\n} from './orchestrator-types.js';\n\nimport type { StreamEvent } from '../types/events.js';\n\n/**\n * Configuration for OrchestratorClient.\n */\nexport interface OrchestratorClientConfig {\n /** Orchestrator API URL */\n apiUrl: string;\n /** API key for authentication */\n apiKey: string;\n /** Project ID */\n projectId: string;\n /** Request timeout in milliseconds (default: 30000) */\n timeout?: number | undefined;\n /** Max retries for failed requests (default: 3) */\n maxRetries?: number | undefined;\n}\n\n/**\n * Error thrown when orchestrator API request fails.\n */\nexport class OrchestratorApiError extends Error {\n constructor(\n message: string,\n public readonly statusCode: number,\n public readonly response?: unknown\n ) {\n super(message);\n this.name = 'OrchestratorApiError';\n }\n}\n\n/**\n * HTTP client for communicating with the Polos orchestrator.\n */\nexport class OrchestratorClient {\n private readonly apiUrl: string;\n private readonly apiKey: string;\n private readonly projectId: string;\n private readonly timeout: number;\n private readonly maxRetries: number;\n\n constructor(config: OrchestratorClientConfig) {\n this.apiUrl = config.apiUrl.replace(/\\/$/, ''); // Remove trailing slash\n this.apiKey = config.apiKey;\n this.projectId = config.projectId;\n this.timeout = config.timeout ?? 30000;\n this.maxRetries = config.maxRetries ?? 3;\n }\n\n /**\n * Get the API URL.\n */\n getApiUrl(): string {\n return this.apiUrl;\n }\n\n /**\n * Get the project ID.\n */\n getProjectId(): string {\n return this.projectId;\n }\n\n /**\n * Get default headers for API requests.\n */\n private getHeaders(workerId?: string): Record<string, string> {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.apiKey}`,\n 'X-Project-ID': this.projectId,\n };\n if (workerId) {\n headers['X-Worker-ID'] = workerId;\n }\n return headers;\n }\n\n /**\n * Make an HTTP request with retry logic.\n */\n private async request<T>(\n method: string,\n path: string,\n options?: {\n body?: unknown;\n workerId?: string;\n retries?: number;\n }\n ): Promise<T> {\n const url = `${this.apiUrl}${path}`;\n const retries = options?.retries ?? this.maxRetries;\n let lastError: Error | undefined;\n\n for (let attempt = 0; attempt <= retries; attempt++) {\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => {\n controller.abort();\n }, this.timeout);\n\n const fetchOptions: RequestInit = {\n method,\n headers: this.getHeaders(options?.workerId),\n signal: controller.signal,\n };\n if (options?.body) {\n fetchOptions.body = JSON.stringify(options.body);\n }\n const response = await fetch(url, fetchOptions);\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n const errorBody = await response.text().catch(() => '');\n let errorData: unknown;\n try {\n errorData = JSON.parse(errorBody);\n } catch {\n errorData = errorBody;\n }\n\n // Don't retry on 4xx errors (except 429)\n if (response.status >= 400 && response.status < 500 && response.status !== 429) {\n throw new OrchestratorApiError(\n `Request failed: ${String(response.status)} ${response.statusText}`,\n response.status,\n errorData\n );\n }\n\n throw new OrchestratorApiError(\n `Request failed: ${String(response.status)} ${response.statusText}`,\n response.status,\n errorData\n );\n }\n\n // Handle empty responses\n const text = await response.text();\n if (!text) {\n return undefined as T;\n }\n\n return JSON.parse(text) as T;\n } catch (error) {\n lastError = error instanceof Error ? error : new Error(String(error));\n\n // Don't retry on non-retryable errors\n if (\n error instanceof OrchestratorApiError &&\n error.statusCode < 500 &&\n error.statusCode !== 429\n ) {\n throw error;\n }\n\n // Wait before retry with exponential backoff\n if (attempt < retries) {\n const delay = Math.min(1000 * Math.pow(2, attempt), 16000);\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n }\n }\n\n throw lastError ?? new Error('Request failed after retries');\n }\n\n // ==================== Worker Lifecycle ====================\n\n /**\n * Register a worker with the orchestrator.\n */\n async registerWorker(request: RegisterWorkerRequest): Promise<RegisterWorkerResponse> {\n return this.request<RegisterWorkerResponse>('POST', '/api/v1/workers/register', {\n body: {\n deployment_id: request.deploymentId,\n project_id: request.projectId,\n mode: request.mode,\n capabilities: {\n runtime: request.capabilities.runtime,\n agent_ids: request.capabilities.agentIds,\n tool_ids: request.capabilities.toolIds,\n workflow_ids: request.capabilities.workflowIds,\n },\n max_concurrent_executions: request.maxConcurrentExecutions,\n push_endpoint_url: request.pushEndpointUrl,\n },\n });\n }\n\n /**\n * Get active worker IDs for the current project.\n * Uses the X-Project-ID header already set on all requests.\n */\n async getActiveWorkerIds(): Promise<string[]> {\n const response = await this.request<GetActiveWorkersResponse>('GET', '/api/v1/workers/active');\n return response.worker_ids;\n }\n\n /**\n * Register a deployment.\n */\n async registerDeployment(request: RegisterDeploymentRequest): Promise<void> {\n await this.request<undefined>('POST', '/api/v1/workers/deployments', {\n body: {\n deployment_id: request.deploymentId,\n },\n });\n }\n\n /**\n * Register workflows for a deployment.\n */\n async registerWorkflows(deploymentId: string, request: RegisterWorkflowsRequest): Promise<void> {\n await this.request<undefined>('POST', `/api/v1/workers/deployments/${deploymentId}/workflows`, {\n body: {\n workflows: request.workflows.map((w) => ({\n workflow_id: w.workflowId,\n queue_name: w.queueName,\n is_event_triggered: w.isEventTriggered,\n event_topic: w.eventTopic,\n batch_size: w.batchSize,\n is_scheduled: w.isScheduled,\n schedule: w.schedule,\n schedule_timezone: w.scheduleTimezone,\n })),\n },\n });\n }\n\n /**\n * Register queues.\n */\n async registerQueues(request: RegisterQueuesRequest): Promise<void> {\n await this.request<undefined>('POST', '/api/v1/workers/queues', {\n body: {\n deployment_id: request.deploymentId,\n queues: request.queues.map((q) => ({\n name: q.name,\n concurrency_limit: q.concurrencyLimit,\n })),\n },\n });\n }\n\n /**\n * Register a tool definition with the orchestrator.\n */\n async registerTool(request: RegisterToolRequest): Promise<void> {\n const body: Record<string, unknown> = {\n id: request.id,\n deployment_id: request.deploymentId,\n tool_type: request.toolType,\n description: request.description,\n parameters: request.parameters,\n };\n if (request.metadata !== undefined) {\n body['metadata'] = request.metadata;\n }\n\n await this.request<undefined>('POST', '/api/v1/tools/register', { body });\n }\n\n /**\n * Register an agent definition with the orchestrator.\n * Matches Python _register_agents() POST to /api/v1/agents/register.\n */\n async registerAgent(request: RegisterAgentRequest): Promise<void> {\n const body: Record<string, unknown> = {\n id: request.id,\n deployment_id: request.deploymentId,\n provider: request.provider,\n model: request.model,\n };\n if (request.systemPrompt !== undefined) body['system_prompt'] = request.systemPrompt;\n if (request.tools !== undefined) body['tools'] = request.tools;\n if (request.temperature !== undefined) body['temperature'] = request.temperature;\n if (request.maxOutputTokens !== undefined) body['max_output_tokens'] = request.maxOutputTokens;\n if (request.metadata !== undefined) body['metadata'] = request.metadata;\n\n await this.request<undefined>('POST', '/api/v1/agents/register', { body });\n }\n\n /**\n * Register a single workflow/agent/tool in deployment_workflows table.\n * Matches Python _register_deployment_workflow().\n */\n async registerDeploymentWorkflow(\n deploymentId: string,\n request: RegisterDeploymentWorkflowRequest\n ): Promise<void> {\n await this.request<undefined>('POST', `/api/v1/workers/deployments/${deploymentId}/workflows`, {\n body: {\n workflow_id: request.workflowId,\n workflow_type: request.workflowType,\n trigger_on_event: request.triggerOnEvent ?? false,\n scheduled: request.scheduled ?? false,\n },\n });\n }\n\n /**\n * Mark worker as online.\n */\n async markOnline(workerId: string): Promise<void> {\n await this.request<undefined>('POST', `/api/v1/workers/${workerId}/online`, {\n workerId,\n });\n }\n\n /**\n * Send heartbeat.\n */\n async sendHeartbeat(workerId: string): Promise<HeartbeatResponse> {\n return this.request<HeartbeatResponse>('POST', `/api/v1/workers/${workerId}/heartbeat`, {\n workerId,\n body: {},\n });\n }\n\n // ==================== Execution Reporting ====================\n\n /**\n * Complete an execution successfully.\n */\n async completeExecution(executionId: string, request: CompleteExecutionRequest): Promise<void> {\n await this.request<undefined>('POST', `/internal/executions/${executionId}/complete`, {\n workerId: request.workerId,\n body: {\n result: request.result,\n worker_id: request.workerId,\n output_schema_name: request.outputSchemaName,\n final_state: request.finalState,\n },\n });\n }\n\n /**\n * Fail an execution.\n */\n async failExecution(executionId: string, request: FailExecutionRequest): Promise<void> {\n await this.request<undefined>('POST', `/internal/executions/${executionId}/fail`, {\n workerId: request.workerId,\n body: {\n error: request.error,\n worker_id: request.workerId,\n stack: request.stack,\n retryable: request.retryable,\n final_state: request.finalState,\n },\n });\n }\n\n /**\n * Confirm cancellation of an execution.\n */\n async confirmCancellation(\n executionId: string,\n request: ConfirmCancellationRequest\n ): Promise<void> {\n await this.request<undefined>(\n 'POST',\n `/internal/executions/${executionId}/confirm-cancellation`,\n {\n workerId: request.workerId,\n body: {\n worker_id: request.workerId,\n },\n }\n );\n }\n\n // ==================== Step Persistence ====================\n\n /**\n * Store a step output.\n */\n async storeStepOutput(\n executionId: string,\n request: StoreStepOutputRequest,\n workerId?: string\n ): Promise<void> {\n const body: Record<string, unknown> = {\n step_key: request.stepKey,\n };\n if (request.outputs !== undefined) body['outputs'] = request.outputs;\n if (request.error !== undefined) body['error'] = request.error;\n if (request.success !== undefined) body['success'] = request.success;\n if (request.sourceExecutionId !== undefined)\n body['source_execution_id'] = request.sourceExecutionId;\n if (request.outputSchemaName !== undefined)\n body['output_schema_name'] = request.outputSchemaName;\n\n const options: { body: unknown; workerId?: string } = { body };\n if (workerId !== undefined) options.workerId = workerId;\n\n await this.request<undefined>('POST', `/internal/executions/${executionId}/steps`, options);\n }\n\n /**\n * Get a specific step output.\n */\n async getStepOutput(\n executionId: string,\n stepKey: string,\n workerId: string\n ): Promise<StepOutput | null> {\n try {\n const response = await this.request<{\n step_key: string;\n outputs: unknown;\n completed_at: string;\n success?: boolean;\n error?: unknown;\n output_schema_name?: string;\n source_execution_id?: string;\n }>('GET', `/internal/executions/${executionId}/steps/${encodeURIComponent(stepKey)}`, {\n workerId,\n });\n return {\n stepKey: response.step_key,\n outputs: response.outputs,\n completedAt: response.completed_at,\n success: response.success,\n error: response.error,\n outputSchemaName: response.output_schema_name,\n sourceExecutionId: response.source_execution_id,\n };\n } catch (error) {\n if (error instanceof OrchestratorApiError && error.statusCode === 404) {\n return null;\n }\n throw error;\n }\n }\n\n /**\n * Get all step outputs for an execution.\n */\n async getAllStepOutputs(executionId: string, workerId: string): Promise<StepOutput[]> {\n const response = await this.request<{\n steps: {\n step_key: string;\n outputs: unknown;\n completed_at: string;\n success?: boolean;\n error?: unknown;\n output_schema_name?: string;\n source_execution_id?: string;\n }[];\n }>('GET', `/internal/executions/${executionId}/steps`, { workerId });\n return response.steps.map((s) => ({\n stepKey: s.step_key,\n outputs: s.outputs,\n completedAt: s.completed_at,\n success: s.success,\n error: s.error,\n outputSchemaName: s.output_schema_name,\n sourceExecutionId: s.source_execution_id,\n }));\n }\n\n // ==================== Wait/Suspend ====================\n\n /**\n * Set execution to waiting state.\n */\n async setWaiting(\n executionId: string,\n request: SetWaitingRequest,\n workerId?: string\n ): Promise<void> {\n const options: { body: unknown; workerId?: string } = {\n body: {\n step_key: request.stepKey,\n wait_type: request.waitType,\n wait_until: request.waitUntil,\n wait_topic: request.waitTopic,\n expires_at: request.expiresAt,\n },\n };\n if (workerId !== undefined) options.workerId = workerId;\n\n await this.request<undefined>('POST', `/internal/executions/${executionId}/wait`, options);\n }\n\n // ==================== Events ====================\n\n /**\n * Publish events. Returns sequence IDs.\n */\n async publishEvent(request: PublishEventRequest): Promise<PublishEventResponse> {\n const body: Record<string, unknown> = {\n topic: request.topic,\n events: request.events.map((e) => {\n const entry: Record<string, unknown> = { data: e.data };\n if (e.eventType !== undefined) entry['event_type'] = e.eventType;\n return entry;\n }),\n };\n if (request.executionId !== undefined) body['execution_id'] = request.executionId;\n if (request.rootExecutionId !== undefined) body['root_execution_id'] = request.rootExecutionId;\n\n return this.request<PublishEventResponse>('POST', '/api/v1/events/publish', {\n body,\n });\n }\n\n /**\n * Stream events via SSE. Matching Python's _stream().\n */\n async *streamEvents(params: StreamEventsParams): AsyncGenerator<StreamEvent> {\n const queryParams = new URLSearchParams();\n queryParams.set('project_id', this.projectId);\n\n if (params.workflowRunId) {\n if (!params.workflowId) {\n throw new Error('workflowId must be provided when workflowRunId is provided');\n }\n queryParams.set('workflow_id', params.workflowId);\n queryParams.set('workflow_run_id', params.workflowRunId);\n } else if (params.topic) {\n queryParams.set('topic', params.topic);\n } else {\n throw new Error('Either topic or workflowRunId must be provided');\n }\n\n if (params.lastSequenceId !== undefined) {\n queryParams.set('last_sequence_id', String(params.lastSequenceId));\n } else if (params.lastTimestamp !== undefined) {\n queryParams.set('last_timestamp', params.lastTimestamp);\n } else {\n queryParams.set('last_timestamp', new Date().toISOString());\n }\n\n const url = `${this.apiUrl}/api/v1/events/stream?${queryParams.toString()}`;\n const headers = this.getHeaders();\n\n const response = await fetch(url, {\n method: 'GET',\n headers,\n });\n\n if (!response.ok) {\n throw new OrchestratorApiError(\n `Stream request failed: ${String(response.status)} ${response.statusText}`,\n response.status\n );\n }\n\n if (!response.body) {\n return;\n }\n\n const reader = response.body.getReader() as ReadableStreamDefaultReader<Uint8Array>;\n const decoder = new TextDecoder();\n let buffer = '';\n let currentEventData: string | null = null;\n\n try {\n for (;;) {\n const result = await reader.read();\n if (result.done) break;\n\n buffer += decoder.decode(result.value, { stream: true });\n const lines = buffer.split('\\n');\n // Keep the last partial line in the buffer\n buffer = lines.pop() ?? '';\n\n for (const rawLine of lines) {\n const line = rawLine.replace(/\\r$/, '');\n\n // Empty line indicates end of event\n if (!line) {\n if (currentEventData) {\n try {\n const eventDict = JSON.parse(currentEventData) as Record<string, unknown>;\n const data = eventDict['data'];\n const streamEvent: StreamEvent = {\n id: eventDict['id'] as string,\n sequenceId: eventDict['sequence_id'] as number,\n topic: eventDict['topic'] as string,\n eventType: eventDict['event_type'] as string | undefined,\n data: (typeof data === 'object' && data !== null ? data : {}) as Record<\n string,\n unknown\n >,\n createdAt: eventDict['created_at'] as string | undefined,\n };\n yield streamEvent;\n } catch {\n // Skip invalid events\n }\n currentEventData = null;\n }\n continue;\n }\n\n // SSE format: data: {...}\n if (line.startsWith('data: ')) {\n currentEventData = line.slice(6);\n }\n // Skip keepalive messages and comments\n }\n }\n } finally {\n await reader.cancel();\n reader.releaseLock();\n }\n }\n\n // ==================== Workflow Invocation ====================\n\n /**\n * Invoke a workflow.\n */\n async invokeWorkflow(\n workflowId: string,\n request: InvokeWorkflowRequest\n ): Promise<InvokeWorkflowResponse> {\n const body: Record<string, unknown> = {\n payload: request.payload,\n };\n if (request.stepKey !== undefined) body['step_key'] = request.stepKey;\n if (request.deploymentId !== undefined) body['deployment_id'] = request.deploymentId;\n if (request.parentExecutionId !== undefined)\n body['parent_execution_id'] = request.parentExecutionId;\n if (request.rootExecutionId !== undefined) body['root_execution_id'] = request.rootExecutionId;\n if (request.rootWorkflowId !== undefined) body['root_workflow_id'] = request.rootWorkflowId;\n if (request.queueName !== undefined) body['queue_name'] = request.queueName;\n if (request.queueConcurrencyLimit !== undefined)\n body['queue_concurrency_limit'] = request.queueConcurrencyLimit;\n if (request.concurrencyKey !== undefined) body['concurrency_key'] = request.concurrencyKey;\n if (request.waitForSubworkflow !== undefined)\n body['wait_for_subworkflow'] = request.waitForSubworkflow;\n if (request.batchId !== undefined) body['batch_id'] = request.batchId;\n if (request.sessionId !== undefined) body['session_id'] = request.sessionId;\n if (request.userId !== undefined) body['user_id'] = request.userId;\n if (request.otelTraceparent !== undefined) body['otel_traceparent'] = request.otelTraceparent;\n if (request.initialState !== undefined) body['initial_state'] = request.initialState;\n if (request.runTimeoutSeconds !== undefined)\n body['run_timeout_seconds'] = request.runTimeoutSeconds;\n if (request.channelContext !== undefined)\n body['channel_context'] = {\n channel_id: request.channelContext.channelId,\n source: request.channelContext.source,\n };\n\n return this.request<InvokeWorkflowResponse>('POST', `/api/v1/workflows/${workflowId}/run`, {\n body,\n });\n }\n\n /**\n * Invoke multiple workflows in a single batch.\n */\n async batchInvokeWorkflows(\n request: BatchInvokeWorkflowsRequest\n ): Promise<BatchInvokeWorkflowsResponse> {\n const body: Record<string, unknown> = {\n workflows: request.workflows.map((w) => {\n const entry: Record<string, unknown> = {\n workflow_id: w.workflowId,\n payload: w.payload,\n };\n if (w.queueName !== undefined) entry['queue_name'] = w.queueName;\n if (w.concurrencyKey !== undefined) entry['concurrency_key'] = w.concurrencyKey;\n if (w.queueConcurrencyLimit !== undefined)\n entry['queue_concurrency_limit'] = w.queueConcurrencyLimit;\n if (w.initialState !== undefined) entry['initial_state'] = w.initialState;\n if (w.runTimeoutSeconds !== undefined) entry['run_timeout_seconds'] = w.runTimeoutSeconds;\n return entry;\n }),\n };\n if (request.deploymentId !== undefined) body['deployment_id'] = request.deploymentId;\n if (request.sessionId !== undefined) body['session_id'] = request.sessionId;\n if (request.userId !== undefined) body['user_id'] = request.userId;\n if (request.stepKey !== undefined) body['step_key'] = request.stepKey;\n if (request.parentExecutionId !== undefined)\n body['parent_execution_id'] = request.parentExecutionId;\n if (request.rootExecutionId !== undefined) body['root_execution_id'] = request.rootExecutionId;\n if (request.rootWorkflowId !== undefined) body['root_workflow_id'] = request.rootWorkflowId;\n if (request.waitForSubworkflow !== undefined)\n body['wait_for_subworkflow'] = request.waitForSubworkflow;\n if (request.otelTraceparent !== undefined) body['otel_traceparent'] = request.otelTraceparent;\n\n return this.request<BatchInvokeWorkflowsResponse>('POST', '/api/v1/workflows/batch_run', {\n body,\n });\n }\n\n /**\n * Get execution status.\n */\n async getExecution(executionId: string): Promise<GetExecutionResponse> {\n return this.request<GetExecutionResponse>('GET', `/api/v1/executions/${executionId}`);\n }\n\n /**\n * Poll for execution result.\n */\n async waitForExecution(\n executionId: string,\n options?: { timeout?: number; pollInterval?: number }\n ): Promise<GetExecutionResponse> {\n const timeout = options?.timeout ?? 300000; // 5 minutes default\n const pollInterval = options?.pollInterval ?? 1000;\n const startTime = Date.now();\n\n while (Date.now() - startTime < timeout) {\n const execution = await this.getExecution(executionId);\n\n if (\n execution.status === 'completed' ||\n execution.status === 'failed' ||\n execution.status === 'cancelled'\n ) {\n return execution;\n }\n\n await new Promise((resolve) => setTimeout(resolve, pollInterval));\n }\n\n throw new Error(`Execution ${executionId} timed out after ${String(timeout)}ms`);\n }\n\n /**\n * Cancel an execution.\n */\n async cancelExecution(executionId: string): Promise<void> {\n await this.request<undefined>('POST', `/api/v1/executions/${executionId}/cancel`);\n }\n\n /**\n * Update execution's otel_span_id (used when workflow is paused via WaitException).\n */\n async updateExecutionOtelSpanId(\n executionId: string,\n otelSpanId: string | undefined\n ): Promise<void> {\n await this.request<undefined>('PUT', `/internal/executions/${executionId}/otel-span-id`, {\n body: { otel_span_id: otelSpanId ?? null },\n });\n }\n\n // ==================== Conversation History ====================\n\n /**\n * Add a message to conversation history.\n * POST /internal/conversation/{conversationId}/add\n */\n async addConversationHistory(\n conversationId: string,\n request: AddConversationHistoryRequest\n ): Promise<void> {\n const encoded = encodeURIComponent(conversationId);\n const body: Record<string, unknown> = {\n agent_id: request.agentId,\n role: request.role,\n content: request.content,\n conversation_history_limit: request.conversationHistoryLimit ?? 10,\n };\n if (request.agentRunId !== undefined) body['agent_run_id'] = request.agentRunId;\n\n await this.request<undefined>('POST', `/internal/conversation/${encoded}/add`, {\n body,\n });\n }\n\n /**\n * Get conversation history for a conversation.\n * GET /api/v1/conversation/{conversationId}/get\n */\n async getConversationHistory(\n conversationId: string,\n params: GetConversationHistoryParams\n ): Promise<ConversationMessage[]> {\n const encoded = encodeURIComponent(conversationId);\n const queryParams = new URLSearchParams();\n queryParams.set('agent_id', params.agentId);\n if (params.deploymentId !== undefined) queryParams.set('deployment_id', params.deploymentId);\n if (params.limit !== undefined) queryParams.set('limit', String(params.limit));\n\n const response = await this.request<{ messages?: ConversationMessage[] }>(\n 'GET',\n `/api/v1/conversation/${encoded}/get?${queryParams.toString()}`\n );\n return response.messages ?? [];\n }\n\n // ==================== Session Memory ====================\n\n /**\n * Get session memory (summary + metadata).\n * GET /internal/session/{sessionId}/memory\n */\n async getSessionMemory(sessionId: string): Promise<SessionMemoryResponse> {\n const encoded = encodeURIComponent(sessionId);\n return this.request<SessionMemoryResponse>('GET', `/internal/session/${encoded}/memory`);\n }\n\n /**\n * Store session memory (summary + messages).\n * PUT /internal/session/{sessionId}/memory\n */\n async putSessionMemory(sessionId: string, request: PutSessionMemoryRequest): Promise<void> {\n const encoded = encodeURIComponent(sessionId);\n await this.request<undefined>('PUT', `/internal/session/${encoded}/memory`, {\n body: {\n summary: request.summary,\n messages: request.messages,\n },\n });\n }\n\n // ==================== Schedules ====================\n\n /**\n * Create or update a schedule. Returns schedule_id.\n */\n async createSchedule(request: CreateScheduleRequest): Promise<CreateScheduleResponse> {\n return this.request<CreateScheduleResponse>('POST', '/api/v1/schedules', {\n body: {\n workflow_id: request.workflowId,\n cron: request.cron,\n timezone: request.timezone,\n key: request.key,\n },\n });\n }\n}\n","/**\n * ExecutionHandle - Represents a workflow execution that can be monitored and managed.\n *\n * Mirrors Python's ExecutionHandle class. Unlike Python (where get/cancel take a client arg),\n * the TS version stores the OrchestratorClient internally for a cleaner API.\n */\n\nimport type { OrchestratorClient } from './runtime/orchestrator-client.js';\nimport type { GetExecutionResponse } from './runtime/orchestrator-types.js';\n\n/**\n * Fields used to construct an ExecutionHandle.\n */\nexport interface ExecutionHandleFields {\n id: string;\n workflowId: string;\n createdAt?: string | undefined;\n parentExecutionId?: string | undefined;\n rootWorkflowId: string;\n rootExecutionId: string;\n sessionId?: string | undefined;\n userId?: string | undefined;\n stepKey?: string | undefined;\n}\n\n/**\n * Handle for a workflow execution that allows monitoring and management.\n */\nexport class ExecutionHandle {\n /** Execution ID */\n readonly id: string;\n /** Workflow ID */\n readonly workflowId: string;\n /** When the execution was created */\n readonly createdAt: string | undefined;\n /** Parent execution ID (if invoked from another workflow) */\n readonly parentExecutionId: string | undefined;\n /** Root workflow ID */\n readonly rootWorkflowId: string;\n /** Root execution ID */\n readonly rootExecutionId: string;\n /** Session ID */\n readonly sessionId: string | undefined;\n /** User ID */\n readonly userId: string | undefined;\n /** Step key (if invoked from a step) */\n readonly stepKey: string | undefined;\n\n private readonly orchestratorClient: OrchestratorClient;\n\n constructor(fields: ExecutionHandleFields, orchestratorClient: OrchestratorClient) {\n this.id = fields.id;\n this.workflowId = fields.workflowId;\n this.createdAt = fields.createdAt;\n this.parentExecutionId = fields.parentExecutionId;\n this.rootWorkflowId = fields.rootWorkflowId;\n this.rootExecutionId = fields.rootExecutionId;\n this.sessionId = fields.sessionId;\n this.userId = fields.userId;\n this.stepKey = fields.stepKey;\n this.orchestratorClient = orchestratorClient;\n }\n\n /**\n * Get the current execution status and details.\n */\n async get(): Promise<GetExecutionResponse> {\n return this.orchestratorClient.getExecution(this.id);\n }\n\n /**\n * Cancel the execution if it's still queued or running.\n *\n * @returns true if cancellation was successful, false on error\n */\n async cancel(): Promise<boolean> {\n try {\n await this.orchestratorClient.cancelExecution(this.id);\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Poll until the execution completes and return the result.\n * Matches Python ExecutionHandle.get_result().\n *\n * @param timeout - Maximum time to wait in seconds (default: 600)\n * @returns The execution result\n * @throws Error if execution fails, is cancelled, or times out\n */\n async getResult(timeout = 600): Promise<unknown> {\n const startTime = Date.now();\n const pollInterval = 500;\n let done = false;\n while (!done) {\n const exec = await this.get();\n if (exec.status === 'completed') return exec.result;\n if (exec.status === 'failed') throw new Error(exec.error ?? 'Execution failed');\n if (exec.status === 'cancelled') throw new Error('Execution cancelled');\n if (Date.now() - startTime > timeout * 1000) {\n done = true;\n } else {\n await new Promise((r) => setTimeout(r, pollInterval));\n }\n }\n throw new Error(`Timed out after ${String(timeout)}s`);\n }\n\n /**\n * Convert the handle to a plain object (excluding undefined fields).\n */\n toDict(): Record<string, unknown> {\n const result: Record<string, unknown> = {\n id: this.id,\n workflowId: this.workflowId,\n rootWorkflowId: this.rootWorkflowId,\n rootExecutionId: this.rootExecutionId,\n };\n if (this.createdAt !== undefined) result['createdAt'] = this.createdAt;\n if (this.parentExecutionId !== undefined) result['parentExecutionId'] = this.parentExecutionId;\n if (this.sessionId !== undefined) result['sessionId'] = this.sessionId;\n if (this.userId !== undefined) result['userId'] = this.userId;\n if (this.stepKey !== undefined) result['stepKey'] = this.stepKey;\n return result;\n }\n}\n","/**\n * PolosClient - Central entry point for interacting with the Polos orchestrator.\n *\n * The client stores configuration and provides methods for invoking workflows,\n * publishing events, and managing schedules.\n */\n\nimport type { Workflow, EventData, StreamEvent } from './types/index.js';\nimport { validateCronGranularity } from './core/workflow.js';\nimport { OrchestratorClient } from './runtime/orchestrator-client.js';\nimport type { GetExecutionResponse } from './runtime/orchestrator-types.js';\nimport { ExecutionHandle } from './execution-handle.js';\nimport { assertNotInExecutionContext } from './runtime/execution-context.js';\n\n/**\n * Configuration options for PolosClient.\n */\nexport interface PolosClientConfig {\n /** Orchestrator API URL */\n apiUrl: string;\n /** API key for authentication */\n apiKey: string;\n /** Project ID */\n projectId: string;\n /** Deployment ID for routing workflows to specific workers */\n deploymentId?: string;\n /** Maximum concurrent workflow executions (default: 100) */\n maxConcurrentWorkflows?: number;\n}\n\n/**\n * Options for invoking a workflow via PolosClient.\n */\nexport interface ClientInvokeOptions {\n /** Queue name override */\n queueName?: string | undefined;\n /** Concurrency limit for queue */\n queueConcurrencyLimit?: number | undefined;\n /** Concurrency key for per-tenant queuing */\n concurrencyKey?: string | undefined;\n /** Session ID */\n sessionId?: string | undefined;\n /** User ID */\n userId?: string | undefined;\n /** Initial state dictionary */\n initialState?: Record<string, unknown> | undefined;\n /** Timeout in seconds for the execution */\n runTimeoutSeconds?: number | undefined;\n /** Parent execution ID (when invoked from another workflow) */\n parentExecutionId?: string | undefined;\n /** Root workflow ID */\n rootWorkflowId?: string | undefined;\n /** Root execution ID */\n rootExecutionId?: string | undefined;\n /** Step key (when invoked from a step) */\n stepKey?: string | undefined;\n /** Channel context for bidirectional channels (e.g., originating Slack thread) */\n channelContext?: { channelId: string; source: Record<string, unknown> } | undefined;\n}\n\n/**\n * Input for batch workflow invocation via PolosClient.\n */\nexport interface ClientBatchWorkflowInput {\n /** Workflow to invoke (string ID or Workflow object) */\n workflow: string | Workflow;\n /** Payload for this invocation */\n payload?: unknown;\n /** Queue name override */\n queueName?: string | undefined;\n /** Concurrency key */\n concurrencyKey?: string | undefined;\n /** Concurrency limit for queue */\n queueConcurrencyLimit?: number | undefined;\n /** Initial state dictionary */\n initialState?: Record<string, unknown> | undefined;\n /** Timeout in seconds for the execution */\n runTimeoutSeconds?: number | undefined;\n}\n\n/**\n * Payload passed to scheduled workflows.\n * Matches Python SchedulePayload.\n */\nexport interface SchedulePayload {\n /** When this workflow was scheduled to run */\n timestamp: string;\n /** When this schedule last ran (null if first run) */\n lastTimestamp: string | null;\n /** Timezone of the schedule */\n timezone: string;\n /** Unique identifier for this schedule */\n scheduleId: string;\n /** User ID or custom identifier for the schedule */\n key: string;\n /** Next scheduled run time */\n upcoming: string;\n}\n\n/**\n * Events API accessed via client.events.\n * Matches Python sdk/python/polos/features/events.py function signatures.\n */\nexport interface EventsApi {\n /**\n * Publish a single event to a topic. Returns the sequence ID.\n * Matches Python publish().\n */\n publish(\n topic: string,\n eventData: EventData,\n executionId?: string,\n rootExecutionId?: string\n ): Promise<number>;\n\n /**\n * Publish a batch of events to a single topic. Returns list of sequence IDs.\n * Matches Python batch_publish().\n */\n batchPublish(\n topic: string,\n events: EventData[],\n executionId?: string,\n rootExecutionId?: string\n ): Promise<number[]>;\n\n /**\n * Stream events from a topic using Server-Sent Events (SSE).\n * Matches Python stream_topic().\n */\n streamTopic(\n topic: string,\n lastSequenceId?: number,\n lastTimestamp?: Date\n ): AsyncIterable<StreamEvent>;\n\n /**\n * Stream events from a workflow run using Server-Sent Events (SSE).\n * Automatically stops when it receives a finish event with matching execution ID.\n * Matches Python stream_workflow().\n */\n streamWorkflow(\n workflowId: string,\n workflowRunId: string,\n lastSequenceId?: number,\n lastTimestamp?: Date\n ): AsyncIterable<StreamEvent>;\n}\n\n/**\n * Schedules API accessed via client.schedules.\n * Matches Python sdk/python/polos/features/schedules.py.\n */\nexport interface SchedulesApi {\n /**\n * Create or update a schedule for a workflow.\n * If a schedule with the same workflow and key already exists, it will be updated.\n * Matches Python schedules.create().\n *\n * @param workflow - Workflow ID to schedule\n * @param cron - Cron expression (e.g., \"0 8 * * *\" for 8 AM daily)\n * @param timezone - Timezone for the schedule (default: \"UTC\")\n * @param key - Key for per-user/per-entity schedules (default: \"global\")\n * @returns schedule_id: Unique identifier for the schedule\n */\n create(workflow: string, cron: string, timezone?: string, key?: string): Promise<string>;\n}\n\n/**\n * PolosClient - The main client for interacting with Polos orchestrator.\n *\n * @example\n * ```typescript\n * import { PolosClient, defineWorkflow } from '@polos/sdk';\n *\n * const client = new PolosClient({\n * apiUrl: 'https://api.polos.dev',\n * apiKey: 'your-api-key',\n * projectId: 'your-project',\n * deploymentId: 'my-deployment', // optional, can also use POLOS_DEPLOYMENT_ID env var\n * });\n *\n * // Invoke a workflow\n * const handle = await client.invoke(myWorkflow, { data: 'value' });\n *\n * // Run and wait for result\n * const result = await client.run(myWorkflow, { data: 'value' });\n * ```\n */\n/** Internal config type with defaults applied but deploymentId remaining optional */\ntype ResolvedPolosClientConfig = Required<Omit<PolosClientConfig, 'deploymentId'>> & {\n deploymentId: string | undefined;\n};\n\n/** Resolve a workflow-or-string to its ID */\nfunction resolveWorkflowId(workflow: string | Workflow): string {\n return typeof workflow === 'string' ? workflow : workflow.id;\n}\n\nexport class PolosClient {\n private readonly config: ResolvedPolosClientConfig;\n private readonly orchestratorClient: OrchestratorClient;\n\n /**\n * Events API for publishing and subscribing to events.\n */\n public readonly events: EventsApi;\n\n /**\n * Schedules API for managing workflow schedules.\n */\n public readonly schedules: SchedulesApi;\n\n constructor(config: PolosClientConfig) {\n this.config = {\n maxConcurrentWorkflows: 100,\n ...config,\n // Use provided deploymentId or fall back to environment variable\n deploymentId: config.deploymentId ?? process.env['POLOS_DEPLOYMENT_ID'],\n };\n\n this.orchestratorClient = new OrchestratorClient({\n apiUrl: this.config.apiUrl,\n apiKey: this.config.apiKey,\n projectId: this.config.projectId,\n });\n\n // Initialize sub-APIs\n this.events = this.createEventsApi();\n this.schedules = this.createSchedulesApi();\n }\n\n /**\n * Create a PolosClient from environment variables.\n *\n * Reads from:\n * - POLOS_API_URL\n * - POLOS_API_KEY\n * - POLOS_PROJECT_ID\n * - POLOS_DEPLOYMENT_ID (optional)\n * - POLOS_MAX_CONCURRENT_WORKFLOWS (optional)\n *\n * @throws Error if required environment variables are missing\n */\n static fromEnv(): PolosClient {\n const apiUrl = process.env['POLOS_API_URL'];\n const apiKey = process.env['POLOS_API_KEY'];\n const projectId = process.env['POLOS_PROJECT_ID'];\n const deploymentId = process.env['POLOS_DEPLOYMENT_ID'];\n\n if (!apiUrl) {\n throw new Error('POLOS_API_URL environment variable is required');\n }\n if (!apiKey) {\n throw new Error('POLOS_API_KEY environment variable is required');\n }\n if (!projectId) {\n throw new Error('POLOS_PROJECT_ID environment variable is required');\n }\n\n const config: PolosClientConfig = {\n apiUrl,\n apiKey,\n projectId,\n ...(deploymentId && { deploymentId }),\n };\n\n const maxConcurrent = process.env['POLOS_MAX_CONCURRENT_WORKFLOWS'];\n if (maxConcurrent) {\n const parsed = parseInt(maxConcurrent, 10);\n if (!isNaN(parsed)) {\n config.maxConcurrentWorkflows = parsed;\n }\n }\n\n return new PolosClient(config);\n }\n\n /**\n * Get the client configuration.\n */\n getConfig(): Readonly<ResolvedPolosClientConfig> {\n return this.config;\n }\n\n /**\n * Get the underlying OrchestratorClient for advanced use.\n */\n getOrchestratorClient(): OrchestratorClient {\n return this.orchestratorClient;\n }\n\n /**\n * Invoke a workflow (fire and forget).\n *\n * @param workflow - The workflow to invoke (string ID or Workflow object)\n * @param payload - Payload to pass to the workflow\n * @param options - Optional invocation options\n * @returns An ExecutionHandle to track the workflow execution\n */\n async invoke(\n workflow: string | Workflow,\n payload?: unknown,\n options?: ClientInvokeOptions\n ): Promise<ExecutionHandle> {\n assertNotInExecutionContext('client.invoke()', 'step.invoke()');\n const workflowId = resolveWorkflowId(workflow);\n\n const response = await this.orchestratorClient.invokeWorkflow(workflowId, {\n workflowId,\n payload,\n deploymentId: this.config.deploymentId,\n queueName: options?.queueName,\n queueConcurrencyLimit: options?.queueConcurrencyLimit,\n concurrencyKey: options?.concurrencyKey,\n sessionId: options?.sessionId,\n userId: options?.userId,\n initialState: options?.initialState,\n runTimeoutSeconds: options?.runTimeoutSeconds,\n parentExecutionId: options?.parentExecutionId,\n rootExecutionId: options?.rootExecutionId,\n stepKey: options?.stepKey,\n channelContext: options?.channelContext,\n });\n\n return new ExecutionHandle(\n {\n id: response.execution_id,\n workflowId,\n createdAt: response.created_at,\n parentExecutionId: options?.parentExecutionId,\n rootWorkflowId: options?.rootWorkflowId ?? workflowId,\n rootExecutionId: options?.rootExecutionId ?? response.execution_id,\n sessionId: options?.sessionId,\n userId: options?.userId,\n stepKey: options?.stepKey,\n },\n this.orchestratorClient\n );\n }\n\n /**\n * Invoke multiple workflows in batch (fire and forget).\n *\n * @param items - Array of workflow invocations\n * @param options - Optional batch-level options\n * @returns Array of ExecutionHandles to track executions\n */\n async batchInvoke(\n items: ClientBatchWorkflowInput[],\n options?: {\n sessionId?: string;\n userId?: string;\n parentExecutionId?: string;\n rootWorkflowId?: string;\n rootExecutionId?: string;\n stepKey?: string;\n waitForSubworkflow?: boolean;\n }\n ): Promise<ExecutionHandle[]> {\n assertNotInExecutionContext('client.batchInvoke()', 'step.batchInvoke()');\n if (items.length === 0) {\n return [];\n }\n\n const response = await this.orchestratorClient.batchInvokeWorkflows({\n workflows: items.map((item) => ({\n workflowId: resolveWorkflowId(item.workflow),\n payload: item.payload,\n queueName: item.queueName,\n concurrencyKey: item.concurrencyKey,\n queueConcurrencyLimit: item.queueConcurrencyLimit,\n initialState: item.initialState,\n runTimeoutSeconds: item.runTimeoutSeconds,\n })),\n deploymentId: this.config.deploymentId,\n sessionId: options?.sessionId,\n userId: options?.userId,\n parentExecutionId: options?.parentExecutionId,\n rootExecutionId: options?.rootExecutionId,\n stepKey: options?.stepKey,\n waitForSubworkflow: options?.waitForSubworkflow,\n });\n\n return response.executions.map((exec, i) => {\n const item = items[i];\n if (item === undefined) {\n throw new Error('item is undefined');\n }\n const wfId = resolveWorkflowId(item.workflow);\n return new ExecutionHandle(\n {\n id: exec.execution_id,\n workflowId: wfId,\n createdAt: exec.created_at,\n parentExecutionId: options?.parentExecutionId,\n rootWorkflowId: options?.rootWorkflowId ?? wfId,\n rootExecutionId: options?.rootExecutionId ?? exec.execution_id,\n sessionId: options?.sessionId,\n userId: options?.userId,\n stepKey: options?.stepKey,\n },\n this.orchestratorClient\n );\n });\n }\n\n /**\n * Resume a suspended execution by publishing a resume event.\n *\n * @param suspendWorkflowId - The workflow ID of the suspended execution\n * @param suspendExecutionId - The execution ID of the suspended execution\n * @param suspendStepKey - The step key that was used in suspend()\n * @param data - Data to pass in the resume event\n */\n async resume(\n suspendWorkflowId: string,\n suspendExecutionId: string,\n suspendStepKey: string,\n data: unknown\n ): Promise<void> {\n const topic = `workflow/${suspendWorkflowId}/${suspendExecutionId}`;\n\n await this.orchestratorClient.publishEvent({\n topic,\n events: [{ eventType: `resume_${suspendStepKey}`, data }],\n });\n }\n\n /**\n * Get execution details.\n *\n * @param executionId - The execution ID to look up\n * @returns Execution details\n */\n async getExecution(executionId: string): Promise<GetExecutionResponse> {\n return this.orchestratorClient.getExecution(executionId);\n }\n\n /**\n * Cancel an execution by its ID.\n *\n * @param executionId - The execution ID to cancel\n * @returns true if cancellation was successful, false on error\n */\n async cancelExecution(executionId: string): Promise<boolean> {\n try {\n await this.orchestratorClient.cancelExecution(executionId);\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Create the events sub-API.\n * Matches Python sdk/python/polos/features/events.py.\n */\n private createEventsApi(): EventsApi {\n const orchestratorClient = this.orchestratorClient;\n\n return {\n publish: async (\n topic: string,\n eventData: EventData,\n executionId?: string,\n rootExecutionId?: string\n ): Promise<number> => {\n const sequenceIds = await this.events.batchPublish(\n topic,\n [eventData],\n executionId,\n rootExecutionId\n );\n return sequenceIds[0] ?? 0;\n },\n\n batchPublish: async (\n topic: string,\n events: EventData[],\n executionId?: string,\n rootExecutionId?: string\n ): Promise<number[]> => {\n if (events.length === 0) {\n return [];\n }\n\n const response = await orchestratorClient.publishEvent({\n topic,\n events: events.map((e) => {\n const entry: { eventType?: string; data: unknown } = { data: e.data };\n if (e.eventType !== undefined) entry.eventType = e.eventType;\n return entry;\n }),\n executionId,\n rootExecutionId,\n });\n\n return response.sequence_ids;\n },\n\n streamTopic: (\n topic: string,\n lastSequenceId?: number,\n lastTimestamp?: Date\n ): AsyncIterable<StreamEvent> => {\n return orchestratorClient.streamEvents({\n topic,\n lastSequenceId,\n lastTimestamp: lastTimestamp?.toISOString(),\n });\n },\n\n streamWorkflow: (\n workflowId: string,\n workflowRunId: string,\n lastSequenceId?: number,\n lastTimestamp?: Date\n ): AsyncIterable<StreamEvent> => {\n // Wrap with finish-event detection matching Python's stream_workflow()\n async function* streamWithFinishCheck() {\n for await (const event of orchestratorClient.streamEvents({\n workflowId,\n workflowRunId,\n lastSequenceId,\n lastTimestamp: lastTimestamp?.toISOString(),\n })) {\n yield event;\n\n // Check for finish event with matching execution_id\n if (\n event.eventType === 'workflow_finish' ||\n event.eventType === 'agent_finish' ||\n event.eventType === 'tool_finish'\n ) {\n const metadata = event.data['_metadata'];\n if (metadata && typeof metadata === 'object' && !Array.isArray(metadata)) {\n const metadataRecord = metadata as Record<string, unknown>;\n if (metadataRecord['execution_id'] === workflowRunId) {\n return;\n }\n }\n }\n }\n }\n\n return streamWithFinishCheck();\n },\n };\n }\n\n /**\n * Create the schedules sub-API.\n * Matches Python sdk/python/polos/features/schedules.py.\n */\n private createSchedulesApi(): SchedulesApi {\n const orchestratorClient = this.orchestratorClient;\n\n return {\n create: async (\n workflow: string,\n cron: string,\n timezone = 'UTC',\n key = 'global'\n ): Promise<string> => {\n validateCronGranularity(cron);\n const response = await orchestratorClient.createSchedule({\n workflowId: workflow,\n cron,\n timezone,\n key,\n });\n return response.schedule_id;\n },\n };\n }\n}\n","/**\n * Tool definition and creation.\n *\n * Provides the defineTool function for creating typed tools that can be\n * exposed to LLMs. Tools are workflows with workflowType: 'tool' plus\n * LLM-specific metadata (description, JSON schema parameters).\n */\n\nimport { type ZodType, toJSONSchema } from 'zod';\nimport type { Channel } from '../channels/channel.js';\nimport type { WorkflowContext } from './context.js';\nimport type { QueueConfig, WorkflowHandler, Workflow } from './workflow.js';\nimport { defineWorkflow } from './workflow.js';\nimport type { HookHandler, Hook as HookObject } from '../middleware/hook.js';\n\n// ── Tool approval ────────────────────────────────────────────────────\n\nexport type ToolApproval = 'always' | 'none';\n\n// ── LLM tool definition ──────────────────────────────────────────────\n\n/**\n * LLM tool definition format (OpenAI/Anthropic compatible).\n */\nexport interface LlmToolDefinition {\n type: 'function';\n function: {\n name: string;\n description: string;\n parameters: Record<string, unknown>;\n };\n}\n\n// ── DefineToolConfig ─────────────────────────────────────────────────\n\n/**\n * Configuration for defineTool().\n */\nexport interface DefineToolConfig<TInput = unknown, TOutput = unknown, TState = unknown> {\n /** Unique tool identifier */\n id: string;\n /** Tool description shown to LLMs */\n description: string;\n /** Zod schema for input validation (optional — some tools take no input) */\n inputSchema?: ZodType<TInput> | undefined;\n /** Zod schema for output validation */\n outputSchema?: ZodType<TOutput> | undefined;\n /** Zod schema for state validation and defaults */\n stateSchema?: ZodType<TState> | undefined;\n /** Queue assignment */\n queue?: string | QueueConfig | undefined;\n /** Hook(s) to run before tool execution */\n onStart?:\n | HookHandler<TInput, TState>\n | HookObject<TInput, TState>\n | (HookHandler<TInput, TState> | HookObject<TInput, TState>)[]\n | undefined;\n /** Hook(s) to run after tool completion */\n onEnd?:\n | HookHandler<TInput, TState>\n | HookObject<TInput, TState>\n | (HookHandler<TInput, TState> | HookObject<TInput, TState>)[]\n | undefined;\n /** Whether to auto-register in the global workflow registry (default: true) */\n autoRegister?: boolean | undefined;\n /** Require human approval before tool execution. @default undefined (no approval) */\n approval?: ToolApproval | undefined;\n /** Notification channels for suspend events. Overrides Worker-level channels. */\n channels?: Channel[] | undefined;\n}\n\n// ── ToolWorkflow ─────────────────────────────────────────────────────\n\n/**\n * A Workflow with tool-specific LLM metadata.\n *\n * Extends the base Workflow interface with fields needed for LLM tool\n * integration: description, JSON schema parameters, and methods for\n * generating LLM-compatible tool definitions.\n */\nexport interface ToolWorkflow<\n TInput = unknown,\n TOutput = unknown,\n TState = unknown,\n> extends Workflow<TInput, TState, TOutput> {\n /** Tool description shown to LLMs */\n readonly toolDescription: string;\n /** JSON schema for tool parameters */\n readonly toolParameters: Record<string, unknown>;\n /** Generate an LLM-compatible tool definition */\n toLlmToolDefinition(): LlmToolDefinition;\n /** Get the tool type (default: \"default\") */\n getToolType(): string;\n /** Get additional tool metadata (default: undefined) */\n getToolMetadata(): Record<string, unknown> | undefined;\n}\n\n// ── isToolWorkflow ───────────────────────────────────────────────────\n\n/**\n * Type guard: checks whether a Workflow is a ToolWorkflow.\n */\nexport function isToolWorkflow(workflow: Workflow): workflow is ToolWorkflow {\n return workflow.config.workflowType === 'tool';\n}\n\n// ── Tool approval resume data ────────────────────────────────────────\n\ninterface ToolApprovalResumeData {\n data?: { approved?: boolean; feedback?: string };\n}\n\n// ── defineTool ───────────────────────────────────────────────────────\n\n/**\n * Define a tool — a workflow with `workflowType: 'tool'` plus LLM metadata.\n *\n * @example\n * ```typescript\n * import { defineTool } from '@polos/sdk';\n * import { z } from 'zod';\n *\n * const searchKb = defineTool({\n * id: 'search-kb',\n * description: 'Search the knowledge base',\n * inputSchema: z.object({\n * query: z.string().describe('Search query'),\n * limit: z.number().optional().describe('Max results'),\n * }),\n * }, async (ctx, input) => {\n * const results = await ctx.step.run('search', () => db.search(input.query));\n * return { results };\n * });\n *\n * // Get LLM tool definition\n * const toolDef = searchKb.toLlmToolDefinition();\n *\n * // Execute via client\n * const result = await client.run(searchKb, { query: 'test' });\n * ```\n */\nexport function defineTool<TInput = unknown, TOutput = unknown, TState = unknown>(\n config: DefineToolConfig<TInput, TOutput, TState>,\n handler: (ctx: WorkflowContext<TState>, input: TInput) => Promise<TOutput>\n): ToolWorkflow<TInput, TOutput, TState> {\n // Derive JSON schema parameters from inputSchema\n const toolParameters: Record<string, unknown> = config.inputSchema\n ? (() => {\n const { $schema: _, ...rest } = toJSONSchema(config.inputSchema) as Record<string, unknown>;\n return rest;\n })()\n : { type: 'object', properties: {} };\n\n // Wrap handler with approval gate when configured\n const effectiveHandler: typeof handler =\n config.approval === 'always'\n ? async (ctx, input) => {\n const approvalId = await ctx.step.uuid('_approval_id');\n const response = await ctx.step.suspend<Record<string, unknown>, ToolApprovalResumeData>(\n `approve_${config.id}_${approvalId}`,\n {\n data: {\n _form: {\n title: `Approve tool: ${config.id}`,\n description: `The agent wants to use the \"${config.id}\" tool.`,\n fields: [\n {\n key: 'approved',\n type: 'boolean',\n label: 'Approve this tool call?',\n required: true,\n default: false,\n },\n {\n key: 'feedback',\n type: 'textarea',\n label: 'Feedback for the agent (optional)',\n description: 'If rejecting, tell the agent what to do instead.',\n required: false,\n },\n ],\n context: { tool: config.id, input },\n },\n _source: 'tool_approval',\n _tool: config.id,\n },\n }\n );\n\n if (response.data?.approved !== true) {\n const feedback = response.data?.feedback;\n throw new Error(\n `Tool \"${config.id}\" was rejected by the user.${feedback ? ` Feedback: ${feedback}` : ''}`\n );\n }\n\n return handler(ctx, input);\n }\n : handler;\n\n // Create the underlying workflow\n const workflow = defineWorkflow<TInput, TState, TOutput>(\n {\n id: config.id,\n description: config.description,\n workflowType: 'tool',\n payloadSchema: config.inputSchema,\n stateSchema: config.stateSchema,\n outputSchema: config.outputSchema,\n queue: config.queue,\n onStart: config.onStart,\n onEnd: config.onEnd,\n channels: config.channels,\n },\n effectiveHandler as WorkflowHandler<TInput, TState, TOutput>,\n config.autoRegister === undefined ? undefined : { autoRegister: config.autoRegister }\n );\n\n // Extend with tool-specific fields\n const toolWorkflow: ToolWorkflow<TInput, TOutput, TState> = Object.assign(workflow, {\n toolDescription: config.description,\n toolParameters,\n toLlmToolDefinition(): LlmToolDefinition {\n return {\n type: 'function' as const,\n function: {\n name: config.id,\n description: config.description,\n parameters: toolParameters,\n },\n };\n },\n getToolType(): string {\n return 'default';\n },\n getToolMetadata(): Record<string, unknown> | undefined {\n return undefined;\n },\n });\n\n return toolWorkflow;\n}\n","/**\n * LLM types and conversion utilities.\n *\n * All wire-format types use snake_case to match Python for cross-language compatibility.\n */\n\nimport type { ModelMessage as CoreMessage, LanguageModel } from 'ai';\nimport { jsonSchema } from 'ai';\nimport type { LlmToolDefinition } from '../core/tool.js';\nimport type { ToolCall } from '../types/llm.js';\nimport type { Guardrail } from '../middleware/guardrail.js';\n\n/**\n * Extract modelId from a LanguageModel (which may be a string or model object).\n */\nexport function getModelId(model: LanguageModel): string {\n return typeof model === 'string' ? model : model.modelId;\n}\n\n/**\n * Extract provider from a LanguageModel (which may be a string or model object).\n */\nexport function getModelProvider(model: LanguageModel): string {\n if (typeof model === 'string') {\n // For string model IDs like \"anthropic/claude-3\", extract provider prefix\n const slashIdx = model.indexOf('/');\n return slashIdx >= 0 ? model.slice(0, slashIdx) : 'unknown';\n }\n return model.provider;\n}\n\n// ── Wire-format types ────────────────────────\n\n/**\n * Token usage statistics\n */\nexport interface LLMUsage {\n input_tokens: number;\n output_tokens: number;\n total_tokens: number;\n cache_read_input_tokens?: number | undefined;\n cache_creation_input_tokens?: number | undefined;\n}\n\n/**\n * A tool call made by the LLM\n */\nexport interface LLMToolCall {\n id: string;\n type: 'function';\n call_id: string;\n function: { name: string; arguments: string };\n}\n\n/**\n * Result from a tool execution\n */\nexport interface LLMToolResult {\n type: 'function_call_output';\n call_id: string;\n name: string;\n output: unknown;\n}\n\n/**\n * Response from a non-streaming LLM generation\n */\nexport interface LLMResponse {\n content: string | null;\n usage: LLMUsage | null;\n tool_calls: LLMToolCall[] | null;\n raw_output: unknown[] | null;\n model: string | null;\n stop_reason: string | null;\n}\n\n/**\n * Stream event types (matching Python exactly).\n */\nexport type LLMStreamEvent =\n | { type: 'text_delta'; data: { content: string } }\n | { type: 'tool_call'; data: { tool_call: LLMToolCall } }\n | {\n type: 'done';\n data: { usage: LLMUsage; raw_output: unknown[]; model: string; stop_reason: string | null };\n }\n | { type: 'error'; data: { error: string } };\n\n/**\n * Options for LLM.generate() and LLM.stream().\n */\nexport interface LLMGenerateOptions {\n /** Conversation messages */\n messages: CoreMessage[];\n /** System prompt */\n system?: string | undefined;\n /** Tools available to the LLM */\n tools?: LlmToolDefinition[] | undefined;\n /** Tool results from previous tool calls */\n tool_results?: LLMToolResult[] | undefined;\n /** Temperature for randomness */\n temperature?: number | undefined;\n /** Maximum tokens to generate */\n maxTokens?: number | undefined;\n /** Top-p sampling parameter */\n topP?: number | undefined;\n /** Zod schema for structured output (passed to Vercel AI SDK Output.object()) */\n outputSchema?: unknown;\n}\n\n/**\n * Payload for llmGenerate() — adds guardrail and agent step fields.\n */\nexport interface LLMGeneratePayload extends LLMGenerateOptions {\n /** Agent step number for step key naming */\n agent_step: number;\n /** Guardrails to apply after generation */\n guardrails?: Guardrail[] | undefined;\n /** Maximum guardrail retries (default: 2) */\n guardrail_max_retries?: number | undefined;\n}\n\n/**\n * Result from llmGenerate() — extends LLMResponse with execution metadata.\n */\nexport interface LLMGenerateResult extends LLMResponse {\n /** Agent run ID (from workflow context) */\n agent_run_id?: string | undefined;\n /** Execution status */\n status?: string | undefined;\n}\n\n/**\n * Payload for llmStream().\n */\nexport interface LLMStreamPayload extends LLMGenerateOptions {\n /** Agent step number for step key naming */\n agent_step: number;\n}\n\n// ── Conversion functions ───────────────────────────────────────────────\n\n/**\n * Convert LlmToolDefinition[] (OpenAI format) to Vercel AI SDK tool format.\n */\nexport function convertToolsToVercel(\n tools: LlmToolDefinition[] | undefined\n): Record<string, { description: string; inputSchema: ReturnType<typeof jsonSchema> }> | undefined {\n if (!tools || tools.length === 0) return undefined;\n\n const result: Record<\n string,\n { description: string; inputSchema: ReturnType<typeof jsonSchema> }\n > = {};\n for (const tool of tools) {\n result[tool.function.name] = {\n description: tool.function.description,\n inputSchema: jsonSchema(tool.function.parameters),\n };\n }\n return result;\n}\n\n/**\n * Convert Python tool results to Vercel CoreMessage[] with role 'tool'.\n */\nexport function convertToolResultsToMessages(\n toolResults: LLMToolResult[] | undefined\n): CoreMessage[] {\n if (!toolResults || toolResults.length === 0) return [];\n\n return toolResults.map(\n (tr): CoreMessage => ({\n role: 'tool' as const,\n content: [\n {\n type: 'tool-result' as const,\n toolCallId: tr.call_id,\n toolName: tr.name,\n output:\n typeof tr.output === 'string'\n ? { type: 'text' as const, value: tr.output }\n : // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment -- coerce unknown tool output to JSON ToolResultOutput\n { type: 'json' as const, value: tr.output as any },\n },\n ],\n })\n );\n}\n\n/**\n * Convert a Vercel AI SDK tool call to Python LLMToolCall format.\n */\nexport function convertVercelToolCallToPython(tc: {\n toolCallId: string;\n toolName: string;\n input: unknown;\n}): LLMToolCall {\n return {\n id: tc.toolCallId,\n type: 'function',\n call_id: tc.toolCallId,\n function: {\n name: tc.toolName,\n arguments: typeof tc.input === 'string' ? tc.input : JSON.stringify(tc.input),\n },\n };\n}\n\n/**\n * Convert Python LLMToolCall to middleware ToolCall format (for guardrails).\n */\nexport function convertPythonToolCallToMiddleware(tc: LLMToolCall): ToolCall {\n let args: unknown;\n try {\n args = JSON.parse(tc.function.arguments);\n } catch {\n args = tc.function.arguments;\n }\n return {\n id: tc.call_id,\n name: tc.function.name,\n args,\n };\n}\n\n/**\n * Convert middleware ToolCall back to Python LLMToolCall format.\n */\nexport function convertMiddlewareToolCallToPython(tc: ToolCall): LLMToolCall {\n return {\n id: tc.id,\n type: 'function',\n call_id: tc.id,\n function: {\n name: tc.name,\n arguments: typeof tc.args === 'string' ? tc.args : JSON.stringify(tc.args),\n },\n };\n}\n\n/**\n * Convert Vercel AI SDK usage to Python LLMUsage format.\n */\nexport function convertVercelUsageToPython(usage: {\n inputTokens: number | undefined;\n outputTokens: number | undefined;\n totalTokens?: number | undefined;\n inputTokenDetails?: {\n cacheReadTokens?: number | undefined;\n cacheWriteTokens?: number | undefined;\n };\n}): LLMUsage {\n const input = usage.inputTokens ?? 0;\n const output = usage.outputTokens ?? 0;\n const result: LLMUsage = {\n input_tokens: input,\n output_tokens: output,\n total_tokens: usage.totalTokens ?? input + output,\n };\n if (usage.inputTokenDetails?.cacheReadTokens != null) {\n result.cache_read_input_tokens = usage.inputTokenDetails.cacheReadTokens;\n }\n if (usage.inputTokenDetails?.cacheWriteTokens != null) {\n result.cache_creation_input_tokens = usage.inputTokenDetails.cacheWriteTokens;\n }\n return result;\n}\n\n/**\n * Convert Vercel finish reason (kebab-case) to Python format (snake_case).\n */\nexport function convertFinishReason(reason: string | undefined): string | null {\n if (!reason) return null;\n switch (reason) {\n case 'tool-calls':\n return 'tool_calls';\n case 'content-filter':\n return 'content_filter';\n default:\n return reason;\n }\n}\n","/**\n * LLM class wrapping Vercel AI SDK LanguageModel.\n *\n * Provides Python-compatible generate() and stream() methods\n * without durability or guardrails (use llmGenerate/llmStream for those).\n */\n\nimport { generateText, streamText, Output } from 'ai';\nimport type { ModelMessage as CoreMessage, LanguageModel } from 'ai';\nimport type { ZodType } from 'zod';\nimport type { LLMGenerateOptions, LLMResponse, LLMStreamEvent, LLMToolCall } from './types.js';\nimport {\n convertToolsToVercel,\n convertToolResultsToMessages,\n convertVercelToolCallToPython,\n convertVercelUsageToPython,\n convertFinishReason,\n getModelId,\n getModelProvider,\n} from './types.js';\n\n/** Cache breakpoint marker for Anthropic prompt caching. */\nexport const ANTHROPIC_CACHE_BREAKPOINT = {\n anthropic: { cacheControl: { type: 'ephemeral' as const } },\n};\n\n/** Check whether a LanguageModel is an Anthropic model. */\nexport function isAnthropicModel(model: LanguageModel): boolean {\n return getModelProvider(model).startsWith('anthropic');\n}\n\n/**\n * Remove all existing cache control markers from the args object (in-place).\n *\n * Must be called before applying fresh breakpoints so that stale markers\n * from previous agent loop iterations don't accumulate and exceed\n * Anthropic's 4-block limit.\n */\nfunction stripAnthropicCacheControl(args: Record<string, unknown>): void {\n // Strip from system prompt\n const system = args['system'];\n if (system && typeof system === 'object' && 'providerOptions' in system) {\n delete (system as Record<string, unknown>)['providerOptions'];\n }\n\n // Strip from tools\n const tools = args['tools'] as Record<string, Record<string, unknown>> | undefined;\n if (tools) {\n for (const name of Object.keys(tools)) {\n delete tools[name]?.['providerOptions'];\n }\n }\n\n // Strip from messages\n const messages = args['messages'] as Record<string, unknown>[] | undefined;\n if (messages) {\n for (const msg of messages) {\n delete msg['providerOptions'];\n }\n }\n}\n\n/**\n * Add Anthropic prompt-caching breakpoints to the args object (in-place).\n *\n * Marks the system prompt, the last tool, and the last message with\n * `providerOptions: { anthropic: { cacheControl: { type: 'ephemeral' } } }`\n * so the @ai-sdk/anthropic provider can enable prompt caching.\n * Strips any existing markers first to stay within the 4-block limit.\n */\nexport function applyAnthropicCacheControl(\n args: Record<string, unknown>,\n model: LanguageModel\n): void {\n if (!isAnthropicModel(model)) return;\n\n stripAnthropicCacheControl(args);\n\n // 1. System prompt: convert string to SystemModelMessage with cache control\n if (typeof args['system'] === 'string') {\n args['system'] = {\n role: 'system',\n content: args['system'],\n providerOptions: ANTHROPIC_CACHE_BREAKPOINT,\n };\n }\n\n // 2. Tools: add cache control to the last tool\n const tools = args['tools'] as Record<string, Record<string, unknown>> | undefined;\n if (tools) {\n const toolNames = Object.keys(tools);\n if (toolNames.length > 0) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const lastToolName = toolNames[toolNames.length - 1]!;\n tools[lastToolName] = {\n ...tools[lastToolName],\n providerOptions: ANTHROPIC_CACHE_BREAKPOINT,\n };\n }\n }\n\n // 3. Last message: add cache control to the last message\n const messages = args['messages'] as Record<string, unknown>[] | undefined;\n if (messages && messages.length > 0) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const lastMsg = messages[messages.length - 1]!;\n messages[messages.length - 1] = {\n ...lastMsg,\n providerOptions: ANTHROPIC_CACHE_BREAKPOINT,\n };\n }\n}\n\n/**\n * Build args object for generateText/streamText, only including defined properties\n * to satisfy exactOptionalPropertyTypes.\n */\nfunction buildGenerateArgs(\n model: LanguageModel,\n messages: CoreMessage[],\n options: LLMGenerateOptions\n): Record<string, unknown> {\n const args: Record<string, unknown> = { model, messages };\n const tools = convertToolsToVercel(options.tools);\n if (options.system !== undefined) args['system'] = options.system;\n if (tools !== undefined) args['tools'] = tools;\n if (options.temperature !== undefined) args['temperature'] = options.temperature;\n if (options.maxTokens !== undefined) args['maxTokens'] = options.maxTokens;\n if (options.topP !== undefined) args['topP'] = options.topP;\n if (options.outputSchema) {\n args['experimental_output'] = Output.object({ schema: options.outputSchema as ZodType });\n }\n applyAnthropicCacheControl(args, model);\n return args;\n}\n\n/**\n * LLM wraps a Vercel AI SDK LanguageModel to provide Python-compatible\n * generate() and stream() methods.\n *\n * @example\n * ```typescript\n * import { LLM } from '@polos/sdk';\n * import { anthropic } from '@ai-sdk/anthropic';\n *\n * const llm = new LLM({ model: anthropic('claude-sonnet-4-20250514') });\n * const response = await llm.generate({\n * messages: [{ role: 'user', content: 'Hello!' }],\n * });\n * console.log(response.content);\n * ```\n */\nexport class LLM {\n readonly model: LanguageModel;\n\n constructor(options: { model: LanguageModel }) {\n this.model = options.model;\n }\n\n /**\n * Generate a response (non-streaming).\n *\n * Returns an LLMResponse in Python-compatible format.\n */\n async generate(options: LLMGenerateOptions): Promise<LLMResponse> {\n const messages = [...options.messages, ...convertToolResultsToMessages(options.tool_results)];\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-explicit-any -- conditionally built args to satisfy exactOptionalPropertyTypes\n const result = await generateText(buildGenerateArgs(this.model, messages, options) as any);\n\n const toolCalls: LLMToolCall[] | null =\n result.toolCalls.length > 0\n ? result.toolCalls.map((tc) => convertVercelToolCallToPython(tc))\n : null;\n\n return {\n content: result.text || null,\n usage: convertVercelUsageToPython(result.totalUsage),\n tool_calls: toolCalls,\n raw_output: [...result.response.messages],\n model: getModelId(this.model),\n stop_reason: convertFinishReason(result.finishReason),\n };\n }\n\n /**\n * Stream a response.\n *\n * Yields LLMStreamEvents in Python-compatible format.\n */\n async *stream(options: LLMGenerateOptions): AsyncGenerator<LLMStreamEvent> {\n const messages = [...options.messages, ...convertToolResultsToMessages(options.tool_results)];\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-explicit-any -- conditionally built args to satisfy exactOptionalPropertyTypes\n const result = streamText(buildGenerateArgs(this.model, messages, options) as any);\n\n let finishUsage:\n | {\n inputTokens: number | undefined;\n outputTokens: number | undefined;\n totalTokens?: number | undefined;\n inputTokenDetails?: {\n cacheReadTokens?: number | undefined;\n cacheWriteTokens?: number | undefined;\n };\n }\n | undefined;\n let finishReason: string | undefined;\n\n for await (const part of result.fullStream) {\n switch (part.type) {\n case 'text-delta':\n yield { type: 'text_delta', data: { content: part.text } };\n break;\n case 'tool-call':\n yield {\n type: 'tool_call',\n data: { tool_call: convertVercelToolCallToPython(part) },\n };\n break;\n case 'finish':\n finishUsage = part.totalUsage;\n finishReason = part.finishReason;\n break;\n case 'error':\n yield {\n type: 'error',\n data: {\n error: part.error instanceof Error ? part.error.message : String(part.error),\n },\n };\n break;\n // Ignore all other part types (reasoning, step-start, step-finish, etc.)\n default:\n break;\n }\n }\n\n // After stream completes, get the full response messages for raw_output\n // (matching generate() which returns result.response.messages)\n const fullResponse = await result.response;\n const rawOutput = [...fullResponse.messages];\n\n yield {\n type: 'done',\n data: {\n usage: finishUsage\n ? convertVercelUsageToPython(finishUsage)\n : { input_tokens: 0, output_tokens: 0, total_tokens: 0 },\n raw_output: rawOutput,\n model: getModelId(this.model),\n stop_reason: convertFinishReason(finishReason),\n },\n };\n }\n}\n","/**\n * Guardrails for validating and transforming LLM outputs.\n *\n * Guardrails are executed after each LLM generation to validate\n * the output and optionally modify it before continuing.\n */\n\nimport type { WorkflowContext } from '../core/context.js';\nimport type { CoreMessage, ToolCall } from '../types/llm.js';\n\n/**\n * Context passed to guardrails during execution.\n */\nexport interface GuardrailContext {\n /** Text content from LLM (if any) */\n content?: string | undefined;\n /** Tool calls from LLM (if any) */\n toolCalls: ToolCall[];\n /** Messages so far in the conversation */\n messages: CoreMessage[];\n /** Number of guardrail retries so far */\n retryCount: number;\n /** Maximum allowed retries */\n maxRetries: number;\n}\n\n/**\n * Result from a guardrail execution.\n */\nexport interface GuardrailResultType {\n /** Whether to continue execution */\n continue: boolean;\n /** Error message if guardrail failed */\n error?: string | undefined;\n /** Modified content to use instead */\n modifiedContent?: string | undefined;\n /** Modified tool calls to use instead */\n modifiedToolCalls?: ToolCall[] | undefined;\n /** Whether to retry the LLM call */\n retry?: boolean | undefined;\n /** Custom feedback to include in retry prompt */\n retryFeedback?: string | undefined;\n}\n\n/**\n * Guardrail handler function type.\n */\nexport type GuardrailHandler<TState = unknown> = (\n ctx: WorkflowContext<TState>,\n guardrailCtx: GuardrailContext\n) => Promise<GuardrailResultType>;\n\n/**\n * Guardrail definition with optional metadata.\n */\nexport interface Guardrail<TState = unknown> {\n /** Guardrail handler function */\n handler: GuardrailHandler<TState>;\n /** Optional guardrail name for debugging/tracing */\n name?: string | undefined;\n /** Optional guardrail description */\n description?: string | undefined;\n /** Priority (lower numbers run first, default: 0) */\n priority?: number | undefined;\n}\n\n/**\n * Options for defining a guardrail.\n */\nexport interface DefineGuardrailOptions {\n /** Guardrail name for debugging/tracing */\n name?: string | undefined;\n /** Guardrail description */\n description?: string | undefined;\n /** Priority (lower numbers run first, default: 0) */\n priority?: number | undefined;\n}\n\n/**\n * Helper for creating guardrail results.\n */\nexport const GuardrailResult = {\n /**\n * Continue execution without modifications.\n *\n * @example\n * ```typescript\n * if (isContentSafe(guardrailCtx.content)) {\n * return GuardrailResult.continue();\n * }\n * ```\n */\n continue: (): GuardrailResultType => ({ continue: true }),\n\n /**\n * Continue execution with modifications.\n *\n * @example\n * ```typescript\n * const sanitized = sanitizeContent(guardrailCtx.content);\n * return GuardrailResult.continueWith({\n * modifiedContent: sanitized,\n * });\n * ```\n */\n continueWith: (options: {\n modifiedContent?: string;\n modifiedToolCalls?: ToolCall[];\n }): GuardrailResultType => {\n const result: GuardrailResultType = { continue: true };\n if (options.modifiedContent !== undefined) {\n result.modifiedContent = options.modifiedContent;\n }\n if (options.modifiedToolCalls !== undefined) {\n result.modifiedToolCalls = options.modifiedToolCalls;\n }\n return result;\n },\n\n /**\n * Stop execution with an error.\n *\n * @example\n * ```typescript\n * if (containsHarmfulContent(guardrailCtx.content)) {\n * return GuardrailResult.fail('Content contains harmful material');\n * }\n * ```\n */\n fail: (error: string): GuardrailResultType => ({\n continue: false,\n error,\n }),\n\n /**\n * Retry the LLM call with optional feedback.\n *\n * This will trigger a new LLM generation with the provided feedback\n * included in the context. The retry count will be incremented.\n *\n * @example\n * ```typescript\n * if (!isValidFormat(guardrailCtx.content)) {\n * return GuardrailResult.retry(\n * 'Please format your response as valid JSON with the required fields.'\n * );\n * }\n * ```\n */\n retry: (feedback?: string): GuardrailResultType => ({\n continue: false,\n retry: true,\n retryFeedback: feedback,\n }),\n};\n\n/**\n * Define a guardrail for validating LLM outputs.\n *\n * @example\n * ```typescript\n * // Content filter guardrail\n * const contentFilter = defineGuardrail(\n * async (ctx, guardrailCtx) => {\n * const content = guardrailCtx.content;\n *\n * if (!content) {\n * return GuardrailResult.fail('No content generated');\n * }\n *\n * if (containsInappropriateContent(content)) {\n * return GuardrailResult.fail('Content contains inappropriate material');\n * }\n *\n * const sanitized = sanitizeContent(content);\n * return GuardrailResult.continueWith({ modifiedContent: sanitized });\n * },\n * { name: 'content-filter', priority: 10 }\n * );\n *\n * // Tool validator guardrail\n * const toolValidator = defineGuardrail(async (ctx, guardrailCtx) => {\n * for (const call of guardrailCtx.toolCalls) {\n * if (call.name === 'dangerous-tool' && !ctx.state.isAdmin) {\n * return GuardrailResult.fail('Unauthorized tool access');\n * }\n * }\n * return GuardrailResult.continue();\n * });\n * ```\n */\nexport function defineGuardrail<TState = unknown>(\n handler: GuardrailHandler<TState>,\n options?: DefineGuardrailOptions\n): Guardrail<TState> {\n return {\n handler,\n name: options?.name,\n description: options?.description,\n priority: options?.priority ?? 0,\n };\n}\n\n/**\n * Type guard to check if a value is a Guardrail object.\n */\nexport function isGuardrail<TState = unknown>(value: unknown): value is Guardrail<TState> {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'handler' in value &&\n typeof (value as Guardrail).handler === 'function'\n );\n}\n\n/**\n * Normalize a guardrail handler or Guardrail object to a Guardrail.\n */\nexport function normalizeGuardrail<TState = unknown>(\n guardrailOrHandler: Guardrail<TState> | GuardrailHandler<TState>\n): Guardrail<TState> {\n if (isGuardrail<TState>(guardrailOrHandler)) {\n return guardrailOrHandler;\n }\n return { handler: guardrailOrHandler };\n}\n\n/**\n * Normalize and sort an array of guardrails by priority.\n */\nexport function normalizeGuardrails<TState = unknown>(\n guardrails: (Guardrail<TState> | GuardrailHandler<TState>)[] | undefined\n): Guardrail<TState>[] {\n if (guardrails === undefined) {\n return [];\n }\n\n return guardrails\n .map((g) => normalizeGuardrail(g))\n .sort((a, b) => (a.priority ?? 0) - (b.priority ?? 0));\n}\n","/**\n * Exponential backoff retry utilities.\n */\n\nexport interface RetryOptions {\n /** Maximum number of retry attempts (default: 3) */\n maxRetries?: number;\n /** Initial delay in milliseconds (default: 1000) */\n baseDelay?: number;\n /** Maximum delay in milliseconds (default: 30000) */\n maxDelay?: number;\n /** Multiplier for exponential backoff (default: 2) */\n backoffMultiplier?: number;\n /** Add random jitter to delays (default: true) */\n jitter?: boolean;\n /** Function to determine if error is retryable (default: all errors) */\n isRetryable?: (error: unknown) => boolean;\n /** Callback called before each retry */\n onRetry?: (error: unknown, attempt: number, delay: number) => void;\n}\n\nconst DEFAULT_OPTIONS: Required<Omit<RetryOptions, 'onRetry' | 'isRetryable'>> = {\n maxRetries: 3,\n baseDelay: 1000,\n maxDelay: 30000,\n backoffMultiplier: 2,\n jitter: true,\n};\n\n/**\n * Calculate delay for a given attempt with exponential backoff.\n */\nexport function calculateDelay(\n attempt: number,\n options: Pick<RetryOptions, 'baseDelay' | 'maxDelay' | 'backoffMultiplier' | 'jitter'>\n): number {\n const { baseDelay = 1000, maxDelay = 30000, backoffMultiplier = 2, jitter = true } = options;\n\n // Exponential backoff: baseDelay * (multiplier ^ attempt)\n let delay = baseDelay * Math.pow(backoffMultiplier, attempt);\n\n // Cap at maxDelay\n delay = Math.min(delay, maxDelay);\n\n // Add jitter (±25%)\n if (jitter) {\n const jitterRange = delay * 0.25;\n delay = delay - jitterRange + Math.random() * jitterRange * 2;\n }\n\n return Math.round(delay);\n}\n\n/**\n * Sleep for a given duration.\n */\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Execute a function with exponential backoff retry.\n *\n * @example\n * ```typescript\n * const result = await retry(\n * () => fetchData(),\n * {\n * maxRetries: 3,\n * baseDelay: 1000,\n * isRetryable: (err) => err instanceof NetworkError,\n * }\n * );\n * ```\n */\nexport async function retry<T>(fn: () => T | Promise<T>, options: RetryOptions = {}): Promise<T> {\n const opts = { ...DEFAULT_OPTIONS, ...options };\n let lastError: unknown;\n\n for (let attempt = 0; attempt <= opts.maxRetries; attempt++) {\n try {\n return await fn();\n } catch (error) {\n lastError = error;\n\n // Check if we should retry\n if (attempt >= opts.maxRetries) {\n break;\n }\n\n // Check if error is retryable\n if (opts.isRetryable && !opts.isRetryable(error)) {\n break;\n }\n\n // Calculate delay and wait\n const delay = calculateDelay(attempt, opts);\n\n // Call onRetry callback\n opts.onRetry?.(error, attempt + 1, delay);\n\n await sleep(delay);\n }\n }\n\n throw lastError;\n}\n\n/**\n * Create a retry wrapper with preset options.\n *\n * @example\n * ```typescript\n * const retryWithBackoff = createRetry({ maxRetries: 5 });\n * const result = await retryWithBackoff(() => fetchData());\n * ```\n */\nexport function createRetry(defaultOptions: RetryOptions) {\n return <T>(fn: () => T | Promise<T>, options?: RetryOptions): Promise<T> => {\n return retry(fn, { ...defaultOptions, ...options });\n };\n}\n","/**\n * StepHelper implementation.\n *\n * Provides durable operations within workflows including step execution,\n * workflow invocation, waiting, and event publishing.\n *\n */\n\nimport { randomUUID } from 'node:crypto';\nimport type { Workflow, WorkflowHandle, WorkflowStatus } from '../types/workflow.js';\nimport { retry, type RetryOptions } from '../utils/retry.js';\n\n/**\n * Error thrown when a step execution fails.\n */\nexport class StepExecutionError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'StepExecutionError';\n }\n}\n\n/**\n * Internal error thrown when workflow execution must pause to wait.\n * @internal\n */\nexport class WaitError extends Error {\n /** Discriminator for runtime checks (survives minification unlike instanceof). */\n readonly __isWaitError = true as const;\n /** Structured data about the wait. */\n readonly waitData: Record<string, unknown>;\n\n constructor(reason: string, waitData?: Record<string, unknown>) {\n super(reason);\n this.name = 'WaitError';\n this.waitData = waitData ?? {};\n }\n}\n\n/**\n * Type guard for WaitError — works across module boundaries and minification.\n * @internal\n */\nexport function isWaitError(error: unknown): error is WaitError {\n return (\n error instanceof WaitError ||\n (typeof error === 'object' &&\n error !== null &&\n '__isWaitError' in error &&\n (error as Record<string, unknown>)['__isWaitError'] === true)\n );\n}\n\n/**\n * Options for step execution.\n */\nexport interface StepOptions {\n /** Maximum retry attempts (default: 2) */\n maxRetries?: number | undefined;\n /** Initial delay for exponential backoff in ms (default: 1000) */\n baseDelay?: number | undefined;\n /** Maximum delay for exponential backoff in ms (default: 10000) */\n maxDelay?: number | undefined;\n /** Input data to record in the trace span (for observability) */\n input?: unknown;\n}\n\n/**\n * Options for invoking another workflow.\n */\nexport interface InvokeOptions {\n /** Concurrency key for rate limiting */\n concurrencyKey?: string | undefined;\n /** Initial state for the sub-workflow */\n initialState?: Record<string, unknown> | undefined;\n /** Queue name to run the sub-workflow on */\n queue?: string | undefined;\n /** Timeout in seconds for the sub-workflow execution */\n runTimeoutSeconds?: number | undefined;\n}\n\n/**\n * Options for waiting a duration.\n */\nexport interface WaitForOptions {\n /** Seconds to wait */\n seconds?: number | undefined;\n /** Minutes to wait */\n minutes?: number | undefined;\n /** Hours to wait */\n hours?: number | undefined;\n /** Days to wait */\n days?: number | undefined;\n /** Weeks to wait */\n weeks?: number | undefined;\n}\n\n/**\n * Options for waiting on an event.\n */\nexport interface WaitForEventOptions {\n /** Event topic to wait on */\n topic: string;\n /** Timeout in seconds */\n timeout?: number | undefined;\n}\n\n/**\n * Options for publishing an event.\n */\nexport interface PublishEventOptions {\n /** Event topic */\n topic: string;\n /** Event type */\n type?: string | undefined;\n /** Event data */\n data: unknown;\n}\n\n/**\n * Options for suspending workflow execution.\n */\nexport interface SuspendOptions<T = unknown> {\n /** Data to include in the suspension */\n data?: T | undefined;\n /** Timeout in seconds before auto-resuming */\n timeout?: number | undefined;\n}\n\n/**\n * Options for resuming a suspended workflow.\n */\nexport interface ResumeOptions {\n /** The step key used in the original suspend() call */\n suspendStepKey: string;\n /** The root execution ID of the suspended execution */\n suspendExecutionId: string;\n /** The root workflow ID of the suspended execution */\n suspendWorkflowId: string;\n /** Data to pass in the resume event */\n data: unknown;\n}\n\n/**\n * Input for batch workflow invocation.\n */\nexport interface BatchWorkflowInput {\n /** Workflow to invoke (ID string or Workflow object) */\n workflow: string | Workflow;\n /** Payload for this invocation */\n payload: unknown;\n /** Initial state for the sub-workflow */\n initialState?: Record<string, unknown> | undefined;\n /** Timeout in seconds for the sub-workflow execution */\n runTimeoutSeconds?: number | undefined;\n}\n\n/**\n * Result of a single workflow in a batch invocation.\n * Matches Python BatchStepResult.\n */\nexport interface BatchStepResult<T = unknown> {\n /** The workflow ID that was invoked */\n workflowId: string;\n /** Whether the workflow completed successfully */\n success: boolean;\n /** The result from the workflow (if successful) */\n result: T | null;\n /** Error message (if failed) */\n error: string | null;\n}\n\n/**\n * Configuration for agent invocation.\n * Matches Python AgentRunConfig.\n *\n * Created by AgentWorkflow.withInput(). Used by step.agentInvoke(),\n * step.batchAgentInvoke(), and the standalone batchAgentInvoke().\n */\nexport class AgentRunConfig {\n /** The agent workflow */\n readonly agent: Workflow;\n /** Input for the agent (string message or message array) */\n readonly input: string | Record<string, unknown>[];\n /** Session ID */\n readonly sessionId: string | undefined;\n /** User ID */\n readonly userId: string | undefined;\n /** Whether to stream the response */\n readonly streaming: boolean;\n /** Initial state for the agent workflow */\n readonly initialState: Record<string, unknown> | undefined;\n /** Timeout in seconds for execution */\n readonly runTimeoutSeconds: number | undefined;\n /** Additional fields to include in the payload */\n readonly kwargs: Record<string, unknown>;\n\n constructor(options: {\n agent: Workflow;\n input: string | Record<string, unknown>[];\n sessionId?: string;\n userId?: string;\n streaming?: boolean;\n initialState?: Record<string, unknown>;\n runTimeoutSeconds?: number;\n kwargs?: Record<string, unknown>;\n }) {\n this.agent = options.agent;\n this.input = options.input;\n this.sessionId = options.sessionId;\n this.userId = options.userId;\n this.streaming = options.streaming ?? false;\n this.initialState = options.initialState;\n this.runTimeoutSeconds = options.runTimeoutSeconds;\n this.kwargs = options.kwargs ?? {};\n }\n}\n\n/**\n * Step execution result stored for replay.\n */\nexport interface StepResult<T = unknown> {\n /** Step key */\n key: string;\n /** Result value */\n value: T;\n /** When the step completed */\n completedAt: Date;\n}\n\n/**\n * Internal step store interface for caching step results.\n */\nexport interface StepStore {\n /** Get a cached step result */\n\n get<T>(key: string): StepResult<T> | undefined;\n /** Store a step result */\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters -- T is used for input type inference\n set<T>(key: string, value: T): void;\n /** Check if a step has been executed */\n has(key: string): boolean;\n}\n\n/**\n * Create an in-memory step store.\n */\nexport function createStepStore(): StepStore {\n const results = new Map<string, StepResult>();\n\n return {\n get<T>(key: string): StepResult<T> | undefined {\n return results.get(key) as StepResult<T> | undefined;\n },\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters -- T is used for input type inference\n set<T>(key: string, value: T): void {\n results.set(key, {\n key,\n value,\n completedAt: new Date(),\n });\n },\n has(key: string): boolean {\n return results.has(key);\n },\n };\n}\n\n/**\n * StepHelper provides durable operations within workflows.\n */\nexport interface StepHelper {\n /**\n * Execute a function as a durable step.\n * Results are cached and replayed on retry.\n */\n run<T>(key: string, fn: () => T | Promise<T>, options?: StepOptions): Promise<T>;\n\n /**\n * Invoke another workflow (fire and forget).\n */\n invoke<TPayload = unknown, TResult = unknown>(\n key: string,\n workflow: string | Workflow<TPayload, unknown, TResult>,\n payload: TPayload,\n options?: InvokeOptions\n ): Promise<WorkflowHandle<TResult>>;\n\n /**\n * Invoke another workflow and wait for result.\n */\n invokeAndWait<TPayload = unknown, TResult = unknown>(\n key: string,\n workflow: string | Workflow<TPayload, unknown, TResult>,\n payload: TPayload,\n options?: InvokeOptions\n ): Promise<TResult>;\n\n /**\n * Invoke multiple workflows in batch.\n */\n batchInvoke(key: string, items: BatchWorkflowInput[]): Promise<WorkflowHandle<unknown>[]>;\n\n /**\n * Invoke multiple workflows and wait for all results.\n */\n batchInvokeAndWait<T>(key: string, items: BatchWorkflowInput[]): Promise<BatchStepResult<T>[]>;\n\n /**\n * Wait for a time duration.\n */\n waitFor(key: string, options: WaitForOptions): Promise<void>;\n\n /**\n * Wait until a specific date/time.\n */\n waitUntil(key: string, date: Date): Promise<void>;\n\n /**\n * Wait for an event on a topic.\n */\n waitForEvent<T>(key: string, options: WaitForEventOptions): Promise<T>;\n\n /**\n * Publish an event to a topic.\n */\n publishEvent(key: string, options: PublishEventOptions): Promise<void>;\n\n /**\n * Publish an event on the current workflow's topic.\n */\n publishWorkflowEvent(key: string, options: { data: unknown; type?: string }): Promise<void>;\n\n /**\n * Suspend workflow execution and wait for external resume.\n */\n suspend<T = unknown, R = unknown>(key: string, options?: SuspendOptions<T>): Promise<R>;\n\n /**\n * Resume a suspended execution by publishing a resume event.\n */\n resume(key: string, options: ResumeOptions): Promise<void>;\n\n /**\n * Generate a durable UUID (persisted via step key).\n */\n uuid(key: string): Promise<string>;\n\n /**\n * Get current timestamp in milliseconds (persisted via step key).\n */\n now(key: string): Promise<number>;\n\n /**\n * Generate a durable random number between 0 and 1 (persisted via step key).\n */\n random(key: string): Promise<number>;\n\n /**\n * Invoke an agent workflow (fire and forget).\n */\n agentInvoke(key: string, config: AgentRunConfig): Promise<WorkflowHandle<unknown>>;\n\n /**\n * Invoke an agent workflow and wait for result.\n */\n agentInvokeAndWait(key: string, config: AgentRunConfig): Promise<unknown>;\n\n /**\n * Invoke multiple agent workflows in batch (fire and forget).\n */\n batchAgentInvoke(key: string, configs: AgentRunConfig[]): Promise<WorkflowHandle<unknown>[]>;\n\n /**\n * Invoke multiple agent workflows in batch and wait for all results.\n */\n batchAgentInvokeAndWait<T>(key: string, configs: AgentRunConfig[]): Promise<BatchStepResult<T>[]>;\n\n /**\n * Create a custom traced span around an async operation.\n */\n trace<T>(\n name: string,\n fn: (span: unknown) => Promise<T>,\n attributes?: Record<string, string | number | boolean>\n ): Promise<T>;\n}\n\n/**\n * Options for creating a StepHelper.\n */\nexport interface CreateStepHelperOptions {\n /** Step store for caching results */\n store: StepStore;\n}\n\n/**\n * Create a local StepHelper instance (for testing / local execution).\n * The real orchestrator-backed implementation is in runtime/executor.ts.\n */\nexport function createStepHelper(options: CreateStepHelperOptions): StepHelper {\n const { store } = options;\n\n return {\n async run<T>(key: string, fn: () => T | Promise<T>, stepOptions?: StepOptions): Promise<T> {\n // Check if step result is cached\n const cached = store.get<T>(key);\n if (cached) {\n return cached.value;\n }\n\n // Execute with retry\n const retryOptions: RetryOptions = {\n maxRetries: stepOptions?.maxRetries ?? 2,\n baseDelay: stepOptions?.baseDelay ?? 1000,\n maxDelay: stepOptions?.maxDelay ?? 10000,\n };\n\n try {\n const result = await retry(fn, retryOptions);\n store.set(key, result);\n return result;\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n throw new StepExecutionError(\n `Step execution failed after ${String(retryOptions.maxRetries)} retries: ${errorMessage}`\n );\n }\n },\n\n // eslint-disable-next-line @typescript-eslint/require-await -- stub implementation\n async invoke<TPayload, TResult>(\n key: string,\n _workflow: string | Workflow<TPayload, unknown, TResult>,\n _payload: TPayload,\n _options?: InvokeOptions\n ): Promise<WorkflowHandle<TResult>> {\n const cached = store.get<WorkflowHandle<TResult>>(key);\n if (cached) {\n return cached.value;\n }\n\n // Local stub — no orchestrator\n const executionId = randomUUID();\n const handle: WorkflowHandle<TResult> = {\n executionId,\n // eslint-disable-next-line @typescript-eslint/require-await -- stub\n getStatus: async (): Promise<WorkflowStatus<TResult>> => ({\n status: 'queued',\n createdAt: new Date(),\n }),\n // eslint-disable-next-line @typescript-eslint/require-await -- stub\n waitForResult: async (): Promise<TResult> => {\n throw new Error('Orchestrator client not configured');\n },\n // eslint-disable-next-line @typescript-eslint/require-await -- stub\n cancel: async (): Promise<void> => {\n throw new Error('Orchestrator client not configured');\n },\n };\n\n store.set(key, handle);\n return handle;\n },\n\n // eslint-disable-next-line @typescript-eslint/require-await -- stub throws WaitError\n async invokeAndWait<TPayload, TResult>(\n key: string,\n workflow: string | Workflow<TPayload, unknown, TResult>,\n _payload: TPayload,\n _options?: InvokeOptions\n ): Promise<TResult> {\n // Check cache (matching Python: _invoke with wait_for_subworkflow=True returns cached result)\n const cached = store.get<TResult>(key);\n if (cached) {\n return cached.value;\n }\n\n // Local stub — no orchestrator. Throw WaitError (matching Python WaitException).\n const workflowId = typeof workflow === 'string' ? workflow : workflow.id;\n throw new WaitError(`Waiting for sub-workflow '${workflowId}' to complete`, { workflowId });\n },\n\n async batchInvoke(\n key: string,\n items: BatchWorkflowInput[]\n ): Promise<WorkflowHandle<unknown>[]> {\n const cached = store.get<WorkflowHandle<unknown>[]>(key);\n if (cached) {\n return cached.value;\n }\n\n const handles: WorkflowHandle<unknown>[] = [];\n for (const [index, item] of items.entries()) {\n const handle = await this.invoke(`${key}:${String(index)}`, item.workflow, item.payload);\n handles.push(handle);\n }\n\n store.set(key, handles);\n return handles;\n },\n\n // eslint-disable-next-line @typescript-eslint/require-await -- stub throws WaitError\n async batchInvokeAndWait<T>(\n key: string,\n items: BatchWorkflowInput[]\n ): Promise<BatchStepResult<T>[]> {\n if (items.length === 0) return [];\n\n // Check cache (matching Python: _check_existing_step → reconstruct results)\n const cached = store.get<BatchStepResult<T>[]>(key);\n if (cached) {\n return cached.value;\n }\n\n // Local stub — no orchestrator. Throw WaitError (matching Python WaitException).\n const workflowIds = items\n .map((item) => (typeof item.workflow === 'string' ? item.workflow : item.workflow.id))\n .join(', ');\n throw new WaitError(`Waiting for sub-workflows [${workflowIds}] to complete`, {\n workflowIds: workflowIds.split(', '),\n });\n },\n\n async waitFor(key: string, options: WaitForOptions): Promise<void> {\n const cached = store.get(key);\n if (cached) return;\n\n let totalSeconds = 0;\n if (options.seconds) totalSeconds += options.seconds;\n if (options.minutes) totalSeconds += options.minutes * 60;\n if (options.hours) totalSeconds += options.hours * 3600;\n if (options.days) totalSeconds += options.days * 86400;\n if (options.weeks) totalSeconds += options.weeks * 604800;\n\n const totalMs = totalSeconds * 1000;\n await new Promise((resolve) => setTimeout(resolve, totalMs));\n store.set(key, { wait_until: new Date(Date.now() + totalMs).toISOString() });\n },\n\n async waitUntil(key: string, date: Date): Promise<void> {\n const cached = store.get(key);\n if (cached) return;\n\n const now = Date.now();\n const waitMs = Math.max(0, date.getTime() - now);\n await new Promise((resolve) => setTimeout(resolve, waitMs));\n store.set(key, { wait_until: date.toISOString() });\n },\n\n // eslint-disable-next-line @typescript-eslint/require-await -- stub implementation\n async waitForEvent<T>(key: string, eventOptions: WaitForEventOptions): Promise<T> {\n const cached = store.get<T>(key);\n if (cached) {\n return cached.value;\n }\n throw new Error(`waitForEvent not implemented locally: ${eventOptions.topic}`);\n },\n\n // eslint-disable-next-line @typescript-eslint/require-await -- stub implementation\n async publishEvent(key: string, _options: PublishEventOptions): Promise<void> {\n if (store.has(key)) return;\n store.set(key, null);\n },\n\n async publishWorkflowEvent(\n key: string,\n options: { data: unknown; type?: string }\n ): Promise<void> {\n // Local stub — no workflow topic available\n return this.publishEvent(key, { topic: 'local', ...options });\n },\n\n // eslint-disable-next-line @typescript-eslint/require-await -- stub implementation\n async suspend<T, R>(key: string, _options?: SuspendOptions<T>): Promise<R> {\n const cached = store.get<R>(key);\n if (cached) {\n return cached.value;\n }\n throw new Error('suspend not implemented locally');\n },\n\n async resume(key: string, options: ResumeOptions): Promise<void> {\n const topic = `workflow/${options.suspendWorkflowId}/${options.suspendExecutionId}`;\n return this.publishEvent(key, {\n topic,\n type: `resume_${options.suspendStepKey}`,\n data: options.data,\n });\n },\n\n // eslint-disable-next-line @typescript-eslint/require-await -- stub implementation\n async uuid(key: string): Promise<string> {\n const cached = store.get<string>(key);\n if (cached) {\n return cached.value;\n }\n const generated = randomUUID();\n store.set(key, generated);\n return generated;\n },\n\n // eslint-disable-next-line @typescript-eslint/require-await -- stub implementation\n async now(key: string): Promise<number> {\n const cached = store.get<number>(key);\n if (cached) {\n return cached.value;\n }\n const timestamp = Date.now();\n store.set(key, timestamp);\n return timestamp;\n },\n\n // eslint-disable-next-line @typescript-eslint/require-await -- stub implementation\n async random(key: string): Promise<number> {\n const cached = store.get<number>(key);\n if (cached) {\n return cached.value;\n }\n const value = Math.random();\n store.set(key, value);\n return value;\n },\n\n // --- Agent invoke stubs (local — delegates to invoke/batchInvoke) ---\n // Matches Python step.py agent_invoke / batch_agent_invoke etc.\n\n async agentInvoke(key: string, config: AgentRunConfig): Promise<WorkflowHandle<unknown>> {\n const payload = {\n input: config.input,\n streaming: config.streaming,\n session_id: undefined as string | undefined,\n user_id: undefined as string | undefined,\n ...config.kwargs,\n };\n return this.invoke(key, config.agent, payload);\n },\n\n async agentInvokeAndWait(key: string, config: AgentRunConfig): Promise<unknown> {\n const payload = {\n input: config.input,\n streaming: config.streaming,\n session_id: undefined as string | undefined,\n user_id: undefined as string | undefined,\n ...config.kwargs,\n };\n return this.invokeAndWait(key, config.agent, payload);\n },\n\n async batchAgentInvoke(\n key: string,\n configs: AgentRunConfig[]\n ): Promise<WorkflowHandle<unknown>[]> {\n const items: BatchWorkflowInput[] = configs.map((config) => ({\n workflow: config.agent,\n payload: {\n input: config.input,\n streaming: config.streaming,\n session_id: undefined as string | undefined,\n user_id: undefined as string | undefined,\n ...config.kwargs,\n },\n initialState: config.initialState,\n runTimeoutSeconds: config.runTimeoutSeconds,\n }));\n return this.batchInvoke(key, items);\n },\n\n async batchAgentInvokeAndWait<T>(\n key: string,\n configs: AgentRunConfig[]\n ): Promise<BatchStepResult<T>[]> {\n const items: BatchWorkflowInput[] = configs.map((config) => ({\n workflow: config.agent,\n payload: {\n input: config.input,\n streaming: config.streaming,\n session_id: undefined as string | undefined,\n user_id: undefined as string | undefined,\n ...config.kwargs,\n },\n initialState: config.initialState,\n runTimeoutSeconds: config.runTimeoutSeconds,\n }));\n return this.batchInvokeAndWait<T>(key, items);\n },\n\n async trace<T>(\n _name: string,\n fn: (span: unknown) => Promise<T>,\n _attributes?: Record<string, string | number | boolean>\n ): Promise<T> {\n return fn(undefined);\n },\n };\n}\n","/**\n * Hook execution engine.\n *\n * Handles sequential execution of hooks with durable step-based execution,\n * payload/output modification, and result aggregation.\n *\n * Matches Python sdk/python/polos/middleware/hook_executor.py.\n */\n\nimport type { WorkflowContext } from '../core/context.js';\nimport type { Hook, HookContext, HookResultType } from './hook.js';\nimport { normalizeHooks } from './hook.js';\n\n/**\n * Error thrown when a hook fails.\n */\nexport class HookExecutionError extends Error {\n constructor(\n message: string,\n public readonly hookName: string | undefined,\n public readonly phase: 'onStart' | 'onEnd',\n public override readonly cause?: Error\n ) {\n super(message, { cause });\n this.name = 'HookExecutionError';\n }\n}\n\n/**\n * Result from executing a chain of hooks.\n */\nexport interface HookChainResult<TPayload> {\n /** Whether all hooks passed */\n success: boolean;\n /** Final payload after all modifications */\n payload: TPayload;\n /** Final output after all modifications (for onEnd hooks) */\n // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents -- needed for exactOptionalPropertyTypes\n output?: unknown | undefined;\n /** Error message if a hook failed */\n error?: string | undefined;\n /** Name of the hook that failed (if any) */\n failedHook?: string | undefined;\n /** Number of hooks executed */\n hooksExecuted: number;\n}\n\n/**\n * Options for hook execution.\n */\nexport interface ExecuteHooksOptions<TPayload> {\n /** The workflow context (must have step for durable execution) */\n ctx: WorkflowContext;\n /** Hook chain name for durable step key naming (e.g., \"on_start\", \"on_end\").\n * Matching Python execute_hooks hook_name parameter. */\n hookName: string;\n /** Payload to pass to hooks */\n payload: TPayload;\n /** Workflow output (for onEnd hooks, matching Python HookContext.current_output) */\n // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents -- needed for exactOptionalPropertyTypes\n output?: unknown | undefined;\n /** Execution phase */\n phase: 'onStart' | 'onEnd';\n}\n\n/**\n * Get a unique identifier for a hook function.\n * Matching Python _get_function_identifier.\n */\nfunction getHookIdentifier(\n hook: { name?: string | undefined; handler: { name: string } },\n index: number\n): string {\n if (hook.name) {\n return hook.name;\n }\n if (hook.handler.name && hook.handler.name !== '') {\n return hook.handler.name;\n }\n return `hook_${String(index)}`;\n}\n\n/**\n * Execute a chain of hooks sequentially with durable execution.\n *\n * Each hook is executed via ctx.step.run() for durability — results are\n * cached and replayed on retry. Matching Python execute_hooks().\n *\n * Hooks are executed in order. If a hook returns `continue: false`,\n * execution stops and the error is returned. Payload and output\n * modifications from each hook are passed to the next hook.\n */\nexport async function executeHookChain<TPayload, TState>(\n hooks:\n | Hook<TPayload, TState>\n | Hook<TPayload, TState>[]\n | ((ctx: WorkflowContext<TState>, hookCtx: HookContext<TPayload>) => Promise<HookResultType>)\n | ((ctx: WorkflowContext<TState>, hookCtx: HookContext<TPayload>) => Promise<HookResultType>)[]\n | undefined,\n options: ExecuteHooksOptions<TPayload>\n): Promise<HookChainResult<TPayload>> {\n const { ctx, hookName, payload, phase, output } = options;\n const normalizedHooks = normalizeHooks(hooks);\n\n if (normalizedHooks.length === 0) {\n return {\n success: true,\n payload,\n output,\n hooksExecuted: 0,\n };\n }\n\n let currentPayload = payload;\n let currentOutput = output;\n let hooksExecuted = 0;\n\n for (const [index, hook] of normalizedHooks.entries()) {\n const funcId = getHookIdentifier(hook, index);\n\n const hookCtx: HookContext<TPayload> = {\n workflowId: ctx.workflowId,\n sessionId: ctx.sessionId,\n userId: ctx.userId,\n currentPayload,\n currentOutput,\n phase,\n };\n\n try {\n // Execute hook durably via step.run (matching Python: ctx.step.run(...))\n const result = await ctx.step.run<HookResultType>(\n `${hookName}.${funcId}.${String(index)}`,\n () => hook.handler(ctx as WorkflowContext<TState>, hookCtx),\n { input: { payload: currentPayload, output: currentOutput, phase } }\n );\n hooksExecuted++;\n\n if (!result.continue) {\n return {\n success: false,\n payload: currentPayload,\n output: currentOutput,\n error: result.error ?? 'Hook execution stopped',\n failedHook: hook.name,\n hooksExecuted,\n };\n }\n\n // Apply payload modifications (matching Python: modified_payload.update(...))\n if (result.modifiedPayload !== undefined) {\n currentPayload = result.modifiedPayload as TPayload;\n }\n\n // Apply output modifications (matching Python: modified_output.update(...))\n if (result.modifiedOutput !== undefined) {\n currentOutput = result.modifiedOutput;\n }\n } catch (err) {\n hooksExecuted++;\n const errorMessage = err instanceof Error ? err.message : String(err);\n\n return {\n success: false,\n payload: currentPayload,\n output: currentOutput,\n error: `Hook${hook.name ? ` '${hook.name}'` : ''} threw an error: ${errorMessage}`,\n failedHook: hook.name,\n hooksExecuted,\n };\n }\n }\n\n return {\n success: true,\n payload: currentPayload,\n output: currentOutput,\n hooksExecuted,\n };\n}\n\n/**\n * Execute hooks and throw if any hook fails.\n *\n * Convenience wrapper around `executeHookChain` that throws\n * a `HookExecutionError` if any hook fails.\n *\n * @returns The final payload after all hook modifications\n * @throws HookExecutionError if any hook fails\n */\nexport async function executeHooksOrThrow<TPayload, TState>(\n hooks:\n | Hook<TPayload, TState>\n | Hook<TPayload, TState>[]\n | ((ctx: WorkflowContext<TState>, hookCtx: HookContext<TPayload>) => Promise<HookResultType>)\n | ((ctx: WorkflowContext<TState>, hookCtx: HookContext<TPayload>) => Promise<HookResultType>)[]\n | undefined,\n options: ExecuteHooksOptions<TPayload>\n): Promise<TPayload> {\n const result = await executeHookChain(hooks, options);\n\n if (!result.success) {\n throw new HookExecutionError(\n result.error ?? 'Hook execution failed',\n result.failedHook,\n options.phase\n );\n }\n\n return result.payload;\n}\n\n/**\n * Create a composite hook from multiple hooks.\n *\n * The composite hook executes all provided hooks in sequence and\n * returns the combined result.\n */\nexport function composeHooks<TPayload = unknown, TState = unknown>(\n hooks: Hook<TPayload, TState>[]\n): Hook<TPayload, TState> {\n return {\n name: `composed(${hooks.map((h) => h.name ?? 'anonymous').join(', ')})`,\n handler: async (ctx, hookCtx) => {\n const result = await executeHookChain(hooks, {\n ctx: ctx as WorkflowContext,\n hookName: 'composed',\n payload: hookCtx.currentPayload,\n phase: hookCtx.phase,\n output: hookCtx.currentOutput,\n });\n\n if (!result.success) {\n return {\n continue: false,\n error: result.error,\n };\n }\n\n return {\n continue: true,\n modifiedPayload: result.payload,\n modifiedOutput: result.output,\n };\n },\n };\n}\n\n/**\n * Create a hook that only runs if a condition is met.\n */\nexport function conditionalHook<TPayload = unknown, TState = unknown>(\n condition: (\n ctx: WorkflowContext<TState>,\n hookCtx: HookContext<TPayload>\n ) => boolean | Promise<boolean>,\n hook: Hook<TPayload, TState>\n): Hook<TPayload, TState> {\n return {\n name: `conditional(${hook.name ?? 'anonymous'})`,\n handler: async (ctx, hookCtx) => {\n const shouldRun = await condition(ctx, hookCtx);\n\n if (!shouldRun) {\n return { continue: true };\n }\n\n return hook.handler(ctx, hookCtx);\n },\n };\n}\n","/**\n * Guardrail execution engine.\n *\n * Handles sequential execution of guardrails with durable step-based execution,\n * content/tool modification, and result aggregation.\n *\n * Matches Python sdk/python/polos/middleware/guardrail_executor.py.\n */\n\nimport type { WorkflowContext } from '../core/context.js';\nimport type { ToolCall } from '../types/llm.js';\nimport type { Guardrail, GuardrailContext, GuardrailResultType } from './guardrail.js';\nimport { normalizeGuardrails } from './guardrail.js';\n\n/**\n * Error thrown when a guardrail fails.\n */\nexport class GuardrailError extends Error {\n constructor(\n message: string,\n public readonly guardrailName: string | undefined,\n public override readonly cause?: Error\n ) {\n super(message, { cause });\n this.name = 'GuardrailError';\n }\n}\n\n/**\n * Result from executing a chain of guardrails.\n */\nexport interface GuardrailChainResult {\n /** Whether all guardrails passed */\n success: boolean;\n /** Final content after all modifications */\n content?: string | undefined;\n /** Final tool calls after all modifications */\n toolCalls: ToolCall[];\n /** Error message if a guardrail failed */\n error?: string | undefined;\n /** Name of the guardrail that failed (if any) */\n failedGuardrail?: string | undefined;\n /** Number of guardrails executed */\n guardrailsExecuted: number;\n}\n\n/**\n * Options for guardrail execution.\n */\nexport interface ExecuteGuardrailsOptions {\n /** The workflow context (must have step for durable execution) */\n ctx: WorkflowContext;\n /** Guardrail chain name for durable step key naming (e.g., \"1.guardrail\").\n * Matching Python execute_guardrails guardrail_name parameter. */\n guardrailName: string;\n /** Text content from LLM */\n content?: string | undefined;\n /** Tool calls from LLM */\n toolCalls: ToolCall[];\n}\n\n/**\n * Get a unique identifier for a guardrail.\n * Matching Python _get_guardrail_identifier.\n */\nfunction getGuardrailIdentifier(guardrail: { name?: string | undefined }, index: number): string {\n if (guardrail.name) {\n return guardrail.name;\n }\n return `guardrail_${String(index)}`;\n}\n\n/**\n * Execute a chain of guardrails sequentially with durable execution.\n *\n * Each guardrail is executed via ctx.step.run() for durability — results are\n * cached and replayed on retry. Matching Python execute_guardrails().\n *\n * Guardrails are executed in priority order. If a guardrail returns\n * `continue: false`, execution stops and the error is returned.\n * Content and tool call modifications are accumulated sequentially.\n *\n * @example\n * ```typescript\n * const result = await executeGuardrailChain(\n * [contentFilter, toolValidator],\n * {\n * ctx: workflowContext,\n * guardrailName: '1.guardrail',\n * content: 'LLM response text',\n * toolCalls: [],\n * }\n * );\n *\n * if (!result.success) {\n * throw new Error(result.error);\n * }\n *\n * // Use the potentially modified content/tools\n * const finalContent = result.content;\n * const finalToolCalls = result.toolCalls;\n * ```\n */\nexport async function executeGuardrailChain<TState>(\n guardrails:\n | (\n | Guardrail<TState>\n | ((\n ctx: WorkflowContext<TState>,\n guardrailCtx: GuardrailContext\n ) => Promise<GuardrailResultType>)\n )[]\n | undefined,\n options: ExecuteGuardrailsOptions\n): Promise<GuardrailChainResult> {\n const { ctx, guardrailName } = options;\n const normalizedGuardrails = normalizeGuardrails(guardrails);\n\n let content = options.content;\n let toolCalls = [...options.toolCalls];\n\n if (normalizedGuardrails.length === 0) {\n return {\n success: true,\n content,\n toolCalls,\n guardrailsExecuted: 0,\n };\n }\n\n let guardrailsExecuted = 0;\n\n for (const [index, guardrail] of normalizedGuardrails.entries()) {\n const funcId = getGuardrailIdentifier(guardrail, index);\n\n // Update context with accumulated modifications (matching Python)\n const guardrailCtx: GuardrailContext = {\n content,\n toolCalls,\n messages: [],\n retryCount: 0,\n maxRetries: 0,\n };\n\n try {\n // Execute guardrail durably via step.run (matching Python: ctx.step.run(...))\n const result = await ctx.step.run<GuardrailResultType>(\n `${guardrailName}.${funcId}.${String(index)}`,\n () => guardrail.handler(ctx as WorkflowContext<TState>, guardrailCtx),\n { input: { content, toolCalls } }\n );\n guardrailsExecuted++;\n\n if (!result.continue) {\n return {\n success: false,\n content,\n toolCalls,\n error: result.error ?? 'Guardrail validation failed',\n failedGuardrail: guardrail.name,\n guardrailsExecuted,\n };\n }\n\n // Apply modifications (matching Python)\n if (result.modifiedContent !== undefined) {\n content = result.modifiedContent;\n }\n if (result.modifiedToolCalls !== undefined) {\n toolCalls = result.modifiedToolCalls;\n }\n } catch (err) {\n guardrailsExecuted++;\n const errorMessage = err instanceof Error ? err.message : String(err);\n\n return {\n success: false,\n content,\n toolCalls,\n error: `Guardrail${guardrail.name ? ` '${guardrail.name}'` : ''} threw an error: ${errorMessage}`,\n failedGuardrail: guardrail.name,\n guardrailsExecuted,\n };\n }\n }\n\n return {\n success: true,\n content,\n toolCalls,\n guardrailsExecuted,\n };\n}\n\n/**\n * Execute guardrails and throw if any guardrail fails.\n *\n * Convenience wrapper around `executeGuardrailChain` that throws\n * a `GuardrailError` if any guardrail fails.\n *\n * @returns The result with final content and tool calls\n * @throws GuardrailError if any guardrail fails\n */\nexport async function executeGuardrailsOrThrow<TState>(\n guardrails:\n | (\n | Guardrail<TState>\n | ((\n ctx: WorkflowContext<TState>,\n guardrailCtx: GuardrailContext\n ) => Promise<GuardrailResultType>)\n )[]\n | undefined,\n options: ExecuteGuardrailsOptions\n): Promise<GuardrailChainResult> {\n const result = await executeGuardrailChain(guardrails, options);\n\n if (!result.success) {\n throw new GuardrailError(result.error ?? 'Guardrail execution failed', result.failedGuardrail);\n }\n\n return result;\n}\n\n/**\n * Create a composite guardrail from multiple guardrails.\n *\n * The composite guardrail executes all provided guardrails in sequence\n * (by priority) and returns the combined result.\n *\n * @example\n * ```typescript\n * const allGuardrails = composeGuardrails([\n * contentFilter,\n * toolValidator,\n * formatChecker,\n * ]);\n *\n * const agent = defineAgent({\n * guardrails: [allGuardrails],\n * });\n * ```\n */\nexport function composeGuardrails<TState = unknown>(\n guardrails: Guardrail<TState>[]\n): Guardrail<TState> {\n return {\n name: `composed(${guardrails.map((g) => g.name ?? 'anonymous').join(', ')})`,\n handler: async (ctx, guardrailCtx) => {\n const result = await executeGuardrailChain(guardrails, {\n ctx: ctx as WorkflowContext,\n guardrailName: 'composed',\n content: guardrailCtx.content,\n toolCalls: guardrailCtx.toolCalls,\n });\n\n if (!result.success) {\n return {\n continue: false,\n error: result.error,\n };\n }\n\n return {\n continue: true,\n modifiedContent: result.content,\n modifiedToolCalls: result.toolCalls,\n };\n },\n };\n}\n","/**\n * Durable LLM generation with guardrail support.\n *\n * Matches Python _llm_generate exactly: wraps LLM.generate() in ctx.step.run()\n * for durability and runs guardrails with retry on failure.\n */\n\nimport type { WorkflowContext } from '../core/context.js';\nimport type { CoreMessage } from '../types/llm.js';\nimport { executeGuardrailChain } from '../middleware/guardrail-executor.js';\nimport type { LLM } from './llm.js';\nimport type { LLMGeneratePayload, LLMGenerateResult } from './types.js';\nimport { convertPythonToolCallToMiddleware, convertMiddlewareToolCallToPython } from './types.js';\n\n/**\n * Durable LLM generation with guardrail support.\n *\n * Matches Python _llm_generate exactly:\n * - Step key is `llm_generate:{agent_step}` (same key across retries, matching Python)\n * - Each guardrail is executed as a durable step via ctx.step.run()\n * - On guardrail failure, appends feedback as user message and retries\n * - On guardrail success, applies content/tool_call modifications\n *\n * @example\n * ```typescript\n * const result = await llmGenerate(ctx, llm, {\n * messages: [{ role: 'user', content: 'Hello' }],\n * agent_step: 1,\n * guardrails: [myGuardrail],\n * guardrail_max_retries: 2,\n * });\n * ```\n */\nexport async function llmGenerate(\n ctx: WorkflowContext,\n llm: LLM,\n payload: LLMGeneratePayload\n): Promise<LLMGenerateResult> {\n const {\n agent_step,\n guardrails,\n guardrail_max_retries: maxRetries = 2,\n ...generateOptions\n } = payload;\n\n const workingMessages: CoreMessage[] = [...generateOptions.messages];\n\n // Step key matches Python: `llm_generate:{agent_step}` (no retry count)\n const stepKey = `llm_generate:${String(agent_step)}`;\n\n let guardrailRetryCount = 0;\n\n // Guardrail retry loop (matching Python: while guardrail_retry_count <= guardrail_max_retries)\n while (guardrailRetryCount <= maxRetries) {\n // Build the LLM call options\n const llmCallOptions = {\n ...generateOptions,\n messages: workingMessages,\n };\n\n // Call LLM via step.run() for durable execution\n const response = await ctx.step.run(stepKey, () => llm.generate(llmCallOptions), {\n input: {\n kwargs: {\n messages: workingMessages,\n system: generateOptions.system,\n tools: generateOptions.tools,\n temperature: generateOptions.temperature,\n maxTokens: generateOptions.maxTokens,\n },\n },\n });\n\n // Build result (matching Python llm_result dict)\n const llmResult: LLMGenerateResult = {\n agent_run_id: ctx.executionId,\n status: 'completed',\n content: response.content,\n tool_calls: response.tool_calls,\n usage: response.usage,\n raw_output: response.raw_output,\n model: response.model,\n stop_reason: response.stop_reason,\n };\n\n // If no guardrails, return immediately (matching Python: if not guardrails: return llm_result)\n if (!guardrails || guardrails.length === 0) {\n return llmResult;\n }\n\n // Execute guardrails on the LLM result (matching Python execute_guardrails)\n // Convert tool calls to middleware format\n const middlewareToolCalls = (llmResult.tool_calls ?? []).map(convertPythonToolCallToMiddleware);\n\n // Use the shared executeGuardrailChain (each guardrail runs as a durable step)\n const guardrailChainResult = await executeGuardrailChain(guardrails, {\n ctx,\n guardrailName: `${String(agent_step)}.guardrail`,\n content: llmResult.content ?? undefined,\n toolCalls: middlewareToolCalls,\n });\n\n // Check guardrail result (matching Python: if guardrail_result.action == HookAction.FAIL)\n if (!guardrailChainResult.success) {\n // Guardrail failed - check if we can retry\n const guardrailErrorMessage = guardrailChainResult.error ?? 'Guardrail validation failed';\n\n if (guardrailRetryCount >= maxRetries) {\n // Exhausted retries - raise exception (matching Python)\n throw new Error(\n `Guardrail failed after ${String(maxRetries)} retries. Last error: ${guardrailErrorMessage}`\n );\n }\n\n // Add feedback to messages for retry (matching Python: messages.append({\"role\": \"user\", ...}))\n const feedbackMessage =\n `Previous attempt failed guardrail validation: ${guardrailErrorMessage}. ` +\n `Please revise your response accordingly.`;\n workingMessages.push({ role: 'user', content: feedbackMessage });\n guardrailRetryCount++;\n continue; // Retry LLM generation\n }\n\n // CONTINUE - all guardrails passed, apply accumulated modifications (matching Python)\n // Python always applies modified_content/modified_tool_calls when not None/empty\n if (guardrailChainResult.content !== undefined) {\n llmResult.content = guardrailChainResult.content ?? null;\n }\n // Always apply tool calls from chain result (matching Python: modified_tool_calls is\n // always a list, and `is not None` is always True, so Python always applies).\n // This ensures guardrails that remove tool calls (set to []) are respected.\n const modifiedToolCalls = guardrailChainResult.toolCalls.map(convertMiddlewareToolCallToPython);\n llmResult.tool_calls = modifiedToolCalls.length > 0 ? modifiedToolCalls : null;\n\n return llmResult;\n }\n\n // Should not reach here, but just in case (matching Python)\n throw new Error(`Failed to generate valid response after ${String(maxRetries)} retries`);\n}\n","/**\n * Durable LLM streaming with event publishing.\n *\n * Matches Python _llm_stream: streams LLM output inside ctx.step.run()\n * and publishes events directly (not via durable step execution).\n */\n\nimport type { WorkflowContext } from '../core/context.js';\nimport type { EventData } from '../types/events.js';\nimport type { LLM } from './llm.js';\nimport type { LLMGenerateResult, LLMStreamPayload, LLMToolCall, LLMUsage } from './types.js';\nimport { getModelId } from './types.js';\n\n/**\n * Function signature for publishing events directly (not via step system).\n * Matches Python's `publish_event(client, topic, event_data)` pattern.\n */\nexport type PublishEventFn = (topic: string, eventData: EventData) => Promise<void>;\n\n/**\n * Durable LLM streaming with event publishing.\n *\n * Wraps the streaming operation in ctx.step.run() for durability.\n * Events are published directly via the provided publishEvent function,\n * bypassing the step system (matching Python's direct publish_event calls).\n *\n * @param ctx - Workflow context for durability and metadata\n * @param llm - LLM instance to stream from\n * @param payload - Stream payload with messages, tools, agent_step, etc.\n * @param publishEvent - Function to publish events directly (e.g. from PolosClient or OrchestratorClient)\n *\n * @example\n * ```typescript\n * const result = await llmStream(ctx, llm, {\n * messages: [{ role: 'user', content: 'Tell me a story' }],\n * agent_step: 1,\n * }, async (topic, eventData) => {\n * await client.events.publish(topic, eventData);\n * });\n * ```\n */\nexport async function llmStream(\n ctx: WorkflowContext,\n llm: LLM,\n payload: LLMStreamPayload,\n publishEvent: PublishEventFn\n): Promise<LLMGenerateResult> {\n const { agent_step, ...generateOptions } = payload;\n\n const topic = `workflow/${ctx.rootWorkflowId}/${ctx.rootExecutionId}`;\n const stepKey = `llm_stream:${String(agent_step)}`;\n\n const result = await ctx.step.run(\n stepKey,\n async () => {\n // Publish stream_start event directly (not via step)\n await publishEvent(topic, {\n eventType: 'stream_start',\n data: { step: agent_step },\n });\n\n let accumulatedContent = '';\n const accumulatedToolCalls: LLMToolCall[] = [];\n let finalUsage: LLMUsage = { input_tokens: 0, output_tokens: 0, total_tokens: 0 };\n let finalModel = getModelId(llm.model);\n let finalStopReason: string | null = null;\n let finalRawOutput: unknown[] | null = null;\n let chunkIndex = 0;\n\n for await (const event of llm.stream(generateOptions)) {\n switch (event.type) {\n case 'text_delta': {\n accumulatedContent += event.data.content;\n await publishEvent(topic, {\n eventType: 'text_delta',\n data: {\n step: agent_step,\n chunk_index: chunkIndex,\n content: event.data.content,\n _metadata: {\n execution_id: ctx.executionId,\n workflow_id: ctx.workflowId,\n },\n },\n });\n chunkIndex++;\n break;\n }\n case 'tool_call': {\n accumulatedToolCalls.push(event.data.tool_call);\n await publishEvent(topic, {\n eventType: 'tool_call',\n data: {\n step: agent_step,\n chunk_index: chunkIndex,\n tool_call: event.data.tool_call,\n _metadata: {\n execution_id: ctx.executionId,\n workflow_id: ctx.workflowId,\n },\n },\n });\n chunkIndex++;\n break;\n }\n case 'done': {\n finalUsage = event.data.usage;\n finalModel = event.data.model;\n finalStopReason = event.data.stop_reason;\n finalRawOutput = event.data.raw_output;\n break;\n }\n case 'error': {\n throw new Error(`LLM stream error: ${event.data.error}`);\n }\n }\n }\n\n return {\n content: accumulatedContent || null,\n usage: finalUsage,\n tool_calls: accumulatedToolCalls.length > 0 ? accumulatedToolCalls : null,\n raw_output: finalRawOutput,\n model: finalModel,\n stop_reason: finalStopReason,\n agent_run_id: ctx.executionId,\n status: 'completed',\n } satisfies LLMGenerateResult;\n },\n {\n input: {\n kwargs: {\n messages: generateOptions.messages,\n system: generateOptions.system,\n tools: generateOptions.tools,\n temperature: generateOptions.temperature,\n maxTokens: generateOptions.maxTokens,\n },\n },\n }\n );\n\n return result;\n}\n","/**\n * Stop conditions for agents.\n *\n * Stop conditions allow you to define when an agent should stop executing.\n * Stop conditions execute durably within workflow context using step.run().\n *\n * Matches Python sdk/python/polos/agents/stop_conditions.py.\n */\n\nimport type { LLMToolCall, LLMUsage } from '../llm/types.js';\n\n// ── Types ────────────────────────────────────────────────────────────\n\n/**\n * Information about a tool result within a step.\n * Matches Python ToolResult Pydantic model.\n */\nexport interface ToolResultInfo {\n tool_name?: string | undefined;\n status?: string | undefined;\n result?: unknown;\n result_schema?: string | undefined;\n tool_call_id?: string | undefined;\n tool_call_call_id?: string | undefined;\n}\n\n/**\n * A single step in agent execution.\n * Matches Python Step Pydantic model.\n */\nexport interface StepInfo {\n step: number;\n content: string | null;\n tool_calls: LLMToolCall[];\n tool_results: ToolResultInfo[];\n usage: LLMUsage | null;\n raw_output: unknown;\n}\n\n/**\n * Context available to stop conditions.\n * Matches Python StopConditionContext Pydantic model.\n */\nexport interface StopConditionContext {\n steps: StepInfo[];\n agent_id?: string | undefined;\n agent_run_id?: string | undefined;\n}\n\n/**\n * A stop condition function that receives context and returns whether to stop.\n */\nexport interface StopCondition {\n (ctx: StopConditionContext): boolean | Promise<boolean>;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type -- metadata for identification\n __stop_condition_fn__?: Function | undefined;\n __stop_condition_name__?: string | undefined;\n}\n\n// ── stopCondition decorator ──────────────────────────────────────────\n\n/**\n * Decorator for stop condition functions.\n *\n * Stop conditions take `ctx: StopConditionContext` as the first parameter\n * and optionally a config object as the second parameter.\n * They return a boolean (true to stop, false to continue).\n *\n * When the decorated function has a config parameter, calling it with config\n * returns a configured callable that captures the config.\n *\n * Matches Python @stop_condition decorator.\n *\n * @example\n * ```typescript\n * // Simple stop condition (no config)\n * const alwaysStop = stopCondition(\n * (ctx: StopConditionContext) => true\n * );\n *\n * // With config\n * const maxTokens = stopCondition(\n * (ctx: StopConditionContext, config: { limit: number }) => {\n * const total = ctx.steps.reduce((sum, s) => sum + (s.usage?.total_tokens ?? 0), 0);\n * return total >= config.limit;\n * }\n * );\n * // Use: maxTokens({ limit: 1000 })\n * ```\n */\n/**\n * A stop condition factory — produces StopCondition callables when given config.\n */\nexport interface StopConditionFactory<TConfig> {\n (config: TConfig): StopCondition;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type -- metadata for identification\n __stop_condition_fn__: Function;\n __stop_condition_name__: string;\n}\n\nexport function stopCondition<TConfig>(\n fn: (ctx: StopConditionContext, config: TConfig) => boolean | Promise<boolean>\n): StopConditionFactory<TConfig>;\nexport function stopCondition(\n fn: (ctx: StopConditionContext) => boolean | Promise<boolean>\n): StopCondition;\nexport function stopCondition<TConfig = void>(\n fn: (ctx: StopConditionContext, config?: TConfig) => boolean | Promise<boolean>\n): StopCondition | StopConditionFactory<TConfig> {\n // Check function arity to determine if config is needed\n const hasConfig = fn.length >= 2;\n\n if (hasConfig) {\n // Returns a factory that takes config and returns a configured StopCondition\n const factory: StopConditionFactory<TConfig> = Object.assign(\n (config: TConfig): StopCondition => {\n const configuredFn = Object.assign(\n (ctx: StopConditionContext): boolean | Promise<boolean> => fn(ctx, config),\n {\n __stop_condition_fn__: fn as Function, // eslint-disable-line @typescript-eslint/no-unsafe-function-type\n __stop_condition_name__: fn.name || 'anonymous',\n }\n );\n return configuredFn;\n },\n {\n __stop_condition_fn__: fn as Function, // eslint-disable-line @typescript-eslint/no-unsafe-function-type\n __stop_condition_name__: fn.name || 'anonymous',\n }\n );\n return factory;\n }\n\n // No config — the function itself is the stop condition\n const wrapper: StopCondition = Object.assign(\n (ctx: StopConditionContext): boolean | Promise<boolean> => fn(ctx),\n {\n __stop_condition_fn__: fn as Function, // eslint-disable-line @typescript-eslint/no-unsafe-function-type\n __stop_condition_name__: fn.name || 'anonymous',\n }\n );\n return wrapper;\n}\n\n// ── Built-in stop conditions ─────────────────────────────────────────\n\n/**\n * Stop when total tokens exceed limit.\n * Matches Python max_tokens stop condition.\n *\n * @example\n * ```typescript\n * defineAgent({\n * stopConditions: [maxTokens({ limit: 1000 })],\n * });\n * ```\n */\nexport const maxTokens = stopCondition(function maxTokens(\n ctx: StopConditionContext,\n config: { limit: number }\n): boolean {\n let total = 0;\n for (const step of ctx.steps) {\n if (step.usage) {\n total += step.usage.total_tokens;\n }\n }\n return total >= config.limit;\n});\n\n/**\n * Stop when number of steps reaches count.\n * Matches Python max_steps stop condition.\n *\n * @example\n * ```typescript\n * defineAgent({\n * stopConditions: [maxSteps({ count: 10 })],\n * });\n * // Or with default count of 5:\n * defineAgent({\n * stopConditions: [maxSteps({ count: 5 })],\n * });\n * ```\n */\nexport const maxSteps = stopCondition(function maxSteps(\n ctx: StopConditionContext,\n config: { count: number }\n): boolean {\n return ctx.steps.length >= config.count;\n});\n\n/**\n * Stop when all specified tools have been executed.\n * Matches Python executed_tool stop condition.\n *\n * @example\n * ```typescript\n * defineAgent({\n * stopConditions: [executedTool({ toolNames: ['get_weather', 'search'] })],\n * });\n * ```\n */\nexport const executedTool = stopCondition(function executedTool(\n ctx: StopConditionContext,\n config: { toolNames: string[] }\n): boolean {\n const required = new Set(config.toolNames);\n if (required.size === 0) return false;\n\n const executed = new Set<string>();\n for (const step of ctx.steps) {\n for (const toolCall of step.tool_calls) {\n executed.add(toolCall.function.name);\n }\n }\n\n for (const name of required) {\n if (!executed.has(name)) return false;\n }\n return true;\n});\n\n/**\n * Stop when all specified texts are found in response content.\n * Matches Python has_text stop condition.\n *\n * @example\n * ```typescript\n * defineAgent({\n * stopConditions: [hasText({ texts: ['done', 'complete'] })],\n * });\n * ```\n */\nexport const hasText = stopCondition(function hasText(\n ctx: StopConditionContext,\n config: { texts: string[] }\n): boolean {\n if (config.texts.length === 0) return false;\n\n const combined: string[] = [];\n for (const step of ctx.steps) {\n if (step.content) {\n combined.push(step.content);\n }\n }\n const fullText = combined.join(' ');\n\n return config.texts.every((t) => fullText.includes(t));\n});\n","/**\n * Simple structured logging utility.\n */\n\nimport { appendFileSync } from 'node:fs';\n\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error';\n\nconst LOG_LEVELS: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n};\n\nexport type LogContext = Record<string, unknown>;\n\nexport interface LogEntry {\n level: LogLevel;\n message: string;\n timestamp: string;\n context?: LogContext | undefined;\n}\n\nexport interface LoggerOptions {\n /** Minimum log level to output (default: 'info') */\n level?: LogLevel | undefined;\n /** Logger name/prefix */\n name?: string | undefined;\n /** Custom log handler */\n handler?: ((entry: LogEntry) => void) | undefined;\n}\n\nexport interface ConfigureLoggingOptions {\n /** Custom log handler for all SDK loggers */\n handler?: ((entry: LogEntry) => void) | undefined;\n /** Path to a log file. SDK logs will be appended to this file instead of stdout. */\n file?: string | undefined;\n}\n\n/**\n * Console log handler.\n */\nfunction consoleHandler(entry: LogEntry): void {\n const prefix = `[${entry.timestamp}] ${entry.level.toUpperCase()}`;\n const message = entry.context\n ? `${prefix}: ${entry.message} ${JSON.stringify(entry.context)}`\n : `${prefix}: ${entry.message}`;\n\n switch (entry.level) {\n case 'debug':\n console.debug(message);\n break;\n case 'info':\n console.info(message);\n break;\n case 'warn':\n console.warn(message);\n break;\n case 'error':\n console.error(message);\n break;\n }\n}\n\n/**\n * The active global handler. All SDK loggers created with the default handler\n * delegate to this, so calling `configureLogging()` retroactively redirects them.\n */\nlet _activeHandler: (entry: LogEntry) => void = consoleHandler;\n\n/**\n * Default handler that delegates to the mutable `_activeHandler`.\n * This is the handler captured by module-level loggers at import time.\n */\nfunction defaultHandler(entry: LogEntry): void {\n _activeHandler(entry);\n}\n\n/**\n * Configure logging for all SDK loggers globally.\n *\n * @example\n * ```typescript\n * // Redirect all SDK logs to a file\n * configureLogging({ file: 'polos.log' });\n *\n * // Use a custom handler\n * configureLogging({ handler: (entry) => myLogger.log(entry) });\n * ```\n */\nexport function configureLogging(options: ConfigureLoggingOptions): void {\n if (options.handler) {\n _activeHandler = options.handler;\n } else if (options.file) {\n const filePath = options.file;\n _activeHandler = (entry: LogEntry) => {\n const prefix = `[${entry.timestamp}] ${entry.level.toUpperCase()}`;\n const line = entry.context\n ? `${prefix}: ${entry.message} ${JSON.stringify(entry.context)}\\n`\n : `${prefix}: ${entry.message}\\n`;\n appendFileSync(filePath, line);\n };\n }\n}\n\n/**\n * Create a logger instance.\n *\n * @example\n * ```typescript\n * const logger = createLogger({ name: 'workflow', level: 'debug' });\n * logger.info('Workflow started', { workflowId: '123' });\n * logger.error('Workflow failed', { error: err.message });\n * ```\n */\nexport function createLogger(options: LoggerOptions = {}) {\n const { level = 'info', name, handler = defaultHandler } = options;\n const minLevel = LOG_LEVELS[level];\n\n function log(logLevel: LogLevel, message: string, context?: LogContext): void {\n if (LOG_LEVELS[logLevel] < minLevel) {\n return;\n }\n\n const entry: LogEntry = {\n level: logLevel,\n message: name ? `[${name}] ${message}` : message,\n timestamp: new Date().toISOString(),\n context,\n };\n\n handler(entry);\n }\n\n return {\n debug: (message: string, context?: LogContext) => {\n log('debug', message, context);\n },\n info: (message: string, context?: LogContext) => {\n log('info', message, context);\n },\n warn: (message: string, context?: LogContext) => {\n log('warn', message, context);\n },\n error: (message: string, context?: LogContext) => {\n log('error', message, context);\n },\n\n /** Create a child logger with additional context */\n child: (childOptions: LoggerOptions) => {\n let childName: string | undefined;\n if (name && childOptions.name) {\n childName = `${name}:${childOptions.name}`;\n } else {\n childName = childOptions.name ?? name;\n }\n return createLogger({\n level,\n handler,\n ...childOptions,\n name: childName,\n });\n },\n };\n}\n\nexport type Logger = ReturnType<typeof createLogger>;\n\n/**\n * Global SDK logger instance.\n * Log level can be configured via POLOS_LOG_LEVEL environment variable.\n */\nconst envLogLevel = process.env['POLOS_LOG_LEVEL'];\nexport const logger = createLogger({\n name: 'polos',\n level: (envLogLevel as LogLevel | undefined) ?? 'info',\n});\n","/**\n * Token estimation utilities for session compaction.\n *\n * Uses a simple heuristic: ~4 characters per token.\n */\n\nimport type { ConversationMessage } from '../runtime/orchestrator-types.js';\n\n/**\n * Estimate token count for a string using the ~4 chars/token heuristic.\n */\nexport function estimateTokens(text: string): number {\n return Math.ceil(text.length / 4);\n}\n\n/**\n * Estimate token count for a single conversation message.\n */\nexport function estimateMessageTokens(message: ConversationMessage): number {\n const content = message.content;\n if (typeof content === 'string') {\n return estimateTokens(content);\n }\n try {\n return estimateTokens(JSON.stringify(content));\n } catch {\n return 0;\n }\n}\n\n/**\n * Estimate total token count for an array of conversation messages.\n */\nexport function estimateMessagesTokens(messages: ConversationMessage[]): number {\n let total = 0;\n for (const msg of messages) {\n total += estimateMessageTokens(msg);\n }\n return total;\n}\n","/**\n * Core session compaction logic.\n *\n * Compacts older conversation messages into a rolling summary via an LLM call,\n * keeping the last N recent messages verbatim.\n */\n\nimport { generateText } from 'ai';\nimport type { ConversationMessage } from '../runtime/orchestrator-types.js';\nimport type { NormalizedCompactionConfig, CompactionResult } from './types.js';\nimport { estimateTokens, estimateMessagesTokens } from './tokens.js';\nimport { createLogger } from '../utils/logger.js';\n\nconst logger = createLogger({ name: 'memory-compaction' });\n\n// ── Constants ────────────────────────────────────────────────────────\n\nexport const COMPACTION_PROMPT = `You are summarizing a conversation between a user and an AI assistant.\n\nYour goal: someone reading only this summary should be able to continue the conversation without the user having to repeat themselves.\n\nCapture:\n- What the user is trying to accomplish (their goal, problem, or question)\n- Key facts, context, or constraints the user shared (personal details, preferences, requirements, deadlines)\n- Decisions made or conclusions reached\n- Recommendations given and whether the user accepted, rejected, or is still considering them\n- Any specific artifacts produced (code, files, plans, drafts, lists — include names and key details)\n- Open threads — anything unresolved, in progress, or that the user said they'd come back to\n- The current state of the conversation (where things left off)\n\nExisting summary (if any):\n{existing_summary}\n\nNew messages to fold into the summary:\n{messages_to_fold}\n\nWrite a concise summary in short paragraphs grouped by topic. Not bullet points — narrative that flows.\nBe factual and specific. No pleasantries, no meta-commentary, no \"the user and assistant discussed...\"\nWrite as if taking notes for a colleague who needs to pick up this conversation.`;\n\nexport const SUMMARY_USER_PREFIX = '[Prior conversation summary]\\n';\nexport const SUMMARY_ASSISTANT_ACK = 'Understood, I have context from our earlier conversation.';\n\n// ── Helpers ──────────────────────────────────────────────────────────\n\n/**\n * Build the user/assistant summary pair to inject at the start of conversation.\n */\nexport function buildSummaryMessages(summary: string): [ConversationMessage, ConversationMessage] {\n return [\n { role: 'user', content: SUMMARY_USER_PREFIX + summary },\n { role: 'assistant', content: SUMMARY_ASSISTANT_ACK },\n ];\n}\n\n/**\n * Detect whether messages[index] and messages[index+1] form a summary pair.\n */\nexport function isSummaryPair(messages: ConversationMessage[], index: number): boolean {\n if (index + 1 >= messages.length) return false;\n const userMsg = messages[index];\n const assistantMsg = messages[index + 1];\n if (!userMsg || !assistantMsg) return false;\n if (userMsg.role !== 'user' || assistantMsg.role !== 'assistant') return false;\n const userContent = typeof userMsg.content === 'string' ? userMsg.content : '';\n const assistantContent = typeof assistantMsg.content === 'string' ? assistantMsg.content : '';\n return userContent.startsWith(SUMMARY_USER_PREFIX) && assistantContent === SUMMARY_ASSISTANT_ACK;\n}\n\n/**\n * Format messages as text for inclusion in the compaction prompt.\n */\nfunction formatMessagesForPrompt(messages: ConversationMessage[]): string {\n return messages\n .map((m) => {\n const content = typeof m.content === 'string' ? m.content : JSON.stringify(m.content);\n return `${m.role}: ${content}`;\n })\n .join('\\n\\n');\n}\n\n// ── Main function ────────────────────────────────────────────────────\n\n/**\n * Compact conversation messages if they exceed the token budget.\n *\n * 1. Estimate total tokens of all messages\n * 2. If under maxConversationTokens -> return as-is (no-op)\n * 3. Otherwise:\n * - Find summary pair at start (if present)\n * - Determine messages to fold (between summary pair and last minRecentMessages)\n * - Call compaction model to generate summary\n * - If summary exceeds maxSummaryTokens, re-summarize\n * - Replace folded messages + old summary pair with new summary pair\n * 4. On failure -> log warning, fall back to naive truncation\n */\nexport async function compactIfNeeded(\n messages: ConversationMessage[],\n currentSummary: string | null,\n config: NormalizedCompactionConfig\n): Promise<CompactionResult> {\n const totalTokens = estimateMessagesTokens(messages);\n\n // Under budget — no-op\n if (totalTokens <= config.maxConversationTokens) {\n return {\n compacted: false,\n messages,\n summary: currentSummary,\n summaryTokens: currentSummary ? estimateTokens(currentSummary) : 0,\n totalTurns: messages.length,\n };\n }\n\n // Determine summary pair boundaries\n let summaryPairEnd = 0;\n if (messages.length >= 2 && isSummaryPair(messages, 0)) {\n summaryPairEnd = 2;\n }\n\n // Messages available for folding: everything between summary pair and recent window\n const recentStart = Math.max(summaryPairEnd, messages.length - config.minRecentMessages);\n\n // Nothing to fold\n if (recentStart <= summaryPairEnd) {\n return {\n compacted: false,\n messages,\n summary: currentSummary,\n summaryTokens: currentSummary ? estimateTokens(currentSummary) : 0,\n totalTurns: messages.length,\n };\n }\n\n const messagesToFold = messages.slice(summaryPairEnd, recentStart);\n const recentMessages = messages.slice(recentStart);\n\n // Nothing to fold (e.g., single message)\n if (messagesToFold.length === 0) {\n return {\n compacted: false,\n messages,\n summary: currentSummary,\n summaryTokens: currentSummary ? estimateTokens(currentSummary) : 0,\n totalTurns: messages.length,\n };\n }\n\n try {\n // Build the compaction prompt\n const existingSummary = currentSummary ?? '(none)';\n const foldedText = formatMessagesForPrompt(messagesToFold);\n const prompt = COMPACTION_PROMPT.replace('{existing_summary}', existingSummary).replace(\n '{messages_to_fold}',\n foldedText\n );\n\n // Call compaction model\n let summary = await callCompactionModel(config, prompt);\n\n // Re-summarize if summary is too long\n if (estimateTokens(summary) > config.maxSummaryTokens) {\n const reSummarizePrompt = COMPACTION_PROMPT.replace('{existing_summary}', '(none)').replace(\n '{messages_to_fold}',\n `The following is a summary that needs to be shortened:\\n\\n${summary}`\n );\n summary = await callCompactionModel(config, reSummarizePrompt);\n }\n\n // Build new messages array: [summary pair] + [recent messages]\n const [summaryUser, summaryAssistant] = buildSummaryMessages(summary);\n const newMessages: ConversationMessage[] = [summaryUser, summaryAssistant, ...recentMessages];\n\n return {\n compacted: true,\n messages: newMessages,\n summary,\n summaryTokens: estimateTokens(summary),\n totalTurns: messages.length,\n };\n } catch (err) {\n logger.warn('Compaction failed, falling back to naive truncation', { error: String(err) });\n\n // Fallback: keep last minRecentMessages\n const fallbackMessages = messages.slice(-config.minRecentMessages);\n return {\n compacted: true,\n messages: fallbackMessages,\n summary: currentSummary,\n summaryTokens: currentSummary ? estimateTokens(currentSummary) : 0,\n totalTurns: messages.length,\n };\n }\n}\n\n/**\n * Call the compaction model to generate a summary.\n */\nasync function callCompactionModel(\n config: NormalizedCompactionConfig,\n prompt: string\n): Promise<string> {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n const result = await generateText({\n model: config.compactionModel,\n messages: [{ role: 'user', content: prompt }],\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any);\n return result.text;\n}\n","/**\n * Agent stream function — core execution loop.\n *\n * Matches Python sdk/python/polos/agents/stream.py _agent_stream_function.\n * Orchestrates: LLM call → tool execution → stop condition evaluation → repeat.\n */\n\nimport type { ModelMessage as CoreMessage } from 'ai';\nimport type { WorkflowContext } from '../core/context.js';\nimport { globalRegistry } from '../core/registry.js';\nimport { isToolWorkflow } from '../core/tool.js';\nimport type { BatchWorkflowInput } from '../core/step.js';\nimport { executeHookChain } from '../middleware/hook-executor.js';\nimport { llmGenerate } from '../llm/generate.js';\nimport { llmStream } from '../llm/stream.js';\nimport type { LLM } from '../llm/llm.js';\nimport type { LLMToolCall, LLMUsage, LLMToolResult, LLMGenerateResult } from '../llm/types.js';\nimport { convertToolResultsToMessages } from '../llm/types.js';\nimport type { Guardrail } from '../middleware/guardrail.js';\nimport type { Hook } from '../middleware/hook.js';\nimport type { PublishEventFn } from '../llm/stream.js';\nimport { getExecutionContext } from '../runtime/execution-context.js';\nimport type {\n StopCondition,\n StopConditionContext,\n StepInfo,\n ToolResultInfo,\n} from './stop-conditions.js';\nimport { maxSteps as maxStepsFn } from './stop-conditions.js';\nimport type { LlmToolDefinition } from '../core/tool.js';\nimport { createLogger } from '../utils/logger.js';\nimport type { CompactionConfig, NormalizedCompactionConfig } from '../memory/types.js';\nimport type { ConversationMessage } from '../runtime/orchestrator-types.js';\nimport { compactIfNeeded, buildSummaryMessages, isSummaryPair } from '../memory/compaction.js';\n\nconst logger = createLogger({ name: 'agent-stream' });\n\n// ── Types ────────────────────────────────────────────────────────────\n\n/**\n * Agent configuration passed within the payload.\n * Matches Python agent_config dict structure.\n */\nexport interface AgentStreamConfig {\n system?: string | undefined;\n tools?: LlmToolDefinition[] | undefined;\n temperature?: number | undefined;\n maxOutputTokens?: number | undefined;\n}\n\n/**\n * Payload for agentStreamFunction.\n */\nexport interface AgentStreamPayload {\n agent_run_id: string;\n name: string;\n agent_config: AgentStreamConfig;\n input: string | Record<string, unknown>[];\n streaming: boolean;\n}\n\n/**\n * Definition of an agent for the stream function.\n */\nexport interface AgentDefinition {\n id: string;\n llm: LLM;\n tools: LlmToolDefinition[];\n stopConditions: StopCondition[];\n agentHooks: {\n onAgentStepStart: Hook[];\n onAgentStepEnd: Hook[];\n onToolStart: Hook[];\n onToolEnd: Hook[];\n };\n guardrails: Guardrail[];\n guardrailMaxRetries: number;\n /** Session compaction configuration — always enabled */\n compaction: CompactionConfig;\n outputSchema?: unknown;\n /** Original Zod schema for Vercel AI SDK structured output (Output.object()) */\n outputZodSchema?: unknown;\n}\n\n/**\n * Result from agent execution.\n * Matches Python AgentResult Pydantic model.\n */\nexport interface AgentStreamResult {\n agent_run_id: string;\n result: unknown;\n result_schema: string | null;\n tool_results: ToolResultInfo[];\n total_steps: number;\n usage: LLMUsage;\n}\n\n// ── Helper ───────────────────────────────────────────────────────────\n\nfunction serializeToolOutput(value: unknown): string {\n if (value === null || value === undefined) return 'null';\n if (typeof value === 'string') return value;\n try {\n return JSON.stringify(value);\n } catch {\n return 'null';\n }\n}\n\n// ── Main function ────────────────────────────────────────────────────\n\n/**\n * Core agent execution loop.\n *\n * Matches Python _agent_stream_function:\n * 1. Retrieve conversation history if enabled\n * 2. Build conversation messages\n * 3. Loop: LLM call → tool execution → stop condition check\n * 4. Store conversation history\n * 5. Return AgentResult\n */\nexport async function agentStreamFunction(\n ctx: WorkflowContext,\n payload: AgentStreamPayload,\n agentDef: AgentDefinition\n): Promise<AgentStreamResult> {\n const agentRunId = ctx.executionId;\n const agentConfig = payload.agent_config;\n const streaming = payload.streaming;\n const inputData = payload.input;\n\n // Result accumulator\n let finalInputTokens = 0;\n let finalOutputTokens = 0;\n let finalTotalTokens = 0;\n let finalCacheReadInputTokens = 0;\n let finalCacheCreationInputTokens = 0;\n let lastLlmResultContent: string | null = null;\n const allToolResults: ToolResultInfo[] = [];\n const steps: StepInfo[] = [];\n let endSteps = false;\n let checkedStructuredOutput = false;\n\n // ── Session compaction setup ──────────────────────────────────────\n // Normalize CompactionConfig -> NormalizedCompactionConfig\n let currentSummary: string | null = null;\n\n const normalizedCompaction: NormalizedCompactionConfig = {\n maxConversationTokens: agentDef.compaction.maxConversationTokens ?? 80000,\n maxSummaryTokens: agentDef.compaction.maxSummaryTokens ?? 20000,\n minRecentMessages: agentDef.compaction.minRecentMessages ?? 2,\n compactionModel: agentDef.compaction.compactionModel ?? agentDef.llm.model,\n enabled: agentDef.compaction.enabled ?? true,\n };\n\n // Build conversation messages — load prior session state first, then append current input\n let conversationMessages: unknown[] = [];\n\n // Load session memory (summary + uncompacted messages) if we have a sessionId\n if (ctx.sessionId) {\n const sessionId = ctx.sessionId;\n const loaded = await ctx.step.run('load_session_memory', async () => {\n const execCtx = getExecutionContext();\n if (!execCtx?.orchestratorClient) return null;\n try {\n const sessionMemory = await execCtx.orchestratorClient.getSessionMemory(sessionId);\n return {\n summary: sessionMemory.summary ?? null,\n messages: sessionMemory.messages,\n };\n } catch (err) {\n logger.warn('Failed to retrieve session memory', { error: String(err) });\n return null;\n }\n });\n\n if (loaded) {\n if (loaded.summary) {\n currentSummary = loaded.summary;\n const [summaryUser, summaryAssistant] = buildSummaryMessages(currentSummary);\n conversationMessages.push(summaryUser, summaryAssistant);\n }\n if (loaded.messages.length > 0) {\n conversationMessages.push(...loaded.messages);\n }\n }\n }\n\n // Add current input to conversation\n if (typeof inputData === 'string') {\n conversationMessages.push({ role: 'user', content: inputData });\n } else {\n conversationMessages.push(...inputData);\n }\n\n // Determine safety max_steps limit\n const stopConditions = agentDef.stopConditions;\n\n // Check if any stop condition is from maxSteps (matching Python exactly)\n let hasMaxStepsCondition = false;\n for (const sc of stopConditions) {\n if (sc.__stop_condition_fn__ === maxStepsFn.__stop_condition_fn__) {\n hasMaxStepsCondition = true;\n break;\n }\n }\n\n const safetyMaxSteps: number | null = hasMaxStepsCondition\n ? null\n : parseInt(process.env['POLOS_AGENT_MAX_STEPS'] ?? '20', 10);\n\n // Build publishEvent function for streaming\n const execCtxForPublish = getExecutionContext();\n const publishEvent: PublishEventFn = async (topic, eventData) => {\n if (execCtxForPublish?.orchestratorClient) {\n try {\n await execCtxForPublish.orchestratorClient.publishEvent({\n topic,\n events: [eventData],\n executionId: ctx.executionId,\n rootExecutionId: ctx.rootExecutionId,\n });\n } catch (err) {\n logger.warn('Failed to publish stream event', { error: String(err) });\n }\n }\n };\n\n // Main loop\n let agentStep = 1;\n\n while (!endSteps && (safetyMaxSteps === null || agentStep <= safetyMaxSteps)) {\n const currentIterationToolResults: LLMToolResult[] = [];\n\n // Execute on_agent_step_start hooks\n if (agentDef.agentHooks.onAgentStepStart.length > 0) {\n const hookResult = await executeHookChain(agentDef.agentHooks.onAgentStepStart, {\n ctx,\n hookName: `${String(agentStep)}.hook.on_agent_step_start`,\n payload: { step: agentStep, messages: conversationMessages },\n phase: 'onStart',\n });\n\n // Apply modifications\n if (typeof hookResult.payload === 'object' && 'messages' in hookResult.payload) {\n conversationMessages = (hookResult.payload as { messages: unknown[] }).messages;\n }\n\n if (!hookResult.success) {\n break;\n }\n }\n\n // Run compaction if needed (before LLM call)\n try {\n const compactionResult = await compactIfNeeded(\n conversationMessages as ConversationMessage[],\n currentSummary,\n normalizedCompaction\n );\n if (compactionResult.compacted) {\n conversationMessages = compactionResult.messages;\n currentSummary = compactionResult.summary;\n }\n } catch (err) {\n logger.warn('Compaction failed, continuing with uncompacted messages', {\n error: String(err),\n });\n }\n\n // Get guardrails from agent\n const guardrails = agentDef.guardrails;\n const guardrailMaxRetries = agentDef.guardrailMaxRetries;\n\n // Use llmGenerate if streaming=false OR guardrails are present (matching Python exactly)\n const useLlmGenerate = !streaming || guardrails.length > 0;\n\n let llmResult: LLMGenerateResult;\n\n // Only pass outputSchema when no tools are active (matching Python: response_format + tool use can conflict)\n const hasTools = agentConfig.tools !== undefined && agentConfig.tools.length > 0;\n const outputSchemaForLlm = !hasTools ? agentDef.outputZodSchema : undefined;\n\n if (useLlmGenerate) {\n llmResult = await llmGenerate(ctx, agentDef.llm, {\n messages: conversationMessages as CoreMessage[],\n system: agentConfig.system,\n tools: agentConfig.tools,\n temperature: agentConfig.temperature,\n maxTokens: agentConfig.maxOutputTokens,\n agent_step: agentStep,\n guardrails,\n guardrail_max_retries: guardrailMaxRetries,\n outputSchema: outputSchemaForLlm,\n });\n\n // If guardrails + streaming + content: publish one text_delta event (matching Python)\n if (guardrails.length > 0 && streaming && llmResult.content) {\n await ctx.step.publishEvent(`llm_generate:text_delta:${String(agentStep)}`, {\n topic: `workflow/${ctx.rootWorkflowId}/${ctx.rootExecutionId}`,\n type: 'text_delta',\n data: {\n step: agentStep,\n chunk_index: 1,\n content: llmResult.content,\n _metadata: {\n execution_id: agentRunId,\n workflow_id: ctx.workflowId,\n },\n },\n });\n }\n } else {\n // No guardrails - use streaming\n llmResult = await llmStream(\n ctx,\n agentDef.llm,\n {\n messages: conversationMessages as CoreMessage[],\n system: agentConfig.system,\n tools: agentConfig.tools,\n temperature: agentConfig.temperature,\n maxTokens: agentConfig.maxOutputTokens,\n agent_step: agentStep,\n outputSchema: outputSchemaForLlm,\n },\n publishEvent\n );\n }\n\n // Accumulate usage\n if (llmResult.usage) {\n finalInputTokens += llmResult.usage.input_tokens;\n finalOutputTokens += llmResult.usage.output_tokens;\n finalTotalTokens += llmResult.usage.total_tokens;\n if (llmResult.usage.cache_read_input_tokens != null) {\n finalCacheReadInputTokens += llmResult.usage.cache_read_input_tokens;\n }\n if (llmResult.usage.cache_creation_input_tokens != null) {\n finalCacheCreationInputTokens += llmResult.usage.cache_creation_input_tokens;\n }\n }\n\n lastLlmResultContent = llmResult.content;\n const toolCalls: LLMToolCall[] = llmResult.tool_calls ?? [];\n\n if (!llmResult.raw_output) {\n throw new Error(\n `LLM failed to generate output: agent_id=${agentDef.id}, agent_step=${String(agentStep)}`\n );\n }\n\n conversationMessages.push(...llmResult.raw_output);\n\n // Execute tools in batch\n const batchWorkflows: BatchWorkflowInput[] = [];\n const toolCallList: {\n tool_call_id: string;\n tool_call_call_id: string;\n tool_name: string;\n tool_call: LLMToolCall;\n }[] = [];\n\n let toolResultsRecordedList: ToolResultInfo[] = [];\n\n for (let idx = 0; idx < toolCalls.length; idx++) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- bounds checked by loop\n const toolCall = toolCalls[idx]!;\n\n if (!toolCall.function.name) {\n continue;\n }\n\n const toolName = toolCall.function.name;\n const toolArgsStr = toolCall.function.arguments;\n const toolCallId = toolCall.id;\n const toolCallCallId = toolCall.call_id;\n\n // Find the tool workflow in registry\n if (!globalRegistry.has(toolName)) {\n logger.warn(`Tool '${toolName}' not found in registry`);\n continue;\n }\n\n const toolWorkflow = globalRegistry.get(toolName);\n if (!isToolWorkflow(toolWorkflow)) {\n logger.warn(`Workflow '${toolName}' is not a tool workflow`);\n continue;\n }\n\n // Parse tool arguments\n let toolArgs: unknown;\n try {\n toolArgs = JSON.parse(toolArgsStr) as unknown;\n } catch {\n toolArgs = {};\n }\n\n // Execute on_tool_start hooks\n if (agentDef.agentHooks.onToolStart.length > 0) {\n const hookResult = await executeHookChain(agentDef.agentHooks.onToolStart, {\n ctx,\n hookName: `${String(agentStep)}.hook.on_tool_start.${String(idx)}`,\n payload: toolArgs,\n phase: 'onStart',\n });\n\n // Apply modifications\n if (hookResult.payload !== undefined) {\n toolArgs = hookResult.payload;\n }\n\n if (!hookResult.success) {\n throw new Error(hookResult.error ?? 'on_tool_start hook failed');\n }\n }\n\n // Add to batch\n batchWorkflows.push({ workflow: toolWorkflow, payload: toolArgs });\n toolCallList.push({\n tool_call_id: toolCallId,\n tool_call_call_id: toolCallCallId,\n tool_name: toolName,\n tool_call: toolCall,\n });\n }\n\n // Execute all tools in batch\n if (batchWorkflows.length > 0) {\n const batchResults = await ctx.step.batchInvokeAndWait(\n `execute_tools:step_${String(agentStep)}`,\n batchWorkflows\n );\n\n toolResultsRecordedList = [];\n\n for (let i = 0; i < batchResults.length; i++) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- bounds match batchResults\n const batchToolResult = batchResults[i]!;\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- bounds match batchResults\n const toolSpec = batchWorkflows[i]!;\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- bounds match batchResults\n const toolCallInfo = toolCallList[i]!;\n const toolName = toolCallInfo.tool_name;\n\n // Check success — convert errors to strings for the LLM (matching Python stream.py)\n const toolResult: unknown = batchToolResult.success\n ? batchToolResult.result\n : `Error: ${batchToolResult.error ?? 'unknown error'}`;\n const toolCallId = toolCallInfo.tool_call_id;\n const toolCallCallId = toolCallInfo.tool_call_call_id;\n\n // Execute on_tool_end hooks\n if (agentDef.agentHooks.onToolEnd.length > 0) {\n const hookResult = await executeHookChain(agentDef.agentHooks.onToolEnd, {\n ctx,\n hookName: `${String(agentStep)}.hook.on_tool_end.${String(i)}`,\n payload: toolSpec.payload,\n output: toolResult,\n phase: 'onEnd',\n });\n\n if (!hookResult.success) {\n throw new Error(hookResult.error ?? 'on_tool_end hook failed');\n }\n }\n\n // Serialize and add tool result to conversation for next iteration\n const toolJsonOutput = serializeToolOutput(toolResult);\n\n currentIterationToolResults.push({\n type: 'function_call_output',\n call_id: toolCallCallId,\n name: toolName,\n output: toolJsonOutput,\n });\n\n toolResultsRecordedList.push({\n tool_name: toolName,\n status: 'completed',\n result: toolResult,\n tool_call_id: toolCallId,\n tool_call_call_id: toolCallCallId,\n });\n }\n\n allToolResults.push(...toolResultsRecordedList);\n\n // Add tool results to conversation as role:'tool' messages\n // so the full conversation accumulates naturally\n const toolResultMessages = convertToolResultsToMessages(currentIterationToolResults);\n conversationMessages.push(...toolResultMessages);\n }\n\n // Build step record\n steps.push({\n step: agentStep,\n content: lastLlmResultContent,\n tool_calls: toolCalls,\n tool_results: toolResultsRecordedList,\n usage: llmResult.usage,\n raw_output: conversationMessages,\n });\n\n // Execute on_agent_step_end hooks\n if (agentDef.agentHooks.onAgentStepEnd.length > 0) {\n const hookResult = await executeHookChain(agentDef.agentHooks.onAgentStepEnd, {\n ctx,\n hookName: `${String(agentStep)}.hook.on_agent_step_end`,\n payload: { step: agentStep, messages: conversationMessages },\n output: steps[steps.length - 1],\n phase: 'onEnd',\n });\n\n // Apply modifications\n if (hookResult.output !== undefined) {\n steps[steps.length - 1] = hookResult.output as StepInfo;\n }\n\n if (!hookResult.success) {\n throw new Error(hookResult.error ?? 'on_agent_step_end hook failed');\n }\n }\n\n // No tool results, we're done\n if (currentIterationToolResults.length === 0) {\n endSteps = true;\n }\n\n // Evaluate stop conditions (if any)\n if (stopConditions.length > 0 && !endSteps) {\n const stopCtx: StopConditionContext = {\n steps: [...steps],\n agent_id: agentDef.id,\n agent_run_id: agentRunId,\n };\n\n for (let idx = 0; idx < stopConditions.length; idx++) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- bounds checked by loop\n const condition = stopConditions[idx]!;\n const funcName = condition.__stop_condition_name__ ?? 'unknown';\n\n const shouldStop = await ctx.step.run(\n `${String(agentStep)}.stop_condition.${funcName}.${String(idx)}`,\n () => condition(stopCtx),\n { input: stopCtx }\n );\n\n if (shouldStop) {\n endSteps = true;\n break;\n }\n }\n }\n\n // Structured output parsing (matching Python)\n if (endSteps && agentDef.outputSchema) {\n const parseResult = parseStructuredOutput(lastLlmResultContent, agentDef.outputSchema);\n\n if (checkedStructuredOutput && !parseResult.success) {\n throw new Error(\n `LLM failed to generate valid structured output: agent_id=${agentDef.id}, agent_step=${String(agentStep)}`\n );\n }\n\n checkedStructuredOutput = true;\n\n if (!parseResult.success) {\n // Reset and retry with fix prompt\n endSteps = false;\n\n const schemaJson = JSON.stringify(agentDef.outputSchema, null, 2);\n const fixPrompt =\n `The previous response was not valid JSON matching the ` +\n `required schema. Please reformat your response to be valid ` +\n `JSON that strictly conforms to this schema:\\n\\n${schemaJson}\\n\\n` +\n `Please provide ONLY valid JSON that matches the schema, ` +\n `with no additional text or formatting.`;\n conversationMessages.push({ role: 'user', content: fixPrompt });\n } else {\n lastLlmResultContent = parseResult.parsed as string | null;\n }\n }\n\n if (!endSteps) {\n agentStep++;\n }\n }\n\n // Store session memory (summary + uncompacted messages)\n if (ctx.sessionId) {\n const sessionId = ctx.sessionId;\n const execCtx = getExecutionContext();\n const orchestratorClient = execCtx?.orchestratorClient;\n if (orchestratorClient) {\n try {\n // Strip the summary pair from the front — only store real conversation messages\n const allMessages = conversationMessages as ConversationMessage[];\n const messagesStart = allMessages.length >= 2 && isSummaryPair(allMessages, 0) ? 2 : 0;\n const messagesToStore = allMessages.slice(messagesStart);\n\n const summaryToStore = currentSummary;\n await ctx.step.run(\n 'store_session_memory',\n async () => {\n await orchestratorClient.putSessionMemory(sessionId, {\n summary: summaryToStore,\n messages: messagesToStore,\n });\n },\n {\n input: {\n messageCount: messagesToStore.length,\n },\n }\n );\n } catch (err) {\n logger.warn('Failed to store session memory', { error: String(err) });\n }\n }\n }\n\n // Return AgentResult\n return {\n agent_run_id: agentRunId,\n result: lastLlmResultContent,\n result_schema: null,\n tool_results: allToolResults,\n total_steps: agentStep,\n usage: {\n input_tokens: finalInputTokens,\n output_tokens: finalOutputTokens,\n total_tokens: finalTotalTokens,\n ...(finalCacheReadInputTokens > 0 && { cache_read_input_tokens: finalCacheReadInputTokens }),\n ...(finalCacheCreationInputTokens > 0 && {\n cache_creation_input_tokens: finalCacheCreationInputTokens,\n }),\n },\n };\n}\n\n// ── Structured output parsing ────────────────────────────────────────\n\ninterface ParseResult {\n parsed: unknown;\n success: boolean;\n}\n\n/**\n * Strip markdown code fences (```json ... ``` or ``` ... ```) from LLM output.\n */\nfunction stripCodeFences(text: string): string {\n const trimmed = text.trim();\n // Match ```json ... ``` or ``` ... ``` (with optional language identifier)\n const match = /^```(?:\\w+)?\\s*\\n?([\\s\\S]*?)\\n?\\s*```$/.exec(trimmed);\n return match?.[1] ? match[1].trim() : trimmed;\n}\n\nfunction parseStructuredOutput(output: string | null, outputSchema: unknown): ParseResult {\n if (!output) {\n return { parsed: output, success: true };\n }\n\n try {\n const cleaned = stripCodeFences(output);\n const parsed: unknown = JSON.parse(cleaned);\n // If outputSchema is a Zod schema with parse method, validate\n if (typeof outputSchema === 'object' && outputSchema !== null && 'parse' in outputSchema) {\n const validated: unknown = (outputSchema as { parse: (v: unknown) => unknown }).parse(parsed);\n return { parsed: validated, success: true };\n }\n return { parsed, success: true };\n } catch (e) {\n logger.warn(`Failed to parse structured output: ${String(e)}`);\n return { parsed: output, success: false };\n }\n}\n","/**\n * StreamResult — wraps an ExecutionHandle + PolosClient to provide\n * streaming iteration over agent execution events.\n *\n * Matches Python sdk/python/polos/agents/agent.py StreamResult class.\n */\n\nimport type { ExecutionHandle } from '../execution-handle.js';\nimport type { PolosClient } from '../client.js';\nimport type { StreamEvent } from '../types/events.js';\nimport type { AgentStreamResult } from './stream.js';\n\n/**\n * Result from streaming an agent execution.\n * Provides async iterables for text chunks and full events,\n * plus methods to accumulate text or wait for the final result.\n */\nexport class StreamResult {\n /** Execution ID */\n readonly id: string;\n /** Workflow ID */\n readonly workflowId: string;\n /** When the execution was created */\n readonly createdAt: string | undefined;\n /** Root workflow ID */\n readonly rootWorkflowId: string;\n /** Root execution ID */\n readonly rootExecutionId: string;\n /** Session ID */\n readonly sessionId: string | undefined;\n /** User ID */\n readonly userId: string | undefined;\n /** Agent run ID (same as execution ID) */\n readonly agentRunId: string;\n /** Event topic for this execution */\n readonly topic: string;\n\n private readonly handle: ExecutionHandle;\n private readonly client: PolosClient;\n\n constructor(handle: ExecutionHandle, client: PolosClient) {\n this.handle = handle;\n this.client = client;\n\n this.id = handle.id;\n this.workflowId = handle.workflowId;\n this.createdAt = handle.createdAt;\n this.rootWorkflowId = handle.rootWorkflowId;\n this.rootExecutionId = handle.rootExecutionId;\n this.sessionId = handle.sessionId;\n this.userId = handle.userId;\n\n // Computed fields matching Python\n this.agentRunId = handle.id;\n this.topic = `workflow/${handle.rootWorkflowId}/${handle.rootExecutionId}`;\n }\n\n /**\n * Async iterable of all SSE events from the workflow execution.\n * Matches Python FullEventIterator.\n */\n get events(): AsyncIterable<StreamEvent> {\n const client = this.client;\n const rootWorkflowId = this.rootWorkflowId;\n const rootExecutionId = this.rootExecutionId;\n\n // Use root IDs matching Python StreamResult._stream_events()\n return client.events.streamWorkflow(rootWorkflowId, rootExecutionId);\n }\n\n /**\n * Async iterable of text chunks only (filtering for text_delta events).\n * Matches Python TextChunkIterator.\n */\n get textChunks(): AsyncIterable<string> {\n const events = this.events;\n\n async function* filterTextChunks() {\n for await (const event of events) {\n if (event.eventType === 'text_delta') {\n const content = event.data['content'];\n if (typeof content === 'string' && content.length > 0) {\n yield content;\n }\n }\n }\n }\n\n return filterTextChunks();\n }\n\n /**\n * Accumulate all text chunks into a single string.\n * Matches Python StreamResult.text().\n */\n async text(): Promise<string> {\n let accumulated = '';\n for await (const chunk of this.textChunks) {\n accumulated += chunk;\n }\n return accumulated;\n }\n\n /**\n * Stream events and return the final AgentStreamResult when agent_finish is received.\n * Matches Python StreamResult.result().\n */\n async result(): Promise<AgentStreamResult> {\n const rootExecutionId = this.rootExecutionId;\n\n for await (const event of this.events) {\n if (event.eventType === 'agent_finish') {\n const metadata = event.data['_metadata'];\n if (metadata && typeof metadata === 'object' && !Array.isArray(metadata)) {\n const metadataRecord = metadata as Record<string, unknown>;\n if (metadataRecord['execution_id'] === rootExecutionId) {\n return event.data as unknown as AgentStreamResult;\n }\n }\n }\n }\n\n // If the stream ends without an agent_finish event, fall back to polling\n return (await this.handle.getResult()) as AgentStreamResult;\n }\n\n /**\n * Get the current execution status and details.\n * Delegates to the underlying ExecutionHandle.\n */\n async get() {\n return this.handle.get();\n }\n}\n","/**\n * Agent definition — creates a Workflow with workflowType: 'agent'.\n *\n * Matches Python sdk/python/polos/agents/agent.py Agent class.\n * Follows the defineTool() pattern: defineAgent() creates a Workflow\n * extended with agent-specific properties.\n */\n\nimport type { LanguageModel } from 'ai';\nimport { type ZodType, toJSONSchema } from 'zod';\nimport type { Channel } from '../channels/channel.js';\nimport type { WorkflowContext } from '../core/context.js';\nimport type {\n QueueConfig,\n Workflow,\n WorkflowHandler,\n WorkflowRunClient,\n WorkflowRunOptions,\n} from '../core/workflow.js';\nimport { defineWorkflow } from '../core/workflow.js';\nimport type { ToolWorkflow, LlmToolDefinition } from '../core/tool.js';\nimport { LLM } from '../llm/llm.js';\nimport type { Hook, HookHandler, Hook as HookObject } from '../middleware/hook.js';\nimport { normalizeHooks } from '../middleware/hook.js';\nimport type { Guardrail, GuardrailHandler } from '../middleware/guardrail.js';\nimport { normalizeGuardrails } from '../middleware/guardrail.js';\nimport type { PolosClient } from '../client.js';\nimport { assertNotInExecutionContext } from '../runtime/execution-context.js';\nimport { AgentRunConfig } from '../core/step.js';\nimport type { StopCondition } from './stop-conditions.js';\nimport { agentStreamFunction } from './stream.js';\nimport type { AgentStreamPayload, AgentStreamResult } from './stream.js';\nimport type { CompactionConfig } from '../memory/types.js';\nimport { StreamResult } from './stream-result.js';\n\n// ── Types ────────────────────────────────────────────────────────────\n\n/** Union type for hook inputs — a handler function, Hook object, or array */\ntype HookOrHandler = HookHandler | HookObject | (HookHandler | HookObject)[];\n\n/**\n * Configuration for defineAgent().\n * Matches Python Agent.__init__ parameters.\n */\nexport interface DefineAgentConfig {\n /** Unique agent identifier */\n id: string;\n /** Vercel AI SDK model instance */\n model: LanguageModel;\n /** Agent description */\n description?: string | undefined;\n /** System prompt for the agent */\n systemPrompt?: string | undefined;\n /** Tools available to the agent (from defineTool()) */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n tools?: ToolWorkflow<any, any, any>[] | undefined;\n /** Temperature for LLM generation */\n temperature?: number | undefined;\n /** Maximum output tokens */\n maxOutputTokens?: number | undefined;\n /** Queue assignment for execution */\n queue?: string | QueueConfig | undefined;\n /** Conditions to stop agent execution */\n stopConditions?: StopCondition[] | undefined;\n /** Zod schema for structured output */\n outputSchema?: ZodType | undefined;\n /** Hook(s) to run before workflow execution */\n onStart?: HookOrHandler | undefined;\n /** Hook(s) to run after workflow completion */\n onEnd?: HookOrHandler | undefined;\n /** Hook(s) to run before each agent step */\n onAgentStepStart?: HookOrHandler | undefined;\n /** Hook(s) to run after each agent step */\n onAgentStepEnd?: HookOrHandler | undefined;\n /** Hook(s) to run before tool execution */\n onToolStart?: HookOrHandler | undefined;\n /** Hook(s) to run after tool completion */\n onToolEnd?: HookOrHandler | undefined;\n /** Guardrails for output validation */\n guardrails?: (Guardrail | GuardrailHandler)[] | undefined;\n /** Maximum guardrail retries (default: 2) */\n guardrailMaxRetries?: number | undefined;\n /** Session compaction configuration — always enabled with sensible defaults */\n compaction?: CompactionConfig | undefined;\n /** Publish text_delta and tool_call events to the workflow topic for all invocations */\n streamToWorkflow?: boolean | undefined;\n /** Notification channels for suspend events. Overrides Worker-level channels. */\n channels?: Channel[] | undefined;\n}\n\n/**\n * Payload for agent run() and stream() calls.\n * Contains the agent input and conversation context.\n */\nexport interface AgentRunPayload {\n /** Input for the agent (string message or message array) */\n input: string | Record<string, unknown>[];\n}\n\n/**\n * A Workflow extended with agent-specific properties.\n * Matches the ToolWorkflow pattern.\n */\nexport interface AgentWorkflow extends Workflow {\n /** Agent configuration */\n readonly agentConfig: DefineAgentConfig;\n /** LLM instance */\n readonly llm: LLM;\n /** Tool definitions for the LLM */\n readonly tools: LlmToolDefinition[];\n /** Stop conditions */\n readonly stopConditions: StopCondition[];\n /** Agent-specific hooks */\n readonly agentHooks: {\n onAgentStepStart: Hook[];\n onAgentStepEnd: Hook[];\n onToolStart: Hook[];\n onToolEnd: Hook[];\n };\n /** Guardrails */\n readonly guardrails: Guardrail[];\n\n /**\n * Invoke the agent with streaming, returning a StreamResult for\n * iterating over text chunks and events.\n * Cannot be called from within a workflow — use step.agentInvoke() instead.\n */\n stream(\n client: PolosClient,\n payload: AgentRunPayload,\n options?: WorkflowRunOptions\n ): Promise<StreamResult>;\n\n /**\n * Invoke the agent and wait for the final result.\n * Cannot be called from within a workflow — use step.agentInvokeAndWait() instead.\n */\n run(\n client: WorkflowRunClient,\n payload: AgentRunPayload,\n options?: WorkflowRunOptions\n ): Promise<AgentStreamResult>;\n\n /**\n * Prepare agent for batch execution with all run() params.\n * Returns an AgentRunConfig for use with batchAgentInvoke().\n * Matches Python Agent.with_input().\n */\n withInput(\n input: string | Record<string, unknown>[],\n options?: {\n sessionId?: string;\n userId?: string;\n initialState?: Record<string, unknown>;\n runTimeoutSeconds?: number;\n streaming?: boolean;\n kwargs?: Record<string, unknown>;\n }\n ): AgentRunConfig;\n}\n\n// ── isAgentWorkflow ──────────────────────────────────────────────────\n\n/**\n * Type guard: checks whether a Workflow is an AgentWorkflow.\n */\nexport function isAgentWorkflow(workflow: Workflow): workflow is AgentWorkflow {\n return workflow.config.workflowType === 'agent';\n}\n\n// ── defineAgent ──────────────────────────────────────────────────────\n\n/**\n * Define an agent — a workflow with `workflowType: 'agent'` plus LLM configuration.\n *\n * @example\n * ```typescript\n * import { defineAgent, defineTool, maxSteps } from '@polos/sdk';\n * import { openai } from '@ai-sdk/openai';\n *\n * const searchTool = defineTool({\n * id: 'search',\n * description: 'Search the knowledge base',\n * inputSchema: z.object({ query: z.string() }),\n * }, async (ctx, input) => {\n * return await db.search(input.query);\n * });\n *\n * const myAgent = defineAgent({\n * id: 'my-agent',\n * model: openai('gpt-4o'),\n * systemPrompt: 'You are a helpful assistant.',\n * tools: [searchTool],\n * stopConditions: [maxSteps({ count: 10 })],\n * });\n * ```\n */\nexport function defineAgent(config: DefineAgentConfig): AgentWorkflow {\n // Create LLM instance from model\n const llm = new LLM({ model: config.model });\n\n // Build tool definitions for the LLM\n const toolDefs: LlmToolDefinition[] = (config.tools ?? []).map((t) => t.toLlmToolDefinition());\n\n // Normalize hooks\n const agentHooks = {\n onAgentStepStart: normalizeHooks(config.onAgentStepStart),\n onAgentStepEnd: normalizeHooks(config.onAgentStepEnd),\n onToolStart: normalizeHooks(config.onToolStart),\n onToolEnd: normalizeHooks(config.onToolEnd),\n };\n\n // Normalize guardrails\n const guardrails = normalizeGuardrails(config.guardrails);\n\n // Validate and collect stop conditions\n const stopConditions: StopCondition[] = config.stopConditions ?? [];\n\n // Convert outputSchema to JSON schema if provided\n const outputSchemaJson = config.outputSchema\n ? (() => {\n const { $schema: _, ...rest } = toJSONSchema(config.outputSchema) as Record<\n string,\n unknown\n >;\n return rest;\n })()\n : undefined;\n\n // Create handler closure\n const handler: WorkflowHandler<unknown, unknown, AgentStreamResult> = async (\n ctx: WorkflowContext,\n payload: unknown\n ): Promise<AgentStreamResult> => {\n const p = payload as Record<string, unknown>;\n\n // Extract fields from payload (matching Python _agent_execute)\n const input = p['input'] as string | Record<string, unknown>[];\n const streamingFlag = p['streaming'] as boolean | undefined;\n\n // Build the stream payload\n const streamPayload: AgentStreamPayload = {\n agent_run_id: ctx.executionId,\n name: config.id,\n agent_config: {\n system: config.systemPrompt,\n tools: toolDefs.length > 0 ? toolDefs : undefined,\n temperature: config.temperature,\n maxOutputTokens: config.maxOutputTokens,\n },\n input,\n streaming: streamingFlag ?? config.streamToWorkflow ?? false,\n };\n\n // Call the core agent stream function\n return agentStreamFunction(ctx, streamPayload, {\n id: config.id,\n llm,\n tools: toolDefs,\n stopConditions,\n agentHooks,\n guardrails,\n guardrailMaxRetries: config.guardrailMaxRetries ?? 2,\n compaction: config.compaction ?? {},\n outputSchema: outputSchemaJson,\n outputZodSchema: config.outputSchema,\n });\n };\n\n // Create the underlying workflow\n const workflow = defineWorkflow(\n {\n id: config.id,\n description: config.description,\n workflowType: 'agent',\n queue: config.queue,\n onStart: config.onStart,\n onEnd: config.onEnd,\n channels: config.channels,\n },\n handler as WorkflowHandler<unknown, unknown, unknown>\n );\n\n // Extend with agent-specific fields (following defineTool pattern)\n const agentWorkflow: AgentWorkflow = Object.assign(workflow, {\n agentConfig: config,\n llm,\n tools: toolDefs,\n stopConditions,\n agentHooks,\n guardrails,\n\n async stream(\n client: PolosClient,\n payload: AgentRunPayload,\n options?: WorkflowRunOptions\n ): Promise<StreamResult> {\n assertNotInExecutionContext('agent.stream()', 'step.agentInvoke()');\n\n const orchPayload: Record<string, unknown> = {\n input: payload.input,\n streaming: true,\n };\n\n const invokeOpts: Record<string, unknown> = {};\n if (options?.sessionId !== undefined) invokeOpts['sessionId'] = options.sessionId;\n if (options?.userId !== undefined) invokeOpts['userId'] = options.userId;\n if (options?.initialState !== undefined) invokeOpts['initialState'] = options.initialState;\n if (options?.timeout !== undefined)\n invokeOpts['runTimeoutSeconds'] = Math.ceil(options.timeout);\n\n const handle = await client.invoke(agentWorkflow, orchPayload, invokeOpts);\n\n return new StreamResult(handle, client);\n },\n\n async run(\n client: WorkflowRunClient,\n payload: AgentRunPayload,\n options?: WorkflowRunOptions\n ): Promise<AgentStreamResult> {\n assertNotInExecutionContext('agent.run()', 'step.agentInvokeAndWait()');\n\n const orchPayload: Record<string, unknown> = {\n input: payload.input,\n streaming: false,\n };\n\n const invokeOpts: Record<string, unknown> = {};\n if (options?.sessionId !== undefined) invokeOpts['sessionId'] = options.sessionId;\n if (options?.userId !== undefined) invokeOpts['userId'] = options.userId;\n if (options?.initialState !== undefined) invokeOpts['initialState'] = options.initialState;\n if (options?.timeout !== undefined)\n invokeOpts['runTimeoutSeconds'] = Math.ceil(options.timeout);\n\n const handle = await client.invoke(agentWorkflow.id, orchPayload, invokeOpts);\n\n return (await handle.getResult(options?.timeout ?? 600)) as AgentStreamResult;\n },\n\n withInput(\n input: string | Record<string, unknown>[],\n options?: {\n sessionId?: string;\n userId?: string;\n initialState?: Record<string, unknown>;\n runTimeoutSeconds?: number;\n streaming?: boolean;\n kwargs?: Record<string, unknown>;\n }\n ): AgentRunConfig {\n return new AgentRunConfig({\n agent: agentWorkflow,\n input,\n ...(options?.sessionId !== undefined && { sessionId: options.sessionId }),\n ...(options?.userId !== undefined && { userId: options.userId }),\n ...(options?.streaming !== undefined && { streaming: options.streaming }),\n ...(options?.initialState !== undefined && { initialState: options.initialState }),\n ...(options?.runTimeoutSeconds !== undefined && {\n runTimeoutSeconds: options.runTimeoutSeconds,\n }),\n ...(options?.kwargs !== undefined && { kwargs: options.kwargs }),\n });\n },\n });\n\n return agentWorkflow;\n}\n","/**\n * Fastify server for push-based workers.\n *\n * Handles execution requests from the orchestrator in push mode.\n */\n\nimport Fastify, { type FastifyInstance, type FastifyReply, type FastifyRequest } from 'fastify';\nimport type { ExecuteRequest } from './orchestrator-types.js';\nimport { createLogger } from '../utils/logger.js';\n\nconst logger = createLogger({ name: 'worker-server' });\n\n/**\n * Execution data passed to the work handler.\n */\nexport interface WorkerExecutionData {\n executionId: string;\n workflowId: string;\n deploymentId: string;\n payload: unknown;\n parentExecutionId?: string | undefined;\n rootExecutionId?: string | undefined;\n rootWorkflowId?: string | undefined;\n stepKey?: string | undefined;\n retryCount: number;\n createdAt?: string | undefined;\n sessionId?: string | undefined;\n userId?: string | undefined;\n otelTraceparent?: string | undefined;\n otelSpanId?: string | undefined;\n initialState?: Record<string, unknown> | undefined;\n runTimeoutSeconds?: number | undefined;\n channelContext?: { channelId: string; source: Record<string, unknown> } | undefined;\n}\n\n/**\n * Callback for handling received work.\n */\nexport type OnWorkReceivedCallback = (data: WorkerExecutionData) => Promise<void>;\n\n/**\n * Callback for handling cancel requests.\n * Returns true if execution was found and cancelled, false otherwise.\n */\nexport type OnCancelRequestedCallback = (executionId: string) => Promise<boolean>;\n\n/**\n * Configuration for WorkerServer.\n */\nexport interface WorkerServerConfig {\n /** Worker ID (assigned by orchestrator) */\n workerId: string;\n /** Maximum concurrent workflows */\n maxConcurrentWorkflows: number;\n /** Callback when work is received from orchestrator */\n onWorkReceived: OnWorkReceivedCallback;\n /** Callback when cancel request is received */\n onCancelRequested?: OnCancelRequestedCallback | undefined;\n /** Port to listen on (default: 8000) */\n port?: number | undefined;\n /** Host to bind to (default: '0.0.0.0') */\n host?: string | undefined;\n /** Whether running in local mode (binds to 127.0.0.1) */\n localMode?: boolean | undefined;\n}\n\n/**\n * Fastify server that receives pushed work from the orchestrator.\n */\nexport class WorkerServer {\n private readonly app: FastifyInstance;\n private workerId: string;\n private readonly maxConcurrentWorkflows: number;\n private readonly onWorkReceived: OnWorkReceivedCallback;\n private readonly onCancelRequested: OnCancelRequestedCallback | undefined;\n private readonly port: number;\n private readonly host: string;\n private currentExecutionCount = 0;\n\n constructor(config: WorkerServerConfig) {\n this.workerId = config.workerId;\n this.maxConcurrentWorkflows = config.maxConcurrentWorkflows;\n this.onWorkReceived = config.onWorkReceived;\n this.onCancelRequested = config.onCancelRequested;\n this.port = config.port ?? 8000;\n this.host = config.localMode ? '127.0.0.1' : (config.host ?? '0.0.0.0');\n\n this.app = Fastify({\n logger: false, // We use our own logger\n });\n\n this.setupRoutes();\n }\n\n /**\n * Update the worker ID (used when re-registering).\n */\n updateWorkerId(newWorkerId: string): void {\n this.workerId = newWorkerId;\n }\n\n /**\n * Get current execution count.\n */\n getCurrentExecutionCount(): number {\n return this.currentExecutionCount;\n }\n\n /**\n * Setup Fastify routes.\n */\n private setupRoutes(): void {\n // POST /execute - Receive pushed work from orchestrator\n this.app.post('/execute', async (request: FastifyRequest, reply: FastifyReply) => {\n try {\n // Check if worker is at capacity\n if (this.currentExecutionCount >= this.maxConcurrentWorkflows) {\n return await reply.status(429).send({ error: 'Worker at capacity' });\n }\n\n const body = request.body as ExecuteRequest;\n\n // Validate worker ID\n if (body.worker_id !== this.workerId) {\n return await reply.status(400).send({ error: 'Worker ID mismatch' });\n }\n\n // Extract execution data from flat body (matches orchestrator PushWorkRequest)\n const executionId = body.execution_id;\n const workflowId = body.workflow_id;\n const payload = body.payload;\n\n logger.info(\n `POST /execute - execution_id=${executionId}, worker_id=${this.workerId}, ` +\n `workflow_id=${workflowId}, root_execution_id=${String(body.root_execution_id)}, ` +\n `root_workflow_id=${String(body.root_workflow_id)}, step_key=${String(body.step_key)}, ` +\n `session_id=${String(body.session_id)}, user_id=${String(body.user_id)}, ` +\n `retry_count=${String(body.retry_count)}`\n );\n\n // Build execution data\n const executionData: WorkerExecutionData = {\n executionId,\n workflowId,\n deploymentId: body.deployment_id ?? '',\n payload,\n parentExecutionId: body.parent_execution_id ?? undefined,\n rootExecutionId: body.root_execution_id ?? undefined,\n rootWorkflowId: body.root_workflow_id ?? undefined,\n stepKey: body.step_key ?? undefined,\n retryCount: body.retry_count,\n createdAt: body.created_at ?? undefined,\n sessionId: body.session_id ?? undefined,\n userId: body.user_id ?? undefined,\n otelTraceparent: body.otel_traceparent ?? undefined,\n otelSpanId: body.otel_span_id ?? undefined,\n initialState: body.initial_state ?? undefined,\n runTimeoutSeconds: body.run_timeout_seconds ?? undefined,\n channelContext: body.channel_context\n ? {\n channelId: body.channel_context['channel_id'] as string,\n source: body.channel_context['source'] as Record<string, unknown>,\n }\n : undefined,\n };\n\n // Increment execution count\n this.currentExecutionCount++;\n\n // Execute in background (don't await)\n void this.executeWithCleanup(executionData);\n\n // Return 200 OK immediately (work accepted)\n return await reply.status(200).send({ status: 'accepted', execution_id: executionId });\n } catch (error) {\n logger.error('Error handling /execute', { error: String(error) });\n return await reply.status(503).send({ error: String(error) });\n }\n });\n\n // POST /cancel/:executionId - Handle cancellation request\n this.app.post<{ Params: { executionId: string } }>(\n '/cancel/:executionId',\n async (request: FastifyRequest<{ Params: { executionId: string } }>, reply: FastifyReply) => {\n try {\n const { executionId } = request.params;\n\n // Get worker_id from header\n const workerId = request.headers['x-worker-id'] as string | undefined;\n if (!workerId) {\n return await reply.status(400).send({ error: 'Missing Worker ID in request headers' });\n }\n\n if (workerId !== this.workerId) {\n return await reply.status(400).send({ error: 'Worker ID mismatch' });\n }\n\n logger.info(`POST /cancel/${executionId}`);\n\n // Trigger cancellation\n if (this.onCancelRequested) {\n const found = await this.onCancelRequested(executionId);\n if (found) {\n return await reply.status(200).send({\n status: 'cancellation_requested',\n execution_id: executionId,\n });\n } else {\n return await reply.status(404).send({\n error: 'Execution not found or already completed',\n execution_id: executionId,\n });\n }\n } else {\n return await reply.status(503).send({ error: 'Cancel handler not configured' });\n }\n } catch (error) {\n logger.error('Error handling /cancel', { error: String(error) });\n return await reply.status(500).send({ error: String(error) });\n }\n }\n );\n\n // GET /health - Health check endpoint\n this.app.get('/health', async (_request: FastifyRequest, reply: FastifyReply) => {\n return reply.status(200).send({\n status: 'healthy',\n mode: 'push',\n current_executions: this.currentExecutionCount,\n max_concurrent_workflows: this.maxConcurrentWorkflows,\n });\n });\n }\n\n /**\n * Execute work with cleanup on completion.\n */\n private async executeWithCleanup(executionData: WorkerExecutionData): Promise<void> {\n try {\n await this.onWorkReceived(executionData);\n } catch (error) {\n // Errors are already handled in the callback\n // This just prevents unhandled promise rejection warnings\n logger.debug('Execution completed with error (already handled)', {\n executionId: executionData.executionId,\n error: String(error),\n });\n } finally {\n // Decrement execution count when done\n this.currentExecutionCount = Math.max(0, this.currentExecutionCount - 1);\n }\n }\n\n /**\n * Start the server.\n */\n async start(): Promise<void> {\n try {\n await this.app.listen({ port: this.port, host: this.host });\n logger.info(`Worker server listening on ${this.host}:${String(this.port)}`);\n } catch (error) {\n logger.error('Failed to start worker server', { error: String(error) });\n throw error;\n }\n }\n\n /**\n * Stop the server gracefully.\n */\n async stop(): Promise<void> {\n try {\n await this.app.close();\n logger.info('Worker server stopped');\n } catch (error) {\n logger.error('Error stopping worker server', { error: String(error) });\n }\n }\n}\n","/**\n * JSON serialization utilities with support for special types.\n */\n\n/**\n * Custom replacer for JSON.stringify that handles:\n * - Date objects -> ISO strings\n * - BigInt -> string with 'n' suffix\n * - undefined -> null (when in arrays)\n * - Map -> object with __type marker\n * - Set -> array with __type marker\n */\nexport function jsonReplacer(_key: string, value: unknown): unknown {\n if (value instanceof Date) {\n return { __type: 'Date', value: value.toISOString() };\n }\n if (typeof value === 'bigint') {\n return { __type: 'BigInt', value: value.toString() };\n }\n if (value instanceof Map) {\n return { __type: 'Map', value: Array.from(value.entries()) };\n }\n if (value instanceof Set) {\n return { __type: 'Set', value: Array.from(value) };\n }\n return value;\n}\n\n/**\n * Custom reviver for JSON.parse that restores:\n * - Date objects from ISO strings\n * - BigInt from string\n * - Map from entries\n * - Set from array\n */\nexport function jsonReviver(_key: string, value: unknown): unknown {\n if (value !== null && typeof value === 'object' && '__type' in value) {\n const typed = value as { __type: string; value: unknown };\n switch (typed.__type) {\n case 'Date':\n return new Date(typed.value as string);\n case 'BigInt':\n return BigInt(typed.value as string);\n case 'Map':\n return new Map(typed.value as [unknown, unknown][]);\n case 'Set':\n return new Set(typed.value as unknown[]);\n }\n }\n return value;\n}\n\n/**\n * Serialize a value to JSON string with support for special types.\n */\nexport function serialize(value: unknown): string {\n return JSON.stringify(value, jsonReplacer);\n}\n\n/**\n * Deserialize a JSON string with support for special types.\n */\n// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters -- T is used for return type inference by callers\nexport function deserialize<T = unknown>(json: string): T {\n return JSON.parse(json, jsonReviver) as T;\n}\n\n/**\n * Deep clone a value using JSON serialization.\n * Handles special types like Date, BigInt, Map, Set.\n */\nexport function deepClone<T>(value: T): T {\n return deserialize(serialize(value));\n}\n\n/**\n * Check if a value is JSON-serializable.\n */\nexport function isSerializable(value: unknown): boolean {\n try {\n serialize(value);\n return true;\n } catch {\n return false;\n }\n}\n","/**\n * State management for workflows.\n *\n * Handles state initialization, validation, and serialization using Zod schemas.\n */\n\nimport type { ZodType } from 'zod';\nimport { serialize, deserialize } from '../utils/serializer.js';\n\n/**\n * Maximum state size in bytes (1MB).\n */\nexport const MAX_STATE_SIZE = 1024 * 1024;\n\n/**\n * Error thrown when state validation fails.\n */\nexport class StateValidationError extends Error {\n constructor(\n message: string,\n public readonly issues: unknown[]\n ) {\n const issueDetails = issues\n .map((issue) => {\n if (issue && typeof issue === 'object') {\n const i = issue as Record<string, unknown>;\n const path = Array.isArray(i['path']) ? (i['path'] as unknown[]).join('.') : '';\n const msg = typeof i['message'] === 'string' ? i['message'] : '';\n return path ? `${path}: ${msg}` : msg;\n }\n return String(issue);\n })\n .join('; ');\n super(issueDetails ? `${message}: ${issueDetails}` : message);\n this.name = 'StateValidationError';\n }\n}\n\n/**\n * Error thrown when state exceeds size limit.\n */\nexport class StateSizeError extends Error {\n constructor(\n public readonly size: number,\n public readonly maxSize: number\n ) {\n super(`State size (${String(size)} bytes) exceeds maximum allowed (${String(maxSize)} bytes)`);\n this.name = 'StateSizeError';\n }\n}\n\n/**\n * Initialize state from a Zod schema.\n * Uses schema defaults to create the initial state.\n */\nexport function initializeState<TState>(schema: ZodType<TState>): TState {\n // Parse an empty object to get defaults\n const result = schema.safeParse({});\n\n if (!result.success) {\n // If parsing fails, try with undefined to trigger defaults\n const retryResult = schema.safeParse(undefined);\n if (!retryResult.success) {\n throw new StateValidationError(\n 'Failed to initialize state from schema defaults',\n retryResult.error.issues\n );\n }\n return retryResult.data;\n }\n\n return result.data;\n}\n\n/**\n * Validate state against a Zod schema.\n */\nexport function validateState<TState>(state: unknown, schema: ZodType<TState>): TState {\n const result = schema.safeParse(state);\n\n if (!result.success) {\n throw new StateValidationError('State validation failed', result.error.issues);\n }\n\n return result.data;\n}\n\n/**\n * Serialize state for persistence.\n * Validates size limit before returning.\n */\n// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters -- TState constraint is useful for callers\nexport function serializeState<TState>(state: TState): string {\n const serialized = serialize(state);\n const size = new TextEncoder().encode(serialized).length;\n\n if (size > MAX_STATE_SIZE) {\n throw new StateSizeError(size, MAX_STATE_SIZE);\n }\n\n return serialized;\n}\n\n/**\n * Deserialize state from storage.\n */\nexport function deserializeState<TState>(serialized: string, schema?: ZodType<TState>): TState {\n const state = deserialize<TState>(serialized);\n\n if (schema) {\n return validateState(state, schema);\n }\n\n return state;\n}\n\n/**\n * Merge partial state updates into existing state.\n */\nexport function mergeState<TState extends object>(\n currentState: TState,\n updates: Partial<TState>\n): TState {\n return {\n ...currentState,\n ...updates,\n };\n}\n\n/**\n * Create a deep clone of state.\n */\nexport function cloneState<TState>(state: TState): TState {\n return deserialize(serialize(state));\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context, createContextKey } from '@opentelemetry/api';\n\nconst SUPPRESS_TRACING_KEY = createContextKey(\n 'OpenTelemetry SDK Context Key SUPPRESS_TRACING'\n);\n\nexport function suppressTracing(context: Context): Context {\n return context.setValue(SUPPRESS_TRACING_KEY, true);\n}\n\nexport function unsuppressTracing(context: Context): Context {\n return context.deleteValue(SUPPRESS_TRACING_KEY);\n}\n\nexport function isTracingSuppressed(context: Context): boolean {\n return context.getValue(SUPPRESS_TRACING_KEY) === true;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst VALID_KEY_CHAR_RANGE = '[_0-9a-z-*/]';\nconst VALID_KEY = `[a-z]${VALID_KEY_CHAR_RANGE}{0,255}`;\nconst VALID_VENDOR_KEY = `[a-z0-9]${VALID_KEY_CHAR_RANGE}{0,240}@[a-z]${VALID_KEY_CHAR_RANGE}{0,13}`;\nconst VALID_KEY_REGEX = new RegExp(`^(?:${VALID_KEY}|${VALID_VENDOR_KEY})$`);\nconst VALID_VALUE_BASE_REGEX = /^[ -~]{0,255}[!-~]$/;\nconst INVALID_VALUE_COMMA_EQUAL_REGEX = /,|=/;\n\n/**\n * Key is opaque string up to 256 characters printable. It MUST begin with a\n * lowercase letter, and can only contain lowercase letters a-z, digits 0-9,\n * underscores _, dashes -, asterisks *, and forward slashes /.\n * For multi-tenant vendor scenarios, an at sign (@) can be used to prefix the\n * vendor name. Vendors SHOULD set the tenant ID at the beginning of the key.\n * see https://www.w3.org/TR/trace-context/#key\n */\nexport function validateKey(key: string): boolean {\n return VALID_KEY_REGEX.test(key);\n}\n\n/**\n * Value is opaque string up to 256 characters printable ASCII RFC0020\n * characters (i.e., the range 0x20 to 0x7E) except comma , and =.\n */\nexport function validateValue(value: string): boolean {\n return (\n VALID_VALUE_BASE_REGEX.test(value) &&\n !INVALID_VALUE_COMMA_EQUAL_REGEX.test(value)\n );\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as api from '@opentelemetry/api';\nimport { validateKey, validateValue } from '../internal/validators';\n\nconst MAX_TRACE_STATE_ITEMS = 32;\nconst MAX_TRACE_STATE_LEN = 512;\nconst LIST_MEMBERS_SEPARATOR = ',';\nconst LIST_MEMBER_KEY_VALUE_SPLITTER = '=';\n\n/**\n * TraceState must be a class and not a simple object type because of the spec\n * requirement (https://www.w3.org/TR/trace-context/#tracestate-field).\n *\n * Here is the list of allowed mutations:\n * - New key-value pair should be added into the beginning of the list\n * - The value of any key can be updated. Modified keys MUST be moved to the\n * beginning of the list.\n */\nexport class TraceState implements api.TraceState {\n private _internalState: Map<string, string> = new Map();\n\n constructor(rawTraceState?: string) {\n if (rawTraceState) this._parse(rawTraceState);\n }\n\n set(key: string, value: string): TraceState {\n // TODO: Benchmark the different approaches(map vs list) and\n // use the faster one.\n const traceState = this._clone();\n if (traceState._internalState.has(key)) {\n traceState._internalState.delete(key);\n }\n traceState._internalState.set(key, value);\n return traceState;\n }\n\n unset(key: string): TraceState {\n const traceState = this._clone();\n traceState._internalState.delete(key);\n return traceState;\n }\n\n get(key: string): string | undefined {\n return this._internalState.get(key);\n }\n\n serialize(): string {\n return this._keys()\n .reduce((agg: string[], key) => {\n agg.push(key + LIST_MEMBER_KEY_VALUE_SPLITTER + this.get(key));\n return agg;\n }, [])\n .join(LIST_MEMBERS_SEPARATOR);\n }\n\n private _parse(rawTraceState: string) {\n if (rawTraceState.length > MAX_TRACE_STATE_LEN) return;\n this._internalState = rawTraceState\n .split(LIST_MEMBERS_SEPARATOR)\n .reverse() // Store in reverse so new keys (.set(...)) will be placed at the beginning\n .reduce((agg: Map<string, string>, part: string) => {\n const listMember = part.trim(); // Optional Whitespace (OWS) handling\n const i = listMember.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER);\n if (i !== -1) {\n const key = listMember.slice(0, i);\n const value = listMember.slice(i + 1, part.length);\n if (validateKey(key) && validateValue(value)) {\n agg.set(key, value);\n } else {\n // TODO: Consider to add warning log\n }\n }\n return agg;\n }, new Map());\n\n // Because of the reverse() requirement, trunc must be done after map is created\n if (this._internalState.size > MAX_TRACE_STATE_ITEMS) {\n this._internalState = new Map(\n Array.from(this._internalState.entries())\n .reverse() // Use reverse same as original tracestate parse chain\n .slice(0, MAX_TRACE_STATE_ITEMS)\n );\n }\n }\n\n private _keys(): string[] {\n return Array.from(this._internalState.keys()).reverse();\n }\n\n private _clone(): TraceState {\n const traceState = new TraceState();\n traceState._internalState = new Map(this._internalState);\n return traceState;\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Context,\n isSpanContextValid,\n SpanContext,\n TextMapGetter,\n TextMapPropagator,\n TextMapSetter,\n trace,\n TraceFlags,\n} from '@opentelemetry/api';\nimport { isTracingSuppressed } from './suppress-tracing';\nimport { TraceState } from './TraceState';\n\nexport const TRACE_PARENT_HEADER = 'traceparent';\nexport const TRACE_STATE_HEADER = 'tracestate';\n\nconst VERSION = '00';\nconst VERSION_PART = '(?!ff)[\\\\da-f]{2}';\nconst TRACE_ID_PART = '(?![0]{32})[\\\\da-f]{32}';\nconst PARENT_ID_PART = '(?![0]{16})[\\\\da-f]{16}';\nconst FLAGS_PART = '[\\\\da-f]{2}';\nconst TRACE_PARENT_REGEX = new RegExp(\n `^\\\\s?(${VERSION_PART})-(${TRACE_ID_PART})-(${PARENT_ID_PART})-(${FLAGS_PART})(-.*)?\\\\s?$`\n);\n\n/**\n * Parses information from the [traceparent] span tag and converts it into {@link SpanContext}\n * @param traceParent - A meta property that comes from server.\n * It should be dynamically generated server side to have the server's request trace Id,\n * a parent span Id that was set on the server's request span,\n * and the trace flags to indicate the server's sampling decision\n * (01 = sampled, 00 = not sampled).\n * for example: '{version}-{traceId}-{spanId}-{sampleDecision}'\n * For more information see {@link https://www.w3.org/TR/trace-context/}\n */\nexport function parseTraceParent(traceParent: string): SpanContext | null {\n const match = TRACE_PARENT_REGEX.exec(traceParent);\n if (!match) return null;\n\n // According to the specification the implementation should be compatible\n // with future versions. If there are more parts, we only reject it if it's using version 00\n // See https://www.w3.org/TR/trace-context/#versioning-of-traceparent\n if (match[1] === '00' && match[5]) return null;\n\n return {\n traceId: match[2],\n spanId: match[3],\n traceFlags: parseInt(match[4], 16),\n };\n}\n\n/**\n * Propagates {@link SpanContext} through Trace Context format propagation.\n *\n * Based on the Trace Context specification:\n * https://www.w3.org/TR/trace-context/\n */\nexport class W3CTraceContextPropagator implements TextMapPropagator {\n inject(context: Context, carrier: unknown, setter: TextMapSetter): void {\n const spanContext = trace.getSpanContext(context);\n if (\n !spanContext ||\n isTracingSuppressed(context) ||\n !isSpanContextValid(spanContext)\n )\n return;\n\n const traceParent = `${VERSION}-${spanContext.traceId}-${\n spanContext.spanId\n }-0${Number(spanContext.traceFlags || TraceFlags.NONE).toString(16)}`;\n\n setter.set(carrier, TRACE_PARENT_HEADER, traceParent);\n if (spanContext.traceState) {\n setter.set(\n carrier,\n TRACE_STATE_HEADER,\n spanContext.traceState.serialize()\n );\n }\n }\n\n extract(context: Context, carrier: unknown, getter: TextMapGetter): Context {\n const traceParentHeader = getter.get(carrier, TRACE_PARENT_HEADER);\n if (!traceParentHeader) return context;\n const traceParent = Array.isArray(traceParentHeader)\n ? traceParentHeader[0]\n : traceParentHeader;\n if (typeof traceParent !== 'string') return context;\n const spanContext = parseTraceParent(traceParent);\n if (!spanContext) return context;\n\n spanContext.isRemote = true;\n\n const traceStateHeader = getter.get(carrier, TRACE_STATE_HEADER);\n if (traceStateHeader) {\n // If more than one `tracestate` header is found, we merge them into a\n // single header.\n const state = Array.isArray(traceStateHeader)\n ? traceStateHeader.join(',')\n : traceStateHeader;\n spanContext.traceState = new TraceState(\n typeof state === 'string' ? state : undefined\n );\n }\n return trace.setSpanContext(context, spanContext);\n }\n\n fields(): string[] {\n return [TRACE_PARENT_HEADER, TRACE_STATE_HEADER];\n }\n}\n","/**\n * OpenTelemetry tracing support for Polos workflows.\n */\n\nimport { randomBytes } from 'node:crypto';\nimport {\n type Context,\n type Span,\n type SpanContext,\n type TextMapGetter,\n type TextMapSetter,\n type Tracer,\n SpanStatusCode,\n context,\n trace,\n} from '@opentelemetry/api';\nimport {\n BasicTracerProvider,\n BatchSpanProcessor,\n type IdGenerator,\n type ReadableSpan,\n type SpanExporter,\n} from '@opentelemetry/sdk-trace-base';\nimport { type ExportResult, W3CTraceContextPropagator } from '@opentelemetry/core';\nimport { AsyncLocalStorageContextManager } from '@opentelemetry/context-async-hooks';\nimport { createLogger } from '../utils/logger.js';\n\nconst logger = createLogger({ name: 'tracing' });\n\n// Re-export types that consumers need\nexport { type Span, type SpanContext, type Context, SpanStatusCode };\n\n// ---------------------------------------------------------------------------\n// Module-level state\n// ---------------------------------------------------------------------------\n\nlet _tracerProvider: BasicTracerProvider | undefined;\nlet _tracer: Tracer | undefined;\nlet _propagator: W3CTraceContextPropagator | undefined;\nlet _initialized = false;\n\n// ---------------------------------------------------------------------------\n// Propagator\n// ---------------------------------------------------------------------------\n\n/**\n * Get the W3C trace context propagator (lazy singleton).\n */\nfunction getPropagator(): W3CTraceContextPropagator {\n _propagator ??= new W3CTraceContextPropagator();\n return _propagator;\n}\n\n/**\n * Simple carrier getter for extracting traceparent from a plain object.\n */\nconst mapGetter: TextMapGetter<Record<string, string>> = {\n get(carrier, key) {\n return carrier[key];\n },\n keys(carrier) {\n return Object.keys(carrier);\n },\n};\n\n/**\n * Simple carrier setter for injecting traceparent into a plain object.\n */\nconst mapSetter: TextMapSetter<Record<string, string>> = {\n set(carrier, key, value) {\n carrier[key] = value;\n },\n};\n\n// ---------------------------------------------------------------------------\n// DatabaseSpanExporter\n// ---------------------------------------------------------------------------\n\n/**\n * Configuration for initializing OpenTelemetry.\n */\nexport interface OtelConfig {\n apiUrl: string;\n apiKey: string;\n projectId: string;\n}\n\n/**\n * Custom span exporter that stores spans to the database via the orchestrator API.\n */\nclass DatabaseSpanExporter implements SpanExporter {\n private readonly apiUrl: string;\n private readonly apiKey: string;\n private readonly projectId: string;\n\n constructor(config: OtelConfig) {\n this.apiUrl = config.apiUrl.replace(/\\/$/, '');\n this.apiKey = config.apiKey;\n this.projectId = config.projectId;\n }\n\n export(spans: ReadableSpan[], resultCallback: (result: ExportResult) => void): void {\n if (spans.length === 0) {\n resultCallback({ code: 0 }); // SUCCESS\n return;\n }\n\n const spanDataList = spans.map((span) => this.spanToDict(span));\n const url = `${this.apiUrl}/internal/spans/batch`;\n\n fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.apiKey}`,\n 'X-Project-ID': this.projectId,\n },\n body: JSON.stringify({ spans: spanDataList }),\n })\n .then((response) => {\n if (!response.ok) {\n logger.warn(`Failed to export spans: HTTP ${String(response.status)}`);\n resultCallback({ code: 1 }); // FAILURE\n } else {\n resultCallback({ code: 0 }); // SUCCESS\n }\n })\n .catch((err: unknown) => {\n logger.warn(`Failed to export spans: ${String(err)}`);\n resultCallback({ code: 1 }); // FAILURE\n });\n }\n\n shutdown(): Promise<void> {\n return Promise.resolve();\n }\n\n forceFlush(): Promise<void> {\n return Promise.resolve();\n }\n\n /**\n * Convert a ReadableSpan to the database dict format/\n */\n private spanToDict(span: ReadableSpan): Record<string, unknown> {\n const spanCtx = span.spanContext();\n const traceId = spanCtx.traceId;\n const spanId = spanCtx.spanId;\n\n // Parent span ID\n let parentSpanId: string | null = null;\n if (span.parentSpanId) {\n parentSpanId = span.parentSpanId;\n }\n\n // Extract attributes, separating input/output/error/state\n const attributes: Record<string, string | null> = {};\n let inputData: unknown = null;\n let outputData: unknown = null;\n let initialState: unknown = null;\n let finalState: unknown = null;\n let errorFromAttributes: unknown = null;\n\n for (const [key, value] of Object.entries(span.attributes)) {\n if (INPUT_KEYS.has(key) && value != null) {\n inputData = tryParseJson(value);\n } else if (OUTPUT_KEYS.has(key) && value != null) {\n outputData = tryParseJson(value);\n } else if (ERROR_KEYS.has(key) && value != null) {\n errorFromAttributes = tryParseJson(value);\n } else if (INITIAL_STATE_KEYS.has(key) && value != null) {\n initialState = tryParseJson(value);\n } else if (FINAL_STATE_KEYS.has(key) && value != null) {\n finalState = tryParseJson(value);\n } else {\n attributes[key] = value != null ? String(value) : null;\n }\n }\n\n // Extract events\n const eventsData: Record<string, unknown>[] = [];\n for (const event of span.events) {\n const eventName = event.name;\n const eventTimestamp = formatHrTime(event.time);\n\n const eventAttributes: Record<string, string | null> = {};\n if (event.attributes) {\n for (const [key, value] of Object.entries(event.attributes)) {\n eventAttributes[key] = value != null ? String(value) : null;\n }\n }\n\n eventsData.push({\n name: eventName,\n timestamp: eventTimestamp,\n attributes: Object.keys(eventAttributes).length > 0 ? eventAttributes : null,\n });\n }\n\n // Status and error\n let errorData: unknown = null;\n if (errorFromAttributes) {\n errorData = errorFromAttributes;\n } else if (span.status.code === SpanStatusCode.ERROR) {\n errorData = {\n message: span.status.message ?? 'Unknown error',\n error_type: 'Error',\n };\n }\n\n // Timestamps\n const startedAt = formatHrTime(span.startTime);\n const endedAt = formatHrTime(span.endTime);\n\n // Span type\n let spanType = 'custom';\n const name = span.name;\n if (name.startsWith('workflow.')) {\n spanType = 'workflow';\n } else if (name.startsWith('agent.')) {\n spanType = 'agent';\n } else if (name.startsWith('tool.')) {\n spanType = 'tool';\n } else if (name.startsWith('step.')) {\n spanType = 'step';\n } else if (attributes['span_type']) {\n spanType = attributes['span_type'];\n }\n\n return {\n trace_id: traceId,\n span_id: spanId,\n parent_span_id: parentSpanId,\n name,\n span_type: spanType,\n attributes: Object.keys(attributes).length > 0 ? attributes : null,\n events: eventsData.length > 0 ? eventsData : null,\n input: inputData,\n output: outputData,\n error: errorData,\n initial_state: initialState,\n final_state: finalState,\n started_at: startedAt,\n ended_at: endedAt,\n };\n }\n}\n\n// ---------------------------------------------------------------------------\n// Span attribute key sets\n// ---------------------------------------------------------------------------\n\nconst INPUT_KEYS = new Set([\n 'step.input',\n 'workflow.input',\n 'agent.input',\n 'tool.input',\n 'llm.input',\n]);\nconst OUTPUT_KEYS = new Set([\n 'step.output',\n 'workflow.output',\n 'agent.output',\n 'tool.output',\n 'llm.output',\n]);\nconst ERROR_KEYS = new Set([\n 'step.error',\n 'workflow.error',\n 'agent.error',\n 'tool.error',\n 'llm.error',\n]);\nconst INITIAL_STATE_KEYS = new Set([\n 'workflow.initial_state',\n 'agent.initial_state',\n 'tool.initial_state',\n]);\nconst FINAL_STATE_KEYS = new Set(['workflow.final_state', 'agent.final_state', 'tool.final_state']);\n\nfunction tryParseJson(value: unknown): unknown {\n if (typeof value !== 'string') return null;\n try {\n return JSON.parse(value) as unknown;\n } catch {\n return null;\n }\n}\n\n/**\n * Format OTel HrTime ([seconds, nanoseconds]) to ISO string.\n */\nfunction formatHrTime(hrTime: unknown): string | null {\n if (hrTime == null) return null;\n if (Array.isArray(hrTime) && hrTime.length === 2) {\n const ms = (hrTime[0] as number) * 1000 + (hrTime[1] as number) / 1e6;\n return new Date(ms).toISOString();\n }\n if (typeof hrTime === 'number') {\n if (hrTime > 1e15) {\n return new Date(hrTime / 1e6).toISOString();\n }\n return new Date(hrTime).toISOString();\n }\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// DeterministicTraceIdGenerator\n// ---------------------------------------------------------------------------\n\nconst TRACE_ID_SYMBOL = Symbol.for('polos.trace_id');\n\n/**\n * ID generator that uses deterministic trace IDs from context when available.\n * Falls back to random IDs.\n */\nclass DeterministicTraceIdGenerator implements IdGenerator {\n generateTraceId(): string {\n // Check active OTel context for deterministic trace ID\n try {\n const currentContext = context.active();\n const deterministicId = currentContext.getValue(TRACE_ID_SYMBOL);\n if (typeof deterministicId === 'string') {\n return deterministicId;\n }\n } catch {\n // fall through to random\n }\n return randomHex(32);\n }\n\n generateSpanId(): string {\n return randomHex(16);\n }\n}\n\nfunction randomHex(length: number): string {\n return randomBytes(length / 2).toString('hex');\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Initialize OpenTelemetry with database exporter.\n */\nexport function initializeOtel(config: OtelConfig): void {\n if (_initialized) return;\n\n try {\n // Check if enabled\n if (process.env['POLOS_OTEL_ENABLED']?.toLowerCase() === 'false') {\n logger.info('OpenTelemetry disabled via POLOS_OTEL_ENABLED=false');\n return;\n }\n\n // Create tracer provider with deterministic ID generator and database exporter\n const dbExporter = new DatabaseSpanExporter(config);\n _tracerProvider = new BasicTracerProvider({\n idGenerator: new DeterministicTraceIdGenerator(),\n spanProcessors: [new BatchSpanProcessor(dbExporter)],\n });\n\n // Register as global with AsyncLocalStorage context manager\n // Required for DeterministicTraceIdGenerator to read trace ID from context\n _tracerProvider.register({\n contextManager: new AsyncLocalStorageContextManager(),\n });\n\n // Get tracer\n const serviceName = process.env['POLOS_OTEL_SERVICE_NAME'] ?? 'polos';\n _tracer = trace.getTracer(serviceName);\n _initialized = true;\n\n logger.info('OpenTelemetry initialized with database exporter');\n } catch (e) {\n logger.warn(`Failed to initialize OpenTelemetry: ${String(e)}. Tracing disabled.`);\n _tracer = undefined;\n }\n}\n\n/**\n * Get the tracer instance. Returns undefined if OTel is not initialized.\n */\nexport function getTracer(): Tracer | undefined {\n return _tracer;\n}\n\n/**\n * Flush pending spans and shut down the OpenTelemetry tracer provider.\n *\n * Must be called during worker shutdown before the process exits so that\n * the BatchSpanProcessor exports any remaining spans.\n */\nexport async function shutdownOtel(): Promise<void> {\n if (!_tracerProvider) return;\n\n try {\n await _tracerProvider.forceFlush();\n await _tracerProvider.shutdown();\n } catch (e) {\n logger.warn(`Error during OpenTelemetry shutdown: ${String(e)}`);\n } finally {\n _tracerProvider = undefined;\n _tracer = undefined;\n _initialized = false;\n }\n}\n\n/**\n * Get the current span from OTel context.\n */\nexport function getCurrentSpan(): Span | undefined {\n return trace.getSpan(context.active());\n}\n\n/**\n * Extract traceparent string from a span using W3C propagator.\n */\nexport function extractTraceparent(span: Span): string | undefined {\n try {\n const prop = getPropagator();\n const carrier: Record<string, string> = {};\n\n // Create a context with the span and inject traceparent into carrier\n const ctx = trace.setSpan(context.active(), span);\n prop.inject(ctx, carrier, mapSetter);\n\n return carrier['traceparent'] ?? undefined;\n } catch (e) {\n logger.warn(`Failed to extract traceparent: ${String(e)}`);\n return undefined;\n }\n}\n\n/**\n * Create OTel context from a W3C traceparent string (for sub-workflows).\n */\nexport function createContextFromTraceparent(traceparent: string): Context | undefined {\n if (!traceparent) return undefined;\n\n try {\n const prop = getPropagator();\n const carrier: Record<string, string> = { traceparent };\n const extractedContext = prop.extract(context.active(), carrier, mapGetter);\n\n return extractedContext;\n } catch (e) {\n logger.warn(`Failed to create context from traceparent '${traceparent}': ${String(e)}`);\n return undefined;\n }\n}\n\n/**\n * Create OTel context with a deterministic trace ID (for root workflows).\n * The DeterministicTraceIdGenerator reads this from the context.\n */\nexport function createContextWithTraceId(traceIdHex: string): Context | undefined {\n try {\n const ctx = context.active();\n return ctx.setValue(TRACE_ID_SYMBOL, traceIdHex);\n } catch (e) {\n logger.warn(`Failed to create context with trace ID: ${String(e)}`);\n return undefined;\n }\n}\n\n/**\n * Generate a deterministic trace ID (32-char hex) from a UUID execution ID.\n */\nexport function generateTraceIdFromExecutionId(executionId: string): string {\n const hexStr = executionId.replace(/-/g, '');\n if (hexStr.length !== 32) {\n throw new Error(`Invalid execution_id format: ${executionId}`);\n }\n return hexStr;\n}\n\n/**\n * Format a Date to ISO string.\n */\nexport function formatTimestamp(date: Date): string {\n return date.toISOString();\n}\n\n/**\n * Check if OpenTelemetry has been initialized.\n */\nexport function isOtelAvailable(): boolean {\n return _initialized;\n}\n","/**\n * Span context utilities for ExecutionContextData.\n *\n * Matches Python's utils/tracing.py. Manages the integration between\n * Polos execution context (AsyncLocalStorage) and OTel span contexts.\n */\n\nimport { type Context, type SpanContext, trace, context as otelContext } from '@opentelemetry/api';\nimport type { ExecutionContextData } from '../runtime/execution-context.js';\n\n/**\n * Get parent OTel context from execution context.\n * Wraps the stored SpanContext in a NonRecordingSpan and sets it in an OTel Context,\n * suitable for passing as `context` to `tracer.startSpan(name, opts, context)`.\n */\nexport function getParentSpanContextFromExecutionContext(\n execContext: ExecutionContextData | undefined\n): Context | undefined {\n if (!execContext) return undefined;\n\n const parentSpanContext = execContext._otelSpanContext as SpanContext | undefined;\n if (!parentSpanContext) return undefined;\n\n // Wrap SpanContext in NonRecordingSpan → set in OTel Context\n const parentSpan = trace.wrapSpanContext(parentSpanContext);\n return trace.setSpan(otelContext.active(), parentSpan);\n}\n\n/**\n * Get raw span context from execution context.\n */\nexport function getSpanContextFromExecutionContext(\n execContext: ExecutionContextData | undefined\n): SpanContext | undefined {\n if (!execContext) return undefined;\n return execContext._otelSpanContext as SpanContext | undefined;\n}\n\n/**\n * Store span context in execution context along with formatted trace ID and span ID.\n */\nexport function setSpanContextInExecutionContext(\n execContext: ExecutionContextData | undefined,\n spanContext: SpanContext | undefined\n): void {\n if (!execContext) return;\n\n execContext._otelSpanContext = spanContext;\n if (spanContext != null) {\n execContext._otelTraceId = spanContext.traceId;\n execContext._otelSpanId = spanContext.spanId;\n }\n}\n","/**\n * Workflow executor - handles execution of workflows with proper context setup.\n *\n * The createOrchestratorStepHelper function.\n */\n\nimport { randomUUID } from 'node:crypto';\nimport type { ZodType } from 'zod';\nimport type { Workflow } from '../core/workflow.js';\nimport type { WorkflowContext, AgentContext } from '../core/context.js';\nimport type { AgentWorkflow } from '../agents/agent.js';\nimport type {\n StepHelper,\n StepOptions,\n InvokeOptions,\n WaitForOptions,\n WaitForEventOptions,\n PublishEventOptions,\n SuspendOptions,\n ResumeOptions,\n BatchWorkflowInput,\n BatchStepResult,\n} from '../core/step.js';\nimport type { AgentRunConfig } from '../core/step.js';\nimport { StepExecutionError, WaitError, isWaitError } from '../core/step.js';\nimport type { WorkflowHandle, WorkflowStatus } from '../core/workflow.js';\nimport type { OrchestratorClient } from './orchestrator-client.js';\nimport type { ExecutionContext, StepOutput, BatchWorkflowEntry } from './orchestrator-types.js';\nimport type { Channel, ChannelContext, SuspendNotification } from '../channels/channel.js';\nimport { executeHookChain } from '../middleware/hook-executor.js';\nimport { normalizeHooks } from '../middleware/hook.js';\nimport { initializeState, validateState, serializeState } from '../core/state.js';\nimport { retry, type RetryOptions } from '../utils/retry.js';\nimport { createLogger } from '../utils/logger.js';\nimport { getModelId, getModelProvider } from '../llm/types.js';\nimport { runInExecutionContext, getExecutionContext } from './execution-context.js';\nimport type { SandboxManager } from '../execution/sandbox-manager.js';\nimport {\n type Span,\n type SpanContext,\n type Context,\n context as otelContext,\n trace as otelTrace,\n} from '@opentelemetry/api';\nimport {\n getTracer,\n extractTraceparent,\n createContextFromTraceparent,\n createContextWithTraceId,\n generateTraceIdFromExecutionId,\n} from '../features/tracing.js';\nimport {\n getParentSpanContextFromExecutionContext,\n getSpanContextFromExecutionContext,\n setSpanContextInExecutionContext,\n} from '../utils/tracing.js';\n\nconst logger = createLogger({ name: 'executor' });\n\n/**\n * Options for executing a workflow.\n */\nexport interface ExecuteWorkflowOptions {\n /** The workflow to execute */\n workflow: Workflow;\n /** Payload for the workflow */\n payload: unknown;\n /** Execution context from orchestrator */\n context: ExecutionContext;\n /** Orchestrator client for API calls */\n orchestratorClient: OrchestratorClient;\n /** Worker ID */\n workerId: string;\n /** Abort signal for cancellation */\n abortSignal?: AbortSignal | undefined;\n /** Notification channels for suspend events */\n channels?: Channel[] | undefined;\n /** Sandbox manager for managed sandbox lifecycle */\n sandboxManager?: SandboxManager | undefined;\n /** Originating channel context for bidirectional channels */\n channelContext?: { channelId: string; source: Record<string, unknown> } | undefined;\n}\n\n/**\n * Result of workflow execution.\n */\nexport interface ExecutionResult {\n /** Whether execution succeeded */\n success: boolean;\n /** Result value (if success) */\n // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents -- needed for exactOptionalPropertyTypes\n result?: unknown | undefined;\n /** Error message (if failure) */\n error?: string | undefined;\n /** Stack trace (if failure) */\n stack?: string | undefined;\n /** Whether the error is retryable */\n retryable?: boolean | undefined;\n /** Whether the execution is paused/waiting (WaitError was thrown) */\n waiting?: boolean | undefined;\n /** Final state after execution */\n finalState?: Record<string, unknown> | undefined;\n}\n\n/**\n * Create a WorkflowHandle for a sub-workflow execution.\n */\nfunction createWorkflowHandle<TResult>(\n orchestratorClient: OrchestratorClient,\n executionId: string\n): WorkflowHandle<TResult> {\n return {\n executionId,\n async getStatus(): Promise<WorkflowStatus<TResult>> {\n const exec = await orchestratorClient.getExecution(executionId);\n return {\n status:\n exec.status === 'completed'\n ? 'completed'\n : exec.status === 'failed'\n ? 'failed'\n : exec.status === 'cancelled'\n ? 'cancelled'\n : exec.status === 'running' || exec.status === 'claimed'\n ? 'running'\n : 'queued',\n result: exec.result as TResult | undefined,\n error: exec.error,\n createdAt: new Date(exec.created_at),\n completedAt: exec.completed_at ? new Date(exec.completed_at) : undefined,\n };\n },\n async waitForResult(opts?: { timeout?: number }): Promise<TResult> {\n const waitOptions = opts?.timeout !== undefined ? { timeout: opts.timeout } : undefined;\n const exec = await orchestratorClient.waitForExecution(executionId, waitOptions);\n if (exec.status === 'failed') {\n throw new Error(exec.error ?? 'Workflow execution failed');\n }\n if (exec.status === 'cancelled') {\n throw new Error('Workflow execution cancelled');\n }\n return exec.result as TResult;\n },\n async cancel(): Promise<void> {\n await orchestratorClient.cancelExecution(executionId);\n },\n };\n}\n\n/**\n * Context info passed to the step helper for sub-workflow invocations.\n */\ninterface StepExecutionContext {\n workflowId: string;\n executionId: string;\n deploymentId: string;\n sessionId?: string | undefined;\n userId?: string | undefined;\n rootExecutionId: string;\n rootWorkflowId: string;\n otelTraceparent?: string | undefined;\n}\n\n/**\n * Create a StepHelper backed by the orchestrator.\n */\nfunction createOrchestratorStepHelper(\n orchestratorClient: OrchestratorClient,\n cachedSteps: Map<string, StepOutput>,\n execCtx: StepExecutionContext,\n workerId: string,\n abortSignal?: AbortSignal,\n channels?: Channel[],\n channelContext?: { channelId: string; source: Record<string, unknown> }\n): StepHelper {\n // --- Abort check ---\n const checkAborted = (): void => {\n if (abortSignal?.aborted) {\n throw new Error('Execution cancelled');\n }\n };\n\n /** Check for existing step output. */\n const checkExistingStep = (key: string): StepOutput | undefined => {\n return cachedSteps.get(key);\n };\n\n /** Handle existing step output — return cached result or throw on failure. */\n const handleExistingStep = (existing: StepOutput): unknown => {\n if (existing.success !== false) {\n return existing.outputs;\n }\n const error = existing.error;\n let errorMessage: string;\n if (typeof error === 'object' && error !== null) {\n const msg = (error as Record<string, unknown>)['message'];\n errorMessage = typeof msg === 'string' ? msg : 'Step execution failed';\n } else if (typeof error === 'string') {\n errorMessage = error;\n } else {\n errorMessage = 'Step execution failed';\n }\n throw new StepExecutionError(errorMessage);\n };\n\n /** Save step output on success. */\n const saveStepOutput = async (\n key: string,\n result: unknown,\n sourceExecutionId?: string\n ): Promise<void> => {\n // Cache locally\n cachedSteps.set(key, {\n stepKey: key,\n outputs: result,\n completedAt: new Date().toISOString(),\n success: true,\n });\n\n // Persist to orchestrator\n await orchestratorClient.storeStepOutput(\n execCtx.executionId,\n {\n stepKey: key,\n outputs: result,\n success: true,\n sourceExecutionId,\n },\n workerId\n );\n };\n\n /** Save step output with error. */\n const saveStepOutputWithError = async (key: string, error: string): Promise<void> => {\n cachedSteps.set(key, {\n stepKey: key,\n outputs: undefined,\n completedAt: new Date().toISOString(),\n success: false,\n error: { message: error },\n });\n\n await orchestratorClient.storeStepOutput(\n execCtx.executionId,\n {\n stepKey: key,\n error: { message: error },\n success: false,\n },\n workerId\n );\n };\n\n /** Publish step event fire-and-forget. */\n const publishStepEvent = (\n eventType: string,\n stepKey: string,\n stepType: string,\n inputParams: Record<string, unknown>\n ): void => {\n const topic = `workflow/${execCtx.rootWorkflowId}/${execCtx.rootExecutionId}`;\n orchestratorClient\n .publishEvent({\n topic,\n events: [\n {\n eventType,\n data: {\n step_key: stepKey,\n step_type: stepType,\n data: inputParams,\n _metadata: {\n execution_id: execCtx.executionId,\n workflow_id: execCtx.workflowId,\n },\n },\n },\n ],\n executionId: execCtx.executionId,\n rootExecutionId: execCtx.rootExecutionId,\n })\n .catch((err: unknown) => {\n logger.warn('Failed to publish step event', { error: String(err) });\n });\n };\n\n // --- Shared invoke helper ---\n\n const _invoke = async (\n key: string,\n workflow: string | Workflow,\n payload: unknown,\n options?: InvokeOptions & { waitForSubworkflow?: boolean }\n ): Promise<[unknown, boolean]> => {\n const workflowId = typeof workflow === 'string' ? workflow : workflow.id;\n\n // Check for existing step output\n const existing = checkExistingStep(key);\n if (existing) {\n const result = handleExistingStep(existing);\n return [result, true];\n }\n\n // Invoke workflow via orchestrator\n const response = await orchestratorClient.invokeWorkflow(workflowId, {\n workflowId,\n payload,\n deploymentId: execCtx.deploymentId,\n parentExecutionId: execCtx.executionId,\n rootExecutionId: execCtx.rootExecutionId,\n rootWorkflowId: execCtx.rootWorkflowId,\n sessionId: execCtx.sessionId,\n userId: execCtx.userId,\n stepKey: options?.waitForSubworkflow ? key : undefined,\n concurrencyKey: options?.concurrencyKey,\n queueName: options?.queue,\n otelTraceparent: getCurrentTraceparent(),\n waitForSubworkflow: options?.waitForSubworkflow ?? false,\n initialState: options?.initialState,\n runTimeoutSeconds: options?.runTimeoutSeconds,\n });\n\n if (options?.waitForSubworkflow) {\n // No need to save — orchestrator saves step output on sub-workflow completion\n return [undefined, false];\n } else {\n // Save serializable handle data\n const handleData = {\n id: response.execution_id,\n workflow_id: workflowId,\n created_at: response.created_at,\n parent_execution_id: execCtx.executionId,\n root_workflow_id: execCtx.rootWorkflowId,\n root_execution_id: execCtx.rootExecutionId,\n session_id: execCtx.sessionId,\n user_id: execCtx.userId,\n };\n await saveStepOutput(key, handleData);\n return [handleData, false];\n }\n };\n\n /** Add a span event on the current span from execution context. */\n const addSpanEventFromExecutionContext = (\n eventName: string,\n eventAttributes: Record<string, string>\n ): void => {\n try {\n const activeSpan = otelTrace.getSpan(otelContext.active());\n if (activeSpan) {\n activeSpan.addEvent(eventName, eventAttributes);\n }\n } catch {\n // ignore — no active span\n }\n };\n\n /** Get the current traceparent, preferring the active span's context. */\n const getCurrentTraceparent = (): string | undefined => {\n const currentExecCtx = getExecutionContext();\n if (currentExecCtx?._otelSpanContext) {\n try {\n const currentSpan = otelTrace.wrapSpanContext(\n currentExecCtx._otelSpanContext as SpanContext\n );\n const tp = extractTraceparent(currentSpan);\n if (tp) return tp;\n } catch {\n // fallback\n }\n }\n return execCtx.otelTraceparent;\n };\n\n // --- StepHelper implementation ---\n\n return {\n async run<T>(key: string, fn: () => T | Promise<T>, options?: StepOptions): Promise<T> {\n checkAborted();\n\n const existing = checkExistingStep(key);\n if (existing) {\n return handleExistingStep(existing) as T;\n }\n\n const retryOpts: RetryOptions = {\n maxRetries: options?.maxRetries ?? 2,\n baseDelay: options?.baseDelay ?? 1000,\n maxDelay: options?.maxDelay ?? 10000,\n };\n\n // Publish step_start event\n publishStepEvent('step_start', key, 'run', {\n max_retries: retryOpts.maxRetries ?? 2,\n base_delay: retryOpts.baseDelay ?? 1000,\n max_delay: retryOpts.maxDelay ?? 10000,\n });\n\n // Create step span\n const tracer = getTracer();\n let span: Span | undefined;\n let oldSpanContext: SpanContext | undefined;\n const execContextData = getExecutionContext();\n\n if (tracer) {\n const parentContext = getParentSpanContextFromExecutionContext(execContextData);\n span = tracer.startSpan(\n `step.${key}`,\n {\n attributes: { 'step.key': key, 'step.type': 'run' },\n },\n parentContext\n );\n oldSpanContext = getSpanContextFromExecutionContext(execContextData);\n setSpanContextInExecutionContext(execContextData, span.spanContext());\n\n // Record step input if provided\n if (options?.input !== undefined) {\n try {\n span.setAttribute('step.input', JSON.stringify(options.input));\n } catch {\n /* ignore */\n }\n }\n }\n\n try {\n const result = await retry(fn, retryOpts);\n\n // Publish step_finish event (fire-and-forget)\n publishStepEvent('step_finish', key, 'run', {});\n\n // Save step output on success\n await saveStepOutput(key, result);\n\n if (span) {\n span.setStatus({ code: 1 /* OK */ });\n try {\n span.setAttribute('step.output', JSON.stringify(result));\n } catch {\n /* ignore */\n }\n span.setAttribute('step.status', 'completed');\n }\n\n return result;\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n const errorStack = error instanceof Error ? error.stack : undefined;\n\n logger.error(\n `Step '${key}' failed after ${String(retryOpts.maxRetries)} retries: ${errorMessage}`,\n {\n stepKey: key,\n error: errorMessage,\n stack: errorStack,\n }\n );\n\n if (span) {\n span.setStatus({ code: 2 /* ERROR */, message: errorMessage });\n if (error instanceof Error) {\n span.recordException(error);\n }\n span.setAttribute('step.status', 'failed');\n try {\n span.setAttribute('step.error', JSON.stringify({ message: errorMessage }));\n } catch {\n /* ignore */\n }\n }\n\n // Save error to step output\n await saveStepOutputWithError(key, errorMessage);\n\n throw new StepExecutionError(\n `Step execution failed after ${String(retryOpts.maxRetries)} retries: ${errorMessage}`\n );\n } finally {\n if (span) {\n setSpanContextInExecutionContext(execContextData, oldSpanContext);\n span.end();\n }\n }\n },\n\n async invoke<TPayload, TResult>(\n key: string,\n workflow: string | Workflow<TPayload, unknown, TResult>,\n payload: TPayload,\n options?: InvokeOptions\n ): Promise<WorkflowHandle<TResult>> {\n checkAborted();\n const workflowIdOrStr = typeof workflow === 'string' ? workflow : workflow.id;\n const [result] = await _invoke(key, workflowIdOrStr, payload, {\n ...options,\n waitForSubworkflow: false,\n });\n // result is serializable handle data { id, workflow_id, ... }\n const handleData = result as { id: string };\n return createWorkflowHandle<TResult>(orchestratorClient, handleData.id);\n },\n\n async invokeAndWait<TPayload, TResult>(\n key: string,\n workflow: string | Workflow<TPayload, unknown, TResult>,\n payload: TPayload,\n options?: InvokeOptions\n ): Promise<TResult> {\n checkAborted();\n const workflowId = typeof workflow === 'string' ? workflow : workflow.id;\n const [result, found] = await _invoke(key, workflowId, payload, {\n ...options,\n waitForSubworkflow: true,\n });\n if (found) {\n return result as TResult;\n }\n throw new WaitError(`Waiting for sub-workflow ${workflowId} to complete`, { workflowId });\n },\n\n async batchInvoke(\n key: string,\n items: BatchWorkflowInput[]\n ): Promise<WorkflowHandle<unknown>[]> {\n checkAborted();\n\n if (items.length === 0) return [];\n\n // Check for existing step output\n const existing = checkExistingStep(key);\n if (existing) {\n const cachedData = handleExistingStep(existing) as { id: string }[];\n return cachedData.map((d) => createWorkflowHandle<unknown>(orchestratorClient, d.id));\n }\n\n // Build batch request\n const workflows: BatchWorkflowEntry[] = items.map((item) => {\n const workflowId = typeof item.workflow === 'string' ? item.workflow : item.workflow.id;\n const entry: BatchWorkflowEntry = {\n workflowId,\n payload: item.payload,\n initialState: item.initialState,\n runTimeoutSeconds: item.runTimeoutSeconds,\n };\n // Extract queue info from Workflow config if available\n if (typeof item.workflow !== 'string') {\n const config = item.workflow.config;\n if (typeof config.queue === 'string') {\n entry.queueName = config.queue;\n } else if (config.queue) {\n entry.queueName = config.queue.name;\n entry.queueConcurrencyLimit = config.queue.concurrencyLimit;\n }\n }\n return entry;\n });\n\n const response = await orchestratorClient.batchInvokeWorkflows({\n workflows,\n deploymentId: execCtx.deploymentId,\n parentExecutionId: execCtx.executionId,\n rootExecutionId: execCtx.rootExecutionId,\n rootWorkflowId: execCtx.rootWorkflowId,\n sessionId: execCtx.sessionId,\n userId: execCtx.userId,\n waitForSubworkflow: false,\n otelTraceparent: getCurrentTraceparent(),\n });\n\n // Save serializable handle data\n const handleData = response.executions.map((exec, i) => {\n const item = items[i];\n const wf = item?.workflow;\n const wfId = typeof wf === 'string' ? wf : wf?.id;\n return {\n id: exec.execution_id,\n workflow_id: wfId,\n created_at: exec.created_at,\n parent_execution_id: execCtx.executionId,\n root_workflow_id: execCtx.rootWorkflowId,\n root_execution_id: execCtx.rootExecutionId,\n session_id: execCtx.sessionId,\n user_id: execCtx.userId,\n };\n });\n\n await saveStepOutput(key, handleData);\n return handleData.map((d) => createWorkflowHandle<unknown>(orchestratorClient, d.id));\n },\n\n async batchInvokeAndWait<T>(\n key: string,\n items: BatchWorkflowInput[]\n ): Promise<BatchStepResult<T>[]> {\n checkAborted();\n\n if (items.length === 0) return [];\n\n // Check for existing step output (matching Python batch_invoke_and_wait:\n // try handleExistingStep, fall back to raw outputs on error — because\n // the step-level success may be false when sub-workflows fail, even\n // though individual items carry their own success/error fields).\n const existing = checkExistingStep(key);\n if (existing) {\n let raw: unknown;\n try {\n raw = handleExistingStep(existing);\n } catch {\n raw = existing.outputs;\n }\n\n // The orchestrator stores batch results as [{workflow_id, success, result, error}, ...].\n // Preserve the wrapper (matching Python BatchStepResult) so callers can check success/error.\n if (Array.isArray(raw)) {\n return raw.map((item: unknown): BatchStepResult<T> => {\n if (item && typeof item === 'object' && 'success' in item) {\n const rec = item as Record<string, unknown>;\n return {\n workflowId: typeof rec['workflow_id'] === 'string' ? rec['workflow_id'] : '',\n success: rec['success'] === true,\n result: (rec['result'] ?? null) as T | null,\n error: typeof rec['error'] === 'string' ? rec['error'] : null,\n };\n }\n // Fallback: treat raw item as a successful result\n return { workflowId: '', success: true, result: item as T, error: null };\n });\n }\n return (raw as T[]).map((r) => ({ workflowId: '', success: true, result: r, error: null }));\n }\n\n // Build batch request with waitForSubworkflow=true\n const workflows: BatchWorkflowEntry[] = items.map((item) => {\n const workflowId = typeof item.workflow === 'string' ? item.workflow : item.workflow.id;\n const entry: BatchWorkflowEntry = {\n workflowId,\n payload: item.payload,\n initialState: item.initialState,\n runTimeoutSeconds: item.runTimeoutSeconds,\n };\n if (typeof item.workflow !== 'string') {\n const config = item.workflow.config;\n if (typeof config.queue === 'string') {\n entry.queueName = config.queue;\n } else if (config.queue) {\n entry.queueName = config.queue.name;\n entry.queueConcurrencyLimit = config.queue.concurrencyLimit;\n }\n }\n return entry;\n });\n\n await orchestratorClient.batchInvokeWorkflows({\n workflows,\n deploymentId: execCtx.deploymentId,\n parentExecutionId: execCtx.executionId,\n rootExecutionId: execCtx.rootExecutionId,\n rootWorkflowId: execCtx.rootWorkflowId,\n stepKey: key,\n sessionId: execCtx.sessionId,\n userId: execCtx.userId,\n waitForSubworkflow: true,\n otelTraceparent: getCurrentTraceparent(),\n });\n\n // Pause execution — orchestrator resumes when all sub-workflows complete\n const workflowIds = items\n .map((item) => (typeof item.workflow === 'string' ? item.workflow : item.workflow.id))\n .join(', ');\n throw new WaitError(`Waiting for sub-workflows [${workflowIds}] to complete`, {\n workflowIds: workflowIds.split(', '),\n });\n },\n\n async waitFor(key: string, options: WaitForOptions): Promise<void> {\n checkAborted();\n\n const existing = checkExistingStep(key);\n if (existing) {\n handleExistingStep(existing);\n return;\n }\n\n // Calculate total wait seconds\n let totalSeconds = 0;\n if (options.seconds) totalSeconds += options.seconds;\n if (options.minutes) totalSeconds += options.minutes * 60;\n if (options.hours) totalSeconds += options.hours * 3600;\n if (options.days) totalSeconds += options.days * 86400;\n if (options.weeks) totalSeconds += options.weeks * 604800;\n\n if (totalSeconds <= 0) {\n await saveStepOutputWithError(key, 'Wait duration must be positive');\n throw new StepExecutionError('Wait duration must be positive');\n }\n\n const waitUntil = new Date(Date.now() + totalSeconds * 1000);\n\n // Add span event\n addSpanEventFromExecutionContext('step.wait_for', {\n 'step.key': key,\n 'wait.seconds': String(totalSeconds),\n 'wait.until': waitUntil.toISOString(),\n });\n\n // Get wait threshold\n const waitThreshold = Number(process.env['POLOS_WAIT_THRESHOLD_SECONDS'] ?? '10');\n\n if (totalSeconds <= waitThreshold) {\n // Short wait — sleep locally\n await new Promise((resolve) => setTimeout(resolve, totalSeconds * 1000));\n await saveStepOutput(key, { wait_until: waitUntil.toISOString() });\n return;\n }\n\n // Long wait — pause execution via orchestrator\n await orchestratorClient.setWaiting(\n execCtx.executionId,\n {\n stepKey: key,\n waitType: 'time',\n waitUntil: waitUntil.toISOString(),\n },\n workerId\n );\n\n throw new WaitError(`Waiting until ${waitUntil.toISOString()}`, {\n waitUntil: waitUntil.toISOString(),\n });\n },\n\n async waitUntil(key: string, date: Date): Promise<void> {\n checkAborted();\n\n const existing = checkExistingStep(key);\n if (existing) {\n handleExistingStep(existing);\n return;\n }\n\n const now = Date.now();\n const waitSeconds = (date.getTime() - now) / 1000;\n\n if (waitSeconds < 0) {\n await saveStepOutputWithError(key, `Wait date ${date.toISOString()} is in the past`);\n throw new StepExecutionError(`Wait date ${date.toISOString()} is in the past`);\n }\n\n // Add span event\n addSpanEventFromExecutionContext('step.wait_until', {\n 'step.key': key,\n 'wait.until': date.toISOString(),\n });\n\n const waitThreshold = Number(process.env['POLOS_WAIT_THRESHOLD_SECONDS'] ?? '10');\n\n if (waitSeconds <= waitThreshold) {\n // Short wait — sleep locally\n await new Promise((resolve) => setTimeout(resolve, waitSeconds * 1000));\n await saveStepOutput(key, { wait_until: date.toISOString() });\n return;\n }\n\n // Long wait — pause execution via orchestrator\n await orchestratorClient.setWaiting(\n execCtx.executionId,\n {\n stepKey: key,\n waitType: 'time',\n waitUntil: date.toISOString(),\n },\n workerId\n );\n\n throw new WaitError(`Waiting until ${date.toISOString()}`, { waitUntil: date.toISOString() });\n },\n\n async waitForEvent<T>(key: string, options: WaitForEventOptions): Promise<T> {\n checkAborted();\n\n const existing = checkExistingStep(key);\n if (existing) {\n return handleExistingStep(existing) as T;\n }\n\n // Add span event\n const eventAttrs: Record<string, string> = {\n 'step.key': key,\n 'wait.topic': options.topic,\n };\n if (options.timeout !== undefined) {\n eventAttrs['wait.timeout_seconds'] = String(options.timeout);\n }\n addSpanEventFromExecutionContext('step.wait_for_event', eventAttrs);\n\n // Calculate expires_at if timeout provided (timeout is in seconds)\n const expiresAt =\n options.timeout !== undefined\n ? new Date(Date.now() + options.timeout * 1000).toISOString()\n : undefined;\n\n // Set waiting state\n await orchestratorClient.setWaiting(\n execCtx.executionId,\n {\n stepKey: key,\n waitType: 'event',\n waitTopic: options.topic,\n waitUntil: expiresAt,\n expiresAt,\n },\n workerId\n );\n\n throw new WaitError(`Waiting for event on topic: ${options.topic}`, { topic: options.topic });\n },\n\n async publishEvent(key: string, options: PublishEventOptions): Promise<void> {\n checkAborted();\n\n const existing = checkExistingStep(key);\n if (existing) {\n handleExistingStep(existing);\n return;\n }\n\n await orchestratorClient.publishEvent({\n topic: options.topic,\n events: [\n {\n eventType: options.type,\n data: options.data,\n },\n ],\n executionId: execCtx.executionId,\n rootExecutionId: execCtx.rootExecutionId,\n });\n\n // Save with null result\n await saveStepOutput(key, null);\n },\n\n async publishWorkflowEvent(\n key: string,\n options: { data: unknown; type?: string }\n ): Promise<void> {\n const topic = `workflow/${execCtx.rootWorkflowId}/${execCtx.rootExecutionId}`;\n // Delegate to publishEvent\n return this.publishEvent(key, { topic, ...options });\n },\n\n async suspend<T, R>(key: string, options?: SuspendOptions<T>): Promise<R> {\n checkAborted();\n\n const existing = checkExistingStep(key);\n if (existing) {\n return handleExistingStep(existing) as R;\n }\n\n // Publish suspend event on workflow topic\n const topic = `workflow/${execCtx.rootWorkflowId}/${execCtx.rootExecutionId}`;\n const approvalUrl = `${orchestratorClient.getApiUrl()}/approve/${execCtx.rootExecutionId}/${key}`;\n const eventData =\n options?.data != null && typeof options.data === 'object' && !Array.isArray(options.data)\n ? { ...(options.data as Record<string, unknown>), _approval_url: approvalUrl }\n : { _original: options?.data, _approval_url: approvalUrl };\n await orchestratorClient.publishEvent({\n topic,\n events: [\n {\n eventType: `suspend_${key}`,\n data: eventData,\n },\n ],\n executionId: execCtx.executionId,\n rootExecutionId: execCtx.rootExecutionId,\n });\n\n // Calculate expires_at (timeout is in seconds)\n const expiresAt =\n options?.timeout !== undefined\n ? new Date(Date.now() + options.timeout * 1000).toISOString()\n : undefined;\n\n // Set waiting state\n await orchestratorClient.setWaiting(\n execCtx.executionId,\n {\n stepKey: key,\n waitType: 'suspend',\n waitTopic: topic,\n waitUntil: expiresAt,\n expiresAt,\n },\n workerId\n );\n\n // Notify channels — after state is persisted, before pausing execution\n if (channels?.length) {\n const eventRecord = eventData as Record<string, unknown>;\n const formData = eventRecord['_form'] as Record<string, unknown> | undefined;\n const notifyConfig = eventRecord['_notify'] as Record<string, unknown> | undefined;\n\n const titleVal = formData?.['title'] as string | undefined;\n const notifyMessage = notifyConfig?.['message'] as string | undefined;\n const formDescription = formData?.['description'] as string | undefined;\n const descriptionVal = notifyMessage ?? formDescription;\n const sourceVal = eventRecord['_source'] as string | undefined;\n const toolVal = eventRecord['_tool'] as string | undefined;\n const contextVal = formData?.['context'] as Record<string, unknown> | undefined;\n const formFieldsVal = formData?.['fields'] as Record<string, unknown>[] | undefined;\n const expiresAtVal = (formData?.['expiresAt'] ?? formData?.['expires_at']) as\n | string\n | undefined;\n\n const notification: SuspendNotification = {\n workflowId: execCtx.rootWorkflowId,\n executionId: execCtx.rootExecutionId,\n stepKey: key,\n approvalUrl,\n };\n if (titleVal !== undefined) notification.title = titleVal;\n if (descriptionVal !== undefined) notification.description = descriptionVal;\n if (sourceVal !== undefined) notification.source = sourceVal;\n if (toolVal !== undefined) notification.tool = toolVal;\n if (contextVal !== undefined) notification.context = contextVal;\n if (formFieldsVal !== undefined) notification.formFields = formFieldsVal;\n if (expiresAtVal !== undefined) notification.expiresAt = expiresAtVal;\n if (channelContext !== undefined) {\n notification.channelContext = channelContext as ChannelContext;\n }\n\n // Fire all notifications concurrently — failures logged, never block suspend\n await Promise.allSettled(\n channels.map(async (ch) => {\n try {\n // Per-channel overrides: merge _notify.[channelId] overrides\n // + inject channelContext.source for matching channel\n let overrides = notifyConfig?.[ch.id] as Record<string, unknown> | undefined;\n if (ch.id === channelContext?.channelId) {\n overrides = { ...channelContext.source, ...overrides };\n }\n const n =\n overrides !== undefined\n ? { ...notification, channelOverrides: overrides }\n : notification;\n await ch.notify(n);\n } catch (err) {\n logger.warn(`Channel ${ch.id} notification failed`, { error: String(err) });\n }\n })\n );\n }\n\n throw new WaitError(`Waiting for resume event: ${topic}`, { topic });\n },\n\n async resume(key: string, options: ResumeOptions): Promise<void> {\n const topic = `workflow/${options.suspendWorkflowId}/${options.suspendExecutionId}`;\n // Delegate to publishEvent\n return this.publishEvent(key, {\n topic,\n type: `resume_${options.suspendStepKey}`,\n data: options.data,\n });\n },\n\n async uuid(key: string): Promise<string> {\n const existing = checkExistingStep(key);\n if (existing) {\n return handleExistingStep(existing) as string;\n }\n\n const generatedUuid = randomUUID();\n await saveStepOutput(key, generatedUuid);\n return generatedUuid;\n },\n\n async now(key: string): Promise<number> {\n const existing = checkExistingStep(key);\n if (existing) {\n return existing.outputs as number;\n }\n\n const timestamp = Date.now();\n await saveStepOutput(key, timestamp);\n return timestamp;\n },\n\n async random(key: string): Promise<number> {\n const existing = checkExistingStep(key);\n if (existing) {\n return handleExistingStep(existing) as number;\n }\n\n const randomValue = Math.random();\n await saveStepOutput(key, randomValue);\n return randomValue;\n },\n\n async agentInvoke(key: string, config: AgentRunConfig): Promise<WorkflowHandle<unknown>> {\n checkAborted();\n\n const payload: Record<string, unknown> = {\n input: config.input,\n streaming: config.streaming,\n session_id: execCtx.sessionId,\n user_id: execCtx.userId,\n ...config.kwargs,\n };\n\n const [result] = await _invoke(key, config.agent, payload, {\n initialState: config.initialState,\n waitForSubworkflow: false,\n runTimeoutSeconds: config.runTimeoutSeconds,\n });\n\n const handleData = result as { id: string };\n return createWorkflowHandle<unknown>(orchestratorClient, handleData.id);\n },\n\n async agentInvokeAndWait(key: string, config: AgentRunConfig): Promise<unknown> {\n checkAborted();\n\n const payload: Record<string, unknown> = {\n input: config.input,\n streaming: config.streaming,\n session_id: execCtx.sessionId,\n user_id: execCtx.userId,\n ...config.kwargs,\n };\n\n const [result, found] = await _invoke(key, config.agent, payload, {\n initialState: config.initialState,\n waitForSubworkflow: true,\n runTimeoutSeconds: config.runTimeoutSeconds,\n });\n\n if (found) {\n // Step output is already deserialized JSON.\n return result;\n }\n\n throw new WaitError(`Waiting for agent workflow '${config.agent.id}' to complete`, {\n agentId: config.agent.id,\n });\n },\n\n async batchAgentInvoke(\n key: string,\n configs: AgentRunConfig[]\n ): Promise<WorkflowHandle<unknown>[]> {\n checkAborted();\n\n const workflows: BatchWorkflowInput[] = configs.map((config) => ({\n workflow: config.agent,\n payload: {\n input: config.input,\n streaming: config.streaming,\n session_id: execCtx.sessionId,\n user_id: execCtx.userId,\n ...config.kwargs,\n },\n initialState: config.initialState,\n runTimeoutSeconds: config.runTimeoutSeconds,\n }));\n\n // Delegate to batchInvoke\n return this.batchInvoke(key, workflows);\n },\n\n async batchAgentInvokeAndWait<T>(\n key: string,\n configs: AgentRunConfig[]\n ): Promise<BatchStepResult<T>[]> {\n checkAborted();\n\n const workflows: BatchWorkflowInput[] = configs.map((config) => ({\n workflow: config.agent,\n payload: {\n input: config.input,\n streaming: config.streaming,\n session_id: execCtx.sessionId,\n user_id: execCtx.userId,\n ...config.kwargs,\n },\n initialState: config.initialState,\n runTimeoutSeconds: config.runTimeoutSeconds,\n }));\n\n // Delegate to batchInvokeAndWait\n return this.batchInvokeAndWait<T>(key, workflows);\n },\n\n async trace<T>(\n name: string,\n fn: (span: unknown) => Promise<T>,\n attributes?: Record<string, string | number | boolean>\n ): Promise<T> {\n const tracer = getTracer();\n if (!tracer) return fn(undefined);\n\n const execContextData = getExecutionContext();\n const parentContext = getParentSpanContextFromExecutionContext(execContextData);\n const spanOpts = attributes ? { attributes } : {};\n const span = tracer.startSpan(name, spanOpts, parentContext);\n\n const oldSpanContext = getSpanContextFromExecutionContext(execContextData);\n setSpanContextInExecutionContext(execContextData, span.spanContext());\n\n try {\n const result = await fn(span);\n span.setStatus({ code: 1 /* OK */ });\n return result;\n } catch (e) {\n span.setStatus({ code: 2 /* ERROR */, message: String(e) });\n if (e instanceof Error) {\n span.recordException(e);\n }\n throw e;\n } finally {\n setSpanContextInExecutionContext(execContextData, oldSpanContext);\n span.end();\n }\n },\n };\n}\n\n/**\n * Execute a workflow.\n *\n * 1. Loads cached step outputs for replay\n * 2. Initializes state\n * 3. Sets up tracing context\n * 4. Publishes start event\n * 5. Executes onStart hooks\n * 6. Calls the workflow handler\n * 7. Executes onEnd hooks\n * 8. Publishes finish event\n * 9. Returns (result, finalState)\n */\nexport async function executeWorkflow(options: ExecuteWorkflowOptions): Promise<ExecutionResult> {\n const {\n workflow,\n payload,\n context,\n orchestratorClient,\n workerId,\n abortSignal,\n channels,\n sandboxManager,\n channelContext,\n } = options;\n\n let state: Record<string, unknown> = {};\n let validatedPayload = payload;\n\n // Determine workflow type from config (default: \"workflow\")\n const workflowType = workflow.config.workflowType ?? 'workflow';\n\n try {\n // Load cached step outputs for replay\n const cachedSteps = new Map<string, StepOutput>();\n try {\n const stepOutputs = await orchestratorClient.getAllStepOutputs(context.executionId, workerId);\n for (const output of stepOutputs) {\n cachedSteps.set(output.stepKey, output);\n }\n if (stepOutputs.length > 0) {\n logger.info(`Loaded ${String(stepOutputs.length)} cached step outputs for replay`);\n }\n } catch (err) {\n logger.warn('Failed to load cached step outputs', { error: String(err) });\n }\n\n // Initialize state\n if (context.initialState) {\n state = context.initialState;\n } else if (workflow.stateSchema) {\n state = initializeState(workflow.stateSchema as ZodType<Record<string, unknown>>);\n }\n\n // Validate payload if schema provided\n if (workflow.payloadSchema) {\n try {\n validatedPayload = validateState(payload, workflow.payloadSchema);\n } catch (err) {\n logger.error(`Payload validation failed for workflow \"${workflow.id}\"`, {\n payload: JSON.stringify(payload).slice(0, 500),\n error: String(err),\n });\n throw err;\n }\n }\n\n // Compute effective root IDs\n const rootExecutionId = context.rootExecutionId ?? context.executionId;\n const rootWorkflowId = context.rootWorkflowId ?? workflow.id;\n\n // Create step helper\n const step = createOrchestratorStepHelper(\n orchestratorClient,\n cachedSteps,\n {\n workflowId: workflow.id,\n executionId: context.executionId,\n deploymentId: context.deploymentId,\n sessionId: context.sessionId,\n userId: context.userId,\n rootExecutionId,\n rootWorkflowId,\n otelTraceparent: context.otelTraceparent,\n },\n workerId,\n abortSignal,\n channels,\n channelContext\n );\n\n // Create workflow context\n let ctx: WorkflowContext<Record<string, unknown>>;\n\n if (workflowType === 'agent') {\n // Build AgentContext for agents\n const agentWf = workflow as AgentWorkflow;\n const agentCtx: AgentContext<Record<string, unknown>> = {\n workflowId: workflow.id,\n executionId: context.executionId,\n deploymentId: context.deploymentId,\n sessionId: context.sessionId,\n userId: context.userId,\n parentExecutionId: context.parentExecutionId,\n rootExecutionId,\n rootWorkflowId,\n retryCount: context.retryCount,\n createdAt: context.createdAt,\n workflowType,\n otelTraceparent: context.otelTraceparent,\n otelSpanId: context.otelSpanId,\n state,\n step,\n agentId: workflow.id,\n model: getModelId(agentWf.llm.model),\n provider: getModelProvider(agentWf.llm.model),\n systemPrompt: agentWf.agentConfig.systemPrompt,\n tools: agentWf.tools,\n temperature: agentWf.agentConfig.temperature,\n maxTokens: agentWf.agentConfig.maxOutputTokens,\n };\n ctx = agentCtx;\n } else {\n // WorkflowContext for regular workflows and tools\n ctx = {\n workflowId: workflow.id,\n executionId: context.executionId,\n deploymentId: context.deploymentId,\n sessionId: context.sessionId,\n userId: context.userId,\n parentExecutionId: context.parentExecutionId,\n rootExecutionId,\n rootWorkflowId,\n retryCount: context.retryCount,\n createdAt: context.createdAt,\n workflowType,\n otelTraceparent: context.otelTraceparent,\n otelSpanId: context.otelSpanId,\n state,\n step,\n };\n }\n\n // --- Set up OpenTelemetry tracing ---\n const tracer = getTracer();\n let span: Span | undefined;\n const isRootWorkflow = !context.parentExecutionId;\n\n if (tracer) {\n const spanName = `${workflowType}.${workflow.id}`;\n\n // Build span attributes\n const spanAttributes: Record<string, string | number> = {\n [`${workflowType}.id`]: workflow.id,\n [`${workflowType}.execution_id`]: context.executionId,\n [`${workflowType}.root_execution_id`]: rootExecutionId,\n [`${workflowType}.deployment_id`]: context.deploymentId,\n [`${workflowType}.type`]: workflowType,\n [`${workflowType}.retry_count`]: context.retryCount,\n };\n if (context.parentExecutionId) {\n spanAttributes[`${workflowType}.parent_execution_id`] = context.parentExecutionId;\n }\n if (context.sessionId) {\n spanAttributes[`${workflowType}.session_id`] = context.sessionId;\n }\n if (context.userId) {\n spanAttributes[`${workflowType}.user_id`] = context.userId;\n }\n if (context.otelSpanId) {\n spanAttributes[`${workflowType}.previous_span_id`] = context.otelSpanId;\n }\n\n // Determine parent context\n let otelParentContext: Context | undefined;\n if (context.otelTraceparent) {\n // Sub-workflow: extract parent from traceparent\n otelParentContext = createContextFromTraceparent(context.otelTraceparent);\n } else {\n // Root workflow: deterministic trace ID\n const traceIdHex = generateTraceIdFromExecutionId(rootExecutionId);\n otelParentContext = createContextWithTraceId(traceIdHex);\n }\n\n // For root workflows, activate context so IdGenerator reads trace ID\n if (isRootWorkflow && otelParentContext) {\n // Use context.with to make the deterministic trace ID available\n span = otelContext.with(otelParentContext, () => {\n return tracer.startSpan(spanName, { attributes: spanAttributes }, otelParentContext);\n });\n } else {\n span = tracer.startSpan(spanName, { attributes: spanAttributes }, otelParentContext);\n }\n }\n\n // Topic for workflow events\n const topic = `workflow/${ctx.rootWorkflowId}/${ctx.rootExecutionId}`;\n\n // Set input and initial state on span\n if (span) {\n try {\n span.setAttribute(`${workflowType}.input`, JSON.stringify(validatedPayload));\n } catch {\n /* ignore */\n }\n try {\n span.setAttribute(`${workflowType}.initial_state`, JSON.stringify(state));\n } catch {\n /* ignore */\n }\n\n // Add resumed event if this is a resumed workflow\n if (context.otelSpanId) {\n span.addEvent(`${workflowType}.resumed`);\n }\n }\n\n // Build execution context data with span context so hooks and handler\n // can create properly-parented OTel spans via getExecutionContext().\n const spanCtx = span?.spanContext();\n const execContextData = {\n executionId: context.executionId,\n workflowId: workflow.id,\n rootExecutionId,\n sessionId: context.sessionId,\n sandboxManager,\n orchestratorClient,\n _otelSpanContext: spanCtx,\n _otelTraceId: spanCtx?.traceId,\n _otelSpanId: spanCtx?.spanId,\n };\n\n try {\n // Run everything (hooks + handler) within execution context so that\n // ctx.step.run() inside hooks creates spans with the correct trace ID.\n return await runInExecutionContext(execContextData, async () => {\n // Publish start event\n await step.publishEvent('publish_start', {\n topic,\n type: `${workflowType}_start`,\n data: {\n payload: validatedPayload,\n _metadata: {\n execution_id: ctx.executionId,\n workflow_id: ctx.workflowId,\n },\n },\n });\n\n // Execute onStart hooks\n if (workflow.config.onStart) {\n const hookResult = await executeHookChain(normalizeHooks(workflow.config.onStart), {\n ctx,\n hookName: 'on_start',\n payload: validatedPayload,\n phase: 'onStart',\n });\n\n if (!hookResult.success) {\n if (span) {\n span.setStatus({\n code: 2 /* ERROR */,\n message: hookResult.error ?? 'onStart hook failed',\n });\n span.setAttribute(`${workflowType}.status`, 'failed');\n }\n return {\n success: false,\n error: hookResult.error ?? 'onStart hook failed',\n retryable: false,\n finalState: state,\n };\n }\n\n // Apply modified payload\n validatedPayload = hookResult.payload;\n }\n\n // Check for cancellation\n if (abortSignal?.aborted) {\n if (span) {\n span.setStatus({ code: 2 /* ERROR */, message: 'Execution cancelled' });\n span.setAttribute(`${workflowType}.status`, 'cancelled');\n }\n return {\n success: false,\n error: 'Execution cancelled',\n retryable: false,\n finalState: state,\n };\n }\n\n // Execute workflow handler\n const result = await workflow.handler(ctx, validatedPayload);\n\n // Extract final state\n if (workflow.stateSchema) {\n state = validateState(\n ctx.state,\n workflow.stateSchema as ZodType<Record<string, unknown>>\n );\n } else {\n state = ctx.state;\n }\n\n // Execute onEnd hooks\n let finalResult: unknown = result;\n if (workflow.config.onEnd) {\n const hookResult = await executeHookChain(normalizeHooks(workflow.config.onEnd), {\n ctx,\n hookName: 'on_end',\n payload: validatedPayload,\n output: result,\n phase: 'onEnd',\n });\n\n if (!hookResult.success) {\n if (span) {\n span.setStatus({\n code: 2 /* ERROR */,\n message: hookResult.error ?? 'onEnd hook failed',\n });\n span.setAttribute(`${workflowType}.status`, 'failed');\n }\n return {\n success: false,\n error: hookResult.error ?? 'onEnd hook failed',\n retryable: false,\n finalState: state,\n };\n }\n\n // Apply modified output\n if (hookResult.output !== undefined) {\n finalResult = hookResult.output;\n }\n }\n\n // Publish finish event\n await step.publishEvent('publish_finish', {\n topic,\n type: `${workflowType}_finish`,\n data: {\n result: finalResult,\n _metadata: {\n execution_id: ctx.executionId,\n workflow_id: ctx.workflowId,\n },\n },\n });\n\n // Success span attributes\n if (span) {\n span.setStatus({ code: 1 /* OK */ });\n span.setAttribute(`${workflowType}.status`, 'completed');\n try {\n span.setAttribute(`${workflowType}.output`, JSON.stringify(finalResult));\n } catch {\n /* ignore */\n }\n try {\n const resultStr = JSON.stringify(finalResult);\n span.setAttribute(`${workflowType}.result_size`, resultStr.length);\n } catch {\n /* ignore */\n }\n try {\n span.setAttribute(`${workflowType}.final_state`, JSON.stringify(state));\n } catch {\n /* ignore */\n }\n }\n\n return {\n success: true,\n result: finalResult,\n finalState: state,\n };\n }); // end runInExecutionContext\n } catch (error) {\n // WaitError — execution is paused, not a failure\n if (isWaitError(error)) {\n if (span) {\n span.setStatus({ code: 1 /* OK */ });\n span.setAttribute(`${workflowType}.status`, 'waiting');\n span.addEvent(`${workflowType}.waiting`, { reason: error.message });\n\n // Save span ID for resume linkage\n const spanContext = span.spanContext();\n if (spanContext.spanId) {\n try {\n await orchestratorClient.updateExecutionOtelSpanId(\n context.executionId,\n spanContext.spanId\n );\n } catch (e) {\n logger.warn(`Failed to update otel_span_id: ${String(e)}`);\n }\n }\n }\n\n return {\n success: false,\n waiting: true,\n error: error.message,\n retryable: false,\n finalState: state,\n };\n }\n\n const errorMessage = error instanceof Error ? error.message : String(error);\n const stack = error instanceof Error ? error.stack : undefined;\n\n // Check if cancelled\n if (errorMessage === 'Execution cancelled' || abortSignal?.aborted) {\n if (span) {\n span.setStatus({ code: 2 /* ERROR */, message: 'Execution cancelled' });\n span.setAttribute(`${workflowType}.status`, 'cancelled');\n }\n return {\n success: false,\n error: 'Execution cancelled',\n retryable: false,\n finalState: state,\n };\n }\n\n logger.error(`${workflowType} '${workflow.id}' execution failed: ${errorMessage}`, {\n workflowId: workflow.id,\n executionId: context.executionId,\n workflowType,\n error: errorMessage,\n stack,\n });\n\n // Error span attributes\n if (span) {\n span.setStatus({ code: 2 /* ERROR */, message: errorMessage });\n if (error instanceof Error) {\n span.recordException(error);\n }\n span.setAttribute(`${workflowType}.status`, 'failed');\n try {\n span.setAttribute(\n `${workflowType}.error`,\n JSON.stringify({ message: errorMessage, stack })\n );\n } catch {\n /* ignore */\n }\n }\n\n // StepExecutionError and \"tool\" workflows are not retryable\n const retryable =\n !(error instanceof StepExecutionError) && workflow.config.workflowType !== 'tool';\n\n return {\n success: false,\n error: errorMessage,\n stack,\n retryable,\n finalState: state,\n };\n } finally {\n if (span) {\n span.end();\n }\n }\n } catch (error) {\n // Outer catch for errors before span creation (step loading, state init, etc.)\n if (isWaitError(error)) {\n return {\n success: false,\n waiting: true,\n error: error.message,\n retryable: false,\n finalState: state,\n };\n }\n\n const errorMessage = error instanceof Error ? error.message : String(error);\n const stack = error instanceof Error ? error.stack : undefined;\n\n if (errorMessage === 'Execution cancelled' || abortSignal?.aborted) {\n return {\n success: false,\n error: 'Execution cancelled',\n retryable: false,\n finalState: state,\n };\n }\n\n logger.error(\n `${workflow.config.workflowType ?? 'workflow'} '${workflow.id}' execution failed: ${errorMessage}`,\n {\n workflowId: workflow.id,\n executionId: context.executionId,\n workflowType: workflow.config.workflowType ?? 'workflow',\n error: errorMessage,\n stack,\n }\n );\n\n const retryable =\n !(error instanceof StepExecutionError) && workflow.config.workflowType !== 'tool';\n\n return {\n success: false,\n error: errorMessage,\n stack,\n retryable,\n finalState: state,\n };\n }\n}\n\n/**\n * Serialize the final state for persistence.\n */\nexport function serializeFinalState(state: Record<string, unknown>): string {\n return serializeState(state);\n}\n","/**\n * Output utilities for the execution framework.\n *\n * Provides functions for truncating large outputs, detecting binary content,\n * parsing grep output, and stripping ANSI escape codes.\n */\n\nimport type { GrepMatch } from './types.js';\n\n/** Default maximum output characters */\nconst DEFAULT_MAX_CHARS = 100_000;\n\n/** Head portion of truncated output (20% of max) */\nconst HEAD_RATIO = 0.2;\n\n/**\n * Truncate output that exceeds the maximum character limit.\n *\n * Keeps the first 20K characters (head) and last 80K characters (tail)\n * of a 100K max, with a truncation message in between.\n */\nexport function truncateOutput(\n output: string,\n maxChars?: number\n): { text: string; truncated: boolean } {\n const max = maxChars ?? DEFAULT_MAX_CHARS;\n if (output.length <= max) {\n return { text: output, truncated: false };\n }\n\n const headSize = Math.floor(max * HEAD_RATIO);\n const tailSize = max - headSize;\n const omitted = output.length - headSize - tailSize;\n\n const head = output.slice(0, headSize);\n const tail = output.slice(-tailSize);\n const text = `${head}\\n\\n--- truncated ${String(omitted)} characters ---\\n\\n${tail}`;\n\n return { text, truncated: true };\n}\n\n/**\n * Detect binary content by checking for null bytes in the first 8KB.\n */\nexport function isBinary(buffer: Buffer): boolean {\n const checkLength = Math.min(buffer.length, 8192);\n for (let i = 0; i < checkLength; i++) {\n if (buffer[i] === 0) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Parse `grep -rn` output into structured GrepMatch objects.\n *\n * Expected format: `filepath:linenum:matched text`\n */\nexport function parseGrepOutput(output: string): GrepMatch[] {\n if (!output.trim()) {\n return [];\n }\n\n const matches: GrepMatch[] = [];\n const lines = output.split('\\n');\n\n for (const line of lines) {\n if (!line) continue;\n\n // Match format: path:line:text\n const match = /^(.+?):(\\d+):(.*)$/.exec(line);\n if (match?.[1] && match[2] && match[3] !== undefined) {\n matches.push({ path: match[1], line: parseInt(match[2], 10), text: match[3] });\n }\n }\n\n return matches;\n}\n\n/**\n * Strip ANSI escape codes from text.\n */\nexport function stripAnsi(text: string): string {\n // Matches all ANSI escape sequences\n // eslint-disable-next-line no-control-regex\n return text.replace(/\\x1b\\[[0-9;]*[a-zA-Z]/g, '');\n}\n","/**\n * Docker execution environment.\n *\n * Runs commands inside a Docker container and accesses files via bind mount\n * for optimal performance. The container runs `sleep infinity` and commands\n * are executed via `docker exec`.\n */\n\nimport { spawn } from 'node:child_process';\nimport * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { randomUUID } from 'node:crypto';\nimport type {\n ExecutionEnvironment,\n ExecOptions,\n ExecResult,\n GlobOptions,\n GrepOptions,\n GrepMatch,\n EnvironmentInfo,\n DockerEnvironmentConfig,\n} from './types.js';\nimport { truncateOutput, isBinary, parseGrepOutput, stripAnsi } from './output.js';\n\n/** Default container working directory */\nconst DEFAULT_CONTAINER_WORKDIR = '/workspace';\n\n/** Default command timeout in seconds */\nconst DEFAULT_TIMEOUT_SECONDS = 300;\n\n/** Default maximum output characters */\nconst DEFAULT_MAX_OUTPUT_CHARS = 100_000;\n\n/**\n * Execute a command via child_process.spawn and capture output.\n * @internal\n */\nfunction spawnCommand(\n command: string,\n args: string[],\n options?: { timeout?: number | undefined; stdin?: string | undefined }\n): Promise<{ exitCode: number; stdout: string; stderr: string }> {\n return new Promise((resolve, reject) => {\n let settled = false;\n const settle = (fn: () => void) => {\n if (!settled) {\n settled = true;\n fn();\n }\n };\n\n const proc = spawn(command, args, { stdio: ['pipe', 'pipe', 'pipe'] });\n\n let stdout = '';\n let stderr = '';\n let killed = false;\n\n proc.stdout.on('data', (data: Buffer) => {\n stdout += data.toString();\n });\n\n proc.stderr.on('data', (data: Buffer) => {\n stderr += data.toString();\n });\n\n // Guard against stream errors leaving the promise unresolved\n proc.stdin.on('error', () => {\n // Ignore stdin errors — the process may have exited before we finished writing.\n // The 'close' event will still fire and resolve the promise.\n });\n proc.stdout.on('error', () => {\n /* noop */\n });\n proc.stderr.on('error', () => {\n /* noop */\n });\n\n const timeoutMs = (options?.timeout ?? DEFAULT_TIMEOUT_SECONDS) * 1000;\n const timer = setTimeout(() => {\n killed = true;\n proc.kill('SIGKILL');\n }, timeoutMs);\n\n proc.on('close', (code) => {\n clearTimeout(timer);\n settle(() => {\n if (killed) {\n resolve({\n exitCode: 137,\n stdout,\n stderr: stderr + '\\n[Process killed: timeout exceeded]',\n });\n } else {\n resolve({ exitCode: code ?? 1, stdout, stderr });\n }\n });\n });\n\n proc.on('error', (err) => {\n clearTimeout(timer);\n settle(() => {\n reject(err);\n });\n });\n\n if (options?.stdin) {\n proc.stdin.write(options.stdin, () => {\n proc.stdin.end();\n });\n } else {\n proc.stdin.end();\n }\n });\n}\n\n/**\n * Docker-based execution environment.\n *\n * Creates a persistent Docker container with a bind-mounted workspace.\n * Commands run inside the container via `docker exec`, while file\n * operations use the host filesystem through the bind mount for speed.\n */\nexport class DockerEnvironment implements ExecutionEnvironment {\n readonly type = 'docker' as const;\n\n private containerId: string | null = null;\n private containerName: string;\n private readonly config: DockerEnvironmentConfig;\n private readonly containerWorkdir: string;\n private readonly maxOutputChars: number;\n\n constructor(config: DockerEnvironmentConfig, maxOutputChars?: number) {\n this.config = config;\n this.containerWorkdir = config.containerWorkdir ?? DEFAULT_CONTAINER_WORKDIR;\n this.containerName = `polos-sandbox-${randomUUID().slice(0, 8)}`;\n this.maxOutputChars = maxOutputChars ?? DEFAULT_MAX_OUTPUT_CHARS;\n }\n\n /**\n * Get the container name (useful for health checking and identification).\n */\n getContainerName(): string {\n return this.containerName;\n }\n\n async initialize(labels?: Record<string, string>): Promise<void> {\n const args = [\n 'run',\n '-d',\n '--name',\n this.containerName,\n '-v',\n `${this.config.workspaceDir}:${this.containerWorkdir}:rw`,\n '-w',\n this.containerWorkdir,\n ];\n\n if (this.config.memory) {\n args.push('--memory', this.config.memory);\n }\n if (this.config.cpus) {\n args.push('--cpus', this.config.cpus);\n }\n args.push('--network', this.config.network ?? 'none');\n\n if (this.config.env) {\n for (const [key, value] of Object.entries(this.config.env)) {\n args.push('-e', `${key}=${value}`);\n }\n }\n\n if (labels) {\n for (const [key, value] of Object.entries(labels)) {\n args.push('--label', `${key}=${value}`);\n }\n }\n\n args.push(this.config.image, 'sleep', 'infinity');\n\n const result = await spawnCommand('docker', args, { timeout: 60 });\n if (result.exitCode !== 0) {\n throw new Error(`Failed to create Docker container: ${result.stderr.trim()}`);\n }\n this.containerId = result.stdout.trim().slice(0, 12);\n\n // Run setup command if provided\n if (this.config.setupCommand) {\n const setupResult = await this.exec(this.config.setupCommand);\n if (setupResult.exitCode !== 0) {\n throw new Error(\n `Setup command failed (exit ${String(setupResult.exitCode)}): ${setupResult.stderr.trim()}`\n );\n }\n }\n }\n\n async exec(command: string, opts?: ExecOptions): Promise<ExecResult> {\n this.assertInitialized();\n\n // Only use -i (interactive/keep-stdin-open) when stdin data is provided.\n // Without stdin data, -i can cause docker exec to hang waiting for EOF.\n const args = opts?.stdin ? ['exec', '-i'] : ['exec'];\n\n // Set working directory\n const cwd = opts?.cwd ?? this.containerWorkdir;\n args.push('-w', cwd);\n\n // Set environment variables\n if (opts?.env) {\n for (const [key, value] of Object.entries(opts.env)) {\n args.push('-e', `${key}=${value}`);\n }\n }\n\n args.push(this.containerName, 'sh', '-c', command);\n\n const timeout = opts?.timeout ?? DEFAULT_TIMEOUT_SECONDS;\n const start = Date.now();\n\n const result = await spawnCommand('docker', args, {\n timeout,\n stdin: opts?.stdin,\n });\n\n const durationMs = Date.now() - start;\n const { text: stdout, truncated: stdoutTruncated } = truncateOutput(\n stripAnsi(result.stdout),\n this.maxOutputChars\n );\n const { text: stderr } = truncateOutput(stripAnsi(result.stderr), this.maxOutputChars);\n\n return {\n exitCode: result.exitCode,\n stdout,\n stderr,\n durationMs,\n truncated: stdoutTruncated,\n };\n }\n\n async readFile(filePath: string): Promise<string> {\n const hostPath = this.toHostPath(filePath);\n const buffer = await fs.readFile(hostPath);\n if (isBinary(buffer)) {\n throw new Error(`Cannot read binary file: ${filePath}`);\n }\n return buffer.toString('utf-8');\n }\n\n async writeFile(filePath: string, content: string): Promise<void> {\n const hostPath = this.toHostPath(filePath);\n await fs.mkdir(path.dirname(hostPath), { recursive: true });\n await fs.writeFile(hostPath, content, 'utf-8');\n }\n\n async fileExists(filePath: string): Promise<boolean> {\n const hostPath = this.toHostPath(filePath);\n try {\n await fs.access(hostPath);\n return true;\n } catch {\n return false;\n }\n }\n\n async glob(pattern: string, opts?: GlobOptions): Promise<string[]> {\n const cwd = opts?.cwd ?? this.containerWorkdir;\n let command = `find ${cwd} -type f -name '${pattern}'`;\n\n if (opts?.ignore) {\n for (const ignore of opts.ignore) {\n command += ` ! -path '${ignore}'`;\n }\n }\n\n command += ' 2>/dev/null | sort | head -1000';\n\n const result = await this.exec(command);\n if (!result.stdout.trim()) return [];\n\n return result.stdout.trim().split('\\n').filter(Boolean);\n }\n\n async grep(pattern: string, opts?: GrepOptions): Promise<GrepMatch[]> {\n const cwd = opts?.cwd ?? this.containerWorkdir;\n const maxResults = opts?.maxResults ?? 100;\n\n let command = 'grep -rn';\n\n if (opts?.contextLines !== undefined) {\n command += ` -C ${String(opts.contextLines)}`;\n }\n\n if (opts?.include) {\n for (const inc of opts.include) {\n command += ` --include='${inc}'`;\n }\n }\n\n // Use -- to separate pattern from paths, escape single quotes in pattern\n const escapedPattern = pattern.replace(/'/g, \"'\\\\''\");\n command += ` -- '${escapedPattern}' ${cwd}`;\n command += ` 2>/dev/null | head -${String(maxResults)}`;\n\n const result = await this.exec(command);\n return parseGrepOutput(result.stdout);\n }\n\n async destroy(): Promise<void> {\n if (!this.containerId) return;\n try {\n await spawnCommand('docker', ['rm', '-f', this.containerName], { timeout: 30 });\n } finally {\n this.containerId = null;\n }\n }\n\n getCwd(): string {\n return this.containerWorkdir;\n }\n\n getInfo(): EnvironmentInfo {\n return {\n type: 'docker',\n cwd: this.containerWorkdir,\n sandboxId: this.containerId ?? undefined,\n };\n }\n\n /**\n * Translate a container path to the corresponding host filesystem path.\n * Validates the path stays within the workspace to prevent traversal.\n */\n toHostPath(containerPath: string): string {\n // Resolve relative to container workdir\n const resolved = path.posix.resolve(this.containerWorkdir, containerPath);\n\n // Ensure the resolved path is within the container workdir\n if (!resolved.startsWith(this.containerWorkdir)) {\n throw new Error(`Path traversal detected: \"${containerPath}\" resolves outside workspace`);\n }\n\n // Translate to host path\n const relative = path.posix.relative(this.containerWorkdir, resolved);\n return path.join(this.config.workspaceDir, relative);\n }\n\n /**\n * Translate a host filesystem path to the corresponding container path.\n */\n toContainerPath(hostPath: string): string {\n const resolved = path.resolve(hostPath);\n\n if (!resolved.startsWith(this.config.workspaceDir)) {\n throw new Error(\n `Path outside workspace: \"${hostPath}\" is not within \"${this.config.workspaceDir}\"`\n );\n }\n\n const relative = path.relative(this.config.workspaceDir, resolved);\n return path.posix.join(this.containerWorkdir, relative);\n }\n\n private assertInitialized(): void {\n if (!this.containerId) {\n throw new Error('Docker environment not initialized. Call initialize() first.');\n }\n }\n}\n","/**\n * Local execution environment.\n *\n * Runs commands and accesses files directly on the host machine.\n * Optionally restricts file operations to a specified directory\n * and blocks symlink traversal when path restriction is active.\n */\n\nimport { spawn } from 'node:child_process';\nimport * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport type {\n ExecutionEnvironment,\n ExecOptions,\n ExecResult,\n GlobOptions,\n GrepOptions,\n GrepMatch,\n EnvironmentInfo,\n LocalEnvironmentConfig,\n} from './types.js';\nimport { truncateOutput, isBinary, parseGrepOutput, stripAnsi } from './output.js';\n\n/** Default command timeout in seconds */\nconst DEFAULT_TIMEOUT_SECONDS = 300;\n\n/** Default maximum output characters */\nconst DEFAULT_MAX_OUTPUT_CHARS = 100_000;\n\n/**\n * Execute a shell command via child_process.spawn.\n * @internal\n */\nfunction spawnLocal(\n command: string,\n options: {\n cwd?: string | undefined;\n env?: Record<string, string> | undefined;\n timeout?: number | undefined;\n stdin?: string | undefined;\n }\n): Promise<{ exitCode: number; stdout: string; stderr: string }> {\n return new Promise((resolve, reject) => {\n let settled = false;\n const settle = (fn: () => void) => {\n if (!settled) {\n settled = true;\n fn();\n }\n };\n\n const proc = spawn('sh', ['-c', command], {\n cwd: options.cwd,\n env: options.env ? { ...process.env, ...options.env } : undefined,\n stdio: ['pipe', 'pipe', 'pipe'],\n });\n\n let stdout = '';\n let stderr = '';\n let killed = false;\n\n proc.stdout.on('data', (data: Buffer) => {\n stdout += data.toString();\n });\n\n proc.stderr.on('data', (data: Buffer) => {\n stderr += data.toString();\n });\n\n // Guard against stream errors leaving the promise unresolved\n proc.stdin.on('error', () => {\n /* noop */\n });\n proc.stdout.on('error', () => {\n /* noop */\n });\n proc.stderr.on('error', () => {\n /* noop */\n });\n\n const timeoutMs = (options.timeout ?? DEFAULT_TIMEOUT_SECONDS) * 1000;\n const timer = setTimeout(() => {\n killed = true;\n proc.kill('SIGKILL');\n }, timeoutMs);\n\n proc.on('close', (code) => {\n clearTimeout(timer);\n settle(() => {\n if (killed) {\n resolve({\n exitCode: 137,\n stdout,\n stderr: stderr + '\\n[Process killed: timeout exceeded]',\n });\n } else {\n resolve({ exitCode: code ?? 1, stdout, stderr });\n }\n });\n });\n\n proc.on('error', (err) => {\n clearTimeout(timer);\n settle(() => {\n reject(err);\n });\n });\n\n if (options.stdin) {\n proc.stdin.write(options.stdin, () => {\n proc.stdin.end();\n });\n } else {\n proc.stdin.end();\n }\n });\n}\n\n/**\n * Local execution environment.\n *\n * Executes commands and file operations directly on the host.\n * When `pathRestriction` is configured, file operations are restricted\n * to the specified directory and symlink traversal is blocked.\n */\nexport class LocalEnvironment implements ExecutionEnvironment {\n readonly type = 'local' as const;\n\n private readonly config: LocalEnvironmentConfig;\n private readonly cwd: string;\n private readonly maxOutputChars: number;\n\n constructor(config?: LocalEnvironmentConfig, maxOutputChars?: number) {\n this.config = config ?? {};\n this.cwd = path.resolve(config?.cwd ?? process.cwd());\n this.maxOutputChars = maxOutputChars ?? DEFAULT_MAX_OUTPUT_CHARS;\n }\n\n async initialize(): Promise<void> {\n // Validate that the working directory exists\n try {\n const stat = await fs.stat(this.cwd);\n if (!stat.isDirectory()) {\n throw new Error(`Working directory is not a directory: ${this.cwd}`);\n }\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n throw new Error(`Working directory does not exist: ${this.cwd}`);\n }\n throw err;\n }\n }\n\n async exec(command: string, opts?: ExecOptions): Promise<ExecResult> {\n const cwd = opts?.cwd ? this.resolvePath(opts.cwd) : this.cwd;\n const timeout = opts?.timeout ?? DEFAULT_TIMEOUT_SECONDS;\n const start = Date.now();\n\n const result = await spawnLocal(command, {\n cwd,\n env: opts?.env,\n timeout,\n stdin: opts?.stdin,\n });\n\n const durationMs = Date.now() - start;\n const { text: stdout, truncated: stdoutTruncated } = truncateOutput(\n stripAnsi(result.stdout),\n this.maxOutputChars\n );\n const { text: stderr } = truncateOutput(stripAnsi(result.stderr), this.maxOutputChars);\n\n return {\n exitCode: result.exitCode,\n stdout,\n stderr,\n durationMs,\n truncated: stdoutTruncated,\n };\n }\n\n async readFile(filePath: string): Promise<string> {\n const resolved = this.resolvePath(filePath);\n // Path restriction for reads is handled at the tool layer (approval gate).\n // Symlink traversal is still blocked at the environment level.\n await this.assertNotSymlink(resolved);\n\n const buffer = await fs.readFile(resolved);\n if (isBinary(buffer)) {\n throw new Error(`Cannot read binary file: ${filePath}`);\n }\n return buffer.toString('utf-8');\n }\n\n async writeFile(filePath: string, content: string): Promise<void> {\n const resolved = this.resolvePath(filePath);\n this.assertPathSafe(resolved);\n\n const parentDir = path.dirname(resolved);\n await fs.mkdir(parentDir, { recursive: true });\n await fs.writeFile(resolved, content, 'utf-8');\n }\n\n async fileExists(filePath: string): Promise<boolean> {\n const resolved = this.resolvePath(filePath);\n try {\n await fs.access(resolved);\n return true;\n } catch {\n return false;\n }\n }\n\n async glob(pattern: string, opts?: GlobOptions): Promise<string[]> {\n const cwd = opts?.cwd ? this.resolvePath(opts.cwd) : this.cwd;\n\n let command = `find ${cwd} -type f -name '${pattern}'`;\n\n if (opts?.ignore) {\n for (const ignore of opts.ignore) {\n command += ` ! -path '${ignore}'`;\n }\n }\n\n command += ' 2>/dev/null | sort | head -1000';\n\n const result = await this.exec(command);\n if (!result.stdout.trim()) return [];\n\n return result.stdout.trim().split('\\n').filter(Boolean);\n }\n\n async grep(pattern: string, opts?: GrepOptions): Promise<GrepMatch[]> {\n const cwd = opts?.cwd ? this.resolvePath(opts.cwd) : this.cwd;\n const maxResults = opts?.maxResults ?? 100;\n\n let command = 'grep -rn';\n\n if (opts?.contextLines !== undefined) {\n command += ` -C ${String(opts.contextLines)}`;\n }\n\n if (opts?.include) {\n for (const inc of opts.include) {\n command += ` --include='${inc}'`;\n }\n }\n\n // Escape single quotes in pattern, use -- to separate pattern from paths\n const escapedPattern = pattern.replace(/'/g, \"'\\\\''\");\n command += ` -- '${escapedPattern}' ${cwd}`;\n command += ` 2>/dev/null | head -${String(maxResults)}`;\n\n const result = await this.exec(command);\n return parseGrepOutput(result.stdout);\n }\n\n async destroy(): Promise<void> {\n // No-op — local environment has no resources to clean up\n }\n\n getCwd(): string {\n return this.cwd;\n }\n\n getInfo(): EnvironmentInfo {\n return {\n type: 'local',\n cwd: this.cwd,\n };\n }\n\n /**\n * Resolve a path relative to the working directory.\n */\n private resolvePath(p: string): string {\n return path.resolve(this.cwd, p);\n }\n\n /**\n * Assert that a resolved path stays within the path restriction.\n * No-op when path restriction is not configured.\n */\n private assertPathSafe(resolvedPath: string): void {\n if (!this.config.pathRestriction) return;\n\n const restriction = path.resolve(this.config.pathRestriction);\n if (resolvedPath !== restriction && !resolvedPath.startsWith(restriction + '/')) {\n throw new Error(`Path traversal detected: \"${resolvedPath}\" is outside of \"${restriction}\"`);\n }\n }\n\n /**\n * Assert that a path is not a symbolic link.\n * Only enforced when path restriction is configured.\n */\n private async assertNotSymlink(resolvedPath: string): Promise<void> {\n if (!this.config.pathRestriction) return;\n\n try {\n const stat = await fs.lstat(resolvedPath);\n if (stat.isSymbolicLink()) {\n throw new Error(\n `Symbolic link detected: \"${resolvedPath}\". Symlinks are blocked when pathRestriction is set.`\n );\n }\n } catch (err) {\n // File doesn't exist — that's fine, let readFile handle the ENOENT\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return;\n throw err;\n }\n }\n}\n","/**\n * Managed sandbox — wraps an ExecutionEnvironment with identity,\n * lifecycle tracking, and crash recovery.\n */\n\nimport { randomUUID } from 'node:crypto';\nimport * as fs from 'node:fs/promises';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\nimport type { ExecutionEnvironment, SandboxConfig, SandboxScope } from './types.js';\nimport { DockerEnvironment } from './docker.js';\nimport { LocalEnvironment } from './local.js';\nimport { createLogger } from '../utils/logger.js';\n\nconst logger = createLogger({ name: 'sandbox' });\n\n/** Default base directory for sandbox workspaces. */\nconst DEFAULT_WORKSPACES_DIR = path.join(os.homedir(), '.polos', 'workspaces');\n\n/** Environment variable to override the base workspaces directory. */\nconst WORKSPACES_DIR_ENV = 'POLOS_WORKSPACES_DIR';\n\n/**\n * A managed sandbox wrapping an ExecutionEnvironment.\n */\nexport interface Sandbox {\n readonly id: string;\n readonly scope: SandboxScope;\n readonly config: SandboxConfig;\n readonly workerId: string;\n readonly sessionId?: string | undefined;\n readonly activeExecutionIds: ReadonlySet<string>;\n readonly initialized: boolean;\n readonly destroyed: boolean;\n readonly lastActivityAt: Date;\n\n /** Get or lazily initialize the environment. Updates lastActivityAt. */\n getEnvironment(): Promise<ExecutionEnvironment>;\n\n /** Record that an execution is using this sandbox. */\n attachExecution(executionId: string): void;\n\n /** Record that an execution is done with this sandbox. */\n detachExecution(executionId: string): void;\n\n /** Destroy the sandbox. Safe to call multiple times. */\n destroy(): Promise<void>;\n\n /** Recreate after container crash. Filesystem survives via bind mount. */\n recreate(): Promise<void>;\n}\n\n/** Health check debounce interval in milliseconds. */\nconst HEALTH_CHECK_DEBOUNCE_MS = 30_000;\n\n/**\n * Concrete implementation of the Sandbox interface.\n */\nexport class ManagedSandbox implements Sandbox {\n readonly id: string;\n readonly scope: SandboxScope;\n readonly config: SandboxConfig;\n private _workerId: string;\n readonly projectId: string;\n readonly sessionId?: string | undefined;\n private readonly _activeExecutionIds = new Set<string>();\n private _lastActivityAt = new Date();\n private _destroyed = false;\n\n private _env: ExecutionEnvironment | null = null;\n private _envPromise: Promise<ExecutionEnvironment> | null = null;\n private _lastHealthCheckAt = 0;\n\n constructor(config: SandboxConfig, workerId: string, projectId: string, sessionId?: string) {\n this.id = config.id ?? `sandbox-${randomUUID().slice(0, 8)}`;\n this.scope = config.scope ?? 'execution';\n this.config = config;\n this._workerId = workerId;\n this.projectId = projectId;\n this.sessionId = sessionId;\n }\n\n get workerId(): string {\n return this._workerId;\n }\n\n get activeExecutionIds(): ReadonlySet<string> {\n return this._activeExecutionIds;\n }\n\n get initialized(): boolean {\n return this._env !== null;\n }\n\n get destroyed(): boolean {\n return this._destroyed;\n }\n\n get lastActivityAt(): Date {\n return this._lastActivityAt;\n }\n\n async getEnvironment(): Promise<ExecutionEnvironment> {\n if (this._destroyed) {\n throw new Error(`Sandbox ${this.id} has been destroyed`);\n }\n\n this._lastActivityAt = new Date();\n\n // If environment exists, optionally health-check\n if (this._env) {\n await this._healthCheck();\n return this._env;\n }\n\n // Coalesce concurrent init calls\n if (this._envPromise) {\n return this._envPromise;\n }\n\n this._envPromise = this._initializeEnvironment();\n try {\n const env = await this._envPromise;\n this._env = env;\n return env;\n } catch (err) {\n this._envPromise = null;\n throw err;\n }\n }\n\n attachExecution(executionId: string): void {\n this._activeExecutionIds.add(executionId);\n }\n\n detachExecution(executionId: string): void {\n this._activeExecutionIds.delete(executionId);\n }\n\n async destroy(): Promise<void> {\n if (this._destroyed) return;\n this._destroyed = true;\n\n if (this._env) {\n try {\n await this._env.destroy();\n } catch (err) {\n logger.warn(`Failed to destroy environment for sandbox ${this.id}`, {\n error: String(err),\n });\n }\n this._env = null;\n this._envPromise = null;\n }\n }\n\n async recreate(): Promise<void> {\n logger.info(`Recreating sandbox ${this.id}`);\n\n // Best-effort destroy old env\n if (this._env) {\n try {\n await this._env.destroy();\n } catch {\n // Container may already be gone\n }\n }\n\n this._env = null;\n this._envPromise = null;\n this._destroyed = false;\n this._lastHealthCheckAt = 0;\n\n // Next getEnvironment() call will re-initialize\n }\n\n /**\n * Create the execution environment based on config.\n */\n /**\n * Compute the default workspace directory for Docker.\n * Uses `POLOS_WORKSPACES_DIR/{projectId}/{sessionId || sandboxId}`.\n */\n private _getDefaultWorkspaceDir(): string {\n const base = process.env[WORKSPACES_DIR_ENV] ?? DEFAULT_WORKSPACES_DIR;\n const leaf = this.sessionId ?? this.id;\n return path.join(base, this.projectId, leaf);\n }\n\n private async _initializeEnvironment(): Promise<ExecutionEnvironment> {\n const envType = this.config.env ?? 'docker';\n\n switch (envType) {\n case 'docker': {\n const workspaceDir = this.config.docker?.workspaceDir ?? this._getDefaultWorkspaceDir();\n\n const dockerConfig = {\n image: 'node:20-slim',\n ...this.config.docker,\n workspaceDir,\n };\n\n // Ensure workspace directory exists on host before bind-mounting\n await fs.mkdir(workspaceDir, { recursive: true });\n\n const env = new DockerEnvironment(dockerConfig, this.config.exec?.maxOutputChars);\n\n // Build labels for lifecycle management and orphan detection\n const labels: Record<string, string> = {\n 'polos.managed': 'true',\n 'polos.sandbox-id': this.id,\n 'polos.worker-id': this._workerId,\n };\n if (this.sessionId) {\n labels['polos.session-id'] = this.sessionId;\n }\n\n await env.initialize(labels);\n return env;\n }\n case 'local': {\n const localCwd = this.config.local?.cwd ?? this._getDefaultWorkspaceDir();\n await fs.mkdir(localCwd, { recursive: true });\n // Default pathRestriction to cwd; set to false to explicitly disable\n const pathRestriction =\n this.config.local?.pathRestriction === false\n ? undefined\n : (this.config.local?.pathRestriction ?? localCwd);\n const localConfig = { ...this.config.local, cwd: localCwd, pathRestriction };\n const env = new LocalEnvironment(localConfig, this.config.exec?.maxOutputChars);\n await env.initialize();\n return env;\n }\n case 'e2b':\n throw new Error('E2B environment is not yet implemented.');\n default:\n throw new Error(`Unknown environment type: ${String(envType)}`);\n }\n }\n\n /**\n * Health check with 30s debounce. Only probes Docker containers.\n */\n private async _healthCheck(): Promise<void> {\n if (!this._env) return;\n if (this._env.type !== 'docker') return;\n\n const now = Date.now();\n if (now - this._lastHealthCheckAt < HEALTH_CHECK_DEBOUNCE_MS) {\n return;\n }\n\n this._lastHealthCheckAt = now;\n\n try {\n await this._env.exec('true', { timeout: 5 });\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n if (msg.includes('No such container') || msg.includes('is not running')) {\n logger.warn(`Container for sandbox ${this.id} is dead, recreating`, { error: msg });\n await this.recreate();\n // Re-initialize immediately so caller gets a working env\n await this.getEnvironment();\n }\n // Other errors (e.g., timeout) — don't recreate, let the actual tool call fail\n }\n }\n}\n","/**\n * SandboxManager — manages sandbox creation, reuse, auto-cleanup,\n * and orphan detection. Lives on the Worker.\n */\n\nimport { spawn } from 'node:child_process';\nimport type { SandboxConfig } from './types.js';\nimport { ManagedSandbox, type Sandbox } from './sandbox.js';\nimport { createLogger } from '../utils/logger.js';\nimport type { OrchestratorClient } from '../runtime/orchestrator-client.js';\n\nconst logger = createLogger({ name: 'sandbox-manager' });\n\n/** Default idle sweep interval: 10 minutes. */\nconst DEFAULT_SWEEP_INTERVAL_MS = 10 * 60 * 1000;\n\n/** Default idle destroy timeout: 1 hour. */\nconst DEFAULT_IDLE_TIMEOUT = '1h';\n\n/** Grace period before removing orphan containers (30 minutes). */\nconst ORPHAN_GRACE_PERIOD_MS = 30 * 60 * 1000;\n\n/**\n * Parse a human-readable duration string to milliseconds.\n * Supports: '30m', '1h', '24h', '3d', '7d'.\n */\nexport function parseDuration(str: string): number {\n const match = /^(\\d+(?:\\.\\d+)?)\\s*(m|h|d)$/.exec(str.trim());\n if (!match) {\n throw new Error(`Invalid duration: \"${str}\". Expected format: \"1h\", \"24h\", \"3d\", etc.`);\n }\n const value = parseFloat(match[1] ?? '0');\n const unit = match[2] ?? 'h';\n\n switch (unit) {\n case 'm':\n return value * 60 * 1000;\n case 'h':\n return value * 60 * 60 * 1000;\n case 'd':\n return value * 24 * 60 * 60 * 1000;\n default:\n throw new Error(`Unknown duration unit: \"${unit}\"`);\n }\n}\n\n/**\n * Manages sandbox lifecycle across executions.\n */\nexport class SandboxManager {\n private _workerId: string;\n private _projectId: string;\n private readonly _orchestratorClient: OrchestratorClient | undefined;\n private readonly sandboxes = new Map<string, ManagedSandbox>();\n private readonly sessionSandboxes = new Map<string, ManagedSandbox>();\n private readonly sessionCreationLocks = new Map<string, Promise<Sandbox>>();\n private sweepTimer: ReturnType<typeof setInterval> | null = null;\n\n constructor(workerId: string, projectId: string, orchestratorClient?: OrchestratorClient) {\n this._workerId = workerId;\n this._projectId = projectId;\n this._orchestratorClient = orchestratorClient;\n }\n\n /**\n * Update the worker ID (called after registration or re-registration).\n */\n setWorkerId(workerId: string): void {\n this._workerId = workerId;\n }\n\n /**\n * Create or retrieve a sandbox.\n *\n * - Session-scoped: returns existing sandbox for the session if available.\n * - Execution-scoped: always creates a new sandbox.\n */\n async getOrCreateSandbox(\n config: SandboxConfig,\n ctx: { executionId: string; sessionId?: string | undefined }\n ): Promise<Sandbox> {\n const scope = config.scope ?? 'execution';\n\n if (scope === 'session') {\n if (!ctx.sessionId) {\n throw new Error('sessionId is required for session-scoped sandboxes');\n }\n\n // Check for existing sandbox\n const existing = this.sessionSandboxes.get(ctx.sessionId);\n if (existing && !existing.destroyed) {\n existing.attachExecution(ctx.executionId);\n return existing;\n }\n\n // Serialize concurrent creation for the same session\n const existingLock = this.sessionCreationLocks.get(ctx.sessionId);\n if (existingLock) {\n const sandbox = await existingLock;\n sandbox.attachExecution(ctx.executionId);\n return sandbox;\n }\n\n // Register the lock as an unresolved promise BEFORE starting creation.\n // This ensures a concurrent caller arriving between here and the resolve\n // will find the lock and wait, even if _createSessionSandbox becomes async.\n let resolveLock!: (value: Sandbox) => void;\n let rejectLock!: (reason: unknown) => void;\n const lockPromise = new Promise<Sandbox>((resolve, reject) => {\n resolveLock = resolve;\n rejectLock = reject;\n });\n this.sessionCreationLocks.set(ctx.sessionId, lockPromise);\n\n try {\n const sandbox = this._createSessionSandbox(config, ctx.executionId, ctx.sessionId);\n resolveLock(sandbox);\n return sandbox;\n } catch (err) {\n rejectLock(err);\n throw err;\n } finally {\n this.sessionCreationLocks.delete(ctx.sessionId);\n }\n }\n\n // Execution-scoped: always new\n return this._createExecutionSandbox(config, ctx.executionId);\n }\n\n /**\n * Notify that an execution completed. Triggers cleanup for execution-scoped sandboxes.\n */\n async onExecutionComplete(executionId: string): Promise<void> {\n for (const [sandboxId, sandbox] of this.sandboxes) {\n if (!sandbox.activeExecutionIds.has(executionId)) continue;\n\n sandbox.detachExecution(executionId);\n\n // Execution-scoped sandboxes are 1:1 with executions — destroy immediately.\n // Session-scoped sandboxes survive; they're cleaned up by the idle sweep.\n if (sandbox.scope === 'execution') {\n await this._destroyAndRemove(sandboxId, sandbox);\n }\n }\n }\n\n /**\n * Destroy a specific sandbox by ID.\n */\n async destroySandbox(sandboxId: string): Promise<void> {\n const sandbox = this.sandboxes.get(sandboxId);\n if (sandbox) {\n await this._destroyAndRemove(sandboxId, sandbox);\n }\n }\n\n /**\n * Destroy all managed sandboxes. Called during worker shutdown.\n */\n async destroyAll(): Promise<void> {\n const entries = Array.from(this.sandboxes.entries());\n await Promise.allSettled(\n entries.map(async ([id, sandbox]) => {\n try {\n await sandbox.destroy();\n } catch (err) {\n logger.warn(`Failed to destroy sandbox ${id}`, { error: String(err) });\n }\n })\n );\n this.sandboxes.clear();\n this.sessionSandboxes.clear();\n }\n\n /**\n * Start periodic sweep. Each cycle:\n * 1. Destroys own sandboxes idle past their idleDestroyTimeout.\n * 2. Removes orphan Docker containers from dead workers (orchestrator-based).\n */\n startSweep(intervalMs: number = DEFAULT_SWEEP_INTERVAL_MS): void {\n this.stopSweep();\n this.sweepTimer = setInterval(() => {\n void this._sweep();\n }, intervalMs);\n // Don't keep process alive just for the sweep\n this.sweepTimer.unref();\n }\n\n /**\n * Stop the periodic sweep.\n */\n stopSweep(): void {\n if (this.sweepTimer) {\n clearInterval(this.sweepTimer);\n this.sweepTimer = null;\n }\n }\n\n /**\n * Lookup a sandbox by ID.\n */\n getSandbox(sandboxId: string): Sandbox | undefined {\n return this.sandboxes.get(sandboxId);\n }\n\n /**\n * Lookup a session sandbox by session ID.\n */\n getSessionSandbox(sessionId: string): Sandbox | undefined {\n return this.sessionSandboxes.get(sessionId);\n }\n\n // ── Private helpers ─────────────────────────────────────────────────\n\n private _createExecutionSandbox(config: SandboxConfig, executionId: string): Sandbox {\n const sandbox = new ManagedSandbox(config, this._workerId, this._projectId);\n sandbox.attachExecution(executionId);\n this.sandboxes.set(sandbox.id, sandbox);\n return sandbox;\n }\n\n private _createSessionSandbox(\n config: SandboxConfig,\n executionId: string,\n sessionId: string\n ): Sandbox {\n const sandbox = new ManagedSandbox(config, this._workerId, this._projectId, sessionId);\n sandbox.attachExecution(executionId);\n this.sandboxes.set(sandbox.id, sandbox);\n this.sessionSandboxes.set(sessionId, sandbox);\n return sandbox;\n }\n\n private async _destroyAndRemove(sandboxId: string, sandbox: ManagedSandbox): Promise<void> {\n await sandbox.destroy();\n this.sandboxes.delete(sandboxId);\n\n if (sandbox.sessionId) {\n const current = this.sessionSandboxes.get(sandbox.sessionId);\n if (current === sandbox) {\n this.sessionSandboxes.delete(sandbox.sessionId);\n }\n }\n }\n\n /**\n * Unified sweep: Phase 1 cleans own idle sandboxes, Phase 2 cleans orphan containers.\n */\n private async _sweep(): Promise<void> {\n // Phase 1: Sweep own idle sandboxes (in-memory lastActivityAt)\n await this._sweepIdleSandboxes();\n\n // Phase 2: Sweep orphan containers from dead workers\n await this._sweepOrphanContainers();\n }\n\n /**\n * Phase 1: Destroy own sandboxes that have been idle past their timeout.\n */\n private async _sweepIdleSandboxes(): Promise<void> {\n const now = Date.now();\n\n for (const [sandboxId, sandbox] of this.sandboxes) {\n // Use lastActivityAt as the sole signal. It's updated on every\n // getEnvironment() call (i.e., every tool invocation). If nothing has\n // touched this sandbox for longer than the timeout, it's dead —\n // regardless of scope or what activeExecutionIds claims.\n //\n // This handles two failure modes:\n // 1. Execution-scoped sandboxes orphaned by crashes (onExecutionComplete never called)\n // 2. Stale activeExecutionIds from executions that crashed without detaching\n const timeoutStr = sandbox.config.idleDestroyTimeout ?? DEFAULT_IDLE_TIMEOUT;\n const timeoutMs = parseDuration(timeoutStr);\n const idleMs = now - sandbox.lastActivityAt.getTime();\n\n if (idleMs > timeoutMs) {\n logger.info(\n `Destroying idle sandbox ${sandboxId} (scope=${sandbox.scope}, ` +\n `session=${sandbox.sessionId ?? 'none'}, idle ${String(Math.round(idleMs / 1000))}s)`\n );\n try {\n await this._destroyAndRemove(sandboxId, sandbox);\n } catch (err) {\n logger.warn(`Failed to destroy idle sandbox ${sandboxId}`, { error: String(err) });\n }\n }\n }\n }\n\n /**\n * Phase 2: Remove Docker containers from dead workers.\n *\n * Queries the orchestrator for active worker IDs, lists all polos-managed\n * Docker containers, and removes any whose worker-id is not in the active set\n * AND whose age exceeds ORPHAN_GRACE_PERIOD_MS.\n *\n * If the orchestrator is unavailable, this phase is skipped entirely.\n */\n private async _sweepOrphanContainers(): Promise<void> {\n if (!this._orchestratorClient) return;\n\n let activeWorkerIds: Set<string>;\n try {\n const ids = await this._orchestratorClient.getActiveWorkerIds();\n activeWorkerIds = new Set(ids);\n } catch (err) {\n logger.warn('Failed to query active workers, skipping orphan cleanup', {\n error: String(err),\n });\n return;\n }\n\n try {\n const result = await spawnSimple('docker', [\n 'ps',\n '-a',\n '--filter',\n 'label=polos.managed=true',\n '--format',\n '{{.Names}}\\t{{.Label \"polos.worker-id\"}}\\t{{.CreatedAt}}',\n ]);\n\n if (result.exitCode !== 0 || !result.stdout.trim()) return;\n\n const now = Date.now();\n const lines = result.stdout.trim().split('\\n').filter(Boolean);\n for (const line of lines) {\n const [name, workerId, createdAt] = line.split('\\t');\n if (!name || !workerId) continue;\n\n // Skip containers belonging to active workers\n if (activeWorkerIds.has(workerId)) continue;\n\n // Skip containers younger than the grace period to avoid TOCTOU races\n const containerAge = now - new Date(createdAt ?? '').getTime();\n if (isNaN(containerAge) || containerAge < ORPHAN_GRACE_PERIOD_MS) continue;\n\n logger.info(`Removing orphaned container: ${name} (worker: ${workerId})`);\n try {\n await spawnSimple('docker', ['rm', '-f', name]);\n } catch (err) {\n logger.warn(`Failed to remove orphaned container ${name}`, { error: String(err) });\n }\n }\n } catch (err) {\n logger.warn('Failed to sweep orphan containers', { error: String(err) });\n }\n }\n}\n\n/**\n * Simple spawn helper for manager-level docker commands.\n */\nfunction spawnSimple(\n command: string,\n args: string[]\n): Promise<{ exitCode: number; stdout: string; stderr: string }> {\n return new Promise((resolve, reject) => {\n const proc = spawn(command, args, { stdio: ['pipe', 'pipe', 'pipe'] });\n let stdout = '';\n let stderr = '';\n\n proc.stdout.on('data', (data: Buffer) => {\n stdout += data.toString();\n });\n proc.stderr.on('data', (data: Buffer) => {\n stderr += data.toString();\n });\n proc.on('close', (code) => {\n resolve({ exitCode: code ?? 1, stdout, stderr });\n });\n proc.on('error', reject);\n });\n}\n","/**\n * Worker class for executing Polos workflows.\n *\n * The worker:\n * 1. Registers with the orchestrator (creates/replaces deployment)\n * 2. Registers all workflow definitions in deployment_workflows table\n * 3. Receives workflows via push mode and executes them\n */\n\nimport type { Workflow } from '../core/workflow.js';\nimport { isToolWorkflow, type ToolWorkflow } from '../core/tool.js';\nimport { isAgentWorkflow, type AgentWorkflow } from '../agents/agent.js';\nimport type { Channel, ChannelContext, ChannelOutputMode } from '../channels/channel.js';\nimport type { StreamEvent } from '../types/events.js';\nimport { globalRegistry } from '../core/registry.js';\nimport { StepExecutionError } from '../core/step.js';\nimport type {\n RegisterWorkerRequest,\n QueueRegistration,\n ExecutionContext,\n} from './orchestrator-types.js';\nimport {\n OrchestratorClient,\n OrchestratorApiError,\n type OrchestratorClientConfig,\n} from './orchestrator-client.js';\nimport { WorkerServer, type WorkerExecutionData } from './worker-server.js';\nimport { executeWorkflow, serializeFinalState, type ExecutionResult } from './executor.js';\nimport { SandboxManager } from '../execution/sandbox-manager.js';\nimport { createLogger } from '../utils/logger.js';\nimport { initializeOtel, shutdownOtel } from '../features/tracing.js';\nimport { getModelId, getModelProvider } from '../llm/types.js';\n\nconst logger = createLogger({ name: 'worker' });\n\n/**\n * Configuration for the Worker.\n */\nexport interface WorkerConfig {\n /** Polos orchestrator API URL */\n apiUrl: string;\n /** API key for authentication */\n apiKey: string;\n /** Project ID */\n projectId: string;\n /** Deployment ID (unique identifier for this deployment) */\n deploymentId: string;\n /** Workflows to register and execute */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n workflows?: Workflow<any, any, any>[] | undefined;\n /** Maximum concurrent workflow executions (default: 100) */\n maxConcurrentWorkflows?: number | undefined;\n /** Worker server URL for push mode (default: http://localhost:8000) */\n workerServerUrl?: string | undefined;\n /** Port for the worker server (default: 8000) */\n port?: number | undefined;\n /** Whether running in local mode (binds to 127.0.0.1) */\n localMode?: boolean | undefined;\n /** Request timeout in milliseconds (default: 30000) */\n timeout?: number | undefined;\n /** Default notification channels for suspend events (e.g., Slack, Discord) */\n channels?: Channel[] | undefined;\n}\n\n/**\n * Worker state.\n */\ntype WorkerState = 'stopped' | 'starting' | 'running' | 'stopping';\n\n/**\n * Worker for executing Polos workflows.\n *\n * @example\n * ```typescript\n * import { Worker, defineWorkflow } from '@polos/sdk';\n * import { z } from 'zod';\n *\n * const myWorkflow = defineWorkflow({\n * id: 'my-workflow',\n * payloadSchema: z.object({ message: z.string() }),\n * }, async (ctx, payload) => {\n * return { received: payload.message };\n * });\n *\n * const worker = new Worker({\n * apiUrl: 'http://localhost:8080',\n * apiKey: process.env.POLOS_API_KEY!,\n * projectId: 'my-project',\n * deploymentId: 'my-deployment',\n * workflows: [myWorkflow],\n * });\n *\n * await worker.run();\n * ```\n */\nexport class Worker {\n private readonly config: WorkerConfig;\n private readonly orchestratorClient: OrchestratorClient;\n private readonly workflowRegistry = new Map<string, Workflow>();\n private readonly channels: Channel[];\n private readonly maxConcurrentWorkflows: number;\n private readonly workerServerUrl: string;\n private readonly port: number;\n\n /** Sandbox manager for managed sandbox lifecycle. */\n readonly sandboxManager: SandboxManager;\n\n private workerId: string | null = null;\n private workerServer: WorkerServer | null = null;\n private state: WorkerState = 'stopped';\n private heartbeatInterval: ReturnType<typeof setInterval> | null = null;\n private activeExecutions = new Map<string, { abortController: AbortController }>();\n private signalHandler: (() => void) | null = null;\n\n constructor(config: WorkerConfig) {\n this.config = config;\n this.channels = config.channels ?? [];\n this.maxConcurrentWorkflows = config.maxConcurrentWorkflows ?? 100;\n this.workerServerUrl =\n config.workerServerUrl ?? `http://localhost:${String(config.port ?? 8000)}`;\n this.port = config.port ?? 8000;\n\n // Create orchestrator client\n const clientConfig: OrchestratorClientConfig = {\n apiUrl: config.apiUrl,\n apiKey: config.apiKey,\n projectId: config.projectId,\n timeout: config.timeout,\n };\n this.orchestratorClient = new OrchestratorClient(clientConfig);\n\n this.sandboxManager = new SandboxManager('', config.projectId, this.orchestratorClient);\n\n // Register workflows\n if (config.workflows) {\n for (const workflow of config.workflows) {\n this.workflowRegistry.set(workflow.id, workflow);\n }\n }\n }\n\n /**\n * Get the worker ID (assigned by orchestrator after registration).\n */\n getWorkerId(): string | null {\n return this.workerId;\n }\n\n /**\n * Get the worker ID, throwing if not registered.\n */\n private getWorkerIdOrThrow(): string {\n if (!this.workerId) {\n throw new Error('Worker not registered');\n }\n return this.workerId;\n }\n\n /**\n * Get the current worker state.\n */\n getState(): WorkerState {\n return this.state;\n }\n\n /**\n * Get registered workflow IDs.\n */\n getWorkflowIds(): string[] {\n return Array.from(this.workflowRegistry.keys());\n }\n\n /**\n * Run the worker (blocks until shutdown).\n */\n async run(): Promise<void> {\n if (this.state !== 'stopped') {\n throw new Error(`Cannot start worker: current state is ${this.state}`);\n }\n\n try {\n await this.registerAll();\n await this.runServer();\n } catch (error) {\n this.state = 'stopped';\n logger.error('Failed to start worker', { error: String(error) });\n throw error;\n }\n }\n\n /**\n * Phase 1: Initialize tracing and register with orchestrator.\n * @internal\n */\n async registerAll(): Promise<void> {\n this.state = 'starting';\n\n logger.info('Starting worker...');\n logger.info(`Deployment ID: ${this.config.deploymentId}`);\n logger.info(`Orchestrator: ${this.config.apiUrl}`);\n logger.info(`Workflows: ${Array.from(this.workflowRegistry.keys()).join(', ')}`);\n\n // Initialize OpenTelemetry tracing\n initializeOtel({\n apiUrl: this.config.apiUrl,\n apiKey: this.config.apiKey,\n projectId: this.config.projectId,\n });\n\n // Step 1: Register worker with orchestrator\n await this.register();\n\n // Initialize sandbox manager with assigned worker ID\n this.sandboxManager.setWorkerId(this.getWorkerIdOrThrow());\n this.sandboxManager.startSweep();\n\n // Step 2: Register deployment\n await this.registerDeployment();\n\n // Step 3: Register agents, tools, and workflows\n await this.registerAgents();\n await this.registerTools();\n await this.registerWorkflows();\n\n // Step 4: Register queues (non-fatal)\n try {\n await this.registerQueues();\n } catch (error) {\n logger.warn('Failed to register queues', { error: String(error) });\n }\n\n // Step 5: Mark worker as online (non-fatal)\n try {\n await this.markOnline();\n } catch (error) {\n logger.warn('Failed to mark worker as online', { error: String(error) });\n }\n }\n\n /**\n * Phase 2: Start worker server, heartbeat, and signal handlers (blocks until shutdown).\n * @internal\n */\n async runServer(): Promise<void> {\n // Setup worker server\n await this.setupWorkerServer();\n\n // Start heartbeat loop\n this.startHeartbeat();\n\n this.state = 'running';\n logger.info('Worker is running');\n\n // Register signal handlers for graceful shutdown\n const signalHandler = (): void => {\n void this.shutdown();\n };\n process.on('SIGINT', signalHandler);\n process.on('SIGTERM', signalHandler);\n this.signalHandler = signalHandler;\n\n // Keep running until shutdown is called\n await new Promise<void>((resolve) => {\n const checkState = (): void => {\n if (this.state === 'stopping' || this.state === 'stopped') {\n resolve();\n } else {\n setTimeout(checkState, 100);\n }\n };\n checkState();\n });\n }\n\n /**\n * Gracefully shutdown the worker.\n */\n async shutdown(): Promise<void> {\n if (this.state === 'stopped' || this.state === 'stopping') {\n logger.warn(`Cannot shutdown worker: current state is ${this.state}`);\n return;\n }\n\n this.state = 'stopping';\n logger.info('Shutting down worker...');\n\n // Remove signal handlers\n if (this.signalHandler) {\n process.removeListener('SIGINT', this.signalHandler);\n process.removeListener('SIGTERM', this.signalHandler);\n this.signalHandler = null;\n }\n\n // Stop heartbeat\n if (this.heartbeatInterval) {\n clearInterval(this.heartbeatInterval);\n this.heartbeatInterval = null;\n }\n\n // Cancel all active executions\n for (const [executionId, execution] of this.activeExecutions) {\n logger.info(`Cancelling execution: ${executionId}`);\n execution.abortController.abort();\n }\n\n // Wait for executions to complete (with timeout)\n const waitTimeout = 30000; // 30 seconds\n const waitStart = Date.now();\n while (this.activeExecutions.size > 0 && Date.now() - waitStart < waitTimeout) {\n await new Promise((resolve) => setTimeout(resolve, 100));\n }\n\n if (this.activeExecutions.size > 0) {\n logger.warn(`${String(this.activeExecutions.size)} executions did not complete in time`);\n }\n\n // Destroy all managed sandboxes\n this.sandboxManager.stopSweep();\n try {\n await this.sandboxManager.destroyAll();\n } catch (err) {\n logger.warn('Failed to destroy sandboxes during shutdown', { error: String(err) });\n }\n\n // Stop worker server\n if (this.workerServer) {\n await this.workerServer.stop();\n this.workerServer = null;\n }\n\n // Flush pending spans before marking as stopped\n await shutdownOtel();\n\n this.state = 'stopped';\n logger.info('Worker shutdown complete');\n }\n\n /**\n * Register worker with orchestrator.\n */\n private async register(): Promise<void> {\n logger.info('Registering worker with orchestrator...');\n\n const request: RegisterWorkerRequest = {\n deploymentId: this.config.deploymentId,\n projectId: this.config.projectId,\n mode: 'push',\n capabilities: {\n runtime: 'typescript',\n agentIds: this.getAgentIds(),\n toolIds: this.getToolIds(),\n workflowIds: Array.from(this.workflowRegistry.keys()),\n },\n maxConcurrentExecutions: this.maxConcurrentWorkflows,\n pushEndpointUrl: this.workerServerUrl,\n };\n\n const response = await this.orchestratorClient.registerWorker(request);\n this.workerId = response.worker_id;\n\n logger.info(`Registered worker: ${this.workerId}`);\n }\n\n /**\n * Register deployment with orchestrator.\n */\n private async registerDeployment(): Promise<void> {\n logger.info('Registering deployment...');\n\n await this.orchestratorClient.registerDeployment({\n deploymentId: this.config.deploymentId,\n });\n\n logger.info(`Deployment registered: ${this.config.deploymentId}`);\n }\n\n /**\n * Get agent IDs from registered workflows.\n */\n private getAgentIds(): string[] {\n const agentIds: string[] = [];\n for (const workflow of this.workflowRegistry.values()) {\n if (isAgentWorkflow(workflow)) {\n agentIds.push(workflow.id);\n }\n }\n return agentIds;\n }\n\n /**\n * Get tool IDs from registered workflows.\n */\n private getToolIds(): string[] {\n const toolIds: string[] = [];\n for (const workflow of this.workflowRegistry.values()) {\n if (isToolWorkflow(workflow)) {\n toolIds.push(workflow.id);\n }\n }\n return toolIds;\n }\n\n /**\n * Register agent definitions with orchestrator.\n */\n private async registerAgents(): Promise<void> {\n const agents: AgentWorkflow[] = [];\n for (const workflow of this.workflowRegistry.values()) {\n if (isAgentWorkflow(workflow)) {\n agents.push(workflow);\n }\n }\n\n if (agents.length === 0) {\n return;\n }\n\n logger.info(`Registering ${String(agents.length)} agent(s)...`);\n\n for (const agent of agents) {\n // Build tool definitions for the agent\n const toolsJson = agent.tools.length > 0 ? agent.tools : undefined;\n\n // Build metadata\n const metadata: Record<string, unknown> = {};\n\n // Add stop condition function names\n if (agent.stopConditions.length > 0) {\n const stopConditionNames: string[] = [];\n for (const sc of agent.stopConditions) {\n if (sc.__stop_condition_name__) {\n stopConditionNames.push(sc.__stop_condition_name__);\n } else if (sc.name) {\n stopConditionNames.push(sc.name);\n } else {\n stopConditionNames.push('anonymous');\n }\n }\n metadata['stop_conditions'] = stopConditionNames;\n }\n\n // Add guardrail info\n if (agent.guardrails.length > 0) {\n const guardrailInfo: { type: string; name: string }[] = [];\n for (const gr of agent.guardrails) {\n const name = gr.name ?? 'anonymous';\n guardrailInfo.push({ type: 'function', name });\n }\n metadata['guardrails'] = guardrailInfo;\n }\n\n // Register agent definition with orchestrator\n await this.orchestratorClient.registerAgent({\n id: agent.id,\n deploymentId: this.config.deploymentId,\n provider: getModelProvider(agent.llm.model),\n model: getModelId(agent.llm.model),\n systemPrompt: agent.agentConfig.systemPrompt,\n tools: toolsJson,\n temperature: agent.agentConfig.temperature,\n maxOutputTokens: agent.agentConfig.maxOutputTokens,\n metadata: Object.keys(metadata).length > 0 ? metadata : null,\n });\n\n // Register in deployment_workflows\n await this.orchestratorClient.registerDeploymentWorkflow(this.config.deploymentId, {\n workflowId: agent.id,\n workflowType: 'agent',\n });\n\n logger.debug(`Registered agent: ${agent.id}`);\n }\n\n logger.info('Agents registered');\n }\n\n /**\n * Register tool definitions with orchestrator.\n */\n private async registerTools(): Promise<void> {\n const tools: ToolWorkflow[] = [];\n for (const workflow of this.workflowRegistry.values()) {\n if (isToolWorkflow(workflow)) {\n tools.push(workflow);\n }\n }\n\n if (tools.length === 0) {\n return;\n }\n\n logger.info(`Registering ${String(tools.length)} tool(s)...`);\n\n for (const tool of tools) {\n await this.orchestratorClient.registerTool({\n id: tool.id,\n deploymentId: this.config.deploymentId,\n toolType: tool.getToolType(),\n description: tool.toolDescription,\n parameters: tool.toolParameters,\n metadata: tool.getToolMetadata(),\n });\n\n // Register in deployment_workflows\n await this.orchestratorClient.registerDeploymentWorkflow(this.config.deploymentId, {\n workflowId: tool.id,\n workflowType: 'tool',\n });\n\n logger.debug(`Registered tool: ${tool.id} (type: ${tool.getToolType()})`);\n }\n\n logger.info('Tools registered');\n }\n\n /**\n * Register workflows with orchestrator.\n */\n private async registerWorkflows(): Promise<void> {\n // Filter to pure workflows only (not agents or tools)\n const pureWorkflows: Workflow[] = [];\n for (const workflow of this.workflowRegistry.values()) {\n if (!isAgentWorkflow(workflow) && !isToolWorkflow(workflow)) {\n pureWorkflows.push(workflow);\n }\n }\n\n if (pureWorkflows.length === 0) {\n logger.info('No workflows to register');\n return;\n }\n\n logger.info(`Registering ${String(pureWorkflows.length)} workflow(s)...`);\n\n for (const workflow of pureWorkflows) {\n const config = workflow.config;\n\n await this.orchestratorClient.registerDeploymentWorkflow(this.config.deploymentId, {\n workflowId: workflow.id,\n workflowType: 'workflow',\n triggerOnEvent: config.triggerOnEvent !== undefined ? true : undefined,\n scheduled: config.schedule !== undefined ? true : undefined,\n });\n\n logger.debug(`Registered workflow: ${workflow.id}`);\n }\n\n logger.info('Workflows registered');\n }\n\n /**\n * Helper to extract queue name and concurrency limit from a workflow config.\n */\n private getQueueInfo(workflow: Workflow): {\n queueName: string;\n concurrencyLimit: number | undefined;\n } {\n const config = workflow.config;\n let queueName: string;\n let concurrencyLimit: number | undefined;\n\n if (typeof config.queue === 'string') {\n queueName = config.queue;\n } else if (config.queue) {\n queueName = config.queue.name;\n concurrencyLimit = config.queue.concurrencyLimit;\n } else {\n queueName = workflow.id;\n }\n\n return { queueName, concurrencyLimit };\n }\n\n /**\n * Helper to merge a queue into the queues map with most-restrictive concurrency.\n */\n private mergeQueue(\n queues: Map<string, number | undefined>,\n queueName: string,\n concurrencyLimit: number | undefined\n ): void {\n if (queues.has(queueName)) {\n const existing = queues.get(queueName);\n if (concurrencyLimit !== undefined && existing !== undefined) {\n queues.set(queueName, Math.min(existing, concurrencyLimit));\n } else if (concurrencyLimit !== undefined) {\n queues.set(queueName, concurrencyLimit);\n }\n } else {\n queues.set(queueName, concurrencyLimit);\n }\n }\n\n /**\n * Register queues with orchestrator.\n */\n private async registerQueues(): Promise<void> {\n const queues = new Map<string, number | undefined>();\n\n // Collect from pure workflows (skip scheduled, skip agents/tools)\n for (const workflow of this.workflowRegistry.values()) {\n if (isAgentWorkflow(workflow) || isToolWorkflow(workflow)) {\n continue;\n }\n\n // Skip scheduled workflows — they get their own queues registered separately\n const config = workflow.config;\n const isSchedulable = config.schedule !== undefined;\n if (isSchedulable) {\n continue;\n }\n\n const { queueName, concurrencyLimit } = this.getQueueInfo(workflow);\n this.mergeQueue(queues, queueName, concurrencyLimit);\n }\n\n // Collect from agents\n for (const workflow of this.workflowRegistry.values()) {\n if (!isAgentWorkflow(workflow)) {\n continue;\n }\n const { queueName, concurrencyLimit } = this.getQueueInfo(workflow);\n this.mergeQueue(queues, queueName, concurrencyLimit);\n }\n\n // Collect from tools\n for (const workflow of this.workflowRegistry.values()) {\n if (!isToolWorkflow(workflow)) {\n continue;\n }\n const { queueName, concurrencyLimit } = this.getQueueInfo(workflow);\n this.mergeQueue(queues, queueName, concurrencyLimit);\n }\n\n if (queues.size === 0) {\n logger.info('No queues to register');\n return;\n }\n\n const queueList: QueueRegistration[] = Array.from(queues.entries()).map(\n ([name, concurrencyLimit]) => ({\n name,\n concurrencyLimit,\n })\n );\n\n await this.orchestratorClient.registerQueues({\n deploymentId: this.config.deploymentId,\n queues: queueList,\n });\n\n logger.info(`Registered ${String(queues.size)} queue(s)`);\n }\n\n /**\n * Mark worker as online.\n */\n private async markOnline(): Promise<void> {\n if (!this.workerId) {\n throw new Error('Worker not registered');\n }\n\n await this.orchestratorClient.markOnline(this.workerId);\n logger.info('Worker marked as online');\n }\n\n /**\n * Setup worker server for push mode.\n */\n private async setupWorkerServer(): Promise<void> {\n if (!this.workerId) {\n throw new Error('Worker not registered');\n }\n\n this.workerServer = new WorkerServer({\n workerId: this.workerId,\n maxConcurrentWorkflows: this.maxConcurrentWorkflows,\n onWorkReceived: (data) => this.handleWorkReceived(data),\n onCancelRequested: (executionId) => this.handleCancelRequested(executionId),\n port: this.port,\n localMode: this.config.localMode,\n });\n\n await this.workerServer.start();\n }\n\n /**\n * Start heartbeat loop.\n */\n private startHeartbeat(): void {\n this.heartbeatInterval = setInterval(() => {\n void this.sendHeartbeat();\n }, 30000); // 30 seconds\n }\n\n /**\n * Send heartbeat to orchestrator.\n */\n private async sendHeartbeat(): Promise<void> {\n if (!this.workerId) {\n return;\n }\n\n try {\n const response = await this.orchestratorClient.sendHeartbeat(this.workerId);\n\n if (response.re_register) {\n logger.info('Orchestrator requested re-registration');\n await this.reRegister();\n }\n } catch (error) {\n logger.warn('Heartbeat failed', { error: String(error) });\n }\n }\n\n /**\n * Re-register worker, deployment, workflows, and queues.\n */\n private async reRegister(): Promise<void> {\n try {\n await this.register();\n await this.registerDeployment();\n await this.registerAgents();\n await this.registerTools();\n await this.registerWorkflows();\n await this.registerQueues();\n await this.markOnline();\n\n // Update worker server with new worker ID\n if (this.workerServer && this.workerId) {\n this.workerServer.updateWorkerId(this.workerId);\n }\n\n // Update sandbox manager with new worker ID\n if (this.workerId) {\n this.sandboxManager.setWorkerId(this.workerId);\n }\n\n logger.info('Re-registration complete');\n } catch (error) {\n logger.error('Re-registration failed', { error: String(error) });\n }\n }\n\n /**\n * Handle work received from orchestrator.\n */\n private async handleWorkReceived(data: WorkerExecutionData): Promise<void> {\n const { executionId, workflowId } = data;\n\n // Find workflow (check local registry first, then global registry)\n let workflow = this.workflowRegistry.get(workflowId);\n if (!workflow && globalRegistry.has(workflowId)) {\n workflow = globalRegistry.get(workflowId);\n }\n if (!workflow) {\n logger.error(`Workflow not found: ${workflowId}`);\n await this.reportFailure(executionId, `Workflow not found: ${workflowId}`, false);\n return;\n }\n\n // Create abort controller for cancellation\n const abortController = new AbortController();\n this.activeExecutions.set(executionId, { abortController });\n\n // Enforce per-execution timeout\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n if (data.runTimeoutSeconds) {\n timeoutId = setTimeout(() => {\n logger.warn(`Execution ${executionId} timed out after ${String(data.runTimeoutSeconds)}s`);\n abortController.abort();\n }, data.runTimeoutSeconds * 1000);\n }\n\n let result: ExecutionResult | undefined;\n let retryableFailure = true;\n\n try {\n // Build execution context\n const context: ExecutionContext = {\n executionId,\n deploymentId: data.deploymentId,\n parentExecutionId: data.parentExecutionId,\n rootExecutionId: data.rootExecutionId,\n rootWorkflowId: data.rootWorkflowId,\n retryCount: data.retryCount,\n sessionId: data.sessionId,\n userId: data.userId,\n otelTraceparent: data.otelTraceparent,\n otelSpanId: data.otelSpanId,\n initialState: data.initialState,\n runTimeoutSeconds: data.runTimeoutSeconds,\n createdAt: data.createdAt,\n channelContext: data.channelContext,\n };\n\n // Resolve channels: workflow-level overrides channelContext overrides worker-level\n const hasWorkflowChannels = workflow.config.channels !== undefined;\n const resolvedChannels = workflow.config.channels ?? this.channels;\n\n // Execute workflow\n result = await executeWorkflow({\n workflow,\n payload: data.payload,\n context,\n orchestratorClient: this.orchestratorClient,\n workerId: this.getWorkerIdOrThrow(),\n abortSignal: abortController.signal,\n channels: resolvedChannels,\n sandboxManager: this.sandboxManager,\n channelContext: hasWorkflowChannels ? undefined : data.channelContext,\n });\n\n // Start channel bridge for output streaming (always uses channelContext, independent of channel resolution)\n if (data.channelContext) {\n this.startChannelBridge(executionId, workflowId, data.channelContext, workflow);\n }\n\n // Handle result\n await this.handleExecutionResult(executionId, workflowId, context, result);\n // Cancelled and successful executions are not retryable.\n // For non-waiting failures reported via result (not thrown), check result.retryable.\n retryableFailure = !result.success && !result.waiting && (result.retryable ?? true);\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n const stack = error instanceof Error ? error.stack : undefined;\n\n // StepExecutionError and \"tool\" workflows are not retryable\n const retryable =\n !(error instanceof StepExecutionError) && workflow.config.workflowType !== 'tool';\n\n retryableFailure = retryable;\n logger.error(`Execution failed: ${executionId}`, { error: errorMessage, stack });\n await this.reportFailure(executionId, errorMessage, retryable, stack);\n } finally {\n if (timeoutId) clearTimeout(timeoutId);\n this.activeExecutions.delete(executionId);\n\n // Notify sandbox manager — but NOT if execution is suspended (waiting)\n // or if the failure is retryable (orchestrator will re-dispatch).\n if (!result?.waiting && !retryableFailure) {\n try {\n await this.sandboxManager.onExecutionComplete(executionId);\n } catch (err) {\n logger.warn('Failed to notify sandbox manager of execution completion', {\n executionId,\n error: String(err),\n });\n }\n }\n }\n }\n\n /**\n * Handle execution result.\n */\n private async handleExecutionResult(\n executionId: string,\n workflowId: string,\n context: ExecutionContext,\n result: ExecutionResult\n ): Promise<void> {\n if (result.success) {\n await this.reportSuccess(executionId, result.result, result.finalState);\n } else if (result.waiting) {\n // Workflow is waiting (WaitError) - don't report as failure\n logger.debug(`Execution ${executionId} is waiting: ${result.error ?? 'unknown'}`);\n } else if (result.error === 'Execution cancelled') {\n await this.emitCancellationEvent(executionId, workflowId, context);\n await this.confirmCancellation(executionId);\n } else {\n await this.reportFailure(\n executionId,\n result.error ?? 'Unknown error',\n result.retryable ?? true,\n result.stack,\n result.finalState\n );\n }\n }\n\n /**\n * Handle cancel request from orchestrator.\n */\n // eslint-disable-next-line @typescript-eslint/require-await -- interface requires async\n private async handleCancelRequested(executionId: string): Promise<boolean> {\n const execution = this.activeExecutions.get(executionId);\n if (execution) {\n execution.abortController.abort();\n return true;\n }\n return false;\n }\n\n /**\n * Report successful execution.\n */\n private async reportSuccess(\n executionId: string,\n result: unknown,\n finalState?: Record<string, unknown>\n ): Promise<void> {\n try {\n await this.orchestratorClient.completeExecution(executionId, {\n result,\n workerId: this.getWorkerIdOrThrow(),\n finalState: finalState\n ? (JSON.parse(serializeFinalState(finalState)) as Record<string, unknown>)\n : undefined,\n });\n logger.debug(`Reported success: ${executionId}`);\n } catch (error) {\n if (error instanceof OrchestratorApiError && error.statusCode === 409) {\n logger.debug(`Execution ${executionId} was reassigned, ignoring completion`);\n return;\n }\n logger.error(`Failed to report success: ${executionId}`, { error: String(error) });\n }\n }\n\n /**\n * Report failed execution.\n */\n private async reportFailure(\n executionId: string,\n error: string,\n retryable: boolean,\n stack?: string,\n finalState?: Record<string, unknown>\n ): Promise<void> {\n try {\n await this.orchestratorClient.failExecution(executionId, {\n error,\n workerId: this.getWorkerIdOrThrow(),\n stack,\n retryable,\n finalState: finalState\n ? (JSON.parse(serializeFinalState(finalState)) as Record<string, unknown>)\n : undefined,\n });\n logger.debug(`Reported failure: ${executionId}`);\n } catch (err) {\n if (err instanceof OrchestratorApiError && err.statusCode === 409) {\n logger.debug(`Execution ${executionId} was reassigned, ignoring failure report`);\n return;\n }\n logger.error(`Failed to report failure: ${executionId}`, { error: String(err) });\n }\n }\n\n /**\n * Emit a cancellation event so UI/streaming clients are notified.\n */\n private async emitCancellationEvent(\n executionId: string,\n workflowId: string,\n context: ExecutionContext\n ): Promise<void> {\n try {\n const rootExecutionId = context.rootExecutionId ?? executionId;\n const rootWorkflowId = context.rootWorkflowId ?? workflowId;\n const topic = `workflow/${rootWorkflowId}/${rootExecutionId}`;\n await this.orchestratorClient.publishEvent({\n topic,\n events: [\n {\n eventType: 'workflow_cancel',\n data: { _metadata: { execution_id: executionId, workflow_id: workflowId } },\n },\n ],\n executionId,\n rootExecutionId: context.rootExecutionId,\n });\n } catch (error) {\n logger.error(`Failed to emit cancellation event for ${executionId}`, {\n error: String(error),\n });\n }\n }\n\n /**\n * Confirm cancellation.\n */\n private async confirmCancellation(executionId: string): Promise<void> {\n try {\n await this.orchestratorClient.confirmCancellation(executionId, {\n workerId: this.getWorkerIdOrThrow(),\n });\n logger.debug(`Confirmed cancellation: ${executionId}`);\n } catch (error) {\n if (error instanceof OrchestratorApiError && error.statusCode === 409) {\n logger.debug(`Execution ${executionId} was reassigned, ignoring cancellation confirmation`);\n return;\n }\n logger.error(`Failed to confirm cancellation: ${executionId}`, { error: String(error) });\n }\n }\n\n /**\n * Start a channel bridge that streams execution events back to the originating channel.\n */\n private startChannelBridge(\n executionId: string,\n workflowId: string,\n channelCtx: { channelId: string; source: Record<string, unknown> },\n workflow: Workflow\n ): void {\n const channel = this.channels.find((ch) => ch.id === channelCtx.channelId);\n if (!channel?.sendOutput) return;\n\n const outputMode: ChannelOutputMode =\n ((workflow.config as unknown as Record<string, unknown>)['channelOutputMode'] as\n | ChannelOutputMode\n | undefined) ??\n channel.outputMode ??\n 'per_step';\n if (outputMode === 'none') return;\n\n const execution = this.activeExecutions.get(executionId);\n if (!execution) return;\n\n const rootExecutionId = execution.abortController.signal.aborted ? executionId : executionId;\n const rootWorkflowId = workflowId;\n\n void (async () => {\n try {\n const stream = this.orchestratorClient.streamEvents({\n workflowId: rootWorkflowId,\n workflowRunId: rootExecutionId,\n });\n for await (const event of stream) {\n if (execution.abortController.signal.aborted) break;\n if (shouldForwardEvent(event, outputMode)) {\n await channel.sendOutput?.(channelCtx as ChannelContext, event);\n }\n }\n } catch (err) {\n logger.warn('Channel bridge error', { error: String(err), executionId });\n }\n })();\n }\n}\n\n/**\n * Determine whether an event should be forwarded based on the output mode.\n */\nfunction shouldForwardEvent(event: StreamEvent, mode: ChannelOutputMode): boolean {\n const eventType = event.eventType;\n if (mode === 'per_step') {\n return (\n eventType === 'text_delta' ||\n eventType === 'tool_call' ||\n eventType === 'step_finish' ||\n eventType === 'workflow_finish' ||\n eventType === 'agent_finish'\n );\n }\n if (mode === 'final') {\n return eventType === 'workflow_finish' || eventType === 'agent_finish';\n }\n return false;\n}\n","/**\n * Unified Polos class that combines PolosClient (submit/stream work) and Worker\n * (receive/execute work) into a single object.\n */\n\nimport {\n PolosClient,\n type EventsApi,\n type SchedulesApi,\n type ClientInvokeOptions,\n type ClientBatchWorkflowInput,\n} from './client.js';\nimport { Worker } from './runtime/worker.js';\nimport type { Workflow, WorkflowRunClient } from './core/workflow.js';\nimport type { Channel } from './channels/channel.js';\nimport { globalRegistry } from './core/registry.js';\nimport type { ExecutionHandle } from './execution-handle.js';\nimport type { GetExecutionResponse } from './runtime/orchestrator-types.js';\nimport { createLogger, configureLogging } from './utils/logger.js';\n\nconst logger = createLogger({ name: 'polos' });\n\n/**\n * Configuration for the unified Polos class.\n * All fields are optional — defaults come from environment variables.\n */\nexport interface PolosConfig {\n /** Project ID (default: POLOS_PROJECT_ID env var) */\n projectId?: string | undefined;\n /** Orchestrator API URL (default: POLOS_API_URL or http://localhost:8080) */\n apiUrl?: string | undefined;\n /** API key (default: POLOS_API_KEY env var) */\n apiKey?: string | undefined;\n /** Deployment ID (default: POLOS_DEPLOYMENT_ID or \"default\") */\n deploymentId?: string | undefined;\n /** Worker server port (default: 8000) */\n port?: number | undefined;\n /** Maximum concurrent workflow executions */\n maxConcurrentWorkflows?: number | undefined;\n /** Notification channels for suspend events */\n channels?: Channel[] | undefined;\n /** Path to a log file. When set, SDK logs are written here instead of stdout. */\n logFile?: string | undefined;\n}\n\n/**\n * Unified Polos client + worker.\n *\n * @example\n * ```typescript\n * import { Polos, defineAgent } from '@polos/sdk';\n * import { openai } from '@ai-sdk/openai';\n *\n * const agent = defineAgent({\n * id: 'weather',\n * model: openai('gpt-4o'),\n * systemPrompt: 'You are a weather assistant.',\n * });\n *\n * const polos = new Polos();\n * await polos.start();\n * const result = await agent.run(polos, { input: \"What's the weather?\" });\n * await polos.stop();\n * ```\n */\nexport class Polos implements WorkflowRunClient {\n private readonly client: PolosClient;\n private readonly worker: Worker;\n private started = false;\n private serverPromise: Promise<void> | null = null;\n\n /**\n * Events API for publishing and subscribing to events.\n */\n public readonly events: EventsApi;\n\n /**\n * Schedules API for managing workflow schedules.\n */\n public readonly schedules: SchedulesApi;\n\n constructor(config: PolosConfig = {}) {\n // Redirect SDK logs to file if requested\n if (config.logFile) {\n configureLogging({ file: config.logFile });\n }\n\n const projectId = config.projectId ?? process.env['POLOS_PROJECT_ID'] ?? '';\n const apiUrl = config.apiUrl ?? process.env['POLOS_API_URL'] ?? 'http://localhost:8080';\n const apiKey = config.apiKey ?? process.env['POLOS_API_KEY'] ?? '';\n const deploymentId = config.deploymentId ?? process.env['POLOS_DEPLOYMENT_ID'] ?? 'default';\n const port =\n config.port ??\n (process.env['POLOS_WORKER_PORT'] ? Number(process.env['POLOS_WORKER_PORT']) : 8000);\n\n // Create client\n this.client = new PolosClient({\n projectId,\n apiUrl,\n apiKey,\n deploymentId,\n });\n\n // Discover workflows from globalRegistry — they auto-register\n // when defined with defineAgent(), defineTool(), defineWorkflow().\n const workflows: Workflow[] = globalRegistry.getAll();\n\n // Create worker\n this.worker = new Worker({\n apiUrl,\n apiKey,\n projectId,\n deploymentId,\n workflows,\n maxConcurrentWorkflows: config.maxConcurrentWorkflows,\n port,\n localMode: true,\n channels: config.channels,\n });\n\n // Expose APIs from client\n this.events = this.client.events;\n this.schedules = this.client.schedules;\n }\n\n /**\n * Start the worker in background (non-blocking).\n *\n * Registers with orchestrator, starts worker server, begins heartbeat.\n * Returns once registration is complete so the caller can immediately\n * invoke workflows.\n */\n async start(): Promise<void> {\n if (this.started) {\n return;\n }\n\n // Phase 1: register (blocking — must complete before we return)\n await this.worker.registerAll();\n this.started = true;\n\n // Phase 2: start server in background (non-blocking)\n this.serverPromise = this.worker.runServer().catch((err: unknown) => {\n logger.error('Worker server error', { error: String(err) });\n });\n\n logger.info('Polos started');\n }\n\n /**\n * Start the worker and block until shutdown signal (SIGINT/SIGTERM).\n *\n * This is the deployment mode — equivalent to Worker.run().\n * Use for servers, Kubernetes, Docker, etc.\n */\n async serve(): Promise<void> {\n await this.start();\n if (this.serverPromise) {\n await this.serverPromise;\n }\n }\n\n /**\n * Gracefully stop the worker and clean up.\n */\n async stop(): Promise<void> {\n if (!this.started) {\n return;\n }\n\n await this.worker.shutdown();\n\n if (this.serverPromise) {\n // Wait for server to finish shutting down\n await this.serverPromise;\n this.serverPromise = null;\n }\n\n this.started = false;\n logger.info('Polos stopped');\n }\n\n /**\n * Get the underlying PolosClient.\n * Needed for APIs that require PolosClient explicitly (e.g., agent.stream()).\n */\n getClient(): PolosClient {\n return this.client;\n }\n\n // ── WorkflowRunClient interface ──\n\n /**\n * Invoke a workflow (fire and forget).\n */\n async invoke(\n workflow: string | Workflow,\n payload?: unknown,\n options?: ClientInvokeOptions\n ): Promise<ExecutionHandle> {\n return this.client.invoke(workflow, payload, options);\n }\n\n /**\n * Invoke multiple workflows in batch.\n */\n async batchInvoke(\n items: ClientBatchWorkflowInput[],\n options?: {\n sessionId?: string;\n userId?: string;\n parentExecutionId?: string;\n rootWorkflowId?: string;\n rootExecutionId?: string;\n stepKey?: string;\n waitForSubworkflow?: boolean;\n }\n ): Promise<ExecutionHandle[]> {\n return this.client.batchInvoke(items, options);\n }\n\n /**\n * Resume a suspended execution.\n */\n async resume(\n suspendWorkflowId: string,\n suspendExecutionId: string,\n suspendStepKey: string,\n data: unknown\n ): Promise<void> {\n return this.client.resume(suspendWorkflowId, suspendExecutionId, suspendStepKey, data);\n }\n\n /**\n * Get execution details.\n */\n async getExecution(executionId: string): Promise<GetExecutionResponse> {\n return this.client.getExecution(executionId);\n }\n\n /**\n * Cancel an execution.\n */\n async cancelExecution(executionId: string): Promise<boolean> {\n return this.client.cancelExecution(executionId);\n }\n}\n","/**\n * Queue configuration for workflow execution.\n *\n * Queues control concurrency and ordering of workflow executions.\n */\n\n/**\n * Options for creating a Queue.\n */\nexport interface QueueOptions {\n /** Maximum concurrent executions in this queue */\n concurrencyLimit?: number | undefined;\n}\n\n/**\n * Queue class for named execution queues.\n *\n * @example\n * ```typescript\n * import { Queue, defineWorkflow } from '@polos/sdk';\n *\n * const dbQueue = new Queue('database-ops', { concurrencyLimit: 5 });\n *\n * const dbWorkflow = defineWorkflow({\n * id: 'db-operation',\n * queue: dbQueue,\n * }, async (ctx, payload) => {\n * // ...\n * });\n * ```\n */\nexport class Queue {\n /** Queue name */\n readonly name: string;\n\n /** Maximum concurrent executions (undefined = no limit) */\n readonly concurrencyLimit?: number | undefined;\n\n constructor(name: string, options?: QueueOptions) {\n this.name = name;\n this.concurrencyLimit = options?.concurrencyLimit;\n }\n\n /**\n * Convert to queue configuration object.\n */\n toConfig(): QueueConfig {\n const config: QueueConfig = { name: this.name };\n if (this.concurrencyLimit !== undefined) {\n config.concurrencyLimit = this.concurrencyLimit;\n }\n return config;\n }\n}\n\n/**\n * Queue configuration object (used in workflow config).\n */\nexport interface QueueConfig {\n /** Queue name */\n name: string;\n /** Maximum concurrent executions */\n concurrencyLimit?: number | undefined;\n}\n\n/**\n * Normalize queue configuration from various input formats.\n */\nexport function normalizeQueueConfig(\n queue: string | Queue | QueueConfig | undefined\n): QueueConfig | undefined {\n if (queue === undefined) {\n return undefined;\n }\n\n if (typeof queue === 'string') {\n return { name: queue };\n }\n\n if (queue instanceof Queue) {\n return queue.toConfig();\n }\n\n return queue;\n}\n\n/**\n * Default queue name.\n */\nexport const DEFAULT_QUEUE = 'default';\n\n/**\n * Get the queue name from various input formats.\n */\nexport function getQueueName(queue: string | Queue | QueueConfig | undefined): string {\n if (queue === undefined) {\n return DEFAULT_QUEUE;\n }\n\n if (typeof queue === 'string') {\n return queue;\n }\n\n if (queue instanceof Queue) {\n return queue.name;\n }\n\n return queue.name;\n}\n","/**\n * Batch workflow triggering utilities.\n *\n * Matches Python sdk/python/polos/runtime/batch.py.\n */\n\nimport type { PolosClient, ClientBatchWorkflowInput } from '../client.js';\nimport type { ExecutionHandle } from '../execution-handle.js';\nimport { AgentRunConfig } from '../core/step.js';\nimport { assertNotInExecutionContext } from './execution-context.js';\n\n// Re-export AgentRunConfig so existing imports from this module still work\nexport { AgentRunConfig };\n\n/**\n * Invoke multiple different workflows in a single batch and return handles immediately.\n *\n * This function cannot be called from within a workflow or agent.\n * Use step.batchInvoke() to call workflows from within workflows.\n *\n * Matches Python batch_invoke().\n */\nexport async function batchInvoke(\n client: PolosClient,\n workflows: ClientBatchWorkflowInput[],\n sessionId?: string,\n userId?: string\n): Promise<ExecutionHandle[]> {\n assertNotInExecutionContext('batchInvoke()', 'step.batchInvoke()');\n\n return client.batchInvoke(workflows, {\n ...(sessionId !== undefined && { sessionId }),\n ...(userId !== undefined && { userId }),\n });\n}\n\n/**\n * Invoke multiple agents in parallel and return execution handles.\n *\n * This helper is intended for use with agent.withInput(), which returns\n * AgentRunConfig instances.\n *\n * Matches Python batch_agent_invoke().\n *\n * @example\n * ```typescript\n * const handles = await batchAgentInvoke(client, [\n * grammarAgent.withInput(\"Check this\"),\n * toneAgent.withInput(\"Check this too\"),\n * ]);\n * ```\n */\nexport async function batchAgentInvoke(\n client: PolosClient,\n agents: AgentRunConfig[]\n): Promise<ExecutionHandle[]> {\n const workflows: ClientBatchWorkflowInput[] = agents.map((config) => ({\n workflow: config.agent,\n payload: {\n input: config.input,\n streaming: config.streaming,\n session_id: config.sessionId,\n user_id: config.userId,\n ...config.kwargs,\n },\n initialState: config.initialState,\n runTimeoutSeconds: config.runTimeoutSeconds,\n }));\n\n return batchInvoke(client, workflows);\n}\n","/**\n * Agent-related type definitions.\n *\n * Note: Core agent implementation types (StopCondition, StopConditionContext,\n * StepInfo, ToolResultInfo, AgentWorkflow, DefineAgentConfig) are defined in\n * src/agents/ and exported from there. This file contains supplementary types\n * used by the public API (Guardrail, Agent, AgentStream, etc.) and placeholder\n * types for future client-side features.\n */\n\nimport type { LanguageModel, ModelMessage } from 'ai';\n\n// Backwards-compat alias: CoreMessage was renamed to ModelMessage in ai v6\ntype CoreMessage = ModelMessage;\nimport type { ZodType } from 'zod';\nimport type { WorkflowContext, QueueConfig, Hook } from './workflow.js';\nimport type { TokenUsage, ToolCall } from './llm.js';\n\n/**\n * Tool definition with Zod schemas for input/output.\n */\nexport interface Tool<TInput = unknown, TOutput = unknown> {\n /** Unique tool identifier */\n id: string;\n /** Tool description (shown to LLM) */\n description: string;\n /** Zod schema for input validation */\n inputSchema: ZodType<TInput>;\n /** Zod schema for output validation */\n outputSchema: ZodType<TOutput>;\n /** Tool handler function */\n handler: ToolHandler<TInput, TOutput>;\n}\n\n/**\n * Tool handler function type.\n */\nexport type ToolHandler<TInput, TOutput> = (\n ctx: WorkflowContext,\n input: TInput\n) => Promise<TOutput>;\n\n/**\n * Configuration for defining a tool.\n */\nexport interface ToolConfig<TInput = unknown, TOutput = unknown> {\n /** Unique tool identifier */\n id: string;\n /** Tool description (shown to LLM) */\n description: string;\n /** Zod schema for input validation */\n inputSchema: ZodType<TInput>;\n /** Zod schema for output validation */\n outputSchema: ZodType<TOutput>;\n}\n\n/**\n * Guardrail function type for validating LLM outputs.\n */\nexport type Guardrail = (\n ctx: WorkflowContext,\n guardrailCtx: GuardrailContext\n) => Promise<GuardrailResult>;\n\n/**\n * Context passed to guardrails.\n */\nexport interface GuardrailContext {\n /** Text content from LLM (if any) */\n content?: string;\n /** Tool calls from LLM (if any) */\n toolCalls: ToolCall[];\n /** Messages so far in the conversation */\n messages: CoreMessage[];\n}\n\n/**\n * Result from a guardrail execution.\n */\nexport interface GuardrailResult {\n /** Whether to continue execution */\n continue: boolean;\n /** Error message if guardrail failed */\n error?: string;\n /** Modified content to use instead */\n modifiedContent?: string;\n /** Modified tool calls to use instead */\n modifiedToolCalls?: ToolCall[];\n}\n\nexport const GuardrailResult = {\n /** Continue execution without modifications */\n continue: (): GuardrailResult => ({ continue: true }),\n\n /** Continue execution with modifications */\n continueWith: (options: {\n modifiedContent?: string;\n modifiedToolCalls?: ToolCall[];\n }): GuardrailResult => {\n const result: GuardrailResult = { continue: true };\n if (options.modifiedContent !== undefined) {\n result.modifiedContent = options.modifiedContent;\n }\n if (options.modifiedToolCalls !== undefined) {\n result.modifiedToolCalls = options.modifiedToolCalls;\n }\n return result;\n },\n\n /** Stop execution with an error */\n fail: (error: string): GuardrailResult => ({\n continue: false,\n error,\n }),\n};\n\n/**\n * Configuration for defining an agent (placeholder for client-side usage).\n */\nexport interface AgentConfig<TOutput = string, TState = unknown> {\n /** Unique agent identifier */\n id: string;\n /** Vercel AI SDK model instance */\n model: LanguageModel;\n /** System prompt for the agent */\n systemPrompt: string;\n /** Tools available to the agent */\n tools?: Tool[];\n\n /** LLM generation configuration */\n temperature?: number;\n maxTokens?: number;\n topP?: number;\n\n /** Queue assignment for execution */\n queue?: string | QueueConfig;\n\n /** Zod schema for structured output */\n outputSchema?: ZodType<TOutput>;\n\n /** Lifecycle hooks */\n onStart?: Hook<string, TState>;\n onEnd?: Hook<string, TState>;\n onAgentStepStart?: Hook<string, TState>;\n onAgentStepEnd?: Hook<string, TState>;\n onToolStart?: Hook<string, TState>;\n onToolEnd?: Hook<string, TState>;\n\n /** Guardrails for output validation */\n guardrails?: Guardrail[];\n /** Max retries when guardrail fails */\n guardrailMaxRetries?: number;\n}\n\n/**\n * Result from running an agent (client-side).\n */\nexport interface AgentResult<TOutput = string> {\n /** Agent output (typed if outputSchema provided) */\n output: TOutput;\n /** All messages in the conversation */\n messages: CoreMessage[];\n /** Token usage statistics */\n usage: TokenUsage;\n /** Steps executed by the agent */\n steps: AgentStep[];\n}\n\n/**\n * A single step in agent execution (client-side view).\n */\nexport interface AgentStep {\n /** Type of step */\n type: 'thinking' | 'tool_call' | 'tool_result' | 'text';\n /** Text content (for thinking/text steps) */\n content?: string;\n /** Tool name (for tool_call/tool_result steps) */\n toolName?: string;\n /** Tool input (for tool_call steps) */\n toolInput?: unknown;\n /** Tool output (for tool_result steps) */\n toolOutput?: unknown;\n /** Token usage for this step */\n usage?: TokenUsage;\n /** When this step occurred */\n timestamp: Date;\n}\n\n/**\n * Agent instance with run/stream methods.\n */\nexport interface Agent<TOutput = string, TState = unknown> {\n /** Agent identifier */\n id: string;\n /** Agent configuration */\n config: AgentConfig<TOutput, TState>;\n\n /**\n * Run the agent with a user message and wait for result.\n */\n run(message: string, options?: AgentRunOptions): Promise<AgentResult<TOutput>>;\n\n /**\n * Run the agent and stream the response.\n */\n stream(message: string, options?: AgentRunOptions): Promise<AgentStream<TOutput>>;\n}\n\n/**\n * Options for running an agent.\n */\nexport interface AgentRunOptions {\n /** Initial conversation messages */\n messages?: CoreMessage[];\n /** Timeout in milliseconds */\n timeout?: number;\n /** Initial state */\n initialState?: unknown;\n}\n\n/**\n * Stream of agent events.\n */\nexport interface AgentStream<TOutput = string> extends AsyncIterable<AgentStreamEvent> {\n /** Async iterable of text chunks only */\n textChunks: AsyncIterable<string>;\n\n /** Accumulate all text chunks into a single string */\n text(): Promise<string>;\n\n /** Wait for final result */\n result(): Promise<AgentResult<TOutput>>;\n}\n\n/**\n * Events emitted during agent streaming.\n * Matches Python's actual SSE event types.\n */\nexport type AgentStreamEvent =\n | { type: 'stream_start'; step: number }\n | { type: 'text_delta'; step: number; chunkIndex: number; content?: string }\n | { type: 'tool_call'; step: number; chunkIndex: number; toolCall?: unknown }\n | { type: 'agent_finish'; result: unknown };\n","/**\n * Ask-user tool — lets agents ask questions and receive answers from the user.\n *\n * Uses ctx.step.suspend() to pause the workflow, emit a suspend event with a\n * _form schema, and wait for the user to respond via client.resume(). Supports\n * both structured form fields and simple free-text responses.\n */\n\nimport { z } from 'zod';\nimport { defineTool } from '../core/tool.js';\nimport type { ToolWorkflow } from '../core/tool.js';\n\nconst askUserInputSchema = z.object({\n question: z.string().describe('The question to ask the user'),\n title: z.string().optional().describe('Short title for the question (shown as heading)'),\n fields: z\n .array(\n z.object({\n key: z.string().describe('Unique key for this field'),\n type: z.enum(['text', 'textarea', 'number', 'boolean', 'select']).describe('Field type'),\n label: z.string().describe('Label shown to user'),\n description: z.string().optional().describe('Help text for the field'),\n required: z.boolean().optional().describe('Whether this field is required'),\n options: z\n .array(\n z.object({\n label: z.string(),\n value: z.string(),\n })\n )\n .optional()\n .describe('Options for select fields'),\n })\n )\n .optional()\n .describe(\n 'Structured form fields for the response. If omitted, shows a single text response field.'\n ),\n});\n\n/**\n * Create the ask_user tool for agent-to-user communication.\n *\n * When an agent calls this tool, the workflow suspends and emits a suspend\n * event with a `_form` schema. The client handles the event, collects the\n * user's response, and resumes the workflow with the response data.\n *\n * @example\n * ```typescript\n * import { createAskUserTool } from '@polos/sdk';\n *\n * const askUser = createAskUserTool();\n * // Add to agent tools array\n * ```\n */\nexport function createAskUserTool(): ToolWorkflow {\n return defineTool(\n {\n id: 'ask_user',\n description:\n 'Ask the user a question and wait for their response. ' +\n 'Use this when you need clarification, a decision, or any input from the user. ' +\n 'You can define structured fields (text, select, boolean, etc.) ' +\n 'for specific response formats, or omit fields for a free-text response.',\n inputSchema: askUserInputSchema,\n },\n async (ctx, input) => {\n const fields = input.fields ?? [\n {\n key: 'response',\n type: 'textarea' as const,\n label: input.question,\n required: true,\n },\n ];\n\n const askId = await ctx.step.uuid('_ask_user_id');\n const response = await ctx.step.suspend(`ask_user_${askId}`, {\n data: {\n _form: {\n title: input.title ?? 'Agent Question',\n description: input.question,\n fields,\n },\n _source: 'ask_user',\n _tool: 'ask_user',\n },\n });\n\n return (response as Record<string, unknown> | undefined)?.['data'] ?? {};\n }\n ) as ToolWorkflow;\n}\n","/**\n * Web search tool — lets agents search the web for current information.\n *\n * Defaults to the Tavily Search API using raw fetch() (no additional\n * dependencies). Users can plug in any search provider via a custom\n * function.\n *\n * @example\n * ```typescript\n * import { createWebSearchTool } from '@polos/sdk';\n *\n * // Tavily with env var (TAVILY_API_KEY)\n * const webSearch = createWebSearchTool();\n *\n * // Custom provider\n * const webSearch = createWebSearchTool({\n * search: async (query, opts) => {\n * const res = await mySearchApi(query, opts.maxResults);\n * return { query, results: res.items };\n * },\n * });\n * ```\n */\n\nimport { z } from 'zod';\nimport { defineTool } from '../core/tool.js';\nimport type { ToolWorkflow, ToolApproval } from '../core/tool.js';\n\n// ── Result types (provider-agnostic) ─────────────────────────────────\n\n/** A single search result item. */\nexport interface WebSearchResultItem {\n title: string;\n url: string;\n /** Snippet or summary of the page content. */\n content: string;\n /** Relevance score, 0–1. */\n score?: number | undefined;\n /** Publication date in ISO 8601 format. */\n publishedDate?: string | undefined;\n}\n\n/** Full search result returned by the tool. */\nexport interface WebSearchResult {\n query: string;\n results: WebSearchResultItem[];\n /** AI-generated summary (Tavily feature). */\n answer?: string | undefined;\n}\n\n// ── Options passed to the search function ────────────────────────────\n\n/** Options forwarded to the search function at call time. */\nexport interface WebSearchOptions {\n maxResults: number;\n topic: 'general' | 'news';\n}\n\n// ── Custom provider interface ────────────────────────────────────────\n\n/** Signature for a custom search provider function. */\nexport type WebSearchFunction = (\n query: string,\n options: WebSearchOptions\n) => Promise<WebSearchResult>;\n\n// ── Configuration ────────────────────────────────────────────────────\n\n/** Tavily-specific configuration knobs. */\nexport interface TavilySearchConfig {\n /** Tavily API key. Falls back to the TAVILY_API_KEY environment variable. */\n apiKey?: string;\n /** Search depth. @default 'basic' */\n searchDepth?: 'basic' | 'advanced';\n /** Include an AI-generated answer in the response. @default true */\n includeAnswer?: boolean;\n /** Include raw page content in results. @default false */\n includeRawContent?: boolean;\n /** Tavily API base URL. @default 'https://api.tavily.com' */\n baseUrl?: string;\n}\n\n/** Configuration for createWebSearchTool(). */\nexport interface WebSearchToolConfig extends TavilySearchConfig {\n /** Custom search provider. When set, overrides the built-in Tavily implementation. */\n search?: WebSearchFunction;\n /** Default maximum results per query. @default 5 */\n maxResults?: number;\n /** Default topic filter. @default 'general' */\n topic?: 'general' | 'news';\n /** Tool identifier exposed to the LLM. @default 'web_search' */\n toolId?: string;\n /** Require human approval before execution. */\n approval?: ToolApproval;\n}\n\n// ── LLM-facing input schema ──────────────────────────────────────────\n\nconst webSearchInputSchema = z.object({\n query: z.string().describe('The search query'),\n maxResults: z.number().optional().describe('Maximum number of results to return'),\n topic: z\n .enum(['general', 'news'])\n .optional()\n .describe('Topic filter: general web search or news'),\n});\n\ntype WebSearchInput = z.infer<typeof webSearchInputSchema>;\n\n// ── Tavily implementation (internal) ─────────────────────────────────\n\ninterface TavilyResponse {\n query: string;\n answer?: string;\n results: {\n title: string;\n url: string;\n content: string;\n score?: number;\n published_date?: string;\n raw_content?: string;\n }[];\n}\n\nfunction createTavilySearchFn(config: TavilySearchConfig): WebSearchFunction {\n return async (query: string, options: WebSearchOptions): Promise<WebSearchResult> => {\n const apiKey = config.apiKey ?? process.env['TAVILY_API_KEY'];\n if (!apiKey) {\n throw new Error(\n 'Tavily API key is required. Provide it via the apiKey option or set the TAVILY_API_KEY environment variable.'\n );\n }\n\n const baseUrl = (config.baseUrl ?? 'https://api.tavily.com').replace(/\\/+$/, '');\n\n const body = {\n query,\n max_results: options.maxResults,\n search_depth: config.searchDepth ?? 'basic',\n include_answer: config.includeAnswer ?? true,\n include_raw_content: config.includeRawContent ?? false,\n topic: options.topic,\n };\n\n const response = await fetch(`${baseUrl}/search`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(body),\n });\n\n if (!response.ok) {\n let errorMessage: string;\n try {\n const errorBody = (await response.json()) as Record<string, unknown>;\n errorMessage =\n typeof errorBody['detail'] === 'string' ? errorBody['detail'] : JSON.stringify(errorBody);\n } catch {\n errorMessage = await response.text();\n }\n throw new Error(`Tavily API error (${String(response.status)}): ${errorMessage}`);\n }\n\n const data = (await response.json()) as TavilyResponse;\n\n return {\n query: data.query,\n answer: data.answer,\n results: data.results.map((r) => ({\n title: r.title,\n url: r.url,\n content: r.content,\n score: r.score,\n publishedDate: r.published_date,\n })),\n };\n };\n}\n\n// ── Factory ──────────────────────────────────────────────────────────\n\n/**\n * Create a web search tool for agent use.\n *\n * By default uses the Tavily Search API via raw fetch(). Pass a custom\n * `search` function to use any other provider.\n *\n * @example\n * ```typescript\n * // Tavily with env var\n * const webSearch = createWebSearchTool();\n *\n * // Tavily with explicit key\n * const webSearch = createWebSearchTool({ apiKey: 'tvly-xxx' });\n *\n * // Custom provider\n * const webSearch = createWebSearchTool({\n * search: async (query, opts) => {\n * const res = await myApi(query, opts.maxResults);\n * return { query, results: res.items };\n * },\n * });\n * ```\n */\nexport function createWebSearchTool(config?: WebSearchToolConfig): ToolWorkflow {\n const toolId = config?.toolId ?? 'web_search';\n const defaultMaxResults = config?.maxResults ?? 5;\n const defaultTopic = config?.topic ?? 'general';\n\n // Search function resolved lazily — custom provider or Tavily default.\n // For Tavily, the API key is resolved at call time (not factory time).\n const searchFn: WebSearchFunction = config?.search ?? createTavilySearchFn(config ?? {});\n\n return defineTool(\n {\n id: toolId,\n description:\n 'Search the web for current information. ' +\n 'Returns a list of relevant results with titles, URLs, and content snippets.',\n inputSchema: webSearchInputSchema,\n approval: config?.approval,\n },\n async (ctx, input: WebSearchInput) => {\n const options: WebSearchOptions = {\n maxResults: input.maxResults ?? defaultMaxResults,\n topic: input.topic ?? defaultTopic,\n };\n\n const result = await ctx.step.run('web_search', () => searchFn(input.query, options), {\n input: { query: input.query, options },\n });\n\n return result;\n }\n ) as ToolWorkflow;\n}\n","/**\n * Security utilities for the execution framework.\n *\n * Provides allowlist evaluation for command security and path safety\n * checks for file operations.\n */\n\nimport { resolve } from 'node:path';\n\n/**\n * Match a text string against a simple glob pattern.\n * Supports `*` as a wildcard that matches any sequence of characters.\n *\n * @param text - The text to match\n * @param pattern - Glob pattern with `*` wildcards\n * @returns Whether the text matches the pattern\n */\nexport function matchGlob(text: string, pattern: string): boolean {\n // Escape regex special chars except *, then convert * to .*\n const escaped = pattern.replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&');\n const regexStr = `^${escaped.replace(/\\*/g, '.*')}$`;\n return new RegExp(regexStr).test(text);\n}\n\n/**\n * Evaluate a command against an allowlist of glob patterns.\n *\n * Matches the full command string against each pattern.\n * Patterns support `*` wildcards (e.g., `node *`, `npm *`, `*`).\n *\n * @param command - The shell command to check\n * @param patterns - Array of glob patterns to match against\n * @returns Whether the command matches any pattern in the allowlist\n */\nexport function evaluateAllowlist(command: string, patterns: string[]): boolean {\n const trimmed = command.trim();\n return patterns.some((pattern) => matchGlob(trimmed, pattern));\n}\n\n/**\n * Check whether a resolved path stays within a restriction directory.\n *\n * @param resolvedPath - The fully resolved path to check\n * @param restriction - The base directory the path must stay within\n * @returns Whether the path is within the restriction\n */\nexport function isWithinRestriction(resolvedPath: string, restriction: string): boolean {\n const base = resolve(restriction);\n return resolvedPath === base || resolvedPath.startsWith(base + '/');\n}\n\n/**\n * Assert that a file path stays within a restriction directory.\n * Throws if path traversal is detected.\n *\n * @param filePath - The file path to check\n * @param restriction - The base directory paths must stay within\n * @throws Error if the resolved path escapes the restriction directory\n */\nexport function assertSafePath(filePath: string, restriction: string): void {\n const base = resolve(restriction);\n const resolved = resolve(base, filePath);\n\n if (!isWithinRestriction(resolved, base)) {\n throw new Error(`Path traversal detected: \"${filePath}\" resolves outside of \"${restriction}\"`);\n }\n}\n","/**\n * Exec tool — run shell commands inside the execution environment.\n */\n\nimport { z } from 'zod';\nimport { defineTool } from '../../core/tool.js';\nimport type { ToolWorkflow } from '../../core/tool.js';\nimport type { WorkflowContext } from '../../core/context.js';\nimport type { ExecutionEnvironment, ExecResult, ExecToolConfig } from '../types.js';\nimport { evaluateAllowlist } from '../security.js';\n\n/**\n * Resume data shape from the approval form.\n */\ninterface ApprovalResumeData {\n data?: {\n approved?: boolean;\n allow_always?: boolean;\n feedback?: string;\n };\n}\n\n/**\n * Suspend for user approval of a command.\n */\nasync function requestApproval(\n ctx: WorkflowContext,\n command: string,\n env: ExecutionEnvironment\n): Promise<{ approved: boolean; feedback?: string }> {\n const envInfo = env.getInfo();\n const approvalId = await ctx.step.uuid('_approval_id');\n const response = await ctx.step.suspend<Record<string, unknown>, ApprovalResumeData>(\n `approve_exec_${approvalId}`,\n {\n data: {\n _form: {\n title: 'Approve command execution',\n description: `The agent wants to run a shell command in the ${envInfo.type} environment.`,\n fields: [\n {\n key: 'approved',\n type: 'boolean',\n label: 'Approve this command?',\n required: true,\n default: false,\n },\n {\n key: 'allow_always',\n type: 'boolean',\n label: 'Always allow this command in the future?',\n required: false,\n default: false,\n },\n {\n key: 'feedback',\n type: 'textarea',\n label: 'Feedback for the agent (optional)',\n description: 'If rejecting, tell the agent what to do instead.',\n required: false,\n },\n ],\n context: {\n command,\n cwd: env.getCwd(),\n environment: envInfo.type,\n },\n },\n _source: 'exec_security',\n _tool: 'exec',\n },\n }\n );\n\n const feedback = response.data?.feedback;\n return {\n approved: response.data?.approved === true,\n ...(feedback ? { feedback } : {}),\n };\n}\n\n/**\n * Build a rejected ExecResult.\n * Includes user feedback in stderr so the agent can adjust its approach.\n */\nfunction rejectedResult(command: string, feedback?: string): ExecResult {\n let stderr = `Command rejected by user: ${command}`;\n if (feedback) {\n stderr += `\\nUser feedback: ${feedback}`;\n }\n return {\n exitCode: -1,\n stdout: '',\n stderr,\n durationMs: 0,\n truncated: false,\n };\n}\n\n/**\n * Create the exec tool for running shell commands.\n */\nexport function createExecTool(\n getEnv: () => Promise<ExecutionEnvironment>,\n config?: ExecToolConfig\n): ToolWorkflow {\n return defineTool(\n {\n id: 'exec',\n description:\n 'Execute a shell command in the sandbox environment. Returns stdout, stderr, and exit code. ' +\n 'Use this for running builds, tests, installing packages, or any shell operation.',\n inputSchema: z.object({\n command: z.string().describe('The shell command to execute'),\n cwd: z.string().optional().describe('Working directory for the command'),\n env: z.record(z.string(), z.string()).optional().describe('Environment variables to set'),\n timeout: z.number().optional().describe('Timeout in seconds (default: 300)'),\n }),\n },\n async (ctx, input) => {\n const env = await getEnv();\n\n if (config?.security === 'approval-always') {\n const result = await requestApproval(ctx, input.command, env);\n if (!result.approved) return rejectedResult(input.command, result.feedback);\n } else if (config?.security === 'allowlist') {\n if (!evaluateAllowlist(input.command, config.allowlist ?? [])) {\n const result = await requestApproval(ctx, input.command, env);\n if (!result.approved) return rejectedResult(input.command, result.feedback);\n }\n }\n // 'allow-always' or undefined → no check\n\n return env.exec(input.command, {\n cwd: input.cwd,\n env: input.env,\n timeout: input.timeout ?? config?.timeout,\n });\n }\n ) as ToolWorkflow;\n}\n","/**\n * Path-based approval for sandbox tools.\n *\n * When pathRestriction is set, tools (read, write, edit, glob, grep) allow\n * operations within the restricted path without approval. Operations\n * outside the restriction suspend for user approval.\n */\n\nimport { resolve } from 'node:path';\nimport type { WorkflowContext } from '../../core/context.js';\nimport { isWithinRestriction } from '../security.js';\n\n/**\n * Configuration for path-restricted approval on read-only tools.\n */\nexport interface PathRestrictionConfig {\n /** Directory to allow without approval. Paths outside require approval. */\n pathRestriction: string;\n}\n\n/**\n * Resume data shape from the path approval form.\n */\ninterface PathApprovalResumeData {\n data?: { approved?: boolean; feedback?: string };\n}\n\n/**\n * Check whether a resolved path is within the restriction.\n */\nexport function isPathAllowed(resolvedPath: string, restriction: string): boolean {\n return isWithinRestriction(resolvedPath, resolve(restriction));\n}\n\n/**\n * Suspend for user approval when accessing a path outside the restriction.\n * Returns the approval result. Throws if rejected.\n */\nexport async function requirePathApproval(\n ctx: WorkflowContext,\n toolName: string,\n targetPath: string,\n restriction: string\n): Promise<void> {\n const approvalId = await ctx.step.uuid('_approval_id');\n const response = await ctx.step.suspend<Record<string, unknown>, PathApprovalResumeData>(\n `approve_${toolName}_${approvalId}`,\n {\n data: {\n _form: {\n title: `${toolName}: access outside workspace`,\n description: `The agent wants to ${toolName} a path outside the workspace.`,\n fields: [\n {\n key: 'approved',\n type: 'boolean',\n label: 'Allow this operation?',\n required: true,\n default: false,\n },\n {\n key: 'feedback',\n type: 'textarea',\n label: 'Feedback for the agent (optional)',\n description: 'If rejecting, tell the agent what to do instead.',\n required: false,\n },\n ],\n context: {\n tool: toolName,\n path: targetPath,\n restriction,\n },\n },\n _source: 'path_approval',\n _tool: toolName,\n },\n }\n );\n\n if (response.data?.approved !== true) {\n const feedback = response.data?.feedback;\n throw new Error(\n `Access to \"${targetPath}\" was rejected by the user.${feedback ? ` Feedback: ${feedback}` : ''}`\n );\n }\n}\n","/**\n * Read tool — read file contents from the execution environment.\n *\n * When pathRestriction is set, reads within the restriction proceed\n * without approval. Reads outside the restriction suspend for user approval.\n */\n\nimport { resolve } from 'node:path';\nimport { z } from 'zod';\nimport { defineTool } from '../../core/tool.js';\nimport type { ToolWorkflow } from '../../core/tool.js';\nimport type { ExecutionEnvironment } from '../types.js';\nimport type { PathRestrictionConfig } from './path-approval.js';\nimport { isPathAllowed, requirePathApproval } from './path-approval.js';\n\n/**\n * Create the read tool for reading file contents.\n */\nexport function createReadTool(\n getEnv: () => Promise<ExecutionEnvironment>,\n pathConfig?: PathRestrictionConfig\n): ToolWorkflow {\n return defineTool(\n {\n id: 'read',\n description:\n 'Read the contents of a file. Returns the file content as text. ' +\n 'Optionally specify offset (line number to start from, 0-based) and limit (number of lines).',\n inputSchema: z.object({\n path: z.string().describe('Path to the file to read'),\n offset: z.number().optional().describe('Line offset to start reading from (0-based)'),\n limit: z.number().optional().describe('Maximum number of lines to return'),\n }),\n },\n async (ctx, input) => {\n const env = await getEnv();\n\n // Check path restriction — approve if outside\n if (pathConfig?.pathRestriction) {\n const resolved = resolve(env.getCwd(), input.path);\n if (!isPathAllowed(resolved, pathConfig.pathRestriction)) {\n await requirePathApproval(ctx, 'read', resolved, pathConfig.pathRestriction);\n }\n }\n\n let content = await env.readFile(input.path);\n\n // Apply offset/limit if specified\n if (input.offset !== undefined || input.limit !== undefined) {\n const lines = content.split('\\n');\n const start = input.offset ?? 0;\n const end = input.limit !== undefined ? start + input.limit : lines.length;\n content = lines.slice(start, end).join('\\n');\n }\n\n return { content, path: input.path };\n }\n ) as ToolWorkflow;\n}\n","/**\n * Write tool — create or overwrite files in the execution environment.\n *\n * When pathRestriction is set, writes within the restriction proceed\n * without approval. Writes outside the restriction suspend for user approval.\n * Set approval to 'always' to require approval for every write, or 'none'\n * to skip approval entirely (overrides path restriction).\n */\n\nimport { resolve } from 'node:path';\nimport { z } from 'zod';\nimport { defineTool } from '../../core/tool.js';\nimport type { ToolWorkflow, ToolApproval } from '../../core/tool.js';\nimport type { ExecutionEnvironment } from '../types.js';\nimport type { PathRestrictionConfig } from './path-approval.js';\nimport { isPathAllowed, requirePathApproval } from './path-approval.js';\n\nexport interface WriteToolConfig {\n /** Explicit approval override. 'always' = approve every write, 'none' = never approve. */\n approval?: ToolApproval;\n /** Path restriction config — writes inside are allowed, outside require approval. */\n pathConfig?: PathRestrictionConfig;\n}\n\n/**\n * Create the write tool for writing file contents.\n */\nexport function createWriteTool(\n getEnv: () => Promise<ExecutionEnvironment>,\n config?: WriteToolConfig\n): ToolWorkflow {\n return defineTool(\n {\n id: 'write',\n description:\n 'Write content to a file. Creates the file if it does not exist, or overwrites it if it does. ' +\n 'Parent directories are created automatically.',\n inputSchema: z.object({\n path: z.string().describe('Path to the file to write'),\n content: z.string().describe('Content to write to the file'),\n }),\n // Only use blanket approval if explicitly set to 'always'\n approval: config?.approval === 'always' ? 'always' : undefined,\n },\n async (ctx, input) => {\n const env = await getEnv();\n\n // Path-restricted approval: approve if outside cwd, skip if inside\n if (!config?.approval && config?.pathConfig?.pathRestriction) {\n const resolved = resolve(env.getCwd(), input.path);\n if (!isPathAllowed(resolved, config.pathConfig.pathRestriction)) {\n await requirePathApproval(ctx, 'write', resolved, config.pathConfig.pathRestriction);\n }\n }\n\n await env.writeFile(input.path, input.content);\n return { success: true, path: input.path };\n }\n ) as ToolWorkflow;\n}\n","/**\n * Edit tool — find-and-replace text in files in the execution environment.\n *\n * When pathRestriction is set, edits within the restriction proceed\n * without approval. Edits outside the restriction suspend for user approval.\n * Set approval to 'always' to require approval for every edit, or 'none'\n * to skip approval entirely (overrides path restriction).\n */\n\nimport { resolve } from 'node:path';\nimport { z } from 'zod';\nimport { defineTool } from '../../core/tool.js';\nimport type { ToolWorkflow, ToolApproval } from '../../core/tool.js';\nimport type { ExecutionEnvironment } from '../types.js';\nimport type { PathRestrictionConfig } from './path-approval.js';\nimport { isPathAllowed, requirePathApproval } from './path-approval.js';\n\nexport interface EditToolConfig {\n /** Explicit approval override. 'always' = approve every edit, 'none' = never approve. */\n approval?: ToolApproval;\n /** Path restriction config — edits inside are allowed, outside require approval. */\n pathConfig?: PathRestrictionConfig;\n}\n\n/**\n * Create the edit tool for find-and-replace in files.\n */\nexport function createEditTool(\n getEnv: () => Promise<ExecutionEnvironment>,\n config?: EditToolConfig\n): ToolWorkflow {\n return defineTool(\n {\n id: 'edit',\n description:\n 'Edit a file by replacing an exact string match. The old_text must match exactly ' +\n '(including whitespace and indentation). Use this for precise code modifications.',\n inputSchema: z.object({\n path: z.string().describe('Path to the file to edit'),\n old_text: z.string().describe('Exact text to find and replace'),\n new_text: z.string().describe('Text to replace the old_text with'),\n }),\n // Only use blanket approval if explicitly set to 'always'\n approval: config?.approval === 'always' ? 'always' : undefined,\n },\n async (ctx, input) => {\n const env = await getEnv();\n\n // Path-restricted approval: approve if outside cwd, skip if inside\n if (!config?.approval && config?.pathConfig?.pathRestriction) {\n const resolved = resolve(env.getCwd(), input.path);\n if (!isPathAllowed(resolved, config.pathConfig.pathRestriction)) {\n await requirePathApproval(ctx, 'edit', resolved, config.pathConfig.pathRestriction);\n }\n }\n\n const content = await env.readFile(input.path);\n\n if (!content.includes(input.old_text)) {\n throw new Error(\n `old_text not found in ${input.path}. Make sure the text matches exactly, ` +\n 'including whitespace and indentation.'\n );\n }\n\n const newContent = content.replace(input.old_text, input.new_text);\n await env.writeFile(input.path, newContent);\n\n return { success: true, path: input.path };\n }\n ) as ToolWorkflow;\n}\n","/**\n * Glob tool — find files by pattern in the execution environment.\n *\n * When pathRestriction is set, searches within the restriction proceed\n * without approval. Custom cwd outside the restriction suspends for approval.\n */\n\nimport { resolve } from 'node:path';\nimport { z } from 'zod';\nimport { defineTool } from '../../core/tool.js';\nimport type { ToolWorkflow } from '../../core/tool.js';\nimport type { ExecutionEnvironment } from '../types.js';\nimport type { PathRestrictionConfig } from './path-approval.js';\nimport { isPathAllowed, requirePathApproval } from './path-approval.js';\n\n/**\n * Create the glob tool for finding files by pattern.\n */\nexport function createGlobTool(\n getEnv: () => Promise<ExecutionEnvironment>,\n pathConfig?: PathRestrictionConfig\n): ToolWorkflow {\n return defineTool(\n {\n id: 'glob',\n description:\n 'Find files matching a glob pattern. Returns a list of file paths. ' +\n 'Use this to discover files in the project structure.',\n inputSchema: z.object({\n pattern: z.string().describe('Glob pattern to match (e.g., \"*.ts\", \"src/**/*.js\")'),\n cwd: z.string().optional().describe('Directory to search in'),\n ignore: z.array(z.string()).optional().describe('Patterns to exclude from results'),\n }),\n },\n async (ctx, input) => {\n const env = await getEnv();\n\n // Check path restriction on custom cwd\n if (pathConfig?.pathRestriction && input.cwd) {\n const resolved = resolve(env.getCwd(), input.cwd);\n if (!isPathAllowed(resolved, pathConfig.pathRestriction)) {\n await requirePathApproval(ctx, 'glob', resolved, pathConfig.pathRestriction);\n }\n }\n\n const files = await env.glob(input.pattern, {\n cwd: input.cwd,\n ignore: input.ignore,\n });\n return { files };\n }\n ) as ToolWorkflow;\n}\n","/**\n * Grep tool — search file contents by pattern in the execution environment.\n *\n * When pathRestriction is set, searches within the restriction proceed\n * without approval. Custom cwd outside the restriction suspends for approval.\n */\n\nimport { resolve } from 'node:path';\nimport { z } from 'zod';\nimport { defineTool } from '../../core/tool.js';\nimport type { ToolWorkflow } from '../../core/tool.js';\nimport type { ExecutionEnvironment } from '../types.js';\nimport type { PathRestrictionConfig } from './path-approval.js';\nimport { isPathAllowed, requirePathApproval } from './path-approval.js';\n\n/**\n * Create the grep tool for searching file contents.\n */\nexport function createGrepTool(\n getEnv: () => Promise<ExecutionEnvironment>,\n pathConfig?: PathRestrictionConfig\n): ToolWorkflow {\n return defineTool(\n {\n id: 'grep',\n description:\n 'Search file contents for a pattern using grep. Returns matching lines with file paths ' +\n 'and line numbers. Use this to find code patterns, references, or specific text.',\n inputSchema: z.object({\n pattern: z.string().describe('Search pattern (regex supported)'),\n cwd: z.string().optional().describe('Directory to search in'),\n include: z\n .array(z.string())\n .optional()\n .describe('File patterns to include (e.g., [\"*.ts\", \"*.js\"])'),\n maxResults: z\n .number()\n .optional()\n .describe('Maximum number of matches to return (default: 100)'),\n contextLines: z.number().optional().describe('Number of context lines around each match'),\n }),\n },\n async (ctx, input) => {\n const env = await getEnv();\n\n // Check path restriction on custom cwd\n if (pathConfig?.pathRestriction && input.cwd) {\n const resolved = resolve(env.getCwd(), input.cwd);\n if (!isPathAllowed(resolved, pathConfig.pathRestriction)) {\n await requirePathApproval(ctx, 'grep', resolved, pathConfig.pathRestriction);\n }\n }\n\n const matches = await env.grep(input.pattern, {\n cwd: input.cwd,\n include: input.include,\n maxResults: input.maxResults,\n contextLines: input.contextLines,\n });\n return { matches };\n }\n ) as ToolWorkflow;\n}\n","/**\n * Sandbox tools factory.\n *\n * Creates a set of tools (exec, read, write, edit, glob, grep) that share\n * a managed sandbox. The sandbox is created lazily on first tool use\n * via the SandboxManager injected through the execution context.\n *\n * @example\n * ```typescript\n * import { defineAgent, sandboxTools } from '@polos/sdk';\n *\n * // Per-execution (default) — sandbox dies when the workflow finishes\n * const agent = defineAgent({\n * id: 'solver',\n * tools: sandboxTools({\n * env: 'docker',\n * docker: { image: 'node:20', workspaceDir: '/path/to/project' },\n * }),\n * });\n *\n * // Per-session — sandbox lives across turns\n * const agent2 = defineAgent({\n * id: 'coder',\n * tools: sandboxTools({\n * scope: 'session',\n * env: 'docker',\n * docker: { image: 'node:20', workspaceDir: '/path/to/project' },\n * }),\n * });\n * ```\n */\n\nimport type { ToolWorkflow } from '../core/tool.js';\nimport type { ExecutionEnvironment, SandboxToolsConfig, ExecToolConfig } from './types.js';\nimport type { Sandbox } from './sandbox.js';\nimport { getExecutionContext } from '../runtime/execution-context.js';\nimport { createExecTool } from './tools/exec.js';\nimport { createReadTool } from './tools/read.js';\nimport { createWriteTool } from './tools/write.js';\nimport { createEditTool } from './tools/edit.js';\nimport { createGlobTool } from './tools/glob.js';\nimport { createGrepTool } from './tools/grep.js';\n\n/**\n * Create sandbox tools for AI agents.\n *\n * Returns an array of ToolWorkflow that can be passed directly to defineAgent().\n * All tools share a single managed sandbox that is lazily created on first use.\n * Lifecycle is managed by the SandboxManager — no manual cleanup needed.\n */\nexport function sandboxTools(config?: SandboxToolsConfig): ToolWorkflow[] {\n // Cache keyed by rootExecutionId so all tool sub-workflows within the same\n // agent run share one sandbox. Each tool call runs as a separate sub-workflow\n // with its own executionId, but rootExecutionId is stable across them.\n const sandboxCache = new Map<string, Sandbox>();\n\n async function getEnv(): Promise<ExecutionEnvironment> {\n const ctx = getExecutionContext();\n if (!ctx) {\n throw new Error(\n 'sandboxTools requires an execution context. ' +\n 'Ensure tools are called within a workflow execution.'\n );\n }\n\n const { executionId, rootExecutionId, sessionId, sandboxManager } = ctx;\n if (!sandboxManager) {\n throw new Error(\n 'No SandboxManager found in execution context. ' +\n 'Ensure the Worker is configured to inject sandboxManager.'\n );\n }\n\n // Use rootExecutionId as cache key so all tool calls in the same agent\n // run share one sandbox. Falls back to executionId for top-level workflows.\n const cacheKey = rootExecutionId ?? executionId;\n\n // Check cache first\n const cached = sandboxCache.get(cacheKey);\n if (cached && !cached.destroyed) {\n return cached.getEnvironment();\n }\n\n // Create or retrieve sandbox via manager\n const sandbox = await sandboxManager.getOrCreateSandbox(config ?? {}, {\n executionId: cacheKey,\n sessionId,\n });\n sandboxCache.set(cacheKey, sandbox);\n\n return sandbox.getEnvironment();\n }\n\n // Validate environment type eagerly\n const envType = config?.env ?? 'docker';\n if (envType === 'e2b') {\n throw new Error('E2B environment is not yet implemented.');\n }\n\n // For local mode, default exec security to 'approval-always' (no sandbox isolation)\n const effectiveExecConfig: ExecToolConfig | undefined =\n envType === 'local' && !config?.exec?.security\n ? { ...config?.exec, security: 'approval-always' }\n : config?.exec;\n\n // Path restriction — used by read, write, edit, glob, grep for approval gating\n const pathConfig = config?.local?.pathRestriction\n ? { pathRestriction: config.local.pathRestriction }\n : undefined;\n\n // fileApproval overrides path-restriction behavior for write/edit.\n // 'always' = approve every write/edit regardless of path.\n // 'none' = never approve (skip path restriction too).\n // undefined = use path restriction (approve only outside cwd).\n const fileApproval = config?.fileApproval;\n\n // Build write/edit config: explicit approval overrides path restriction\n const writeEditConfig = fileApproval\n ? { approval: fileApproval }\n : pathConfig\n ? { pathConfig }\n : undefined;\n\n // Determine which tools to include\n const include = new Set(\n config?.tools ?? (['exec', 'read', 'write', 'edit', 'glob', 'grep'] as const)\n );\n\n const tools: ToolWorkflow[] = [];\n\n if (include.has('exec')) tools.push(createExecTool(getEnv, effectiveExecConfig));\n if (include.has('read')) tools.push(createReadTool(getEnv, pathConfig));\n if (include.has('write')) tools.push(createWriteTool(getEnv, writeEditConfig));\n if (include.has('edit')) tools.push(createEditTool(getEnv, writeEditConfig));\n if (include.has('glob')) tools.push(createGlobTool(getEnv, pathConfig));\n if (include.has('grep')) tools.push(createGrepTool(getEnv, pathConfig));\n\n return tools;\n}\n","/**\n * Slack channel implementation — sends a Block Kit message with a \"Respond\"\n * link button when an agent suspends.\n *\n * Uses native `fetch` (Node 18+) — no @slack/web-api dependency required.\n */\n\nimport type { Channel, ChannelContext, ChannelOutputMode, SuspendNotification } from './channel.js';\nimport type { StreamEvent } from '../types/events.js';\n\n/**\n * Configuration for the Slack notification channel.\n */\nexport interface SlackChannelConfig {\n /** Slack bot token (xoxb-...) */\n botToken: string;\n /** Default Slack channel for notifications (e.g., \"#agent-notifications\") */\n defaultChannel: string;\n /** Slack signing secret for verifying inbound webhooks */\n signingSecret?: string;\n}\n\n/** Minimal Slack Block Kit block type. */\ninterface SlackBlock {\n type: string;\n text?: { type: string; text: string };\n elements?: Record<string, unknown>[];\n}\n\n/**\n * Slack notification channel that posts Block Kit messages with a \"Respond\"\n * link button pointing to the approval page.\n */\nexport class SlackChannel implements Channel {\n readonly id = 'slack';\n readonly outputMode: ChannelOutputMode = 'per_step';\n private readonly config: SlackChannelConfig;\n\n constructor(config: SlackChannelConfig) {\n if (!config.botToken.startsWith('xoxb-')) {\n throw new Error(\n 'Invalid Slack bot token: must start with \"xoxb-\". ' +\n \"Use the Bot User OAuth Token from your Slack app's OAuth & Permissions page.\"\n );\n }\n this.config = config;\n }\n\n async notify(notification: SuspendNotification): Promise<void> {\n const overrides = notification.channelOverrides;\n const channel = (overrides?.['channel'] as string | undefined) ?? this.config.defaultChannel;\n const threadTs = overrides?.['thread_ts'] as string | undefined;\n const blocks = this.buildBlocks(notification);\n const text = notification.title ?? 'Agent needs your input';\n\n await this.postMessage(channel, threadTs, text, blocks);\n }\n\n async sendOutput(context: ChannelContext, event: StreamEvent): Promise<void> {\n const channel = context.source['channel'] as string;\n const threadTs = context.source['threadTs'] as string | undefined;\n if (!channel) return;\n\n const text = this.formatOutputEvent(event);\n if (!text) return;\n\n await this.postMessage(channel, threadTs, text);\n }\n\n private async postMessage(\n channel: string,\n threadTs: string | undefined,\n text: string,\n blocks?: SlackBlock[]\n ): Promise<void> {\n const body: Record<string, unknown> = { channel, text };\n if (threadTs) body['thread_ts'] = threadTs;\n if (blocks) body['blocks'] = blocks;\n\n const response = await fetch('https://slack.com/api/chat.postMessage', {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${this.config.botToken}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(body),\n });\n\n const data = (await response.json()) as { ok: boolean; error?: string };\n if (!data.ok) {\n throw new Error(`Slack API error: ${data.error ?? 'unknown'}`);\n }\n }\n\n private formatOutputEvent(event: StreamEvent): string | null {\n const eventType = event.eventType;\n\n if (eventType === 'workflow_finish' || eventType === 'agent_finish') {\n const metadata = event.data['_metadata'] as Record<string, unknown> | undefined;\n const result = event.data['result'];\n const error = event.data['error'] as string | undefined;\n const workflowId = metadata?.['workflow_id'] as string | undefined;\n if (error) {\n return `\\u274C *${workflowId ?? 'Workflow'} failed:* ${error}`;\n }\n const resultStr = typeof result === 'string' ? result : JSON.stringify(result, null, 2);\n if (resultStr) {\n return `\\u2705 *${workflowId ?? 'Workflow'} finished:*\\n${resultStr}`;\n }\n return `\\u2705 *${workflowId ?? 'Workflow'} finished*`;\n }\n\n if (eventType === 'tool_call') {\n const toolCall = event.data['tool_call'] as Record<string, unknown> | undefined;\n if (toolCall) {\n const fn = toolCall['function'] as Record<string, unknown> | undefined;\n const name = fn?.['name'] as string | undefined;\n if (name) {\n return `\\uD83D\\uDD27 Calling tool: \\`${name}\\``;\n }\n }\n return null;\n }\n\n if (eventType === 'step_finish') {\n const stepKey = event.data['step_key'] as string | undefined;\n const error = event.data['error'] as string | undefined;\n if (error) {\n return `\\u26A0\\uFE0F Step \\`${stepKey ?? 'unknown'}\\` failed: ${error}`;\n }\n return null;\n }\n\n // text_delta: skip individual deltas to avoid noise\n return null;\n }\n\n private buildBlocks(n: SuspendNotification): SlackBlock[] {\n const blocks: SlackBlock[] = [];\n\n // Header\n blocks.push({\n type: 'header',\n text: { type: 'plain_text', text: n.title ?? 'Agent needs your input' },\n });\n\n // Description\n if (n.description) {\n blocks.push({\n type: 'section',\n text: { type: 'mrkdwn', text: n.description },\n });\n }\n\n // Source/tool metadata\n if (n.source || n.tool) {\n const parts: string[] = [];\n if (n.source) parts.push(`*Source:* ${n.source}`);\n if (n.tool) parts.push(`*Tool:* \\`${n.tool}\\``);\n blocks.push({\n type: 'context',\n elements: [{ type: 'mrkdwn', text: parts.join(' | ') }],\n });\n }\n\n // Context data (tool arguments, etc.)\n if (n.context && Object.keys(n.context).length > 0) {\n const contextText = JSON.stringify(n.context, null, 2);\n blocks.push({\n type: 'section',\n text: { type: 'mrkdwn', text: '```' + contextText + '```' },\n });\n }\n\n // Expiry warning\n if (n.expiresAt) {\n blocks.push({\n type: 'context',\n elements: [{ type: 'mrkdwn', text: `Expires: ${n.expiresAt}` }],\n });\n }\n\n // Action buttons — inline Approve/Reject for simple approvals, link button otherwise\n if (this.isSimpleApproval(n)) {\n const approveValue = JSON.stringify({\n executionId: n.executionId,\n stepKey: n.stepKey,\n approved: true,\n });\n const rejectValue = JSON.stringify({\n executionId: n.executionId,\n stepKey: n.stepKey,\n approved: false,\n });\n blocks.push({\n type: 'actions',\n elements: [\n {\n type: 'button',\n action_id: 'polos_approve',\n text: { type: 'plain_text', text: 'Approve' },\n style: 'primary',\n value: approveValue,\n },\n {\n type: 'button',\n action_id: 'polos_reject',\n text: { type: 'plain_text', text: 'Reject' },\n style: 'danger',\n value: rejectValue,\n },\n {\n type: 'button',\n text: { type: 'plain_text', text: 'View Details' },\n url: n.approvalUrl,\n },\n ],\n });\n } else {\n blocks.push({\n type: 'actions',\n elements: [\n {\n type: 'button',\n text: { type: 'plain_text', text: 'Respond' },\n url: n.approvalUrl,\n style: 'primary',\n },\n ],\n });\n }\n\n return blocks;\n }\n\n private isSimpleApproval(n: SuspendNotification): boolean {\n const fields = n.formFields;\n if (!fields || fields.length === 0) return false;\n return fields.some((f) => f['key'] === 'approved' && f['type'] === 'boolean');\n }\n}\n"]}
|