@keystrokehq/keystroke 0.0.172 → 0.0.174

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 (91) hide show
  1. package/dist/action.cjs +2 -3
  2. package/dist/action.d.cts +3 -3
  3. package/dist/action.d.mts +3 -3
  4. package/dist/action.mjs +2 -2
  5. package/dist/agent.cjs +3 -3
  6. package/dist/agent.d.cts +2 -2
  7. package/dist/agent.d.mts +2 -2
  8. package/dist/agent.mjs +3 -3
  9. package/dist/app.cjs +72 -0
  10. package/dist/app.cjs.map +1 -0
  11. package/dist/app.d.cts +58 -0
  12. package/dist/app.d.cts.map +1 -0
  13. package/dist/app.d.mts +58 -0
  14. package/dist/app.d.mts.map +1 -0
  15. package/dist/app.mjs +71 -0
  16. package/dist/app.mjs.map +1 -0
  17. package/dist/client.cjs +3 -1
  18. package/dist/client.cjs.map +1 -1
  19. package/dist/client.d.cts +6 -0
  20. package/dist/client.d.cts.map +1 -1
  21. package/dist/client.d.mts +6 -0
  22. package/dist/client.d.mts.map +1 -1
  23. package/dist/client.mjs +3 -1
  24. package/dist/client.mjs.map +1 -1
  25. package/dist/config.d.cts +1 -1
  26. package/dist/config.d.mts +1 -1
  27. package/dist/credentials.cjs +2 -3
  28. package/dist/credentials.d.cts +2 -2
  29. package/dist/credentials.d.mts +2 -2
  30. package/dist/credentials.mjs +2 -2
  31. package/dist/{dist-Dz0i7l87.cjs → dist-BLADLFrG.cjs} +41 -63
  32. package/dist/dist-BLADLFrG.cjs.map +1 -0
  33. package/dist/{dist-bGasqeNy.mjs → dist-BX0Upt63.mjs} +41 -63
  34. package/dist/dist-BX0Upt63.mjs.map +1 -0
  35. package/dist/{dist--dtTaEXy.cjs → dist-Bwkl4vwe.cjs} +8 -10
  36. package/dist/dist-Bwkl4vwe.cjs.map +1 -0
  37. package/dist/{dist-BF5yN9sB.mjs → dist-CFy63Npi.mjs} +30 -50
  38. package/dist/dist-CFy63Npi.mjs.map +1 -0
  39. package/dist/{dist--zLOSTcG.cjs → dist-DEwBt6Ee.cjs} +31 -63
  40. package/dist/dist-DEwBt6Ee.cjs.map +1 -0
  41. package/dist/{dist-DT5CSOQc.mjs → dist-g-XZ7Tbo.mjs} +8 -10
  42. package/dist/dist-g-XZ7Tbo.mjs.map +1 -0
  43. package/dist/{index-1uEWGKCk.d.mts → index-B8ZRIgPK.d.mts} +12 -9
  44. package/dist/index-B8ZRIgPK.d.mts.map +1 -0
  45. package/dist/{index-s53YoTdO.d.cts → index-CDWAJRJD.d.cts} +2 -2
  46. package/dist/{index-BDPrsenN.d.mts.map → index-CDWAJRJD.d.cts.map} +1 -1
  47. package/dist/{index-BPC4loSM.d.mts → index-CITVigQS.d.mts} +2 -2
  48. package/dist/index-CITVigQS.d.mts.map +1 -0
  49. package/dist/{index-uWH8vj_f.d.cts → index-CUYwOWCh.d.cts} +4 -4
  50. package/dist/{index-uWH8vj_f.d.cts.map → index-CUYwOWCh.d.cts.map} +1 -1
  51. package/dist/{index-DvJmjY4X.d.mts → index-DPyUP9U_.d.mts} +4 -4
  52. package/dist/{index-DvJmjY4X.d.mts.map → index-DPyUP9U_.d.mts.map} +1 -1
  53. package/dist/{index-BDPrsenN.d.mts → index-DT9Ml-7N.d.mts} +2 -2
  54. package/dist/{index-s53YoTdO.d.cts.map → index-DT9Ml-7N.d.mts.map} +1 -1
  55. package/dist/{index-B9hlxKDT.d.cts → index-DjLUdkRo.d.cts} +12 -9
  56. package/dist/index-DjLUdkRo.d.cts.map +1 -0
  57. package/dist/{index-DAzE8I-g.d.cts → index-hf0OTB6M.d.cts} +14 -16
  58. package/dist/index-hf0OTB6M.d.cts.map +1 -0
  59. package/dist/{index-DAzE8I-g.d.mts → index-hf0OTB6M.d.mts} +14 -16
  60. package/dist/index-hf0OTB6M.d.mts.map +1 -0
  61. package/dist/{index-Ugto82oH.d.cts → index-y_2btA4s.d.cts} +2 -2
  62. package/dist/index-y_2btA4s.d.cts.map +1 -0
  63. package/dist/{mistral-GXPqP1mo.cjs → mistral-CC5EGzH4.cjs} +2 -2
  64. package/dist/{mistral-GXPqP1mo.cjs.map → mistral-CC5EGzH4.cjs.map} +1 -1
  65. package/dist/{mistral-D56Ydau-.mjs → mistral-DbKZmAHf.mjs} +2 -2
  66. package/dist/{mistral-D56Ydau-.mjs.map → mistral-DbKZmAHf.mjs.map} +1 -1
  67. package/dist/{sse-U_LwOMpt.mjs → sse-DqYCbW54.mjs} +2 -2
  68. package/dist/{sse-U_LwOMpt.mjs.map → sse-DqYCbW54.mjs.map} +1 -1
  69. package/dist/{sse-D1mtozXN.cjs → sse-dAxMgDEB.cjs} +2 -2
  70. package/dist/{sse-D1mtozXN.cjs.map → sse-dAxMgDEB.cjs.map} +1 -1
  71. package/dist/trigger.cjs +1 -1
  72. package/dist/trigger.d.cts +3 -3
  73. package/dist/trigger.d.mts +3 -3
  74. package/dist/trigger.mjs +1 -1
  75. package/dist/workflow.cjs +1 -1
  76. package/dist/workflow.d.cts +2 -2
  77. package/dist/workflow.d.mts +2 -2
  78. package/dist/workflow.mjs +1 -1
  79. package/package.json +7 -1
  80. package/dist/dist--dtTaEXy.cjs.map +0 -1
  81. package/dist/dist--zLOSTcG.cjs.map +0 -1
  82. package/dist/dist-BF5yN9sB.mjs.map +0 -1
  83. package/dist/dist-DT5CSOQc.mjs.map +0 -1
  84. package/dist/dist-Dz0i7l87.cjs.map +0 -1
  85. package/dist/dist-bGasqeNy.mjs.map +0 -1
  86. package/dist/index-1uEWGKCk.d.mts.map +0 -1
  87. package/dist/index-B9hlxKDT.d.cts.map +0 -1
  88. package/dist/index-BPC4loSM.d.mts.map +0 -1
  89. package/dist/index-DAzE8I-g.d.cts.map +0 -1
  90. package/dist/index-DAzE8I-g.d.mts.map +0 -1
  91. package/dist/index-Ugto82oH.d.cts.map +0 -1
