@codemation/core 1.0.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/CHANGELOG.md +312 -0
  2. package/dist/{EngineRuntimeRegistration.types-BP6tsaNP.d.ts → EngineRuntimeRegistration.types-D1fyApMI.d.ts} +2 -2
  3. package/dist/{EngineWorkflowRunnerService-DzOCa1BW.d.cts → EngineRuntimeRegistration.types-pB3FnzqR.d.cts} +17 -17
  4. package/dist/{InMemoryRunDataFactory-1iz7_SnO.d.cts → InMemoryRunDataFactory-Xw7v4-sj.d.cts} +31 -29
  5. package/dist/InMemoryRunEventBusRegistry-VM3OWnHo.cjs +47 -0
  6. package/dist/InMemoryRunEventBusRegistry-VM3OWnHo.cjs.map +1 -0
  7. package/dist/InMemoryRunEventBusRegistry-sM4z4n_i.js +41 -0
  8. package/dist/InMemoryRunEventBusRegistry-sM4z4n_i.js.map +1 -0
  9. package/dist/{RunIntentService-BqhmdoA1.d.ts → RunIntentService-BE9CAkbf.d.ts} +966 -471
  10. package/dist/{RunIntentService-S-1lW-gS.d.cts → RunIntentService-siBSjaaY.d.cts} +859 -493
  11. package/dist/bootstrap/index.cjs +5 -2
  12. package/dist/bootstrap/index.d.cts +212 -135
  13. package/dist/bootstrap/index.d.ts +4 -4
  14. package/dist/bootstrap/index.js +3 -3
  15. package/dist/{bootstrap-BfZE19lK.cjs → bootstrap-Cm5ruQxx.cjs} +253 -2
  16. package/dist/bootstrap-Cm5ruQxx.cjs.map +1 -0
  17. package/dist/{bootstrap-jqh1kCNI.js → bootstrap-D3r505ko.js} +236 -3
  18. package/dist/bootstrap-D3r505ko.js.map +1 -0
  19. package/dist/{index-CGs3Hnoz.d.ts → index-DeLl1Tne.d.ts} +599 -219
  20. package/dist/index.cjs +323 -176
  21. package/dist/index.cjs.map +1 -1
  22. package/dist/index.d.cts +511 -80
  23. package/dist/index.d.ts +3 -3
  24. package/dist/index.js +299 -166
  25. package/dist/index.js.map +1 -1
  26. package/dist/{runtime-u6O644ST.js → runtime-BGNbRnqs.js} +933 -74
  27. package/dist/runtime-BGNbRnqs.js.map +1 -0
  28. package/dist/{runtime-DWKfb0BI.cjs → runtime-DKXJwTNv.cjs} +1027 -72
  29. package/dist/runtime-DKXJwTNv.cjs.map +1 -0
  30. package/dist/testing.cjs +4 -4
  31. package/dist/testing.cjs.map +1 -1
  32. package/dist/testing.d.cts +2 -2
  33. package/dist/testing.d.ts +2 -2
  34. package/dist/testing.js +3 -3
  35. package/package.json +7 -2
  36. package/src/ai/AiHost.ts +9 -0
  37. package/src/authoring/DefinedCollectionRegistry.ts +17 -0
  38. package/src/authoring/defineCollection.types.ts +181 -0
  39. package/src/authoring/definePollingTrigger.types.ts +396 -0
  40. package/src/authoring/definePollingTriggerInternals.ts +74 -0
  41. package/src/authoring/index.ts +19 -0
  42. package/src/bootstrap/index.ts +9 -0
  43. package/src/bootstrap/runtime/EngineRuntimeRegistrar.ts +8 -0
  44. package/src/browser.ts +1 -0
  45. package/src/contracts/CodemationTelemetryAttributeNames.ts +6 -0
  46. package/src/contracts/NoOpNodeExecutionTelemetry.ts +2 -11
  47. package/src/contracts/NoOpTelemetrySpanScope.ts +46 -10
  48. package/src/contracts/assertionTypes.ts +63 -0
  49. package/src/contracts/baseTypes.ts +12 -0
  50. package/src/contracts/collectionTypes.ts +44 -0
  51. package/src/contracts/credentialTypes.ts +23 -1
  52. package/src/contracts/executionPersistenceContracts.ts +30 -0
  53. package/src/contracts/index.ts +4 -0
  54. package/src/contracts/runTypes.ts +37 -1
  55. package/src/contracts/runtimeTypes.ts +42 -0
  56. package/src/contracts/telemetryTypes.ts +8 -0
  57. package/src/contracts/testTriggerTypes.ts +66 -0
  58. package/src/contracts/workflowTypes.ts +36 -7
  59. package/src/contracts.ts +59 -0
  60. package/src/events/ConnectionInvocationEventPublisher.ts +46 -0
  61. package/src/events/index.ts +1 -0
  62. package/src/events/runEvents.ts +74 -0
  63. package/src/execution/ChildExecutionScopeFactory.ts +55 -0
  64. package/src/execution/DefaultExecutionContextFactory.ts +6 -0
  65. package/src/execution/ExecutionTelemetryCostTrackingDecoratorFactory.ts +18 -0
  66. package/src/execution/NodeExecutor.ts +10 -2
  67. package/src/execution/NodeInstanceFactory.ts +13 -1
  68. package/src/execution/NodeInstantiationError.ts +16 -0
  69. package/src/execution/NodeRunStateWriter.ts +7 -0
  70. package/src/execution/NodeRunStateWriterFactory.ts +7 -0
  71. package/src/execution/WorkflowRunExecutionContextFactory.ts +3 -0
  72. package/src/execution/index.ts +2 -0
  73. package/src/index.ts +8 -0
  74. package/src/orchestration/AbortControllerFactory.ts +9 -0
  75. package/src/orchestration/NodeExecutionRequestHandlerService.ts +1 -0
  76. package/src/orchestration/RunContinuationService.ts +3 -0
  77. package/src/orchestration/RunStartService.ts +114 -2
  78. package/src/orchestration/TestSuiteOrchestrator.ts +350 -0
  79. package/src/orchestration/TestSuiteRunIdFactory.ts +11 -0
  80. package/src/orchestration/TriggerRuntimeService.ts +34 -7
  81. package/src/orchestration/index.ts +9 -0
  82. package/src/runtime/EngineFactory.ts +12 -0
  83. package/src/triggers/polling/PollingTriggerDedupWindow.ts +23 -0
  84. package/src/triggers/polling/PollingTriggerLogger.ts +18 -0
  85. package/src/triggers/polling/PollingTriggerRuntime.ts +122 -0
  86. package/src/triggers/polling/index.ts +5 -0
  87. package/src/types/index.ts +12 -9
  88. package/src/workflow/definition/NodeIterationIdFactory.ts +26 -0
  89. package/src/workflow/dsl/NodeIdSlugifier.ts +18 -0
  90. package/src/workflow/dsl/WorkflowBuilder.ts +71 -3
  91. package/src/workflow/dsl/WorkflowDefinitionError.ts +15 -0
  92. package/src/workflow/index.ts +3 -0
  93. package/dist/InMemoryRunEventBusRegistry-B0_C4OnP.cjs +0 -262
  94. package/dist/InMemoryRunEventBusRegistry-B0_C4OnP.cjs.map +0 -1
  95. package/dist/InMemoryRunEventBusRegistry-C2U83Hmv.js +0 -238
  96. package/dist/InMemoryRunEventBusRegistry-C2U83Hmv.js.map +0 -1
  97. package/dist/bootstrap-BfZE19lK.cjs.map +0 -1
  98. package/dist/bootstrap-jqh1kCNI.js.map +0 -1
  99. package/dist/runtime-DWKfb0BI.cjs.map +0 -1
  100. package/dist/runtime-u6O644ST.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["context: DefinedNodeRunContext<TConfig, TBindings>","payload: DefineNodeExecuteArgs<TConfig, TInputJson>","name: string","id?: string","definition: DefinedNode<TKey, TConfig, TInputJson, TOutputJson, TBindings>","z","current: z.ZodTypeAny","name: string","ZodError","name: string","node: TNodeConfig","node","isItemExpr","node","out: AgentMessageDto[]","isItemExpr","messages: AgentMessageDto[]","AgentConnectionNodeCollector: AgentConnectionNodeCollectorApi","collected: AgentConnectionNodeDescriptor[]","ConnectionNodeIdFactory","tool","inner: WorkflowExecutionRepository","eventBus: RunEventBus","now: () => Date","ItemsInputNormalizer"],"sources":["../src/contracts/Clock.ts","../src/authoring/DefinedNodeRegistry.ts","../src/authoring/defineNode.types.ts","../src/authoring/defineCredential.types.ts","../src/ai/CallableToolKindToken.ts","../src/ai/CallableToolConfig.ts","../src/ai/CallableToolFactory.ts","../src/authoring/callableTool.types.ts","../src/ai/NodeBackedToolConfig.ts","../src/ai/AgentConfigInspectorFactory.ts","../src/ai/AgentToolFactory.ts","../src/ai/AgentMessageConfigNormalizerFactory.ts","../src/ai/AiHost.ts","../src/ai/AgentConnectionNodeCollector.ts","../src/workflow/definition/ConnectionInvocationIdFactory.ts","../src/workflow/graph/ExecutableGraph.ts","../src/workflow/graph/DefaultWorkflowGraphFactory.ts","../src/events/EventPublishingWorkflowExecutionRepository.ts","../src/serialization/ItemsInputNormalizer.ts"],"sourcesContent":["/** Port for time; inject `SystemClock` in production and a fake/test clock in tests. */\nexport interface Clock {\n now(): Date;\n}\n\nexport class SystemClock implements Clock {\n now(): Date {\n return new Date();\n }\n}\n","import type { DefinedNode } from \"./defineNode.types\";\n\nexport class DefinedNodeRegistry {\n private static readonly definitions = new Map<\n string,\n DefinedNode<string, Record<string, unknown>, unknown, unknown>\n >();\n\n static register(definition: DefinedNode<string, Record<string, unknown>, unknown, unknown>): void {\n this.definitions.set(definition.key, definition);\n }\n\n static resolve(key: string): DefinedNode<string, Record<string, unknown>, unknown, unknown> | undefined {\n return this.definitions.get(key);\n }\n}\n","import type {\n AnyCredentialType,\n CredentialJsonRecord,\n CredentialRequirement,\n CredentialTypeId,\n} from \"../contracts/credentialTypes\";\nimport type { ParamDeep } from \"../contracts/params\";\nimport type { RunnableNode, RunnableNodeExecuteArgs, NodeExecutionContext } from \"../contracts/runtimeTypes\";\nimport type { Item, Items, RunnableNodeConfig } from \"../contracts/workflowTypes\";\nimport type { TypeToken } from \"../di\";\nimport { node as persistedNode } from \"../runtime-types/runtimeTypeDecorators.types\";\nimport type { ZodType } from \"zod\";\nimport { z } from \"zod\";\nimport { DefinedNodeRegistry } from \"./DefinedNodeRegistry\";\n\ntype MaybePromise<TValue> = TValue | Promise<TValue>;\n\ntype ResolvableCredentialType = AnyCredentialType | CredentialTypeId;\n\ntype SessionForCredentialType<TCredential extends ResolvableCredentialType> = TCredential extends AnyCredentialType\n ? Awaited<ReturnType<TCredential[\"createSession\"]>>\n : unknown;\n\nexport type DefinedNodeCredentialBinding =\n | ResolvableCredentialType\n | Readonly<{\n readonly type: ResolvableCredentialType | ReadonlyArray<ResolvableCredentialType>;\n readonly label?: string;\n readonly optional?: true;\n readonly helpText?: string;\n readonly helpUrl?: string;\n }>;\n\nexport type DefinedNodeCredentialBindings = Readonly<Record<string, DefinedNodeCredentialBinding>>;\n\ntype SessionForBinding<TBinding extends DefinedNodeCredentialBinding> =\n TBinding extends Readonly<{ type: infer TType }>\n ? TType extends ReadonlyArray<infer TEntry>\n ? SessionForCredentialType<TEntry & ResolvableCredentialType>\n : SessionForCredentialType<TType & ResolvableCredentialType>\n : SessionForCredentialType<TBinding & ResolvableCredentialType>;\n\nexport type DefinedNodeCredentialAccessors<TBindings extends DefinedNodeCredentialBindings | undefined> =\n TBindings extends DefinedNodeCredentialBindings\n ? Readonly<{\n [TKey in keyof TBindings]: () => Promise<SessionForBinding<TBindings[TKey]>>;\n }>\n : Readonly<Record<string, never>>;\n\nexport interface DefinedNodeRunContext<\n TConfig extends CredentialJsonRecord,\n TBindings extends DefinedNodeCredentialBindings | undefined,\n> {\n readonly config: TConfig;\n readonly credentials: DefinedNodeCredentialAccessors<TBindings>;\n readonly execution: NodeExecutionContext<RunnableNodeConfig<TConfig, unknown>>;\n}\n\n/**\n * Arguments for {@link defineNode} `execute` (engine `ctx` matches {@link RunnableNode.execute};\n * the second callback parameter adds {@link DefinedNodeRunContext} for credential accessors).\n */\nexport type DefineNodeExecuteArgs<TConfig extends CredentialJsonRecord, TInputJson> = Readonly<{\n input: TInputJson;\n item: Item;\n itemIndex: number;\n items: Items;\n ctx: NodeExecutionContext<RunnableNodeConfig<TInputJson, unknown> & Readonly<{ config: TConfig }>>;\n}>;\n\nexport type DefinedNodeConfigInput<TConfigResolved extends CredentialJsonRecord, TItemJson> = ParamDeep<\n TConfigResolved,\n TItemJson\n>;\n\nexport interface DefinedNode<\n TKey extends string,\n TConfig extends CredentialJsonRecord,\n TInputJson,\n TOutputJson,\n _TBindings extends DefinedNodeCredentialBindings | undefined = undefined,\n> {\n readonly kind: \"defined-node\";\n readonly key: TKey;\n readonly title: string;\n readonly description?: string;\n create<TConfigItemJson = TInputJson>(\n config: DefinedNodeConfigInput<TConfig, TConfigItemJson>,\n name?: string,\n id?: string,\n ): RunnableNodeConfig<TInputJson, TOutputJson>;\n register(context: { registerNode<TValue>(token: TypeToken<TValue>, implementation?: TypeToken<TValue>): void }): void;\n}\n\n/**\n * Plugin / DSL-friendly node: per-item `execute` with optional {@link RunnableNodeConfig.inputSchema}.\n */\nexport interface DefineNodeOptions<\n TKey extends string,\n TConfig extends CredentialJsonRecord,\n TInputJson,\n TOutputJson,\n TBindings extends DefinedNodeCredentialBindings | undefined = undefined,\n> {\n readonly key: TKey;\n readonly title: string;\n readonly description?: string;\n /**\n * Canvas icon for this node (same contract as `NodeConfigBase.icon` on runnable configs).\n * The Next host resolves Lucide (`lucide:…`), built-in SVGs (`builtin:…`), Simple Icons (`si:…`), and image URLs (`https:`, `data:`, `/…`).\n */\n readonly icon?: string;\n /** Default values / form hints for **static** node configuration (credentials, retry, IDs), not per-item payload. */\n readonly input?: Readonly<Record<keyof TConfig & string, unknown>>;\n readonly configSchema?: z.ZodType<TConfig>;\n readonly credentials?: TBindings;\n /**\n * Validates **`input`** (engine also accepts `inputSchema` on the node class).\n */\n readonly inputSchema?: ZodType<TInputJson>;\n /** Preserve inbound `item.binary` when `execute` returns plain JSON or item-shaped results without `binary`. */\n readonly keepBinaries?: boolean;\n execute(\n args: DefineNodeExecuteArgs<TConfig, TInputJson>,\n context: DefinedNodeRunContext<TConfig, TBindings>,\n ): MaybePromise<TOutputJson>;\n}\n\n/**\n * Batch-oriented defined node: `run` receives all item JSON once (last item in activation); emits one output per input row.\n */\nexport interface DefineBatchNodeOptions<\n TKey extends string,\n TConfig extends CredentialJsonRecord,\n TInputJson,\n TOutputJson,\n TBindings extends DefinedNodeCredentialBindings | undefined = undefined,\n> {\n readonly key: TKey;\n readonly title: string;\n readonly description?: string;\n readonly icon?: string;\n readonly input?: Readonly<Record<keyof TConfig & string, unknown>>;\n readonly configSchema?: z.ZodType<TConfig>;\n readonly credentials?: TBindings;\n run(\n items: ReadonlyArray<TInputJson>,\n context: DefinedNodeRunContext<TConfig, TBindings>,\n ): MaybePromise<ReadonlyArray<TOutputJson>>;\n}\n\nconst definedNodeCredentialRequirementFactory = {\n create(bindings: DefinedNodeCredentialBindings | undefined): ReadonlyArray<CredentialRequirement> {\n if (!bindings) {\n return [];\n }\n return Object.entries(bindings).map(([slotKey, binding]) => {\n if (typeof binding === \"string\" || this.isCredentialType(binding)) {\n return {\n slotKey,\n label: this.humanize(slotKey),\n acceptedTypes: [this.resolveTypeId(binding)],\n };\n }\n\n const types = Array.isArray(binding.type) ? binding.type : [binding.type];\n return {\n slotKey,\n label: binding.label ?? this.humanize(slotKey),\n acceptedTypes: types.map((entry) => this.resolveTypeId(entry)),\n optional: binding.optional,\n helpText: binding.helpText,\n helpUrl: binding.helpUrl,\n };\n });\n },\n\n isCredentialType(value: unknown): value is AnyCredentialType {\n return (\n Boolean(value) &&\n typeof value === \"object\" &&\n \"definition\" in (value as Record<string, unknown>) &&\n typeof (value as AnyCredentialType).definition?.typeId === \"string\"\n );\n },\n\n resolveTypeId(type: ResolvableCredentialType): string {\n return typeof type === \"string\" ? type : type.definition.typeId;\n },\n\n humanize(key: string): string {\n return key\n .replace(/([a-z0-9])([A-Z])/g, \"$1 $2\")\n .replace(/[-_.]+/g, \" \")\n .replace(/\\s+/g, \" \")\n .trim()\n .replace(/^./, (character) => character.toUpperCase());\n },\n} as const;\n\nconst definedNodeCredentialAccessorFactory = {\n create<TBindings extends DefinedNodeCredentialBindings | undefined>(\n bindings: TBindings,\n ctx: NodeExecutionContext<RunnableNodeConfig<any, any>>,\n ): DefinedNodeCredentialAccessors<TBindings> {\n if (!bindings) {\n return {} as DefinedNodeCredentialAccessors<TBindings>;\n }\n const entries = Object.keys(bindings).map((slotKey) => [slotKey, () => ctx.getCredential(slotKey)] as const);\n return Object.fromEntries(entries) as DefinedNodeCredentialAccessors<TBindings>;\n },\n} as const;\n\nexport function defineNode<\n TKey extends string,\n TConfig extends CredentialJsonRecord,\n TInputJson,\n TOutputJson,\n TBindings extends DefinedNodeCredentialBindings | undefined = undefined,\n>(\n options: DefineNodeOptions<TKey, TConfig, TInputJson, TOutputJson, TBindings>,\n): DefinedNode<TKey, TConfig, TInputJson, TOutputJson, TBindings> {\n const credentialRequirements = definedNodeCredentialRequirementFactory.create(options.credentials);\n type DefinedRunnableNodeConfigShape = RunnableNodeConfig<TInputJson, TOutputJson> & Readonly<{ config: TConfig }>;\n\n const DefinedNodeRuntime = class implements RunnableNode<DefinedRunnableNodeConfigShape, TInputJson, TOutputJson> {\n readonly kind = \"node\" as const;\n readonly outputPorts = [\"main\"] as const;\n readonly inputSchema = options.inputSchema;\n\n async execute(\n args: Readonly<RunnableNodeExecuteArgs<DefinedRunnableNodeConfigShape, TInputJson>>,\n ): Promise<unknown> {\n const ctx = args.ctx;\n const context: DefinedNodeRunContext<TConfig, TBindings> = {\n config: ctx.config.config,\n credentials: definedNodeCredentialAccessorFactory.create(\n options.credentials,\n ctx,\n ) as DefinedNodeCredentialAccessors<TBindings>,\n execution: ctx as unknown as NodeExecutionContext<RunnableNodeConfig<TConfig, unknown>>,\n };\n const payload: DefineNodeExecuteArgs<TConfig, TInputJson> = {\n input: args.input,\n item: args.item,\n itemIndex: args.itemIndex,\n items: args.items,\n ctx,\n };\n return await options.execute(payload, context);\n }\n };\n\n persistedNode({ name: options.key })(DefinedNodeRuntime);\n\n const DefinedRunnableNodeConfig = class implements RunnableNodeConfig<TInputJson, TOutputJson> {\n readonly kind = \"node\" as const;\n readonly type: TypeToken<unknown> = DefinedNodeRuntime;\n readonly icon = options.icon;\n readonly inputSchema = options.inputSchema;\n readonly keepBinaries = options.keepBinaries ?? false;\n\n constructor(\n public readonly name: string,\n config: DefinedNodeConfigInput<TConfig, unknown>,\n public readonly id?: string,\n ) {\n this.config = config as unknown as TConfig;\n }\n\n public readonly config: TConfig;\n\n getCredentialRequirements(): ReadonlyArray<CredentialRequirement> {\n return credentialRequirements;\n }\n };\n\n const definition: DefinedNode<TKey, TConfig, TInputJson, TOutputJson, TBindings> = {\n kind: \"defined-node\",\n key: options.key,\n title: options.title,\n description: options.description,\n create<TConfigItemJson = TInputJson>(\n config: DefinedNodeConfigInput<TConfig, TConfigItemJson>,\n name = options.title,\n id?: string,\n ) {\n return new DefinedRunnableNodeConfig(name, config as DefinedNodeConfigInput<TConfig, unknown>, id);\n },\n register(context) {\n context.registerNode(DefinedNodeRuntime);\n },\n };\n\n DefinedNodeRegistry.register(definition as DefinedNode<string, Record<string, unknown>, unknown, unknown, undefined>);\n\n return definition;\n}\n\nexport function defineBatchNode<\n TKey extends string,\n TConfig extends CredentialJsonRecord,\n TInputJson,\n TOutputJson,\n TBindings extends DefinedNodeCredentialBindings | undefined = undefined,\n>(\n options: DefineBatchNodeOptions<TKey, TConfig, TInputJson, TOutputJson, TBindings>,\n): DefinedNode<TKey, TConfig, TInputJson, TOutputJson, TBindings> {\n const credentialRequirements = definedNodeCredentialRequirementFactory.create(options.credentials);\n type DefinedRunnableNodeConfigShape = RunnableNodeConfig<TInputJson, TOutputJson> & Readonly<{ config: TConfig }>;\n\n const DefinedNodeRuntime = class implements RunnableNode<DefinedRunnableNodeConfigShape, TInputJson, TOutputJson> {\n readonly kind = \"node\" as const;\n readonly outputPorts = [\"main\"] as const;\n\n async execute(\n args: Readonly<RunnableNodeExecuteArgs<DefinedRunnableNodeConfigShape, TInputJson>>,\n ): Promise<unknown> {\n if (args.itemIndex !== args.items.length - 1) {\n return [];\n }\n const ctx = args.ctx;\n const context: DefinedNodeRunContext<TConfig, TBindings> = {\n config: ctx.config.config,\n credentials: definedNodeCredentialAccessorFactory.create(\n options.credentials,\n ctx,\n ) as DefinedNodeCredentialAccessors<TBindings>,\n execution: ctx as unknown as NodeExecutionContext<RunnableNodeConfig<TConfig, unknown>>,\n };\n const outputs = await options.run(\n args.items.map((item) => item.json as TInputJson),\n context,\n );\n return [...outputs];\n }\n };\n\n persistedNode({ name: options.key })(DefinedNodeRuntime);\n\n const DefinedRunnableNodeConfig = class implements RunnableNodeConfig<TInputJson, TOutputJson> {\n readonly kind = \"node\" as const;\n readonly type: TypeToken<unknown> = DefinedNodeRuntime;\n readonly icon = options.icon;\n\n constructor(\n public readonly name: string,\n config: DefinedNodeConfigInput<TConfig, unknown>,\n public readonly id?: string,\n ) {\n this.config = config as unknown as TConfig;\n }\n\n public readonly config: TConfig;\n\n getCredentialRequirements(): ReadonlyArray<CredentialRequirement> {\n return credentialRequirements;\n }\n };\n\n const definition: DefinedNode<TKey, TConfig, TInputJson, TOutputJson, TBindings> = {\n kind: \"defined-node\",\n key: options.key,\n title: options.title,\n description: options.description,\n create<TConfigItemJson = TInputJson>(\n config: DefinedNodeConfigInput<TConfig, TConfigItemJson>,\n name = options.title,\n id?: string,\n ) {\n return new DefinedRunnableNodeConfig(name, config as DefinedNodeConfigInput<TConfig, unknown>, id);\n },\n register(context) {\n context.registerNode(DefinedNodeRuntime);\n },\n };\n\n DefinedNodeRegistry.register(definition as DefinedNode<string, Record<string, unknown>, unknown, unknown, undefined>);\n\n return definition;\n}\n","import type {\n AnyCredentialType,\n CredentialFieldSchema,\n CredentialHealth,\n CredentialJsonRecord,\n CredentialSessionFactoryArgs,\n CredentialType,\n CredentialTypeDefinition,\n} from \"../contracts/credentialTypes\";\nimport { z } from \"zod\";\n\ntype MaybePromise<TValue> = TValue | Promise<TValue>;\n\ntype CredentialFieldInput = CredentialFieldSchema[\"type\"] | Readonly<Omit<CredentialFieldSchema, \"key\">>;\n\ntype CredentialFieldMap<TConfig extends CredentialJsonRecord> = Readonly<\n Record<keyof TConfig & string, CredentialFieldInput>\n>;\n\ntype ZodObjectSchema<TConfig extends CredentialJsonRecord = CredentialJsonRecord> = z.ZodType<TConfig>;\n\ntype InferCredentialConfig<TSource> =\n TSource extends z.ZodType<infer TConfig, any, any>\n ? Readonly<TConfig> & CredentialJsonRecord\n : TSource extends CredentialFieldMap<infer TConfig>\n ? TConfig\n : CredentialJsonRecord;\n\nexport interface DefineCredentialOptions<\n TPublicSource extends CredentialFieldMap<any> | ZodObjectSchema<any>,\n TSecretSource extends CredentialFieldMap<any> | ZodObjectSchema<any>,\n TSession,\n> {\n readonly key: string;\n readonly label: string;\n readonly description?: string;\n readonly public: TPublicSource;\n readonly secret: TSecretSource;\n readonly supportedSourceKinds?: CredentialTypeDefinition[\"supportedSourceKinds\"];\n readonly auth?: CredentialTypeDefinition[\"auth\"];\n createSession(\n args: CredentialSessionFactoryArgs<InferCredentialConfig<TPublicSource>, InferCredentialConfig<TSecretSource>>,\n ): MaybePromise<TSession>;\n test(\n args: CredentialSessionFactoryArgs<InferCredentialConfig<TPublicSource>, InferCredentialConfig<TSecretSource>>,\n ): MaybePromise<CredentialHealth>;\n}\n\nexport class CredentialFieldSchemaFactory {\n static create<TConfig extends CredentialJsonRecord>(\n source: CredentialFieldMap<TConfig> | ZodObjectSchema<TConfig>,\n ): ReadonlyArray<CredentialFieldSchema> {\n if (source instanceof z.ZodObject) {\n return this.createFromZodObject(source);\n }\n return this.createFromMap(source as CredentialFieldMap<TConfig>);\n }\n\n private static createFromMap<TConfig extends CredentialJsonRecord>(\n source: CredentialFieldMap<TConfig>,\n ): ReadonlyArray<CredentialFieldSchema> {\n return Object.entries(source).map(([key, input], index) => {\n if (typeof input === \"string\") {\n return {\n key,\n label: this.humanize(key),\n order: index,\n type: input as CredentialFieldSchema[\"type\"],\n };\n }\n return {\n key,\n order: index,\n ...(input as Readonly<Omit<CredentialFieldSchema, \"key\">>),\n };\n });\n }\n\n private static createFromZodObject<_TConfig extends CredentialJsonRecord>(\n source: z.ZodObject,\n ): ReadonlyArray<CredentialFieldSchema> {\n const shape = source.shape;\n return Object.entries(shape).map(([key, schema], index) => {\n const resolved = this.unwrap(schema);\n return {\n key,\n label: this.humanize(key),\n order: index,\n required: this.isRequired(schema) ? true : undefined,\n type: this.resolveType(resolved),\n };\n });\n }\n\n private static isRequired(schema: z.ZodTypeAny): boolean {\n return !(schema instanceof z.ZodOptional || schema instanceof z.ZodDefault);\n }\n\n private static unwrap(schema: z.ZodTypeAny): z.ZodTypeAny {\n let current: z.ZodTypeAny = schema;\n while (current instanceof z.ZodOptional || current instanceof z.ZodDefault) {\n current = current.unwrap() as z.ZodTypeAny;\n }\n return current;\n }\n\n private static resolveType(schema: z.ZodTypeAny): CredentialFieldSchema[\"type\"] {\n if (schema instanceof z.ZodBoolean) {\n return \"boolean\";\n }\n if (schema instanceof z.ZodString) {\n return \"string\";\n }\n return \"json\";\n }\n\n private static humanize(key: string): string {\n return key\n .replace(/([a-z0-9])([A-Z])/g, \"$1 $2\")\n .replace(/[-_.]+/g, \" \")\n .replace(/\\s+/g, \" \")\n .trim()\n .replace(/^./, (character) => character.toUpperCase());\n }\n}\n\nexport function defineCredential<\n TPublicSource extends CredentialFieldMap<any> | ZodObjectSchema<any>,\n TSecretSource extends CredentialFieldMap<any> | ZodObjectSchema<any>,\n TSession,\n>(\n options: DefineCredentialOptions<TPublicSource, TSecretSource, TSession>,\n): CredentialType<InferCredentialConfig<TPublicSource>, InferCredentialConfig<TSecretSource>, TSession> & {\n readonly key: string;\n} {\n const definition: CredentialTypeDefinition = {\n typeId: options.key,\n displayName: options.label,\n description: options.description,\n publicFields: CredentialFieldSchemaFactory.create(options.public),\n secretFields: CredentialFieldSchemaFactory.create(options.secret),\n supportedSourceKinds: options.supportedSourceKinds ?? [\"db\", \"env\", \"code\"],\n auth: options.auth,\n };\n\n const credentialType: AnyCredentialType = {\n definition,\n async createSession(args) {\n return await options.createSession(\n args as CredentialSessionFactoryArgs<\n InferCredentialConfig<TPublicSource>,\n InferCredentialConfig<TSecretSource>\n >,\n );\n },\n async test(args) {\n return await options.test(\n args as CredentialSessionFactoryArgs<\n InferCredentialConfig<TPublicSource>,\n InferCredentialConfig<TSecretSource>\n >,\n );\n },\n };\n\n return {\n ...credentialType,\n key: options.key,\n } as CredentialType<InferCredentialConfig<TPublicSource>, InferCredentialConfig<TSecretSource>, TSession> & {\n readonly key: string;\n };\n}\n","/**\n * Shared {@link import(\"../di\").TypeToken} marker for {@link CallableToolConfig}.\n * Callable tools are not registered in {@link NodeResolver}; this class only satisfies {@link ToolConfig#type}.\n */\nexport class CallableToolKindToken {}\n","import type { CredentialRequirement } from \"../contracts/credentialTypes\";\nimport type { TypeToken } from \"../di\";\nimport type { AgentCanvasPresentation, ToolConfig, ToolExecuteArgs, ZodSchemaAny } from \"./AiHost\";\nimport { ZodError, type input as ZodInput, type output as ZodOutput } from \"zod\";\n\nimport { CallableToolKindToken } from \"./CallableToolKindToken\";\n\nexport type CallableToolExecuteHandler<TInputSchema extends ZodSchemaAny, TOutputSchema extends ZodSchemaAny> = (\n args: ToolExecuteArgs<CallableToolConfig<TInputSchema, TOutputSchema>, ZodInput<TInputSchema>>,\n) => Promise<ZodOutput<TOutputSchema>> | ZodOutput<TOutputSchema>;\n\nexport type CallableToolConfigOptions<\n TInputSchema extends ZodSchemaAny,\n TOutputSchema extends ZodSchemaAny,\n> = Readonly<{\n name: string;\n description?: string;\n presentation?: AgentCanvasPresentation;\n inputSchema: TInputSchema;\n outputSchema: TOutputSchema;\n /**\n * Optional credential slots for this tool (same contract as other {@link ToolConfig} shapes).\n */\n credentialRequirements?: ReadonlyArray<CredentialRequirement>;\n execute: CallableToolExecuteHandler<TInputSchema, TOutputSchema>;\n}>;\n\n/**\n * Inline callable agent tool: DSL sugar over {@link ToolConfig} without a separate {@link NodeResolver}-registered {@link Tool} class.\n */\nexport class CallableToolConfig<\n TInputSchema extends ZodSchemaAny,\n TOutputSchema extends ZodSchemaAny,\n> implements ToolConfig {\n readonly type: TypeToken<unknown> = CallableToolKindToken;\n readonly toolKind = \"callable\" as const;\n readonly description?: string;\n readonly presentation?: AgentCanvasPresentation;\n private readonly inputSchemaValue: TInputSchema;\n private readonly outputSchemaValue: TOutputSchema;\n private readonly credentialRequirementsValue?: ReadonlyArray<CredentialRequirement>;\n private readonly executeHandler: CallableToolExecuteHandler<TInputSchema, TOutputSchema>;\n\n constructor(\n public readonly name: string,\n options: CallableToolConfigOptions<TInputSchema, TOutputSchema>,\n ) {\n this.description = options.description;\n this.presentation = options.presentation;\n this.inputSchemaValue = options.inputSchema;\n this.outputSchemaValue = options.outputSchema;\n this.credentialRequirementsValue = options.credentialRequirements;\n this.executeHandler = options.execute;\n }\n\n getCredentialRequirements(): ReadonlyArray<CredentialRequirement> {\n return this.credentialRequirementsValue ?? [];\n }\n\n getInputSchema(): TInputSchema {\n return this.inputSchemaValue;\n }\n\n getOutputSchema(): TOutputSchema {\n return this.outputSchemaValue;\n }\n\n /**\n * Parses tool input and output with the configured Zod schemas.\n */\n async executeTool(\n args: ToolExecuteArgs<CallableToolConfig<TInputSchema, TOutputSchema>, ZodInput<TInputSchema>>,\n ): Promise<ZodOutput<TOutputSchema>> {\n const parsedInput = this.parseInput(args.input);\n const raw = await Promise.resolve(\n this.executeHandler({\n ...args,\n config: this,\n input: parsedInput,\n }),\n );\n return this.parseOutput(raw);\n }\n\n private parseInput(input: unknown): ZodInput<TInputSchema> {\n try {\n return this.inputSchemaValue.parse(input) as ZodInput<TInputSchema>;\n } catch (error) {\n throw this.decorateValidationError(error, \"input\");\n }\n }\n\n private parseOutput(output: unknown): ZodOutput<TOutputSchema> {\n try {\n return this.outputSchemaValue.parse(output) as ZodOutput<TOutputSchema>;\n } catch (error) {\n throw this.decorateValidationError(error, \"output\");\n }\n }\n\n private decorateValidationError(error: unknown, stage: \"input\" | \"output\"): Error {\n if (error instanceof ZodError) {\n (error as ZodError & { codemationToolValidationStage?: \"input\" | \"output\" }).codemationToolValidationStage =\n stage;\n return error;\n }\n return error instanceof Error ? error : new Error(String(error));\n }\n}\n","import type { ZodSchemaAny } from \"./AiHost\";\nimport { CallableToolConfig } from \"./CallableToolConfig\";\nimport type { CallableToolConfigOptions } from \"./CallableToolConfig\";\n\nclass CallableToolFactoryImpl {\n callableTool<TInputSchema extends ZodSchemaAny, TOutputSchema extends ZodSchemaAny>(\n options: CallableToolConfigOptions<TInputSchema, TOutputSchema>,\n ): CallableToolConfig<TInputSchema, TOutputSchema> {\n return new CallableToolConfig(options.name, options);\n }\n}\n\nexport const CallableToolFactory = new CallableToolFactoryImpl();\n","import type { ZodSchemaAny } from \"../ai/AiHost\";\nimport type { CallableToolConfig, CallableToolConfigOptions } from \"../ai/CallableToolConfig\";\nimport { CallableToolFactory } from \"../ai/CallableToolFactory\";\n\n/**\n * Workflow-facing helper for inline Zod-typed agent tools (same as {@link CallableToolFactory.callableTool}).\n */\nexport function callableTool<TInputSchema extends ZodSchemaAny, TOutputSchema extends ZodSchemaAny>(\n options: CallableToolConfigOptions<TInputSchema, TOutputSchema>,\n): CallableToolConfig<TInputSchema, TOutputSchema> {\n return CallableToolFactory.callableTool(options);\n}\n","import type { CredentialRequirement } from \"../contracts/credentialTypes\";\nimport type { TypeToken } from \"../di\";\nimport type { Item, NodeOutputs, RunnableNodeConfig, RunnableNodeInputJson } from \"../types\";\nimport type { input as ZodInput, output as ZodOutput } from \"zod\";\nimport type {\n AgentCanvasPresentation,\n NodeBackedToolConfigOptions,\n NodeBackedToolInputMapper,\n NodeBackedToolInputMapperArgs,\n NodeBackedToolOutputMapper,\n NodeBackedToolOutputMapperArgs,\n ToolConfig,\n ZodSchemaAny,\n} from \"./AiHost\";\n\nexport class NodeBackedToolConfig<\n TNodeConfig extends RunnableNodeConfig<any, any>,\n TInputSchema extends ZodSchemaAny,\n TOutputSchema extends ZodSchemaAny,\n> implements ToolConfig {\n readonly type: TypeToken<unknown>;\n readonly toolKind = \"nodeBacked\" as const;\n readonly description?: string;\n readonly presentation?: AgentCanvasPresentation;\n private readonly inputSchemaValue: TInputSchema;\n private readonly outputSchemaValue: TOutputSchema;\n private readonly mapInputValue?: NodeBackedToolInputMapper<TNodeConfig, ZodInput<TInputSchema>>;\n private readonly mapOutputValue?: NodeBackedToolOutputMapper<\n TNodeConfig,\n ZodInput<TInputSchema>,\n ZodOutput<TOutputSchema>\n >;\n\n constructor(\n public readonly name: string,\n public readonly node: TNodeConfig,\n options: NodeBackedToolConfigOptions<TNodeConfig, TInputSchema, TOutputSchema>,\n ) {\n this.type = node.type;\n this.description = options.description;\n this.presentation = options.presentation;\n this.inputSchemaValue = options.inputSchema;\n this.outputSchemaValue = options.outputSchema;\n this.mapInputValue = options.mapInput;\n this.mapOutputValue = options.mapOutput;\n }\n\n getCredentialRequirements(): ReadonlyArray<CredentialRequirement> {\n return this.node.getCredentialRequirements?.() ?? [];\n }\n\n getInputSchema(): TInputSchema {\n return this.inputSchemaValue;\n }\n\n getOutputSchema(): TOutputSchema {\n return this.outputSchemaValue;\n }\n\n toNodeItem(\n args: NodeBackedToolInputMapperArgs<TNodeConfig, ZodInput<TInputSchema>>,\n ): Item<RunnableNodeInputJson<TNodeConfig>> {\n const mapped = this.mapInputValue?.(args) ?? (args.input as RunnableNodeInputJson<TNodeConfig>);\n if (this.isItem(mapped)) {\n return mapped;\n }\n return { json: mapped };\n }\n\n toToolOutput(args: NodeBackedToolOutputMapperArgs<TNodeConfig, ZodInput<TInputSchema>>): ZodOutput<TOutputSchema> {\n const raw = this.mapOutputValue?.(args) ?? this.readDefaultToolOutput(args.outputs);\n return this.outputSchemaValue.parse(raw) as ZodOutput<TOutputSchema>;\n }\n\n private readDefaultToolOutput(outputs: NodeOutputs): unknown {\n const firstMainItem = outputs.main?.[0];\n if (!firstMainItem) {\n throw new Error(`Node-backed tool \"${this.name}\" did not produce a main output item.`);\n }\n return firstMainItem.json;\n }\n\n private isItem(value: unknown): value is Item {\n return typeof value === \"object\" && value !== null && \"json\" in value;\n }\n}\n","import type { NodeConfigBase } from \"../types\";\nimport { isItemExpr } from \"../contracts/itemExpr\";\nimport type { AgentNodeConfig } from \"./AiHost\";\n\nexport class AgentConfigInspector {\n static isAgentNodeConfig(config: NodeConfigBase | undefined): config is AgentNodeConfig<any, any> {\n if (!config) return false;\n const candidate = config as Partial<AgentNodeConfig<any, any>>;\n return !!candidate.chatModel && this.hasCompatibleMessageConfiguration(candidate);\n }\n\n private static hasCompatibleMessageConfiguration(candidate: Partial<AgentNodeConfig<any, any>>): boolean {\n const messages = candidate.messages;\n if (messages === undefined || messages === null) {\n return false;\n }\n if (Array.isArray(messages)) {\n return messages.length > 0;\n }\n if (typeof messages === \"object\") {\n if (isItemExpr(messages)) {\n return true;\n }\n const o = messages as { prompt?: unknown; buildMessages?: unknown };\n return (Array.isArray(o.prompt) && o.prompt.length > 0) || typeof o.buildMessages === \"function\";\n }\n return false;\n }\n}\n","import type { Item, RunnableNodeConfig } from \"../types\";\nimport type { NodeBackedToolConfigOptions, ZodSchemaAny } from \"./AiHost\";\nimport { AgentConfigInspector } from \"./AgentConfigInspectorFactory\";\nimport { NodeBackedToolConfig } from \"./NodeBackedToolConfig\";\n\nclass AgentToolFactoryImpl {\n asTool<\n TNodeConfig extends RunnableNodeConfig<any, any>,\n TInputSchema extends ZodSchemaAny,\n TOutputSchema extends ZodSchemaAny,\n >(\n node: TNodeConfig,\n options: Readonly<{ name?: string } & NodeBackedToolConfigOptions<TNodeConfig, TInputSchema, TOutputSchema>>,\n ): NodeBackedToolConfig<TNodeConfig, TInputSchema, TOutputSchema> {\n return new NodeBackedToolConfig(\n options.name ?? node.name ?? \"tool\",\n node,\n this.withDefaultAgentInputMapper(node, options),\n );\n }\n\n private withDefaultAgentInputMapper<\n TNodeConfig extends RunnableNodeConfig<any, any>,\n TInputSchema extends ZodSchemaAny,\n TOutputSchema extends ZodSchemaAny,\n >(\n node: TNodeConfig,\n options: Readonly<{ name?: string } & NodeBackedToolConfigOptions<TNodeConfig, TInputSchema, TOutputSchema>>,\n ): Readonly<{ name?: string } & NodeBackedToolConfigOptions<TNodeConfig, TInputSchema, TOutputSchema>> {\n if (options.mapInput || !AgentConfigInspector.isAgentNodeConfig(node)) {\n return options;\n }\n return {\n ...options,\n mapInput: ({ input, item }) => this.mergeAgentToolInputWithCurrentItem(input, item) as never,\n };\n }\n\n private mergeAgentToolInputWithCurrentItem(input: unknown, item: Item): unknown {\n if (!this.isMergeableRecord(input) || !this.isMergeableRecord(item.json)) {\n return input;\n }\n return {\n ...item.json,\n ...input,\n };\n }\n\n private isMergeableRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n }\n}\n\nexport const AgentToolFactory = new AgentToolFactoryImpl();\n","import { isItemExpr } from \"../contracts/itemExpr\";\n\nimport type {\n AgentMessageBuildArgs,\n AgentMessageConfig,\n AgentMessageDto,\n AgentMessageLine,\n AgentMessageRole,\n AgentNodeConfig,\n} from \"./AiHost\";\n\nexport class AgentMessageConfigNormalizer {\n /**\n * Prefer {@code input.messages} when present (ItemNode / engine-mapped payloads); otherwise resolve from\n * {@link AgentNodeConfig.messages} templates.\n */\n static resolveFromInputOrConfig<TInputJson, TOutputJson>(\n input: unknown,\n config: AgentNodeConfig<TInputJson, TOutputJson>,\n args: AgentMessageBuildArgs<TInputJson>,\n ): ReadonlyArray<AgentMessageDto> {\n const fromInput = this.tryMessagesFromStructuredInput(input);\n if (fromInput.length > 0) {\n return fromInput;\n }\n return this.normalize(config, args);\n }\n\n static normalize<TInputJson, TOutputJson>(\n config: AgentNodeConfig<TInputJson, TOutputJson>,\n args: AgentMessageBuildArgs<TInputJson>,\n ): ReadonlyArray<AgentMessageDto> {\n const fromMessages = this.normalizeRichMessages(config.messages, args);\n if (fromMessages.length > 0) {\n return fromMessages;\n }\n throw new Error(\n \"AIAgent messages must be a non-empty array, or an object with a non-empty prompt array and/or buildMessages that returns messages.\",\n );\n }\n\n private static tryMessagesFromStructuredInput(input: unknown): ReadonlyArray<AgentMessageDto> {\n if (!input || typeof input !== \"object\") {\n return [];\n }\n const raw = (input as { messages?: unknown }).messages;\n if (!Array.isArray(raw) || raw.length === 0) {\n return [];\n }\n const out: AgentMessageDto[] = [];\n for (const m of raw) {\n if (!m || typeof m !== \"object\") {\n continue;\n }\n const role = (m as { role?: unknown }).role;\n const content = (m as { content?: unknown }).content;\n if (role !== \"system\" && role !== \"user\" && role !== \"assistant\") {\n continue;\n }\n if (typeof content !== \"string\") {\n continue;\n }\n out.push({ role: role as AgentMessageRole, content });\n }\n return out;\n }\n\n private static normalizeRichMessages<TInputJson>(\n config: AgentMessageConfig<TInputJson>,\n args: AgentMessageBuildArgs<TInputJson>,\n ): ReadonlyArray<AgentMessageDto> {\n if (isItemExpr(config)) {\n throw new Error(\n \"AIAgent messages wrapped in itemExpr(...) must be resolved by the engine before prompt normalization.\",\n );\n }\n if (Array.isArray(config)) {\n return config.map((line) => this.lineToDto(line, args));\n }\n const structured = config as {\n readonly prompt?: ReadonlyArray<AgentMessageLine<TInputJson>>;\n readonly buildMessages?: (a: AgentMessageBuildArgs<TInputJson>) => ReadonlyArray<AgentMessageDto>;\n };\n const messages: AgentMessageDto[] = [];\n for (const line of structured.prompt ?? []) {\n messages.push(this.lineToDto(line, args));\n }\n for (const message of structured.buildMessages?.(args) ?? []) {\n messages.push(message);\n }\n return messages;\n }\n\n private static lineToDto<TInputJson>(\n line: AgentMessageLine<TInputJson>,\n args: AgentMessageBuildArgs<TInputJson>,\n ): AgentMessageDto {\n const content = typeof line.content === \"function\" ? line.content(args) : line.content;\n return { role: line.role, content };\n }\n}\n","import type { TypeToken } from \"../di\";\n\nimport type { CredentialRequirement } from \"../contracts/credentialTypes\";\nimport type { Expr } from \"../contracts/params\";\n\nimport type {\n Item,\n Items,\n JsonValue,\n NodeExecutionContext,\n NodeOutputs,\n RunnableNodeConfig,\n RunnableNodeInputJson,\n} from \"../types\";\n\nimport type { input as ZodInput, output as ZodOutput, ZodType } from \"zod\";\n\nexport interface AgentCanvasPresentation<TIcon extends string = string> {\n readonly label?: string;\n readonly icon?: TIcon;\n}\n\nexport type ZodSchemaAny = ZodType<any, any, any>;\n\nexport interface ToolConfig {\n readonly type: TypeToken<unknown>;\n readonly name: string;\n readonly description?: string;\n readonly presentation?: AgentCanvasPresentation;\n getCredentialRequirements?(): ReadonlyArray<CredentialRequirement>;\n}\n\nexport type ToolExecuteArgs<TConfig extends ToolConfig = ToolConfig, TInput = unknown> = Readonly<{\n config: TConfig;\n input: TInput;\n ctx: NodeExecutionContext<any>;\n item: Item;\n itemIndex: number;\n items: Items;\n}>;\n\nexport interface Tool<\n TConfig extends ToolConfig = ToolConfig,\n TInputSchema extends ZodSchemaAny = ZodSchemaAny,\n TOutputSchema extends ZodSchemaAny = ZodSchemaAny,\n> {\n readonly defaultDescription: string;\n readonly inputSchema: TInputSchema;\n readonly outputSchema: TOutputSchema;\n execute(\n args: ToolExecuteArgs<TConfig, ZodInput<TInputSchema>>,\n ): Promise<ZodOutput<TOutputSchema>> | ZodOutput<TOutputSchema>;\n}\n\nexport type AgentTool<\n TInputSchema extends ZodSchemaAny = ZodSchemaAny,\n TOutputSchema extends ZodSchemaAny = ZodSchemaAny,\n> = Tool<ToolConfig, TInputSchema, TOutputSchema>;\n\nexport type AgentToolExecuteArgs<TInput = unknown> = ToolExecuteArgs<ToolConfig, TInput>;\n\nexport type AgentToolToken = TypeToken<Tool<ToolConfig, ZodSchemaAny, ZodSchemaAny>>;\n\nexport type AgentMessageRole = \"system\" | \"user\" | \"assistant\";\n\nexport type AgentMessageBuildArgs<TInputJson = unknown> = Readonly<{\n item: Item<TInputJson>;\n itemIndex: number;\n items: Items<TInputJson>;\n ctx: NodeExecutionContext<any>;\n}>;\n\nexport interface AgentMessageDto {\n readonly role: AgentMessageRole;\n readonly content: string;\n}\n\nexport type AgentMessageTemplateContent<TInputJson = unknown> =\n | string\n | ((args: AgentMessageBuildArgs<TInputJson>) => string);\n\nexport interface AgentMessageTemplate<TInputJson = unknown> {\n readonly role: AgentMessageRole;\n readonly content: AgentMessageTemplateContent<TInputJson>;\n}\n\n/** A single prompt line: fixed DTO or template with optional function `content`. */\nexport type AgentMessageLine<TInputJson = unknown> = AgentMessageDto | AgentMessageTemplate<TInputJson>;\n\n/**\n * Message list for an agent. Prefer a **plain array** of `{ role, content }` (optionally with function `content` for templates).\n * Use the object form only when you need `buildMessages` to append messages after optional `prompt` lines.\n */\nexport type AgentMessageConfig<TInputJson = unknown> =\n | Expr<ReadonlyArray<AgentMessageLine<TInputJson>>, TInputJson>\n | ReadonlyArray<AgentMessageLine<TInputJson>>\n | {\n readonly prompt?: ReadonlyArray<AgentMessageLine<TInputJson>>;\n readonly buildMessages?: (args: AgentMessageBuildArgs<TInputJson>) => ReadonlyArray<AgentMessageDto>;\n };\n\nexport type AgentTurnLimitBehavior = \"error\" | \"respondWithLastMessage\";\n\nexport interface AgentModelInvocationOptions {\n readonly maxTokens?: number;\n readonly providerOptions?: Readonly<Record<string, JsonValue>>;\n}\n\nexport interface AgentGuardrailConfig {\n readonly maxTurns?: number;\n readonly onTurnLimitReached?: AgentTurnLimitBehavior;\n readonly modelInvocationOptions?: AgentModelInvocationOptions;\n}\n\n/** Defaults aligned with common tool-agent iteration limits (many products use ~10 max rounds). */\nexport const AgentGuardrailDefaults = {\n maxTurns: 10,\n onTurnLimitReached: \"error\" as AgentTurnLimitBehavior,\n} as const;\n\nexport interface AgentToolDefinition {\n readonly name: string;\n readonly description: string;\n readonly inputSchema: ZodSchemaAny;\n}\n\nexport type AgentToolCall = Readonly<{ id?: string; name: string; input: unknown }>;\n\nexport type AgentToolCallPlanner<_TNodeConfig = unknown> = (\n item: Item,\n index: number,\n items: Items,\n ctx: NodeExecutionContext<any>,\n) => ReadonlyArray<AgentToolCall>;\n\nexport interface ChatModelConfig {\n readonly type: TypeToken<ChatModelFactory<ChatModelConfig>>;\n readonly name: string;\n readonly provider?: string;\n readonly modelName?: string;\n readonly presentation?: AgentCanvasPresentation;\n getCredentialRequirements?(): ReadonlyArray<CredentialRequirement>;\n}\n\n/**\n * Provider-neutral chat language model wrapper returned by a {@link ChatModelFactory}.\n *\n * Thin adapter around an AI SDK `LanguageModelV2` (from `@ai-sdk/provider`) plus the call-site\n * defaults Codemation needs at every generate/stream: the provider label, the model name used for\n * pricing / telemetry, and the default invocation options (max output tokens, temperature,\n * provider-specific overrides).\n *\n * The consumer (AIAgentNode / AgentStructuredOutputRunner) passes `languageModel` directly into\n * `generateText({ model, ... })` from the `ai` package.\n */\nexport interface ChatLanguageModel {\n /** AI SDK `LanguageModelV2` instance (kept `unknown` to avoid leaking the SDK type into `@codemation/core`). */\n readonly languageModel: unknown;\n /** Stable pricing/telemetry key — e.g. `\"gpt-4.1-nano\"`. */\n readonly modelName: string;\n /** Provider label — e.g. `\"openai\"`. Used for cost tracking. */\n readonly provider?: string;\n /** Defaults merged into every call. Consumers may override per-invocation. */\n readonly defaultCallOptions?: ChatLanguageModelCallOptions;\n}\n\nexport interface ChatLanguageModelCallOptions {\n readonly maxOutputTokens?: number;\n readonly temperature?: number;\n readonly providerOptions?: Readonly<Record<string, Readonly<Record<string, JsonValue>>>>;\n}\n\n/**\n * Options for a structured-output generate call. Mirrors\n * `generateText({ output: Output.object(...) })` from the `ai` package.\n */\nexport interface StructuredOutputOptions {\n /** Optional schema name — used by some providers as the JSON schema name attribute. */\n readonly schemaName?: string;\n /** When `true`, the consumer should pass a strict-mode-compatible JSON Schema record. */\n readonly strict?: boolean;\n}\n\nexport interface ChatModelFactory<TConfig extends ChatModelConfig = ChatModelConfig> {\n create(\n args: Readonly<{ config: TConfig; ctx: NodeExecutionContext<any> }>,\n ): Promise<ChatLanguageModel> | ChatLanguageModel;\n}\n\nexport type NodeBackedToolInputMapperArgs<\n TNodeConfig extends RunnableNodeConfig<any, any>,\n TToolInput = unknown,\n> = Readonly<{\n input: TToolInput;\n item: Item;\n itemIndex: number;\n items: Items;\n ctx: NodeExecutionContext<any>;\n node: TNodeConfig;\n}>;\n\nexport type NodeBackedToolOutputMapperArgs<\n TNodeConfig extends RunnableNodeConfig<any, any>,\n TToolInput = unknown,\n> = Readonly<{\n input: TToolInput;\n item: Item;\n itemIndex: number;\n items: Items;\n ctx: NodeExecutionContext<any>;\n node: TNodeConfig;\n outputs: NodeOutputs;\n}>;\n\nexport type NodeBackedToolInputMapper<TNodeConfig extends RunnableNodeConfig<any, any>, TToolInput = unknown> = (\n args: NodeBackedToolInputMapperArgs<TNodeConfig, TToolInput>,\n) => Item<RunnableNodeInputJson<TNodeConfig>> | RunnableNodeInputJson<TNodeConfig>;\n\nexport type NodeBackedToolOutputMapper<\n TNodeConfig extends RunnableNodeConfig<any, any>,\n TToolInput = unknown,\n TToolOutput = unknown,\n> = (args: NodeBackedToolOutputMapperArgs<TNodeConfig, TToolInput>) => TToolOutput;\n\nexport type NodeBackedToolConfigOptions<\n TNodeConfig extends RunnableNodeConfig<any, any>,\n TInputSchema extends ZodSchemaAny,\n TOutputSchema extends ZodSchemaAny,\n> = Readonly<{\n description?: string;\n presentation?: AgentCanvasPresentation;\n inputSchema: TInputSchema;\n outputSchema: TOutputSchema;\n mapInput?: NodeBackedToolInputMapper<TNodeConfig, ZodInput<TInputSchema>>;\n mapOutput?: NodeBackedToolOutputMapper<TNodeConfig, ZodInput<TInputSchema>, ZodOutput<TOutputSchema>>;\n}>;\n\nexport interface AgentNodeConfig<TInputJson = unknown, TOutputJson = unknown> extends RunnableNodeConfig<\n TInputJson,\n TOutputJson\n> {\n readonly messages: AgentMessageConfig<TInputJson>;\n readonly chatModel: ChatModelConfig;\n readonly tools?: ReadonlyArray<ToolConfig>;\n readonly guardrails?: AgentGuardrailConfig;\n readonly outputSchema?: ZodType<TOutputJson>;\n}\n\nexport type AgentAttachmentRole = \"languageModel\" | \"tool\" | \"nestedAgent\";\n\nexport { NodeBackedToolConfig } from \"./NodeBackedToolConfig\";\nexport { CallableToolConfig } from \"./CallableToolConfig\";\nexport type { CallableToolConfigOptions, CallableToolExecuteHandler } from \"./CallableToolConfig\";\nexport { CallableToolFactory } from \"./CallableToolFactory\";\nexport { CallableToolKindToken } from \"./CallableToolKindToken\";\nexport { AgentToolFactory } from \"./AgentToolFactory\";\nexport { AgentMessageConfigNormalizer } from \"./AgentMessageConfigNormalizerFactory\";\nexport { AgentConfigInspector } from \"./AgentConfigInspectorFactory\";\n","import type { CredentialRequirement } from \"../contracts/credentialTypes\";\nimport type { NodeConfigBase, NodeConnectionName, NodeId } from \"../types\";\nimport { ConnectionNodeIdFactory } from \"../workflow/definition/ConnectionNodeIdFactory\";\nimport { AgentConfigInspector } from \"./AgentConfigInspectorFactory\";\nimport type { AgentNodeConfig, ToolConfig } from \"./AiHost\";\nimport { NodeBackedToolConfig } from \"./NodeBackedToolConfig\";\n\nexport type AgentConnectionNodeRole = \"languageModel\" | \"tool\" | \"nestedAgent\";\n\nexport type AgentConnectionCredentialSource = Readonly<{\n getCredentialRequirements?(): ReadonlyArray<CredentialRequirement>;\n}>;\n\nexport type AgentConnectionNodeDescriptor = Readonly<{\n nodeId: NodeId;\n parentNodeId: NodeId;\n connectionName: NodeConnectionName;\n role: AgentConnectionNodeRole;\n name: string;\n typeName: string;\n icon?: string;\n credentialSource: AgentConnectionCredentialSource;\n}>;\n\ntype AgentConnectionNodeCollectorApi = Readonly<{\n collect(parentNodeId: NodeId, agentConfig: AgentNodeConfig<any, any>): ReadonlyArray<AgentConnectionNodeDescriptor>;\n}>;\n\nexport const AgentConnectionNodeCollector: AgentConnectionNodeCollectorApi = new (class {\n collect(parentNodeId: NodeId, agentConfig: AgentNodeConfig<any, any>): ReadonlyArray<AgentConnectionNodeDescriptor> {\n const collected: AgentConnectionNodeDescriptor[] = [];\n this.collectInto(parentNodeId, agentConfig, collected);\n return collected;\n }\n\n private collectInto(\n parentNodeId: NodeId,\n agentConfig: AgentNodeConfig<any, any>,\n collected: AgentConnectionNodeDescriptor[],\n ): void {\n collected.push({\n nodeId: ConnectionNodeIdFactory.languageModelConnectionNodeId(parentNodeId),\n parentNodeId,\n connectionName: \"llm\",\n role: \"languageModel\",\n name: agentConfig.chatModel.presentation?.label ?? agentConfig.chatModel.name,\n typeName: agentConfig.chatModel.name,\n icon: agentConfig.chatModel.presentation?.icon,\n credentialSource: agentConfig.chatModel,\n });\n\n for (const tool of agentConfig.tools ?? []) {\n const toolNodeId = ConnectionNodeIdFactory.toolConnectionNodeId(parentNodeId, tool.name);\n const isNestedAgent = this.isNodeBackedAgentTool(tool);\n collected.push({\n nodeId: toolNodeId,\n parentNodeId,\n connectionName: \"tools\",\n role: isNestedAgent ? \"nestedAgent\" : \"tool\",\n name: tool.presentation?.label ?? tool.name,\n typeName: tool.name,\n icon: tool.presentation?.icon,\n credentialSource: tool,\n });\n this.collectNestedAgentTools(toolNodeId, tool, collected);\n }\n }\n\n private collectNestedAgentTools(\n toolNodeId: NodeId,\n tool: ToolConfig,\n collected: AgentConnectionNodeDescriptor[],\n ): void {\n if (!this.isNodeBackedAgentTool(tool)) {\n return;\n }\n const innerAgent =\n tool instanceof NodeBackedToolConfig ? tool.node : (tool as unknown as { node: AgentNodeConfig<any, any> }).node;\n this.collectInto(toolNodeId, innerAgent, collected);\n }\n\n /**\n * After JSON round-trip (persisted snapshots), tools are plain objects — `instanceof NodeBackedToolConfig` fails.\n * Detect node-backed tools structurally via {@link NodeBackedToolConfig#toolKind}.\n */\n private isNodeBackedAgentTool(tool: ToolConfig): boolean {\n if (tool instanceof NodeBackedToolConfig) {\n return AgentConfigInspector.isAgentNodeConfig(tool.node);\n }\n if (!tool || typeof tool !== \"object\") {\n return false;\n }\n const t = tool as unknown as Record<string, unknown>;\n if (t.toolKind !== \"nodeBacked\") {\n return false;\n }\n return AgentConfigInspector.isAgentNodeConfig(t.node as NodeConfigBase);\n }\n})();\n","import { randomUUID } from \"node:crypto\";\n\nimport type { NodeId } from \"../../types\";\n\n/**\n * Unique ids for persisted connection invocation history rows (LLM/tool calls under an owning node).\n */\nexport class ConnectionInvocationIdFactory {\n static create(): string {\n return `cinv_${randomUUID()}`;\n }\n\n /** Deterministic id for tests when a stable sequence is needed. */\n static createForTest(runId: string, connectionNodeId: NodeId, sequence: number): string {\n return `cinv_${runId}_${connectionNodeId}_${sequence}`;\n }\n}\n","import type { InputPortKey, NodeId, OutputPortKey, WorkflowDefinition, WorkflowGraph } from \"../../types\";\n\nexport class ExecutableGraph implements WorkflowGraph {\n private readonly outgoingByNodeAndPort = new Map<\n NodeId,\n Map<OutputPortKey, Array<Readonly<{ nodeId: NodeId; input: InputPortKey }>>>\n >();\n\n constructor(def: WorkflowDefinition) {\n for (const e of def.edges) {\n const byPort =\n this.outgoingByNodeAndPort.get(e.from.nodeId) ??\n new Map<OutputPortKey, Array<Readonly<{ nodeId: NodeId; input: InputPortKey }>>>();\n const next = byPort.get(e.from.output) ?? [];\n next.push({ nodeId: e.to.nodeId, input: e.to.input });\n byPort.set(e.from.output, next);\n this.outgoingByNodeAndPort.set(e.from.nodeId, byPort);\n }\n }\n\n next(nodeId: NodeId, output: OutputPortKey): Array<Readonly<{ nodeId: NodeId; input: InputPortKey }>> {\n return this.outgoingByNodeAndPort.get(nodeId)?.get(output) ?? [];\n }\n}\n","import type { WorkflowDefinition, WorkflowGraph, WorkflowGraphFactory } from \"../../types\";\nimport { ExecutableGraph } from \"./ExecutableGraph\";\n\nexport class DefaultWorkflowGraphFactory implements WorkflowGraphFactory {\n create(def: WorkflowDefinition): WorkflowGraph {\n return new ExecutableGraph(def);\n }\n}\n","import type {\n PersistedRunSchedulingState,\n PersistedRunState,\n RunId,\n RunPruneCandidate,\n RunSummary,\n WorkflowExecutionListingRepository,\n WorkflowExecutionPruneRepository,\n WorkflowExecutionRepository,\n WorkflowId,\n} from \"../types\";\nimport type { RunEventBus } from \"./runEvents\";\n\nexport class EventPublishingWorkflowExecutionRepository\n implements WorkflowExecutionRepository, WorkflowExecutionListingRepository, WorkflowExecutionPruneRepository\n{\n constructor(\n private readonly inner: WorkflowExecutionRepository,\n private readonly eventBus: RunEventBus,\n private readonly now: () => Date = () => new Date(),\n ) {}\n\n async createRun(args: Parameters<WorkflowExecutionRepository[\"createRun\"]>[0]): Promise<void> {\n await this.inner.createRun(args);\n await this.eventBus.publish({\n kind: \"runCreated\",\n runId: args.runId,\n workflowId: args.workflowId,\n parent: args.parent,\n at: this.now().toISOString(),\n });\n }\n\n async load(runId: RunId): Promise<PersistedRunState | undefined> {\n return await this.inner.load(runId);\n }\n\n async loadSchedulingState(runId: RunId): Promise<PersistedRunSchedulingState | undefined> {\n return await this.inner.loadSchedulingState(runId);\n }\n\n async save(state: PersistedRunState): Promise<void> {\n await this.inner.save(state);\n await this.eventBus.publish({\n kind: \"runSaved\",\n runId: state.runId,\n workflowId: state.workflowId,\n parent: state.parent,\n at: this.now().toISOString(),\n state,\n });\n }\n\n async deleteRun(runId: RunId): Promise<void> {\n if (!this.inner.deleteRun) return;\n await this.inner.deleteRun(runId);\n }\n\n async listRuns(args?: Readonly<{ workflowId?: WorkflowId; limit?: number }>): Promise<ReadonlyArray<RunSummary>> {\n const listingRepository = this.inner as unknown as Partial<WorkflowExecutionListingRepository>;\n if (!listingRepository.listRuns) return [];\n return await listingRepository.listRuns(args);\n }\n\n async listRunsOlderThan(\n args: Readonly<{ nowIso: string; defaultRetentionSeconds: number; limit?: number }>,\n ): Promise<ReadonlyArray<RunPruneCandidate>> {\n const pruneRepository = this.inner as unknown as Partial<WorkflowExecutionPruneRepository>;\n if (!pruneRepository.listRunsOlderThan) return [];\n return await pruneRepository.listRunsOlderThan(args);\n }\n}\n","import type { Item, Items } from \"../contracts/workflowTypes\";\nimport { injectable } from \"../di\";\n\n/**\n * Normalizes external inputs into the engine's canonical `Items` shape.\n * Used at host and builder boundaries where callers may provide either a raw value,\n * a single item-like object, or an array of item-like values.\n */\n@injectable()\nexport class ItemsInputNormalizer {\n normalize(raw: unknown): Items {\n if (raw === undefined || raw === null) {\n return [];\n }\n if (Array.isArray(raw)) {\n return raw.map((value) => this.normalizeItem(value));\n }\n return [this.normalizeItem(raw)];\n }\n\n private normalizeItem(raw: unknown): Item {\n if (!this.isItem(raw)) {\n return { json: raw };\n }\n return {\n json: raw.json,\n ...(raw.binary === undefined ? {} : { binary: raw.binary }),\n ...(raw.meta === undefined ? {} : { meta: raw.meta }),\n ...(raw.paired === undefined ? {} : { paired: raw.paired }),\n };\n }\n\n private isItem(raw: unknown): raw is Item {\n return typeof raw === \"object\" && raw !== null && Object.prototype.hasOwnProperty.call(raw, \"json\");\n }\n}\n"],"mappings":";;;;;;;;;;AAKA,IAAa,cAAb,MAA0C;CACxC,MAAY;AACV,yBAAO,IAAI,MAAM;;;;;;ACLrB,IAAa,sBAAb,MAAiC;CAC/B,OAAwB,8BAAc,IAAI,KAGvC;CAEH,OAAO,SAAS,YAAkF;AAChG,OAAK,YAAY,IAAI,WAAW,KAAK,WAAW;;CAGlD,OAAO,QAAQ,KAAyF;AACtG,SAAO,KAAK,YAAY,IAAI,IAAI;;;;;;AC0IpC,MAAM,0CAA0C;CAC9C,OAAO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file":"index.cjs","names":["definedNodeCredentialRequirementFactory","definedNodeCredentialAccessorFactory","context: DefinedNodeRunContext<TConfig, TBindings>","payload: DefineNodeExecuteArgs<TConfig, TInputJson>","name: string","id?: string","definition: DefinedNode<TKey, TConfig, TInputJson, TOutputJson, TBindings>","z","current: z.ZodTypeAny","name: string","ZodError","_type: CollectionFieldType","fields: Record<string, CollectionFieldDefinition>","definition: CollectionDefinition","name: string","cfg: TConfig","credentialRequirements: ReadonlyArray<CredentialRequirement>","id?: string","seedWrapped: InternalWrappedState","wrapped: InternalWrappedState","newItems: Array<{ json: TItemJson }>","newKeys: string[]","NodeBackedToolConfig","node","AgentConfigInspector","out: AgentMessageDto[]","isItemExpr","messages: AgentMessageDto[]","inner: WorkflowExecutionRepository","eventBus: RunEventBus","now: () => Date","ItemsInputNormalizer"],"sources":["../src/contracts/Clock.ts","../src/authoring/DefinedNodeRegistry.ts","../src/authoring/defineNode.types.ts","../src/authoring/defineCredential.types.ts","../src/ai/CallableToolKindToken.ts","../src/ai/CallableToolConfig.ts","../src/ai/CallableToolFactory.ts","../src/authoring/callableTool.types.ts","../src/authoring/DefinedCollectionRegistry.ts","../src/authoring/defineCollection.types.ts","../src/authoring/definePollingTriggerInternals.ts","../src/authoring/definePollingTrigger.types.ts","../src/ai/AgentToolFactory.ts","../src/ai/AgentMessageConfigNormalizerFactory.ts","../src/ai/AiHost.ts","../src/events/EventPublishingWorkflowExecutionRepository.ts","../src/serialization/ItemsInputNormalizer.ts","../src/contracts/assertionTypes.ts"],"sourcesContent":["/** Port for time; inject `SystemClock` in production and a fake/test clock in tests. */\nexport interface Clock {\n now(): Date;\n}\n\nexport class SystemClock implements Clock {\n now(): Date {\n return new Date();\n }\n}\n","import type { DefinedNode } from \"./defineNode.types\";\n\nexport class DefinedNodeRegistry {\n private static readonly definitions = new Map<\n string,\n DefinedNode<string, Record<string, unknown>, unknown, unknown>\n >();\n\n static register(definition: DefinedNode<string, Record<string, unknown>, unknown, unknown>): void {\n this.definitions.set(definition.key, definition);\n }\n\n static resolve(key: string): DefinedNode<string, Record<string, unknown>, unknown, unknown> | undefined {\n return this.definitions.get(key);\n }\n}\n","import type {\n AnyCredentialType,\n CredentialJsonRecord,\n CredentialRequirement,\n CredentialTypeId,\n} from \"../contracts/credentialTypes\";\nimport type { ParamDeep } from \"../contracts/params\";\nimport type { RunnableNode, RunnableNodeExecuteArgs, NodeExecutionContext } from \"../contracts/runtimeTypes\";\nimport type { Item, Items, RunnableNodeConfig } from \"../contracts/workflowTypes\";\nimport type { TypeToken } from \"../di\";\nimport { node as persistedNode } from \"../runtime-types/runtimeTypeDecorators.types\";\nimport type { ZodType } from \"zod\";\nimport { z } from \"zod\";\nimport { DefinedNodeRegistry } from \"./DefinedNodeRegistry\";\n\ntype MaybePromise<TValue> = TValue | Promise<TValue>;\n\ntype ResolvableCredentialType = AnyCredentialType | CredentialTypeId;\n\ntype SessionForCredentialType<TCredential extends ResolvableCredentialType> = TCredential extends AnyCredentialType\n ? Awaited<ReturnType<TCredential[\"createSession\"]>>\n : unknown;\n\nexport type DefinedNodeCredentialBinding =\n | ResolvableCredentialType\n | Readonly<{\n readonly type: ResolvableCredentialType | ReadonlyArray<ResolvableCredentialType>;\n readonly label?: string;\n readonly optional?: true;\n readonly helpText?: string;\n readonly helpUrl?: string;\n }>;\n\nexport type DefinedNodeCredentialBindings = Readonly<Record<string, DefinedNodeCredentialBinding>>;\n\ntype SessionForBinding<TBinding extends DefinedNodeCredentialBinding> =\n TBinding extends Readonly<{ type: infer TType }>\n ? TType extends ReadonlyArray<infer TEntry>\n ? SessionForCredentialType<TEntry & ResolvableCredentialType>\n : SessionForCredentialType<TType & ResolvableCredentialType>\n : SessionForCredentialType<TBinding & ResolvableCredentialType>;\n\nexport type DefinedNodeCredentialAccessors<TBindings extends DefinedNodeCredentialBindings | undefined> =\n TBindings extends DefinedNodeCredentialBindings\n ? Readonly<{\n [TKey in keyof TBindings]: () => Promise<SessionForBinding<TBindings[TKey]>>;\n }>\n : Readonly<Record<string, never>>;\n\nexport interface DefinedNodeRunContext<\n TConfig extends CredentialJsonRecord,\n TBindings extends DefinedNodeCredentialBindings | undefined,\n> {\n readonly config: TConfig;\n readonly credentials: DefinedNodeCredentialAccessors<TBindings>;\n readonly execution: NodeExecutionContext<RunnableNodeConfig<TConfig, unknown>>;\n}\n\n/**\n * Arguments for {@link defineNode} `execute` (engine `ctx` matches {@link RunnableNode.execute};\n * the second callback parameter adds {@link DefinedNodeRunContext} for credential accessors).\n */\nexport type DefineNodeExecuteArgs<TConfig extends CredentialJsonRecord, TInputJson> = Readonly<{\n input: TInputJson;\n item: Item;\n itemIndex: number;\n items: Items;\n ctx: NodeExecutionContext<RunnableNodeConfig<TInputJson, unknown> & Readonly<{ config: TConfig }>>;\n}>;\n\nexport type DefinedNodeConfigInput<TConfigResolved extends CredentialJsonRecord, TItemJson> = ParamDeep<\n TConfigResolved,\n TItemJson\n>;\n\nexport interface DefinedNode<\n TKey extends string,\n TConfig extends CredentialJsonRecord,\n TInputJson,\n TOutputJson,\n _TBindings extends DefinedNodeCredentialBindings | undefined = undefined,\n> {\n readonly kind: \"defined-node\";\n readonly key: TKey;\n readonly title: string;\n readonly description?: string;\n create<TConfigItemJson = TInputJson>(\n config: DefinedNodeConfigInput<TConfig, TConfigItemJson>,\n name?: string,\n id?: string,\n ): RunnableNodeConfig<TInputJson, TOutputJson>;\n register(context: { registerNode<TValue>(token: TypeToken<TValue>, implementation?: TypeToken<TValue>): void }): void;\n}\n\n/**\n * Plugin / DSL-friendly node: per-item `execute` with optional {@link RunnableNodeConfig.inputSchema}.\n */\nexport interface DefineNodeOptions<\n TKey extends string,\n TConfig extends CredentialJsonRecord,\n TInputJson,\n TOutputJson,\n TBindings extends DefinedNodeCredentialBindings | undefined = undefined,\n> {\n readonly key: TKey;\n readonly title: string;\n readonly description?: string;\n /**\n * Canvas icon for this node (same contract as `NodeConfigBase.icon` on runnable configs).\n * The Next host resolves Lucide (`lucide:…`), built-in SVGs (`builtin:…`), Simple Icons (`si:…`), and image URLs (`https:`, `data:`, `/…`).\n */\n readonly icon?: string;\n /** Default values / form hints for **static** node configuration (credentials, retry, IDs), not per-item payload. */\n readonly input?: Readonly<Record<keyof TConfig & string, unknown>>;\n readonly configSchema?: z.ZodType<TConfig>;\n readonly credentials?: TBindings;\n /**\n * Validates **`input`** (engine also accepts `inputSchema` on the node class).\n */\n readonly inputSchema?: ZodType<TInputJson>;\n /** Preserve inbound `item.binary` when `execute` returns plain JSON or item-shaped results without `binary`. */\n readonly keepBinaries?: boolean;\n execute(\n args: DefineNodeExecuteArgs<TConfig, TInputJson>,\n context: DefinedNodeRunContext<TConfig, TBindings>,\n ): MaybePromise<TOutputJson>;\n}\n\n/**\n * Batch-oriented defined node: `run` receives all item JSON once (last item in activation); emits one output per input row.\n */\nexport interface DefineBatchNodeOptions<\n TKey extends string,\n TConfig extends CredentialJsonRecord,\n TInputJson,\n TOutputJson,\n TBindings extends DefinedNodeCredentialBindings | undefined = undefined,\n> {\n readonly key: TKey;\n readonly title: string;\n readonly description?: string;\n readonly icon?: string;\n readonly input?: Readonly<Record<keyof TConfig & string, unknown>>;\n readonly configSchema?: z.ZodType<TConfig>;\n readonly credentials?: TBindings;\n run(\n items: ReadonlyArray<TInputJson>,\n context: DefinedNodeRunContext<TConfig, TBindings>,\n ): MaybePromise<ReadonlyArray<TOutputJson>>;\n}\n\nconst definedNodeCredentialRequirementFactory = {\n create(bindings: DefinedNodeCredentialBindings | undefined): ReadonlyArray<CredentialRequirement> {\n if (!bindings) {\n return [];\n }\n return Object.entries(bindings).map(([slotKey, binding]) => {\n if (typeof binding === \"string\" || this.isCredentialType(binding)) {\n return {\n slotKey,\n label: this.humanize(slotKey),\n acceptedTypes: [this.resolveTypeId(binding)],\n };\n }\n\n const types = Array.isArray(binding.type) ? binding.type : [binding.type];\n return {\n slotKey,\n label: binding.label ?? this.humanize(slotKey),\n acceptedTypes: types.map((entry) => this.resolveTypeId(entry)),\n optional: binding.optional,\n helpText: binding.helpText,\n helpUrl: binding.helpUrl,\n };\n });\n },\n\n isCredentialType(value: unknown): value is AnyCredentialType {\n return (\n Boolean(value) &&\n typeof value === \"object\" &&\n \"definition\" in (value as Record<string, unknown>) &&\n typeof (value as AnyCredentialType).definition?.typeId === \"string\"\n );\n },\n\n resolveTypeId(type: ResolvableCredentialType): string {\n return typeof type === \"string\" ? type : type.definition.typeId;\n },\n\n humanize(key: string): string {\n return key\n .replace(/([a-z0-9])([A-Z])/g, \"$1 $2\")\n .replace(/[-_.]+/g, \" \")\n .replace(/\\s+/g, \" \")\n .trim()\n .replace(/^./, (character) => character.toUpperCase());\n },\n} as const;\n\nconst definedNodeCredentialAccessorFactory = {\n create<TBindings extends DefinedNodeCredentialBindings | undefined>(\n bindings: TBindings,\n ctx: NodeExecutionContext<RunnableNodeConfig<any, any>>,\n ): DefinedNodeCredentialAccessors<TBindings> {\n if (!bindings) {\n return {} as DefinedNodeCredentialAccessors<TBindings>;\n }\n const entries = Object.keys(bindings).map((slotKey) => [slotKey, () => ctx.getCredential(slotKey)] as const);\n return Object.fromEntries(entries) as DefinedNodeCredentialAccessors<TBindings>;\n },\n} as const;\n\nexport function defineNode<\n TKey extends string,\n TConfig extends CredentialJsonRecord,\n TInputJson,\n TOutputJson,\n TBindings extends DefinedNodeCredentialBindings | undefined = undefined,\n>(\n options: DefineNodeOptions<TKey, TConfig, TInputJson, TOutputJson, TBindings>,\n): DefinedNode<TKey, TConfig, TInputJson, TOutputJson, TBindings> {\n const credentialRequirements = definedNodeCredentialRequirementFactory.create(options.credentials);\n type DefinedRunnableNodeConfigShape = RunnableNodeConfig<TInputJson, TOutputJson> & Readonly<{ config: TConfig }>;\n\n const DefinedNodeRuntime = class implements RunnableNode<DefinedRunnableNodeConfigShape, TInputJson, TOutputJson> {\n readonly kind = \"node\" as const;\n readonly outputPorts = [\"main\"] as const;\n readonly inputSchema = options.inputSchema;\n\n async execute(\n args: Readonly<RunnableNodeExecuteArgs<DefinedRunnableNodeConfigShape, TInputJson>>,\n ): Promise<unknown> {\n const ctx = args.ctx;\n const context: DefinedNodeRunContext<TConfig, TBindings> = {\n config: ctx.config.config,\n credentials: definedNodeCredentialAccessorFactory.create(\n options.credentials,\n ctx,\n ) as DefinedNodeCredentialAccessors<TBindings>,\n execution: ctx as unknown as NodeExecutionContext<RunnableNodeConfig<TConfig, unknown>>,\n };\n const payload: DefineNodeExecuteArgs<TConfig, TInputJson> = {\n input: args.input,\n item: args.item,\n itemIndex: args.itemIndex,\n items: args.items,\n ctx,\n };\n return await options.execute(payload, context);\n }\n };\n\n persistedNode({ name: options.key })(DefinedNodeRuntime);\n\n const DefinedRunnableNodeConfig = class implements RunnableNodeConfig<TInputJson, TOutputJson> {\n readonly kind = \"node\" as const;\n readonly type: TypeToken<unknown> = DefinedNodeRuntime;\n readonly icon = options.icon;\n readonly inputSchema = options.inputSchema;\n readonly keepBinaries = options.keepBinaries ?? false;\n\n constructor(\n public readonly name: string,\n config: DefinedNodeConfigInput<TConfig, unknown>,\n public readonly id?: string,\n ) {\n this.config = config as unknown as TConfig;\n }\n\n public readonly config: TConfig;\n\n getCredentialRequirements(): ReadonlyArray<CredentialRequirement> {\n return credentialRequirements;\n }\n };\n\n const definition: DefinedNode<TKey, TConfig, TInputJson, TOutputJson, TBindings> = {\n kind: \"defined-node\",\n key: options.key,\n title: options.title,\n description: options.description,\n create<TConfigItemJson = TInputJson>(\n config: DefinedNodeConfigInput<TConfig, TConfigItemJson>,\n name = options.title,\n id?: string,\n ) {\n return new DefinedRunnableNodeConfig(name, config as DefinedNodeConfigInput<TConfig, unknown>, id);\n },\n register(context) {\n context.registerNode(DefinedNodeRuntime);\n },\n };\n\n DefinedNodeRegistry.register(definition as DefinedNode<string, Record<string, unknown>, unknown, unknown, undefined>);\n\n return definition;\n}\n\nexport function defineBatchNode<\n TKey extends string,\n TConfig extends CredentialJsonRecord,\n TInputJson,\n TOutputJson,\n TBindings extends DefinedNodeCredentialBindings | undefined = undefined,\n>(\n options: DefineBatchNodeOptions<TKey, TConfig, TInputJson, TOutputJson, TBindings>,\n): DefinedNode<TKey, TConfig, TInputJson, TOutputJson, TBindings> {\n const credentialRequirements = definedNodeCredentialRequirementFactory.create(options.credentials);\n type DefinedRunnableNodeConfigShape = RunnableNodeConfig<TInputJson, TOutputJson> & Readonly<{ config: TConfig }>;\n\n const DefinedNodeRuntime = class implements RunnableNode<DefinedRunnableNodeConfigShape, TInputJson, TOutputJson> {\n readonly kind = \"node\" as const;\n readonly outputPorts = [\"main\"] as const;\n\n async execute(\n args: Readonly<RunnableNodeExecuteArgs<DefinedRunnableNodeConfigShape, TInputJson>>,\n ): Promise<unknown> {\n if (args.itemIndex !== args.items.length - 1) {\n return [];\n }\n const ctx = args.ctx;\n const context: DefinedNodeRunContext<TConfig, TBindings> = {\n config: ctx.config.config,\n credentials: definedNodeCredentialAccessorFactory.create(\n options.credentials,\n ctx,\n ) as DefinedNodeCredentialAccessors<TBindings>,\n execution: ctx as unknown as NodeExecutionContext<RunnableNodeConfig<TConfig, unknown>>,\n };\n const outputs = await options.run(\n args.items.map((item) => item.json as TInputJson),\n context,\n );\n return [...outputs];\n }\n };\n\n persistedNode({ name: options.key })(DefinedNodeRuntime);\n\n const DefinedRunnableNodeConfig = class implements RunnableNodeConfig<TInputJson, TOutputJson> {\n readonly kind = \"node\" as const;\n readonly type: TypeToken<unknown> = DefinedNodeRuntime;\n readonly icon = options.icon;\n\n constructor(\n public readonly name: string,\n config: DefinedNodeConfigInput<TConfig, unknown>,\n public readonly id?: string,\n ) {\n this.config = config as unknown as TConfig;\n }\n\n public readonly config: TConfig;\n\n getCredentialRequirements(): ReadonlyArray<CredentialRequirement> {\n return credentialRequirements;\n }\n };\n\n const definition: DefinedNode<TKey, TConfig, TInputJson, TOutputJson, TBindings> = {\n kind: \"defined-node\",\n key: options.key,\n title: options.title,\n description: options.description,\n create<TConfigItemJson = TInputJson>(\n config: DefinedNodeConfigInput<TConfig, TConfigItemJson>,\n name = options.title,\n id?: string,\n ) {\n return new DefinedRunnableNodeConfig(name, config as DefinedNodeConfigInput<TConfig, unknown>, id);\n },\n register(context) {\n context.registerNode(DefinedNodeRuntime);\n },\n };\n\n DefinedNodeRegistry.register(definition as DefinedNode<string, Record<string, unknown>, unknown, unknown, undefined>);\n\n return definition;\n}\n","import type {\n AnyCredentialType,\n CredentialFieldSchema,\n CredentialHealth,\n CredentialJsonRecord,\n CredentialSessionFactoryArgs,\n CredentialType,\n CredentialTypeDefinition,\n} from \"../contracts/credentialTypes\";\nimport { z } from \"zod\";\n\ntype MaybePromise<TValue> = TValue | Promise<TValue>;\n\ntype CredentialFieldInput = CredentialFieldSchema[\"type\"] | Readonly<Omit<CredentialFieldSchema, \"key\">>;\n\ntype CredentialFieldMap<TConfig extends CredentialJsonRecord> = Readonly<\n Record<keyof TConfig & string, CredentialFieldInput>\n>;\n\ntype ZodObjectSchema<TConfig extends CredentialJsonRecord = CredentialJsonRecord> = z.ZodType<TConfig>;\n\ntype InferCredentialConfig<TSource> =\n TSource extends z.ZodType<infer TConfig, any, any>\n ? Readonly<TConfig> & CredentialJsonRecord\n : TSource extends CredentialFieldMap<infer TConfig>\n ? TConfig\n : CredentialJsonRecord;\n\nexport interface DefineCredentialOptions<\n TPublicSource extends CredentialFieldMap<any> | ZodObjectSchema<any>,\n TSecretSource extends CredentialFieldMap<any> | ZodObjectSchema<any>,\n TSession,\n> {\n readonly key: string;\n readonly label: string;\n readonly description?: string;\n readonly public: TPublicSource;\n readonly secret: TSecretSource;\n readonly supportedSourceKinds?: CredentialTypeDefinition[\"supportedSourceKinds\"];\n readonly auth?: CredentialTypeDefinition[\"auth\"];\n createSession(\n args: CredentialSessionFactoryArgs<InferCredentialConfig<TPublicSource>, InferCredentialConfig<TSecretSource>>,\n ): MaybePromise<TSession>;\n test(\n args: CredentialSessionFactoryArgs<InferCredentialConfig<TPublicSource>, InferCredentialConfig<TSecretSource>>,\n ): MaybePromise<CredentialHealth>;\n}\n\nexport class CredentialFieldSchemaFactory {\n static create<TConfig extends CredentialJsonRecord>(\n source: CredentialFieldMap<TConfig> | ZodObjectSchema<TConfig>,\n ): ReadonlyArray<CredentialFieldSchema> {\n if (source instanceof z.ZodObject) {\n return this.createFromZodObject(source);\n }\n return this.createFromMap(source as CredentialFieldMap<TConfig>);\n }\n\n private static createFromMap<TConfig extends CredentialJsonRecord>(\n source: CredentialFieldMap<TConfig>,\n ): ReadonlyArray<CredentialFieldSchema> {\n return Object.entries(source).map(([key, input], index) => {\n if (typeof input === \"string\") {\n return {\n key,\n label: this.humanize(key),\n order: index,\n type: input as CredentialFieldSchema[\"type\"],\n };\n }\n return {\n key,\n order: index,\n ...(input as Readonly<Omit<CredentialFieldSchema, \"key\">>),\n };\n });\n }\n\n private static createFromZodObject<_TConfig extends CredentialJsonRecord>(\n source: z.ZodObject,\n ): ReadonlyArray<CredentialFieldSchema> {\n const shape = source.shape;\n return Object.entries(shape).map(([key, schema], index) => {\n const resolved = this.unwrap(schema);\n return {\n key,\n label: this.humanize(key),\n order: index,\n required: this.isRequired(schema) ? true : undefined,\n type: this.resolveType(resolved),\n };\n });\n }\n\n private static isRequired(schema: z.ZodTypeAny): boolean {\n return !(schema instanceof z.ZodOptional || schema instanceof z.ZodDefault);\n }\n\n private static unwrap(schema: z.ZodTypeAny): z.ZodTypeAny {\n let current: z.ZodTypeAny = schema;\n while (current instanceof z.ZodOptional || current instanceof z.ZodDefault) {\n current = current.unwrap() as z.ZodTypeAny;\n }\n return current;\n }\n\n private static resolveType(schema: z.ZodTypeAny): CredentialFieldSchema[\"type\"] {\n if (schema instanceof z.ZodBoolean) {\n return \"boolean\";\n }\n if (schema instanceof z.ZodString) {\n return \"string\";\n }\n return \"json\";\n }\n\n private static humanize(key: string): string {\n return key\n .replace(/([a-z0-9])([A-Z])/g, \"$1 $2\")\n .replace(/[-_.]+/g, \" \")\n .replace(/\\s+/g, \" \")\n .trim()\n .replace(/^./, (character) => character.toUpperCase());\n }\n}\n\nexport function defineCredential<\n TPublicSource extends CredentialFieldMap<any> | ZodObjectSchema<any>,\n TSecretSource extends CredentialFieldMap<any> | ZodObjectSchema<any>,\n TSession,\n>(\n options: DefineCredentialOptions<TPublicSource, TSecretSource, TSession>,\n): CredentialType<InferCredentialConfig<TPublicSource>, InferCredentialConfig<TSecretSource>, TSession> & {\n readonly key: string;\n} {\n const definition: CredentialTypeDefinition = {\n typeId: options.key,\n displayName: options.label,\n description: options.description,\n publicFields: CredentialFieldSchemaFactory.create(options.public),\n secretFields: CredentialFieldSchemaFactory.create(options.secret),\n supportedSourceKinds: options.supportedSourceKinds ?? [\"db\", \"env\", \"code\"],\n auth: options.auth,\n };\n\n const credentialType: AnyCredentialType = {\n definition,\n async createSession(args) {\n return await options.createSession(\n args as CredentialSessionFactoryArgs<\n InferCredentialConfig<TPublicSource>,\n InferCredentialConfig<TSecretSource>\n >,\n );\n },\n async test(args) {\n return await options.test(\n args as CredentialSessionFactoryArgs<\n InferCredentialConfig<TPublicSource>,\n InferCredentialConfig<TSecretSource>\n >,\n );\n },\n };\n\n return {\n ...credentialType,\n key: options.key,\n } as CredentialType<InferCredentialConfig<TPublicSource>, InferCredentialConfig<TSecretSource>, TSession> & {\n readonly key: string;\n };\n}\n","/**\n * Shared {@link import(\"../di\").TypeToken} marker for {@link CallableToolConfig}.\n * Callable tools are not registered in {@link NodeResolver}; this class only satisfies {@link ToolConfig#type}.\n */\nexport class CallableToolKindToken {}\n","import type { CredentialRequirement } from \"../contracts/credentialTypes\";\nimport type { TypeToken } from \"../di\";\nimport type { AgentCanvasPresentation, ToolConfig, ToolExecuteArgs, ZodSchemaAny } from \"./AiHost\";\nimport { ZodError, type input as ZodInput, type output as ZodOutput } from \"zod\";\n\nimport { CallableToolKindToken } from \"./CallableToolKindToken\";\n\nexport type CallableToolExecuteHandler<TInputSchema extends ZodSchemaAny, TOutputSchema extends ZodSchemaAny> = (\n args: ToolExecuteArgs<CallableToolConfig<TInputSchema, TOutputSchema>, ZodInput<TInputSchema>>,\n) => Promise<ZodOutput<TOutputSchema>> | ZodOutput<TOutputSchema>;\n\nexport type CallableToolConfigOptions<\n TInputSchema extends ZodSchemaAny,\n TOutputSchema extends ZodSchemaAny,\n> = Readonly<{\n name: string;\n description?: string;\n presentation?: AgentCanvasPresentation;\n inputSchema: TInputSchema;\n outputSchema: TOutputSchema;\n /**\n * Optional credential slots for this tool (same contract as other {@link ToolConfig} shapes).\n */\n credentialRequirements?: ReadonlyArray<CredentialRequirement>;\n execute: CallableToolExecuteHandler<TInputSchema, TOutputSchema>;\n}>;\n\n/**\n * Inline callable agent tool: DSL sugar over {@link ToolConfig} without a separate {@link NodeResolver}-registered {@link Tool} class.\n */\nexport class CallableToolConfig<\n TInputSchema extends ZodSchemaAny,\n TOutputSchema extends ZodSchemaAny,\n> implements ToolConfig {\n readonly type: TypeToken<unknown> = CallableToolKindToken;\n readonly toolKind = \"callable\" as const;\n readonly description?: string;\n readonly presentation?: AgentCanvasPresentation;\n private readonly inputSchemaValue: TInputSchema;\n private readonly outputSchemaValue: TOutputSchema;\n private readonly credentialRequirementsValue?: ReadonlyArray<CredentialRequirement>;\n private readonly executeHandler: CallableToolExecuteHandler<TInputSchema, TOutputSchema>;\n\n constructor(\n public readonly name: string,\n options: CallableToolConfigOptions<TInputSchema, TOutputSchema>,\n ) {\n this.description = options.description;\n this.presentation = options.presentation;\n this.inputSchemaValue = options.inputSchema;\n this.outputSchemaValue = options.outputSchema;\n this.credentialRequirementsValue = options.credentialRequirements;\n this.executeHandler = options.execute;\n }\n\n getCredentialRequirements(): ReadonlyArray<CredentialRequirement> {\n return this.credentialRequirementsValue ?? [];\n }\n\n getInputSchema(): TInputSchema {\n return this.inputSchemaValue;\n }\n\n getOutputSchema(): TOutputSchema {\n return this.outputSchemaValue;\n }\n\n /**\n * Parses tool input and output with the configured Zod schemas.\n */\n async executeTool(\n args: ToolExecuteArgs<CallableToolConfig<TInputSchema, TOutputSchema>, ZodInput<TInputSchema>>,\n ): Promise<ZodOutput<TOutputSchema>> {\n const parsedInput = this.parseInput(args.input);\n const raw = await Promise.resolve(\n this.executeHandler({\n ...args,\n config: this,\n input: parsedInput,\n }),\n );\n return this.parseOutput(raw);\n }\n\n private parseInput(input: unknown): ZodInput<TInputSchema> {\n try {\n return this.inputSchemaValue.parse(input) as ZodInput<TInputSchema>;\n } catch (error) {\n throw this.decorateValidationError(error, \"input\");\n }\n }\n\n private parseOutput(output: unknown): ZodOutput<TOutputSchema> {\n try {\n return this.outputSchemaValue.parse(output) as ZodOutput<TOutputSchema>;\n } catch (error) {\n throw this.decorateValidationError(error, \"output\");\n }\n }\n\n private decorateValidationError(error: unknown, stage: \"input\" | \"output\"): Error {\n if (error instanceof ZodError) {\n (error as ZodError & { codemationToolValidationStage?: \"input\" | \"output\" }).codemationToolValidationStage =\n stage;\n return error;\n }\n return error instanceof Error ? error : new Error(String(error));\n }\n}\n","import type { ZodSchemaAny } from \"./AiHost\";\nimport { CallableToolConfig } from \"./CallableToolConfig\";\nimport type { CallableToolConfigOptions } from \"./CallableToolConfig\";\n\nclass CallableToolFactoryImpl {\n callableTool<TInputSchema extends ZodSchemaAny, TOutputSchema extends ZodSchemaAny>(\n options: CallableToolConfigOptions<TInputSchema, TOutputSchema>,\n ): CallableToolConfig<TInputSchema, TOutputSchema> {\n return new CallableToolConfig(options.name, options);\n }\n}\n\nexport const CallableToolFactory = new CallableToolFactoryImpl();\n","import type { ZodSchemaAny } from \"../ai/AiHost\";\nimport type { CallableToolConfig, CallableToolConfigOptions } from \"../ai/CallableToolConfig\";\nimport { CallableToolFactory } from \"../ai/CallableToolFactory\";\n\n/**\n * Workflow-facing helper for inline Zod-typed agent tools (same as {@link CallableToolFactory.callableTool}).\n */\nexport function callableTool<TInputSchema extends ZodSchemaAny, TOutputSchema extends ZodSchemaAny>(\n options: CallableToolConfigOptions<TInputSchema, TOutputSchema>,\n): CallableToolConfig<TInputSchema, TOutputSchema> {\n return CallableToolFactory.callableTool(options);\n}\n","import type { CollectionDefinition } from \"./defineCollection.types\";\n\nexport class DefinedCollectionRegistry {\n private static readonly definitions = new Map<string, CollectionDefinition>();\n\n static register(definition: CollectionDefinition): void {\n this.definitions.set(definition.name, definition);\n }\n\n static resolve(name: string): CollectionDefinition | undefined {\n return this.definitions.get(name);\n }\n\n static list(): ReadonlyArray<CollectionDefinition> {\n return Array.from(this.definitions.values());\n }\n}\n","import { DefinedCollectionRegistry } from \"./DefinedCollectionRegistry\";\n\nexport type CollectionFieldType = \"text\" | \"int\" | \"bigint\" | \"double\" | \"bool\" | \"timestamptz\" | \"jsonb\" | \"uuid\";\n\nexport interface CollectionColumnBuilder {\n notNull(): CollectionColumnBuilder;\n default(value: unknown): CollectionColumnBuilder;\n readonly _type: CollectionFieldType;\n readonly _nullable: boolean;\n readonly _default?: unknown;\n}\n\nclass CollectionColumnBuilderImpl implements CollectionColumnBuilder {\n _nullable: boolean;\n _default?: unknown;\n\n constructor(readonly _type: CollectionFieldType) {\n this._nullable = true;\n }\n\n notNull(): CollectionColumnBuilder {\n this._nullable = false;\n return this;\n }\n\n default(value: unknown): CollectionColumnBuilder {\n this._default = value;\n this._nullable = false;\n return this;\n }\n}\n\nexport const c = {\n text(): CollectionColumnBuilder {\n return new CollectionColumnBuilderImpl(\"text\");\n },\n int(): CollectionColumnBuilder {\n return new CollectionColumnBuilderImpl(\"int\");\n },\n bigint(): CollectionColumnBuilder {\n return new CollectionColumnBuilderImpl(\"bigint\");\n },\n double(): CollectionColumnBuilder {\n return new CollectionColumnBuilderImpl(\"double\");\n },\n bool(): CollectionColumnBuilder {\n return new CollectionColumnBuilderImpl(\"bool\");\n },\n timestamptz(): CollectionColumnBuilder {\n return new CollectionColumnBuilderImpl(\"timestamptz\");\n },\n jsonb(): CollectionColumnBuilder {\n return new CollectionColumnBuilderImpl(\"jsonb\");\n },\n uuid(): CollectionColumnBuilder {\n return new CollectionColumnBuilderImpl(\"uuid\");\n },\n} as const;\n\nexport interface CollectionFieldDefinition {\n readonly type: CollectionFieldType;\n readonly nullable: boolean;\n readonly default?: unknown;\n}\n\nexport interface CollectionIndexDefinition {\n readonly on: ReadonlyArray<string>;\n readonly unique?: boolean;\n}\n\nexport interface CollectionDefinition {\n readonly name: string;\n readonly fields: Readonly<Record<string, CollectionFieldDefinition>>;\n readonly indexes: ReadonlyArray<CollectionIndexDefinition>;\n}\n\nexport interface DefinedCollection<TDefinition extends CollectionDefinition = CollectionDefinition> {\n readonly kind: \"defined-collection\";\n readonly definition: TDefinition;\n register(context: { registerCollection(d: CollectionDefinition): void }): void;\n}\n\n/**\n * Validates that a name follows the required pattern: lowercase + underscores, starts with letter.\n */\nfunction validateCollectionName(name: string): void {\n const pattern = /^[a-z][a-z0-9_]*$/;\n if (!pattern.test(name)) {\n throw new Error(\n `Collection name \"${name}\" must start with a lowercase letter and contain only lowercase letters, digits, and underscores.`,\n );\n }\n}\n\n/**\n * Validates that all field names follow the required pattern.\n */\nfunction validateFieldNames(fields: Record<string, CollectionFieldDefinition>): void {\n const pattern = /^[a-z][a-z0-9_]*$/;\n const reserved = [\"id\", \"created_at\", \"updated_at\"];\n\n for (const fieldName of Object.keys(fields)) {\n if (reserved.includes(fieldName)) {\n throw new Error(`Field name \"${fieldName}\" is reserved for internal use.`);\n }\n if (!pattern.test(fieldName)) {\n throw new Error(\n `Field name \"${fieldName}\" must start with a lowercase letter and contain only lowercase letters, digits, and underscores.`,\n );\n }\n }\n}\n\n/**\n * Validates that all indexed fields exist in the declared fields.\n */\nfunction validateIndexes(indexes: ReadonlyArray<CollectionIndexDefinition>, fieldNames: Set<string>): void {\n for (const index of indexes) {\n for (const fieldName of index.on) {\n if (!fieldNames.has(fieldName)) {\n throw new Error(`Index references non-existent field \"${fieldName}\".`);\n }\n }\n }\n}\n\nexport interface DefineCollectionOptions {\n readonly name: string;\n readonly fields: Record<string, CollectionColumnBuilder>;\n readonly indexes?: ReadonlyArray<CollectionIndexDefinition>;\n}\n\nexport function defineCollection<TName extends string>(\n options: DefineCollectionOptions & { name: TName },\n): DefinedCollection<\n CollectionDefinition & {\n name: TName;\n }\n> {\n validateCollectionName(options.name);\n\n // Convert the column builders to field definitions\n const fields: Record<string, CollectionFieldDefinition> = {};\n for (const [fieldName, builder] of Object.entries(options.fields)) {\n const columnBuilder = builder as CollectionColumnBuilder;\n fields[fieldName] = {\n type: columnBuilder._type,\n nullable: columnBuilder._nullable,\n default: columnBuilder._default,\n };\n }\n\n validateFieldNames(fields);\n\n const fieldNames = new Set(Object.keys(fields));\n const indexes = options.indexes ?? [];\n validateIndexes(indexes, fieldNames);\n\n const definition: CollectionDefinition = {\n name: options.name,\n fields,\n indexes,\n };\n\n // Register immediately (mirror defineNode behavior)\n DefinedCollectionRegistry.register(definition);\n\n const result: DefinedCollection = {\n kind: \"defined-collection\",\n definition,\n register(context: { registerCollection(d: CollectionDefinition): void }) {\n context.registerCollection(definition);\n },\n };\n\n return result as DefinedCollection<\n CollectionDefinition & {\n name: TName;\n }\n >;\n}\n","/**\n * Shared internal helpers for defineNode and definePollingTrigger.\n * Not part of the public API — import only from authoring helpers.\n */\nimport type { AnyCredentialType, CredentialRequirement, CredentialTypeId } from \"../contracts/credentialTypes\";\nimport type { NodeExecutionContext } from \"../contracts/runtimeTypes\";\nimport type { RunnableNodeConfig } from \"../contracts/workflowTypes\";\nimport type { DefinedNodeCredentialAccessors, DefinedNodeCredentialBindings } from \"./defineNode.types\";\n\ntype ResolvableCredentialType = AnyCredentialType | CredentialTypeId;\n\nexport const definedNodeCredentialRequirementFactory = {\n create(bindings: DefinedNodeCredentialBindings | undefined): ReadonlyArray<CredentialRequirement> {\n if (!bindings) {\n return [];\n }\n return Object.entries(bindings).map(([slotKey, binding]) => {\n if (typeof binding === \"string\" || this.isCredentialType(binding)) {\n return {\n slotKey,\n label: this.humanize(slotKey),\n acceptedTypes: [this.resolveTypeId(binding)],\n };\n }\n\n const types = Array.isArray(binding.type) ? binding.type : [binding.type];\n return {\n slotKey,\n label: binding.label ?? this.humanize(slotKey),\n acceptedTypes: types.map((entry) => this.resolveTypeId(entry)),\n optional: binding.optional,\n helpText: binding.helpText,\n helpUrl: binding.helpUrl,\n };\n });\n },\n\n isCredentialType(value: unknown): value is AnyCredentialType {\n return (\n Boolean(value) &&\n typeof value === \"object\" &&\n \"definition\" in (value as Record<string, unknown>) &&\n typeof (value as AnyCredentialType).definition?.typeId === \"string\"\n );\n },\n\n resolveTypeId(type: ResolvableCredentialType): string {\n return typeof type === \"string\" ? type : type.definition.typeId;\n },\n\n humanize(key: string): string {\n return key\n .replace(/([a-z0-9])([A-Z])/g, \"$1 $2\")\n .replace(/[-_.]+/g, \" \")\n .replace(/\\s+/g, \" \")\n .trim()\n .replace(/^./, (character) => character.toUpperCase());\n },\n} as const;\n\nexport const definedNodeCredentialAccessorFactory = {\n create<TBindings extends DefinedNodeCredentialBindings | undefined>(\n bindings: TBindings,\n ctx:\n | NodeExecutionContext<RunnableNodeConfig<any, any>>\n | { getCredential<TSession = unknown>(slotKey: string): Promise<TSession> },\n ): DefinedNodeCredentialAccessors<TBindings> {\n if (!bindings) {\n return {} as DefinedNodeCredentialAccessors<TBindings>;\n }\n const entries = Object.keys(bindings).map((slotKey) => [slotKey, () => ctx.getCredential(slotKey)] as const);\n return Object.fromEntries(entries) as DefinedNodeCredentialAccessors<TBindings>;\n },\n} as const;\n","/**\n * definePollingTrigger — declarative helper for authoring polling triggers.\n *\n * Mirrors the ergonomics of `defineNode` / `defineRestNode` / `defineCredential`.\n * Plugin authors supply a `poll` function plus metadata; the helper synthesises the\n * two internal classes (`DefinedPollingTriggerRuntime` + `DefinedPollingTriggerConfig`)\n * that the engine's trigger machinery requires. Internal classes, DI annotations, and\n * `PollingTriggerRuntime` wiring are hidden from the plugin-author surface entirely.\n */\nimport type {\n Items,\n JsonValue,\n NodeExecutionContext,\n NodeOutputs,\n TestableTriggerNode,\n TriggerNodeConfig,\n TriggerSetupContext,\n TriggerTestItemsContext,\n TypeToken,\n} from \"..\";\nimport type { CredentialJsonRecord, CredentialRequirement } from \"../contracts/credentialTypes\";\nimport type { DefinedNodeCredentialAccessors, DefinedNodeCredentialBindings } from \"./defineNode.types\";\nimport { node as persistedNode } from \"../runtime-types/runtimeTypeDecorators.types\";\nimport {\n definedNodeCredentialRequirementFactory,\n definedNodeCredentialAccessorFactory,\n} from \"./definePollingTriggerInternals\";\nimport type { ZodType } from \"zod\";\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\ntype MaybePromise<TValue> = TValue | Promise<TValue>;\n\n/**\n * Context passed into the `poll` callback on each tick.\n */\nexport interface DefinePollingTriggerPollContext<\n TConfig extends CredentialJsonRecord,\n TState extends JsonValue | undefined,\n TBindings extends DefinedNodeCredentialBindings | undefined,\n> {\n readonly config: TConfig;\n readonly state: TState;\n readonly credentials: DefinedNodeCredentialAccessors<TBindings>;\n}\n\n/**\n * What `poll` must return each tick.\n */\nexport interface DefinePollingTriggerPollResult<TItemJson, TState extends JsonValue | undefined> {\n /**\n * New items to emit. Each item may carry an optional `dedupKey`; duplicate keys are\n * filtered out against a rolling dedup window (managed internally by the runtime).\n * Items without a `dedupKey` are always emitted.\n */\n readonly items: ReadonlyArray<{ json: TItemJson; dedupKey?: string }>;\n /** Persisted as the trigger's setup state for the next tick. */\n readonly nextState: TState;\n}\n\n/**\n * Context passed into the `execute` callback for post-emit enrichment (e.g. fetching\n * attachment bytes). Mirrors `NodeExecutionContext` so plugin authors use familiar patterns.\n */\nexport type DefinePollingTriggerExecuteContext<TConfig extends TriggerNodeConfig<any, any>> =\n NodeExecutionContext<TConfig>;\n\n/**\n * Context passed into the `testItems` callback.\n */\nexport type DefinePollingTriggerTestItemsContext<TConfig extends TriggerNodeConfig<any, any>> =\n TriggerTestItemsContext<TConfig>;\n\n/**\n * Options accepted by `definePollingTrigger`.\n */\nexport interface DefinePollingTriggerOptions<\n TKey extends string,\n TConfig extends CredentialJsonRecord,\n TItemJson,\n TState extends JsonValue | undefined,\n TBindings extends DefinedNodeCredentialBindings | undefined = undefined,\n> {\n /**\n * Unique node-token-id-style key, e.g. `\"msgraph-mail.on-new-mail\"`.\n * Used as the persisted runtime type name — must be stable across deployments.\n */\n readonly key: TKey;\n readonly title: string;\n readonly description?: string;\n /** Canvas icon (same contract as `NodeConfigBase.icon`). */\n readonly icon?: string;\n /**\n * Zod schema for the trigger's user-facing configuration.\n * When provided, the returned `create()` method is typed against the inferred config type.\n */\n readonly configSchema?: ZodType<TConfig>;\n /** Credential bindings keyed by slot (same format as `defineNode`). */\n readonly credentials?: TBindings;\n /**\n * Called once when the trigger arms (or re-arms after a server restart) to provide the\n * initial value for `state` when no persisted state exists.\n */\n initialState?(): TState;\n /**\n * Polling interval in milliseconds. The runtime enforces a minimum of 25 ms.\n * @default 60_000\n */\n readonly pollIntervalMs?: number;\n /**\n * The per-tick poll logic. Called by the runtime each interval.\n * Must return new items plus the next persisted state.\n */\n poll(\n pollCtx: DefinePollingTriggerPollContext<TConfig, TState, TBindings>,\n ): MaybePromise<DefinePollingTriggerPollResult<TItemJson, TState>>;\n /**\n * Optional post-emit enrichment step (runs in the normal node-execute phase after the\n * trigger fires and the workflow run starts). Use for expensive per-item work such as\n * fetching attachment bytes via `ctx.binary.attach`. When omitted, the trigger passes\n * items through unchanged.\n */\n execute?(\n items: Items<TItemJson>,\n ctx: NodeExecutionContext<DefinedPollingTriggerConfig<TConfig, TItemJson>>,\n ): MaybePromise<NodeOutputs>;\n /**\n * Optional implementation for the workflow UI's \"Test\" button. Should return a small\n * sample of current items without consulting or mutating polling state.\n */\n testItems?(\n ctx: TriggerTestItemsContext<DefinedPollingTriggerConfig<TConfig, TItemJson>>,\n ): MaybePromise<Items<TItemJson>>;\n}\n\n// ---------------------------------------------------------------------------\n// DefinedPollingTrigger (returned object)\n// ---------------------------------------------------------------------------\n\n/**\n * The object returned by `definePollingTrigger`. Register it via\n * `definePlugin({ nodes: [myTrigger] })` or call `.register(ctx)` directly.\n *\n * `poll` is also directly callable for unit-testing — no runtime needed.\n */\nexport interface DefinedPollingTrigger<\n TKey extends string,\n TConfig extends CredentialJsonRecord,\n TItemJson,\n TState extends JsonValue | undefined,\n TBindings extends DefinedNodeCredentialBindings | undefined = undefined,\n> {\n readonly kind: \"defined-polling-trigger\";\n readonly key: TKey;\n readonly title: string;\n readonly description?: string;\n /**\n * Create the trigger config for use in workflow definitions.\n * @param cfg - User-facing trigger configuration.\n * @param name - Display name (defaults to `title`).\n * @param id - Optional stable node id.\n */\n create(cfg: TConfig, name?: string, id?: string): DefinedPollingTriggerConfig<TConfig, TItemJson>;\n /**\n * Test seam: call `poll` directly without starting the runtime.\n * Returns `{ items, nextState }` just like the real runtime receives.\n */\n poll(\n pollCtx: Omit<DefinePollingTriggerPollContext<TConfig, TState, TBindings>, \"credentials\"> & {\n credentials?: DefinedNodeCredentialAccessors<TBindings>;\n },\n ): MaybePromise<DefinePollingTriggerPollResult<TItemJson, TState>>;\n /** Registers the synthesised runtime class with the plugin container. */\n register(context: { registerNode<TValue>(token: TypeToken<TValue>, implementation?: TypeToken<TValue>): void }): void;\n}\n\n// ---------------------------------------------------------------------------\n// DefinedPollingTriggerConfig (TriggerNodeConfig shape for the engine)\n// ---------------------------------------------------------------------------\n\n/**\n * TriggerNodeConfig produced by `DefinedPollingTrigger.create(...)`.\n * Holds user configuration and credential requirements for the engine.\n * The setup state type is opaque `JsonValue | undefined` — the runtime\n * uses an internal wrapped shape that plugin authors never see.\n */\nexport class DefinedPollingTriggerConfig<TConfig extends CredentialJsonRecord, TItemJson> implements TriggerNodeConfig<\n TItemJson,\n JsonValue | undefined\n> {\n readonly kind = \"trigger\" as const;\n readonly type: TypeToken<unknown>;\n readonly icon: string | undefined;\n\n constructor(\n public readonly name: string,\n public readonly cfg: TConfig,\n typeToken: TypeToken<unknown>,\n icon: string | undefined,\n private readonly credentialRequirements: ReadonlyArray<CredentialRequirement>,\n public readonly id?: string,\n ) {\n this.type = typeToken;\n this.icon = icon;\n }\n\n getCredentialRequirements(): ReadonlyArray<CredentialRequirement> {\n return this.credentialRequirements;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Internal wrapped state helpers\n// ---------------------------------------------------------------------------\n\n/** Opaque shape stored in the trigger setup state repository. @internal */\ninterface InternalWrappedState {\n readonly userState: JsonValue | undefined;\n readonly seenKeys: ReadonlyArray<string>;\n}\n\nfunction isWrappedState(value: unknown): value is InternalWrappedState {\n return (\n value !== null &&\n typeof value === \"object\" &&\n \"seenKeys\" in (value as Record<string, unknown>) &&\n Array.isArray((value as InternalWrappedState).seenKeys)\n );\n}\n\n// ---------------------------------------------------------------------------\n// Implementation factory\n// ---------------------------------------------------------------------------\n\n/**\n * Declarative helper for authoring polling triggers.\n *\n * ```ts\n * export const onNewMail = definePollingTrigger({\n * key: \"my-plugin.on-new-mail\",\n * title: \"On new mail\",\n * configSchema: z.object({ folder: z.string() }),\n * credentials: { auth: myOAuthCredentialType },\n * initialState: () => ({ lastSeenId: undefined }),\n * pollIntervalMs: 60_000,\n * async poll({ config, state, credentials }) {\n * const session = await credentials.auth();\n * const messages = await fetchMessages(session, config.folder, state.lastSeenId);\n * return {\n * items: messages.map(m => ({ json: m, dedupKey: m.id })),\n * nextState: { lastSeenId: messages[0]?.id ?? state.lastSeenId },\n * };\n * },\n * });\n * ```\n */\nexport function definePollingTrigger<\n TKey extends string,\n TConfig extends CredentialJsonRecord,\n TItemJson,\n TState extends JsonValue | undefined,\n TBindings extends DefinedNodeCredentialBindings | undefined = undefined,\n>(\n options: DefinePollingTriggerOptions<TKey, TConfig, TItemJson, TState, TBindings>,\n): DefinedPollingTrigger<TKey, TConfig, TItemJson, TState, TBindings> {\n const credentialRequirements = definedNodeCredentialRequirementFactory.create(options.credentials);\n const DEFAULT_INTERVAL_MS = 60_000;\n\n type TConfig_ = DefinedPollingTriggerConfig<TConfig, TItemJson>;\n\n // ---------------------------------------------------------------------------\n // Synthesised runtime class (implements TestableTriggerNode)\n // ---------------------------------------------------------------------------\n\n const DefinedPollingTriggerRuntime = class implements TestableTriggerNode<TConfig_> {\n readonly kind = \"trigger\" as const;\n readonly outputPorts = [\"main\"] as const;\n\n async setup(ctx: TriggerSetupContext<TConfig_, JsonValue | undefined>): Promise<JsonValue | undefined> {\n const cfg = ctx.config.cfg;\n const intervalMs =\n (cfg as Partial<{ pollIntervalMs: number }>).pollIntervalMs ?? options.pollIntervalMs ?? DEFAULT_INTERVAL_MS;\n\n // Unwrap previously persisted state, or create the initial wrapped state.\n const persisted = ctx.previousState;\n const existingWrapped: InternalWrappedState | undefined = isWrappedState(persisted) ? persisted : undefined;\n const seedWrapped: InternalWrappedState = existingWrapped ?? {\n userState: options.initialState ? options.initialState() : undefined,\n seenKeys: [],\n };\n\n const result = await ctx.polling.start<InternalWrappedState, TItemJson>({\n intervalMs,\n seedState: seedWrapped,\n runCycle: async ({ previousState }) => {\n const wrapped: InternalWrappedState = previousState ?? seedWrapped;\n const seenSet = new Set(wrapped.seenKeys);\n\n const credentialAccessors = definedNodeCredentialAccessorFactory.create(\n options.credentials,\n ctx,\n ) as DefinedNodeCredentialAccessors<TBindings>;\n\n const pollResult = await options.poll({\n config: cfg,\n state: wrapped.userState as TState,\n credentials: credentialAccessors,\n });\n\n // Dedup: filter items whose dedupKey is already seen\n const newItems: Array<{ json: TItemJson }> = [];\n const newKeys: string[] = [];\n for (const item of pollResult.items) {\n if (item.dedupKey !== undefined) {\n if (seenSet.has(item.dedupKey)) {\n continue;\n }\n newKeys.push(item.dedupKey);\n }\n newItems.push({ json: item.json });\n }\n\n // Merge keys, cap the window at 2000 to bound state size\n const allKeys = [...wrapped.seenKeys, ...newKeys];\n const cappedKeys = allKeys.length > 2000 ? allKeys.slice(allKeys.length - 2000) : allKeys;\n\n const nextWrapped: InternalWrappedState = {\n userState: pollResult.nextState,\n seenKeys: cappedKeys,\n };\n\n return {\n items: newItems as Items<TItemJson>,\n nextState: nextWrapped,\n };\n },\n });\n\n return result as JsonValue | undefined;\n }\n\n async execute(items: Items<TItemJson>, ctx: NodeExecutionContext<TConfig_>): Promise<NodeOutputs> {\n if (options.execute) {\n return await options.execute(items, ctx);\n }\n return { main: items };\n }\n\n async getTestItems(ctx: TriggerTestItemsContext<TConfig_>): Promise<Items> {\n if (options.testItems) {\n return await options.testItems(ctx);\n }\n return [];\n }\n };\n\n persistedNode({ name: options.key })(DefinedPollingTriggerRuntime);\n\n // ---------------------------------------------------------------------------\n // Returned definition object\n // ---------------------------------------------------------------------------\n\n const definition: DefinedPollingTrigger<TKey, TConfig, TItemJson, TState, TBindings> = {\n kind: \"defined-polling-trigger\",\n key: options.key,\n title: options.title,\n description: options.description,\n\n create(cfg: TConfig, name = options.title, id?: string): DefinedPollingTriggerConfig<TConfig, TItemJson> {\n return new DefinedPollingTriggerConfig<TConfig, TItemJson>(\n name,\n cfg,\n DefinedPollingTriggerRuntime,\n options.icon,\n credentialRequirements,\n id,\n );\n },\n\n poll(pollCtx) {\n return options.poll({\n config: pollCtx.config,\n state: pollCtx.state,\n credentials: (pollCtx.credentials ?? {}) as DefinedNodeCredentialAccessors<TBindings>,\n });\n },\n\n register(context) {\n context.registerNode(DefinedPollingTriggerRuntime);\n },\n };\n\n return definition;\n}\n","import type { Item, RunnableNodeConfig } from \"../types\";\nimport type { NodeBackedToolConfigOptions, ZodSchemaAny } from \"./AiHost\";\nimport { AgentConfigInspector } from \"./AgentConfigInspectorFactory\";\nimport { NodeBackedToolConfig } from \"./NodeBackedToolConfig\";\n\nclass AgentToolFactoryImpl {\n asTool<\n TNodeConfig extends RunnableNodeConfig<any, any>,\n TInputSchema extends ZodSchemaAny,\n TOutputSchema extends ZodSchemaAny,\n >(\n node: TNodeConfig,\n options: Readonly<{ name?: string } & NodeBackedToolConfigOptions<TNodeConfig, TInputSchema, TOutputSchema>>,\n ): NodeBackedToolConfig<TNodeConfig, TInputSchema, TOutputSchema> {\n return new NodeBackedToolConfig(\n options.name ?? node.name ?? \"tool\",\n node,\n this.withDefaultAgentInputMapper(node, options),\n );\n }\n\n private withDefaultAgentInputMapper<\n TNodeConfig extends RunnableNodeConfig<any, any>,\n TInputSchema extends ZodSchemaAny,\n TOutputSchema extends ZodSchemaAny,\n >(\n node: TNodeConfig,\n options: Readonly<{ name?: string } & NodeBackedToolConfigOptions<TNodeConfig, TInputSchema, TOutputSchema>>,\n ): Readonly<{ name?: string } & NodeBackedToolConfigOptions<TNodeConfig, TInputSchema, TOutputSchema>> {\n if (options.mapInput || !AgentConfigInspector.isAgentNodeConfig(node)) {\n return options;\n }\n return {\n ...options,\n mapInput: ({ input, item }) => this.mergeAgentToolInputWithCurrentItem(input, item) as never,\n };\n }\n\n private mergeAgentToolInputWithCurrentItem(input: unknown, item: Item): unknown {\n if (!this.isMergeableRecord(input) || !this.isMergeableRecord(item.json)) {\n return input;\n }\n return {\n ...item.json,\n ...input,\n };\n }\n\n private isMergeableRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n }\n}\n\nexport const AgentToolFactory = new AgentToolFactoryImpl();\n","import { isItemExpr } from \"../contracts/itemExpr\";\n\nimport type {\n AgentMessageBuildArgs,\n AgentMessageConfig,\n AgentMessageDto,\n AgentMessageLine,\n AgentMessageRole,\n AgentNodeConfig,\n} from \"./AiHost\";\n\nexport class AgentMessageConfigNormalizer {\n /**\n * Prefer {@code input.messages} when present (ItemNode / engine-mapped payloads); otherwise resolve from\n * {@link AgentNodeConfig.messages} templates.\n */\n static resolveFromInputOrConfig<TInputJson, TOutputJson>(\n input: unknown,\n config: AgentNodeConfig<TInputJson, TOutputJson>,\n args: AgentMessageBuildArgs<TInputJson>,\n ): ReadonlyArray<AgentMessageDto> {\n const fromInput = this.tryMessagesFromStructuredInput(input);\n if (fromInput.length > 0) {\n return fromInput;\n }\n return this.normalize(config, args);\n }\n\n static normalize<TInputJson, TOutputJson>(\n config: AgentNodeConfig<TInputJson, TOutputJson>,\n args: AgentMessageBuildArgs<TInputJson>,\n ): ReadonlyArray<AgentMessageDto> {\n const fromMessages = this.normalizeRichMessages(config.messages, args);\n if (fromMessages.length > 0) {\n return fromMessages;\n }\n throw new Error(\n \"AIAgent messages must be a non-empty array, or an object with a non-empty prompt array and/or buildMessages that returns messages.\",\n );\n }\n\n private static tryMessagesFromStructuredInput(input: unknown): ReadonlyArray<AgentMessageDto> {\n if (!input || typeof input !== \"object\") {\n return [];\n }\n const raw = (input as { messages?: unknown }).messages;\n if (!Array.isArray(raw) || raw.length === 0) {\n return [];\n }\n const out: AgentMessageDto[] = [];\n for (const m of raw) {\n if (!m || typeof m !== \"object\") {\n continue;\n }\n const role = (m as { role?: unknown }).role;\n const content = (m as { content?: unknown }).content;\n if (role !== \"system\" && role !== \"user\" && role !== \"assistant\") {\n continue;\n }\n if (typeof content !== \"string\") {\n continue;\n }\n out.push({ role: role as AgentMessageRole, content });\n }\n return out;\n }\n\n private static normalizeRichMessages<TInputJson>(\n config: AgentMessageConfig<TInputJson>,\n args: AgentMessageBuildArgs<TInputJson>,\n ): ReadonlyArray<AgentMessageDto> {\n if (isItemExpr(config)) {\n throw new Error(\n \"AIAgent messages wrapped in itemExpr(...) must be resolved by the engine before prompt normalization.\",\n );\n }\n if (Array.isArray(config)) {\n return config.map((line) => this.lineToDto(line, args));\n }\n const structured = config as {\n readonly prompt?: ReadonlyArray<AgentMessageLine<TInputJson>>;\n readonly buildMessages?: (a: AgentMessageBuildArgs<TInputJson>) => ReadonlyArray<AgentMessageDto>;\n };\n const messages: AgentMessageDto[] = [];\n for (const line of structured.prompt ?? []) {\n messages.push(this.lineToDto(line, args));\n }\n for (const message of structured.buildMessages?.(args) ?? []) {\n messages.push(message);\n }\n return messages;\n }\n\n private static lineToDto<TInputJson>(\n line: AgentMessageLine<TInputJson>,\n args: AgentMessageBuildArgs<TInputJson>,\n ): AgentMessageDto {\n const content = typeof line.content === \"function\" ? line.content(args) : line.content;\n return { role: line.role, content };\n }\n}\n","import type { TypeToken } from \"../di\";\n\nimport type { CredentialRequirement } from \"../contracts/credentialTypes\";\nimport type { Expr } from \"../contracts/params\";\n\nimport type {\n Item,\n Items,\n JsonValue,\n NodeExecutionContext,\n NodeOutputs,\n RunnableNodeConfig,\n RunnableNodeInputJson,\n} from \"../types\";\n\nimport type { input as ZodInput, output as ZodOutput, ZodType } from \"zod\";\n\nexport interface AgentCanvasPresentation<TIcon extends string = string> {\n readonly label?: string;\n readonly icon?: TIcon;\n}\n\nexport type ZodSchemaAny = ZodType<any, any, any>;\n\nexport interface ToolConfig {\n readonly type: TypeToken<unknown>;\n readonly name: string;\n readonly description?: string;\n readonly presentation?: AgentCanvasPresentation;\n getCredentialRequirements?(): ReadonlyArray<CredentialRequirement>;\n}\n\nexport type ToolExecuteArgs<TConfig extends ToolConfig = ToolConfig, TInput = unknown> = Readonly<{\n config: TConfig;\n input: TInput;\n ctx: NodeExecutionContext<any>;\n item: Item;\n itemIndex: number;\n items: Items;\n /**\n * Optional sub-agent boundary hooks: when present, the live `agent.tool.call` span and the\n * planned tool-call invocationId are forwarded so node-backed runtimes can re-root their child\n * execution scope. Plain function tools may safely ignore these hooks.\n */\n hooks?: Readonly<{\n parentSpan?: import(\"../contracts/telemetryTypes\").TelemetrySpanScope;\n parentInvocationId?: import(\"../contracts/runTypes\").ConnectionInvocationId;\n }>;\n}>;\n\nexport interface Tool<\n TConfig extends ToolConfig = ToolConfig,\n TInputSchema extends ZodSchemaAny = ZodSchemaAny,\n TOutputSchema extends ZodSchemaAny = ZodSchemaAny,\n> {\n readonly defaultDescription: string;\n readonly inputSchema: TInputSchema;\n readonly outputSchema: TOutputSchema;\n execute(\n args: ToolExecuteArgs<TConfig, ZodInput<TInputSchema>>,\n ): Promise<ZodOutput<TOutputSchema>> | ZodOutput<TOutputSchema>;\n}\n\nexport type AgentTool<\n TInputSchema extends ZodSchemaAny = ZodSchemaAny,\n TOutputSchema extends ZodSchemaAny = ZodSchemaAny,\n> = Tool<ToolConfig, TInputSchema, TOutputSchema>;\n\nexport type AgentToolExecuteArgs<TInput = unknown> = ToolExecuteArgs<ToolConfig, TInput>;\n\nexport type AgentToolToken = TypeToken<Tool<ToolConfig, ZodSchemaAny, ZodSchemaAny>>;\n\nexport type AgentMessageRole = \"system\" | \"user\" | \"assistant\";\n\nexport type AgentMessageBuildArgs<TInputJson = unknown> = Readonly<{\n item: Item<TInputJson>;\n itemIndex: number;\n items: Items<TInputJson>;\n ctx: NodeExecutionContext<any>;\n}>;\n\nexport interface AgentMessageDto {\n readonly role: AgentMessageRole;\n readonly content: string;\n}\n\nexport type AgentMessageTemplateContent<TInputJson = unknown> =\n | string\n | ((args: AgentMessageBuildArgs<TInputJson>) => string);\n\nexport interface AgentMessageTemplate<TInputJson = unknown> {\n readonly role: AgentMessageRole;\n readonly content: AgentMessageTemplateContent<TInputJson>;\n}\n\n/** A single prompt line: fixed DTO or template with optional function `content`. */\nexport type AgentMessageLine<TInputJson = unknown> = AgentMessageDto | AgentMessageTemplate<TInputJson>;\n\n/**\n * Message list for an agent. Prefer a **plain array** of `{ role, content }` (optionally with function `content` for templates).\n * Use the object form only when you need `buildMessages` to append messages after optional `prompt` lines.\n */\nexport type AgentMessageConfig<TInputJson = unknown> =\n | Expr<ReadonlyArray<AgentMessageLine<TInputJson>>, TInputJson>\n | ReadonlyArray<AgentMessageLine<TInputJson>>\n | {\n readonly prompt?: ReadonlyArray<AgentMessageLine<TInputJson>>;\n readonly buildMessages?: (args: AgentMessageBuildArgs<TInputJson>) => ReadonlyArray<AgentMessageDto>;\n };\n\nexport type AgentTurnLimitBehavior = \"error\" | \"respondWithLastMessage\";\n\nexport interface AgentModelInvocationOptions {\n readonly maxTokens?: number;\n readonly providerOptions?: Readonly<Record<string, JsonValue>>;\n}\n\nexport interface AgentGuardrailConfig {\n readonly maxTurns?: number;\n readonly onTurnLimitReached?: AgentTurnLimitBehavior;\n readonly modelInvocationOptions?: AgentModelInvocationOptions;\n}\n\n/** Defaults aligned with common tool-agent iteration limits (many products use ~10 max rounds). */\nexport const AgentGuardrailDefaults = {\n maxTurns: 10,\n onTurnLimitReached: \"error\" as AgentTurnLimitBehavior,\n} as const;\n\nexport interface AgentToolDefinition {\n readonly name: string;\n readonly description: string;\n readonly inputSchema: ZodSchemaAny;\n}\n\nexport type AgentToolCall = Readonly<{ id?: string; name: string; input: unknown }>;\n\nexport type AgentToolCallPlanner<_TNodeConfig = unknown> = (\n item: Item,\n index: number,\n items: Items,\n ctx: NodeExecutionContext<any>,\n) => ReadonlyArray<AgentToolCall>;\n\nexport interface ChatModelConfig {\n readonly type: TypeToken<ChatModelFactory<ChatModelConfig>>;\n readonly name: string;\n readonly provider?: string;\n readonly modelName?: string;\n readonly presentation?: AgentCanvasPresentation;\n getCredentialRequirements?(): ReadonlyArray<CredentialRequirement>;\n}\n\n/**\n * Provider-neutral chat language model wrapper returned by a {@link ChatModelFactory}.\n *\n * Thin adapter around an AI SDK `LanguageModelV2` (from `@ai-sdk/provider`) plus the call-site\n * defaults Codemation needs at every generate/stream: the provider label, the model name used for\n * pricing / telemetry, and the default invocation options (max output tokens, temperature,\n * provider-specific overrides).\n *\n * The consumer (AIAgentNode / AgentStructuredOutputRunner) passes `languageModel` directly into\n * `generateText({ model, ... })` from the `ai` package.\n */\nexport interface ChatLanguageModel {\n /** AI SDK `LanguageModelV2` instance (kept `unknown` to avoid leaking the SDK type into `@codemation/core`). */\n readonly languageModel: unknown;\n /** Stable pricing/telemetry key — e.g. `\"gpt-4.1-nano\"`. */\n readonly modelName: string;\n /** Provider label — e.g. `\"openai\"`. Used for cost tracking. */\n readonly provider?: string;\n /** Defaults merged into every call. Consumers may override per-invocation. */\n readonly defaultCallOptions?: ChatLanguageModelCallOptions;\n}\n\nexport interface ChatLanguageModelCallOptions {\n readonly maxOutputTokens?: number;\n readonly temperature?: number;\n readonly providerOptions?: Readonly<Record<string, Readonly<Record<string, JsonValue>>>>;\n}\n\n/**\n * Options for a structured-output generate call. Mirrors\n * `generateText({ output: Output.object(...) })` from the `ai` package.\n */\nexport interface StructuredOutputOptions {\n /** Optional schema name — used by some providers as the JSON schema name attribute. */\n readonly schemaName?: string;\n /** When `true`, the consumer should pass a strict-mode-compatible JSON Schema record. */\n readonly strict?: boolean;\n}\n\nexport interface ChatModelFactory<TConfig extends ChatModelConfig = ChatModelConfig> {\n create(\n args: Readonly<{ config: TConfig; ctx: NodeExecutionContext<any> }>,\n ): Promise<ChatLanguageModel> | ChatLanguageModel;\n}\n\nexport type NodeBackedToolInputMapperArgs<\n TNodeConfig extends RunnableNodeConfig<any, any>,\n TToolInput = unknown,\n> = Readonly<{\n input: TToolInput;\n item: Item;\n itemIndex: number;\n items: Items;\n ctx: NodeExecutionContext<any>;\n node: TNodeConfig;\n}>;\n\nexport type NodeBackedToolOutputMapperArgs<\n TNodeConfig extends RunnableNodeConfig<any, any>,\n TToolInput = unknown,\n> = Readonly<{\n input: TToolInput;\n item: Item;\n itemIndex: number;\n items: Items;\n ctx: NodeExecutionContext<any>;\n node: TNodeConfig;\n outputs: NodeOutputs;\n}>;\n\nexport type NodeBackedToolInputMapper<TNodeConfig extends RunnableNodeConfig<any, any>, TToolInput = unknown> = (\n args: NodeBackedToolInputMapperArgs<TNodeConfig, TToolInput>,\n) => Item<RunnableNodeInputJson<TNodeConfig>> | RunnableNodeInputJson<TNodeConfig>;\n\nexport type NodeBackedToolOutputMapper<\n TNodeConfig extends RunnableNodeConfig<any, any>,\n TToolInput = unknown,\n TToolOutput = unknown,\n> = (args: NodeBackedToolOutputMapperArgs<TNodeConfig, TToolInput>) => TToolOutput;\n\nexport type NodeBackedToolConfigOptions<\n TNodeConfig extends RunnableNodeConfig<any, any>,\n TInputSchema extends ZodSchemaAny,\n TOutputSchema extends ZodSchemaAny,\n> = Readonly<{\n description?: string;\n presentation?: AgentCanvasPresentation;\n inputSchema: TInputSchema;\n outputSchema: TOutputSchema;\n mapInput?: NodeBackedToolInputMapper<TNodeConfig, ZodInput<TInputSchema>>;\n mapOutput?: NodeBackedToolOutputMapper<TNodeConfig, ZodInput<TInputSchema>, ZodOutput<TOutputSchema>>;\n}>;\n\nexport interface AgentNodeConfig<TInputJson = unknown, TOutputJson = unknown> extends RunnableNodeConfig<\n TInputJson,\n TOutputJson\n> {\n readonly messages: AgentMessageConfig<TInputJson>;\n readonly chatModel: ChatModelConfig;\n readonly tools?: ReadonlyArray<ToolConfig>;\n readonly guardrails?: AgentGuardrailConfig;\n readonly outputSchema?: ZodType<TOutputJson>;\n}\n\nexport type AgentAttachmentRole = \"languageModel\" | \"tool\" | \"nestedAgent\";\n\nexport { NodeBackedToolConfig } from \"./NodeBackedToolConfig\";\nexport { CallableToolConfig } from \"./CallableToolConfig\";\nexport type { CallableToolConfigOptions, CallableToolExecuteHandler } from \"./CallableToolConfig\";\nexport { CallableToolFactory } from \"./CallableToolFactory\";\nexport { CallableToolKindToken } from \"./CallableToolKindToken\";\nexport { AgentToolFactory } from \"./AgentToolFactory\";\nexport { AgentMessageConfigNormalizer } from \"./AgentMessageConfigNormalizerFactory\";\nexport { AgentConfigInspector } from \"./AgentConfigInspectorFactory\";\n","import type {\n PersistedRunSchedulingState,\n PersistedRunState,\n RunId,\n RunPruneCandidate,\n RunSummary,\n WorkflowExecutionListingRepository,\n WorkflowExecutionPruneRepository,\n WorkflowExecutionRepository,\n WorkflowId,\n} from \"../types\";\nimport type { RunEventBus } from \"./runEvents\";\n\nexport class EventPublishingWorkflowExecutionRepository\n implements WorkflowExecutionRepository, WorkflowExecutionListingRepository, WorkflowExecutionPruneRepository\n{\n constructor(\n private readonly inner: WorkflowExecutionRepository,\n private readonly eventBus: RunEventBus,\n private readonly now: () => Date = () => new Date(),\n ) {}\n\n async createRun(args: Parameters<WorkflowExecutionRepository[\"createRun\"]>[0]): Promise<void> {\n await this.inner.createRun(args);\n await this.eventBus.publish({\n kind: \"runCreated\",\n runId: args.runId,\n workflowId: args.workflowId,\n parent: args.parent,\n at: this.now().toISOString(),\n });\n }\n\n async load(runId: RunId): Promise<PersistedRunState | undefined> {\n return await this.inner.load(runId);\n }\n\n async loadSchedulingState(runId: RunId): Promise<PersistedRunSchedulingState | undefined> {\n return await this.inner.loadSchedulingState(runId);\n }\n\n async save(state: PersistedRunState): Promise<void> {\n await this.inner.save(state);\n await this.eventBus.publish({\n kind: \"runSaved\",\n runId: state.runId,\n workflowId: state.workflowId,\n parent: state.parent,\n at: this.now().toISOString(),\n state,\n });\n }\n\n async deleteRun(runId: RunId): Promise<void> {\n if (!this.inner.deleteRun) return;\n await this.inner.deleteRun(runId);\n }\n\n async listRuns(args?: Readonly<{ workflowId?: WorkflowId; limit?: number }>): Promise<ReadonlyArray<RunSummary>> {\n const listingRepository = this.inner as unknown as Partial<WorkflowExecutionListingRepository>;\n if (!listingRepository.listRuns) return [];\n return await listingRepository.listRuns(args);\n }\n\n async listRunsOlderThan(\n args: Readonly<{ nowIso: string; defaultRetentionSeconds: number; limit?: number }>,\n ): Promise<ReadonlyArray<RunPruneCandidate>> {\n const pruneRepository = this.inner as unknown as Partial<WorkflowExecutionPruneRepository>;\n if (!pruneRepository.listRunsOlderThan) return [];\n return await pruneRepository.listRunsOlderThan(args);\n }\n}\n","import type { Item, Items } from \"../contracts/workflowTypes\";\nimport { injectable } from \"../di\";\n\n/**\n * Normalizes external inputs into the engine's canonical `Items` shape.\n * Used at host and builder boundaries where callers may provide either a raw value,\n * a single item-like object, or an array of item-like values.\n */\n@injectable()\nexport class ItemsInputNormalizer {\n normalize(raw: unknown): Items {\n if (raw === undefined || raw === null) {\n return [];\n }\n if (Array.isArray(raw)) {\n return raw.map((value) => this.normalizeItem(value));\n }\n return [this.normalizeItem(raw)];\n }\n\n private normalizeItem(raw: unknown): Item {\n if (!this.isItem(raw)) {\n return { json: raw };\n }\n return {\n json: raw.json,\n ...(raw.binary === undefined ? {} : { binary: raw.binary }),\n ...(raw.meta === undefined ? {} : { meta: raw.meta }),\n ...(raw.paired === undefined ? {} : { paired: raw.paired }),\n };\n }\n\n private isItem(raw: unknown): raw is Item {\n return typeof raw === \"object\" && raw !== null && Object.prototype.hasOwnProperty.call(raw, \"json\");\n }\n}\n","import type { JsonValue, NodeId } from \"./workflowTypes\";\n\n/**\n * One assertion emitted by an assertion-emitting node (a node whose config sets\n * `emitsAssertions: true`). Each emitted item on `main` carries one of these as `item.json`.\n *\n * Pass/fail is derived from `score >= (passThreshold ?? 0.5)` — see {@link deriveAssertionPassed}.\n * The `errored` marker is for cases where the assertion code itself threw (distinct from\n * \"the assertion was evaluated and the score was low\") and is treated as a hard fail in rollups\n * regardless of `score`.\n */\nexport interface AssertionResult {\n readonly name: string;\n /** 0..1 score. Source of truth for pass/fail (compared against `passThreshold`). */\n readonly score: number;\n /** 0..1 threshold for \"passed\". When omitted, consumers default to 0.5. */\n readonly passThreshold?: number;\n /** True when evaluating the assertion threw — treated as fail regardless of `score`. */\n readonly errored?: true;\n /** What the assertion expected. Free-form JSON; UIs render with a JSON viewer. */\n readonly expected?: JsonValue;\n /** What the workflow actually produced. */\n readonly actual?: JsonValue;\n /** Short human-readable explanation, especially for fails / errors. */\n readonly message?: string;\n /** Bag of supplemental fields (e.g. judge prompt, judge raw response, comparison method). */\n readonly details?: Readonly<Record<string, JsonValue>>;\n}\n\n/**\n * Default {@link AssertionResult.passThreshold} when authors omit it. Boolean-style assertions\n * (assertEqual / contains / etc.) emit `score: 1` or `score: 0` so this default works for them;\n * AI-judge assertions are expected to set their own threshold.\n */\nexport const DEFAULT_ASSERTION_PASS_THRESHOLD = 0.5;\n\n/**\n * Derive whether an assertion result is considered \"passing\" using the score-based contract:\n * `errored` always fails, otherwise `score >= (passThreshold ?? 0.5)`. This is the canonical\n * derivation — UI and rollup code should call it rather than inlining the comparison so future\n * tweaks (e.g. NaN handling) land in one place.\n */\nexport function deriveAssertionPassed(result: {\n readonly score: number;\n readonly passThreshold?: number;\n readonly errored?: true;\n}): boolean {\n if (result.errored === true) return false;\n const threshold = result.passThreshold ?? DEFAULT_ASSERTION_PASS_THRESHOLD;\n return result.score >= threshold;\n}\n\n/**\n * Provenance for a persisted {@link AssertionResult}: which node produced it and where in the\n * per-item iteration tree it landed. Filled in by the host-side persister, not the node itself.\n */\nexport interface AssertionResultProvenance {\n readonly nodeId: NodeId;\n /** Per-item iteration id when the emitting node ran inside a per-item loop. */\n readonly iterationId?: string;\n /** Item index (0-based) within the activation that produced this assertion. */\n readonly itemIndex?: number;\n}\n"],"mappings":";;;;;;;;AAKA,IAAa,cAAb,MAA0C;CACxC,MAAY;AACV,yBAAO,IAAI,MAAM;;;;;;ACLrB,IAAa,sBAAb,MAAiC;CAC/B,OAAwB,8BAAc,IAAI,KAGvC;CAEH,OAAO,SAAS,YAAkF;AAChG,OAAK,YAAY,IAAI,WAAW,KAAK,WAAW;;CAGlD,OAAO,QAAQ,KAAyF;AACtG,SAAO,KAAK,YAAY,IAAI,IAAI;;;;;;AC0IpC,MAAMA,4CAA0C;CAC9C,OAAO,UAA2F;AAChG,MAAI,CAAC,SACH,QAAO,EAAE;AAEX,SAAO,OAAO,QAAQ,SAAS,CAAC,KAAK,CAAC,SAAS,aAAa;AAC1D,OAAI,OAAO,YAAY,YAAY,KAAK,iBAAiB,QAAQ,CAC/D,QAAO;IACL;IACA,OAAO,KAAK,SAAS,QAAQ;IAC7B,eAAe,CAAC,KAAK,cAAc,QAAQ,CAAC;IAC7C;GAGH,MAAM,QAAQ,MAAM,QAAQ,QAAQ,KAAK,GAAG,QAAQ,OAAO,CAAC,QAAQ,KAAK;AACzE,UAAO;IACL;IACA,OAAO,QAAQ,SAAS,KAAK,SAAS,QAAQ;IAC9C,eAAe,MAAM,KAAK,UAAU,KAAK,cAAc,MAAM,CAAC;IAC9D,UAAU,QAAQ;IAClB,UAAU,QAAQ;IAClB,SAAS,QAAQ;IAClB;IACD;;CAGJ,iBAAiB,OAA4C;AAC3D,SACE,QAAQ,MAAM,IACd,OAAO,UAAU,YACjB,gBAAiB,SACjB,OAAQ,MAA4B,YAAY,WAAW;;CAI/D,cAAc,MAAwC;AACpD,SAAO,OAAO,SAAS,WAAW,OAAO,KAAK,WAAW;;CAG3D,SAAS,KAAqB;AAC5B,SAAO,IACJ,QAAQ,sBAAsB,QAAQ,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