@kortyx/hooks 0.4.0 → 0.5.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 +22 -0
- package/README.md +21 -4
- package/dist/index.d.ts +92 -5
- package/dist/index.js +767 -13
- package/dist/index.js.map +1 -0
- package/dist/internal.d.ts +24 -3
- package/dist/internal.js +125 -5
- package/dist/internal.js.map +1 -0
- package/package.json +11 -7
- package/dist/context.d.ts +0 -26
- package/dist/context.d.ts.map +0 -1
- package/dist/context.js +0 -82
- package/dist/hooks.d.ts +0 -29
- package/dist/hooks.d.ts.map +0 -1
- package/dist/hooks.js +0 -108
- package/dist/index.d.ts.map +0 -1
- package/dist/internal.d.ts.map +0 -1
- package/dist/reason-engine.d.ts +0 -19
- package/dist/reason-engine.d.ts.map +0 -1
- package/dist/reason-engine.js +0 -81
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/context.ts","../src/validation.ts","../src/interrupt.ts","../src/structured.ts","../src/reason/checkpoint.ts","../src/reason/engine.ts","../src/reason-engine.ts","../src/reason/parsing.ts","../src/reason/prompting.ts","../src/reason/use-reason.ts","../src/hooks.ts"],"sourcesContent":["// release-test: 2026-01-22\n/**\n * @kortyx/hooks\n *\n * Internal hook implementations resolved via async-local context.\n */\n\nexport type { HookRuntimeContext } from \"./context\";\nexport { runWithHookContext } from \"./context\";\nexport type {\n UseInterruptArgs,\n UseReasonArgs,\n UseReasonResult,\n UseStructuredDataArgs,\n} from \"./hooks\";\nexport {\n useAiMemory,\n useEmit,\n useInterrupt,\n useNodeState,\n useReason,\n useStructuredData,\n useWorkflowState,\n} from \"./hooks\";\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { GraphState, NodeContext } from \"@kortyx/core\";\nimport type { MemoryAdapter } from \"@kortyx/memory\";\nimport type { GetProviderFn } from \"@kortyx/providers\";\n\ntype NodeStateStore = {\n byIndex: unknown[];\n byKey: Record<string, unknown>;\n};\n\ntype HookMemory = {\n nodeState?: Record<string, unknown>;\n workflowState?: Record<string, unknown>;\n};\n\nexport type HookRuntimeContext = {\n node: NodeContext;\n state: GraphState;\n getProvider?: GetProviderFn;\n memoryAdapter?: MemoryAdapter;\n};\n\ntype HookInternalContext = HookRuntimeContext & {\n nodeStateIndex: number;\n reasonCallIndex: number;\n currentNodeState: NodeStateStore;\n workflowState: Record<string, unknown>;\n dirty: boolean;\n};\n\nconst storage = new AsyncLocalStorage<HookInternalContext>();\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n\nconst normalizeNodeState = (value: unknown): NodeStateStore => {\n if (Array.isArray(value)) {\n return { byIndex: [...value], byKey: {} };\n }\n\n if (isRecord(value)) {\n const byIndex = Array.isArray(value.byIndex) ? [...value.byIndex] : [];\n const byKey = isRecord(value.byKey) ? { ...value.byKey } : {};\n return { byIndex, byKey };\n }\n\n return { byIndex: [], byKey: {} };\n};\n\nconst cloneWorkflowState = (value: unknown): Record<string, unknown> =>\n isRecord(value) ? { ...value } : {};\n\nconst getHookMemory = (state: GraphState): HookMemory => {\n const memory = (state.memory ?? {}) as Record<string, unknown>;\n const internal = isRecord(memory.__kortyx) ? memory.__kortyx : undefined;\n const result: HookMemory = {};\n if (isRecord(internal?.nodeState)) result.nodeState = internal?.nodeState;\n if (isRecord(internal?.workflowState)) {\n result.workflowState = internal?.workflowState;\n }\n return result;\n};\n\nconst createInternalContext = (\n ctx: HookRuntimeContext,\n): HookInternalContext => {\n const hookMemory = getHookMemory(ctx.state);\n const nodeId = ctx.node.graph.node;\n const storedNodeId =\n typeof (hookMemory.nodeState as any)?.nodeId === \"string\"\n ? String((hookMemory.nodeState as any)?.nodeId)\n : \"\";\n const storedState = (hookMemory.nodeState as any)?.state;\n const currentNodeState =\n storedNodeId && storedNodeId === nodeId\n ? normalizeNodeState(storedState)\n : { byIndex: [], byKey: {} };\n\n return {\n ...ctx,\n nodeStateIndex: 0,\n reasonCallIndex: 0,\n currentNodeState,\n workflowState: cloneWorkflowState(hookMemory.workflowState),\n dirty: false,\n };\n};\n\nconst buildMemoryUpdates = (ctx: HookInternalContext) => {\n if (!ctx.dirty) return null;\n return {\n __kortyx: {\n nodeState: {\n nodeId: ctx.node.graph.node,\n state: ctx.currentNodeState,\n },\n workflowState: ctx.workflowState,\n },\n } as Record<string, unknown>;\n};\n\nexport async function runWithHookContext<T>(\n ctx: HookRuntimeContext,\n fn: () => Promise<T>,\n): Promise<{ result: T; memoryUpdates: Record<string, unknown> | null }> {\n const internal = createInternalContext(ctx);\n try {\n const result = await storage.run(internal, fn);\n return { result, memoryUpdates: buildMemoryUpdates(internal) };\n } catch (err) {\n const memoryUpdates = buildMemoryUpdates(internal);\n if (memoryUpdates) {\n const currentMemory = isRecord(internal.state.memory)\n ? (internal.state.memory as Record<string, unknown>)\n : {};\n internal.state.memory = {\n ...currentMemory,\n ...memoryUpdates,\n } as unknown as GraphState[\"memory\"];\n if (err && typeof err === \"object\") {\n (err as any).__kortyxMemoryUpdates = memoryUpdates;\n }\n }\n throw err;\n }\n}\n\nexport function getHookContext(): HookInternalContext {\n const ctx = storage.getStore();\n if (!ctx) {\n throw new Error(\"Hooks can only be used while a node is executing.\");\n }\n return ctx;\n}\n","import type { SchemaLike } from \"./types\";\n\nexport const parseWithSchema = <T>(\n schema: SchemaLike<T> | undefined,\n value: unknown,\n label: string,\n): T => {\n if (!schema) return value as T;\n\n const parsed = schema.safeParse(value);\n if (parsed.success) return parsed.data;\n\n const parsedError =\n \"error\" in parsed && parsed.error ? parsed.error : undefined;\n const reason =\n typeof parsedError?.message === \"string\" && parsedError.message.length > 0\n ? parsedError.message\n : \"invalid payload\";\n throw new Error(`${label} validation failed: ${reason}`);\n};\n","import type { InterruptInput, InterruptResult } from \"@kortyx/core\";\nimport { getHookContext } from \"./context\";\nimport type { UseInterruptArgs } from \"./types\";\nimport { parseWithSchema } from \"./validation\";\n\nexport const awaitInterruptInternal = <\n TRequest extends InterruptInput = InterruptInput,\n TResponse = InterruptResult,\n>(\n args: UseInterruptArgs<TRequest, TResponse>,\n): Promise<TResponse> => {\n const ctx = getHookContext();\n\n const request = parseWithSchema(\n args.requestSchema,\n args.request,\n \"useInterrupt request\",\n );\n\n const enrichedRequest = {\n ...request,\n ...(typeof args.schemaId === \"string\" && args.schemaId.length > 0\n ? { schemaId: args.schemaId }\n : {}),\n ...(typeof args.schemaVersion === \"string\" && args.schemaVersion.length > 0\n ? { schemaVersion: args.schemaVersion }\n : {}),\n ...(typeof args.id === \"string\" && args.id.length > 0\n ? { id: args.id }\n : {}),\n ...(args.meta && typeof args.meta === \"object\" && !Array.isArray(args.meta)\n ? { meta: args.meta }\n : {}),\n } as InterruptInput;\n\n const raw = ctx.node.awaitInterrupt(enrichedRequest);\n const response = parseWithSchema(\n args.responseSchema,\n raw,\n \"useInterrupt response\",\n );\n\n return Promise.resolve(response);\n};\n","import { getHookContext } from \"./context\";\nimport type {\n StructuredDataMode,\n UseReasonStructuredConfig,\n UseStructuredDataArgs,\n} from \"./types\";\nimport { parseWithSchema } from \"./validation\";\n\nexport const emitStructuredData = <TData = unknown>(\n args: UseStructuredDataArgs<TData>,\n): void => {\n const ctx = getHookContext();\n const validated = parseWithSchema(\n args.dataSchema,\n args.data,\n \"useStructuredData data\",\n );\n\n ctx.node.emit(\"structured_data\", {\n node: ctx.node.graph.node,\n ...(typeof args.dataType === \"string\" && args.dataType.length > 0\n ? { dataType: args.dataType }\n : {}),\n ...(typeof args.mode === \"string\" ? { mode: args.mode } : {}),\n ...(typeof args.schemaId === \"string\" && args.schemaId.length > 0\n ? { schemaId: args.schemaId }\n : {}),\n ...(typeof args.schemaVersion === \"string\" && args.schemaVersion.length > 0\n ? { schemaVersion: args.schemaVersion }\n : {}),\n ...(typeof args.id === \"string\" && args.id.length > 0\n ? { id: args.id }\n : {}),\n ...(typeof args.opId === \"string\" && args.opId.length > 0\n ? { opId: args.opId }\n : {}),\n data: validated,\n });\n};\n\nexport const shouldEmitStructured = (\n cfg: UseReasonStructuredConfig | undefined,\n): boolean => (cfg?.stream ?? \"patch\") !== \"off\";\n\nexport const resolveStructuredMode = (\n cfg: UseReasonStructuredConfig | undefined,\n): StructuredDataMode => {\n const mode = cfg?.stream ?? \"patch\";\n if (mode === \"snapshot\") return \"snapshot\";\n if (mode === \"patch\") return \"patch\";\n return \"final\";\n};\n","import type { InterruptInput } from \"@kortyx/core\";\n\nexport type ReasonInterruptCheckpoint = {\n status: \"awaiting_interrupt\";\n request: InterruptInput;\n firstText: string;\n firstRaw?: unknown;\n firstOutput?: unknown;\n};\n\nexport const resolveReasonCheckpointKey = (args: {\n id?: string;\n autoIndex: number;\n}): string =>\n typeof args.id === \"string\" && args.id.length > 0\n ? `__useReason:${args.id}`\n : `__useReason:auto:${args.autoIndex}`;\n\nexport const readReasonCheckpoint = (\n raw: unknown,\n): ReasonInterruptCheckpoint | undefined => {\n if (!raw || typeof raw !== \"object\") return undefined;\n const value = raw as Record<string, unknown>;\n if (value.status !== \"awaiting_interrupt\") return undefined;\n if (typeof value.firstText !== \"string\") return undefined;\n if (!value.request || typeof value.request !== \"object\") return undefined;\n return {\n status: \"awaiting_interrupt\",\n request: value.request as InterruptInput,\n firstText: value.firstText,\n ...(Object.hasOwn(value, \"firstRaw\") ? { firstRaw: value.firstRaw } : {}),\n ...(Object.hasOwn(value, \"firstOutput\")\n ? { firstOutput: value.firstOutput }\n : {}),\n };\n};\n\nexport const resolveHookMemoryPatch = (args: {\n nodeId: string;\n currentNodeState: unknown;\n workflowState: Record<string, unknown>;\n}): Record<string, unknown> => ({\n __kortyx: {\n nodeState: {\n nodeId: args.nodeId,\n state: args.currentNodeState,\n },\n workflowState: args.workflowState,\n },\n});\n","import { randomUUID } from \"node:crypto\";\nimport type { ProviderModelRef } from \"@kortyx/providers\";\nimport { getHookContext } from \"../context\";\nimport type { RunReasonEngineResult } from \"../reason-engine\";\nimport { runReasonEngine } from \"../reason-engine\";\n\nexport type ReasonEngineInput = {\n model: ProviderModelRef;\n input: string;\n system?: string | undefined;\n temperature?: number | undefined;\n emit?: boolean | undefined;\n stream?: boolean | undefined;\n};\n\nexport const createRuntimeId = (): string => {\n try {\n return randomUUID();\n } catch {\n return `${Date.now()}-${Math.random().toString(36).slice(2)}`;\n }\n};\n\nexport async function reasonEngine(\n args: ReasonEngineInput,\n meta: { id?: string; opId: string },\n inputOverride?: string,\n): Promise<RunReasonEngineResult> {\n const ctx = getHookContext();\n const getProvider = ctx.getProvider;\n if (!getProvider) {\n throw new Error(\"useReason requires a provider factory in runtime config.\");\n }\n\n return runReasonEngine({\n getProvider,\n model: args.model,\n input: inputOverride ?? args.input,\n system: args.system,\n temperature: args.temperature,\n defaultTemperature: ctx.node.config?.model?.temperature,\n stream: args.stream,\n emit: args.emit,\n nodeId: ctx.node.graph.node,\n emitEvent: ctx.node.emit,\n id: meta.id,\n opId: meta.opId,\n });\n}\n","import { randomUUID } from \"node:crypto\";\nimport type {\n GetProviderFn,\n KortyxPromptMessage,\n KortyxStreamChunk,\n ProviderModelRef,\n} from \"@kortyx/providers\";\n\nexport interface RunReasonEngineArgs {\n getProvider: GetProviderFn;\n model: ProviderModelRef;\n input: string;\n system?: string | undefined;\n temperature?: number | undefined;\n defaultTemperature?: number | undefined;\n stream?: boolean | undefined;\n emit?: boolean | undefined;\n nodeId?: string | undefined;\n emitEvent?: ((event: string, payload: unknown) => void) | undefined;\n id?: string | undefined;\n opId?: string | undefined;\n segmentId?: string | undefined;\n}\n\nexport interface RunReasonEngineResult {\n text: string;\n raw?: unknown;\n}\n\nconst chunkToText = (chunk: KortyxStreamChunk | string): string => {\n if (typeof chunk === \"string\") return chunk;\n if (typeof chunk.text === \"string\") return chunk.text;\n if (typeof chunk.content === \"string\") return chunk.content;\n return \"\";\n};\n\nconst createRuntimeId = (): string => {\n try {\n return randomUUID();\n } catch {\n return `${Date.now()}-${Math.random().toString(36).slice(2)}`;\n }\n};\n\nconst emitNodeEvent = (\n emitEvent: RunReasonEngineArgs[\"emitEvent\"],\n nodeId: string | undefined,\n event: string,\n payload: Record<string, unknown>,\n): void => {\n if (!emitEvent) return;\n emitEvent(event, {\n ...payload,\n ...(typeof nodeId === \"string\" && nodeId.length > 0\n ? { node: nodeId }\n : {}),\n });\n};\n\nexport async function runReasonEngine(\n args: RunReasonEngineArgs,\n): Promise<RunReasonEngineResult> {\n const stream = args.stream ?? args.model.options?.streaming ?? true;\n const emit = args.emit ?? true;\n const temperature =\n args.temperature ??\n args.model.options?.temperature ??\n args.defaultTemperature;\n\n const model = args.getProvider(args.model.providerId, args.model.modelId, {\n ...(temperature !== undefined ? { temperature } : {}),\n streaming: stream,\n });\n\n const messages: KortyxPromptMessage[] = [];\n if (typeof args.system === \"string\" && args.system.length > 0) {\n messages.push({ role: \"system\", content: args.system });\n }\n messages.push({ role: \"user\", content: String(args.input ?? \"\") });\n\n const opId =\n typeof args.opId === \"string\" && args.opId.length > 0\n ? args.opId\n : createRuntimeId();\n const segmentId =\n typeof args.segmentId === \"string\" && args.segmentId.length > 0\n ? args.segmentId\n : createRuntimeId();\n\n const commonMeta: Record<string, unknown> = {\n ...(typeof args.id === \"string\" && args.id.length > 0\n ? { id: args.id }\n : {}),\n opId,\n segmentId,\n };\n\n if (stream) {\n let final = \"\";\n let raw: unknown;\n\n if (emit) {\n emitNodeEvent(args.emitEvent, args.nodeId, \"text-start\", {\n ...commonMeta,\n });\n }\n\n const response = await model.stream(messages);\n for await (const chunk of response) {\n const text = chunkToText(chunk);\n if (!text) continue;\n final += text;\n if (typeof chunk === \"object\" && chunk && \"raw\" in chunk) {\n raw = (chunk as KortyxStreamChunk).raw;\n }\n if (emit) {\n emitNodeEvent(args.emitEvent, args.nodeId, \"text-delta\", {\n ...commonMeta,\n delta: text,\n });\n }\n }\n\n if (emit) {\n emitNodeEvent(args.emitEvent, args.nodeId, \"text-end\", {\n ...commonMeta,\n });\n }\n\n return {\n text: final,\n ...(raw !== undefined ? { raw } : {}),\n };\n }\n\n const response = await model.invoke(messages);\n\n if (emit) {\n emitNodeEvent(args.emitEvent, args.nodeId, \"text-start\", {\n ...commonMeta,\n });\n if (response.content) {\n emitNodeEvent(args.emitEvent, args.nodeId, \"text-delta\", {\n ...commonMeta,\n delta: response.content,\n });\n }\n emitNodeEvent(args.emitEvent, args.nodeId, \"text-end\", {\n ...commonMeta,\n });\n }\n\n return {\n text: response.content,\n ...(response.raw !== undefined ? { raw: response.raw } : {}),\n };\n}\n","import type { InterruptInput } from \"@kortyx/core\";\nimport type { SchemaLike } from \"../types\";\nimport { parseWithSchema } from \"../validation\";\n\nconst tryJsonParse = (\n value: string,\n): { ok: true; value: unknown } | { ok: false } => {\n try {\n return { ok: true, value: JSON.parse(value) };\n } catch {\n return { ok: false };\n }\n};\n\nconst extractJsonCodeBlock = (value: string): string | null => {\n const match = value.match(/```(?:json)?\\s*([\\s\\S]*?)```/i);\n if (!match || typeof match[1] !== \"string\") return null;\n const inner = match[1].trim();\n return inner.length > 0 ? inner : null;\n};\n\nconst tryStringify = (value: unknown): string => {\n if (typeof value === \"string\") return value;\n try {\n return JSON.stringify(value, null, 2);\n } catch {\n return String(value);\n }\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n\nexport const resolveOutputCandidate = (text: string): unknown => {\n const trimmed = text.trim();\n if (!trimmed) return text;\n\n const direct = tryJsonParse(trimmed);\n if (direct.ok) return direct.value;\n\n const block = extractJsonCodeBlock(trimmed);\n if (block) {\n const parsedBlock = tryJsonParse(block);\n if (parsedBlock.ok) return parsedBlock.value;\n }\n\n return text;\n};\n\nexport const parseInterruptFirstPassResult = <\n TRequest extends InterruptInput = InterruptInput,\n TOutput = unknown,\n>(args: {\n text: string;\n requestSchema: SchemaLike<TRequest>;\n outputSchema?: SchemaLike<TOutput>;\n}): {\n draftText: string;\n request: TRequest;\n output?: TOutput;\n} => {\n const candidate = resolveOutputCandidate(args.text);\n if (!isRecord(candidate)) {\n throw new Error(\n \"useReason first pass with interrupt must return a JSON object.\",\n );\n }\n\n const requestCandidates: unknown[] = [\n candidate.interruptRequest,\n candidate.request,\n candidate.interrupt,\n candidate,\n ];\n const requestPayload = requestCandidates.find(\n (value) => value !== null && value !== undefined,\n );\n\n const request = parseWithSchema(\n args.requestSchema,\n requestPayload,\n \"useReason interrupt.request\",\n );\n\n let output: TOutput | undefined;\n if (args.outputSchema) {\n const outputPayload = Object.hasOwn(candidate, \"output\")\n ? candidate.output\n : candidate;\n output = parseWithSchema(\n args.outputSchema,\n outputPayload,\n \"useReason output\",\n );\n }\n\n const explicitDraft =\n typeof candidate.draftText === \"string\" && candidate.draftText.length > 0\n ? candidate.draftText\n : typeof candidate.text === \"string\" && candidate.text.length > 0\n ? candidate.text\n : undefined;\n\n if (!args.outputSchema && !explicitDraft) {\n throw new Error(\n \"useReason first pass with interrupt requires `draftText` when outputSchema is not provided.\",\n );\n }\n\n const draftText =\n explicitDraft ??\n (output !== undefined ? tryStringify(output) : String(args.text ?? \"\"));\n\n return {\n draftText,\n request,\n ...(output !== undefined ? { output } : {}),\n };\n};\n","import type { InterruptInput } from \"@kortyx/core\";\nimport { toJSONSchema } from \"zod\";\nimport type { SchemaLike } from \"../types\";\n\nconst tryStringify = (value: unknown): string => {\n if (typeof value === \"string\") return value;\n try {\n return JSON.stringify(value, null, 2);\n } catch {\n return String(value);\n }\n};\n\nconst tryGetSchemaHint = (schema: unknown): string | undefined => {\n try {\n const hint = toJSONSchema(schema as never);\n return JSON.stringify(hint, null, 2);\n } catch {\n return undefined;\n }\n};\n\nconst withSchemaHint = (\n input: string,\n label: string,\n schema: unknown,\n): string => {\n const hint = tryGetSchemaHint(schema);\n if (!hint) return input;\n return `${input}\\n\\n${label}:\\n${hint}`;\n};\n\nexport const defaultInterruptFirstPassInput = (args: {\n input: string;\n requestSchema: SchemaLike<unknown>;\n outputSchema?: SchemaLike<unknown>;\n}): string => {\n const base = args.outputSchema\n ? [\n args.input,\n \"Output rules:\",\n \"- Return JSON only. No markdown fences.\",\n \"- Return an object with keys: output, interruptRequest, draftText.\",\n \"- output must match the expected output JSON schema.\",\n \"- interruptRequest must match the expected interrupt request JSON schema.\",\n \"- interruptRequest must be a non-null object.\",\n \"- draftText should be a concise plain-language summary of output.\",\n \"- If uncertain, still return a valid interruptRequest with safe default options.\",\n ].join(\"\\n\\n\")\n : [\n args.input,\n \"Output rules:\",\n \"- Return JSON only. No markdown fences.\",\n \"- Return an object with keys: draftText, interruptRequest.\",\n \"- draftText should be the current draft answer text.\",\n \"- interruptRequest must match the expected interrupt request JSON schema.\",\n \"- interruptRequest must be a non-null object.\",\n \"- If uncertain, still return a valid interruptRequest with safe default options.\",\n ].join(\"\\n\\n\");\n\n const withInterruptSchema = withSchemaHint(\n base,\n \"Expected interrupt request JSON schema (for `interruptRequest`)\",\n args.requestSchema,\n );\n\n if (!args.outputSchema) return withInterruptSchema;\n const withOutputSchema = withSchemaHint(\n withInterruptSchema,\n \"Expected output JSON schema (for `output`)\",\n args.outputSchema,\n );\n return [\n withOutputSchema,\n \"JSON template:\",\n '{ \"output\": { ... }, \"interruptRequest\": { ... }, \"draftText\": \"...\" }',\n ].join(\"\\n\\n\");\n};\n\nexport const defaultContinuationInput = (args: {\n input: string;\n draftText: string;\n draftOutput?: unknown;\n request: InterruptInput;\n response: unknown;\n}): string =>\n [\n \"You are continuing a paused reasoning task after user input.\",\n \"Update the previous result using the user response and return the final answer only.\",\n \"If the previous output was JSON, return JSON in the same schema.\",\n \"\",\n `Original request:\\n${args.input}`,\n `Draft answer text:\\n${args.draftText}`,\n `Draft output object:\\n${tryStringify(args.draftOutput ?? args.draftText)}`,\n `Interrupt request shown to user:\\n${tryStringify(args.request)}`,\n `User response:\\n${tryStringify(args.response)}`,\n ].join(\"\\n\\n\");\n\nexport const withOutputGuardrails = (\n input: string,\n schema?: SchemaLike<unknown>,\n): string => {\n const base = [\n input,\n \"Output rules:\",\n \"- Return only JSON, no markdown fences.\",\n \"- Ensure the response conforms to the expected output schema.\",\n \"- Do not include explanatory text outside the JSON object.\",\n ].join(\"\\n\\n\");\n return withSchemaHint(base, \"Expected output JSON schema\", schema);\n};\n","import type { InterruptInput, InterruptResult } from \"@kortyx/core\";\nimport { getHookContext } from \"../context\";\nimport { awaitInterruptInternal } from \"../interrupt\";\nimport {\n emitStructuredData,\n resolveStructuredMode,\n shouldEmitStructured,\n} from \"../structured\";\nimport type { SchemaLike, UseReasonArgs, UseReasonResult } from \"../types\";\nimport { parseWithSchema } from \"../validation\";\nimport {\n type ReasonInterruptCheckpoint,\n readReasonCheckpoint,\n resolveHookMemoryPatch,\n resolveReasonCheckpointKey,\n} from \"./checkpoint\";\nimport { createRuntimeId, reasonEngine } from \"./engine\";\nimport {\n parseInterruptFirstPassResult,\n resolveOutputCandidate,\n} from \"./parsing\";\nimport {\n defaultContinuationInput,\n defaultInterruptFirstPassInput,\n withOutputGuardrails,\n} from \"./prompting\";\n\nconst emitReasonStructuredOutput = <TOutput>(args: {\n id?: string;\n opId: string;\n output: TOutput;\n structured: UseReasonArgs<TOutput>[\"structured\"];\n}): void => {\n if (!shouldEmitStructured(args.structured)) return;\n\n emitStructuredData<TOutput>({\n dataType: args.structured?.dataType ?? \"reason-output\",\n data: args.output,\n mode: resolveStructuredMode(args.structured),\n ...(args.structured?.schemaId\n ? { schemaId: args.structured.schemaId }\n : {}),\n ...(args.structured?.schemaVersion\n ? { schemaVersion: args.structured.schemaVersion }\n : {}),\n ...(args.id ? { id: args.id } : {}),\n opId: args.opId,\n });\n};\n\nexport async function useReason<\n TOutput = unknown,\n TRequest extends InterruptInput = InterruptInput,\n TResponse = InterruptResult,\n>(\n args: UseReasonArgs<TOutput, TRequest, TResponse>,\n): Promise<UseReasonResult<TOutput, TResponse>> {\n const ctx = getHookContext();\n const id =\n typeof args.id === \"string\" && args.id.length > 0 ? args.id : undefined;\n const opId = createRuntimeId();\n const checkpointKey = resolveReasonCheckpointKey({\n ...(id ? { id } : {}),\n autoIndex: ctx.reasonCallIndex++,\n });\n const existingCheckpoint = readReasonCheckpoint(\n ctx.currentNodeState.byKey[checkpointKey],\n );\n\n const reasonMeta =\n typeof id === \"string\" ? ({ id, opId } as const) : ({ opId } as const);\n const suppressTextStream = Boolean(args.outputSchema || args.interrupt);\n\n let firstText = \"\";\n let firstRaw: unknown;\n let firstOutput: TOutput | undefined;\n let firstInterruptRequest: TRequest | undefined;\n\n let finalText = \"\";\n let finalRaw: unknown;\n let finalOutput: TOutput | undefined;\n\n if (existingCheckpoint) {\n firstText = existingCheckpoint.firstText;\n firstRaw = existingCheckpoint.firstRaw;\n firstOutput = existingCheckpoint.firstOutput as TOutput | undefined;\n finalText = firstText;\n finalRaw = firstRaw;\n finalOutput = firstOutput;\n } else {\n const first = await reasonEngine(\n {\n ...args,\n emit: suppressTextStream ? false : args.emit,\n stream: suppressTextStream ? false : args.stream,\n },\n reasonMeta,\n args.interrupt\n ? defaultInterruptFirstPassInput({\n input: args.input,\n requestSchema: args.interrupt.requestSchema,\n ...(args.outputSchema\n ? { outputSchema: args.outputSchema as SchemaLike<unknown> }\n : {}),\n })\n : args.outputSchema\n ? withOutputGuardrails(\n args.input,\n args.outputSchema as SchemaLike<unknown>,\n )\n : undefined,\n );\n firstRaw = first.raw;\n finalRaw = first.raw;\n\n if (args.interrupt) {\n const firstPass = parseInterruptFirstPassResult<TRequest, TOutput>({\n text: first.text,\n requestSchema: args.interrupt.requestSchema,\n ...(args.outputSchema\n ? { outputSchema: args.outputSchema as SchemaLike<TOutput> }\n : {}),\n });\n firstText = firstPass.draftText;\n finalText = firstPass.draftText;\n firstInterruptRequest = firstPass.request;\n firstOutput = firstPass.output;\n finalOutput = firstPass.output;\n\n if (firstOutput !== undefined) {\n emitReasonStructuredOutput<TOutput>({\n ...(id ? { id } : {}),\n opId,\n output: firstOutput,\n structured: args.structured,\n });\n }\n } else {\n firstText = first.text;\n finalText = first.text;\n if (args.outputSchema) {\n firstOutput = parseWithSchema(\n args.outputSchema,\n resolveOutputCandidate(first.text),\n \"useReason output\",\n );\n\n emitReasonStructuredOutput<TOutput>({\n ...(id ? { id } : {}),\n opId,\n output: firstOutput,\n structured: args.structured,\n });\n }\n finalOutput = firstOutput;\n }\n }\n\n let interruptResponse: TResponse | undefined;\n\n if (args.interrupt) {\n const requestSchema = args.interrupt.requestSchema;\n\n const interruptRequest = existingCheckpoint\n ? parseWithSchema(\n requestSchema,\n existingCheckpoint.request,\n \"useReason interrupt.request\",\n )\n : firstInterruptRequest;\n\n if (!interruptRequest) {\n throw new Error(\n \"useReason interrupt request is missing; first pass did not produce a valid interrupt payload.\",\n );\n }\n\n if (!existingCheckpoint) {\n ctx.currentNodeState.byKey[checkpointKey] = {\n status: \"awaiting_interrupt\",\n request: interruptRequest,\n firstText,\n ...(firstRaw !== undefined ? { firstRaw } : {}),\n ...(firstOutput !== undefined ? { firstOutput } : {}),\n } satisfies ReasonInterruptCheckpoint;\n ctx.dirty = true;\n }\n\n const resumeMemoryPatch = resolveHookMemoryPatch({\n nodeId: ctx.node.graph.node,\n currentNodeState: ctx.currentNodeState,\n workflowState: ctx.workflowState,\n });\n\n interruptResponse = await awaitInterruptInternal<TRequest, TResponse>({\n request: interruptRequest,\n requestSchema,\n responseSchema: args.interrupt.responseSchema,\n ...(args.interrupt.schemaId ? { schemaId: args.interrupt.schemaId } : {}),\n ...(args.interrupt.schemaVersion\n ? { schemaVersion: args.interrupt.schemaVersion }\n : {}),\n ...(id ? { id } : {}),\n meta: {\n __kortyxResumeMemory: resumeMemoryPatch,\n },\n });\n\n if (Object.hasOwn(ctx.currentNodeState.byKey, checkpointKey)) {\n delete ctx.currentNodeState.byKey[checkpointKey];\n ctx.dirty = true;\n }\n\n const continuationInput = defaultContinuationInput({\n input: args.input,\n draftText: firstText,\n ...(firstOutput !== undefined ? { draftOutput: firstOutput } : {}),\n request: interruptRequest,\n response: interruptResponse,\n });\n\n const second = await reasonEngine(\n {\n ...args,\n emit: suppressTextStream ? false : args.emit,\n stream: suppressTextStream ? false : args.stream,\n },\n reasonMeta,\n args.outputSchema\n ? withOutputGuardrails(\n continuationInput,\n args.outputSchema as SchemaLike<unknown>,\n )\n : continuationInput,\n );\n finalText = second.text;\n finalRaw = second.raw;\n\n if (args.outputSchema) {\n finalOutput = parseWithSchema(\n args.outputSchema,\n resolveOutputCandidate(finalText),\n \"useReason output\",\n );\n\n emitReasonStructuredOutput<TOutput>({\n ...(id ? { id } : {}),\n opId,\n output: finalOutput,\n structured: args.structured,\n });\n }\n }\n\n return {\n ...(id ? { id } : {}),\n opId,\n text: finalText,\n ...(finalRaw !== undefined ? { raw: finalRaw } : {}),\n ...(finalOutput !== undefined ? { output: finalOutput } : {}),\n ...(interruptResponse !== undefined ? { interruptResponse } : {}),\n };\n}\n","import type {\n InterruptInput,\n InterruptResult,\n NodeContext,\n} from \"@kortyx/core\";\nimport type { MemoryAdapter } from \"@kortyx/memory\";\nimport { getHookContext } from \"./context\";\nimport { awaitInterruptInternal } from \"./interrupt\";\nimport { useReason as useReasonInternal } from \"./reason/use-reason\";\nimport { emitStructuredData } from \"./structured\";\nimport type {\n UseInterruptArgs,\n UseReasonArgs,\n UseReasonResult,\n UseStructuredDataArgs,\n} from \"./types\";\n\nexport type {\n SchemaLike,\n StructuredDataMode,\n UseInterruptArgs,\n UseReasonArgs,\n UseReasonInterruptConfig,\n UseReasonResult,\n UseReasonStructuredConfig,\n UseReasonStructuredStreamMode,\n UseStructuredDataArgs,\n} from \"./types\";\n\ntype StateSetter<T> = (next: T | ((prev: T) => T)) => void;\n\nexport function useEmit(): NodeContext[\"emit\"] {\n const ctx = getHookContext();\n return ctx.node.emit;\n}\n\nexport function useStructuredData<TData = unknown>(\n args: UseStructuredDataArgs<TData>,\n): void {\n emitStructuredData(args);\n}\n\nexport function useReason<\n TOutput = unknown,\n TRequest extends InterruptInput = InterruptInput,\n TResponse = InterruptResult,\n>(\n args: UseReasonArgs<TOutput, TRequest, TResponse>,\n): Promise<UseReasonResult<TOutput, TResponse>> {\n return useReasonInternal(args);\n}\n\nexport function useAiMemory(): MemoryAdapter {\n const ctx = getHookContext();\n if (!ctx.memoryAdapter) {\n throw new Error(\"useAiMemory requires a memory adapter in runtime config.\");\n }\n return ctx.memoryAdapter;\n}\n\nexport function useInterrupt<\n TRequest extends InterruptInput = InterruptInput,\n TResponse = InterruptResult,\n>(args: UseInterruptArgs<TRequest, TResponse>): Promise<TResponse> {\n return awaitInterruptInternal(args);\n}\n\nexport function useNodeState<T>(initialValue: T): [T, StateSetter<T>];\nexport function useNodeState<T>(\n key: string,\n initialValue?: T,\n): [T, StateSetter<T>];\nexport function useNodeState<T>(\n keyOrInitial: string | T,\n initialValue?: T,\n): [T, StateSetter<T>] {\n const ctx = getHookContext();\n const nodeState = ctx.currentNodeState;\n\n if (typeof keyOrInitial === \"string\") {\n const key = keyOrInitial;\n const hasInitial = arguments.length > 1;\n\n if (!Object.hasOwn(nodeState.byKey, key) && hasInitial) {\n nodeState.byKey[key] = initialValue as T;\n ctx.dirty = true;\n }\n\n const getValue = () => nodeState.byKey[key] as T;\n const setValue: StateSetter<T> = (next) => {\n const prev = getValue();\n const resolved =\n typeof next === \"function\" ? (next as (p: T) => T)(prev) : next;\n nodeState.byKey[key] = resolved;\n ctx.dirty = true;\n };\n\n return [getValue(), setValue];\n }\n\n const index = ctx.nodeStateIndex++;\n if (index >= nodeState.byIndex.length) {\n nodeState.byIndex[index] = keyOrInitial as T;\n ctx.dirty = true;\n }\n\n const getValue = () => nodeState.byIndex[index] as T;\n const setValue: StateSetter<T> = (next) => {\n const prev = getValue();\n const resolved =\n typeof next === \"function\" ? (next as (p: T) => T)(prev) : next;\n nodeState.byIndex[index] = resolved;\n ctx.dirty = true;\n };\n\n return [getValue(), setValue];\n}\n\nexport function useWorkflowState<T>(\n key: string,\n initialValue?: T,\n): [T, StateSetter<T>] {\n const ctx = getHookContext();\n const workflowState = ctx.workflowState;\n const hasInitial = arguments.length > 1;\n\n if (!Object.hasOwn(workflowState, key) && hasInitial) {\n workflowState[key] = initialValue as T;\n ctx.dirty = true;\n }\n\n const getValue = () => workflowState[key] as T;\n const setValue: StateSetter<T> = (next) => {\n const prev = getValue();\n const resolved =\n typeof next === \"function\" ? (next as (p: T) => T)(prev) : next;\n workflowState[key] = resolved;\n ctx.dirty = true;\n };\n\n return [getValue(), setValue];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAAAA;AAAA,EAAA;AAAA;AAAA;AAAA;;;ACAA,8BAAkC;AA8BlC,IAAM,UAAU,IAAI,0CAAuC;AAE3D,IAAM,WAAW,CAAC,UAChB,QAAQ,KAAK,KAAK,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK;AAErE,IAAM,qBAAqB,CAAC,UAAmC;AAC7D,MAAI,MAAM,QAAQ,KAAK,GAAG;AACxB,WAAO,EAAE,SAAS,CAAC,GAAG,KAAK,GAAG,OAAO,CAAC,EAAE;AAAA,EAC1C;AAEA,MAAI,SAAS,KAAK,GAAG;AACnB,UAAM,UAAU,MAAM,QAAQ,MAAM,OAAO,IAAI,CAAC,GAAG,MAAM,OAAO,IAAI,CAAC;AACrE,UAAM,QAAQ,SAAS,MAAM,KAAK,IAAI,EAAE,GAAG,MAAM,MAAM,IAAI,CAAC;AAC5D,WAAO,EAAE,SAAS,MAAM;AAAA,EAC1B;AAEA,SAAO,EAAE,SAAS,CAAC,GAAG,OAAO,CAAC,EAAE;AAClC;AAEA,IAAM,qBAAqB,CAAC,UAC1B,SAAS,KAAK,IAAI,EAAE,GAAG,MAAM,IAAI,CAAC;AAEpC,IAAM,gBAAgB,CAAC,UAAkC;AACvD,QAAM,SAAU,MAAM,UAAU,CAAC;AACjC,QAAM,WAAW,SAAS,OAAO,QAAQ,IAAI,OAAO,WAAW;AAC/D,QAAM,SAAqB,CAAC;AAC5B,MAAI,SAAS,UAAU,SAAS,EAAG,QAAO,YAAY,UAAU;AAChE,MA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AAI;AAC3B,QAAI,QAAQ;AAAA,EACd;AAEA,SAAO,CAAC,SAAS,GAAG,QAAQ;AAC9B;AAEO,SAAS,iBACd,KACA,cACqB;AACrB,QAAM,MAAM,eAAe;AAC3B,QAAM,gBAAgB,IAAI;AAC1B,QAAM,aAAa,UAAU,SAAS;AAEtC,MAAI,CAAC,OAAO,OAAO,eAAe,GAAG,KAAK,YAAY;AACpD,kBAAc,GAAG,IAAI;AACrB,QAAI,QAAQ;AAAA,EACd;AAEA,QAAM,WAAW,MAAM,cAAc,GAAG;AACxC,QAAM,WAA2B,CAAC,SAAS;AACzC,UAAM,OAAO,SAAS;AACtB,UAAM,WACJ,OAAO,SAAS,aAAc,KAAqB,IAAI,IAAI;AAC7D,kBAAc,GAAG,IAAI;AACrB,QAAI,QAAQ;AAAA,EACd;AAEA,SAAO,CAAC,SAAS,GAAG,QAAQ;AAC9B;","names":["useReason","import_node_crypto","response","createRuntimeId","isRecord","tryStringify","createRuntimeId","useReason","getValue","setValue"]}
|
package/dist/internal.d.ts
CHANGED
|
@@ -1,3 +1,24 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
import { GetProviderFn, ProviderModelRef } from '@kortyx/providers';
|
|
2
|
+
|
|
3
|
+
interface RunReasonEngineArgs {
|
|
4
|
+
getProvider: GetProviderFn;
|
|
5
|
+
model: ProviderModelRef;
|
|
6
|
+
input: string;
|
|
7
|
+
system?: string | undefined;
|
|
8
|
+
temperature?: number | undefined;
|
|
9
|
+
defaultTemperature?: number | undefined;
|
|
10
|
+
stream?: boolean | undefined;
|
|
11
|
+
emit?: boolean | undefined;
|
|
12
|
+
nodeId?: string | undefined;
|
|
13
|
+
emitEvent?: ((event: string, payload: unknown) => void) | undefined;
|
|
14
|
+
id?: string | undefined;
|
|
15
|
+
opId?: string | undefined;
|
|
16
|
+
segmentId?: string | undefined;
|
|
17
|
+
}
|
|
18
|
+
interface RunReasonEngineResult {
|
|
19
|
+
text: string;
|
|
20
|
+
raw?: unknown;
|
|
21
|
+
}
|
|
22
|
+
declare function runReasonEngine(args: RunReasonEngineArgs): Promise<RunReasonEngineResult>;
|
|
23
|
+
|
|
24
|
+
export { type RunReasonEngineArgs, type RunReasonEngineResult, runReasonEngine };
|
package/dist/internal.js
CHANGED
|
@@ -1,5 +1,125 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
var
|
|
5
|
-
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
3
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
4
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
5
|
+
var __export = (target, all) => {
|
|
6
|
+
for (var name in all)
|
|
7
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
8
|
+
};
|
|
9
|
+
var __copyProps = (to, from, except, desc) => {
|
|
10
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
11
|
+
for (let key of __getOwnPropNames(from))
|
|
12
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
13
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
14
|
+
}
|
|
15
|
+
return to;
|
|
16
|
+
};
|
|
17
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
18
|
+
|
|
19
|
+
// src/internal.ts
|
|
20
|
+
var internal_exports = {};
|
|
21
|
+
__export(internal_exports, {
|
|
22
|
+
runReasonEngine: () => runReasonEngine
|
|
23
|
+
});
|
|
24
|
+
module.exports = __toCommonJS(internal_exports);
|
|
25
|
+
|
|
26
|
+
// src/reason-engine.ts
|
|
27
|
+
var import_node_crypto = require("crypto");
|
|
28
|
+
var chunkToText = (chunk) => {
|
|
29
|
+
if (typeof chunk === "string") return chunk;
|
|
30
|
+
if (typeof chunk.text === "string") return chunk.text;
|
|
31
|
+
if (typeof chunk.content === "string") return chunk.content;
|
|
32
|
+
return "";
|
|
33
|
+
};
|
|
34
|
+
var createRuntimeId = () => {
|
|
35
|
+
try {
|
|
36
|
+
return (0, import_node_crypto.randomUUID)();
|
|
37
|
+
} catch {
|
|
38
|
+
return `${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
var emitNodeEvent = (emitEvent, nodeId, event, payload) => {
|
|
42
|
+
if (!emitEvent) return;
|
|
43
|
+
emitEvent(event, {
|
|
44
|
+
...payload,
|
|
45
|
+
...typeof nodeId === "string" && nodeId.length > 0 ? { node: nodeId } : {}
|
|
46
|
+
});
|
|
47
|
+
};
|
|
48
|
+
async function runReasonEngine(args) {
|
|
49
|
+
const stream = args.stream ?? args.model.options?.streaming ?? true;
|
|
50
|
+
const emit = args.emit ?? true;
|
|
51
|
+
const temperature = args.temperature ?? args.model.options?.temperature ?? args.defaultTemperature;
|
|
52
|
+
const model = args.getProvider(args.model.providerId, args.model.modelId, {
|
|
53
|
+
...temperature !== void 0 ? { temperature } : {},
|
|
54
|
+
streaming: stream
|
|
55
|
+
});
|
|
56
|
+
const messages = [];
|
|
57
|
+
if (typeof args.system === "string" && args.system.length > 0) {
|
|
58
|
+
messages.push({ role: "system", content: args.system });
|
|
59
|
+
}
|
|
60
|
+
messages.push({ role: "user", content: String(args.input ?? "") });
|
|
61
|
+
const opId = typeof args.opId === "string" && args.opId.length > 0 ? args.opId : createRuntimeId();
|
|
62
|
+
const segmentId = typeof args.segmentId === "string" && args.segmentId.length > 0 ? args.segmentId : createRuntimeId();
|
|
63
|
+
const commonMeta = {
|
|
64
|
+
...typeof args.id === "string" && args.id.length > 0 ? { id: args.id } : {},
|
|
65
|
+
opId,
|
|
66
|
+
segmentId
|
|
67
|
+
};
|
|
68
|
+
if (stream) {
|
|
69
|
+
let final = "";
|
|
70
|
+
let raw;
|
|
71
|
+
if (emit) {
|
|
72
|
+
emitNodeEvent(args.emitEvent, args.nodeId, "text-start", {
|
|
73
|
+
...commonMeta
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
const response2 = await model.stream(messages);
|
|
77
|
+
for await (const chunk of response2) {
|
|
78
|
+
const text = chunkToText(chunk);
|
|
79
|
+
if (!text) continue;
|
|
80
|
+
final += text;
|
|
81
|
+
if (typeof chunk === "object" && chunk && "raw" in chunk) {
|
|
82
|
+
raw = chunk.raw;
|
|
83
|
+
}
|
|
84
|
+
if (emit) {
|
|
85
|
+
emitNodeEvent(args.emitEvent, args.nodeId, "text-delta", {
|
|
86
|
+
...commonMeta,
|
|
87
|
+
delta: text
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
if (emit) {
|
|
92
|
+
emitNodeEvent(args.emitEvent, args.nodeId, "text-end", {
|
|
93
|
+
...commonMeta
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
return {
|
|
97
|
+
text: final,
|
|
98
|
+
...raw !== void 0 ? { raw } : {}
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
const response = await model.invoke(messages);
|
|
102
|
+
if (emit) {
|
|
103
|
+
emitNodeEvent(args.emitEvent, args.nodeId, "text-start", {
|
|
104
|
+
...commonMeta
|
|
105
|
+
});
|
|
106
|
+
if (response.content) {
|
|
107
|
+
emitNodeEvent(args.emitEvent, args.nodeId, "text-delta", {
|
|
108
|
+
...commonMeta,
|
|
109
|
+
delta: response.content
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
emitNodeEvent(args.emitEvent, args.nodeId, "text-end", {
|
|
113
|
+
...commonMeta
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
return {
|
|
117
|
+
text: response.content,
|
|
118
|
+
...response.raw !== void 0 ? { raw: response.raw } : {}
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
122
|
+
0 && (module.exports = {
|
|
123
|
+
runReasonEngine
|
|
124
|
+
});
|
|
125
|
+
//# sourceMappingURL=internal.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/internal.ts","../src/reason-engine.ts"],"sourcesContent":["export type {\n RunReasonEngineArgs,\n RunReasonEngineResult,\n} from \"./reason-engine\";\nexport { runReasonEngine } from \"./reason-engine\";\n","import { randomUUID } from \"node:crypto\";\nimport type {\n GetProviderFn,\n KortyxPromptMessage,\n KortyxStreamChunk,\n ProviderModelRef,\n} from \"@kortyx/providers\";\n\nexport interface RunReasonEngineArgs {\n getProvider: GetProviderFn;\n model: ProviderModelRef;\n input: string;\n system?: string | undefined;\n temperature?: number | undefined;\n defaultTemperature?: number | undefined;\n stream?: boolean | undefined;\n emit?: boolean | undefined;\n nodeId?: string | undefined;\n emitEvent?: ((event: string, payload: unknown) => void) | undefined;\n id?: string | undefined;\n opId?: string | undefined;\n segmentId?: string | undefined;\n}\n\nexport interface RunReasonEngineResult {\n text: string;\n raw?: unknown;\n}\n\nconst chunkToText = (chunk: KortyxStreamChunk | string): string => {\n if (typeof chunk === \"string\") return chunk;\n if (typeof chunk.text === \"string\") return chunk.text;\n if (typeof chunk.content === \"string\") return chunk.content;\n return \"\";\n};\n\nconst createRuntimeId = (): string => {\n try {\n return randomUUID();\n } catch {\n return `${Date.now()}-${Math.random().toString(36).slice(2)}`;\n }\n};\n\nconst emitNodeEvent = (\n emitEvent: RunReasonEngineArgs[\"emitEvent\"],\n nodeId: string | undefined,\n event: string,\n payload: Record<string, unknown>,\n): void => {\n if (!emitEvent) return;\n emitEvent(event, {\n ...payload,\n ...(typeof nodeId === \"string\" && nodeId.length > 0\n ? { node: nodeId }\n : {}),\n });\n};\n\nexport async function runReasonEngine(\n args: RunReasonEngineArgs,\n): Promise<RunReasonEngineResult> {\n const stream = args.stream ?? args.model.options?.streaming ?? true;\n const emit = args.emit ?? true;\n const temperature =\n args.temperature ??\n args.model.options?.temperature ??\n args.defaultTemperature;\n\n const model = args.getProvider(args.model.providerId, args.model.modelId, {\n ...(temperature !== undefined ? { temperature } : {}),\n streaming: stream,\n });\n\n const messages: KortyxPromptMessage[] = [];\n if (typeof args.system === \"string\" && args.system.length > 0) {\n messages.push({ role: \"system\", content: args.system });\n }\n messages.push({ role: \"user\", content: String(args.input ?? \"\") });\n\n const opId =\n typeof args.opId === \"string\" && args.opId.length > 0\n ? args.opId\n : createRuntimeId();\n const segmentId =\n typeof args.segmentId === \"string\" && args.segmentId.length > 0\n ? args.segmentId\n : createRuntimeId();\n\n const commonMeta: Record<string, unknown> = {\n ...(typeof args.id === \"string\" && args.id.length > 0\n ? { id: args.id }\n : {}),\n opId,\n segmentId,\n };\n\n if (stream) {\n let final = \"\";\n let raw: unknown;\n\n if (emit) {\n emitNodeEvent(args.emitEvent, args.nodeId, \"text-start\", {\n ...commonMeta,\n });\n }\n\n const response = await model.stream(messages);\n for await (const chunk of response) {\n const text = chunkToText(chunk);\n if (!text) continue;\n final += text;\n if (typeof chunk === \"object\" && chunk && \"raw\" in chunk) {\n raw = (chunk as KortyxStreamChunk).raw;\n }\n if (emit) {\n emitNodeEvent(args.emitEvent, args.nodeId, \"text-delta\", {\n ...commonMeta,\n delta: text,\n });\n }\n }\n\n if (emit) {\n emitNodeEvent(args.emitEvent, args.nodeId, \"text-end\", {\n ...commonMeta,\n });\n }\n\n return {\n text: final,\n ...(raw !== undefined ? { raw } : {}),\n };\n }\n\n const response = await model.invoke(messages);\n\n if (emit) {\n emitNodeEvent(args.emitEvent, args.nodeId, \"text-start\", {\n ...commonMeta,\n });\n if (response.content) {\n emitNodeEvent(args.emitEvent, args.nodeId, \"text-delta\", {\n ...commonMeta,\n delta: response.content,\n });\n }\n emitNodeEvent(args.emitEvent, args.nodeId, \"text-end\", {\n ...commonMeta,\n });\n }\n\n return {\n text: response.content,\n ...(response.raw !== undefined ? { raw: response.raw } : {}),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,yBAA2B;AA6B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,IACH;AACA,kBAAc,KAAK,WAAW,KAAK,QAAQ,YAAY;AAAA,MACrD,GAAG;AAAA,IACL,CAAC;AAAA,EACH;AAEA,SAAO;AAAA,IACL,MAAM,SAAS;AAAA,IACf,GAAI,SAAS,QAAQ,SAAY,EAAE,KAAK,SAAS,IAAI,IAAI,CAAC;AAAA,EAC5D;AACF;","names":["response"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kortyx/hooks",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "Lifecycle hooks and extension points for Kortyx.",
|
|
6
6
|
"keywords": [
|
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
"kortyx"
|
|
14
14
|
],
|
|
15
15
|
"license": "Apache-2.0",
|
|
16
|
-
"homepage": "https://
|
|
16
|
+
"homepage": "https://kortyx.io/",
|
|
17
17
|
"bugs": {
|
|
18
18
|
"url": "https://github.com/kortyx-io/kortyx/issues"
|
|
19
19
|
},
|
|
@@ -36,26 +36,30 @@
|
|
|
36
36
|
"CHANGELOG.md"
|
|
37
37
|
],
|
|
38
38
|
"scripts": {
|
|
39
|
-
"build": "
|
|
39
|
+
"build": "tsup",
|
|
40
40
|
"predev": "tsc -p tsconfig.build.json",
|
|
41
41
|
"dev": "tsc --watch",
|
|
42
42
|
"lint": "biome check src",
|
|
43
|
-
"test": "pnpm -s type-check",
|
|
43
|
+
"test": "vitest run && pnpm -s type-check",
|
|
44
|
+
"test:watch": "vitest",
|
|
44
45
|
"type-check": "tsc --noEmit"
|
|
45
46
|
},
|
|
46
47
|
"dependencies": {
|
|
47
48
|
"@kortyx/core": "workspace:*",
|
|
48
49
|
"@kortyx/memory": "workspace:*",
|
|
49
|
-
"@kortyx/providers": "workspace:*"
|
|
50
|
+
"@kortyx/providers": "workspace:*",
|
|
51
|
+
"zod": "^4.1.13"
|
|
50
52
|
},
|
|
51
53
|
"devDependencies": {
|
|
52
54
|
"turbo": "^2.5.4",
|
|
53
|
-
"typescript": "5.7.2"
|
|
55
|
+
"typescript": "5.7.2",
|
|
56
|
+
"tsup": "^8.5.1",
|
|
57
|
+
"vitest": "^3.2.4"
|
|
54
58
|
},
|
|
55
59
|
"sideEffects": false,
|
|
56
60
|
"repository": {
|
|
57
61
|
"type": "git",
|
|
58
|
-
"url": "https://github.com/kortyx-io/kortyx",
|
|
62
|
+
"url": "https://github.com/kortyx-io/kortyx.git",
|
|
59
63
|
"directory": "packages/hooks"
|
|
60
64
|
}
|
|
61
65
|
}
|
package/dist/context.d.ts
DELETED
|
@@ -1,26 +0,0 @@
|
|
|
1
|
-
import type { GraphState, NodeContext } from "@kortyx/core";
|
|
2
|
-
import type { MemoryAdapter } from "@kortyx/memory";
|
|
3
|
-
import type { GetProviderFn } from "@kortyx/providers";
|
|
4
|
-
type NodeStateStore = {
|
|
5
|
-
byIndex: unknown[];
|
|
6
|
-
byKey: Record<string, unknown>;
|
|
7
|
-
};
|
|
8
|
-
export type HookRuntimeContext = {
|
|
9
|
-
node: NodeContext;
|
|
10
|
-
state: GraphState;
|
|
11
|
-
getProvider?: GetProviderFn;
|
|
12
|
-
memoryAdapter?: MemoryAdapter;
|
|
13
|
-
};
|
|
14
|
-
type HookInternalContext = HookRuntimeContext & {
|
|
15
|
-
nodeStateIndex: number;
|
|
16
|
-
currentNodeState: NodeStateStore;
|
|
17
|
-
workflowState: Record<string, unknown>;
|
|
18
|
-
dirty: boolean;
|
|
19
|
-
};
|
|
20
|
-
export declare function runWithHookContext<T>(ctx: HookRuntimeContext, fn: () => Promise<T>): Promise<{
|
|
21
|
-
result: T;
|
|
22
|
-
memoryUpdates: Record<string, unknown> | null;
|
|
23
|
-
}>;
|
|
24
|
-
export declare function getHookContext(): HookInternalContext;
|
|
25
|
-
export {};
|
|
26
|
-
//# sourceMappingURL=context.d.ts.map
|
package/dist/context.d.ts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"context.d.ts","sourceRoot":"","sources":["../src/context.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC5D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AACpD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAEvD,KAAK,cAAc,GAAG;IACpB,OAAO,EAAE,OAAO,EAAE,CAAC;IACnB,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAChC,CAAC;AAOF,MAAM,MAAM,kBAAkB,GAAG;IAC/B,IAAI,EAAE,WAAW,CAAC;IAClB,KAAK,EAAE,UAAU,CAAC;IAClB,WAAW,CAAC,EAAE,aAAa,CAAC;IAC5B,aAAa,CAAC,EAAE,aAAa,CAAC;CAC/B,CAAC;AAEF,KAAK,mBAAmB,GAAG,kBAAkB,GAAG;IAC9C,cAAc,EAAE,MAAM,CAAC;IACvB,gBAAgB,EAAE,cAAc,CAAC;IACjC,aAAa,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACvC,KAAK,EAAE,OAAO,CAAC;CAChB,CAAC;AAwEF,wBAAsB,kBAAkB,CAAC,CAAC,EACxC,GAAG,EAAE,kBAAkB,EACvB,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GACnB,OAAO,CAAC;IAAE,MAAM,EAAE,CAAC,CAAC;IAAC,aAAa,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAAA;CAAE,CAAC,CAYvE;AAED,wBAAgB,cAAc,IAAI,mBAAmB,CAMpD"}
|
package/dist/context.js
DELETED
|
@@ -1,82 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.runWithHookContext = runWithHookContext;
|
|
4
|
-
exports.getHookContext = getHookContext;
|
|
5
|
-
const node_async_hooks_1 = require("node:async_hooks");
|
|
6
|
-
const storage = new node_async_hooks_1.AsyncLocalStorage();
|
|
7
|
-
const isRecord = (value) => Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
8
|
-
const normalizeNodeState = (value) => {
|
|
9
|
-
if (Array.isArray(value)) {
|
|
10
|
-
return { byIndex: [...value], byKey: {} };
|
|
11
|
-
}
|
|
12
|
-
if (isRecord(value)) {
|
|
13
|
-
const byIndex = Array.isArray(value.byIndex) ? [...value.byIndex] : [];
|
|
14
|
-
const byKey = isRecord(value.byKey) ? { ...value.byKey } : {};
|
|
15
|
-
return { byIndex, byKey };
|
|
16
|
-
}
|
|
17
|
-
return { byIndex: [], byKey: {} };
|
|
18
|
-
};
|
|
19
|
-
const cloneWorkflowState = (value) => isRecord(value) ? { ...value } : {};
|
|
20
|
-
const getHookMemory = (state) => {
|
|
21
|
-
const memory = (state.memory ?? {});
|
|
22
|
-
const internal = isRecord(memory.__kortyx) ? memory.__kortyx : undefined;
|
|
23
|
-
const result = {};
|
|
24
|
-
if (isRecord(internal?.nodeState))
|
|
25
|
-
result.nodeState = internal?.nodeState;
|
|
26
|
-
if (isRecord(internal?.workflowState)) {
|
|
27
|
-
result.workflowState = internal?.workflowState;
|
|
28
|
-
}
|
|
29
|
-
return result;
|
|
30
|
-
};
|
|
31
|
-
const createInternalContext = (ctx) => {
|
|
32
|
-
const hookMemory = getHookMemory(ctx.state);
|
|
33
|
-
const nodeId = ctx.node.graph.node;
|
|
34
|
-
const storedNodeId = typeof hookMemory.nodeState?.nodeId === "string"
|
|
35
|
-
? String(hookMemory.nodeState?.nodeId)
|
|
36
|
-
: "";
|
|
37
|
-
const storedState = hookMemory.nodeState?.state;
|
|
38
|
-
const currentNodeState = storedNodeId && storedNodeId === nodeId
|
|
39
|
-
? normalizeNodeState(storedState)
|
|
40
|
-
: { byIndex: [], byKey: {} };
|
|
41
|
-
return {
|
|
42
|
-
...ctx,
|
|
43
|
-
nodeStateIndex: 0,
|
|
44
|
-
currentNodeState,
|
|
45
|
-
workflowState: cloneWorkflowState(hookMemory.workflowState),
|
|
46
|
-
dirty: false,
|
|
47
|
-
};
|
|
48
|
-
};
|
|
49
|
-
const buildMemoryUpdates = (ctx) => {
|
|
50
|
-
if (!ctx.dirty)
|
|
51
|
-
return null;
|
|
52
|
-
return {
|
|
53
|
-
__kortyx: {
|
|
54
|
-
nodeState: {
|
|
55
|
-
nodeId: ctx.node.graph.node,
|
|
56
|
-
state: ctx.currentNodeState,
|
|
57
|
-
},
|
|
58
|
-
workflowState: ctx.workflowState,
|
|
59
|
-
},
|
|
60
|
-
};
|
|
61
|
-
};
|
|
62
|
-
async function runWithHookContext(ctx, fn) {
|
|
63
|
-
const internal = createInternalContext(ctx);
|
|
64
|
-
try {
|
|
65
|
-
const result = await storage.run(internal, fn);
|
|
66
|
-
return { result, memoryUpdates: buildMemoryUpdates(internal) };
|
|
67
|
-
}
|
|
68
|
-
catch (err) {
|
|
69
|
-
const memoryUpdates = buildMemoryUpdates(internal);
|
|
70
|
-
if (memoryUpdates && err && typeof err === "object") {
|
|
71
|
-
err.__kortyxMemoryUpdates = memoryUpdates;
|
|
72
|
-
}
|
|
73
|
-
throw err;
|
|
74
|
-
}
|
|
75
|
-
}
|
|
76
|
-
function getHookContext() {
|
|
77
|
-
const ctx = storage.getStore();
|
|
78
|
-
if (!ctx) {
|
|
79
|
-
throw new Error("Hooks can only be used while a node is executing.");
|
|
80
|
-
}
|
|
81
|
-
return ctx;
|
|
82
|
-
}
|
package/dist/hooks.d.ts
DELETED
|
@@ -1,29 +0,0 @@
|
|
|
1
|
-
import type { InterruptInput, InterruptResult, NodeContext } from "@kortyx/core";
|
|
2
|
-
import type { MemoryAdapter } from "@kortyx/memory";
|
|
3
|
-
import type { ProviderModelRef } from "@kortyx/providers";
|
|
4
|
-
type StateSetter<T> = (next: T | ((prev: T) => T)) => void;
|
|
5
|
-
export type UseReasonArgs = {
|
|
6
|
-
model: ProviderModelRef;
|
|
7
|
-
input: string;
|
|
8
|
-
system?: string | undefined;
|
|
9
|
-
temperature?: number | undefined;
|
|
10
|
-
emit?: boolean | undefined;
|
|
11
|
-
stream?: boolean | undefined;
|
|
12
|
-
};
|
|
13
|
-
export type UseReasonResult = {
|
|
14
|
-
text: string;
|
|
15
|
-
raw?: unknown;
|
|
16
|
-
};
|
|
17
|
-
export declare function useEmit(): NodeContext["emit"];
|
|
18
|
-
export declare function useStructuredData(args: {
|
|
19
|
-
data: unknown;
|
|
20
|
-
dataType?: string | undefined;
|
|
21
|
-
}): void;
|
|
22
|
-
export declare function useReason(args: UseReasonArgs): Promise<UseReasonResult>;
|
|
23
|
-
export declare function useAiMemory(): MemoryAdapter;
|
|
24
|
-
export declare function useAiInterrupt(input: InterruptInput): Promise<InterruptResult>;
|
|
25
|
-
export declare function useNodeState<T>(initialValue: T): [T, StateSetter<T>];
|
|
26
|
-
export declare function useNodeState<T>(key: string, initialValue?: T): [T, StateSetter<T>];
|
|
27
|
-
export declare function useWorkflowState<T>(key: string, initialValue?: T): [T, StateSetter<T>];
|
|
28
|
-
export {};
|
|
29
|
-
//# sourceMappingURL=hooks.d.ts.map
|
package/dist/hooks.d.ts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"hooks.d.ts","sourceRoot":"","sources":["../src/hooks.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,cAAc,EACd,eAAe,EACf,WAAW,EACZ,MAAM,cAAc,CAAC;AACtB,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AACpD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAK1D,KAAK,WAAW,CAAC,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,KAAK,IAAI,CAAC;AAE3D,MAAM,MAAM,aAAa,GAAG;IAC1B,KAAK,EAAE,gB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"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.useEmit = useEmit;
|
|
4
|
-
exports.useStructuredData = useStructuredData;
|
|
5
|
-
exports.useReason = useReason;
|
|
6
|
-
exports.useAiMemory = useAiMemory;
|
|
7
|
-
exports.useAiInterrupt = useAiInterrupt;
|
|
8
|
-
exports.useNodeState = useNodeState;
|
|
9
|
-
exports.useWorkflowState = useWorkflowState;
|
|
10
|
-
const context_1 = require("./context");
|
|
11
|
-
const reason_engine_1 = require("./reason-engine");
|
|
12
|
-
function useEmit() {
|
|
13
|
-
const ctx = (0, context_1.getHookContext)();
|
|
14
|
-
return ctx.node.emit;
|
|
15
|
-
}
|
|
16
|
-
function useStructuredData(args) {
|
|
17
|
-
const ctx = (0, context_1.getHookContext)();
|
|
18
|
-
ctx.node.emit("structured_data", {
|
|
19
|
-
node: ctx.node.graph.node,
|
|
20
|
-
...(typeof args.dataType === "string" && args.dataType.length > 0
|
|
21
|
-
? { dataType: args.dataType }
|
|
22
|
-
: {}),
|
|
23
|
-
data: args.data,
|
|
24
|
-
});
|
|
25
|
-
}
|
|
26
|
-
async function reasonEngine(args) {
|
|
27
|
-
const ctx = (0, context_1.getHookContext)();
|
|
28
|
-
const getProvider = ctx.getProvider;
|
|
29
|
-
if (!getProvider) {
|
|
30
|
-
throw new Error("useReason requires a provider factory in runtime config.");
|
|
31
|
-
}
|
|
32
|
-
return (0, reason_engine_1.runReasonEngine)({
|
|
33
|
-
getProvider,
|
|
34
|
-
model: args.model,
|
|
35
|
-
input: args.input,
|
|
36
|
-
system: args.system,
|
|
37
|
-
temperature: args.temperature,
|
|
38
|
-
defaultTemperature: ctx.node.config?.model?.temperature,
|
|
39
|
-
stream: args.stream,
|
|
40
|
-
emit: args.emit,
|
|
41
|
-
nodeId: ctx.node.graph.node,
|
|
42
|
-
emitEvent: ctx.node.emit,
|
|
43
|
-
});
|
|
44
|
-
}
|
|
45
|
-
function useReason(args) {
|
|
46
|
-
return reasonEngine(args);
|
|
47
|
-
}
|
|
48
|
-
function useAiMemory() {
|
|
49
|
-
const ctx = (0, context_1.getHookContext)();
|
|
50
|
-
if (!ctx.memoryAdapter) {
|
|
51
|
-
throw new Error("useAiMemory requires a memory adapter in runtime config.");
|
|
52
|
-
}
|
|
53
|
-
return ctx.memoryAdapter;
|
|
54
|
-
}
|
|
55
|
-
function useAiInterrupt(input) {
|
|
56
|
-
const ctx = (0, context_1.getHookContext)();
|
|
57
|
-
return Promise.resolve(ctx.node.awaitInterrupt(input));
|
|
58
|
-
}
|
|
59
|
-
function useNodeState(keyOrInitial, initialValue) {
|
|
60
|
-
const ctx = (0, context_1.getHookContext)();
|
|
61
|
-
const nodeState = ctx.currentNodeState;
|
|
62
|
-
if (typeof keyOrInitial === "string") {
|
|
63
|
-
const key = keyOrInitial;
|
|
64
|
-
const hasInitial = arguments.length > 1;
|
|
65
|
-
if (!Object.hasOwn(nodeState.byKey, key) && hasInitial) {
|
|
66
|
-
nodeState.byKey[key] = initialValue;
|
|
67
|
-
ctx.dirty = true;
|
|
68
|
-
}
|
|
69
|
-
const getValue = () => nodeState.byKey[key];
|
|
70
|
-
const setValue = (next) => {
|
|
71
|
-
const prev = getValue();
|
|
72
|
-
const resolved = typeof next === "function" ? next(prev) : next;
|
|
73
|
-
nodeState.byKey[key] = resolved;
|
|
74
|
-
ctx.dirty = true;
|
|
75
|
-
};
|
|
76
|
-
return [getValue(), setValue];
|
|
77
|
-
}
|
|
78
|
-
const index = ctx.nodeStateIndex++;
|
|
79
|
-
if (index >= nodeState.byIndex.length) {
|
|
80
|
-
nodeState.byIndex[index] = keyOrInitial;
|
|
81
|
-
ctx.dirty = true;
|
|
82
|
-
}
|
|
83
|
-
const getValue = () => nodeState.byIndex[index];
|
|
84
|
-
const setValue = (next) => {
|
|
85
|
-
const prev = getValue();
|
|
86
|
-
const resolved = typeof next === "function" ? next(prev) : next;
|
|
87
|
-
nodeState.byIndex[index] = resolved;
|
|
88
|
-
ctx.dirty = true;
|
|
89
|
-
};
|
|
90
|
-
return [getValue(), setValue];
|
|
91
|
-
}
|
|
92
|
-
function useWorkflowState(key, initialValue) {
|
|
93
|
-
const ctx = (0, context_1.getHookContext)();
|
|
94
|
-
const workflowState = ctx.workflowState;
|
|
95
|
-
const hasInitial = arguments.length > 1;
|
|
96
|
-
if (!Object.hasOwn(workflowState, key) && hasInitial) {
|
|
97
|
-
workflowState[key] = initialValue;
|
|
98
|
-
ctx.dirty = true;
|
|
99
|
-
}
|
|
100
|
-
const getValue = () => workflowState[key];
|
|
101
|
-
const setValue = (next) => {
|
|
102
|
-
const prev = getValue();
|
|
103
|
-
const resolved = typeof next === "function" ? next(prev) : next;
|
|
104
|
-
workflowState[key] = resolved;
|
|
105
|
-
ctx.dirty = true;
|
|
106
|
-
};
|
|
107
|
-
return [getValue(), setValue];
|
|
108
|
-
}
|
package/dist/index.d.ts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAOA,YAAY,EAAE,kBAAkB,EAAE,MAAM,WAAW,CAAC;AACpD,OAAO,EAAE,kBAAkB,EAAE,MAAM,WAAW,CAAC;AAC/C,YAAY,EAAE,aAAa,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAC9D,OAAO,EACL,cAAc,EACd,WAAW,EACX,OAAO,EACP,YAAY,EACZ,SAAS,EACT,iBAAiB,EACjB,gBAAgB,GACjB,MAAM,SAAS,CAAC"}
|
package/dist/internal.d.ts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"internal.d.ts","sourceRoot":"","sources":["../src/internal.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,mBAAmB,EACnB,qBAAqB,GACtB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC"}
|
package/dist/reason-engine.d.ts
DELETED
|
@@ -1,19 +0,0 @@
|
|
|
1
|
-
import type { GetProviderFn, ProviderModelRef } from "@kortyx/providers";
|
|
2
|
-
export interface RunReasonEngineArgs {
|
|
3
|
-
getProvider: GetProviderFn;
|
|
4
|
-
model: ProviderModelRef;
|
|
5
|
-
input: string;
|
|
6
|
-
system?: string | undefined;
|
|
7
|
-
temperature?: number | undefined;
|
|
8
|
-
defaultTemperature?: number | undefined;
|
|
9
|
-
stream?: boolean | undefined;
|
|
10
|
-
emit?: boolean | undefined;
|
|
11
|
-
nodeId?: string | undefined;
|
|
12
|
-
emitEvent?: ((event: string, payload: unknown) => void) | undefined;
|
|
13
|
-
}
|
|
14
|
-
export interface RunReasonEngineResult {
|
|
15
|
-
text: string;
|
|
16
|
-
raw?: unknown;
|
|
17
|
-
}
|
|
18
|
-
export declare function runReasonEngine(args: RunReasonEngineArgs): Promise<RunReasonEngineResult>;
|
|
19
|
-
//# sourceMappingURL=reason-engine.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"reason-engine.d.ts","sourceRoot":"","sources":["../src/reason-engine.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,aAAa,EAGb,gBAAgB,EACjB,MAAM,mBAAmB,CAAC;AAE3B,MAAM,WAAW,mBAAmB;IAClC,WAAW,EAAE,aAAa,CAAC;IAC3B,KAAK,EAAE,gBAAgB,CAAC;IACxB,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAC5B,WAAW,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IACjC,kBAAkB,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IACxC,MAAM,CAAC,EAAE,OAAO,GAAG,SAAS,CAAC;IAC7B,IAAI,CAAC,EAAE,OAAO,GAAG,SAAS,CAAC;IAC3B,MAAM,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAC5B,SAAS,CAAC,EAAE,CAAC,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,KAAK,IAAI,CAAC,GAAG,SAAS,CAAC;CACrE;AAED,MAAM,WAAW,qBAAqB;IACpC,IAAI,EAAE,MAAM,CAAC;IACb,GAAG,CAAC,EAAE,OAAO,CAAC;CACf;AAwBD,wBAAsB,eAAe,CACnC,IAAI,EAAE,mBAAmB,GACxB,OAAO,CAAC,qBAAqB,CAAC,CAoEhC"}
|