@codemation/core 0.13.2 → 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +99 -0
- package/dist/{CostCatalogContract-Dxq1BTyi.d.cts → CostCatalogContract-B9aYIqJu.d.cts} +2 -2
- package/dist/{EngineRuntimeRegistration.types-CqcTWexS.d.cts → EngineRuntimeRegistration.types-BYAmGMdS.d.cts} +3 -3
- package/dist/{EngineRuntimeRegistration.types-Cr75cSfL.d.ts → EngineRuntimeRegistration.types-CVLI8DsJ.d.ts} +2 -2
- package/dist/{InMemoryRunDataFactory-Csy2evr_.d.cts → InMemoryRunDataFactory-C3rIszrW.d.cts} +4 -2
- package/dist/{ItemsInputNormalizer-BbQTSEkZ.cjs → ItemsInputNormalizer-B9SdLG24.cjs} +2 -2
- package/dist/{ItemsInputNormalizer-BbQTSEkZ.cjs.map → ItemsInputNormalizer-B9SdLG24.cjs.map} +1 -1
- package/dist/{ItemsInputNormalizer-CSZGMgl3.js → ItemsInputNormalizer-CZEODg94.js} +2 -2
- package/dist/{ItemsInputNormalizer-CSZGMgl3.js.map → ItemsInputNormalizer-CZEODg94.js.map} +1 -1
- package/dist/{ItemsInputNormalizer-BYljnXU0.d.ts → ItemsInputNormalizer-DoOawd9R.d.ts} +2 -2
- package/dist/{ItemsInputNormalizer-Bi8m-Ijs.d.cts → ItemsInputNormalizer-UCpn7luX.d.cts} +3 -3
- package/dist/{RunIntentService-BitgkKaT.d.cts → RunIntentService-0f3ICjAz.d.cts} +2 -2
- package/dist/{RunIntentService-DYpqfu6D.d.ts → RunIntentService-Dx_HHxDX.d.ts} +2 -2
- package/dist/{agentMcpTypes-DGIwk6Ue.d.cts → agentMcpTypes-B11B3Hd-.d.cts} +8 -1
- package/dist/bootstrap/index.cjs +3 -3
- package/dist/bootstrap/index.d.cts +5 -5
- package/dist/bootstrap/index.d.ts +5 -5
- package/dist/bootstrap/index.js +3 -3
- package/dist/{bootstrap-DIv-vloi.cjs → bootstrap-Be0LB0nh.cjs} +3 -3
- package/dist/{bootstrap-DIv-vloi.cjs.map → bootstrap-Be0LB0nh.cjs.map} +1 -1
- package/dist/{bootstrap-Bkd-Nfbn.js → bootstrap-pSQdsMfa.js} +3 -3
- package/dist/{bootstrap-Bkd-Nfbn.js.map → bootstrap-pSQdsMfa.js.map} +1 -1
- package/dist/browser.cjs +2 -2
- package/dist/browser.d.cts +3 -3
- package/dist/browser.d.ts +2 -2
- package/dist/browser.js +2 -2
- package/dist/contracts.d.cts +4 -4
- package/dist/contracts.d.ts +1 -1
- package/dist/{di-tom0pM2h.js → di-CEV6wTc4.js} +4 -5
- package/dist/di-CEV6wTc4.js.map +1 -0
- package/dist/{di-LP2qSHkY.cjs → di-DhwtDRgs.cjs} +4 -5
- package/dist/di-DhwtDRgs.cjs.map +1 -0
- package/dist/{executionPersistenceContracts-CN9d7AnL.d.cts → executionPersistenceContracts-CX9Ql8N1.d.cts} +2 -2
- package/dist/{index-rllWL4r-.d.ts → index-CbJdbIHe.d.ts} +93 -6
- package/dist/{index-BSQ2LoIh.d.ts → index-uPnD9EE6.d.ts} +51 -11
- package/dist/index.cjs +20 -7
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +135 -16
- package/dist/index.d.ts +5 -5
- package/dist/index.js +19 -8
- package/dist/index.js.map +1 -1
- package/dist/{params-DRUr0F5v.d.cts → params-Dwl10Ws9.d.cts} +3 -4
- package/dist/{runtime-CWPdvJpC.js → runtime-CSunvf7A.js} +112 -15
- package/dist/runtime-CSunvf7A.js.map +1 -0
- package/dist/{runtime-_VdHwGkJ.cjs → runtime-n2tqRwaf.cjs} +117 -14
- package/dist/runtime-n2tqRwaf.cjs.map +1 -0
- package/dist/testing.cjs +3 -3
- package/dist/testing.d.cts +3 -3
- package/dist/testing.d.ts +3 -3
- package/dist/testing.js +3 -3
- package/package.json +1 -1
- package/src/authoring/defineNode.types.ts +18 -7
- package/src/authoring/definePollingTrigger.types.ts +20 -5
- package/src/authoring/index.ts +1 -0
- package/src/authoring/nodeBaseOptions.types.ts +18 -0
- package/src/contracts/itemExpr.ts +15 -11
- package/src/contracts/workflowTypes.ts +7 -0
- package/src/contracts/workspaceFileTypes.ts +42 -2
- package/src/execution/NodeOutputNormalizer.ts +8 -1
- package/src/execution/RunnableOutputBehaviorResolver.ts +12 -0
- package/src/index.ts +10 -2
- package/src/workflow/dsl/ChainCursorResolver.ts +13 -0
- package/src/workflow/dsl/WhenBuilder.ts +66 -2
- package/src/workflow/dsl/workflowBuilderTypes.ts +29 -0
- package/src/workflowSnapshots/WorkflowSnapshotCodec.ts +1 -0
- package/dist/di-LP2qSHkY.cjs.map +0 -1
- package/dist/di-tom0pM2h.js.map +0 -1
- package/dist/runtime-CWPdvJpC.js.map +0 -1
- package/dist/runtime-_VdHwGkJ.cjs.map +0 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["input","current: z.ZodTypeAny","name: string","input","output","_type: CollectionFieldType","fields: Record<string, CollectionFieldDefinition>","definition: CollectionDefinition","name: string","cfg: TConfig","credentialRequirements: ReadonlyArray<CredentialRequirement>","id?: string","inspectorSummaryFn?: (\n args: Readonly<{ config: TConfig }>,\n ) => ReadonlyArray<NodeInspectorSummaryRow> | undefined","seedWrapped: InternalWrappedState","wrapped: InternalWrappedState","newItems: Array<{ json: TItemJson }>","newKeys: string[]","node","input","input","out: AgentMessageDto[]","messages: AgentMessageDto[]","inner: WorkflowExecutionRepository","eventBus: RunEventBus","now: () => Date","node","errors: WorkflowEdgePortError[]","source: CredentialMaterialRef[\"source\"]","providerName: string","status: number","providerErrorBody: string","key: string"],"sources":["../src/contracts/Clock.ts","../src/contracts/inboxChannelTypes.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/validation/WorkflowEdgePortValidator.ts","../src/credentials/CredentialMaterialProvider.types.ts","../src/credentials/ManagedCredentialMaterialWriteError.ts","../src/credentials/ManagedMaterialFetchError.ts","../src/contracts/workspaceFileTypes.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 { TypeToken } from \"../di\";\nimport type { HumanTaskActor, HumanTaskHandle, HumanTaskSubject } from \"./runtimeTypes\";\nimport type { Item } from \"./workflowTypes\";\n\n/**\n * A single inbox delivery channel.\n * Implementations: `LocalInboxChannel`, `ControlPlaneInboxChannel`.\n */\nexport interface InboxChannel {\n readonly kind: \"local\" | \"control-plane-inbox\";\n deliver(args: InboxDeliverArgs): Promise<InboxDelivery>;\n updateOnDecision?(args: InboxOnDecisionArgs): Promise<void>;\n updateOnTimeout?(args: InboxOnTimeoutArgs): Promise<void>;\n}\n\nexport type InboxDeliverArgs = Readonly<{\n task: HumanTaskHandle;\n subject: HumanTaskSubject;\n priority: \"low\" | \"normal\" | \"high\";\n item: Item;\n /** Present in managed mode (from `PairingConfig.workspaceId`). */\n workspaceId?: string;\n}>;\n\nexport type InboxDelivery =\n | { kind: \"local\"; inboxItemId: string }\n | { kind: \"cp\"; inboxItemId: string; workspaceId: string };\n\nexport type InboxOnDecisionArgs = Readonly<{\n delivery: InboxDelivery;\n decision: { approved: boolean; note?: string };\n actor: HumanTaskActor;\n}>;\n\nexport type InboxOnTimeoutArgs = Readonly<{\n delivery: InboxDelivery;\n policy: \"halt\" | \"auto-accept\";\n}>;\n\n/**\n * Resolves the correct `InboxChannel` for the current deployment mode\n * (local dev vs. managed/CP). Implemented in `@codemation/host`.\n */\nexport interface InboxChannelResolverSeam {\n resolve(): { channel: InboxChannel; workspaceId?: string };\n}\n\nexport const InboxChannelResolverToken = Symbol.for(\"codemation.core.InboxChannelResolver\") as TypeToken<\n InboxChannelResolverSeam | undefined\n>;\n\nexport const LocalInboxChannelToken = Symbol.for(\"codemation.core.LocalInboxChannel\") as TypeToken<\n InboxChannel | undefined\n>;\n\nexport const ControlPlaneInboxChannelToken = Symbol.for(\"codemation.core.ControlPlaneInboxChannel\") as TypeToken<\n InboxChannel | undefined\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 NodeInspectorSummaryRow,\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 * Static configuration summary surfaced in the workflow inspector — see\n * {@link import(\"../contracts/workflowTypes\").NodeConfigBase.inspectorSummary}.\n *\n * Receives the static config; returns 2–6 short label/value pairs (or `undefined` to skip).\n */\n readonly inspectorSummary?: (\n args: Readonly<{ config: TConfig }>,\n ) => ReadonlyArray<NodeInspectorSummaryRow> | undefined;\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 private readonly inspectorSummaryFn?: (\n args: Readonly<{ config: TConfig }>,\n ) => ReadonlyArray<NodeInspectorSummaryRow> | undefined,\n ) {\n this.type = typeToken;\n this.icon = icon;\n }\n\n getCredentialRequirements(): ReadonlyArray<CredentialRequirement> {\n return this.credentialRequirements;\n }\n\n inspectorSummary(): ReadonlyArray<NodeInspectorSummaryRow> | undefined {\n return this.inspectorSummaryFn?.({ config: this.cfg });\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 options.inspectorSummary as\n | ((args: Readonly<{ config: TConfig }>) => ReadonlyArray<NodeInspectorSummaryRow> | undefined)\n | undefined,\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 * Marks THIS tool binding as human-in-the-loop and sets the behavior when a human rejects the\n * approval: `\"return\"` feeds the rejection back to the agent as a tool result, `\"halt\"` stops the\n * run. Set per binding, so two tools backed by the same node can reject differently. When set, it\n * takes precedence over any `humanApprovalToolBehavior` marker carried by the backing node.\n */\n onRejected?: \"halt\" | \"return\";\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 { Edge, NodeDefinition } from \"../contracts/workflowTypes\";\nimport type { WorkflowEdgePortError, WorkflowEdgePortValidationResult } from \"./WorkflowEdgePortError.types\";\n\nexport class WorkflowEdgePortValidator {\n validate(workflow: {\n nodes: ReadonlyArray<NodeDefinition>;\n edges: ReadonlyArray<Edge>;\n }): WorkflowEdgePortValidationResult {\n const nodeById = new Map<string, NodeDefinition>();\n for (const node of workflow.nodes) {\n nodeById.set(node.id, node);\n }\n\n const errors: WorkflowEdgePortError[] = [];\n\n for (const edge of workflow.edges) {\n const sourceNode = nodeById.get(edge.from.nodeId);\n const allowedPorts = this.allowedOutputPorts(sourceNode);\n if (allowedPorts !== null && !allowedPorts.includes(edge.from.output)) {\n const nodeKind = sourceNode?.config.name ?? sourceNode?.name;\n const message = `Edge from node \"${edge.from.nodeId}\"${nodeKind ? ` (kind \"${nodeKind}\")` : \"\"} references undeclared output port \"${edge.from.output}\". Allowed ports: [${allowedPorts.map((p) => `\"${p}\"`).join(\", \")}].`;\n errors.push({\n edge,\n sourceNodeId: edge.from.nodeId,\n sourceNodeName: sourceNode?.name,\n sourceNodeKind: nodeKind,\n badPort: edge.from.output,\n allowedPorts,\n message,\n });\n }\n }\n\n return { valid: errors.length === 0, errors };\n }\n\n /**\n * Returns the declared output ports for a node, or null if the node is\n * unknown / has no declared ports (legacy nodes — treat as unconstrained).\n */\n private allowedOutputPorts(node: NodeDefinition | undefined): ReadonlyArray<string> | null {\n if (!node) {\n return null;\n }\n const declared = node.config.declaredOutputPorts;\n if (declared && declared.length > 0) {\n return declared as string[];\n }\n // No declared ports — treat as unconstrained (legacy nodes default to \"main\").\n return null;\n }\n}\n","import type { OAuthMaterial } from \"./OAuthFlowExecutor.types\";\n\n/**\n * Material provider seam — see `docs/design/credentials-oauth-unification.md`,\n * \"Material provider seam\" section. Sits beside the workspace's\n * `CredentialStore`; persistence of the row stays at the store, persistence of\n * the bytes goes through this provider so they can live at the control plane\n * in managed mode.\n */\n\n/**\n * Pointer to material bytes. For local rows `ref` is the workspace instance id\n * and the bytes co-locate with the row (existing `CredentialOAuth2Material` /\n * `CredentialSecretMaterial` tables). For control-plane rows `ref` is the\n * CP-side credential id; the workspace stores only the pointer.\n */\nexport type CredentialMaterialRef = Readonly<{\n source: \"local\" | \"control-plane\";\n id: string;\n}>;\n\n/**\n * Decrypted material bytes returned by a provider. Shape matches\n * `OAuthMaterial` — every supported credential type today is OAuth-shaped.\n */\nexport type MaterialBundle = OAuthMaterial;\n\n/**\n * Caller context recorded by the CP material endpoint per fetch (D5 in the\n * `credentials-vault` sprint README). The local provider accepts but ignores\n * it; standalone mode has no audit log.\n */\nexport type CallerContext = Readonly<{\n workspaceId: string;\n caller:\n | Readonly<{ kind: \"workflow-node\"; workflowId: string; nodeId: string }>\n | Readonly<{ kind: \"concierge\"; chatId: string }>\n | Readonly<{ kind: \"research-agent\"; chatId: string }>\n | Readonly<{ kind: \"manual\"; userId: string }>;\n reason?: string;\n}>;\n\nexport interface CredentialMaterialProvider {\n getMaterial(ref: CredentialMaterialRef, context: CallerContext): Promise<MaterialBundle>;\n setMaterial(ref: CredentialMaterialRef, material: MaterialBundle): Promise<void>;\n}\n\n/**\n * Thrown by a provider when asked to operate on a `ref.source` it does not\n * handle (e.g. the local provider being asked to read `control-plane` bytes).\n * Exported so `instanceof`-checks work across the workspace boundary.\n */\nexport class IllegalMaterialSourceError extends Error {\n constructor(\n public readonly source: CredentialMaterialRef[\"source\"],\n public readonly providerName: string,\n ) {\n super(`Provider \"${providerName}\" cannot handle material source \"${source}\".`);\n this.name = \"IllegalMaterialSourceError\";\n }\n}\n","/**\n * Thrown by managed-mode providers when `setMaterial` is called. Managed\n * credential bytes are owned by the control plane; the workspace must not\n * mutate them. See `docs/design/credentials-oauth-unification.md` and\n * `planning/sprints/credentials-vault/02-controlplane-material-provider.md`.\n */\nexport class ManagedCredentialMaterialWriteError extends Error {\n constructor(\n message: string = \"managed credentials are owned by the control plane; use the Connected apps page to create or modify them.\",\n ) {\n super(message);\n this.name = \"ManagedCredentialMaterialWriteError\";\n }\n}\n","/**\n * Thrown by `ControlPlaneCredentialMaterialProvider` when the control-plane\n * material endpoint returns a non-2xx response or a malformed body. Exposes\n * the HTTP status and the raw error body so call sites can surface actionable\n * detail without parsing strings.\n */\nexport class ManagedMaterialFetchError extends Error {\n constructor(\n public readonly status: number,\n public readonly providerErrorBody: string,\n message?: string,\n ) {\n super(message ?? `Control-plane material fetch failed: HTTP ${status} ${providerErrorBody}`);\n this.name = \"ManagedMaterialFetchError\";\n }\n}\n","import type { TypeToken } from \"../di\";\n\n/**\n * Metadata returned for a workspace file object.\n * Filename and contentType come from the S3 object's custom metadata\n * (stamped by the control plane at upload time — story 03).\n * The local-fs driver reads them from a companion .meta.json sidecar.\n */\nexport interface WorkspaceFileMetadata {\n /** Storage key: `<workspaceId>/files/<fileId>` */\n readonly key: string;\n /** Last path segment of the storage key. */\n readonly fileId: string;\n /** Original filename as stamped by the CP at upload time. Empty string if not yet stamped (pre-story-03). */\n readonly filename: string;\n readonly contentType: string;\n readonly size: number;\n readonly lastModified: Date;\n}\n\n/**\n * Read-only, workspace-scoped port for accessing the shared workspace file pool.\n * Implemented in `@codemation/host`; nodes reach it via `ctx.resolve(WorkspaceFileStorageToken)`.\n *\n * Key scheme: `<workspaceId>/files/<fileId>` — but nodes never construct raw keys.\n * Use the workspace-level helpers (`listFiles`, `getFileByName`, `getFileById`) instead.\n *\n * This adapter is SEPARATE from the run-scoped BinaryStorage — do not confuse the two.\n */\nexport interface IWorkspaceFileStorage {\n /**\n * Lists all files in this workspace, sorted newest-first by lastModified.\n * Optional case-insensitive substring filter on filename.\n */\n listFiles(filenameFilter?: string): Promise<ReadonlyArray<WorkspaceFileMetadata>>;\n\n /**\n * Returns metadata for the newest file with the given filename in this workspace.\n * @throws WorkspaceFileNotFoundError when no file with that name exists.\n */\n getFileByName(filename: string): Promise<WorkspaceFileMetadata>;\n\n /**\n * Returns metadata for the file with the given fileId in this workspace.\n * @throws WorkspaceFileNotFoundError when no file with that id exists.\n */\n getFileById(fileId: string): Promise<WorkspaceFileMetadata>;\n\n /**\n * Returns a non-buffered stream of the stored object's bytes.\n * Accepts a full storage key or a fileId (prefixes as needed).\n * @throws WorkspaceFileNotFoundError when the key does not exist.\n */\n getStream(key: string): Promise<ReadableStream<Uint8Array>>;\n}\n\n/**\n * Error thrown when a requested workspace file key does not exist.\n */\nexport class WorkspaceFileNotFoundError extends Error {\n constructor(readonly key: string) {\n super(`Workspace file not found: ${key}`);\n this.name = \"WorkspaceFileNotFoundError\";\n }\n}\n\n/**\n * DI token for the workspace-scoped file storage adapter.\n * Registered by `@codemation/host`; resolved by workspace-file nodes via `ctx.resolve(...)`.\n */\nexport const WorkspaceFileStorageToken = Symbol.for(\"codemation.core.WorkspaceFileStorage\") as TypeToken<\n IWorkspaceFileStorage | undefined\n>;\n"],"mappings":";;;;;;;;AAKA,IAAa,cAAb,MAA0C;CACxC,MAAY;AACV,yBAAO,IAAI,MAAM;;;;;;ACwCrB,MAAa,4BAA4B,OAAO,IAAI,uCAAuC;AAI3F,MAAa,yBAAyB,OAAO,IAAI,oCAAoC;AAIrF,MAAa,gCAAgC,OAAO,IAAI,2CAA2C;;;;ACPnG,IAAa,+BAAb,MAA0C;CACxC,OAAO,OACL,QACsC;AACtC,MAAI,kBAAkB,EAAE,UACtB,QAAO,KAAK,oBAAoB,OAAO;AAEzC,SAAO,KAAK,cAAc,OAAsC;;CAGlE,OAAe,cACb,QACsC;AACtC,SAAO,OAAO,QAAQ,OAAO,CAAC,KAAK,CAAC,KAAKA,UAAQ,UAAU;AAC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AAS,EAChC,QAAO;AAGT,SAAO;;;;;;;;;;;ACGX,IAAa,6BAAb,cAAgD,MAAM;CACpD,YACE,AAAgBE,QAChB,AAAgBC,cAChB;AACA,QAAM,aAAa,aAAa,mCAAmC,OAAO,IAAI;EAH9D;EACA;AAGhB,OAAK,OAAO;;;;;;;;;;;;ACpDhB,IAAa,sCAAb,cAAyD,MAAM;CAC7D,YACE,UAAkB,6GAClB;AACA,QAAM,QAAQ;AACd,OAAK,OAAO;;;;;;;;;;;;ACLhB,IAAa,4BAAb,cAA+C,MAAM;CACnD,YACE,AAAgBC,QAChB,AAAgBC,mBAChB,SACA;AACA,QAAM,WAAW,6CAA6C,OAAO,GAAG,oBAAoB;EAJ5E;EACA;AAIhB,OAAK,OAAO;;;;;;;;;AC8ChB,IAAa,6BAAb,cAAgD,MAAM;CACpD,YAAY,AAASC,KAAa;AAChC,QAAM,6BAA6B,MAAM;EADtB;AAEnB,OAAK,OAAO;;;;;;;AAQhB,MAAa,4BAA4B,OAAO,IAAI,uCAAuC"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["input","current: z.ZodTypeAny","name: string","input","output","_type: CollectionFieldType","fields: Record<string, CollectionFieldDefinition>","definition: CollectionDefinition","name: string","cfg: TConfig","credentialRequirements: ReadonlyArray<CredentialRequirement>","inspectorSummaryFn?: (\n args: Readonly<{ config: TConfig }>,\n ) => ReadonlyArray<NodeInspectorSummaryRow> | undefined","seedWrapped: InternalWrappedState","wrapped: InternalWrappedState","newItems: Array<{ json: TItemJson }>","newKeys: string[]","node","input","input","out: AgentMessageDto[]","messages: AgentMessageDto[]","inner: WorkflowExecutionRepository","eventBus: RunEventBus","now: () => Date","node","errors: WorkflowEdgePortError[]","source: CredentialMaterialRef[\"source\"]","providerName: string","status: number","providerErrorBody: string","key: string"],"sources":["../src/contracts/Clock.ts","../src/contracts/inboxChannelTypes.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/validation/WorkflowEdgePortValidator.ts","../src/credentials/CredentialMaterialProvider.types.ts","../src/credentials/ManagedCredentialMaterialWriteError.ts","../src/credentials/ManagedMaterialFetchError.ts","../src/contracts/workspaceFileTypes.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 { TypeToken } from \"../di\";\nimport type { HumanTaskActor, HumanTaskHandle, HumanTaskSubject } from \"./runtimeTypes\";\nimport type { Item } from \"./workflowTypes\";\n\n/**\n * A single inbox delivery channel.\n * Implementations: `LocalInboxChannel`, `ControlPlaneInboxChannel`.\n */\nexport interface InboxChannel {\n readonly kind: \"local\" | \"control-plane-inbox\";\n deliver(args: InboxDeliverArgs): Promise<InboxDelivery>;\n updateOnDecision?(args: InboxOnDecisionArgs): Promise<void>;\n updateOnTimeout?(args: InboxOnTimeoutArgs): Promise<void>;\n}\n\nexport type InboxDeliverArgs = Readonly<{\n task: HumanTaskHandle;\n subject: HumanTaskSubject;\n priority: \"low\" | \"normal\" | \"high\";\n item: Item;\n /** Present in managed mode (from `PairingConfig.workspaceId`). */\n workspaceId?: string;\n}>;\n\nexport type InboxDelivery =\n | { kind: \"local\"; inboxItemId: string }\n | { kind: \"cp\"; inboxItemId: string; workspaceId: string };\n\nexport type InboxOnDecisionArgs = Readonly<{\n delivery: InboxDelivery;\n decision: { approved: boolean; note?: string };\n actor: HumanTaskActor;\n}>;\n\nexport type InboxOnTimeoutArgs = Readonly<{\n delivery: InboxDelivery;\n policy: \"halt\" | \"auto-accept\";\n}>;\n\n/**\n * Resolves the correct `InboxChannel` for the current deployment mode\n * (local dev vs. managed/CP). Implemented in `@codemation/host`.\n */\nexport interface InboxChannelResolverSeam {\n resolve(): { channel: InboxChannel; workspaceId?: string };\n}\n\nexport const InboxChannelResolverToken = Symbol.for(\"codemation.core.InboxChannelResolver\") as TypeToken<\n InboxChannelResolverSeam | undefined\n>;\n\nexport const LocalInboxChannelToken = Symbol.for(\"codemation.core.LocalInboxChannel\") as TypeToken<\n InboxChannel | undefined\n>;\n\nexport const ControlPlaneInboxChannelToken = Symbol.for(\"codemation.core.ControlPlaneInboxChannel\") as TypeToken<\n InboxChannel | undefined\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 NodeInspectorSummaryRow,\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 type { NodeBaseOptions } from \"./nodeBaseOptions.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 * Static configuration summary surfaced in the workflow inspector — see\n * {@link import(\"../contracts/workflowTypes\").NodeConfigBase.inspectorSummary}.\n *\n * Receives the static config; returns 2–6 short label/value pairs (or `undefined` to skip).\n */\n readonly inspectorSummary?: (\n args: Readonly<{ config: TConfig }>,\n ) => ReadonlyArray<NodeInspectorSummaryRow> | undefined;\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 idOrOptions - Optional stable node id, or `{ id?, description? }` authoring options\n * (a bare string id still works — back-compat).\n */\n create(\n cfg: TConfig,\n name?: string,\n idOrOptions?: string | NodeBaseOptions,\n ): 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 readonly id?: string;\n readonly description?: string;\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 idOrOptions?: string | NodeBaseOptions,\n private readonly inspectorSummaryFn?: (\n args: Readonly<{ config: TConfig }>,\n ) => ReadonlyArray<NodeInspectorSummaryRow> | undefined,\n ) {\n this.type = typeToken;\n this.icon = icon;\n const resolved = typeof idOrOptions === \"string\" ? { id: idOrOptions } : idOrOptions;\n this.id = resolved?.id;\n this.description = resolved?.description;\n }\n\n getCredentialRequirements(): ReadonlyArray<CredentialRequirement> {\n return this.credentialRequirements;\n }\n\n inspectorSummary(): ReadonlyArray<NodeInspectorSummaryRow> | undefined {\n return this.inspectorSummaryFn?.({ config: this.cfg });\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(\n cfg: TConfig,\n name = options.title,\n idOrOptions?: string | NodeBaseOptions,\n ): DefinedPollingTriggerConfig<TConfig, TItemJson> {\n return new DefinedPollingTriggerConfig<TConfig, TItemJson>(\n name,\n cfg,\n DefinedPollingTriggerRuntime,\n options.icon,\n credentialRequirements,\n idOrOptions,\n options.inspectorSummary as\n | ((args: Readonly<{ config: TConfig }>) => ReadonlyArray<NodeInspectorSummaryRow> | undefined)\n | undefined,\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 * Marks THIS tool binding as human-in-the-loop and sets the behavior when a human rejects the\n * approval: `\"return\"` feeds the rejection back to the agent as a tool result, `\"halt\"` stops the\n * run. Set per binding, so two tools backed by the same node can reject differently. When set, it\n * takes precedence over any `humanApprovalToolBehavior` marker carried by the backing node.\n */\n onRejected?: \"halt\" | \"return\";\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 { Edge, NodeDefinition } from \"../contracts/workflowTypes\";\nimport type { WorkflowEdgePortError, WorkflowEdgePortValidationResult } from \"./WorkflowEdgePortError.types\";\n\nexport class WorkflowEdgePortValidator {\n validate(workflow: {\n nodes: ReadonlyArray<NodeDefinition>;\n edges: ReadonlyArray<Edge>;\n }): WorkflowEdgePortValidationResult {\n const nodeById = new Map<string, NodeDefinition>();\n for (const node of workflow.nodes) {\n nodeById.set(node.id, node);\n }\n\n const errors: WorkflowEdgePortError[] = [];\n\n for (const edge of workflow.edges) {\n const sourceNode = nodeById.get(edge.from.nodeId);\n const allowedPorts = this.allowedOutputPorts(sourceNode);\n if (allowedPorts !== null && !allowedPorts.includes(edge.from.output)) {\n const nodeKind = sourceNode?.config.name ?? sourceNode?.name;\n const message = `Edge from node \"${edge.from.nodeId}\"${nodeKind ? ` (kind \"${nodeKind}\")` : \"\"} references undeclared output port \"${edge.from.output}\". Allowed ports: [${allowedPorts.map((p) => `\"${p}\"`).join(\", \")}].`;\n errors.push({\n edge,\n sourceNodeId: edge.from.nodeId,\n sourceNodeName: sourceNode?.name,\n sourceNodeKind: nodeKind,\n badPort: edge.from.output,\n allowedPorts,\n message,\n });\n }\n }\n\n return { valid: errors.length === 0, errors };\n }\n\n /**\n * Returns the declared output ports for a node, or null if the node is\n * unknown / has no declared ports (legacy nodes — treat as unconstrained).\n */\n private allowedOutputPorts(node: NodeDefinition | undefined): ReadonlyArray<string> | null {\n if (!node) {\n return null;\n }\n const declared = node.config.declaredOutputPorts;\n if (declared && declared.length > 0) {\n return declared as string[];\n }\n // No declared ports — treat as unconstrained (legacy nodes default to \"main\").\n return null;\n }\n}\n","import type { OAuthMaterial } from \"./OAuthFlowExecutor.types\";\n\n/**\n * Material provider seam — see `docs/design/credentials-oauth-unification.md`,\n * \"Material provider seam\" section. Sits beside the workspace's\n * `CredentialStore`; persistence of the row stays at the store, persistence of\n * the bytes goes through this provider so they can live at the control plane\n * in managed mode.\n */\n\n/**\n * Pointer to material bytes. For local rows `ref` is the workspace instance id\n * and the bytes co-locate with the row (existing `CredentialOAuth2Material` /\n * `CredentialSecretMaterial` tables). For control-plane rows `ref` is the\n * CP-side credential id; the workspace stores only the pointer.\n */\nexport type CredentialMaterialRef = Readonly<{\n source: \"local\" | \"control-plane\";\n id: string;\n}>;\n\n/**\n * Decrypted material bytes returned by a provider. Shape matches\n * `OAuthMaterial` — every supported credential type today is OAuth-shaped.\n */\nexport type MaterialBundle = OAuthMaterial;\n\n/**\n * Caller context recorded by the CP material endpoint per fetch (D5 in the\n * `credentials-vault` sprint README). The local provider accepts but ignores\n * it; standalone mode has no audit log.\n */\nexport type CallerContext = Readonly<{\n workspaceId: string;\n caller:\n | Readonly<{ kind: \"workflow-node\"; workflowId: string; nodeId: string }>\n | Readonly<{ kind: \"concierge\"; chatId: string }>\n | Readonly<{ kind: \"research-agent\"; chatId: string }>\n | Readonly<{ kind: \"manual\"; userId: string }>;\n reason?: string;\n}>;\n\nexport interface CredentialMaterialProvider {\n getMaterial(ref: CredentialMaterialRef, context: CallerContext): Promise<MaterialBundle>;\n setMaterial(ref: CredentialMaterialRef, material: MaterialBundle): Promise<void>;\n}\n\n/**\n * Thrown by a provider when asked to operate on a `ref.source` it does not\n * handle (e.g. the local provider being asked to read `control-plane` bytes).\n * Exported so `instanceof`-checks work across the workspace boundary.\n */\nexport class IllegalMaterialSourceError extends Error {\n constructor(\n public readonly source: CredentialMaterialRef[\"source\"],\n public readonly providerName: string,\n ) {\n super(`Provider \"${providerName}\" cannot handle material source \"${source}\".`);\n this.name = \"IllegalMaterialSourceError\";\n }\n}\n","/**\n * Thrown by managed-mode providers when `setMaterial` is called. Managed\n * credential bytes are owned by the control plane; the workspace must not\n * mutate them. See `docs/design/credentials-oauth-unification.md` and\n * `planning/sprints/credentials-vault/02-controlplane-material-provider.md`.\n */\nexport class ManagedCredentialMaterialWriteError extends Error {\n constructor(\n message: string = \"managed credentials are owned by the control plane; use the Connected apps page to create or modify them.\",\n ) {\n super(message);\n this.name = \"ManagedCredentialMaterialWriteError\";\n }\n}\n","/**\n * Thrown by `ControlPlaneCredentialMaterialProvider` when the control-plane\n * material endpoint returns a non-2xx response or a malformed body. Exposes\n * the HTTP status and the raw error body so call sites can surface actionable\n * detail without parsing strings.\n */\nexport class ManagedMaterialFetchError extends Error {\n constructor(\n public readonly status: number,\n public readonly providerErrorBody: string,\n message?: string,\n ) {\n super(message ?? `Control-plane material fetch failed: HTTP ${status} ${providerErrorBody}`);\n this.name = \"ManagedMaterialFetchError\";\n }\n}\n","import type { TypeToken } from \"../di\";\n\n/**\n * Metadata returned for a workspace file object.\n * Filename and contentType come from the S3 object's custom metadata\n * (stamped by the control plane at upload time — story 03).\n * The local-fs driver reads them from a companion .meta.json sidecar.\n */\nexport interface WorkspaceFileMetadata {\n /** Storage key: `<workspaceId>/files/<fileId>` */\n readonly key: string;\n /** Last path segment of the storage key. */\n readonly fileId: string;\n /** Original filename as stamped by the CP at upload time. Empty string if not yet stamped (pre-story-03). */\n readonly filename: string;\n readonly contentType: string;\n readonly size: number;\n readonly lastModified: Date;\n}\n\n/**\n * Workspace-scoped port for accessing the shared workspace file pool.\n * Implemented in `@codemation/host`; nodes reach it via `ctx.resolve(WorkspaceFileStorageToken)`.\n *\n * Key scheme: `<workspaceId>/files/<fileId>` — but nodes never construct raw keys.\n * Use the workspace-level helpers (`listFiles`, `getFileByName`, `getFileById`, `writeFile`) instead.\n *\n * This adapter is SEPARATE from the run-scoped BinaryStorage — do not confuse the two.\n */\nexport interface IWorkspaceFileStorage {\n /**\n * Lists all files in this workspace, sorted newest-first by lastModified.\n * Optional case-insensitive substring filter on filename.\n */\n listFiles(filenameFilter?: string): Promise<ReadonlyArray<WorkspaceFileMetadata>>;\n\n /**\n * Returns metadata for the newest file with the given filename in this workspace.\n * @throws WorkspaceFileNotFoundError when no file with that name exists.\n */\n getFileByName(filename: string): Promise<WorkspaceFileMetadata>;\n\n /**\n * Returns metadata for the file with the given fileId in this workspace.\n * @throws WorkspaceFileNotFoundError when no file with that id exists.\n */\n getFileById(fileId: string): Promise<WorkspaceFileMetadata>;\n\n /**\n * Returns a non-buffered stream of the stored object's bytes.\n * Accepts a full storage key or a fileId (prefixes as needed).\n * @throws WorkspaceFileNotFoundError when the key does not exist.\n */\n getStream(key: string): Promise<ReadableStream<Uint8Array>>;\n\n /**\n * Writes a file into the workspace's shared file pool.\n *\n * Generates a new fileId internally; the caller never constructs a raw key.\n * Stamps the filename into object metadata so read-side adapters can resolve\n * files by name without querying a registry.\n *\n * Returns the stored file's metadata (fileId, key, filename, contentType, size,\n * lastModified). Callers that need concierge visibility must also register a\n * WorkspaceFile row on the CP side via the HMAC-paired\n * `POST /internal/workspace-files/register` endpoint — see the host-side\n * `WorkspaceFileRegistrarClient`.\n *\n * @param filename Original filename; stored in object metadata.\n * @param body Bytes to write (contiguous — required for presigned PUT Content-Length).\n * @param contentType MIME type.\n */\n writeFile(filename: string, body: Uint8Array, contentType: string): Promise<WorkspaceFileMetadata>;\n}\n\n/**\n * Error thrown when a requested workspace file key does not exist.\n */\nexport class WorkspaceFileNotFoundError extends Error {\n constructor(readonly key: string) {\n super(`Workspace file not found: ${key}`);\n this.name = \"WorkspaceFileNotFoundError\";\n }\n}\n\n/**\n * Port for registering a workflow-written file in the CP's WorkspaceFile table.\n * Optional: only wired when the host is paired with a control plane.\n * Implemented by `WorkspaceFileRegistrarClient` in `@codemation/host`.\n * Nodes call this after `writeFile` so the concierge can see the file via\n * `list_files` / `get_file`.\n */\nexport interface IWorkspaceFileRegistrar {\n register(meta: WorkspaceFileMetadata): Promise<void>;\n}\n\n/**\n * DI token for the workspace-scoped file storage adapter.\n * Registered by `@codemation/host`; resolved by workspace-file nodes via `ctx.resolve(...)`.\n */\nexport const WorkspaceFileStorageToken = Symbol.for(\"codemation.core.WorkspaceFileStorage\") as TypeToken<\n IWorkspaceFileStorage | undefined\n>;\n\n/**\n * DI token for the optional CP registry hook.\n * Present only when the host is paired (managed mode). Standalone / local-fs\n * deployments leave this undefined — workflow-written files will be in S3/local\n * but will not appear in the concierge's list_files.\n */\nexport const WorkspaceFileRegistrarToken = Symbol.for(\"codemation.core.WorkspaceFileRegistrar\") as TypeToken<\n IWorkspaceFileRegistrar | undefined\n>;\n"],"mappings":";;;;;;;;AAKA,IAAa,cAAb,MAA0C;CACxC,MAAY;AACV,yBAAO,IAAI,MAAM;;;;;;ACwCrB,MAAa,4BAA4B,OAAO,IAAI,uCAAuC;AAI3F,MAAa,yBAAyB,OAAO,IAAI,oCAAoC;AAIrF,MAAa,gCAAgC,OAAO,IAAI,2CAA2C;;;;ACPnG,IAAa,+BAAb,MAA0C;CACxC,OAAO,OACL,QACsC;AACtC,MAAI,kBAAkB,EAAE,UACtB,QAAO,KAAK,oBAAoB,OAAO;AAEzC,SAAO,KAAK,cAAc,OAAsC;;CAGlE,OAAe,cACb,QACsC;AACtC,SAAO,OAAO,QAAQ,OAAO,CAAC,KAAK,CAAC,KAAKA,UAAQ,UAAU;AACzD,OAAI,OAAOA,YAAU,SACnB,QAAO;IACL;IACA,O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,OACH,QAAO;EAET,MAAM,WAAWA,OAAK,OAAO;AAC7B,MAAI,YAAY,SAAS,SAAS,EAChC,QAAO;AAGT,SAAO;;;;;;;;;;;ACGX,IAAa,6BAAb,cAAgD,MAAM;CACpD,YACE,AAAgBE,QAChB,AAAgBC,cAChB;AACA,QAAM,aAAa,aAAa,mCAAmC,OAAO,IAAI;EAH9D;EACA;AAGhB,OAAK,OAAO;;;;;;;;;;;;ACpDhB,IAAa,sCAAb,cAAyD,MAAM;CAC7D,YACE,UAAkB,6GAClB;AACA,QAAM,QAAQ;AACd,OAAK,OAAO;;;;;;;;;;;;ACLhB,IAAa,4BAAb,cAA+C,MAAM;CACnD,YACE,AAAgBC,QAChB,AAAgBC,mBAChB,SACA;AACA,QAAM,WAAW,6CAA6C,OAAO,GAAG,oBAAoB;EAJ5E;EACA;AAIhB,OAAK,OAAO;;;;;;;;;ACiEhB,IAAa,6BAAb,cAAgD,MAAM;CACpD,YAAY,AAASC,KAAa;AAChC,QAAM,6BAA6B,MAAM;EADtB;AAEnB,OAAK,OAAO;;;;;;;AAmBhB,MAAa,4BAA4B,OAAO,IAAI,uCAAuC;;;;;;;AAU3F,MAAa,8BAA8B,OAAO,IAAI,yCAAyC"}
|
|
@@ -1,7 +1,6 @@
|
|
|
1
|
-
import { Ct as Item, Mt as NodeActivationId, Tt as Items, Xi as WorkflowId, Xt as RunDataSnapshot, Zt as RunId, qi as NodeId, rr as NodeExecutionContext } from "./agentMcpTypes-
|
|
1
|
+
import { Ct as Item, Mt as NodeActivationId, Tt as Items, Xi as WorkflowId, Xt as RunDataSnapshot, Zt as RunId, qi as NodeId, rr as NodeExecutionContext } from "./agentMcpTypes-B11B3Hd-.cjs";
|
|
2
2
|
|
|
3
3
|
//#region src/contracts/itemExpr.d.ts
|
|
4
|
-
declare const ITEM_EXPR_BRAND: unique symbol;
|
|
5
4
|
type ItemExprResolvedContext = Readonly<{
|
|
6
5
|
runId: RunId;
|
|
7
6
|
workflowId: WorkflowId;
|
|
@@ -21,7 +20,7 @@ type ItemExprArgs<TItemJson = unknown> = Readonly<{
|
|
|
21
20
|
}>;
|
|
22
21
|
type ItemExprCallback<T, TItemJson = unknown> = (args: ItemExprArgs<TItemJson>) => T | Promise<T>;
|
|
23
22
|
type ItemExpr<T, TItemJson = unknown> = Readonly<{
|
|
24
|
-
readonly
|
|
23
|
+
readonly __codemationItemExpr: "codemation.itemExpr";
|
|
25
24
|
readonly fn: ItemExprCallback<T, TItemJson>;
|
|
26
25
|
}>;
|
|
27
26
|
declare function itemExpr<T, TItemJson = unknown>(fn: ItemExprCallback<T, TItemJson>): ItemExpr<T, TItemJson>;
|
|
@@ -41,4 +40,4 @@ type Param<T, TItemJson = unknown> = T | Expr<T, TItemJson>;
|
|
|
41
40
|
type ParamDeep<T, TItemJson = unknown> = Expr<T, TItemJson> | (T extends readonly (infer U)[] ? ReadonlyArray<ParamDeep<U, TItemJson>> : never) | (T extends object ? { [K in keyof T]: ParamDeep<T[K], TItemJson> } : T);
|
|
42
41
|
//#endregion
|
|
43
42
|
export { ItemExprArgs as a, ItemExprResolvedContext as c, resolveItemExprsForExecution as d, resolveItemExprsInUnknown as f, ItemExpr as i, isItemExpr as l, Param as n, ItemExprCallback as o, ParamDeep as r, ItemExprContext as s, Expr as t, itemExpr as u };
|
|
44
|
-
//# sourceMappingURL=params-
|
|
43
|
+
//# sourceMappingURL=params-Dwl10Ws9.d.cts.map
|