@@ -1,6 +1,6 @@
1
- const require_dist = require("./dist--zLOSTcG.cjs");
1
+ const require_dist = require("./dist-DEwBt6Ee.cjs");
2
2
  const require_dist$1 = require("./dist-CLr3qkxM.cjs");
3
- const require_dist$2 = require("./dist-Dz0i7l87.cjs");
3
+ const require_dist$2 = require("./dist-BLADLFrG.cjs");
4
4
  let zod = require("zod");
5
5
  let node_async_hooks = require("node:async_hooks");
6
6
  //#region ../workflow/dist/index.mjs
@@ -330,11 +330,11 @@ async function runDurableStep(state, options) {
330
330
  }
331
331
  }));
332
332
  }
333
- function withCredentialChainOverride(requirements, chain) {
334
- if (!requirements || !chain) return requirements;
333
+ function withCredentialScopeOverride(requirements, scope) {
334
+ if (!requirements || !scope) return requirements;
335
335
  return require_dist.normalizeCredentialList(requirements).map((requirement) => ({
336
336
  ...requirement,
337
- chain
337
+ scope
338
338
  }));
339
339
  }
340
340
  /** Builds the per-run action runner; durability lives in {@link runDurableStep}. */
@@ -347,8 +347,7 @@ function createActionRunner(state, options = {}) {
347
347
  replayMessage: "action replayed from checkpoint",
348
348
  parseCached: (cached) => action.output.parse(cached),
349
349
  execute: async () => {
350
- const requirements = withCredentialChainOverride(require_dist.getActionCredentialRequirements(action), runOptions?.credentialChain);
351
- const contextOverride = runOptions?.credentialSelection ? { selection: runOptions.credentialSelection } : void 0;
350
+ const requirements = withCredentialScopeOverride(require_dist.getActionCredentialRequirements(action), runOptions?.credentialScope);
352
351
  return require_dist.executeAction(action, input, requirements?.length ? await require_dist$2.resolveActionCredentials(requirements, {
353
352
  resolveCredentials: options.resolveCredentials,
354
353
  context: options.credentialContext,
@@ -356,8 +355,7 @@ function createActionRunner(state, options = {}) {
356
355
  consumer: {
357
356
  kind: "action",
358
357
  name: action.slug
359
- },
360
- contextOverride
358
+ }
361
359
  }) : {});
362
360
  }
363
361
  });
