@keystrokehq/keystroke 1.0.15 → 1.0.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/dist/agent.cjs +6 -5
  2. package/dist/agent.cjs.map +1 -1
  3. package/dist/agent.d.cts +2 -2
  4. package/dist/agent.d.mts +2 -2
  5. package/dist/agent.mjs +6 -5
  6. package/dist/agent.mjs.map +1 -1
  7. package/dist/{dist-qrlBz5eZ.mjs → dist-CFKSzdSZ.mjs} +4 -2
  8. package/dist/dist-CFKSzdSZ.mjs.map +1 -0
  9. package/dist/{dist-DESn8Gyx.mjs → dist-DtLObwAS.mjs} +2 -2
  10. package/dist/{dist-DESn8Gyx.mjs.map → dist-DtLObwAS.mjs.map} +1 -1
  11. package/dist/{dist-CIXPxH8Y.cjs → dist-DvZ4Dj_O.cjs} +4 -2
  12. package/dist/dist-DvZ4Dj_O.cjs.map +1 -0
  13. package/dist/{dist-jju5p8QW.cjs → dist-sGyB6KsC.cjs} +2 -2
  14. package/dist/{dist-jju5p8QW.cjs.map → dist-sGyB6KsC.cjs.map} +1 -1
  15. package/dist/index-BTz2OMAM.d.cts.map +1 -1
  16. package/dist/{index-BQEzTb7P.d.cts → index-C9qevi4R.d.cts} +10 -3
  17. package/dist/index-C9qevi4R.d.cts.map +1 -0
  18. package/dist/{index-ub0OqZXh.d.mts → index-CGa7YLSI.d.mts} +10 -3
  19. package/dist/index-CGa7YLSI.d.mts.map +1 -0
  20. package/dist/index-Cq2F2XdS.d.mts.map +1 -1
  21. package/dist/{mistral-HS6Ekkp2.cjs → mistral-BUpUX0vh.cjs} +2 -2
  22. package/dist/{mistral-HS6Ekkp2.cjs.map → mistral-BUpUX0vh.cjs.map} +1 -1
  23. package/dist/{mistral-B3AiRi15.mjs → mistral-Cy4OBeve.mjs} +2 -2
  24. package/dist/{mistral-B3AiRi15.mjs.map → mistral-Cy4OBeve.mjs.map} +1 -1
  25. package/dist/{sse-DISKrIFa.mjs → sse-4YoGxYO1.mjs} +2 -2
  26. package/dist/{sse-DISKrIFa.mjs.map → sse-4YoGxYO1.mjs.map} +1 -1
  27. package/dist/{sse-ELfo0nZE.cjs → sse-C0gnbJhp.cjs} +2 -2
  28. package/dist/{sse-ELfo0nZE.cjs.map → sse-C0gnbJhp.cjs.map} +1 -1
  29. package/dist/trigger.cjs +1 -1
  30. package/dist/trigger.d.cts +1 -1
  31. package/dist/trigger.d.mts +1 -1
  32. package/dist/trigger.mjs +1 -1
  33. package/dist/workflow.cjs +1 -1
  34. package/dist/workflow.mjs +1 -1
  35. package/package.json +1 -1
  36. package/dist/dist-CIXPxH8Y.cjs.map +0 -1
  37. package/dist/dist-qrlBz5eZ.mjs.map +0 -1
  38. package/dist/index-BQEzTb7P.d.cts.map +0 -1
  39. package/dist/index-ub0OqZXh.d.mts.map +0 -1
@@ -1,5 +1,5 @@
1
1
  const require_dist = require("./dist-CDMCEgV0.cjs");
2
- const require_dist$1 = require("./dist-CIXPxH8Y.cjs");
2
+ const require_dist$1 = require("./dist-DvZ4Dj_O.cjs");
3
3
  let zod = require("zod");
4
4
  let node_async_hooks = require("node:async_hooks");
5
5
  //#region ../workflow/dist/index.mjs
@@ -600,4 +600,4 @@ Object.defineProperty(exports, "serializeWorkflowError", {
600
600
  }
601
601
  });
602
602
 