@@ -595,4 +593,4 @@ Object.defineProperty(exports, "serializeWorkflowError", {
595
593
  }
596
594
  });
597
595
 
598
- //# sourceMappingURL=dist--dtTaEXy.cjs.map
596
+ //# sourceMappingURL=dist-Bwkl4vwe.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dist-Bwkl4vwe.cjs","names":["z","SandboxDefinitionSchema","withSpan","logSystem","captureConsole","normalizeCredentialList","getActionCredentialRequirements","executeAction","resolveActionCredentials","AsyncLocalStorage","registerWorkflowRunGetter","getRunSignal","getWorkflowRunHandle"],"sources":["../../workflow/dist/index.mjs"],"sourcesContent":["import { z } from \"zod\";\nimport { SandboxDefinitionSchema } from \"@keystrokehq/sandbox\";\nimport { executeAction, getActionCredentialRequirements, getRunSignal, getWorkflowRunHandle, normalizeCredentialList, registerWorkflowRunGetter } 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\tsandbox: SandboxDefinitionSchema.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();\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 () => {\n\t\t\tconst requirements = withCredentialScopeOverride(getActionCredentialRequirements(action), runOptions?.credentialScope);\n\t\t\treturn executeAction(action, input, 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}\n\t\t\t}) : {});\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: () => 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: () => 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});\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":";;;;;;AAOA,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,SAASC,eAAAA,wBAAwB,SAAS;CAC1C,OAAO;CACP,QAAQ;CACR,KAAKD,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,OA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D,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,SAASQ,aAAAA,qBAAqB;CACpC,IAAI,CAAC,QAAQ,WAAW,MAAM,IAAI,MAAM,mGAAmG;CAC3I,OAAO,OAAO,UAAU;EACvB;EACA,GAAG;CACJ,CAAC;AACF"}
@@ -866,32 +866,18 @@ const CredentialAuthKindSchema = z.enum([
866
866
  "oauth_managed",
867
867
  "keystroke"
868
868
  ]);
869
- /** Where a credential instance is stored (`credential_instances.scope_type`). */
870
- const CredentialScopeTypeSchema = z.enum([
871
- "organization",
872
- "project",
873
- "user"
874
- ]);
875
869
  /**
876
- * Resolution chain step when an action/tool looks up credentials.
877
- * `selection` uses explicit instance ids; other levels map to {@link CredentialScopeType}.
870
+ * Where a credential instance is stored (`credential_instances.scope_type`), and the only thing an
871
+ * action/tool can pin via `.scope(...)`. There is no resolution chain: when no scope is pinned, the
872
+ * resolver tries the project default, then the org default, then throws.
878
873
  */