603
- //# sourceMappingURL=dist-jju5p8QW.cjs.map
603
+ //# sourceMappingURL=dist-sGyB6KsC.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"dist-jju5p8QW.cjs","names":["z","withSpan","logSystem","captureConsole","normalizeCredentialList","getActionCredentialRequirements","resolveActionCredentials","runWithMcpCredentialContext","executeAction","AsyncLocalStorage","registerWorkflowRunGetter","getRunSignal","getWorkflowRunHandle"],"sources":["../../workflow/dist/index.mjs"],"sourcesContent":["import { z } from \"zod\";\nimport { executeAction, getActionCredentialRequirements, getRunSignal, getWorkflowRunHandle, normalizeCredentialList, registerWorkflowRunGetter, runWithMcpCredentialContext } from \"@keystrokehq/action\";\nimport { captureConsole, logSystem, withSpan } from \"@keystrokehq/tracing\";\nimport { resolveActionCredentials } from \"@keystrokehq/credentials\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n//#region src/run-canceled-error.ts\nvar RunCanceledError = class extends Error {\n\tconstructor(runId) {\n\t\tsuper(runId ? `Workflow run ${runId} was canceled` : \"Workflow run was canceled\");\n\t\tthis.name = \"RunCanceledError\";\n\t}\n};\nfunction isRunCanceledError(error) {\n\treturn error instanceof RunCanceledError;\n}\n//#endregion\n//#region src/workflow-definition.ts\nconst zodSchema = z.custom((v) => v instanceof z.ZodType, \"must be a Zod schema\");\n/** Runtime validation for an unbranded workflow definition. */\nconst workflowCoreSchema = z.object({\n\tslug: z.string().trim().min(1),\n\tname: z.string().optional(),\n\tdescription: z.string().optional(),\n\tsubscription: z.object({ mode: z.enum([\"system\", \"subscribable\"]).optional() }).optional(),\n\tinput: zodSchema,\n\toutput: zodSchema,\n\trun: z.function()\n});\nconst WORKFLOW = Symbol.for(\"keystroke.workflow\");\n/**\n* Validates brand + shape via `workflowCoreSchema` so discovery and guards\n* reject malformed definitions.\n*/\nfunction isWorkflow(value) {\n\tif (typeof value !== \"object\" || value === null) return false;\n\tif (!(WORKFLOW in value) || value[WORKFLOW] !== true) return false;\n\treturn workflowCoreSchema.safeParse(value).success;\n}\n//#endregion\n//#region src/define-workflow.ts\nfunction defineWorkflow(def) {\n\tconst result = workflowCoreSchema.safeParse(def);\n\tif (!result.success) throw new Error(`Invalid workflow definition: ${formatIssues(result.error.issues)}`);\n\treturn {\n\t\t...result.data,\n\t\t[WORKFLOW]: true\n\t};\n}\nfunction formatIssues(issues) {\n\treturn issues.map((issue) => {\n\t\treturn `${issue.path.length > 0 ? `${issue.path.join(\".\")}: ` : \"\"}${issue.message}`;\n\t}).join(\"; \");\n}\n//#endregion\n//#region src/replay/error.ts\nfunction serializeWorkflowError(error) {\n\tif (error instanceof Error) return {\n\t\tname: error.name,\n\t\tmessage: error.message\n\t};\n\treturn { message: String(error) };\n}\n/** Rebuild an Error from a recorded error so replay re-raises the same failure. */\nfunction deserializeWorkflowError(data) {\n\tconst serialized = data;\n\tconst error = new Error(serialized?.message ?? \"Workflow step failed\");\n\tif (serialized?.name) error.name = serialized.name;\n\treturn error;\n}\n//#endregion\n//#region src/replay/duration.ts\nconst UNIT_MS = {\n\tms: 1,\n\ts: 1e3,\n\tm: 6e4,\n\th: 36e5,\n\td: 864e5\n};\n/** Resolve a sleep duration to an absolute resume time. */\nfunction resolveResumeAt(duration, now = /* @__PURE__ */ new Date()) {\n\tif (duration instanceof Date) return duration;\n\tif (typeof duration === \"number\") return new Date(now.getTime() + Math.max(0, duration));\n\treturn new Date(now.getTime() + parseDurationToMs(duration));\n}\nfunction parseDurationToMs(value) {\n\tconst match = /^(\\d+(?:\\.\\d+)?)\\s*(ms|s|m|h|d)$/.exec(value.trim());\n\tif (!match) throw new Error(`Invalid sleep duration \"${value}\". Use a number of ms, a Date, or a string like \"5s\", \"10m\", \"1h\".`);\n\tconst amount = Number(match[1]);\n\tconst unit = match[2];\n\treturn Math.round(amount * UNIT_MS[unit]);\n}\n//#endregion\n//#region src/replay/events-consumer.ts\n/** Indexes replay events by correlationId for O(1) cache-hit checks during replay. */\nvar EventsConsumer = class {\n\tbyCorrelationId = /* @__PURE__ */ new Map();\n\tconstructor(events) {\n\t\tfor (const event of events) {\n\t\t\tif (!event.correlationId) continue;\n\t\t\tconst list = this.byCorrelationId.get(event.correlationId);\n\t\t\tif (list) list.push(event);\n\t\t\telse this.byCorrelationId.set(event.correlationId, [event]);\n\t\t}\n\t}\n\tevents(correlationId) {\n\t\treturn this.byCorrelationId.get(correlationId) ?? [];\n\t}\n\thasEventType(correlationId, type) {\n\t\treturn this.events(correlationId).some((event) => event.type === type);\n\t}\n\t/**\n\t* Cache lookup for a step. Returns the recorded output on a `step_completed`,\n\t* re-raises the recorded error on a terminal `step_failed` (so a permanently\n\t* failed step is not re-executed), and otherwise reports a miss — including\n\t* when only `step_retrying` events exist (the step re-runs on the next pass).\n\t*/\n\tgetStepResult(correlationId) {\n\t\tconst events = this.events(correlationId);\n\t\tconst failed = events.find((event) => event.type === \"step_failed\");\n\t\tif (failed) throw deserializeWorkflowError(failed.data);\n\t\tconst completed = events.find((event) => event.type === \"step_completed\");\n\t\tif (completed) return {\n\t\t\tcompleted: true,\n\t\t\tresult: completed.data\n\t\t};\n\t\treturn { completed: false };\n\t}\n\t/** Number of prior `step_retrying` events recorded for a step (= failed attempts so far). */\n\tcountRetrying(correlationId) {\n\t\treturn this.events(correlationId).filter((event) => event.type === \"step_retrying\").length;\n\t}\n\tisSleepCompleted(correlationId) {\n\t\treturn this.hasEventType(correlationId, \"sleep_completed\");\n\t}\n\t/** Returns the persisted resumeAt for a scheduled-but-not-completed sleep, if any. */\n\tgetSleepResumeAt(correlationId) {\n\t\tconst scheduled = this.events(correlationId).find((event) => event.type === \"sleep_scheduled\");\n\t\tif (!scheduled) return;\n\t\tconst data = scheduled.data;\n\t\treturn data?.resumeAt ? new Date(data.resumeAt) : void 0;\n\t}\n\tgetHookToken(correlationId) {\n\t\treturn (this.events(correlationId).find((event) => event.type === \"hook_created\")?.data)?.token;\n\t}\n\tgetHookResult(correlationId) {\n\t\tconst resumed = this.events(correlationId).find((event) => event.type === \"hook_resumed\");\n\t\tif (!resumed) return { resolved: false };\n\t\treturn {\n\t\t\tresolved: true,\n\t\t\tpayload: resumed.data?.payload\n\t\t};\n\t}\n};\n//#endregion\n//#region src/replay/suspension.ts\n/** A promise that never settles — returned by a suspending primitive so the body parks. */\nfunction createPendingPromise() {\n\treturn new Promise(() => {});\n}\n/**\n* Collects pending items requested within a single tick and resolves once, so\n* parallel suspensions (e.g. Promise.all of two sleeps) batch into one suspension.\n*/\nvar SuspensionCoordinator = class {\n\titems = /* @__PURE__ */ new Map();\n\tscheduled = false;\n\tresolve;\n\tpromise;\n\tconstructor() {\n\t\tthis.promise = new Promise((resolve) => {\n\t\t\tthis.resolve = resolve;\n\t\t});\n\t}\n\trequest(item) {\n\t\tthis.items.set(item.correlationId, item);\n\t\tif (!this.scheduled) {\n\t\t\tthis.scheduled = true;\n\t\t\tqueueMicrotask(() => {\n\t\t\t\tthis.resolve([...this.items.values()]);\n\t\t\t});\n\t\t}\n\t}\n\twaitForSuspension() {\n\t\treturn this.promise;\n\t}\n};\n//#endregion\n//#region src/replay/replay-context.ts\nfunction createReplayState(params) {\n\treturn {\n\t\trunId: params.runId,\n\t\tconsumer: params.consumer,\n\t\tcoordinator: params.coordinator,\n\t\teventLog: params.eventLog,\n\t\tnewEvents: [],\n\t\tnow: params.now ?? /* @__PURE__ */ new Date(),\n\t\thookBaseUrl: params.hookBaseUrl,\n\t\tsleepCounter: 0,\n\t\thookCounter: 0,\n\t\tstepOccurrences: /* @__PURE__ */ new Map(),\n\t\tstepCorrelationIds: /* @__PURE__ */ new Set()\n\t};\n}\n/**\n* Allocate the correlation id for a step. An explicit `.stepId(x)` maps to\n* `step:x` (and must be unique within a run); otherwise the key is\n* `step:<actionKey>#<occurrence>` so that two calls to the same action get\n* distinct, replay-stable ids and inserting an unrelated call never shifts the\n* ids of later calls (unlike a single global ordinal).\n*/\nfunction nextStepCorrelationId(state, actionKey, explicitId) {\n\tif (explicitId !== void 0) {\n\t\tconst correlationId = `step:${explicitId}`;\n\t\tif (state.stepCorrelationIds.has(correlationId)) throw new Error(`Duplicate step id \"${explicitId}\" in workflow run ${state.runId}`);\n\t\tstate.stepCorrelationIds.add(correlationId);\n\t\treturn correlationId;\n\t}\n\tconst occurrence = state.stepOccurrences.get(actionKey) ?? 0;\n\tstate.stepOccurrences.set(actionKey, occurrence + 1);\n\tconst correlationId = `step:${actionKey}#${occurrence}`;\n\tstate.stepCorrelationIds.add(correlationId);\n\treturn correlationId;\n}\nfunction createSleep(state) {\n\treturn function sleep(duration) {\n\t\tconst correlationId = `sleep#${state.sleepCounter++}`;\n\t\tif (state.consumer.isSleepCompleted(correlationId)) return Promise.resolve();\n\t\tconst scheduledResumeAt = state.consumer.getSleepResumeAt(correlationId);\n\t\tconst resumeAt = scheduledResumeAt ?? resolveResumeAt(duration, state.now);\n\t\tif (scheduledResumeAt && resumeAt.getTime() <= state.now.getTime()) {\n\t\t\tstate.newEvents.push({\n\t\t\t\tid: `sleep_completed:${state.runId}:${correlationId}`,\n\t\t\t\trunId: state.runId,\n\t\t\t\ttype: \"sleep_completed\",\n\t\t\t\tcorrelationId\n\t\t\t});\n\t\t\treturn Promise.resolve();\n\t\t}\n\t\tif (!scheduledResumeAt) state.newEvents.push({\n\t\t\tid: `sleep_scheduled:${state.runId}:${correlationId}`,\n\t\t\trunId: state.runId,\n\t\t\ttype: \"sleep_scheduled\",\n\t\t\tcorrelationId,\n\t\t\tdata: { resumeAt: resumeAt.toISOString() }\n\t\t});\n\t\tstate.coordinator.request({\n\t\t\tkind: \"sleep\",\n\t\t\tcorrelationId,\n\t\t\tresumeAt\n\t\t});\n\t\treturn createPendingPromise();\n\t};\n}\nfunction createHook(state) {\n\treturn function hook(options) {\n\t\tconst correlationId = `hook#${state.hookCounter++}`;\n\t\tconst token = options?.token ?? state.consumer.getHookToken(correlationId) ?? `hook_${crypto.randomUUID()}`;\n\t\treturn {\n\t\t\ttoken,\n\t\t\tresumeUrl: state.hookBaseUrl ? `${state.hookBaseUrl}/hooks/${token}/resume` : `/hooks/${token}/resume`,\n\t\t\tthen(onFulfilled, onRejected) {\n\t\t\t\tconst result = state.consumer.getHookResult(correlationId);\n\t\t\t\tif (result.resolved) {\n\t\t\t\t\tconst payload = options?.schema ? options.schema.parse(result.payload) : result.payload;\n\t\t\t\t\treturn Promise.resolve(payload).then(onFulfilled, onRejected);\n\t\t\t\t}\n\t\t\t\tif (!state.consumer.hasEventType(correlationId, \"hook_created\")) state.newEvents.push({\n\t\t\t\t\tid: `hook_created:${state.runId}:${correlationId}`,\n\t\t\t\t\trunId: state.runId,\n\t\t\t\t\ttype: \"hook_created\",\n\t\t\t\t\tcorrelationId,\n\t\t\t\t\tdata: { token }\n\t\t\t\t});\n\t\t\t\tstate.coordinator.request({\n\t\t\t\t\tkind: \"hook\",\n\t\t\t\t\tcorrelationId,\n\t\t\t\t\ttoken\n\t\t\t\t});\n\t\t\t\treturn createPendingPromise().then(onFulfilled, onRejected);\n\t\t\t}\n\t\t};\n\t};\n}\n//#endregion\n//#region src/run-durable-step.ts\n/**\n* Shared durable-step shell: resolve a stable `correlation_id`, short-circuit\n* from the event log on a cache hit, otherwise execute and append\n* `step_completed` immediately (per-step crash durability). A thrown step\n* appends `step_retrying` (non-fatal, re-run on the next attempt) and\n* rethrows; the terminal `step_failed` is written by the job handler once the\n* queue exhausts retries.\n*/\nasync function runDurableStep(state, options) {\n\tconst { runId, consumer, eventLog } = state;\n\tgetRunSignal().throwIfAborted();\n\tconst correlationId = nextStepCorrelationId(state, options.key, options.id);\n\tconst cached = consumer.getStepResult(correlationId);\n\tconst metadata = {\n\t\trunId,\n\t\t[options.metadataKey]: options.key,\n\t\tcorrelationId\n\t};\n\tif (cached.completed) {\n\t\tawait withSpan({\n\t\t\tkind: options.kind,\n\t\t\tname: options.key,\n\t\t\trefId: `${runId}:${correlationId}`,\n\t\t\tmetadata: {\n\t\t\t\t...metadata,\n\t\t\t\treplayed: true\n\t\t\t}\n\t\t}, async () => {\n\t\t\tawait logSystem(\"info\", options.replayMessage, metadata);\n\t\t});\n\t\treturn options.parseCached ? options.parseCached(cached.result) : cached.result;\n\t}\n\treturn withSpan({\n\t\tkind: options.kind,\n\t\tname: options.key,\n\t\trefId: `${runId}:${correlationId}`,\n\t\tmetadata\n\t}, async () => captureConsole(async () => {\n\t\ttry {\n\t\t\tconst result = await options.execute(correlationId);\n\t\t\tawait eventLog.append({\n\t\t\t\tid: `step_completed:${runId}:${correlationId}`,\n\t\t\t\trunId,\n\t\t\t\ttype: \"step_completed\",\n\t\t\t\tcorrelationId,\n\t\t\t\tdata: result\n\t\t\t});\n\t\t\treturn result;\n\t\t} catch (error) {\n\t\t\tconst attempt = consumer.countRetrying(correlationId);\n\t\t\tawait eventLog.append({\n\t\t\t\tid: `step_retrying:${runId}:${correlationId}:${attempt}`,\n\t\t\t\trunId,\n\t\t\t\ttype: \"step_retrying\",\n\t\t\t\tcorrelationId,\n\t\t\t\tdata: serializeWorkflowError(error)\n\t\t\t});\n\t\t\tstate.failedCorrelationId = correlationId;\n\t\t\tthrow error;\n\t\t}\n\t}));\n}\n//#endregion\n//#region src/create-action-runner.ts\nfunction withCredentialScopeOverride(requirements, scope) {\n\tif (!requirements || !scope) return requirements;\n\treturn normalizeCredentialList(requirements).map((requirement) => ({\n\t\t...requirement,\n\t\tscope\n\t}));\n}\n/** Builds the per-run action runner; durability lives in {@link runDurableStep}. */\nfunction createActionRunner(state, options = {}) {\n\treturn (action, input, runOptions) => runDurableStep(state, {\n\t\tkind: \"action\",\n\t\tkey: action.slug,\n\t\tid: runOptions?.id,\n\t\tmetadataKey: \"actionKey\",\n\t\treplayMessage: \"action replayed from checkpoint\",\n\t\tparseCached: (cached) => action.output.parse(cached),\n\t\texecute: async (correlationId) => {\n\t\t\tconst requirements = withCredentialScopeOverride(getActionCredentialRequirements(action), runOptions?.credentialScope);\n\t\t\tconst credentials = requirements?.length ? await resolveActionCredentials(requirements, {\n\t\t\t\tresolveCredentials: options.resolveCredentials,\n\t\t\t\tcontext: options.credentialContext,\n\t\t\t\toauthAdapter: options.oauthAdapter,\n\t\t\t\tconsumer: {\n\t\t\t\t\tkind: \"action\",\n\t\t\t\t\tname: action.slug,\n\t\t\t\t\tid: correlationId\n\t\t\t\t}\n\t\t\t}) : {};\n\t\t\treturn runWithMcpCredentialContext({\n\t\t\t\t...options.mcpCredentialContext,\n\t\t\t\tconsumerId: correlationId\n\t\t\t}, () => executeAction(action, input, credentials));\n\t\t}\n\t});\n}\n//#endregion\n//#region src/create-agent-step-runner.ts\n/**\n* Builds the per-run agent runner: each `agent.prompt()` in a workflow body\n* becomes a durable step keyed `step:<agentKey>#<occurrence>` (same scheme as\n* actions). The actual prompt execution is delegated to `runAgent`, supplied\n* by the host (server) via `executeWorkflow({ runAgent })`.\n*/\nfunction createAgentStepRunner(state, runAgent) {\n\treturn (agent, input, options) => {\n\t\tconst slug = agent.slug;\n\t\treturn runDurableStep(state, {\n\t\t\tkind: \"agent_session\",\n\t\t\tkey: slug,\n\t\t\tid: options?.id,\n\t\t\tmetadataKey: \"agentKey\",\n\t\t\treplayMessage: \"agent step replayed from checkpoint\",\n\t\t\texecute: (_correlationId) => runAgent(agent, input, options?.runPrompt)\n\t\t});\n\t};\n}\n//#endregion\n//#region src/create-llm-step-runner.ts\n/**\n* Builds the per-run LLM runner: each `promptLlm()` in a workflow body becomes a\n* durable step keyed `step:promptLlm#<occurrence>`. The actual LLM call is\n* delegated to `runLlm`, supplied by the host (server) via `executeWorkflow({ runLlm })`.\n*/\nfunction createLlmStepRunner(state, runLlm) {\n\treturn (opts) => runDurableStep(state, {\n\t\tkind: \"llm\",\n\t\tkey: \"promptLlm\",\n\t\tid: opts.stepId,\n\t\tmetadataKey: \"llmKey\",\n\t\treplayMessage: \"llm step replayed from checkpoint\",\n\t\tparseCached: (cached) => opts.outputSchema ? opts.outputSchema.parse(cached) : cached,\n\t\texecute: (_correlationId) => runLlm(opts)\n\t});\n}\n//#endregion\n//#region src/run-context.ts\nconst storage = new AsyncLocalStorage();\nregisterWorkflowRunGetter(() => {\n\tconst store = storage.getStore();\n\tif (!store) return;\n\treturn {\n\t\tactionRunner: store.actionRunner,\n\t\tagentRunner: store.agentRunner,\n\t\tllmRunner: store.llmRunner\n\t};\n});\nfunction runWithWorkflowContext(store, fn) {\n\treturn storage.run(store, fn);\n}\n//#endregion\n//#region src/replay/memory-event-log.ts\n/** In-memory durable log for inline execution and tests. */\nvar MemoryEventLog = class {\n\tevents = [];\n\tids = /* @__PURE__ */ new Set();\n\tasync append(event) {\n\t\tconst id = event.id ?? crypto.randomUUID();\n\t\tif (this.ids.has(id)) return false;\n\t\tthis.ids.add(id);\n\t\tthis.events.push({\n\t\t\tid,\n\t\t\trunId: event.runId,\n\t\t\tseq: this.events.length,\n\t\t\ttype: event.type,\n\t\t\tcorrelationId: event.correlationId ?? null,\n\t\t\tdata: event.data ?? null\n\t\t});\n\t\treturn true;\n\t}\n\tasync listReplay(runId) {\n\t\treturn this.events.filter((event) => event.runId === runId).map((event) => ({ ...event }));\n\t}\n};\n//#endregion\n//#region src/execute-workflow.ts\n/**\n* The single way to run a workflow: replay its event log from the top, execute\n* un-cached primitives, and either complete/fail or suspend at the first\n* un-satisfied sleep/hook. New events (sleep_scheduled/sleep_completed/\n* hook_created/run_completed/run_failed) are flushed before returning.\n*\n* Durability comes entirely from the log — a suspended run resumes by calling\n* this again with the same `runId` and event log once the sleep is due or the\n* hook is resumed.\n*/\nasync function executeWorkflow(workflow, input, options = {}) {\n\tconst runId = options.runId ?? crypto.randomUUID();\n\tconst eventLog = options.eventLog ?? new MemoryEventLog();\n\tconst signal = getRunSignal();\n\tconst consumer = new EventsConsumer(await eventLog.listReplay(runId));\n\tconst coordinator = new SuspensionCoordinator();\n\tconst state = createReplayState({\n\t\trunId,\n\t\tconsumer,\n\t\tcoordinator,\n\t\teventLog,\n\t\thookBaseUrl: options.hookBaseUrl,\n\t\tnow: options.now\n\t});\n\tconst actionRunner = createActionRunner(state, {\n\t\tresolveCredentials: options.resolveCredentials,\n\t\tcredentialContext: options.credentialContext,\n\t\toauthAdapter: options.oauthAdapter,\n\t\tmcpCredentialContext: { assignmentTarget: {\n\t\t\ttype: \"workflow\",\n\t\t\tkey: workflow.slug\n\t\t} }\n\t});\n\tconst ctx = {\n\t\trunId,\n\t\tsleep: createSleep(state),\n\t\thook: createHook(state),\n\t\t...options.context\n\t};\n\tconst agentRunner = options.runAgent ? createAgentStepRunner(state, options.runAgent) : void 0;\n\tconst llmRunner = options.runLlm ? createLlmStepRunner(state, options.runLlm) : void 0;\n\tconst validatedInput = workflow.input.parse(input);\n\tconst bodyPromise = runWithWorkflowContext({\n\t\tactionRunner,\n\t\tagentRunner,\n\t\tllmRunner,\n\t\trunId\n\t}, () => captureConsole(async () => workflow.run(validatedInput, ctx)));\n\tlet onAbort;\n\tconst waitForAbort = signal.aborted ? Promise.resolve({ type: \"canceled\" }) : new Promise((resolve) => {\n\t\tonAbort = () => resolve({ type: \"canceled\" });\n\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t});\n\tconst outcome = await Promise.race([\n\t\tbodyPromise.then((output) => ({\n\t\t\ttype: \"done\",\n\t\t\toutput\n\t\t}), (error) => ({\n\t\t\ttype: \"error\",\n\t\t\terror\n\t\t})),\n\t\tcoordinator.waitForSuspension().then((items) => ({\n\t\t\ttype: \"suspended\",\n\t\t\titems\n\t\t})),\n\t\twaitForAbort\n\t]);\n\tif (onAbort) signal.removeEventListener(\"abort\", onAbort);\n\tlet result;\n\tif (outcome.type === \"suspended\") {\n\t\tbodyPromise.catch(() => {});\n\t\tresult = {\n\t\t\tstatus: \"suspended\",\n\t\t\titems: outcome.items\n\t\t};\n\t} else if (outcome.type === \"done\") {\n\t\tconst output = workflow.output.parse(outcome.output);\n\t\tstate.newEvents.push({\n\t\t\tid: `run_completed:${runId}`,\n\t\t\trunId,\n\t\t\ttype: \"run_completed\",\n\t\t\tdata: { output }\n\t\t});\n\t\tresult = {\n\t\t\tstatus: \"completed\",\n\t\t\toutput\n\t\t};\n\t} else if (outcome.type === \"canceled\" || isRunCanceledError(outcome.error)) {\n\t\tbodyPromise.catch(() => {});\n\t\tstate.newEvents.push({\n\t\t\tid: `run_canceled:${runId}`,\n\t\t\trunId,\n\t\t\ttype: \"run_canceled\"\n\t\t});\n\t\tresult = { status: \"canceled\" };\n\t} else result = {\n\t\tstatus: \"failed\",\n\t\terror: outcome.error,\n\t\tfailedCorrelationId: state.failedCorrelationId\n\t};\n\tfor (const event of state.newEvents) await eventLog.append(event);\n\treturn result;\n}\n//#endregion\n//#region src/prompt-llm.ts\nfunction promptLlm(prompt, opts) {\n\tconst handle = getWorkflowRunHandle();\n\tif (!handle?.llmRunner) throw new Error(\"promptLlm must run inside a workflow with an injected llm executor (executeWorkflow({ runLlm })).\");\n\treturn handle.llmRunner({\n\t\tprompt,\n\t\t...opts\n\t});\n}\n//#endregion\nexport { MemoryEventLog, RunCanceledError, defineWorkflow, deserializeWorkflowError, executeWorkflow, isRunCanceledError, isWorkflow, promptLlm, serializeWorkflowError };\n\n//# sourceMappingURL=index.mjs.map"],"mappings":";;;;;AAMA,IAAI,mBAAmB,cAAc,MAAM;CAC1C,YAAY,OAAO;EAClB,MAAM,QAAQ,gBAAgB,MAAM,iBAAiB,2BAA2B;EAChF,KAAK,OAAO;CACb;AACD;AACA,SAAS,mBAAmB,OAAO;CAClC,OAAO,iBAAiB;AACzB;AAGA,MAAM,YAAYA,IAAAA,EAAE,QAAQ,MAAM,aAAaA,IAAAA,EAAE,SAAS,sBAAsB;;AAEhF,MAAM,qBAAqBA,IAAAA,EAAE,OAAO;CACnC,MAAMA,IAAAA,EAAE,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC;CAC7B,MAAMA,IAAAA,EAAE,OAAO,EAAE,SAAS;CAC1B,aAAaA,IAAAA,EAAE,OAAO,EAAE,SAAS;CACjC,cAAcA,IAAAA,EAAE,OAAO,EAAE,MAAMA,IAAAA,EAAE,KAAK,CAAC,UAAU,cAAc,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,SAAS;CACzF,OAAO;CACP,QAAQ;CACR,KAAKA,IAAAA,EAAE,SAAS;AACjB,CAAC;AACD,MAAM,WAAW,OAAO,IAAI,oBAAoB;;;;;AAKhD,SAAS,WAAW,OAAO;CAC1B,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO;CACxD,IAAI,EAAE,YAAY,UAAU,MAAM,cAAc,MAAM,OAAO;CAC7D,OAAO,mBAAmB,UAAU,KAAK,EAAE;AAC5C;AAGA,SAAS,eAAe,KAAK;CAC5B,MAAM,SAAS,mBAAmB,UAAU,GAAG;CAC/C,IAAI,CAAC,OAAO,SAAS,MAAM,IAA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W;GAChD,MAAM;GACN;EACD,EAAE;EACF;CACD,CAAC;CACD,IAAI,SAAS,OAAO,oBAAoB,SAAS,OAAO;CACxD,IAAI;CACJ,IAAI,QAAQ,SAAS,aAAa;EACjC,YAAY,YAAY,CAAC,CAAC;EAC1B,SAAS;GACR,QAAQ;GACR,OAAO,QAAQ;EAChB;CACD,OAAO,IAAI,QAAQ,SAAS,QAAQ;EACnC,MAAM,SAAS,SAAS,OAAO,MAAM,QAAQ,MAAM;EACnD,MAAM,UAAU,KAAK;GACpB,IAAI,iBAAiB;GACrB;GACA,MAAM;GACN,MAAM,EAAE,OAAO;EAChB,CAAC;EACD,SAAS;GACR,QAAQ;GACR;EACD;CACD,OAAO,IAAI,QAAQ,SAAS,cAAc,mBAAmB,QAAQ,KAAK,GAAG;EAC5E,YAAY,YAAY,CAAC,CAAC;EAC1B,MAAM,UAAU,KAAK;GACpB,IAAI,gBAAgB;GACpB;GACA,MAAM;EACP,CAAC;EACD,SAAS,EAAE,QAAQ,WAAW;CAC/B,OAAO,SAAS;EACf,QAAQ;EACR,OAAO,QAAQ;EACf,qBAAqB,MAAM;CAC5B;CACA,KAAK,MAAM,SAAS,MAAM,WAAW,MAAM,SAAS,OAAO,KAAK;CAChE,OAAO;AACR;AAGA,SAAS,UAAU,QAAQ,MAAM;CAChC,MAAM,SAASS,aAAAA,qBAAqB;CACpC,IAAI,CAAC,QAAQ,WAAW,MAAM,IAAI,MAAM,mGAAmG;CAC3I,OAAO,OAAO,UAAU;EACvB;EACA,GAAG;CACJ,CAAC;AACF"}
1
+ {"version":3,"file":"dist-sGyB6KsC.cjs","names":["z","withSpan","logSystem","captureConsole","normalizeCredentialList","getActionCredentialRequirements","resolveActionCredentials","runWithMcpCredentialContext","executeAction","AsyncLocalStorage","registerWorkflowRunGetter","getRunSignal","getWorkflowRunHandle"],"sources":["../../workflow/dist/index.mjs"],"sourcesContent":["import { z } from \"zod\";\nimport { executeAction, getActionCredentialRequirements, getRunSignal, getWorkflowRunHandle, normalizeCredentialList, registerWorkflowRunGetter, runWithMcpCredentialContext } from \"@keystrokehq/action\";\nimport { captureConsole, logSystem, withSpan } from \"@keystrokehq/tracing\";\nimport { resolveActionCredentials } from \"@keystrokehq/credentials\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n//#region src/run-canceled-error.ts\nvar RunCanceledError = class extends Error {\n\tconstructor(runId) {\n\t\tsuper(runId ? `Workflow run ${runId} was canceled` : \"Workflow run was canceled\");\n\t\tthis.name = \"RunCanceledError\";\n\t}\n};\nfunction isRunCanceledError(error) {\n\treturn error instanceof RunCanceledError;\n}\n//#endregion\n//#region src/workflow-definition.ts\nconst zodSchema = z.custom((v) => v instanceof z.ZodType, \"must be a Zod schema\");\n/** Runtime validation for an unbranded workflow definition. */\nconst workflowCoreSchema = z.object({\n\tslug: z.string().trim().min(1),\n\tname: z.string().optional(),\n\tdescription: z.string().optional(),\n\tsubscription: z.object({ mode: z.enum([\"system\", \"subscribable\"]).optional() }).optional(),\n\tinput: zodSchema,\n\toutput: zodSchema,\n\trun: z.function()\n});\nconst WORKFLOW = Symbol.for(\"keystroke.workflow\");\n/**\n* Validates brand + shape via `workflowCoreSchema` so discovery and guards\n* reject malformed definitions.\n*/\nfunction isWorkflow(value) {\n\tif (typeof value !== \"object\" || value === null) return false;\n\tif (!(WORKFLOW in value) || value[WORKFLOW] !== true) return false;\n\treturn workflowCoreSchema.safeParse(value).success;\n}\n//#endregion\n//#region src/define-workflow.ts\nfunction defineWorkflow(def) {\n\tconst result = workflowCoreSchema.safeParse(def);\n\tif (!result.success) throw new Error(`Invalid workflow definition: ${formatIssues(result.error.issues)}`);\n\treturn {\n\t\t...result.data,\n\t\t[WORKFLOW]: true\n\t};\n}\nfunction formatIssues(issues) {\n\treturn issues.map((issue) => {\n\t\treturn `${issue.path.length > 0 ? `${issue.path.join(\".\")}: ` : \"\"}${issue.message}`;\n\t}).join(\"; \");\n}\n//#endregion\n//#region src/replay/error.ts\nfunction serializeWorkflowError(error) {\n\tif (error instanceof Error) return {\n\t\tname: error.name,\n\t\tmessage: error.message\n\t};\n\treturn { message: String(error) };\n}\n/** Rebuild an Error from a recorded error so replay re-raises the same failure. */\nfunction deserializeWorkflowError(data) {\n\tconst serialized = data;\n\tconst error = new Error(serialized?.message ?? \"Workflow step failed\");\n\tif (serialized?.name) error.name = serialized.name;\n\treturn error;\n}\n//#endregion\n//#region src/replay/duration.ts\nconst UNIT_MS = {\n\tms: 1,\n\ts: 1e3,\n\tm: 6e4,\n\th: 36e5,\n\td: 864e5\n};\n/** Resolve a sleep duration to an absolute resume time. */\nfunction resolveResumeAt(duration, now = /* @__PURE__ */ new Date()) {\n\tif (duration instanceof Date) return duration;\n\tif (typeof duration === \"number\") return new Date(now.getTime() + Math.max(0, duration));\n\treturn new Date(now.getTime() + parseDurationToMs(duration));\n}\nfunction parseDurationToMs(value) {\n\tconst match = /^(\\d+(?:\\.\\d+)?)\\s*(ms|s|m|h|d)$/.exec(value.trim());\n\tif (!match) throw new Error(`Invalid sleep duration \"${value}\". Use a number of ms, a Date, or a string like \"5s\", \"10m\", \"1h\".`);\n\tconst amount = Number(match[1]);\n\tconst unit = match[2];\n\treturn Math.round(amount * UNIT_MS[unit]);\n}\n//#endregion\n//#region src/replay/events-consumer.ts\n/** Indexes replay events by correlationId for O(1) cache-hit checks during replay. */\nvar EventsConsumer = class {\n\tbyCorrelationId = /* @__PURE__ */ new Map();\n\tconstructor(events) {\n\t\tfor (const event of events) {\n\t\t\tif (!event.correlationId) continue;\n\t\t\tconst list = this.byCorrelationId.get(event.correlationId);\n\t\t\tif (list) list.push(event);\n\t\t\telse this.byCorrelationId.set(event.correlationId, [event]);\n\t\t}\n\t}\n\tevents(correlationId) {\n\t\treturn this.byCorrelationId.get(correlationId) ?? [];\n\t}\n\thasEventType(correlationId, type) {\n\t\treturn this.events(correlationId).some((event) => event.type === type);\n\t}\n\t/**\n\t* Cache lookup for a step. Returns the recorded output on a `step_completed`,\n\t* re-raises the recorded error on a terminal `step_failed` (so a permanently\n\t* failed step is not re-executed), and otherwise reports a miss — including\n\t* when only `step_retrying` events exist (the step re-runs on the next pass).\n\t*/\n\tgetStepResult(correlationId) {\n\t\tconst events = this.events(correlationId);\n\t\tconst failed = events.find((event) => event.type === \"step_failed\");\n\t\tif (failed) throw deserializeWorkflowError(failed.data);\n\t\tconst completed = events.find((event) => event.type === \"step_completed\");\n\t\tif (completed) return {\n\t\t\tcompleted: true,\n\t\t\tresult: completed.data\n\t\t};\n\t\treturn { completed: false };\n\t}\n\t/** Number of prior `step_retrying` events recorded for a step (= failed attempts so far). */\n\tcountRetrying(correlationId) {\n\t\treturn this.events(correlationId).filter((event) => event.type === \"step_retrying\").length;\n\t}\n\tisSleepCompleted(correlationId) {\n\t\treturn this.hasEventType(correlationId, \"sleep_completed\");\n\t}\n\t/** Returns the persisted resumeAt for a scheduled-but-not-completed sleep, if any. */\n\tgetSleepResumeAt(correlationId) {\n\t\tconst scheduled = this.events(correlationId).find((event) => event.type === \"sleep_scheduled\");\n\t\tif (!scheduled) return;\n\t\tconst data = scheduled.data;\n\t\treturn data?.resumeAt ? new Date(data.resumeAt) : void 0;\n\t}\n\tgetHookToken(correlationId) {\n\t\treturn (this.events(correlationId).find((event) => event.type === \"hook_created\")?.data)?.token;\n\t}\n\tgetHookResult(correlationId) {\n\t\tconst resumed = this.events(correlationId).find((event) => event.type === \"hook_resumed\");\n\t\tif (!resumed) return { resolved: false };\n\t\treturn {\n\t\t\tresolved: true,\n\t\t\tpayload: resumed.data?.payload\n\t\t};\n\t}\n};\n//#endregion\n//#region src/replay/suspension.ts\n/** A promise that never settles — returned by a suspending primitive so the body parks. */\nfunction createPendingPromise() {\n\treturn new Promise(() => {});\n}\n/**\n* Collects pending items requested within a single tick and resolves once, so\n* parallel suspensions (e.g. Promise.all of two sleeps) batch into one suspension.\n*/\nvar SuspensionCoordinator = class {\n\titems = /* @__PURE__ */ new Map();\n\tscheduled = false;\n\tresolve;\n\tpromise;\n\tconstructor() {\n\t\tthis.promise = new Promise((resolve) => {\n\t\t\tthis.resolve = resolve;\n\t\t});\n\t}\n\trequest(item) {\n\t\tthis.items.set(item.correlationId, item);\n\t\tif (!this.scheduled) {\n\t\t\tthis.scheduled = true;\n\t\t\tqueueMicrotask(() => {\n\t\t\t\tthis.resolve([...this.items.values()]);\n\t\t\t});\n\t\t}\n\t}\n\twaitForSuspension() {\n\t\treturn this.promise;\n\t}\n};\n//#endregion\n//#region src/replay/replay-context.ts\nfunction createReplayState(params) {\n\treturn {\n\t\trunId: params.runId,\n\t\tconsumer: params.consumer,\n\t\tcoordinator: params.coordinator,\n\t\teventLog: params.eventLog,\n\t\tnewEvents: [],\n\t\tnow: params.now ?? /* @__PURE__ */ new Date(),\n\t\thookBaseUrl: params.hookBaseUrl,\n\t\tsleepCounter: 0,\n\t\thookCounter: 0,\n\t\tstepOccurrences: /* @__PURE__ */ new Map(),\n\t\tstepCorrelationIds: /* @__PURE__ */ new Set()\n\t};\n}\n/**\n* Allocate the correlation id for a step. An explicit `.stepId(x)` maps to\n* `step:x` (and must be unique within a run); otherwise the key is\n* `step:<actionKey>#<occurrence>` so that two calls to the same action get\n* distinct, replay-stable ids and inserting an unrelated call never shifts the\n* ids of later calls (unlike a single global ordinal).\n*/\nfunction nextStepCorrelationId(state, actionKey, explicitId) {\n\tif (explicitId !== void 0) {\n\t\tconst correlationId = `step:${explicitId}`;\n\t\tif (state.stepCorrelationIds.has(correlationId)) throw new Error(`Duplicate step id \"${explicitId}\" in workflow run ${state.runId}`);\n\t\tstate.stepCorrelationIds.add(correlationId);\n\t\treturn correlationId;\n\t}\n\tconst occurrence = state.stepOccurrences.get(actionKey) ?? 0;\n\tstate.stepOccurrences.set(actionKey, occurrence + 1);\n\tconst correlationId = `step:${actionKey}#${occurrence}`;\n\tstate.stepCorrelationIds.add(correlationId);\n\treturn correlationId;\n}\nfunction createSleep(state) {\n\treturn function sleep(duration) {\n\t\tconst correlationId = `sleep#${state.sleepCounter++}`;\n\t\tif (state.consumer.isSleepCompleted(correlationId)) return Promise.resolve();\n\t\tconst scheduledResumeAt = state.consumer.getSleepResumeAt(correlationId);\n\t\tconst resumeAt = scheduledResumeAt ?? resolveResumeAt(duration, state.now);\n\t\tif (scheduledResumeAt && resumeAt.getTime() <= state.now.getTime()) {\n\t\t\tstate.newEvents.push({\n\t\t\t\tid: `sleep_completed:${state.runId}:${correlationId}`,\n\t\t\t\trunId: state.runId,\n\t\t\t\ttype: \"sleep_completed\",\n\t\t\t\tcorrelationId\n\t\t\t});\n\t\t\treturn Promise.resolve();\n\t\t}\n\t\tif (!scheduledResumeAt) state.newEvents.push({\n\t\t\tid: `sleep_scheduled:${state.runId}:${correlationId}`,\n\t\t\trunId: state.runId,\n\t\t\ttype: \"sleep_scheduled\",\n\t\t\tcorrelationId,\n\t\t\tdata: { resumeAt: resumeAt.toISOString() }\n\t\t});\n\t\tstate.coordinator.request({\n\t\t\tkind: \"sleep\",\n\t\t\tcorrelationId,\n\t\t\tresumeAt\n\t\t});\n\t\treturn createPendingPromise();\n\t};\n}\nfunction createHook(state) {\n\treturn function hook(options) {\n\t\tconst correlationId = `hook#${state.hookCounter++}`;\n\t\tconst token = options?.token ?? state.consumer.getHookToken(correlationId) ?? `hook_${crypto.randomUUID()}`;\n\t\treturn {\n\t\t\ttoken,\n\t\t\tresumeUrl: state.hookBaseUrl ? `${state.hookBaseUrl}/hooks/${token}/resume` : `/hooks/${token}/resume`,\n\t\t\tthen(onFulfilled, onRejected) {\n\t\t\t\tconst result = state.consumer.getHookResult(correlationId);\n\t\t\t\tif (result.resolved) {\n\t\t\t\t\tconst payload = options?.schema ? options.schema.parse(result.payload) : result.payload;\n\t\t\t\t\treturn Promise.resolve(payload).then(onFulfilled, onRejected);\n\t\t\t\t}\n\t\t\t\tif (!state.consumer.hasEventType(correlationId, \"hook_created\")) state.newEvents.push({\n\t\t\t\t\tid: `hook_created:${state.runId}:${correlationId}`,\n\t\t\t\t\trunId: state.runId,\n\t\t\t\t\ttype: \"hook_created\",\n\t\t\t\t\tcorrelationId,\n\t\t\t\t\tdata: { token }\n\t\t\t\t});\n\t\t\t\tstate.coordinator.request({\n\t\t\t\t\tkind: \"hook\",\n\t\t\t\t\tcorrelationId,\n\t\t\t\t\ttoken\n\t\t\t\t});\n\t\t\t\treturn createPendingPromise().then(onFulfilled, onRejected);\n\t\t\t}\n\t\t};\n\t};\n}\n//#endregion\n//#region src/run-durable-step.ts\n/**\n* Shared durable-step shell: resolve a stable `correlation_id`, short-circuit\n* from the event log on a cache hit, otherwise execute and append\n* `step_completed` immediately (per-step crash durability). A thrown step\n* appends `step_retrying` (non-fatal, re-run on the next attempt) and\n* rethrows; the terminal `step_failed` is written by the job handler once the\n* queue exhausts retries.\n*/\nasync function runDurableStep(state, options) {\n\tconst { runId, consumer, eventLog } = state;\n\tgetRunSignal().throwIfAborted();\n\tconst correlationId = nextStepCorrelationId(state, options.key, options.id);\n\tconst cached = consumer.getStepResult(correlationId);\n\tconst metadata = {\n\t\trunId,\n\t\t[options.metadataKey]: options.key,\n\t\tcorrelationId\n\t};\n\tif (cached.completed) {\n\t\tawait withSpan({\n\t\t\tkind: options.kind,\n\t\t\tname: options.key,\n\t\t\trefId: `${runId}:${correlationId}`,\n\t\t\tmetadata: {\n\t\t\t\t...metadata,\n\t\t\t\treplayed: true\n\t\t\t}\n\t\t}, async () => {\n\t\t\tawait logSystem(\"info\", options.replayMessage, metadata);\n\t\t});\n\t\treturn options.parseCached ? options.parseCached(cached.result) : cached.result;\n\t}\n\treturn withSpan({\n\t\tkind: options.kind,\n\t\tname: options.key,\n\t\trefId: `${runId}:${correlationId}`,\n\t\tmetadata\n\t}, async () => captureConsole(async () => {\n\t\ttry {\n\t\t\tconst result = await options.execute(correlationId);\n\t\t\tawait eventLog.append({\n\t\t\t\tid: `step_completed:${runId}:${correlationId}`,\n\t\t\t\trunId,\n\t\t\t\ttype: \"step_completed\",\n\t\t\t\tcorrelationId,\n\t\t\t\tdata: result\n\t\t\t});\n\t\t\treturn result;\n\t\t} catch (error) {\n\t\t\tconst attempt = consumer.countRetrying(correlationId);\n\t\t\tawait eventLog.append({\n\t\t\t\tid: `step_retrying:${runId}:${correlationId}:${attempt}`,\n\t\t\t\trunId,\n\t\t\t\ttype: \"step_retrying\",\n\t\t\t\tcorrelationId,\n\t\t\t\tdata: serializeWorkflowError(error)\n\t\t\t});\n\t\t\tstate.failedCorrelationId = correlationId;\n\t\t\tthrow error;\n\t\t}\n\t}));\n}\n//#endregion\n//#region src/create-action-runner.ts\nfunction withCredentialScopeOverride(requirements, scope) {\n\tif (!requirements || !scope) return requirements;\n\treturn normalizeCredentialList(requirements).map((requirement) => ({\n\t\t...requirement,\n\t\tscope\n\t}));\n}\n/** Builds the per-run action runner; durability lives in {@link runDurableStep}. */\nfunction createActionRunner(state, options = {}) {\n\treturn (action, input, runOptions) => runDurableStep(state, {\n\t\tkind: \"action\",\n\t\tkey: action.slug,\n\t\tid: runOptions?.id,\n\t\tmetadataKey: \"actionKey\",\n\t\treplayMessage: \"action replayed from checkpoint\",\n\t\tparseCached: (cached) => action.output.parse(cached),\n\t\texecute: async (correlationId) => {\n\t\t\tconst requirements = withCredentialScopeOverride(getActionCredentialRequirements(action), runOptions?.credentialScope);\n\t\t\tconst credentials = requirements?.length ? await resolveActionCredentials(requirements, {\n\t\t\t\tresolveCredentials: options.resolveCredentials,\n\t\t\t\tcontext: options.credentialContext,\n\t\t\t\toauthAdapter: options.oauthAdapter,\n\t\t\t\tconsumer: {\n\t\t\t\t\tkind: \"action\",\n\t\t\t\t\tname: action.slug,\n\t\t\t\t\tid: correlationId\n\t\t\t\t}\n\t\t\t}) : {};\n\t\t\treturn runWithMcpCredentialContext({\n\t\t\t\t...options.mcpCredentialContext,\n\t\t\t\tconsumerId: correlationId\n\t\t\t}, () => executeAction(action, input, credentials));\n\t\t}\n\t});\n}\n//#endregion\n//#region src/create-agent-step-runner.ts\n/**\n* Builds the per-run agent runner: each `agent.prompt()` in a workflow body\n* becomes a durable step keyed `step:<agentKey>#<occurrence>` (same scheme as\n* actions). The actual prompt execution is delegated to `runAgent`, supplied\n* by the host (server) via `executeWorkflow({ runAgent })`.\n*/\nfunction createAgentStepRunner(state, runAgent) {\n\treturn (agent, input, options) => {\n\t\tconst slug = agent.slug;\n\t\treturn runDurableStep(state, {\n\t\t\tkind: \"agent_session\",\n\t\t\tkey: slug,\n\t\t\tid: options?.id,\n\t\t\tmetadataKey: \"agentKey\",\n\t\t\treplayMessage: \"agent step replayed from checkpoint\",\n\t\t\texecute: (_correlationId) => runAgent(agent, input, options?.runPrompt)\n\t\t});\n\t};\n}\n//#endregion\n//#region src/create-llm-step-runner.ts\n/**\n* Builds the per-run LLM runner: each `promptLlm()` in a workflow body becomes a\n* durable step keyed `step:promptLlm#<occurrence>`. The actual LLM call is\n* delegated to `runLlm`, supplied by the host (server) via `executeWorkflow({ runLlm })`.\n*/\nfunction createLlmStepRunner(state, runLlm) {\n\treturn (opts) => runDurableStep(state, {\n\t\tkind: \"llm\",\n\t\tkey: \"promptLlm\",\n\t\tid: opts.stepId,\n\t\tmetadataKey: \"llmKey\",\n\t\treplayMessage: \"llm step replayed from checkpoint\",\n\t\tparseCached: (cached) => opts.outputSchema ? opts.outputSchema.parse(cached) : cached,\n\t\texecute: (_correlationId) => runLlm(opts)\n\t});\n}\n//#endregion\n//#region src/run-context.ts\nconst storage = new AsyncLocalStorage();\nregisterWorkflowRunGetter(() => {\n\tconst store = storage.getStore();\n\tif (!store) return;\n\treturn {\n\t\tactionRunner: store.actionRunner,\n\t\tagentRunner: store.agentRunner,\n\t\tllmRunner: store.llmRunner\n\t};\n});\nfunction runWithWorkflowContext(store, fn) {\n\treturn storage.run(store, fn);\n}\n//#endregion\n//#region src/replay/memory-event-log.ts\n/** In-memory durable log for inline execution and tests. */\nvar MemoryEventLog = class {\n\tevents = [];\n\tids = /* @__PURE__ */ new Set();\n\tasync append(event) {\n\t\tconst id = event.id ?? crypto.randomUUID();\n\t\tif (this.ids.has(id)) return false;\n\t\tthis.ids.add(id);\n\t\tthis.events.push({\n\t\t\tid,\n\t\t\trunId: event.runId,\n\t\t\tseq: this.events.length,\n\t\t\ttype: event.type,\n\t\t\tcorrelationId: event.correlationId ?? null,\n\t\t\tdata: event.data ?? null\n\t\t});\n\t\treturn true;\n\t}\n\tasync listReplay(runId) {\n\t\treturn this.events.filter((event) => event.runId === runId).map((event) => ({ ...event }));\n\t}\n};\n//#endregion\n//#region src/execute-workflow.ts\n/**\n* The single way to run a workflow: replay its event log from the top, execute\n* un-cached primitives, and either complete/fail or suspend at the first\n* un-satisfied sleep/hook. New events (sleep_scheduled/sleep_completed/\n* hook_created/run_completed/run_failed) are flushed before returning.\n*\n* Durability comes entirely from the log — a suspended run resumes by calling\n* this again with the same `runId` and event log once the sleep is due or the\n* hook is resumed.\n*/\nasync function executeWorkflow(workflow, input, options = {}) {\n\tconst runId = options.runId ?? crypto.randomUUID();\n\tconst eventLog = options.eventLog ?? new MemoryEventLog();\n\tconst signal = getRunSignal();\n\tconst consumer = new EventsConsumer(await eventLog.listReplay(runId));\n\tconst coordinator = new SuspensionCoordinator();\n\tconst state = createReplayState({\n\t\trunId,\n\t\tconsumer,\n\t\tcoordinator,\n\t\teventLog,\n\t\thookBaseUrl: options.hookBaseUrl,\n\t\tnow: options.now\n\t});\n\tconst actionRunner = createActionRunner(state, {\n\t\tresolveCredentials: options.resolveCredentials,\n\t\tcredentialContext: options.credentialContext,\n\t\toauthAdapter: options.oauthAdapter,\n\t\tmcpCredentialContext: { assignmentTarget: {\n\t\t\ttype: \"workflow\",\n\t\t\tkey: workflow.slug\n\t\t} }\n\t});\n\tconst ctx = {\n\t\trunId,\n\t\tsleep: createSleep(state),\n\t\thook: createHook(state),\n\t\t...options.context\n\t};\n\tconst agentRunner = options.runAgent ? createAgentStepRunner(state, options.runAgent) : void 0;\n\tconst llmRunner = options.runLlm ? createLlmStepRunner(state, options.runLlm) : void 0;\n\tconst validatedInput = workflow.input.parse(input);\n\tconst bodyPromise = runWithWorkflowContext({\n\t\tactionRunner,\n\t\tagentRunner,\n\t\tllmRunner,\n\t\trunId\n\t}, () => captureConsole(async () => workflow.run(validatedInput, ctx)));\n\tlet onAbort;\n\tconst waitForAbort = signal.aborted ? Promise.resolve({ type: \"canceled\" }) : new Promise((resolve) => {\n\t\tonAbort = () => resolve({ type: \"canceled\" });\n\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t});\n\tconst outcome = await Promise.race([\n\t\tbodyPromise.then((output) => ({\n\t\t\ttype: \"done\",\n\t\t\toutput\n\t\t}), (error) => ({\n\t\t\ttype: \"error\",\n\t\t\terror\n\t\t})),\n\t\tcoordinator.waitForSuspension().then((items) => ({\n\t\t\ttype: \"suspended\",\n\t\t\titems\n\t\t})),\n\t\twaitForAbort\n\t]);\n\tif (onAbort) signal.removeEventListener(\"abort\", onAbort);\n\tlet result;\n\tif (outcome.type === \"suspended\") {\n\t\tbodyPromise.catch(() => {});\n\t\tresult = {\n\t\t\tstatus: \"suspended\",\n\t\t\titems: outcome.items\n\t\t};\n\t} else if (outcome.type === \"done\") {\n\t\tconst output = workflow.output.parse(outcome.output);\n\t\tstate.newEvents.push({\n\t\t\tid: `run_completed:${runId}`,\n\t\t\trunId,\n\t\t\ttype: \"run_completed\",\n\t\t\tdata: { output }\n\t\t});\n\t\tresult = {\n\t\t\tstatus: \"completed\",\n\t\t\toutput\n\t\t};\n\t} else if (outcome.type === \"canceled\" || isRunCanceledError(outcome.error)) {\n\t\tbodyPromise.catch(() => {});\n\t\tstate.newEvents.push({\n\t\t\tid: `run_canceled:${runId}`,\n\t\t\trunId,\n\t\t\ttype: \"run_canceled\"\n\t\t});\n\t\tresult = { status: \"canceled\" };\n\t} else result = {\n\t\tstatus: \"failed\",\n\t\terror: outcome.error,\n\t\tfailedCorrelationId: state.failedCorrelationId\n\t};\n\tfor (const event of state.newEvents) await eventLog.append(event);\n\treturn result;\n}\n//#endregion\n//#region src/prompt-llm.ts\nfunction promptLlm(prompt, opts) {\n\tconst handle = getWorkflowRunHandle();\n\tif (!handle?.llmRunner) throw new Error(\"promptLlm must run inside a workflow with an injected llm executor (executeWorkflow({ runLlm })).\");\n\treturn handle.llmRunner({\n\t\tprompt,\n\t\t...opts\n\t});\n}\n//#endregion\nexport { MemoryEventLog, RunCanceledError, defineWorkflow, deserializeWorkflowError, executeWorkflow, isRunCanceledError, isWorkflow, promptLlm, serializeWorkflowError };\n\n//# sourceMappingURL=index.mjs.map"],"mappings":";;;;;AAMA,IAAI,mBAAmB,cAAc,MAAM;CAC1C,YAAY,OAAO;EAClB,MAAM,QAAQ,gBAAgB,MAAM,iBAAiB,2BAA2B;EAChF,KAAK,OAAO;CACb;AACD;AACA,SAAS,mBAAmB,OAAO;CAClC,OAAO,iBAAiB;AACzB;AAGA,MAAM,YAAYA,IAAAA,EAAE,QAAQ,MAAM,aAAaA,IAAAA,EAAE,SAAS,sBAAsB;;AAEhF,MAAM,qBAAqBA,IAAAA,EAAE,OAAO;CACnC,MAAMA,IAAAA,EAAE,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC;CAC7B,MAAMA,IAAAA,EAAE,OAAO,EAAE,SAAS;CAC1B,aAAaA,IAAAA,EAAE,OAAO,EAAE,SAAS;CACjC,cAAcA,IAAAA,EAAE,OAAO,EAAE,MAAMA,IAAAA,EAAE,KAAK,CAAC,UAAU,cAAc,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,SAAS;CACzF,OAAO;CACP,QAAQ;CACR,KAAKA,IAAAA,EAAE,SAAS;AACjB,CAAC;AACD,MAAM,WAAW,OAAO,IAAI,oBAAoB;;;;;AAKhD,SAAS,WAAW,OAAO;CAC1B,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO;CACxD,IAAI,EAAE,YAAY,UAAU,MAAM,cAAc,MAAM,OAAO;CAC7D,OAAO,mBAAmB,UAAU,KAAK,EAAE;AAC5C;AAGA,SAAS,eAAe,KAAK;CAC5B,MAAM,SAAS,mBAAmB,UAAU,G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EACD,EAAE;EACF,YAAY,kBAAkB,EAAE,MAAM,WAAW;GAChD,MAAM;GACN;EACD,EAAE;EACF;CACD,CAAC;CACD,IAAI,SAAS,OAAO,oBAAoB,SAAS,OAAO;CACxD,IAAI;CACJ,IAAI,QAAQ,SAAS,aAAa;EACjC,YAAY,YAAY,CAAC,CAAC;EAC1B,SAAS;GACR,QAAQ;GACR,OAAO,QAAQ;EAChB;CACD,OAAO,IAAI,QAAQ,SAAS,QAAQ;EACnC,MAAM,SAAS,SAAS,OAAO,MAAM,QAAQ,MAAM;EACnD,MAAM,UAAU,KAAK;GACpB,IAAI,iBAAiB;GACrB;GACA,MAAM;GACN,MAAM,EAAE,OAAO;EAChB,CAAC;EACD,SAAS;GACR,QAAQ;GACR;EACD;CACD,OAAO,IAAI,QAAQ,SAAS,cAAc,mBAAmB,QAAQ,KAAK,GAAG;EAC5E,YAAY,YAAY,CAAC,CAAC;EAC1B,MAAM,UAAU,KAAK;GACpB,IAAI,gBAAgB;GACpB;GACA,MAAM;EACP,CAAC;EACD,SAAS,EAAE,QAAQ,WAAW;CAC/B,OAAO,SAAS;EACf,QAAQ;EACR,OAAO,QAAQ;EACf,qBAAqB,MAAM;CAC5B;CACA,KAAK,MAAM,SAAS,MAAM,WAAW,MAAM,SAAS,OAAO,KAAK;CAChE,OAAO;AACR;AAGA,SAAS,UAAU,QAAQ,MAAM;CAChC,MAAM,SAASS,aAAAA,qBAAqB;CACpC,IAAI,CAAC,QAAQ,WAAW,MAAM,IAAI,MAAM,mGAAmG;CAC3I,OAAO,OAAO,UAAU;EACvB;EACA,GAAG;CACJ,CAAC;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"index-BTz2OMAM.d.cts","names":["_$drizzle_orm_node_postgres0","Pool","MigrationConfig","MigrationMeta","TracingSink","AgentTriggerType","CredentialAuthKind","CredentialScopeType","HistoryAgentSessionDetail","HistoryRun","HistoryRunKind","HistoryRunStatus","HistoryWorkflowRunDetail","RunSourceKind","WorkflowEventType","DEFAULT_DATABASE_URL","runWithTenantScope","T","Promise","tenantId","fn","getServerTenantScopeId","DEFAULT_PROJECT_ID","runWithProjectScope","projectId","getBoundProjectScopeId","getProjectScopeId","PostgresConnectionConfig","host","port","database","user","password","ssl","qualifyConnectionUser","NodeJS","ProcessEnv","env","buildPostgresUrl","config","parsePostgresUrl","url","resolvePostgresConfigFromEnv","resolvePostgresUrlFromEnv","resolveProjectDatabaseUrlFromEnv","resolveDatabaseUrlFromEnv","closeDatabase","StoredRunSourceKind$1","agentSessions","_$drizzle_orm_pg_core0","PgColumn","Date","PgTableWithColumns","name","schema","columns","id","tableName","dataType","columnType","data","driverParam","notNull","hasDefault","isPrimaryKey","isAutoincrement","hasRuntimeDefault","enumValues","baseColumn","identity","generated","agentId","sourceKind","$type","sourceId","parentSpanId","ranByUserId","title","canceledAt","totalDurationMs","liveMessage","createdAt","updatedAt","deletedAt","dialect","UsageRunKind","TriggerScheduleKind","triggerSchedules","attachmentSlug","kind","schedule","nextRunAt","enabled","TriggerRunType","triggerRuns","attachmentId","sourcePath","triggerType","payload","triggeredAt","WorkflowRunStatus","WorkflowRunTrigger","StoredRunSourceKind","workflowRuns","workflowSlug","subscriptionId","triggerRunId","parentWorkflowRunId","status","trigger","startedAt","finishedAt","input","output","error","WorkflowHookStatus","workflowHooks","hookId","runId","token","correlationId","resumedAt","CredentialAssignmentTargetType","credentialAssignments","targetType","targetKey","consumerId","credentialSlug","instanceId","JobKind","JobStatus","JobTrigger","TraceSpanKind","TraceSpanStatus","traceSpans","traceId","refId","metadata","TraceLogLevel","TraceLogSource","traceLogs","spanId","seq","level","message","source","agents","slug","description","route","moduleFile","model","systemPrompt","toolCount","credentialCount","appSlugs","registeredAt","agentEvents","sessionId","eventType","StoredTriggerSourceSlugFields","key","StoredTriggerSource","Record","endpoint","requestSchema","filterSchema","code","storedTriggerSourceSlug","normalizeStoredTriggerSource","StoredTriggerTargetKind","StoredTriggerOrigin","StoredTriggerLifecycleStatus","StoredTriggerLifecycle","maxExecutions","until","executionCount","triggerAttachments","targetKind","agentSlug","origin","prompt","lifecycle","createdBySessionId","workflowEvents","type","credentialInstances","appSlug","scopeType","scopeId","label","isDefault","authKind","ciphertext","connectionId","sharedConnectionId","SlackGatewayMode","StoredGatewaySource","mode","credentialKey","channelIds","subscribeOnMention","channelName","channelKind","gatewayAttachments","platform","teamId","channelId","gatewayAttachmentKeyForChannel","gatewayThreadSessions","threadId","skills","workflows","subscribable","workflowSubscriptions","userId","resourceActivityKinds","ResourceActivityKind","resourceActivity","resourceKind","resourceId","lastOpenedAt","AgentRow","$inferSelect","listActiveAgents","projectIds","options","selectAgentBySlug","selectActiveAgentsByIds","ids","selectActiveAgentById","resolveAgentProjectId","AgentSessionRow","AgentSessionSourceFilter","selectAgentSessionById","addAgentSessionDuration","deltaMs","clearAgentSessionCancellation","AgentEventRow","TriggerAttachmentRow","getTriggerAttachmentBySlug","listActiveTriggerAttachments","selectWebhookTriggerAttachments","selectEphemeralTriggerAttachmentsByAgentSlug","selectTriggerAttachmentsByAgentSlug","selectEphemeralTriggerAttachments","TriggerScheduleRow","UpsertTriggerScheduleValues","selectTriggerScheduleBySlug","upsertTriggerSchedule","values","disableAllTriggerSchedules","now","disableTriggerSchedulesNotInSlugs","attachmentSlugs","listEnabledTriggerSchedules","claimDueTriggerSchedules","resolveNextRunAt","limit","claimDueTriggerSchedulesForOrg","listTriggerSchedulesBySlugs","triggerRunSummaryFromRow","TriggerRunRow","WorkflowRunRow","row","workflowRun","agentSession","triggerRunRecordFromRow","WorkflowEventRow","AppendWorkflowEventValues","listStepCompletedEvents","TraceLogRow","TraceSpanRow","createDatabaseTracingSink","flushNow","TraceTriggerSummary","TraceGatewaySummary","gatewayAttachmentId","gatewayAttachmentKey","TraceResponse","gateway","spans","logs","getTraceForWorkflowRun","workflowRunId","getTraceForTriggerRun","getTraceForAgentSession","workflowRunSummaryFromRow","workflowRunRecordFromRow","triggerRunDetailFromRow","workflowStepRunFromEvent","actionKey","completedAt","traceResponseToJson","trace","selectWorkflowRunById","resolveWorkflowRunProjectId","listWorkflowRunsByWorkflowSlug","selectWorkflowRunForWorkflow","listWorkflowRunsPaginated","ReturnType","cursor","items","nextCursor","WorkflowHookRow","InsertWorkflowHookValues","requeueExpiredLeases","GatewayAttachmentRow","GatewayChannelConflictError","Error","ownerProjectId","constructor","getActiveOrgGatewayAttachmentByChannel","getActiveOrgGatewayAttachmentByTeamAndChannel","getActiveGatewayAttachmentByChannel","listActiveGatewayAttachments","ActiveGatewayBinding","listActiveOrgGatewayBindingsByPlatform","listActiveGatewayAttachmentsByAgentSlug","softDeleteGatewayAttachmentsForAgentPlatformTeam","listActiveGatewayAttachmentsByPlatform","softDeleteGatewayAttachmentByChannel","upsertGatewayAttachmentByChannel","getGatewayAttachmentBySlug","GatewayThreadSessionRow","selectGatewayThreadSessionByThreadId","WorkflowRow","listActiveWorkflows","selectActiveWorkflowBySlug","selectActiveWorkflowsByIds","selectActiveWorkflowById","SkillRow","listActiveSkills","selectActiveSkillsByIds","selectActiveSkillById","WorkflowSubscriptionRow","InsertWorkflowSubscriptionValues","UpdateWorkflowSubscriptionValues","selectWorkflowSubscriptionById","selectWorkflowSubscriptionByWorkflowAndUser","listWorkflowSubscriptionsByWorkflowSlug","listEnabledWorkflowSubscriptionsByWorkflowSlug","insertWorkflowSubscription","updateWorkflowSubscriptionById","deleteWorkflowSubscriptionById","ResourceActivityRow","TouchResourceActivityInput","touchResourceActivity","listRecentResourceActivity","selectWorkflowLastRunAtByIds","Map","workflowIds","selectAgentLastRunAtByIds","agentIds","ProjectResourceCounts","agentCount","workflowCount","skillCount","selectProjectResourceCounts","ListHistoryRunsOptions","HistoryRunCore","Omit","buildHistoryWorkflowRunDetail","buildHistoryAgentSessionDetail","listHistoryRuns","findHistoryRunCore","CredentialInstanceRow","InsertCredentialInstanceValues","listAllCredentialInstances","listCredentialInstancesByConnectionId","selectCredentialInstanceById","listCredentialInstancesByScope","selectCredentialInstancesForScope","upsertCredentialInstance","deleteCredentialInstanceById","clearCredentialInstanceDefaults","exceptId","CredentialAssignmentRow","UpsertCredentialAssignmentValues","listCredentialAssignmentsByTarget","selectCredentialAssignmentById","upsertCredentialAssignment","deleteCredentialAssignmentById","listRecentWorkflowStepConsumers","runLimit","listDistinctAssignmentConsumerIds","createPgDb","NodePgDatabase","pool","usageRecords","runKind","quantity","unit","amount","jobs","targetId","scheduledAt","attempt","maxAttempts","leasedBy","leaseExpiresAt","$client","Database","DatabaseDialect","PgPool","PgDatabase","SqliteDatabase","AppDatabase","DatabaseHandle","db","searchPath","close","InitDatabaseOptions","migrate","migrationsFolder","max","closeAllProjectDatabasePools","isDatabaseInitialized","getDatabaseHandle","initDatabase","RunWithProjectDatabaseOptions","runWithProjectDatabase","ConnectionOptions","PgConnectionOptions","SqliteConnectionOptions","createPgConnection","PostgresCancelHandler","PostgresCancelChannel","publishCancel","subscribeCancel","handler","createPostgresCancelChannel","connectionString","channel","createSqliteConnection","createConnection","resolveSqlitePath","inferDialect","override","adaptPgMigrationsForSearchPath","migrations","loadMigrations","embedded","migratePgDatabase","resolveMigrationsFolder","runMigrations","handle","resolveMigrationsSchema","primarySearchPathSchema","resolveSearchPath","appendSearchPathToUrl","cancelWorkflowRun","cancelAgentSession","RunSource","runSource","sourceFromSpan","span","resolveRunSourceFromTraceContext","DiscoveredAgentRecord","AgentRegistryEntry","MESSAGE_EVENT_TYPE","syncAgentRegistry","records","getAgentByRoute","AgentSession","createSession","getSession","touchSession","setSessionTitle","nextSeq","appendEvent","listMessageEvents","countMessageEvents","AgentEventRecord","listSessionEvents","setSessionLiveMessage","clearLiveMessage","getSessionLiveMessage","LlmUsageRecordInput","recordLlmUsageFromAssistantMessage","usage","failAgentSession","AgentSessionStatus$1","agentSessionSummaryFromParts","messageCount","ranByUserName","gatewayPlatform","agentSessionRecordFromParts","gatewaySessionDetailFromParts","agentEventFromRow","AgentSessionStatus","AgentSessionSource","listAgentSessionsPaginated","resolveUserName","AgentSessionDetailInclude","buildAgentSessionDetail","include","session","messages","events","buildAgentSessionChatState","sinceSeq","live","DiscoveredSkillRecord","SkillRegistryEntry","syncSkillRegistry","TriggerAttachmentRegistryEntry","DiscoveredTriggerAttachmentRecord","syncTriggerAttachmentRegistry","CreateAgentAttachmentExecutionInput","createAgentAttachmentExecution","getTriggerRunForAgentSession","EPHEMERAL_TRIGGER_MODULE_FILE","UpsertEphemeralTriggerInput","Extract","upsertEphemeralTrigger","deleteEphemeralTrigger","isEphemeralTriggerActive","recordEphemeralTriggerExecution","selectActiveEphemeralScheduledAttachmentSlugs","selectActiveEphemeralCronAttachmentSlugs","listAgentTriggers","getOrCreateGatewayThreadSession","existingSessionId","DiscoveredWorkflowRecord","WorkflowRegistryEntry","syncWorkflowRegistry","WorkflowSubscriptionProfile","getWorkflowSubscription","listCredentialInstancesForAssignment","CreateWorkflowRunInput","CreateAttachmentExecutionInput","Exclude","createWorkflowRun","createPendingWorkflowRun","markWorkflowRunRunning","markWorkflowRunSleeping","markWorkflowRunWaitingHook","completeWorkflowRun","failWorkflowRun","recordWorkflowLlmUsage","finalizeCanceledWorkflowRun","createAttachmentExecution","createPendingAttachmentExecution","markAttachmentExecutionRunning","WorkflowRunDetailInclude","buildWorkflowRunDetail","run","steps","WorkflowEventRecord","EventLog","append","event","listReplay","createDatabaseEventLog","WorkflowHookRecord","HookStore","create","getByToken","markResumed","createDatabaseHookStore","TriggerRunDetailInclude","listTriggerRunsPaginated","buildTriggerRunDetail","Array","encryptCredentialPayload","plaintext","decryptCredentialPayload","setCredentialInstanceValue","value","OAuthCredentialTargets","projectNamesById","organization","ensureOAuthCredentialInstance","accountLabel","externalId","userLabel","targets","ensureKeystrokeCredentialInstance","projectName","EnqueueJobInput","ClaimedJob","JobSnapshot","enqueueJob","claimNextJob","workerId","markJobComplete","jobId","markJobFailed","scheduleJobRetry","delayMs","getJobByRunId","Client","AgentTool","AgentToolResult","Tool","MCP","McpCallToolOptions","AbortSignal","signal","McpTransport","McpAuthOptions","Record","headers","env","searchParams","McpHttpTransport","URL","type","url","transport","McpStdioTransport","command","args","cwd","stderr","McpDeclaredTool","name","title","description","inputSchema","McpDefinitionInput","TCredentials","fetch","RequestInit","key","credentials","auth","resolved","declaredTools","clientName","clientVersion","requestInit","McpDefinition","McpServerOptions","McpConnection","Promise","tools","callTool","toolName","options","close","McpStdioOptions","defineMcp","def","isMcp","value","connectMcpServer","connectMcpStdio","connectMcpDefinition","JsonSchemaObject","createToolName","serverName","normalizeInputSchema","schema","mcpToolsToAgentTools","client","p","CredentialInstanceRow","x","CredentialAssignmentRow","CREDENTIAL_SCOPE_TYPES","CredentialAssignmentSet","CredentialAssignmentTargetType","CredentialConsumer","CredentialConsumer$1","CredentialInput","CredentialList","CredentialRunContext","CredentialRunContext$1","CredentialScopeType","CredentialScopeType$1","CredentialSelectionOption","CredentialSelectionOption$1","OAuthAccessTokenRefreshParams","OAuthAccessTokenRefreshResult","OAuthAccessTokenRefresher","OAuthTokenAdapter","OAuthTokenAdapter$1","OAuthTokenRefreshRegistry","OAuthTokenRefreshRegistry$1","ResolvedCredentials","MCP","McpConnection","McpDefinition","McpDefinition$1","McpDefinitionInput","AgentTool","z","CredentialToolErrorCapture","tools","takeCredentialError","captureCredentialToolErrors","selectAssignedInstanceId","assignments","consumerId","credentialSlug","buildAssignmentSet","rows","loadCredentialAssignments","Promise","targetType","targetKey","options","withCredentialAssignments","context","ResolveKeystrokeInstanceIdResult","instanceId","scopeType","scopeId","ResolveKeystrokeInstanceIdOptions","ReadonlyArray","app","scopes","assignmentTarget","type","key","consumer","resolveKeystrokeInstanceId","ResolveCredentialRefOptions","ref","userId","canAccess","row","ResolveCredentialRefResult","error","status","resolveCredentialRef","canAssignCredentialInstance","projectId","canManageCredentialInstance","credentialScopePrefix","formatCredentialRef","slug","formatCredentialRefSuggestion","appSlug","ParsedCredentialRef","kind","id","parseCredentialRef","WorkflowSubscriptionProfile","workflowKey","enabled","CredentialRunContextInput","Record","Partial","subscription","orgId","credentialSelection","request","ToolCredentialResolver","T","resolve","requirements","buildCredentialRunContext","input","buildWorkflowRunContext","actor","CredentialBackend","ZodType","resolveApiKey","schema","getOAuthAccessToken","connectionId","accessToken","CreateLocalCredentialBackendOptions","_$_keystrokehq_shared0","tokenRefresh","CreatePlatformCredentialBackendOptions","platformUrl","workerToken","CreateCredentialResolverOptions","credentialBackend","oauthAdapter","CredentialResolver","createCredentialResolver","ResolveCredentialRequirementsOptions","resolveCredentialRequirements","ResolvedMcpTools","connection","resolveMcpTools","TCredentials","def","resolver","McpInput","Omit","defineMcp","credentials","auth","TRequirements","TResolved","NonNullable","ReturnType","resolved","parseResolvedCredentials","ResolveActionCredentialsOptions","resolveCredentials","contextOverride","resolveActionCredentials","MissingCredentialsError","Error","code","chainAttempted","constructor","NeedsSelectionError","OAuthNotConfiguredError","message","CredentialAccessDeniedError","CredentialError","isCredentialError","credentialScopeMatchesContext","formatCredentialErrorMessage","orgSlug","webUrl","connect","AgentConnectContext","resolveAgentConnectContext","stubOAuthTokenAdapter","createOAuthTokenRefreshRegistry","createLocalCredentialBackend","createPlatformCredentialBackend","isWorkerRuntime","NodeJS","ProcessEnv","env","createCredentialBackend","setProjectCredentialBackend","backend","getProjectCredentialBackend","createOAuthTokenAdapterFromBackend"],"sources":["../../database/dist/index.d.mts","../../mcp/dist/index.d.mts","../../credentials/dist/index.d.mts"],"mappings":";;;;;;;KAirQK8d,mBAAAA;EACHhS,KAAAA;EACAyM,QAAAA;EACAE,MAAAA;EACAhQ,QAAAA,EAAU0B,MAAM;AAAA;;;;cChrQJib,GAAAA;AAAAA,KACTC,kBAAAA;EACHE,MAAAA,GAASD,WAAW;AAAA;AAAA,KAEjBE,YAAAA;AAAAA,KACAC,cAAAA;EACHE,OAAAA,GAAUD,MAAAA;EACVE,GAAAA,GAAMF,MAAAA,kBDyqQNjd;ECxqQAod,YAAAA,GAAeH,MAAAA;AAAAA;AAAAA,KAEZI,gBAAAA;EACHE,IAAAA;EACAC,GAAAA,WAAcF,GAAAA;E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AAAAA,iBAIeY,SAAAA,gBAAyBzC,MAAAA,gBAAAA,CAAuB0C,GAAAA,EAAKvB,kBAAAA,CAAmBC,YAAAA,IAAgBW,aAAAA,CAAcX,YAAAA;AAAAA;AAAAA,iBAGtGuB,KAAAA,CAAMC,KAAAA,YAAiBA,KAAAA,IAASb,aAAa;AAAA;AAAA,iBAG7Cc,gBAAAA,CAAiB9B,IAAAA,UAAcuB,OAAAA,EAASN,gBAAAA,GAAmBE,OAAAA,CAAQD,aAAAA;AAAAA;AAAAA,iBAGnEa,eAAAA,CAAgB/B,IAAAA,UAAcuB,OAAAA,EAASE,eAAAA,GAAkBN,OAAAA,CAAQD,aAAAA;AAAAA;AAAAA,iBAGjEc,oBAAAA,gBAAoC/C,MAAAA,gBAAAA,CAAuB0C,GAAAA,EAAKX,aAAAA,CAAcX,YAAAA,GAAeK,IAAAA,GAAO1B,cAAAA,GAAiBmC,OAAAA,CAAQD,aAAAA;AAAAA;;;KCoBzImH,sBAAAA;EACHE,OAAAA,WAAkBrF,cAAAA,EAAgBsF,YAAAA,EAAcF,CAAAA,EAAGlC,QAAAA,EAAUpD,kBAAAA,GAAuBmC,OAAAA,CAAQnB,mBAAAA,CAAoBsE,CAAAA;AAAAA;AAAAA"}
1
+ {"version":3,"file":"index-BTz2OMAM.d.cts","names":["_$drizzle_orm_node_postgres0","Pool","MigrationConfig","MigrationMeta","TracingSink","AgentTriggerType","CredentialAuthKind","CredentialScopeType","HistoryAgentSessionDetail","HistoryRun","HistoryRunKind","HistoryRunStatus","HistoryWorkflowRunDetail","RunSourceKind","WorkflowEventType","DEFAULT_DATABASE_URL","runWithTenantScope","T","Promise","tenantId","fn","getServerTenantScopeId","DEFAULT_PROJECT_ID","runWithProjectScope","projectId","getBoundProjectScopeId","getProjectScopeId","PostgresConnectionConfig","host","port","database","user","password","ssl","qualifyConnectionUser","NodeJS","ProcessEnv","env","buildPostgresUrl","config","parsePostgresUrl","url","resolvePostgresConfigFromEnv","resolvePostgresUrlFromEnv","resolveProjectDatabaseUrlFromEnv","resolveDatabaseUrlFromEnv","closeDatabase","StoredRunSourceKind$1","agentSessions","_$drizzle_orm_pg_core0","PgColumn","Date","PgTableWithColumns","name","schema","columns","id","tableName","dataType","columnType","data","driverParam","notNull","hasDefault","isPrimaryKey","isAutoincrement","hasRuntimeDefault","enumValues","baseColumn","identity","generated","agentId","sourceKind","$type","sourceId","parentSpanId","ranByUserId","title","canceledAt","totalDurationMs","liveMessage","createdAt","updatedAt","deletedAt","dialect","UsageRunKind","TriggerScheduleKind","triggerSchedules","attachmentSlug","kind","schedule","nextRunAt","enabled","TriggerRunType","triggerRuns","attachmentId","sourcePath","triggerType","payload","triggeredAt","WorkflowRunStatus","WorkflowRunTrigger","StoredRunSourceKind","workflowRuns","workflowSlug","subscriptionId","triggerRunId","parentWorkflowRunId","status","trigger","startedAt","finishedAt","input","output","error","WorkflowHookStatus","workflowHooks","hookId","runId","token","correlationId","resumedAt","CredentialAssignmentTargetType","credentialAssignments","targetType","targetKey","consumerId","credentialSlug","instanceId","JobKind","JobStatus","JobTrigger","TraceSpanKind","TraceSpanStatus","traceSpans","traceId","refId","metadata","TraceLogLevel","TraceLogSource","traceLogs","spanId","seq","level","message","source","agents","slug","description","route","moduleFile","model","systemPrompt","toolCount","credentialCount","appSlugs","registeredAt","agentEvents","sessionId","eventType","StoredTriggerSourceSlugFields","key","StoredTriggerSource","Record","endpoint","requestSchema","filterSchema","code","storedTriggerSourceSlug","normalizeStoredTriggerSource","StoredTriggerTargetKind","StoredTriggerOrigin","StoredTriggerLifecycleStatus","StoredTriggerLifecycle","maxExecutions","until","executionCount","triggerAttachments","targetKind","agentSlug","origin","prompt","lifecycle","createdBySessionId","workflowEvents","type","credentialInstances","appSlug","scopeType","scopeId","label","isDefault","authKind","ciphertext","connectionId","sharedConnectionId","grantedScopes","SlackGatewayMode","StoredGatewaySource","mode","credentialKey","channelIds","subscribeOnMention","channelName","channelKind","gatewayAttachments","platform","teamId","channelId","gatewayAttachmentKeyForChannel","gatewayThreadSessions","threadId","skills","workflows","subscribable","workflowSubscriptions","userId","resourceActivityKinds","ResourceActivityKind","resourceActivity","resourceKind","resourceId","lastOpenedAt","AgentRow","$inferSelect","listActiveAgents","projectIds","options","selectAgentBySlug","selectActiveAgentsByIds","ids","selectActiveAgentById","resolveAgentProjectId","AgentSessionRow","AgentSessionSourceFilter","selectAgentSessionById","addAgentSessionDuration","deltaMs","clearAgentSessionCancellation","AgentEventRow","TriggerAttachmentRow","getTriggerAttachmentBySlug","listActiveTriggerAttachments","selectWebhookTriggerAttachments","selectEphemeralTriggerAttachmentsByAgentSlug","selectTriggerAttachmentsByAgentSlug","selectEphemeralTriggerAttachments","TriggerScheduleRow","UpsertTriggerScheduleValues","selectTriggerScheduleBySlug","upsertTriggerSchedule","values","disableAllTriggerSchedules","now","disableTriggerSchedulesNotInSlugs","attachmentSlugs","listEnabledTriggerSchedules","claimDueTriggerSchedules","resolveNextRunAt","limit","claimDueTriggerSchedulesForOrg","listTriggerSchedulesBySlugs","triggerRunSummaryFromRow","TriggerRunRow","WorkflowRunRow","row","workflowRun","agentSession","triggerRunRecordFromRow","WorkflowEventRow","AppendWorkflowEventValues","listStepCompletedEvents","TraceLogRow","TraceSpanRow","createDatabaseTracingSink","flushNow","TraceTriggerSummary","TraceGatewaySummary","gatewayAttachmentId","gatewayAttachmentKey","TraceResponse","gateway","spans","logs","getTraceForWorkflowRun","workflowRunId","getTraceForTriggerRun","getTraceForAgentSession","workflowRunSummaryFromRow","workflowRunRecordFromRow","triggerRunDetailFromRow","workflowStepRunFromEvent","actionKey","completedAt","traceResponseToJson","trace","selectWorkflowRunById","resolveWorkflowRunProjectId","listWorkflowRunsByWorkflowSlug","selectWorkflowRunForWorkflow","listWorkflowRunsPaginated","ReturnType","cursor","items","nextCursor","WorkflowHookRow","InsertWorkflowHookValues","requeueExpiredLeases","GatewayAttachmentRow","GatewayChannelConflictError","Error","ownerProjectId","constructor","getActiveOrgGatewayAttachmentByChannel","getActiveOrgGatewayAttachmentByTeamAndChannel","getActiveGatewayAttachmentByChannel","listActiveGatewayAttachments","ActiveGatewayBinding","listActiveOrgGatewayBindingsByPlatform","listActiveGatewayAttachmentsByAgentSlug","softDeleteGatewayAttachmentsForAgentPlatformTeam","listActiveGatewayAttachmentsByPlatform","softDeleteGatewayAttachmentByChannel","upsertGatewayAttachmentByChannel","getGatewayAttachmentBySlug","GatewayThreadSessionRow","selectGatewayThreadSessionByThreadId","WorkflowRow","listActiveWorkflows","selectActiveWorkflowBySlug","selectActiveWorkflowsByIds","selectActiveWorkflowById","SkillRow","listActiveSkills","selectActiveSkillsByIds","selectActiveSkillById","WorkflowSubscriptionRow","InsertWorkflowSubscriptionValues","UpdateWorkflowSubscriptionValues","selectWorkflowSubscriptionById","selectWorkflowSubscriptionByWorkflowAndUser","listWorkflowSubscriptionsByWorkflowSlug","listEnabledWorkflowSubscriptionsByWorkflowSlug","insertWorkflowSubscription","updateWorkflowSubscriptionById","deleteWorkflowSubscriptionById","ResourceActivityRow","TouchResourceActivityInput","touchResourceActivity","listRecentResourceActivity","selectWorkflowLastRunAtByIds","Map","workflowIds","selectAgentLastRunAtByIds","agentIds","ProjectResourceCounts","agentCount","workflowCount","skillCount","selectProjectResourceCounts","ListHistoryRunsOptions","HistoryRunCore","Omit","buildHistoryWorkflowRunDetail","buildHistoryAgentSessionDetail","listHistoryRuns","findHistoryRunCore","CredentialInstanceRow","InsertCredentialInstanceValues","listAllCredentialInstances","listCredentialInstancesByConnectionId","selectCredentialInstanceById","listCredentialInstancesByScope","selectCredentialInstancesForScope","upsertCredentialInstance","deleteCredentialInstanceById","clearCredentialInstanceDefaults","exceptId","CredentialAssignmentRow","UpsertCredentialAssignmentValues","listCredentialAssignmentsByTarget","selectCredentialAssignmentById","upsertCredentialAssignment","deleteCredentialAssignmentById","listRecentWorkflowStepConsumers","runLimit","listDistinctAssignmentConsumerIds","createPgDb","NodePgDatabase","pool","usageRecords","runKind","quantity","unit","amount","jobs","targetId","scheduledAt","attempt","maxAttempts","leasedBy","leaseExpiresAt","$client","Database","DatabaseDialect","PgPool","PgDatabase","SqliteDatabase","AppDatabase","DatabaseHandle","db","searchPath","close","InitDatabaseOptions","migrate","migrationsFolder","max","closeAllProjectDatabasePools","isDatabaseInitialized","getDatabaseHandle","initDatabase","RunWithProjectDatabaseOptions","runWithProjectDatabase","ConnectionOptions","PgConnectionOptions","SqliteConnectionOptions","createPgConnection","PostgresCancelHandler","PostgresCancelChannel","publishCancel","subscribeCancel","handler","createPostgresCancelChannel","connectionString","channel","createSqliteConnection","createConnection","resolveSqlitePath","inferDialect","override","adaptPgMigrationsForSearchPath","migrations","loadMigrations","embedded","migratePgDatabase","resolveMigrationsFolder","runMigrations","handle","resolveMigrationsSchema","primarySearchPathSchema","resolveSearchPath","appendSearchPathToUrl","cancelWorkflowRun","cancelAgentSession","RunSource","runSource","sourceFromSpan","span","resolveRunSourceFromTraceContext","DiscoveredAgentRecord","AgentRegistryEntry","MESSAGE_EVENT_TYPE","syncAgentRegistry","records","getAgentByRoute","AgentSession","createSession","getSession","touchSession","setSessionTitle","nextSeq","appendEvent","listMessageEvents","countMessageEvents","AgentEventRecord","listSessionEvents","setSessionLiveMessage","clearLiveMessage","getSessionLiveMessage","LlmUsageRecordInput","recordLlmUsageFromAssistantMessage","usage","failAgentSession","AgentSessionStatus$1","agentSessionSummaryFromParts","messageCount","ranByUserName","gatewayPlatform","agentSessionRecordFromParts","gatewaySessionDetailFromParts","agentEventFromRow","AgentSessionStatus","AgentSessionSource","listAgentSessionsPaginated","resolveUserName","AgentSessionDetailInclude","buildAgentSessionDetail","include","session","messages","events","buildAgentSessionChatState","sinceSeq","live","DiscoveredSkillRecord","SkillRegistryEntry","syncSkillRegistry","TriggerAttachmentRegistryEntry","DiscoveredTriggerAttachmentRecord","syncTriggerAttachmentRegistry","CreateAgentAttachmentExecutionInput","createAgentAttachmentExecution","getTriggerRunForAgentSession","EPHEMERAL_TRIGGER_MODULE_FILE","UpsertEphemeralTriggerInput","Extract","upsertEphemeralTrigger","deleteEphemeralTrigger","isEphemeralTriggerActive","recordEphemeralTriggerExecution","selectActiveEphemeralScheduledAttachmentSlugs","selectActiveEphemeralCronAttachmentSlugs","listAgentTriggers","getOrCreateGatewayThreadSession","existingSessionId","DiscoveredWorkflowRecord","WorkflowRegistryEntry","syncWorkflowRegistry","WorkflowSubscriptionProfile","getWorkflowSubscription","listCredentialInstancesForAssignment","CreateWorkflowRunInput","CreateAttachmentExecutionInput","Exclude","createWorkflowRun","createPendingWorkflowRun","markWorkflowRunRunning","markWorkflowRunSleeping","markWorkflowRunWaitingHook","completeWorkflowRun","failWorkflowRun","recordWorkflowLlmUsage","finalizeCanceledWorkflowRun","createAttachmentExecution","createPendingAttachmentExecution","markAttachmentExecutionRunning","WorkflowRunDetailInclude","buildWorkflowRunDetail","run","steps","WorkflowEventRecord","EventLog","append","event","listReplay","createDatabaseEventLog","WorkflowHookRecord","HookStore","create","getByToken","markResumed","createDatabaseHookStore","TriggerRunDetailInclude","listTriggerRunsPaginated","buildTriggerRunDetail","Array","encryptCredentialPayload","plaintext","decryptCredentialPayload","setCredentialInstanceValue","value","OAuthCredentialTargets","projectNamesById","organization","ensureOAuthCredentialInstance","accountLabel","externalId","userLabel","targets","ensureKeystrokeCredentialInstance","projectName","EnqueueJobInput","ClaimedJob","JobSnapshot","enqueueJob","claimNextJob","workerId","markJobComplete","jobId","markJobFailed","scheduleJobRetry","delayMs","getJobByRunId","Client","AgentTool","AgentToolResult","Tool","MCP","McpCallToolOptions","AbortSignal","signal","McpTransport","McpAuthOptions","Record","headers","env","searchParams","McpHttpTransport","URL","type","url","transport","McpStdioTransport","command","args","cwd","stderr","McpDeclaredTool","name","title","description","inputSchema","McpDefinitionInput","TCredentials","fetch","RequestInit","key","credentials","auth","resolved","declaredTools","clientName","clientVersion","requestInit","McpDefinition","McpServerOptions","McpConnection","Promise","tools","callTool","toolName","options","close","McpStdioOptions","defineMcp","def","isMcp","value","connectMcpServer","connectMcpStdio","connectMcpDefinition","JsonSchemaObject","createToolName","serverName","normalizeInputSchema","schema","mcpToolsToAgentTools","client","p","CredentialInstanceRow","x","CredentialAssignmentRow","CREDENTIAL_SCOPE_TYPES","CredentialAssignmentSet","CredentialAssignmentTargetType","CredentialConsumer","CredentialConsumer$1","CredentialInput","CredentialList","CredentialRunContext","CredentialRunContext$1","CredentialScopeType","CredentialScopeType$1","CredentialSelectionOption","CredentialSelectionOption$1","OAuthAccessTokenRefreshParams","OAuthAccessTokenRefreshResult","OAuthAccessTokenRefresher","OAuthTokenAdapter","OAuthTokenAdapter$1","OAuthTokenRefreshRegistry","OAuthTokenRefreshRegistry$1","ResolvedCredentials","MCP","McpConnection","McpDefinition","McpDefinition$1","McpDefinitionInput","AgentTool","z","CredentialToolErrorCapture","tools","takeCredentialError","captureCredentialToolErrors","selectAssignedInstanceId","assignments","consumerId","credentialSlug","buildAssignmentSet","rows","loadCredentialAssignments","Promise","targetType","targetKey","options","withCredentialAssignments","context","ResolveKeystrokeInstanceIdResult","instanceId","scopeType","scopeId","ResolveKeystrokeInstanceIdOptions","ReadonlyArray","app","scopes","assignmentTarget","type","key","consumer","resolveKeystrokeInstanceId","ResolveCredentialRefOptions","ref","userId","canAccess","row","ResolveCredentialRefResult","error","status","resolveCredentialRef","canAssignCredentialInstance","projectId","canManageCredentialInstance","credentialScopePrefix","formatCredentialRef","slug","formatCredentialRefSuggestion","appSlug","ParsedCredentialRef","kind","id","parseCredentialRef","WorkflowSubscriptionProfile","workflowKey","enabled","CredentialRunContextInput","Record","Partial","subscription","orgId","credentialSelection","request","ToolCredentialResolver","T","resolve","requirements","buildCredentialRunContext","input","buildWorkflowRunContext","actor","CredentialBackend","ZodType","resolveApiKey","schema","getOAuthAccessToken","connectionId","accessToken","CreateLocalCredentialBackendOptions","_$_keystrokehq_shared0","tokenRefresh","CreatePlatformCredentialBackendOptions","platformUrl","workerToken","CreateCredentialResolverOptions","credentialBackend","oauthAdapter","CredentialResolver","createCredentialResolver","ResolveCredentialRequirementsOptions","resolveCredentialRequirements","ResolvedMcpTools","connection","resolveMcpTools","TCredentials","def","resolver","McpInput","Omit","defineMcp","credentials","auth","TRequirements","TResolved","NonNullable","ReturnType","resolved","parseResolvedCredentials","ResolveActionCredentialsOptions","resolveCredentials","contextOverride","resolveActionCredentials","MissingCredentialsError","Error","code","chainAttempted","constructor","NeedsSelectionError","OAuthNotConfiguredError","message","CredentialAccessDeniedError","CredentialError","isCredentialError","credentialScopeMatchesContext","formatCredentialErrorMessage","orgSlug","webUrl","connect","AgentConnectContext","resolveAgentConnectContext","stubOAuthTokenAdapter","createOAuthTokenRefreshRegistry","createLocalCredentialBackend","createPlatformCredentialBackend","isWorkerRuntime","NodeJS","ProcessEnv","env","createCredentialBackend","setProjectCredentialBackend","backend","getProjectCredentialBackend","createOAuthTokenAdapterFromBackend"],"sources":["../../database/dist/index.d.mts","../../mcp/dist/index.d.mts","../../credentials/dist/index.d.mts"],"mappings":";;;;;;;KAwtQK+d,mBAAAA;EACHjS,KAAAA;EACA0M,QAAAA;EACAE,MAAAA;EACAjQ,QAAAA,EAAU0B,MAAM;AAAA;;;;cCvtQJkb,GAAAA;AAAAA,KACTC,kBAAAA;EACHE,MAAAA,GAASD,WAAW;AAAA;AAAA,KAEjBE,YAAAA;AAAAA,KACAC,cAAAA;EACHE,OAAAA,GAAUD,MAAAA;EACVE,GAAAA,GAAMF,MAAAA,kBDgtQNld;EC/sQAqd,YAAAA,GAAeH,MAAAA;AAAAA;AAAAA,KAEZI,gBAAAA;EACHE,IAAAA;EACAC,GAAAA,WAAcF,GAAAA;EACdG,SAAAA,GAAYV,YAAY;AAAA;AAAA,KAErBW,iBAAAA;EACHH,IAAAA;EACAI,OAAAA;EACAC,IAAAA;EACAC,GAAAA;EACAC,MAAAA;AAAAA;AAAAA,KAEGC,eAAAA;EACHC,IAAAA;EACAC,KAAAA;EACAC,WAAAA;EACAC,WAAAA,GAAclB,MAAM;AAAA;AAAA,KAEjBmB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CAAiB9B,IAAAA,UAAcuB,OAAAA,EAASN,gBAAAA,GAAmBE,OAAAA,CAAQD,aAAAA;AAAAA;AAAAA,iBAGnEa,eAAAA,CAAgB/B,IAAAA,UAAcuB,OAAAA,EAASE,eAAAA,GAAkBN,OAAAA,CAAQD,aAAAA;AAAAA;AAAAA,iBAGjEc,oBAAAA,gBAAoC/C,MAAAA,gBAAAA,CAAuB0C,GAAAA,EAAKX,aAAAA,CAAcX,YAAAA,GAAeK,IAAAA,GAAO1B,cAAAA,GAAiBmC,OAAAA,CAAQD,aAAAA;AAAAA;;;KCoBzImH,sBAAAA;EACHE,OAAAA,WAAkBrF,cAAAA,EAAgBsF,YAAAA,EAAcF,CAAAA,EAAGlC,QAAAA,EAAUpD,kBAAAA,GAAuBmC,OAAAA,CAAQnB,mBAAAA,CAAoBsE,CAAAA;AAAAA;AAAAA"}
@@ -99,6 +99,11 @@ declare function defineTool<T extends AgentTool>(tool: T): T; //#endregion
99
99
  //#region src/define/types.d.ts
100
100
  /** MCP defs vary by credential shape at authoring time. */
101
101
  type AgentMcpTool = McpDefinition<any>;
102
+ /** Per-agent built-in web_search / web_fetch host tool options (each defaults to on). */
103
+ type WebToolsOptions = {
104
+ search?: boolean;
105
+ fetch?: boolean;
106
+ };
102
107
  /** Author-facing agent input — asset slugs resolve from src/skills/ and src/files/. */
103
108
  type AgentDefinitionAuthorInput = AgentCreateInput & {
104
109
  /** Discovery and route id for this agent (`POST /agents/{slug}`). */slug: string;
@@ -108,7 +113,8 @@ type AgentDefinitionAuthorInput = AgentCreateInput & {
108
113
  runtimeHooks?: RuntimeHooks; /** Skill folder names under `src/skills/{slug}/`. */
109
114
  skills?: string[]; /** Sandbox layout, project files, and execution mode. */
110
115
  sandbox?: SandboxDefinitionInput; /** Persistent memory (default on). Pass `false` to disable. */
111
- memory?: false | DefaultMemoryOptions;
116
+ memory?: false | DefaultMemoryOptions; /** Built-in web_search / web_fetch host tools (default on). Pass `false` to disable both. */
117
+ web?: false | WebToolsOptions;
112
118
  };
113
119
  /** Input to {@link defineAgent}. */
114
120
  type AgentDefinitionInput = AgentDefinitionAuthorInput;
@@ -119,6 +125,7 @@ type AgentDefinition = AgentCreateInput & {
119
125
  sandbox?: SandboxDefinition;
120
126
  skills?: SkillDefinition[];
121
127
  memory?: false | DefaultMemoryOptions;
128
+ web?: false | WebToolsOptions;
122
129
  };
123
130
  type PromptInput = {
124
131
  message: string;
@@ -326,5 +333,5 @@ type ResolveAgentToolsOptions = {
326
333
  };
327
334
  declare function resolveAgentTools(tools: Array<ActionDefinition | AgentTool | AgentMcpTool>, resolver: ToolCredentialResolver, options?: ResolveAgentToolsOptions): Promise<ResolvedAgentTools>; //#endregion
328
335
  //#endregion
329
- export { forceToolChoice as A, runAgentPrompt as B, SubagentToolMetadata as C, defineSubagentTool as D, defineAgent as E, prompt as F, AgentModelId as G, snapshot as H, resolveAgentAssets as I, ThinkingLevelSchema as J, AgentModelIdSchema as K, resolveAgentId as L, messages as M, normalizeAgentDefinition as N, defineTool as O, prepareAgentSession as P, resolveAgentTools as R, SubagentToolInherit as S, createAgent as T, AgentCreateInput as U, runLlm as V, AgentCreateInputSchema as W, resolveAgentModel as X, parseAgentCreateInput as Y, resolveThinkingLevel as Z, SessionAgentMismatchError as _, AgentDefinitionInput as a, SubagentTool as b, BuildAgentRuntimeContext as c, PromptInput as d, PromptResponse as f, SandboxedAgentRuntime as g, SUBAGENT_TOOL as h, AgentDefinition as i, getSubagentToolMetadata as j, errorMessage as k, DefineSubagentToolInput as l, RunAgentPromptOptions as m, AgentAssetInput as n, AgentRuntime as o, ResolvedAgentAssets as p, DEFAULT_THINKING_LEVEL as q, AgentConfig as r, AgentSnapshot as s, Agent as t, ForcedToolChoice as u, SessionLifecycle as v, buildAgentRuntime as w, SubagentToolDetails as x, SessionLifecycleContext as y, resolveAgentWorkspaceRoot as z };
330
- //# sourceMappingURL=index-BQEzTb7P.d.cts.map
336
+ export { errorMessage as A, resolveAgentWorkspaceRoot as B, SubagentToolMetadata as C, defineAgent as D, createAgent as E, prepareAgentSession as F, AgentCreateInputSchema as G, runLlm as H, prompt as I, DEFAULT_THINKING_LEVEL as J, AgentModelId as K, resolveAgentAssets as L, getSubagentToolMetadata as M, messages as N, defineSubagentTool as O, normalizeAgentDefinition as P, resolveThinkingLevel as Q, resolveAgentId as R, SubagentToolInherit as S, buildAgentRuntime as T, snapshot as U, runAgentPrompt as V, AgentCreateInput as W, parseAgentCreateInput as X, ThinkingLevelSchema as Y, resolveAgentModel as Z, SessionAgentMismatchError as _, AgentDefinitionInput as a, SubagentTool as b, BuildAgentRuntimeContext as c, PromptInput as d, PromptResponse as f, SandboxedAgentRuntime as g, SUBAGENT_TOOL as h, AgentDefinition as i, forceToolChoice as j, defineTool as k, DefineSubagentToolInput as l, RunAgentPromptOptions as m, AgentAssetInput as n, AgentRuntime as o, ResolvedAgentAssets as p, AgentModelIdSchema as q, AgentConfig as r, AgentSnapshot as s, Agent as t, ForcedToolChoice as u, SessionLifecycle as v, WebToolsOptions as w, SubagentToolDetails as x, SessionLifecycleContext as y, resolveAgentTools as z };
337
+ //# sourceMappingURL=index-C9qevi4R.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index-C9qevi4R.d.cts","names":["h","ThinkingLevel","r","Model","z","AgentModelId","AgentModelIdSchema","ZodCustom","resolveAgentModel","Promise","modelId","ThinkingLevelSchema","ZodEnum","off","minimal","low","medium","high","xhigh","DEFAULT_THINKING_LEVEL","AgentCreateInputSchema","ZodString","ZodOptional","core","$strip","ZodObject","systemPrompt","model","thinkingLevel","AgentCreateInput","infer","parseAgentCreateInput","input","resolveThinkingLevel","level","a","c","i","l","n","o","s","t","DatabaseSync","Type","AgentTool","resolveMemoryRelativePath","memoryDir","inputPath","orderMemoryRelativePaths","relativePaths","listMemoryFilePaths","readMemoryFileContent","MemoryConfig","enabled","dir","memoryFile","userFile","archiveDir","dbFile","sessionsDir","memoryCharLimit","userCharLimit","archiveTocLimit","securityScan","loadMemoryConfig","Partial","overrides","Memory","Promise","tool","systemPromptInjection","close","MemoryFactory","create","agentId","sessionId","ctx","DefaultMemoryOptions","user","memories","createDefaultMemory","NodeJS","ProcessEnv","options","env","MemoryStoragePort","Uint8Array","Buffer","listObjects","prefix","getObject","key","putObject","body","contentType","input","deleteObject","StorageBackedMemoryOptions","storage","seed","createStorageBackedMemory","SnapshotResult","block","warnings","buildMemorySnapshot","config","ArchiveHit","path","snippet","rank","SessionHit","session_file","line_no","role","ts","searchArchive","db","query","limit","searchSessions","reindexSessions","memoryToolParameters","TLiteral","TObject","TString","TUnion","TOptional","TNumber","TBoolean","action","content","oldText","newText","scope","full","createMemoryTool","_$_earendil_works_pi_agent_core0","c","AgentMessage","d","AgentTool","h","ThinkingLevel","l","AgentOptions","m","PiAgent","o","getModel","r","Model","u","AgentState","a","parseAgentCreateInput","AgentModelIdSchema","i","ThinkingLevelSchema","resolveAgentModel","n","AgentCreateInputSchema","resolveThinkingLevel","DEFAULT_THINKING_LEVEL","s","AgentModelId","t","AgentCreateInput","z","LlmUsageRecordInput","Api","McpAuthOptions","McpCallToolOptions","McpConnection","McpConnection$1","McpDefinition","McpDefinition$1","McpDefinitionInput","McpHttpTransport","McpServerOptions","McpStdioOptions","McpStdioTransport","McpTransport","connectMcpDefinition","connectMcpServer","connectMcpStdio","defineMcp","isMcp","ActionDefinition","McpCredentialContext","CredentialRunContext","OAuthTokenAdapter","ToolCredentialResolver","DefaultMemoryOptions","Memory","MemoryFactory","AgentWorkspaceRoots","RuntimeHooks","RuntimeProvider","Sandbox","SandboxDefinition","SandboxDefinitionInput","SandboxMode","SkillDefinition","loadAssetManifest","PromptLlmRunOptions","AgentConfig","Omit","systemPrompt","model","thinkingLevel","messages","tools","AgentRuntime","Readonly","pi","AgentSnapshot","state","createAgent","config","prompt","Promise","runtime","message","snapshot","errorMessage","defineTool","T","tool","AgentMcpTool","WebToolsOptions","search","fetch","AgentDefinitionAuthorInput","Array","slug","name","description","runtimeHooks","skills","sandbox","memory","web","AgentDefinitionInput","AgentDefinition","PromptInput","sessionId","subscriptionId","context","SessionLifecycleContext","agentId","SessionLifecycle","beforeRuntime","ctx","afterRuntime","RunAgentPromptOptions","stepId","workspacesRoot","agentRoot","sessionRoot","workspaceRoot","mode","runtimeProvider","vmRuntimeProvider","memoryFactory","credentials","oauthAdapter","hostTools","tracing","trigger","gatewayAttachmentId","gatewayAttachmentKey","agentKey","skipAgentSessionSpan","invocationRoute","sessionLifecycle","PromptResponse","error","canceled","BuildAgentRuntimeContext","SandboxedAgentRuntime","mcpConnections","takeCredentialError","buildAgentRuntime","def","runPrompt","agentSlug","Agent","buildRuntime","input","defineAgent","resolveAgentId","explicitId","SUBAGENT_TOOL","SubagentToolInherit","workspace","SubagentToolMetadata","agent","inherit","SubagentToolDetails","SubagentTool","DefineSubagentToolInput","label","parameters","toMessage","params","getSubagentToolMetadata","defineSubagentTool","runAgentPrompt","options","SessionAgentMismatchError","Error","constructor","prepareAgentSession","ranByUserId","normalizeAgentDefinition","appRoot","RunLlmHooks","onUsage","usage","runLlm","opts","hooks","ForcedToolChoice","type","function","forceToolChoice","api","toolName","resolveAgentWorkspaceRoot","AgentAssetInput","skillKeys","ResolvedAgentAssets","resolveAgentAssets","ResolvedAgentTools","ResolveAgentToolsOptions","mcpCredentialContext","resolveAgentTools","resolver"],"sources":["../../agent/dist/schemas-BjkCaevQ.d.mts","../../memory/dist/index.d.mts","../../agent/dist/index.d.mts"],"mappings":";;;;;;;;;;KAKKK,YAAAA;AAAAA,cACSC,kBAAAA,EAAoBF,CAAAA,CAAEG,SAAS;;iBAE5BC,iBAAAA,CAAkBE,OAAAA,EAASL,YAAAA,GAAeI,OAAAA,CAAQN,KAAAA;AAAAA;AAAAA,cAGrDQ,mBAAAA,EAAqBP,CAAAA,CAAEQ,OAAO;EAC1CC,GAAAA;EACAC,OAAAA;EACAC,GAAAA;EACAC,MAAAA;EACAC,IAAAA;EACAC,KAAAA;AAAAA;AAAAA,cAEYC,sBAAAA;;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;EAEAwF,IAAAA;EACAC,QAAAA;IACEzF,IAAAA;EAAAA;AAAAA;EAGFR,IAAAA;IACEQ,IAAAA;EAAAA;AAAAA;;;;;iBAOa0F,eAAAA,CAAgBC,GAAAA,EAAK7J,GAAAA,EAAK8J,QAAAA,WAAmBL,gBAAgB;AAAA;;;;;;;AAnNd;AAAA;;;iBAgO/CM,yBAAAA,CAA0B/E,OAAAA,UAAiBJ,SAAAA,UAAmB+D,OAAAA;EAC7EpD,cAAAA;EACAC,SAAAA;EACAC,WAAAA,WA/NyB;EAgOzBC,aAAAA;EACApB,OAAAA,GAAUxC,iBAAAA;EACVuC,MAAAA,GAASpC,eAAAA;AAAAA,IACPkB,OAAAA,CAAQzB,mBAAAA;AAAAA;AAAAA,KAGPsI,eAAAA;EACHC,SAAAA;EACA7C,SAAAA;EACA8B,OAAAA;AAAAA;AAAAA,KAEGgB,mBAAAA;EACH7F,MAAAA,GAASpC,eAAe;AAAA;;iBAGTkI,kBAAAA,CAAmB5C,KAAAA,EAAOyC,eAAAA,GAAkBE,mBAAmB;AAAA;AAAA,KAG3EE,kBAAAA;EACH1H,KAAAA,EAAOvE,SAAAA;EACP4I,cAAAA,EAAgB3G,aAAe;AAAA;AAAA,KAE5BiK,wBAAAA;EACHC,oBAAAA,GAAuBnJ,oBAAoB;AAAA;AAAA,iBAE5BoJ,iBAAAA,CAAkB7H,KAAAA,EAAOsB,KAAAA,CAAM9C,gBAAAA,GAAmB/C,SAAAA,GAAYwF,YAAAA,GAAe6G,QAAAA,EAAUlJ,sBAAAA,EAAwBqH,OAAAA,GAAU0B,wBAAAA,GAA2BlH,OAAAA,CAAQiH,kBAAAA"}
@@ -100,6 +100,11 @@ declare function defineTool<T extends AgentTool>(tool: T): T; //#endregion
100
100
  //#region src/define/types.d.ts
101
101
  /** MCP defs vary by credential shape at authoring time. */
102
102
  type AgentMcpTool = McpDefinition<any>;
103
+ /** Per-agent built-in web_search / web_fetch host tool options (each defaults to on). */
104
+ type WebToolsOptions = {
105
+ search?: boolean;
106
+ fetch?: boolean;
107
+ };
103
108
  /** Author-facing agent input — asset slugs resolve from src/skills/ and src/files/. */
104
109
  type AgentDefinitionAuthorInput = AgentCreateInput & {
105
110
  /** Discovery and route id for this agent (`POST /agents/{slug}`). */slug: string;
@@ -109,7 +114,8 @@ type AgentDefinitionAuthorInput = AgentCreateInput & {
109
114
  runtimeHooks?: RuntimeHooks; /** Skill folder names under `src/skills/{slug}/`. */
110
115
  skills?: string[]; /** Sandbox layout, project files, and execution mode. */
111
116
  sandbox?: SandboxDefinitionInput; /** Persistent memory (default on). Pass `false` to disable. */
112
- memory?: false | DefaultMemoryOptions;
117
+ memory?: false | DefaultMemoryOptions; /** Built-in web_search / web_fetch host tools (default on). Pass `false` to disable both. */
118
+ web?: false | WebToolsOptions;
113
119
  };
114
120
  /** Input to {@link defineAgent}. */
115
121
  type AgentDefinitionInput = AgentDefinitionAuthorInput;
@@ -120,6 +126,7 @@ type AgentDefinition = AgentCreateInput & {
120
126
  sandbox?: SandboxDefinition;
121
127
  skills?: SkillDefinition[];
122
128
  memory?: false | DefaultMemoryOptions;
129
+ web?: false | WebToolsOptions;
123
130
  };
124
131
  type PromptInput = {
125
132
  message: string;
@@ -327,5 +334,5 @@ type ResolveAgentToolsOptions = {
327
334
  };
328
335
  declare function resolveAgentTools(tools: Array<ActionDefinition | AgentTool | AgentMcpTool>, resolver: ToolCredentialResolver, options?: ResolveAgentToolsOptions): Promise<ResolvedAgentTools>; //#endregion
329
336
  //#endregion
330
- export { forceToolChoice as A, runAgentPrompt as B, SubagentToolMetadata as C, defineSubagentTool as D, defineAgent as E, prompt as F, AgentModelId as G, snapshot as H, resolveAgentAssets as I, ThinkingLevelSchema as J, AgentModelIdSchema as K, resolveAgentId as L, messages as M, normalizeAgentDefinition as N, defineTool as O, prepareAgentSession as P, resolveAgentTools as R, SubagentToolInherit as S, createAgent as T, AgentCreateInput as U, runLlm as V, AgentCreateInputSchema as W, resolveAgentModel as X, parseAgentCreateInput as Y, resolveThinkingLevel as Z, SessionAgentMismatchError as _, AgentDefinitionInput as a, SubagentTool as b, BuildAgentRuntimeContext as c, PromptInput as d, PromptResponse as f, SandboxedAgentRuntime as g, SUBAGENT_TOOL as h, AgentDefinition as i, getSubagentToolMetadata as j, errorMessage as k, DefineSubagentToolInput as l, RunAgentPromptOptions as m, AgentAssetInput as n, AgentRuntime as o, ResolvedAgentAssets as p, DEFAULT_THINKING_LEVEL as q, AgentConfig as r, AgentSnapshot as s, Agent as t, ForcedToolChoice as u, SessionLifecycle as v, buildAgentRuntime as w, SubagentToolDetails as x, SessionLifecycleContext as y, resolveAgentWorkspaceRoot as z };
331
- //# sourceMappingURL=index-ub0OqZXh.d.mts.map
337
+ export { errorMessage as A, resolveAgentWorkspaceRoot as B, SubagentToolMetadata as C, defineAgent as D, createAgent as E, prepareAgentSession as F, AgentCreateInputSchema as G, runLlm as H, prompt as I, DEFAULT_THINKING_LEVEL as J, AgentModelId as K, resolveAgentAssets as L, getSubagentToolMetadata as M, messages as N, defineSubagentTool as O, normalizeAgentDefinition as P, resolveThinkingLevel as Q, resolveAgentId as R, SubagentToolInherit as S, buildAgentRuntime as T, snapshot as U, runAgentPrompt as V, AgentCreateInput as W, parseAgentCreateInput as X, ThinkingLevelSchema as Y, resolveAgentModel as Z, SessionAgentMismatchError as _, AgentDefinitionInput as a, SubagentTool as b, BuildAgentRuntimeContext as c, PromptInput as d, PromptResponse as f, SandboxedAgentRuntime as g, SUBAGENT_TOOL as h, AgentDefinition as i, forceToolChoice as j, defineTool as k, DefineSubagentToolInput as l, RunAgentPromptOptions as m, AgentAssetInput as n, AgentRuntime as o, ResolvedAgentAssets as p, AgentModelIdSchema as q, AgentConfig as r, AgentSnapshot as s, Agent as t, ForcedToolChoice as u, SessionLifecycle as v, WebToolsOptions as w, SubagentToolDetails as x, SessionLifecycleContext as y, resolveAgentTools as z };
338
+ //# sourceMappingURL=index-CGa7YLSI.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index-CGa7YLSI.d.mts","names":["h","ThinkingLevel","r","Model","z","AgentModelId","AgentModelIdSchema","ZodCustom","resolveAgentModel","Promise","modelId","ThinkingLevelSchema","ZodEnum","off","minimal","low","medium","high","xhigh","DEFAULT_THINKING_LEVEL","AgentCreateInputSchema","ZodString","ZodOptional","core","$strip","ZodObject","systemPrompt","model","thinkingLevel","AgentCreateInput","infer","parseAgentCreateInput","input","resolveThinkingLevel","level","a","c","i","l","n","o","s","t","DatabaseSync","Type","AgentTool","resolveMemoryRelativePath","memoryDir","inputPath","orderMemoryRelativePaths","relativePaths","listMemoryFilePaths","readMemoryFileContent","MemoryConfig","enabled","dir","memoryFile","userFile","archiveDir","dbFile","sessionsDir","memoryCharLimit","userCharLimit","archiveTocLimit","securityScan","loadMemoryConfig","Partial","overrides","Memory","Promise","tool","systemPromptInjection","close","MemoryFactory","create","agentId","sessionId","ctx","DefaultMemoryOptions","user","memories","createDefaultMemory","NodeJS","ProcessEnv","options","env","MemoryStoragePort","Uint8Array","Buffer","listObjects","prefix","getObject","key","putObject","body","contentType","input","deleteObject","StorageBackedMemoryOptions","storage","seed","createStorageBackedMemory","SnapshotResult","block","warnings","buildMemorySnapshot","config","ArchiveHit","path","snippet","rank","SessionHit","session_file","line_no","role","ts","searchArchive","db","query","limit","searchSessions","reindexSessions","memoryToolParameters","TLiteral","TObject","TString","TUnion","TOptional","TNumber","TBoolean","action","content","oldText","newText","scope","full","createMemoryTool","_$_earendil_works_pi_agent_core0","c","AgentMessage","d","AgentTool","h","ThinkingLevel","l","AgentOptions","m","PiAgent","o","getModel","r","Model","u","AgentState","a","parseAgentCreateInput","AgentModelIdSchema","i","ThinkingLevelSchema","resolveAgentModel","n","AgentCreateInputSchema","resolveThinkingLevel","DEFAULT_THINKING_LEVEL","s","AgentModelId","t","AgentCreateInput","z","LlmUsageRecordInput","Api","McpAuthOptions","McpCallToolOptions","McpConnection","McpConnection$1","McpDefinition","McpDefinition$1","McpDefinitionInput","McpHttpTransport","McpServerOptions","McpStdioOptions","McpStdioTransport","McpTransport","connectMcpDefinition","connectMcpServer","connectMcpStdio","defineMcp","isMcp","ActionDefinition","McpCredentialContext","CredentialRunContext","OAuthTokenAdapter","ToolCredentialResolver","DefaultMemoryOptions","Memory","MemoryFactory","AgentWorkspaceRoots","RuntimeHooks","RuntimeProvider","Sandbox","SandboxDefinition","SandboxDefinitionInput","SandboxMode","SkillDefinition","loadAssetManifest","PromptLlmRunOptions","AgentConfig","Omit","systemPrompt","model","thinkingLevel","messages","tools","AgentRuntime","Readonly","pi","AgentSnapshot","state","createAgent","config","prompt","Promise","runtime","message","snapshot","errorMessage","defineTool","T","tool","AgentMcpTool","WebToolsOptions","search","fetch","AgentDefinitionAuthorInput","Array","slug","name","description","runtimeHooks","skills","sandbox","memory","web","AgentDefinitionInput","AgentDefinition","PromptInput","sessionId","subscriptionId","context","SessionLifecycleContext","agentId","SessionLifecycle","beforeRuntime","ctx","afterRuntime","RunAgentPromptOptions","stepId","workspacesRoot","agentRoot","sessionRoot","workspaceRoot","mode","runtimeProvider","vmRuntimeProvider","memoryFactory","credentials","oauthAdapter","hostTools","tracing","trigger","gatewayAttachmentId","gatewayAttachmentKey","agentKey","skipAgentSessionSpan","invocationRoute","sessionLifecycle","PromptResponse","error","canceled","BuildAgentRuntimeContext","SandboxedAgentRuntime","mcpConnections","takeCredentialError","buildAgentRuntime","def","runPrompt","agentSlug","Agent","buildRuntime","input","defineAgent","resolveAgentId","explicitId","SUBAGENT_TOOL","SubagentToolInherit","workspace","SubagentToolMetadata","agent","inherit","SubagentToolDetails","SubagentTool","DefineSubagentToolInput","label","parameters","toMessage","params","getSubagentToolMetadata","defineSubagentTool","runAgentPrompt","options","SessionAgentMismatchError","Error","constructor","prepareAgentSession","ranByUserId","normalizeAgentDefinition","appRoot","RunLlmHooks","onUsage","usage","runLlm","opts","hooks","ForcedToolChoice","type","function","forceToolChoice","api","toolName","resolveAgentWorkspaceRoot","AgentAssetInput","skillKeys","ResolvedAgentAssets","resolveAgentAssets","ResolvedAgentTools","ResolveAgentToolsOptions","mcpCredentialContext","resolveAgentTools","resolver"],"sources":["../../agent/dist/schemas-BjkCaevQ.d.mts","../../memory/dist/index.d.mts","../../agent/dist/index.d.mts"],"mappings":";;;;;;;;;;;KAKKK,YAAAA;AAAAA,cACSC,kBAAAA,EAAoBF,CAAAA,CAAEG,SAAS;;iBAE5BC,iBAAAA,CAAkBE,OAAAA,EAASL,YAAAA,GAAeI,OAAAA,CAAQN,KAAAA;AAAAA;AAAAA,cAGrDQ,mBAAAA,EAAqBP,CAAAA,CAAEQ,OAAO;EAC1CC,GAAAA;EACAC,OAAAA;EACAC,GAAAA;EACAC,MAAAA;EACAC,IAAAA;EACAC,KAAAA;AAAAA;AAAAA,cAEYC,sBAAAA;AAb+B;AAAA,cAe/BC,sBAAAA,EAAwBhB,CAAAA,CAAEqB,SAAAA;EACtCC,YAAAA,EAActB,CAAAA,CAAEiB,SAAAA;EAChBM,KAAAA,EAAOvB,CAAAA,CAAEG,SAAAA;EACTqB,aAAAA,EAAexB,CAAAA,CAAEkB,WAAAA,CAAYlB,CAAAA,CAAEQ,OAAAA;IAC7BC,GAAAA;IACAC,OAAAA;IACAC,GAAAA;IACAC,MAAAA;IACAC,IAAAA;IACAC,KAAAA;EAAAA;AAAAA,GAEDd,CAAAA,CAAEmB,IAAAA,CAAKC,MAAAA;AAAAA,KACLK,gBAAAA,GAAmBzB,CAAAA,CAAE0B,KAAK,QAAQV,sBAAAA;AAAAA,iBACtBW,qBAAAA,CAAsBC,KAAAA,YAAiBH,gBAAgB;AAAA,iBACvDI,oBAAAA,CAAqBC,KAAAA,GAAQjC,aAAAA,GAAgBA,aAAa;;;;;KCtBtEoD,YAAAA;EACHC,OAAAA;EACAC,GAAAA;EACAC,UAAAA;EACAC,QAAAA;EACAC,UAAAA;EACAC,MAAAA;EACAC,WAAAA;EACAC,eAAAA;EACAC,aAAAA;EACAC,eAAAA;EACAC,YAAAA;AAAAA;AAA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BAAAA;EACH1H,KAAAA,EAAOvE,SAAAA;EACP4I,cAAAA,EAAgB3G,aAAe;AAAA;AAAA,KAE5BiK,wBAAAA;EACHC,oBAAAA,GAAuBnJ,oBAAoB;AAAA;AAAA,iBAE5BoJ,iBAAAA,CAAkB7H,KAAAA,EAAOsB,KAAAA,CAAM9C,gBAAAA,GAAmB/C,SAAAA,GAAYwF,YAAAA,GAAe6G,QAAAA,EAAUlJ,sBAAAA,EAAwBqH,OAAAA,GAAU0B,wBAAAA,GAA2BlH,OAAAA,CAAQiH,kBAAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"index-Cq2F2XdS.d.mts","names":["_$drizzle_orm_node_postgres0","Pool","MigrationConfig","MigrationMeta","TracingSink","AgentTriggerType","CredentialAuthKind","CredentialScopeType","HistoryAgentSessionDetail","HistoryRun","HistoryRunKind","HistoryRunStatus","HistoryWorkflowRunDetail","RunSourceKind","WorkflowEventType","DEFAULT_DATABASE_URL","runWithTenantScope","T","Promise","tenantId","fn","getServerTenantScopeId","DEFAULT_PROJECT_ID","runWithProjectScope","projectId","getBoundProjectScopeId","getProjectScopeId","PostgresConnectionConfig","host","port","database","user","password","ssl","qualifyConnectionUser","NodeJS","ProcessEnv","env","buildPostgresUrl","config","parsePostgresUrl","url","resolvePostgresConfigFromEnv","resolvePostgresUrlFromEnv","resolveProjectDatabaseUrlFromEnv","resolveDatabaseUrlFromEnv","closeDatabase","StoredRunSourceKind$1","agentSessions","_$drizzle_orm_pg_core0","PgColumn","Date","PgTableWithColumns","name","schema","columns","id","tableName","dataType","columnType","data","driverParam","notNull","hasDefault","isPrimaryKey","isAutoincrement","hasRuntimeDefault","enumValues","baseColumn","identity","generated","agentId","sourceKind","$type","sourceId","parentSpanId","ranByUserId","title","canceledAt","totalDurationMs","liveMessage","createdAt","updatedAt","deletedAt","dialect","UsageRunKind","TriggerScheduleKind","triggerSchedules","attachmentSlug","kind","schedule","nextRunAt","enabled","TriggerRunType","triggerRuns","attachmentId","sourcePath","triggerType","payload","triggeredAt","WorkflowRunStatus","WorkflowRunTrigger","StoredRunSourceKind","workflowRuns","workflowSlug","subscriptionId","triggerRunId","parentWorkflowRunId","status","trigger","startedAt","finishedAt","input","output","error","WorkflowHookStatus","workflowHooks","hookId","runId","token","correlationId","resumedAt","CredentialAssignmentTargetType","credentialAssignments","targetType","targetKey","consumerId","credentialSlug","instanceId","JobKind","JobStatus","JobTrigger","TraceSpanKind","TraceSpanStatus","traceSpans","traceId","refId","metadata","TraceLogLevel","TraceLogSource","traceLogs","spanId","seq","level","message","source","agents","slug","description","route","moduleFile","model","systemPrompt","toolCount","credentialCount","appSlugs","registeredAt","agentEvents","sessionId","eventType","StoredTriggerSourceSlugFields","key","StoredTriggerSource","Record","endpoint","requestSchema","filterSchema","code","storedTriggerSourceSlug","normalizeStoredTriggerSource","StoredTriggerTargetKind","StoredTriggerOrigin","StoredTriggerLifecycleStatus","StoredTriggerLifecycle","maxExecutions","until","executionCount","triggerAttachments","targetKind","agentSlug","origin","prompt","lifecycle","createdBySessionId","workflowEvents","type","credentialInstances","appSlug","scopeType","scopeId","label","isDefault","authKind","ciphertext","connectionId","sharedConnectionId","SlackGatewayMode","StoredGatewaySource","mode","credentialKey","channelIds","subscribeOnMention","channelName","channelKind","gatewayAttachments","platform","teamId","channelId","gatewayAttachmentKeyForChannel","gatewayThreadSessions","threadId","skills","workflows","subscribable","workflowSubscriptions","userId","resourceActivityKinds","ResourceActivityKind","resourceActivity","resourceKind","resourceId","lastOpenedAt","AgentRow","$inferSelect","listActiveAgents","projectIds","options","selectAgentBySlug","selectActiveAgentsByIds","ids","selectActiveAgentById","resolveAgentProjectId","AgentSessionRow","AgentSessionSourceFilter","selectAgentSessionById","addAgentSessionDuration","deltaMs","clearAgentSessionCancellation","AgentEventRow","TriggerAttachmentRow","getTriggerAttachmentBySlug","listActiveTriggerAttachments","selectWebhookTriggerAttachments","selectEphemeralTriggerAttachmentsByAgentSlug","selectTriggerAttachmentsByAgentSlug","selectEphemeralTriggerAttachments","TriggerScheduleRow","UpsertTriggerScheduleValues","selectTriggerScheduleBySlug","upsertTriggerSchedule","values","disableAllTriggerSchedules","now","disableTriggerSchedulesNotInSlugs","attachmentSlugs","listEnabledTriggerSchedules","claimDueTriggerSchedules","resolveNextRunAt","limit","claimDueTriggerSchedulesForOrg","listTriggerSchedulesBySlugs","triggerRunSummaryFromRow","TriggerRunRow","WorkflowRunRow","row","workflowRun","agentSession","triggerRunRecordFromRow","WorkflowEventRow","AppendWorkflowEventValues","listStepCompletedEvents","TraceLogRow","TraceSpanRow","createDatabaseTracingSink","flushNow","TraceTriggerSummary","TraceGatewaySummary","gatewayAttachmentId","gatewayAttachmentKey","TraceResponse","gateway","spans","logs","getTraceForWorkflowRun","workflowRunId","getTraceForTriggerRun","getTraceForAgentSession","workflowRunSummaryFromRow","workflowRunRecordFromRow","triggerRunDetailFromRow","workflowStepRunFromEvent","actionKey","completedAt","traceResponseToJson","trace","selectWorkflowRunById","resolveWorkflowRunProjectId","listWorkflowRunsByWorkflowSlug","selectWorkflowRunForWorkflow","listWorkflowRunsPaginated","ReturnType","cursor","items","nextCursor","WorkflowHookRow","InsertWorkflowHookValues","requeueExpiredLeases","GatewayAttachmentRow","GatewayChannelConflictError","Error","ownerProjectId","constructor","getActiveOrgGatewayAttachmentByChannel","getActiveOrgGatewayAttachmentByTeamAndChannel","getActiveGatewayAttachmentByChannel","listActiveGatewayAttachments","ActiveGatewayBinding","listActiveOrgGatewayBindingsByPlatform","listActiveGatewayAttachmentsByAgentSlug","softDeleteGatewayAttachmentsForAgentPlatformTeam","listActiveGatewayAttachmentsByPlatform","softDeleteGatewayAttachmentByChannel","upsertGatewayAttachmentByChannel","getGatewayAttachmentBySlug","GatewayThreadSessionRow","selectGatewayThreadSessionByThreadId","WorkflowRow","listActiveWorkflows","selectActiveWorkflowBySlug","selectActiveWorkflowsByIds","selectActiveWorkflowById","SkillRow","listActiveSkills","selectActiveSkillsByIds","selectActiveSkillById","WorkflowSubscriptionRow","InsertWorkflowSubscriptionValues","UpdateWorkflowSubscriptionValues","selectWorkflowSubscriptionById","selectWorkflowSubscriptionByWorkflowAndUser","listWorkflowSubscriptionsByWorkflowSlug","listEnabledWorkflowSubscriptionsByWorkflowSlug","insertWorkflowSubscription","updateWorkflowSubscriptionById","deleteWorkflowSubscriptionById","ResourceActivityRow","TouchResourceActivityInput","touchResourceActivity","listRecentResourceActivity","selectWorkflowLastRunAtByIds","Map","workflowIds","selectAgentLastRunAtByIds","agentIds","ProjectResourceCounts","agentCount","workflowCount","skillCount","selectProjectResourceCounts","ListHistoryRunsOptions","HistoryRunCore","Omit","buildHistoryWorkflowRunDetail","buildHistoryAgentSessionDetail","listHistoryRuns","findHistoryRunCore","CredentialInstanceRow","InsertCredentialInstanceValues","listAllCredentialInstances","listCredentialInstancesByConnectionId","selectCredentialInstanceById","listCredentialInstancesByScope","selectCredentialInstancesForScope","upsertCredentialInstance","deleteCredentialInstanceById","clearCredentialInstanceDefaults","exceptId","CredentialAssignmentRow","UpsertCredentialAssignmentValues","listCredentialAssignmentsByTarget","selectCredentialAssignmentById","upsertCredentialAssignment","deleteCredentialAssignmentById","listRecentWorkflowStepConsumers","runLimit","listDistinctAssignmentConsumerIds","createPgDb","NodePgDatabase","pool","usageRecords","runKind","quantity","unit","amount","jobs","targetId","scheduledAt","attempt","maxAttempts","leasedBy","leaseExpiresAt","$client","Database","DatabaseDialect","PgPool","PgDatabase","SqliteDatabase","AppDatabase","DatabaseHandle","db","searchPath","close","InitDatabaseOptions","migrate","migrationsFolder","max","closeAllProjectDatabasePools","isDatabaseInitialized","getDatabaseHandle","initDatabase","RunWithProjectDatabaseOptions","runWithProjectDatabase","ConnectionOptions","PgConnectionOptions","SqliteConnectionOptions","createPgConnection","PostgresCancelHandler","PostgresCancelChannel","publishCancel","subscribeCancel","handler","createPostgresCancelChannel","connectionString","channel","createSqliteConnection","createConnection","resolveSqlitePath","inferDialect","override","adaptPgMigrationsForSearchPath","migrations","loadMigrations","embedded","migratePgDatabase","resolveMigrationsFolder","runMigrations","handle","resolveMigrationsSchema","primarySearchPathSchema","resolveSearchPath","appendSearchPathToUrl","cancelWorkflowRun","cancelAgentSession","RunSource","runSource","sourceFromSpan","span","resolveRunSourceFromTraceContext","DiscoveredAgentRecord","AgentRegistryEntry","MESSAGE_EVENT_TYPE","syncAgentRegistry","records","getAgentByRoute","AgentSession","createSession","getSession","touchSession","setSessionTitle","nextSeq","appendEvent","listMessageEvents","countMessageEvents","AgentEventRecord","listSessionEvents","setSessionLiveMessage","clearLiveMessage","getSessionLiveMessage","LlmUsageRecordInput","recordLlmUsageFromAssistantMessage","usage","failAgentSession","AgentSessionStatus$1","agentSessionSummaryFromParts","messageCount","ranByUserName","gatewayPlatform","agentSessionRecordFromParts","gatewaySessionDetailFromParts","agentEventFromRow","AgentSessionStatus","AgentSessionSource","listAgentSessionsPaginated","resolveUserName","AgentSessionDetailInclude","buildAgentSessionDetail","include","session","messages","events","buildAgentSessionChatState","sinceSeq","live","DiscoveredSkillRecord","SkillRegistryEntry","syncSkillRegistry","TriggerAttachmentRegistryEntry","DiscoveredTriggerAttachmentRecord","syncTriggerAttachmentRegistry","CreateAgentAttachmentExecutionInput","createAgentAttachmentExecution","getTriggerRunForAgentSession","EPHEMERAL_TRIGGER_MODULE_FILE","UpsertEphemeralTriggerInput","Extract","upsertEphemeralTrigger","deleteEphemeralTrigger","isEphemeralTriggerActive","recordEphemeralTriggerExecution","selectActiveEphemeralScheduledAttachmentSlugs","selectActiveEphemeralCronAttachmentSlugs","listAgentTriggers","getOrCreateGatewayThreadSession","existingSessionId","DiscoveredWorkflowRecord","WorkflowRegistryEntry","syncWorkflowRegistry","WorkflowSubscriptionProfile","getWorkflowSubscription","listCredentialInstancesForAssignment","CreateWorkflowRunInput","CreateAttachmentExecutionInput","Exclude","createWorkflowRun","createPendingWorkflowRun","markWorkflowRunRunning","markWorkflowRunSleeping","markWorkflowRunWaitingHook","completeWorkflowRun","failWorkflowRun","recordWorkflowLlmUsage","finalizeCanceledWorkflowRun","createAttachmentExecution","createPendingAttachmentExecution","markAttachmentExecutionRunning","WorkflowRunDetailInclude","buildWorkflowRunDetail","run","steps","WorkflowEventRecord","EventLog","append","event","listReplay","createDatabaseEventLog","WorkflowHookRecord","HookStore","create","getByToken","markResumed","createDatabaseHookStore","TriggerRunDetailInclude","listTriggerRunsPaginated","buildTriggerRunDetail","Array","encryptCredentialPayload","plaintext","decryptCredentialPayload","setCredentialInstanceValue","value","OAuthCredentialTargets","projectNamesById","organization","ensureOAuthCredentialInstance","accountLabel","externalId","userLabel","targets","ensureKeystrokeCredentialInstance","projectName","EnqueueJobInput","ClaimedJob","JobSnapshot","enqueueJob","claimNextJob","workerId","markJobComplete","jobId","markJobFailed","scheduleJobRetry","delayMs","getJobByRunId","Client","AgentTool","AgentToolResult","Tool","MCP","McpCallToolOptions","AbortSignal","signal","McpTransport","McpAuthOptions","Record","headers","env","searchParams","McpHttpTransport","URL","type","url","transport","McpStdioTransport","command","args","cwd","stderr","McpDeclaredTool","name","title","description","inputSchema","McpDefinitionInput","TCredentials","fetch","RequestInit","key","credentials","auth","resolved","declaredTools","clientName","clientVersion","requestInit","McpDefinition","McpServerOptions","McpConnection","Promise","tools","callTool","toolName","options","close","McpStdioOptions","defineMcp","def","isMcp","value","connectMcpServer","connectMcpStdio","connectMcpDefinition","JsonSchemaObject","createToolName","serverName","normalizeInputSchema","schema","mcpToolsToAgentTools","client","p","CredentialInstanceRow","x","CredentialAssignmentRow","CREDENTIAL_SCOPE_TYPES","CredentialAssignmentSet","CredentialAssignmentTargetType","CredentialConsumer","CredentialConsumer$1","CredentialInput","CredentialList","CredentialRunContext","CredentialRunContext$1","CredentialScopeType","CredentialScopeType$1","CredentialSelectionOption","CredentialSelectionOption$1","OAuthAccessTokenRefreshParams","OAuthAccessTokenRefreshResult","OAuthAccessTokenRefresher","OAuthTokenAdapter","OAuthTokenAdapter$1","OAuthTokenRefreshRegistry","OAuthTokenRefreshRegistry$1","ResolvedCredentials","MCP","McpConnection","McpDefinition","McpDefinition$1","McpDefinitionInput","AgentTool","z","CredentialToolErrorCapture","tools","takeCredentialError","captureCredentialToolErrors","selectAssignedInstanceId","assignments","consumerId","credentialSlug","buildAssignmentSet","rows","loadCredentialAssignments","Promise","targetType","targetKey","options","withCredentialAssignments","context","ResolveKeystrokeInstanceIdResult","instanceId","scopeType","scopeId","ResolveKeystrokeInstanceIdOptions","ReadonlyArray","app","scopes","assignmentTarget","type","key","consumer","resolveKeystrokeInstanceId","ResolveCredentialRefOptions","ref","userId","canAccess","row","ResolveCredentialRefResult","error","status","resolveCredentialRef","canAssignCredentialInstance","projectId","canManageCredentialInstance","credentialScopePrefix","formatCredentialRef","slug","formatCredentialRefSuggestion","appSlug","ParsedCredentialRef","kind","id","parseCredentialRef","WorkflowSubscriptionProfile","workflowKey","enabled","CredentialRunContextInput","Record","Partial","subscription","orgId","credentialSelection","request","ToolCredentialResolver","T","resolve","requirements","buildCredentialRunContext","input","buildWorkflowRunContext","actor","CredentialBackend","ZodType","resolveApiKey","schema","getOAuthAccessToken","connectionId","accessToken","CreateLocalCredentialBackendOptions","_$_keystrokehq_shared0","tokenRefresh","CreatePlatformCredentialBackendOptions","platformUrl","workerToken","CreateCredentialResolverOptions","credentialBackend","oauthAdapter","CredentialResolver","createCredentialResolver","ResolveCredentialRequirementsOptions","resolveCredentialRequirements","ResolvedMcpTools","connection","resolveMcpTools","TCredentials","def","resolver","McpInput","Omit","defineMcp","credentials","auth","TRequirements","TResolved","NonNullable","ReturnType","resolved","parseResolvedCredentials","ResolveActionCredentialsOptions","resolveCredentials","contextOverride","resolveActionCredentials","MissingCredentialsError","Error","code","chainAttempted","constructor","NeedsSelectionError","OAuthNotConfiguredError","message","CredentialAccessDeniedError","CredentialError","isCredentialError","credentialScopeMatchesContext","formatCredentialErrorMessage","orgSlug","webUrl","connect","AgentConnectContext","resolveAgentConnectContext","stubOAuthTokenAdapter","createOAuthTokenRefreshRegistry","createLocalCredentialBackend","createPlatformCredentialBackend","isWorkerRuntime","NodeJS","ProcessEnv","env","createCredentialBackend","setProjectCredentialBackend","backend","getProjectCredentialBackend","createOAuthTokenAdapterFromBackend"],"sources":["../../database/dist/index.d.mts","../../mcp/dist/index.d.mts","../../credentials/dist/index.d.mts"],"mappings":";;;;;;;KAirQK8d,mBAAAA;EACHhS,KAAAA;EACAyM,QAAAA;EACAE,MAAAA;EACAhQ,QAAAA,EAAU0B,MAAM;AAAA;;;;cChrQJib,GAAAA;AAAAA,KACTC,kBAAAA;EACHE,MAAAA,GAASD,WAAW;AAAA;AAAA,KAEjBE,YAAAA;AAAAA,KACAC,cAAAA;EACHE,OAAAA,GAAUD,MAAAA;EACVE,GAAAA,GAAMF,MAAAA,kBDyqQNjd;ECxqQAod,YAAAA,GAAeH,MAAAA;AAAAA;AAAAA,KAEZI,gBAAAA;EACHE,IAAAA;EACAC,GAAAA,WAAcF,GAAAA;EACdG,SAAAA,GAAYV,YAAY;AAAA;AAAA,KAErBW,iBAAAA;EACHH,IAAAA;EACAI,OAAAA;EACAC,IAAAA;EACAC,GAAAA;EACAC,MAAAA;AAAAA;AAAAA,KAEGC,eAAAA;EACHC,IAAAA;EACAC,KAAAA;EACAC,WAAAA;EACAC,WAAAA,GAAclB,MAAM;AAAA;AAAA,KAEjBmB,kBAAAA,gBAAkCnB,MAAAA;EACrCuB,GAAAA;EACAR,IAAAA;EACAP,SAAAA,EAAWJ,gBAAAA,GAAmBK,iBAAAA;EAC9Be,WAAAA;EACAC,IAAAA,IAAQC,QAAAA,EAAUN,YAAAA,KAAiBrB,cAAAA,EA1B7BC;EA2BN2B,aAAAA,YAAyBb,eAAAA;EACzBc,UAAAA;EACAC,aAAAA;EACAR,KAAAA,UAAeA,KAAAA;EACfS,WAAAA,GAAcR,WAAAA;AAAAA;AAAAA,KAEXS,aAAAA,gBAA6B/B,MAAAA,mBAAyBmB,kBAAAA,CAAmBC,YAAAA;EAAAA,UAClE1B,GAAAA;AAAAA;AAAAA,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A,EAAcF,CAAAA,EAAGlC,QAAAA,EAAUpD,kBAAAA,GAAuBmC,OAAAA,CAAQnB,mBAAAA,CAAoBsE,CAAAA;AAAAA;AAAAA"}
1
+ {"version":3,"file":"index-Cq2F2XdS.d.mts","names":["_$drizzle_orm_node_postgres0","Pool","MigrationConfig","MigrationMeta","TracingSink","AgentTriggerType","CredentialAuthKind","CredentialScopeType","HistoryAgentSessionDetail","HistoryRun","HistoryRunKind","HistoryRunStatus","HistoryWorkflowRunDetail","RunSourceKind","WorkflowEventType","DEFAULT_DATABASE_URL","runWithTenantScope","T","Promise","tenantId","fn","getServerTenantScopeId","DEFAULT_PROJECT_ID","runWithProjectScope","projectId","getBoundProjectScopeId","getProjectScopeId","PostgresConnectionConfig","host","port","database","user","password","ssl","qualifyConnectionUser","NodeJS","ProcessEnv","env","buildPostgresUrl","config","parsePostgresUrl","url","resolvePostgresConfigFromEnv","resolvePostgresUrlFromEnv","resolveProjectDatabaseUrlFromEnv","resolveDatabaseUrlFromEnv","closeDatabase","StoredRunSourceKind$1","agentSessions","_$drizzle_orm_pg_core0","PgColumn","Date","PgTableWithColumns","name","schema","columns","id","tableName","dataType","columnType","data","driverParam","notNull","hasDefault","isPrimaryKey","isAutoincrement","hasRuntimeDefault","enumValues","baseColumn","identity","generated","agentId","sourceKind","$type","sourceId","parentSpanId","ranByUserId","title","canceledAt","totalDurationMs","liveMessage","createdAt","updatedAt","deletedAt","dialect","UsageRunKind","TriggerScheduleKind","triggerSchedules","attachmentSlug","kind","schedule","nextRunAt","enabled","TriggerRunType","triggerRuns","attachmentId","sourcePath","triggerType","payload","triggeredAt","WorkflowRunStatus","WorkflowRunTrigger","StoredRunSourceKind","workflowRuns","workflowSlug","subscriptionId","triggerRunId","parentWorkflowRunId","status","trigger","startedAt","finishedAt","input","output","error","WorkflowHookStatus","workflowHooks","hookId","runId","token","correlationId","resumedAt","CredentialAssignmentTargetType","credentialAssignments","targetType","targetKey","consumerId","credentialSlug","instanceId","JobKind","JobStatus","JobTrigger","TraceSpanKind","TraceSpanStatus","traceSpans","traceId","refId","metadata","TraceLogLevel","TraceLogSource","traceLogs","spanId","seq","level","message","source","agents","slug","description","route","moduleFile","model","systemPrompt","toolCount","credentialCount","appSlugs","registeredAt","agentEvents","sessionId","eventType","StoredTriggerSourceSlugFields","key","StoredTriggerSource","Record","endpoint","requestSchema","filterSchema","code","storedTriggerSourceSlug","normalizeStoredTriggerSource","StoredTriggerTargetKind","StoredTriggerOrigin","StoredTriggerLifecycleStatus","StoredTriggerLifecycle","maxExecutions","until","executionCount","triggerAttachments","targetKind","agentSlug","origin","prompt","lifecycle","createdBySessionId","workflowEvents","type","credentialInstances","appSlug","scopeType","scopeId","label","isDefault","authKind","ciphertext","connectionId","sharedConnectionId","grantedScopes","SlackGatewayMode","StoredGatewaySource","mode","credentialKey","channelIds","subscribeOnMention","channelName","channelKind","gatewayAttachments","platform","teamId","channelId","gatewayAttachmentKeyForChannel","gatewayThreadSessions","threadId","skills","workflows","subscribable","workflowSubscriptions","userId","resourceActivityKinds","ResourceActivityKind","resourceActivity","resourceKind","resourceId","lastOpenedAt","AgentRow","$inferSelect","listActiveAgents","projectIds","options","selectAgentBySlug","selectActiveAgentsByIds","ids","selectActiveAgentById","resolveAgentProjectId","AgentSessionRow","AgentSessionSourceFilter","selectAgentSessionById","addAgentSessionDuration","deltaMs","clearAgentSessionCancellation","AgentEventRow","TriggerAttachmentRow","getTriggerAttachmentBySlug","listActiveTriggerAttachments","selectWebhookTriggerAttachments","selectEphemeralTriggerAttachmentsByAgentSlug","selectTriggerAttachmentsByAgentSlug","selectEphemeralTriggerAttachments","TriggerScheduleRow","UpsertTriggerScheduleValues","selectTriggerScheduleBySlug","upsertTriggerSchedule","values","disableAllTriggerSchedules","now","disableTriggerSchedulesNotInSlugs","attachmentSlugs","listEnabledTriggerSchedules","claimDueTriggerSchedules","resolveNextRunAt","limit","claimDueTriggerSchedulesForOrg","listTriggerSchedulesBySlugs","triggerRunSummaryFromRow","TriggerRunRow","WorkflowRunRow","row","workflowRun","agentSession","triggerRunRecordFromRow","WorkflowEventRow","AppendWorkflowEventValues","listStepCompletedEvents","TraceLogRow","TraceSpanRow","createDatabaseTracingSink","flushNow","TraceTriggerSummary","TraceGatewaySummary","gatewayAttachmentId","gatewayAttachmentKey","TraceResponse","gateway","spans","logs","getTraceForWorkflowRun","workflowRunId","getTraceForTriggerRun","getTraceForAgentSession","workflowRunSummaryFromRow","workflowRunRecordFromRow","triggerRunDetailFromRow","workflowStepRunFromEvent","actionKey","completedAt","traceResponseToJson","trace","selectWorkflowRunById","resolveWorkflowRunProjectId","listWorkflowRunsByWorkflowSlug","selectWorkflowRunForWorkflow","listWorkflowRunsPaginated","ReturnType","cursor","items","nextCursor","WorkflowHookRow","InsertWorkflowHookValues","requeueExpiredLeases","GatewayAttachmentRow","GatewayChannelConflictError","Error","ownerProjectId","constructor","getActiveOrgGatewayAttachmentByChannel","getActiveOrgGatewayAttachmentByTeamAndChannel","getActiveGatewayAttachmentByChannel","listActiveGatewayAttachments","ActiveGatewayBinding","listActiveOrgGatewayBindingsByPlatform","listActiveGatewayAttachmentsByAgentSlug","softDeleteGatewayAttachmentsForAgentPlatformTeam","listActiveGatewayAttachmentsByPlatform","softDeleteGatewayAttachmentByChannel","upsertGatewayAttachmentByChannel","getGatewayAttachmentBySlug","GatewayThreadSessionRow","selectGatewayThreadSessionByThreadId","WorkflowRow","listActiveWorkflows","selectActiveWorkflowBySlug","selectActiveWorkflowsByIds","selectActiveWorkflowById","SkillRow","listActiveSkills","selectActiveSkillsByIds","selectActiveSkillById","WorkflowSubscriptionRow","InsertWorkflowSubscriptionValues","UpdateWorkflowSubscriptionValues","selectWorkflowSubscriptionById","selectWorkflowSubscriptionByWorkflowAndUser","listWorkflowSubscriptionsByWorkflowSlug","listEnabledWorkflowSubscriptionsByWorkflowSlug","insertWorkflowSubscription","updateWorkflowSubscriptionById","deleteWorkflowSubscriptionById","ResourceActivityRow","TouchResourceActivityInput","touchResourceActivity","listRecentResourceActivity","selectWorkflowLastRunAtByIds","Map","workflowIds","selectAgentLastRunAtByIds","agentIds","ProjectResourceCounts","agentCount","workflowCount","skillCount","selectProjectResourceCounts","ListHistoryRunsOptions","HistoryRunCore","Omit","buildHistoryWorkflowRunDetail","buildHistoryAgentSessionDetail","listHistoryRuns","findHistoryRunCore","CredentialInstanceRow","InsertCredentialInstanceValues","listAllCredentialInstances","listCredentialInstancesByConnectionId","selectCredentialInstanceById","listCredentialInstancesByScope","selectCredentialInstancesForScope","upsertCredentialInstance","deleteCredentialInstanceById","clearCredentialInstanceDefaults","exceptId","CredentialAssignmentRow","UpsertCredentialAssignmentValues","listCredentialAssignmentsByTarget","selectCredentialAssignmentById","upsertCredentialAssignment","deleteCredentialAssignmentById","listRecentWorkflowStepConsumers","runLimit","listDistinctAssignmentConsumerIds","createPgDb","NodePgDatabase","pool","usageRecords","runKind","quantity","unit","amount","jobs","targetId","scheduledAt","attempt","maxAttempts","leasedBy","leaseExpiresAt","$client","Database","DatabaseDialect","PgPool","PgDatabase","SqliteDatabase","AppDatabase","DatabaseHandle","db","searchPath","close","InitDatabaseOptions","migrate","migrationsFolder","max","closeAllProjectDatabasePools","isDatabaseInitialized","getDatabaseHandle","initDatabase","RunWithProjectDatabaseOptions","runWithProjectDatabase","ConnectionOptions","PgConnectionOptions","SqliteConnectionOptions","createPgConnection","PostgresCancelHandler","PostgresCancelChannel","publishCancel","subscribeCancel","handler","createPostgresCancelChannel","connectionString","channel","createSqliteConnection","createConnection","resolveSqlitePath","inferDialect","override","adaptPgMigrationsForSearchPath","migrations","loadMigrations","embedded","migratePgDatabase","resolveMigrationsFolder","runMigrations","handle","resolveMigrationsSchema","primarySearchPathSchema","resolveSearchPath","appendSearchPathToUrl","cancelWorkflowRun","cancelAgentSession","RunSource","runSource","sourceFromSpan","span","resolveRunSourceFromTraceContext","DiscoveredAgentRecord","AgentRegistryEntry","MESSAGE_EVENT_TYPE","syncAgentRegistry","records","getAgentByRoute","AgentSession","createSession","getSession","touchSession","setSessionTitle","nextSeq","appendEvent","listMessageEvents","countMessageEvents","AgentEventRecord","listSessionEvents","setSessionLiveMessage","clearLiveMessage","getSessionLiveMessage","LlmUsageRecordInput","recordLlmUsageFromAssistantMessage","usage","failAgentSession","AgentSessionStatus$1","agentSessionSummaryFromParts","messageCount","ranByUserName","gatewayPlatform","agentSessionRecordFromParts","gatewaySessionDetailFromParts","agentEventFromRow","AgentSessionStatus","AgentSessionSource","listAgentSessionsPaginated","resolveUserName","AgentSessionDetailInclude","buildAgentSessionDetail","include","session","messages","events","buildAgentSessionChatState","sinceSeq","live","DiscoveredSkillRecord","SkillRegistryEntry","syncSkillRegistry","TriggerAttachmentRegistryEntry","DiscoveredTriggerAttachmentRecord","syncTriggerAttachmentRegistry","CreateAgentAttachmentExecutionInput","createAgentAttachmentExecution","getTriggerRunForAgentSession","EPHEMERAL_TRIGGER_MODULE_FILE","UpsertEphemeralTriggerInput","Extract","upsertEphemeralTrigger","deleteEphemeralTrigger","isEphemeralTriggerActive","recordEphemeralTriggerExecution","selectActiveEphemeralScheduledAttachmentSlugs","selectActiveEphemeralCronAttachmentSlugs","listAgentTriggers","getOrCreateGatewayThreadSession","existingSessionId","DiscoveredWorkflowRecord","WorkflowRegistryEntry","syncWorkflowRegistry","WorkflowSubscriptionProfile","getWorkflowSubscription","listCredentialInstancesForAssignment","CreateWorkflowRunInput","CreateAttachmentExecutionInput","Exclude","createWorkflowRun","createPendingWorkflowRun","markWorkflowRunRunning","markWorkflowRunSleeping","markWorkflowRunWaitingHook","completeWorkflowRun","failWorkflowRun","recordWorkflowLlmUsage","finalizeCanceledWorkflowRun","createAttachmentExecution","createPendingAttachmentExecution","markAttachmentExecutionRunning","WorkflowRunDetailInclude","buildWorkflowRunDetail","run","steps","WorkflowEventRecord","EventLog","append","event","listReplay","createDatabaseEventLog","WorkflowHookRecord","HookStore","create","getByToken","markResumed","createDatabaseHookStore","TriggerRunDetailInclude","listTriggerRunsPaginated","buildTriggerRunDetail","Array","encryptCredentialPayload","plaintext","decryptCredentialPayload","setCredentialInstanceValue","value","OAuthCredentialTargets","projectNamesById","organization","ensureOAuthCredentialInstance","accountLabel","externalId","userLabel","targets","ensureKeystrokeCredentialInstance","projectName","EnqueueJobInput","ClaimedJob","JobSnapshot","enqueueJob","claimNextJob","workerId","markJobComplete","jobId","markJobFailed","scheduleJobRetry","delayMs","getJobByRunId","Client","AgentTool","AgentToolResult","Tool","MCP","McpCallToolOptions","AbortSignal","signal","McpTransport","McpAuthOptions","Record","headers","env","searchParams","McpHttpTransport","URL","type","url","transport","McpStdioTransport","command","args","cwd","stderr","McpDeclaredTool","name","title","description","inputSchema","McpDefinitionInput","TCredentials","fetch","RequestInit","key","credentials","auth","resolved","declaredTools","clientName","clientVersion","requestInit","McpDefinition","McpServerOptions","McpConnection","Promise","tools","callTool","toolName","options","close","McpStdioOptions","defineMcp","def","isMcp","value","connectMcpServer","connectMcpStdio","connectMcpDefinition","JsonSchemaObject","createToolName","serverName","normalizeInputSchema","schema","mcpToolsToAgentTools","client","p","CredentialInstanceRow","x","CredentialAssignmentRow","CREDENTIAL_SCOPE_TYPES","CredentialAssignmentSet","CredentialAssignmentTargetType","CredentialConsumer","CredentialConsumer$1","CredentialInput","CredentialList","CredentialRunContext","CredentialRunContext$1","CredentialScopeType","CredentialScopeType$1","CredentialSelectionOption","CredentialSelectionOption$1","OAuthAccessTokenRefreshParams","OAuthAccessTokenRefreshResult","OAuthAccessTokenRefresher","OAuthTokenAdapter","OAuthTokenAdapter$1","OAuthTokenRefreshRegistry","OAuthTokenRefreshRegistry$1","ResolvedCredentials","MCP","McpConnection","McpDefinition","McpDefinition$1","McpDefinitionInput","AgentTool","z","CredentialToolErrorCapture","tools","takeCredentialError","captureCredentialToolErrors","selectAssignedInstanceId","assignments","consumerId","credentialSlug","buildAssignmentSet","rows","loadCredentialAssignments","Promise","targetType","targetKey","options","withCredentialAssignments","context","ResolveKeystrokeInstanceIdResult","instanceId","scopeType","scopeId","ResolveKeystrokeInstanceIdOptions","ReadonlyArray","app","scopes","assignmentTarget","type","key","consumer","resolveKeystrokeInstanceId","ResolveCredentialRefOptions","ref","userId","canAccess","row","ResolveCredentialRefResult","error","status","resolveCredentialRef","canAssignCredentialInstance","projectId","canManageCredentialInstance","credentialScopePrefix","formatCredentialRef","slug","formatCredentialRefSuggestion","appSlug","ParsedCredentialRef","kind","id","parseCredentialRef","WorkflowSubscriptionProfile","workflowKey","enabled","CredentialRunContextInput","Record","Partial","subscription","orgId","credentialSelection","request","ToolCredentialResolver","T","resolve","requirements","buildCredentialRunContext","input","buildWorkflowRunContext","actor","CredentialBackend","ZodType","resolveApiKey","schema","getOAuthAccessToken","connectionId","accessToken","CreateLocalCredentialBackendOptions","_$_keystrokehq_shared0","tokenRefresh","CreatePlatformCredentialBackendOptions","platformUrl","workerToken","CreateCredentialResolverOptions","credentialBackend","oauthAdapter","CredentialResolver","createCredentialResolver","ResolveCredentialRequirementsOptions","resolveCredentialRequirements","ResolvedMcpTools","connection","resolveMcpTools","TCredentials","def","resolver","McpInput","Omit","defineMcp","credentials","auth","TRequirements","TResolved","NonNullable","ReturnType","resolved","parseResolvedCredentials","ResolveActionCredentialsOptions","resolveCredentials","contextOverride","resolveActionCredentials","MissingCredentialsError","Error","code","chainAttempted","constructor","NeedsSelectionError","OAuthNotConfiguredError","message","CredentialAccessDeniedError","CredentialError","isCredentialError","credentialScopeMatchesContext","formatCredentialErrorMessage","orgSlug","webUrl","connect","AgentConnectContext","resolveAgentConnectContext","stubOAuthTokenAdapter","createOAuthTokenRefreshRegistry","createLocalCredentialBackend","createPlatformCredentialBackend","isWorkerRuntime","NodeJS","ProcessEnv","env","createCredentialBackend","setProjectCredentialBackend","backend","getProjectCredentialBackend","createOAuthTokenAdapterFromBackend"],"sources":["../../database/dist/index.d.mts","../../mcp/dist/index.d.mts","../../credentials/dist/index.d.mts"],"mappings":";;;;;;;KAwtQK+d,mBAAAA;EACHjS,KAAAA;EACA0M,QA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Z4Dj_O.cjs");
3
3
  const require_env_api_keys = require("./env-api-keys-BFptfIIs.cjs");
4
4
  const require_event_stream = require("./event-stream-CS-ls7wC.cjs");
5
5
  const require_json_parse = require("./json-parse-TT8Vr6d3.cjs");
@@ -27563,4 +27563,4 @@ function mapChatStopReason(reason) {
27563
27563
  exports.streamMistral = streamMistral;
27564
27564
  exports.streamSimpleMistral = streamSimpleMistral;
27565
27565
 
27566
- //# sourceMappingURL=mistral-HS6Ekkp2.cjs.map
27566
+ //# sourceMappingURL=mistral-BUpUX0vh.cjs.map