879
- const CredentialScopeLevelSchema = z.enum([
880
- "selection",
874
+ const CredentialScopeTypeSchema = z.enum([
881
875
  "organization",
882
876
  "project",
883
877
  "user"
884
878
  ]);
885
879
  CredentialAuthKindSchema.options;
886
- CredentialScopeTypeSchema.options;
887
- const CREDENTIAL_SCOPE_LEVELS = CredentialScopeLevelSchema.options;
888
- /** Default chain when `credential.static(...).scope()` is called with no args. */
889
- const DEFAULT_CREDENTIAL_RESOLUTION_CHAIN = ["organization", "project"];
890
- const CREDENTIAL_SCOPE_LEVEL_TO_SCOPE_TYPE = {
891
- organization: "organization",
892
- project: "project",
893
- user: "user"
894
- };
880
+ const CREDENTIAL_SCOPE_TYPES = CredentialScopeTypeSchema.options;
895
881
  /** Scope of a platform app credential (maps to `credential_instances.scope_type`). */
896
882
  const AppCredentialScopeSchema = z.enum([
897
883
  "user",
@@ -1015,7 +1001,14 @@ const KeystrokeCredentialSchema = z.object({
1015
1001
  z.object({
1016
1002
  app: z.string().trim().min(1),
1017
1003
  tool: z.string().trim().min(1),
1018
- arguments: z.record(z.string(), z.unknown()).default({})
1004
+ arguments: z.record(z.string(), z.unknown()).default({}),
1005
+ /**
1006
+ * Resolved credential instance to execute against. When set, the platform executes that exact
1007
+ * connection (scoped to the caller's org); when omitted it resolves the app's instance by scope.
1008
+ */
1009
+ instanceId: z.string().trim().min(1).optional(),
1010
+ /** Pinned provider toolkit version, sourced from the app definition; forwarded to the provider. */
1011
+ version: z.string().trim().min(1)
1019
1012
  });
1020
1013
  const TeamRequestTypeSchema = z.enum([
1021
1014
  "org-deletion",
@@ -1040,12 +1033,12 @@ function createRef(kind, key, schema, options) {
1040
1033
  key,
1041
1034
  schema,
1042
1035
  ...tokenField !== void 0 ? { tokenField } : {},
1043
- scope(...chain) {
1036
+ scope(scope) {
1044
1037
  return {
1045
1038
  key,
1046
1039
  kind,
1047
1040
  schema,
1048
- chain: chain.length > 0 ? chain : DEFAULT_CREDENTIAL_RESOLUTION_CHAIN,
1041
+ scope,
1049
1042
  ...tokenField !== void 0 ? { tokenField } : {}
1050
1043
  };
1051
1044
  }
@@ -1076,7 +1069,7 @@ function normalizeCredentialList(list) {
1076
1069
  return list.map((item) => toCredentialRequirement(item));
1077
1070
  }
1078
1071
  function isCredentialRequirement(item) {
1079
- return "chain" in item;
1072
+ return typeof item.scope !== "function";
1080
1073
  }
1081
1074
  function toCredentialRequirement(item) {
1082
1075
  if (isCredentialRequirement(item)) return item;
@@ -1084,7 +1077,6 @@ function toCredentialRequirement(item) {
1084
1077
  key: item.key,
1085
1078
  kind: item.kind,
1086
1079
  schema: item.schema,
1087
- chain: DEFAULT_CREDENTIAL_RESOLUTION_CHAIN,
1088
1080
  ...item.tokenField !== void 0 ? { tokenField: item.tokenField } : {}
1089
1081
  };
1090
1082
  }
@@ -2250,19 +2242,13 @@ function registerWorkflowRunGetter(fn) {
2250
2242
  function getWorkflowRunHandle() {
2251
2243
  return registry().getter?.();
2252
2244
  }
2253
- function buildSelectionForAction(action, instanceId) {
2254
- if (!action.credentials?.length) return {};
2255
- const requirements = normalizeCredentialList(action.credentials);
2256
- return Object.fromEntries(requirements.map((requirement) => [requirement.key, instanceId]));
2257
- }
2258
2245
  function executeStep(state) {
2259
2246
  if (state.input === void 0) throw new Error(`Step "${state.action.slug}" has no input. Call .run(input) before awaiting or chaining .scope().`);
2260
2247
  const handle = getWorkflowRunHandle();
2261
2248
  if (!handle) throw new Error(`Step "${state.action.slug}" must run inside a workflow or be called as .run(input, credentials) in tests.`);
2262
2249
  return handle.actionRunner(state.action, state.input, {
2263
2250
  id: state.id,
2264
- credentialChain: state.chain,
2265
- credentialSelection: state.selection
2251
+ credentialScope: state.scope
2266
2252
  });
2267
2253
  }
2268
2254
  function isStepInvocation(value) {
@@ -2270,20 +2256,10 @@ function isStepInvocation(value) {
2270
2256
  }
2271
2257
  function createStepInvocation(state) {
2272
2258
  return {
2273
- scope(...chain) {
2259
+ scope(scope) {
2274
2260
  return createStepInvocation({
2275
2261
  ...state,
2276
- chain: chain.length > 0 ? chain : state.chain
2277
- });
2278
- },
2279
- select(instanceIdOrMap) {
2280
- const nextSelection = typeof instanceIdOrMap === "string" ? buildSelectionForAction(state.action, instanceIdOrMap) : instanceIdOrMap;
2281
- return createStepInvocation({
2282
- ...state,
2283
- selection: {
2284
- ...state.selection,
2285
- ...nextSelection
2286
- }
2262
+ scope
2287
2263
  });
2288
2264
  },
2289
2265
  run(input) {
@@ -2315,11 +2291,15 @@ function attachStepApi(action) {
2315
2291
  input
2316
2292
  });
2317
2293
  },
2318
- scope(...chain) {
2319
- return createStepInvocation({
2320
- action: stepAction,
2321
- input: void 0,
2322
- chain
2294
+ scope(scope) {
2295
+ if (!action.credentials) return attachStepApi(action);
2296
+ const credentials = normalizeCredentialList(action.credentials).map((requirement) => ({
2297
+ ...requirement,
2298
+ scope
2299
+ }));
2300
+ return attachStepApi({
2301
+ ...action,
2302
+ credentials
2323
2303
  });
2324
2304
  }
2325
2305
  };
@@ -2374,6 +2354,6 @@ function resolveActionTool(action, options) {
2374
2354
  };
2375
2355
  }
2376
2356
  //#endregion
2377
- export { mcpEntityId as C, toolParameters as E, isCredentialInput as S, toCredentialRequirement as T, CREDENTIAL_SCOPE_LEVEL_TO_SCOPE_TYPE as _, getActionCredentialRequirements as a, credentialInputSchema as b, isAction as c, registerWorkflowRunGetter as d, resolveActionTool as f, CREDENTIAL_SCOPE_LEVELS as g, runWithinActionExecution as h, executeAction as i, isStepInvocation as l, runWithRunSignal as m, createStepInvocation as n, getRunSignal as o, runOutsideActionExecution as p, defineAction as r, getWorkflowRunHandle as s, actionCoreSchema as t, isWithinActionExecution as u, DEFAULT_CREDENTIAL_RESOLUTION_CHAIN as v, normalizeCredentialList as w, defineCredential as x, credential as y };
2357
+ export { toCredentialRequirement as C, normalizeCredentialList as S, credential as _, getActionCredentialRequirements as a, isCredentialInput as b, isAction as c, registerWorkflowRunGetter as d, resolveActionTool as f, CREDENTIAL_SCOPE_TYPES as g, runWithinActionExecution as h, executeAction as i, isStepInvocation as l, runWithRunSignal as m, createStepInvocation as n, getRunSignal as o, runOutsideActionExecution as p, defineAction as r, getWorkflowRunHandle as s, actionCoreSchema as t, isWithinActionExecution as u, credentialInputSchema as v, toolParameters as w, mcpEntityId as x, defineCredential as y };
2378
2358
 
2379
- //# sourceMappingURL=dist-BF5yN9sB.mjs.map
2359
+ //# sourceMappingURL=dist-CFy63Npi.mjs.map