Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

fix(eve): identify dynamic tool callbacks by name instead of source offsets (#2384)

Andrew Barba02403b96130f
diff --git a/.changeset/dynamic-tools-name-identity.md b/.changeset/dynamic-tools-name-identity.md
new file mode 100644
index 000000000..ae3bd8b51
--- /dev/null
+++ b/.changeset/dynamic-tools-name-identity.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Dynamic tool callbacks are now identified by tool name and phase instead of byte offsets in the authored source. Editing an agent file no longer risks a parked approval replaying the wrong tool: after a redeploy or crash, parked calls run the latest deployed callback code under the same name, and a tool that no longer exists fails closed with an explicit error. Session-scoped resolvers may run once more on resume to rebind callbacks, so keep them idempotent.
diff --git a/apps/docs/registry.json b/apps/docs/registry.json
index 9363fb902..784adb880 100644
--- a/apps/docs/registry.json
+++ b/apps/docs/registry.json
@@ -33,9 +33,7 @@
"type": "registry:item",
"title": "Self-modification (Experimental)",
"description": "Add an experimental, development-only source editing subagent to an eve project.",
- "dependencies": [
- "@eve/self-modification"
- ],
+ "dependencies": ["@eve/self-modification"],
"files": [
{
"path": "registry/experimental/self-modification/agent.ts",
@@ -59,9 +57,7 @@
"type": "registry:item",
"title": "agent-browser",
"description": "Add browser automation tools backed by agent-browser to an eve agent.",
- "dependencies": [
- "@agent-browser/eve"
- ],
+ "dependencies": ["@agent-browser/eve"],
"files": [
{
"path": "registry/extensions/agent-browser.ts",
@@ -75,9 +71,7 @@
"type": "registry:item",
"title": "Browserbase",
"description": "Search, fetch, and automate the web with Browserbase and Stagehand.",
- "dependencies": [
- "@browserbasehq/eve"
- ],
+ "dependencies": ["@browserbasehq/eve"],
"envVars": {
"BROWSERBASE_API_KEY": ""
},
@@ -94,10 +88,7 @@
"type": "registry:item",
"title": "GitHub Tools",
"description": "Add scoped GitHub tools with Vercel Connect authentication and approval rules.",
- "dependencies": [
- "@github-tools/eve-extension",
- "@vercel/connect"
- ],
+ "dependencies": ["@github-tools/eve-extension", "@vercel/connect"],
"envVars": {
"GITHUB_TOKEN": ""
},
@@ -114,9 +105,7 @@
"type": "registry:item",
"title": "Jetty",
"description": "Grade agent turns, compare experiments, and store durable evaluation trajectories.",
- "dependencies": [
- "@jetty/eve"
- ],
+ "dependencies": ["@jetty/eve"],
"envVars": {
"JETTY_API_TOKEN": "",
"JETTY_COLLECTION": ""
@@ -134,9 +123,7 @@
"type": "registry:item",
"title": "KERNEL",
"description": "Let your eve agent use the Internet with KERNEL browser infrastructure, observability, and stealth.",
- "dependencies": [
- "@onkernel/eve-extension"
- ],
+ "dependencies": ["@onkernel/eve-extension"],
"envVars": {
"KERNEL_API_KEY": ""
},
@@ -153,9 +140,7 @@
"type": "registry:item",
"title": "Upstash AgentKit",
"description": "Add long-term memory, Redis Search, and durable chat history with Upstash Redis.",
- "dependencies": [
- "@upstash/agentkit-eve-extension"
- ],
+ "dependencies": ["@upstash/agentkit-eve-extension"],
"envVars": {
"UPSTASH_REDIS_REST_URL": "",
"UPSTASH_REDIS_REST_TOKEN": ""
@@ -173,9 +158,7 @@
"type": "registry:item",
"title": "Kybernesis Arcana",
"description": "Give an eve agent a workspace-scoped long-term memory with recall, storage, and brain notes.",
- "dependencies": [
- "@kybernesis/arcana"
- ],
+ "dependencies": ["@kybernesis/arcana"],
"envVars": {
"ARCANA_API_KEY": "",
"ARCANA_WORKSPACE": ""
@@ -193,9 +176,7 @@
"type": "registry:item",
"title": "Hindsight",
"description": "Recall relevant context before every turn and retain each exchange automatically.",
- "dependencies": [
- "@vectorize-io/hindsight-eve"
- ],
+ "dependencies": ["@vectorize-io/hindsight-eve"],
"envVars": {
"HINDSIGHT_API_KEY": "",
"HINDSIGHT_API_URL": "",
@@ -241,20 +222,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "vercel",
- "vercel",
- "vercel"
- ]
+ "args": ["integration", "connect", "vercel", "vercel", "vercel"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/vercel.ts",
@@ -274,20 +247,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "linear",
- "mcp.linear.app",
- "linear"
- ]
+ "args": ["integration", "connect", "linear", "mcp.linear.app", "linear"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/linear.ts",
@@ -307,20 +272,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "notion",
- "mcp.notion.com",
- "notion"
- ]
+ "args": ["integration", "connect", "notion", "mcp.notion.com", "notion"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/notion.ts",
@@ -340,20 +297,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "datadog",
- "mcp.datadoghq.com",
- "datadog"
- ]
+ "args": ["integration", "connect", "datadog", "mcp.datadoghq.com", "datadog"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/datadog.ts",
@@ -373,20 +322,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "honeycomb",
- "mcp.honeycomb.io",
- "honeycomb"
- ]
+ "args": ["integration", "connect", "honeycomb", "mcp.honeycomb.io", "honeycomb"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/honeycomb.ts",
@@ -406,20 +347,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "agentcard",
- "agentcard",
- "agentcard"
- ]
+ "args": ["integration", "connect", "agentcard", "agentcard", "agentcard"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/agentcard.ts",
@@ -439,20 +372,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "airtable",
- "airtable",
- "airtable"
- ]
+ "args": ["integration", "connect", "airtable", "airtable", "airtable"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/airtable.ts",
@@ -472,20 +397,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "bitly",
- "bitly",
- "bitly"
- ]
+ "args": ["integration", "connect", "bitly", "bitly", "bitly"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/bitly.ts",
@@ -505,20 +422,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "brex",
- "brex",
- "brex"
- ]
+ "args": ["integration", "connect", "brex", "brex", "brex"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/brex.ts",
@@ -538,20 +447,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "candid",
- "candid",
- "candid"
- ]
+ "args": ["integration", "connect", "candid", "candid", "candid"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/candid.ts",
@@ -571,20 +472,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "clickhouse",
- "clickhouse",
- "clickhouse"
- ]
+ "args": ["integration", "connect", "clickhouse", "clickhouse", "clickhouse"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/clickhouse.ts",
@@ -604,20 +497,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "cloudinary",
- "cloudinary",
- "cloudinary"
- ]
+ "args": ["integration", "connect", "cloudinary", "cloudinary", "cloudinary"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/cloudinary.ts",
@@ -637,20 +522,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "coda",
- "coda",
- "coda"
- ]
+ "args": ["integration", "connect", "coda", "coda", "coda"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/coda.ts",
@@ -670,20 +547,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "context",
- "mcp.context.dev",
- "context"
- ]
+ "args": ["integration", "connect", "context", "mcp.context.dev", "context"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/context.ts",
@@ -703,20 +572,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "egnyte",
- "egnyte",
- "egnyte"
- ]
+ "args": ["integration", "connect", "egnyte", "egnyte", "egnyte"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/egnyte.ts",
@@ -736,20 +597,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "embat",
- "embat",
- "embat"
- ]
+ "args": ["integration", "connect", "embat", "embat", "embat"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/embat.ts",
@@ -769,20 +622,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "hugging-face",
- "hugging-face",
- "hugging-face"
- ]
+ "args": ["integration", "connect", "hugging-face", "hugging-face", "hugging-face"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/hugging-face.ts",
@@ -802,20 +647,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "local-falcon",
- "local-falcon",
- "local-falcon"
- ]
+ "args": ["integration", "connect", "local-falcon", "local-falcon", "local-falcon"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/local-falcon.ts",
@@ -835,20 +672,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "make",
- "make",
- "make"
- ]
+ "args": ["integration", "connect", "make", "make", "make"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/make.ts",
@@ -868,20 +697,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "manufact",
- "manufact",
- "manufact"
- ]
+ "args": ["integration", "connect", "manufact", "manufact", "manufact"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/manufact.ts",
@@ -901,20 +722,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "mem0",
- "mem0",
- "mem0"
- ]
+ "args": ["integration", "connect", "mem0", "mem0", "mem0"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/mem0.ts",
@@ -934,20 +747,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "miro",
- "miro",
- "miro"
- ]
+ "args": ["integration", "connect", "miro", "miro", "miro"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/miro.ts",
@@ -967,20 +772,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "mixpanel",
- "mixpanel",
- "mixpanel"
- ]
+ "args": ["integration", "connect", "mixpanel", "mixpanel", "mixpanel"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/mixpanel.ts",
@@ -1000,20 +797,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "natural",
- "mcp.natural.com",
- "natural"
- ]
+ "args": ["integration", "connect", "natural", "mcp.natural.com", "natural"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/natural.ts",
@@ -1033,20 +822,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "netlify",
- "netlify",
- "netlify"
- ]
+ "args": ["integration", "connect", "netlify", "netlify", "netlify"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/netlify.ts",
@@ -1066,20 +847,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "oreilly",
- "oreilly",
- "oreilly"
- ]
+ "args": ["integration", "connect", "oreilly", "oreilly", "oreilly"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/oreilly.ts",
@@ -1099,20 +872,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "planetscale",
- "planetscale",
- "planetscale"
- ]
+ "args": ["integration", "connect", "planetscale", "planetscale", "planetscale"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/planetscale.ts",
@@ -1132,20 +897,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "posthog",
- "posthog",
- "posthog"
- ]
+ "args": ["integration", "connect", "posthog", "posthog", "posthog"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/posthog.ts",
@@ -1165,20 +922,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "postman",
- "postman",
- "postman"
- ]
+ "args": ["integration", "connect", "postman", "postman", "postman"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/postman.ts",
@@ -1198,20 +947,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "razorpay",
- "razorpay",
- "razorpay"
- ]
+ "args": ["integration", "connect", "razorpay", "razorpay", "razorpay"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/razorpay.ts",
@@ -1231,20 +972,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "sentry",
- "sentry",
- "sentry"
- ]
+ "args": ["integration", "connect", "sentry", "sentry", "sentry"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/sentry.ts",
@@ -1264,20 +997,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "similarweb",
- "similarweb",
- "similarweb"
- ]
+ "args": ["integration", "connect", "similarweb", "similarweb", "similarweb"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/similarweb.ts",
@@ -1297,20 +1022,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "stripe",
- "stripe",
- "stripe"
- ]
+ "args": ["integration", "connect", "stripe", "stripe", "stripe"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/stripe.ts",
@@ -1330,20 +1047,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "supabase",
- "supabase",
- "supabase"
- ]
+ "args": ["integration", "connect", "supabase", "supabase", "supabase"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/supabase.ts",
@@ -1363,20 +1072,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "ticket-tailor",
- "ticket-tailor",
- "ticket-tailor"
- ]
+ "args": ["integration", "connect", "ticket-tailor", "ticket-tailor", "ticket-tailor"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/ticket-tailor.ts",
@@ -1396,20 +1097,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "ticktick",
- "ticktick",
- "ticktick"
- ]
+ "args": ["integration", "connect", "ticktick", "ticktick", "ticktick"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/ticktick.ts",
@@ -1429,20 +1122,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "tinybird",
- "tinybird",
- "tinybird"
- ]
+ "args": ["integration", "connect", "tinybird", "tinybird", "tinybird"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/tinybird.ts",
@@ -1462,20 +1147,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "todoist",
- "todoist",
- "todoist"
- ]
+ "args": ["integration", "connect", "todoist", "todoist", "todoist"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/todoist.ts",
@@ -1495,20 +1172,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "webflow",
- "webflow",
- "webflow"
- ]
+ "args": ["integration", "connect", "webflow", "webflow", "webflow"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/webflow.ts",
@@ -1528,20 +1197,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "wix",
- "wix",
- "wix"
- ]
+ "args": ["integration", "connect", "wix", "wix", "wix"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/wix.ts",
@@ -1561,20 +1222,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "zapier",
- "zapier",
- "zapier"
- ]
+ "args": ["integration", "connect", "zapier", "zapier", "zapier"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/zapier.ts",
@@ -1594,20 +1247,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "zomato",
- "zomato",
- "zomato"
- ]
+ "args": ["integration", "connect", "zomato", "zomato", "zomato"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/zomato.ts",
@@ -1627,40 +1272,28 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "setup",
- "slack"
- ]
+ "args": ["integration", "setup", "slack"]
},
"requires": ">=0.33.0",
"docs": "/docs/channels/slack",
"implementation": "native"
}
},
- "dependencies": [
- "@vercel/connect@>=0.4.2"
- ]
+ "dependencies": ["@vercel/connect@>=0.4.2"]
},
{
"name": "channel/discord",
"type": "registry:item",
"title": "Discord",
"description": "Connect an eve agent to Discord with guided connector and slash-command setup.",
- "dependencies": [
- "@vercel/connect@>=0.6.0"
- ],
+ "dependencies": ["@vercel/connect@>=0.6.0"],
"meta": {
"eve": {
"setup": {
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "setup",
- "discord"
- ]
+ "args": ["integration", "setup", "discord"]
},
"requires": ">=0.33.0",
"docs": "/docs/channels/discord",
@@ -1747,20 +1380,14 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "setup",
- "github"
- ]
+ "args": ["integration", "setup", "github"]
},
"requires": ">=0.33.0",
"docs": "/docs/channels/github",
"implementation": "native"
}
},
- "dependencies": [
- "@vercel/connect@>=0.6.0"
- ]
+ "dependencies": ["@vercel/connect@>=0.6.0"]
},
{
"name": "channel/linear-agent",
@@ -1773,20 +1400,14 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "setup",
- "linear"
- ]
+ "args": ["integration", "setup", "linear"]
},
"requires": ">=0.33.0",
"docs": "/docs/channels/linear",
"implementation": "native"
}
},
- "dependencies": [
- "@vercel/connect"
- ]
+ "dependencies": ["@vercel/connect"]
},
{
"name": "channel/web",
@@ -1799,11 +1420,7 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "setup",
- "web"
- ]
+ "args": ["integration", "setup", "web"]
},
"requires": ">=0.33.0",
"docs": "/docs/channels/eve",
@@ -2031,11 +1648,7 @@
"type": "registry:item",
"title": "Google Chat",
"description": "Google Chat spaces and DMs via the Chat SDK.",
- "dependencies": [
- "chat",
- "@chat-adapter/gchat",
- "@chat-adapter/state-memory"
- ],
+ "dependencies": ["chat", "@chat-adapter/gchat", "@chat-adapter/state-memory"],
"files": [
{
"path": "registry/channels/chat-sdk-gchat.ts",
@@ -2058,11 +1671,7 @@
"type": "registry:item",
"title": "WhatsApp",
"description": "Customer messaging through WhatsApp Business Cloud via the Chat SDK.",
- "dependencies": [
- "chat",
- "@chat-adapter/whatsapp",
- "@chat-adapter/state-memory"
- ],
+ "dependencies": ["chat", "@chat-adapter/whatsapp", "@chat-adapter/state-memory"],
"files": [
{
"path": "registry/channels/chat-sdk-whatsapp.ts",
@@ -2088,11 +1697,7 @@
"type": "registry:item",
"title": "X",
"description": "Public mentions and DMs on X via the Chat SDK.",
- "dependencies": [
- "chat",
- "@chat-adapter/x",
- "@chat-adapter/state-memory"
- ],
+ "dependencies": ["chat", "@chat-adapter/x", "@chat-adapter/state-memory"],
"files": [
{
"path": "registry/channels/chat-sdk-x.ts",
@@ -2116,11 +1721,7 @@
"type": "registry:item",
"title": "Messenger",
"description": "Facebook Messenger bots with templates, buttons, and reactions via the Chat SDK.",
- "dependencies": [
- "chat",
- "@chat-adapter/messenger",
- "@chat-adapter/state-memory"
- ],
+ "dependencies": ["chat", "@chat-adapter/messenger", "@chat-adapter/state-memory"],
"files": [
{
"path": "registry/channels/chat-sdk-messenger.ts",
@@ -2145,11 +1746,7 @@
"type": "registry:item",
"title": "Zernio",
"description": "Reach seven social and messaging platforms through one Zernio integration.",
- "dependencies": [
- "chat",
- "@zernio/chat-sdk-adapter",
- "@chat-adapter/state-memory"
- ],
+ "dependencies": ["chat", "@zernio/chat-sdk-adapter", "@chat-adapter/state-memory"],
"envVars": {
"ZERNIO_API_KEY": "",
"ZERNIO_WEBHOOK_SECRET": ""
@@ -2173,11 +1770,7 @@
"type": "registry:item",
"title": "Velt",
"description": "Add agents to anchored comments across documents, canvases, PDFs, and video.",
- "dependencies": [
- "chat",
- "@veltdev/chat-sdk-adapter",
- "@chat-adapter/state-memory"
- ],
+ "dependencies": ["chat", "@veltdev/chat-sdk-adapter", "@chat-adapter/state-memory"],
"envVars": {
"VELT_API_KEY": "",
"VELT_WEBHOOK_SECRET": ""
@@ -2201,11 +1794,7 @@
"type": "registry:item",
"title": "Sendblue",
"description": "Send and receive iMessage, SMS, and RCS through Sendblue.",
- "dependencies": [
- "chat",
- "chat-adapter-sendblue",
- "@chat-adapter/state-memory"
- ],
+ "dependencies": ["chat", "chat-adapter-sendblue", "@chat-adapter/state-memory"],
"envVars": {
"SENDBLUE_API_KEY": "",
"SENDBLUE_API_SECRET": "",
@@ -2230,11 +1819,7 @@
"type": "registry:item",
"title": "Novu",
"description": "Reach Slack, Teams, WhatsApp, Telegram, and email through Novu.",
- "dependencies": [
- "chat",
- "@novu/chat-sdk-adapter",
- "@chat-adapter/state-memory"
- ],
+ "dependencies": ["chat", "@novu/chat-sdk-adapter", "@chat-adapter/state-memory"],
"files": [
{
"path": "registry/channels/chat-sdk-novu.ts",
@@ -2258,11 +1843,7 @@
"type": "registry:item",
"title": "Liveblocks",
"description": "Bring your agent into Liveblocks comment threads, mentions, and reactions.",
- "dependencies": [
- "chat",
- "@liveblocks/chat-sdk-adapter",
- "@chat-adapter/state-memory"
- ],
+ "dependencies": ["chat", "@liveblocks/chat-sdk-adapter", "@chat-adapter/state-memory"],
"envVars": {
"LIVEBLOCKS_SECRET_KEY": "",
"LIVEBLOCKS_WEBHOOK_SECRET": ""
@@ -2286,20 +1867,14 @@
"type": "registry:item",
"title": "Linq",
"description": "Connect an eve agent to iMessage and SMS through Linq with guided Connect or portable setup.",
- "dependencies": [
- "@vercel/connect@>=0.9.0"
- ],
+ "dependencies": ["@vercel/connect@>=0.9.0"],
"meta": {
"eve": {
"setup": {
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "setup",
- "linq"
- ]
+ "args": ["integration", "setup", "linq"]
},
"requires": ">=0.41.0",
"docs": "/docs/channels/linq",
@@ -2312,11 +1887,7 @@
"type": "registry:item",
"title": "Kapso",
"description": "Managed WhatsApp conversations, media, buttons, and history through Kapso.",
- "dependencies": [
- "chat",
- "@kapso/chat-adapter",
- "@chat-adapter/state-memory"
- ],
+ "dependencies": ["chat", "@kapso/chat-adapter", "@chat-adapter/state-memory"],
"envVars": {
"KAPSO_API_KEY": "",
"KAPSO_PHONE_NUMBER_ID": "",
@@ -2341,20 +1912,14 @@
"type": "registry:item",
"title": "Photon iMessage",
"description": "Connect an eve agent to iMessage through Photon with guided project and phone setup.",
- "dependencies": [
- "@vercel/connect@>=0.5.0"
- ],
+ "dependencies": ["@vercel/connect@>=0.5.0"],
"meta": {
"eve": {
"setup": {
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "setup",
- "photon"
- ]
+ "args": ["integration", "setup", "photon"]
},
"requires": ">=0.33.0",
"docs": "/docs/channels/photon",
@@ -2367,11 +1932,7 @@
"type": "registry:item",
"title": "Dial",
"description": "Give your agent a phone number for SMS, MMS, iMessage, and voice transcripts.",
- "dependencies": [
- "chat",
- "@getdial/chat-sdk-adapter",
- "@chat-adapter/state-memory"
- ],
+ "dependencies": ["chat", "@getdial/chat-sdk-adapter", "@chat-adapter/state-memory"],
"envVars": {
"DIAL_API_KEY": "",
"DIAL_FROM_NUMBER_ID": "",
@@ -2396,11 +1957,7 @@
"type": "registry:item",
"title": "AgentPhone",
"description": "SMS, MMS, iMessage, and voice conversations through AgentPhone.",
- "dependencies": [
- "chat",
- "@agentphone/chat-sdk-adapter",
- "@chat-adapter/state-memory"
- ],
+ "dependencies": ["chat", "@agentphone/chat-sdk-adapter", "@chat-adapter/state-memory"],
"envVars": {
"AGENTPHONE_API_KEY": "",
"AGENTPHONE_AGENT_ID": "",
@@ -2425,11 +1982,7 @@
"type": "registry:item",
"title": "Lark / Feishu",
"description": "Lark and Feishu chats with native card streaming via the Chat SDK.",
- "dependencies": [
- "chat",
- "@larksuite/vercel-chat-adapter",
- "@chat-adapter/state-memory"
- ],
+ "dependencies": ["chat", "@larksuite/vercel-chat-adapter", "@chat-adapter/state-memory"],
"envVars": {
"LARK_APP_ID": "",
"LARK_APP_SECRET": ""
@@ -2453,11 +2006,7 @@
"type": "registry:item",
"title": "Beeper",
"description": "Matrix rooms and bridged messaging networks through Beeper.",
- "dependencies": [
- "chat",
- "@beeper/chat-adapter-matrix",
- "@chat-adapter/state-memory"
- ],
+ "dependencies": ["chat", "@beeper/chat-adapter-matrix", "@chat-adapter/state-memory"],
"files": [
{
"path": "registry/channels/chat-sdk-beeper.ts",
@@ -2481,11 +2030,7 @@
"type": "registry:item",
"title": "Resend",
"description": "Send and receive threaded email through Resend via the Chat SDK.",
- "dependencies": [
- "chat",
- "@resend/chat-sdk-adapter",
- "@chat-adapter/state-memory"
- ],
+ "dependencies": ["chat", "@resend/chat-sdk-adapter", "@chat-adapter/state-memory"],
"envVars": {
"RESEND_API_KEY": "",
"RESEND_WEBHOOK_SECRET": "",
@@ -2510,9 +2055,7 @@
"type": "registry:item",
"title": "Braintrust",
"description": "Trace eve agent sessions in Braintrust, including turns, steps, tool calls, and subagent interactions.",
- "dependencies": [
- "braintrust"
- ],
+ "dependencies": ["braintrust"],
"envVars": {
"BRAINTRUST_API_KEY": ""
},
@@ -2558,9 +2101,7 @@
"type": "registry:item",
"title": "Sentry",
"description": "Send agent traces to Sentry's OTLP endpoint for tracing and debugging.",
- "dependencies": [
- "@vercel/otel"
- ],
+ "dependencies": ["@vercel/otel"],
"envVars": {
"SENTRY_OTLP_TRACES_ENDPOINT": "",
"SENTRY_PUBLIC_KEY": ""
@@ -2578,9 +2119,7 @@
"type": "registry:item",
"title": "Datadog",
"description": "Export agent traces to Datadog APM alongside the rest of your stack.",
- "dependencies": [
- "@vercel/otel"
- ],
+ "dependencies": ["@vercel/otel"],
"envVars": {
"DATADOG_OTLP_TRACES_ENDPOINT": "",
"DD_API_KEY": ""
@@ -2598,9 +2137,7 @@
"type": "registry:item",
"title": "Honeycomb",
"description": "Send OpenTelemetry traces to Honeycomb and query every agent turn.",
- "dependencies": [
- "@vercel/otel"
- ],
+ "dependencies": ["@vercel/otel"],
"envVars": {
"HONEYCOMB_API_KEY": ""
},
@@ -2617,9 +2154,7 @@
"type": "registry:item",
"title": "Arize",
"description": "Export traces to Arize AX for LLM observability and evaluation.",
- "dependencies": [
- "@vercel/otel"
- ],
+ "dependencies": ["@vercel/otel"],
"envVars": {
"ARIZE_SPACE_ID": "",
"ARIZE_API_KEY": ""
@@ -2637,9 +2172,7 @@
"type": "registry:item",
"title": "Raindrop",
"description": "Send agent traces to Raindrop to detect and debug AI product issues.",
- "dependencies": [
- "@vercel/otel"
- ],
+ "dependencies": ["@vercel/otel"],
"envVars": {
"RAINDROP_WRITE_KEY": ""
},
@@ -2656,9 +2189,7 @@
"type": "registry:item",
"title": "Jaeger",
"description": "Trace your agent with a local or self-hosted Jaeger OTLP backend.",
- "dependencies": [
- "@vercel/otel"
- ],
+ "dependencies": ["@vercel/otel"],
"files": [
{
"path": "registry/instrumentation/jaeger.ts",
diff --git a/docs/guides/dynamic-capabilities.md b/docs/guides/dynamic-capabilities.md
index 7e3820244..a18214602 100644
--- a/docs/guides/dynamic-capabilities.md
+++ b/docs/guides/dynamic-capabilities.md
@@ -166,7 +166,15 @@ Write callback properties as inline function expressions, arrows, method shortha
Closure values must be JSON-serializable. Plain objects, arrays, strings, finite numbers, booleans, and `null` are supported; `undefined` object properties are omitted. Functions, class instances, `Date`, `Map`, symbols, non-finite numbers, and cyclic values fail resolution with the tool name and callback phase instead of being serialized lossily.
-Call expressions such as `execute: makeExecutor()` are not transformed. Put the callback body directly in `defineTool()` inside an authored module; eve-provided factories may also supply pre-registered callbacks. eve rejects a dynamic tool if any present callback lacks durable metadata, and replay never reruns the current resolver to recover one.
+Call expressions such as `execute: makeExecutor()` are not transformed. Put the callback body directly in `defineTool()` inside an authored module; eve-provided factories may also supply pre-registered callbacks. eve rejects a dynamic tool if any present callback lacks durable metadata.
+
+### Identity and redeploys
+
+A parked call binds to its callback by **tool name and phase** — the same identity a static tool uses — never by source position. This gives dynamic tools static-tool semantics across deploys:
+
+- Editing a callback body (or anything else that does not change tool names) is safe: replaying a parked call runs the latest deployed code with the closure values snapshotted when the call was made.
+- If a persisted callback has no registered implementation (fresh process after a crash, or after a redeploy), eve re-runs `session.started` resolvers once to rebind it, then replays.
+- If the tool no longer exists under that name, replay fails closed with an explicit error instead of invoking something else. Turn-scoped and step-scoped tools are not rebound; a parked call to a missing one errors.
### Naming
@@ -189,7 +197,7 @@ A dynamic tool or skill whose name matches an **authored** one **overrides** it
| `turn.started` | Once per turn | Every model call in the turn |
| `step.started` | Before each model call | That model call |
-¹ Workflow recovery can redeliver a resolver event, so keep resolvers idempotent. Replaying a parked callback does not depend on running the resolver again.
+¹ Workflow recovery can redeliver a resolver event, so keep resolvers idempotent. Replaying a parked callback does not depend on running the resolver again — except for the one-shot rebind described under [Identity and redeploys](#identity-and-redeploys).
### Execution order
diff --git a/packages/eve/src/context/build-dynamic-tools.ts b/packages/eve/src/context/build-dynamic-tools.ts
index 6e21ed4e3..ff1f6a956 100644
--- a/packages/eve/src/context/build-dynamic-tools.ts
+++ b/packages/eve/src/context/build-dynamic-tools.ts
@@ -15,28 +15,23 @@ import type {
ApprovalResponseDecision,
ApprovalStatus,
} from "#public/definitions/approval.js";
-import type { DurableDynamicCallbackReference } from "#shared/durable-dynamic-tool-callbacks.js";
+import {
+ callDurableDynamicCallback,
+ lookupDurableDynamicCallback,
+ type DurableDynamicCallbackPhase,
+} from "#shared/durable-dynamic-tool-callbacks.js";
import { toInputSchema, toOutputSchema } from "#shared/tool-schema.js";
const log = createLogger("dynamic-tools");
-function lookupStepFunction(stepId: string): ((...args: unknown[]) => unknown) | null {
- const registry = (globalThis as Record<symbol, Map<string, Function> | undefined>)[
- Symbol.for("@workflow/core//registeredSteps")
- ];
- const callback = registry?.get(stepId);
- return callback ? (callback as (...args: unknown[]) => unknown) : null;
-}
-
function missingCallbackError(
metadata: DurableDynamicToolMetadata,
- phase: keyof DurableDynamicToolMetadata["callbacks"],
- reference: DurableDynamicCallbackReference,
+ phase: DurableDynamicCallbackPhase,
): Error {
return new Error(
- `Dynamic tool "${metadata.name}" cannot replay its ${phase} callback because ` +
- `step function "${reference.stepId}" is not registered. Rebuild the agent and ensure ` +
- "the callback is created at module scope or transformed from authored source.",
+ `Dynamic tool "${metadata.name}" cannot replay its ${phase} callback because it is not ` +
+ "registered in this process. The tool was removed or renamed since this call was parked, " +
+ "or its resolver did not run. Restore the tool definition or start a new session.",
);
}
@@ -46,26 +41,30 @@ function buildReplayedApproval(
const requestReference = metadata.callbacks.approvalRequest;
if (requestReference === undefined) return undefined;
- const request = lookupStepFunction(requestReference.stepId);
+ const request = lookupDurableDynamicCallback(metadata.name, "approvalRequest");
const requestPolicy =
- request === null
+ request === undefined
? async () => {
- log.error(missingCallbackError(metadata, "approvalRequest", requestReference).message);
+ log.error(missingCallbackError(metadata, "approvalRequest").message);
return "user-approval" as const;
}
: async (context: ApprovalContext) =>
- (await request(requestReference.closure, context)) as ApprovalStatus;
+ (await callDurableDynamicCallback(
+ request,
+ requestReference.closure,
+ context,
+ )) as ApprovalStatus;
const responseReference = metadata.callbacks.approvalResponse;
if (responseReference === undefined) return requestPolicy;
- const response = lookupStepFunction(responseReference.stepId);
+ const response = lookupDurableDynamicCallback(metadata.name, "approvalResponse");
return {
request: requestPolicy,
response:
- response === null
+ response === undefined
? async () => {
- const error = missingCallbackError(metadata, "approvalResponse", responseReference);
+ const error = missingCallbackError(metadata, "approvalResponse");
log.error(error.message);
return {
reason: error.message,
@@ -73,7 +72,11 @@ function buildReplayedApproval(
};
}
: async (context: ApprovalResponseContext) =>
- (await response(responseReference.closure, context)) as ApprovalResponseDecision,
+ (await callDurableDynamicCallback(
+ response,
+ responseReference.closure,
+ context,
+ )) as ApprovalResponseDecision,
};
}
@@ -83,22 +86,22 @@ export function replayDynamicTools(
): HarnessToolDefinition[] {
return metadata.map((entry) => {
const executeReference = entry.callbacks.execute;
- const execute = lookupStepFunction(executeReference.stepId);
+ const execute = lookupDurableDynamicCallback(entry.name, "execute");
const toModelOutputReference = entry.callbacks.toModelOutput;
const toModelOutput =
toModelOutputReference === undefined
? undefined
- : lookupStepFunction(toModelOutputReference.stepId);
+ : lookupDurableDynamicCallback(entry.name, "toModelOutput");
return {
description: entry.description,
execute: createToolExecuteWithAuth({
scope: entry.name,
execute: (input, context) => {
- if (execute === null) {
- throw missingCallbackError(entry, "execute", executeReference);
+ if (execute === undefined) {
+ throw missingCallbackError(entry, "execute");
}
- return execute(executeReference.closure, input, context);
+ return callDurableDynamicCallback(execute, executeReference.closure, input, context);
},
}),
inputSchema: toInputSchema(entry.inputSchema),
@@ -109,10 +112,14 @@ export function replayDynamicTools(
? {}
: {
toModelOutput: (output: unknown) => {
- if (toModelOutput === null) {
- throw missingCallbackError(entry, "toModelOutput", toModelOutputReference);
+ if (toModelOutput === undefined) {
+ throw missingCallbackError(entry, "toModelOutput");
}
- return toModelOutput!(toModelOutputReference.closure, output);
+ return callDurableDynamicCallback(
+ toModelOutput!,
+ toModelOutputReference.closure,
+ output,
+ );
},
}),
};
diff --git a/packages/eve/src/context/dynamic-tool-lifecycle.test.ts b/packages/eve/src/context/dynamic-tool-lifecycle.test.ts
index 2ac8c25d6..c8cbac0a9 100644
--- a/packages/eve/src/context/dynamic-tool-lifecycle.test.ts
+++ b/packages/eve/src/context/dynamic-tool-lifecycle.test.ts
@@ -33,7 +33,11 @@ import {
StepDynamicToolMetadataKey,
TurnDynamicToolMetadataKey,
} from "#context/keys.js";
-import { stampDurableDynamicToolCallbacks } from "#shared/durable-dynamic-tool-callbacks.js";
+import {
+ lookupDurableDynamicCallback,
+ registerDurableDynamicCallback,
+ stampDurableDynamicToolCallbacks,
+} from "#shared/durable-dynamic-tool-callbacks.js";
import type { ResolvedDynamicToolResolver } from "#runtime/types.js";
import { createSessionStartedEvent, type UnstampedMessageStreamEvent } from "#protocol/message.js";
@@ -101,17 +105,13 @@ describe("dynamic tool naming", () => {
describe("durable callback capture validation", () => {
function validateExecuteCapture(closure: unknown) {
- getOrCreateStepRegistry(Symbol.for("@workflow/core//registeredSteps")).set(
- "capture-execute",
- () => null,
- );
const entry = defineTool({
description: "captured tool",
inputSchema: { type: "object" },
execute: async () => null,
});
stampDurableDynamicToolCallbacks(entry, {
- execute: { closure: closure as JsonObject, stepId: "capture-execute" },
+ execute: { callback: () => null, closure: closure as JsonObject },
});
return validateDurableDynamicToolCallbacks("captured", entry);
}
@@ -160,26 +160,36 @@ describe("durable callback capture validation", () => {
});
// ---------------------------------------------------------------------------
-// replayDynamicSessionTools — step function lookup + closure replay
+// replayDynamicSessionTools — name+phase lookup + closure replay
// ---------------------------------------------------------------------------
-function getOrCreateStepRegistry(sym: symbol): Map<string, Function> {
- const g = globalThis as Record<symbol, Map<string, Function> | undefined>;
- const existing = g[sym];
+const dynamicCallbackRegistrySym = Symbol.for("eve:dynamic-tool-callbacks");
+
+function getDynamicCallbackRegistry(): Map<string, Map<string, Function>> {
+ const g = globalThis as Record<symbol, Map<string, Map<string, Function>> | undefined>;
+ const existing = g[dynamicCallbackRegistrySym];
if (existing !== undefined) return existing;
- const fresh = new Map<string, Function>();
- g[sym] = fresh;
+ const fresh = new Map<string, Map<string, Function>>();
+ g[dynamicCallbackRegistrySym] = fresh;
return fresh;
}
+function registerTestCallback(
+ toolName: string,
+ phase: string,
+ callback: (closure: unknown, ...args: unknown[]) => unknown,
+): void {
+ registerDurableDynamicCallback({
+ callback: callback as never,
+ phase: phase as never,
+ toolName,
+ });
+}
+
describe("replayDynamicSessionTools", () => {
- function metadata(
- name: string,
- stepId: string,
- closure: JsonObject = {},
- ): DurableDynamicToolMetadata {
+ function metadata(name: string, closure: JsonObject = {}): DurableDynamicToolMetadata {
return {
- callbacks: { execute: { closure, stepId } },
+ callbacks: { execute: { closure } },
description: `${name} description`,
entryKey: name,
inputSchema: { type: "object" },
@@ -189,29 +199,21 @@ describe("replayDynamicSessionTools", () => {
}
it("fails execution closed when the registered callback is unavailable", async () => {
- const [tool] = replayDynamicSessionTools(
- [metadata("unregistered", "eve:dynamic-tool//missing")],
- [],
- );
+ const [tool] = replayDynamicSessionTools([metadata("unregistered")], []);
await expect(tool!.execute!({}, executeOptions)).rejects.toThrow(
'Dynamic tool "unregistered" cannot replay its execute callback',
);
});
it("reconstructs tool with registered step function and closure vars", async () => {
- const stepId = "eve:dynamic-tool//__eve_dynamic_exec_test_replay";
const stepFn = vi.fn((__vars: unknown, input: unknown) => ({
result: (__vars as Record<string, unknown>).apiUrl,
input,
}));
- Object.assign(stepFn, { stepId });
-
- const registrySym = Symbol.for("@workflow/core//registeredSteps");
- const registry = getOrCreateStepRegistry(registrySym);
- registry.set(stepId, stepFn);
+ registerTestCallback("replay-tool", "execute", stepFn);
try {
- const durable = metadata("replay-tool", stepId, {
+ const durable = metadata("replay-tool", {
apiUrl: "https://api.example.com",
tenantName: "Acme",
});
@@ -230,26 +232,32 @@ describe("replayDynamicSessionTools", () => {
expect.anything(),
);
} finally {
- registry.delete(stepId);
+ getDynamicCallbackRegistry().delete("replay-tool");
}
});
+ it("runs the latest registered implementation after a redeploy rebinds the name", async () => {
+ registerTestCallback("latest-tool", "execute", () => ({ version: 1 }));
+ const tools = replayDynamicSessionTools([metadata("latest-tool")], []);
+ await expect(tools[0]!.execute!({}, executeOptions)).resolves.toEqual({ version: 1 });
+
+ // A redeploy re-resolves and replaces the binding under the same identity.
+ registerTestCallback("latest-tool", "execute", () => ({ version: 2 }));
+ const rebound = replayDynamicSessionTools([metadata("latest-tool")], []);
+ await expect(rebound[0]!.execute!({}, executeOptions)).resolves.toEqual({ version: 2 });
+ getDynamicCallbackRegistry().delete("latest-tool");
+ });
+
it("replayed tool passes stored closure vars, not live values", async () => {
- const stepId = "eve:dynamic-tool//__eve_dynamic_exec_snapshot";
const calls: unknown[] = [];
- const stepFn = (__vars: unknown, input: unknown) => {
+ registerTestCallback("snapshot-tool", "execute", (__vars: unknown, input: unknown) => {
calls.push({ vars: __vars, input });
return { ok: true };
- };
- Object.assign(stepFn, { stepId });
-
- const registrySym = Symbol.for("@workflow/core//registeredSteps");
- const registry = getOrCreateStepRegistry(registrySym);
- registry.set(stepId, stepFn);
+ });
try {
const closureVars = { counter: 1, label: "v1" };
- const tools = replayDynamicSessionTools([metadata("snapshot-tool", stepId, closureVars)], []);
+ const tools = replayDynamicSessionTools([metadata("snapshot-tool", closureVars)], []);
const tool = tools[0]!;
tool.execute!({}, executeOptions);
@@ -263,25 +271,18 @@ describe("replayDynamicSessionTools", () => {
expect(calls).toHaveLength(2);
expect((calls[0] as Record<string, unknown>).vars).toBe(closureVars);
} finally {
- registry.delete(stepId);
+ getDynamicCallbackRegistry().delete("snapshot-tool");
}
});
it("reconstructs multiple tools from metadata", () => {
- const registrySym = Symbol.for("@workflow/core//registeredSteps");
- const registry = getOrCreateStepRegistry(registrySym);
-
- const stepIdA = "eve:dynamic-tool//__eve_dynamic_exec_multi_a";
- const stepIdB = "eve:dynamic-tool//__eve_dynamic_exec_multi_b";
- const fnA = () => ({ tool: "a" });
- const fnB = () => ({ tool: "b" });
- registry.set(stepIdA, fnA);
- registry.set(stepIdB, fnB);
+ registerTestCallback("tenant__query", "execute", () => ({ tool: "a" }));
+ registerTestCallback("tenant__export", "execute", () => ({ tool: "b" }));
try {
const durable = [
- metadata("tenant__query", stepIdA, { tenant: "acme" }),
- metadata("tenant__export", stepIdB, { tenant: "acme" }),
+ metadata("tenant__query", { tenant: "acme" }),
+ metadata("tenant__export", { tenant: "acme" }),
];
const tools = replayDynamicSessionTools(durable, []);
@@ -289,8 +290,8 @@ describe("replayDynamicSessionTools", () => {
expect(tools[0]!.name).toBe("tenant__query");
expect(tools[1]!.name).toBe("tenant__export");
} finally {
- registry.delete(stepIdA);
- registry.delete(stepIdB);
+ getDynamicCallbackRegistry().delete("tenant__query");
+ getDynamicCallbackRegistry().delete("tenant__export");
}
});
});
@@ -348,85 +349,76 @@ function makeEvent(type: string): UnstampedMessageStreamEvent {
return { type, data: {} } as UnstampedMessageStreamEvent;
}
-const registrySym = Symbol.for("@workflow/core//registeredSteps");
-const testRegistry = getOrCreateStepRegistry(registrySym);
-let stepCounter = 0;
+const dynamicCallbackRegistry = getDynamicCallbackRegistry();
function simulateColdStart(ctx: ContextContainer): void {
for (const metadata of ctx.get(SessionDynamicToolMetadataKey) ?? []) {
- for (const callback of Object.values(metadata.callbacks)) {
- testRegistry.delete(callback.stepId);
- }
+ dynamicCallbackRegistry.delete(metadata.name);
}
ctx.clearVirtualContext();
}
/**
- * Creates a tool entry with bundler-injected step function fields so
- * `buildDynamicTools` can replay it from durable metadata.
+ * Creates a tool entry stamped with a live durable callback so resolve-time
+ * registration binds it under the tool's final name.
*/
function createReplayableTool(
description = "stub",
executeFn: (input: Record<string, unknown>) => unknown = () => ({ ok: true }),
): DynamicToolEntry {
- const stepId = `test-step-${++stepCounter}`;
- testRegistry.set(stepId, (_vars: unknown, input: unknown) =>
- executeFn(input as Record<string, unknown>),
- );
const entry = defineTool({
description,
inputSchema: { type: "object" },
execute: async (input: Record<string, unknown>): Promise<unknown> => executeFn(input),
});
stampDurableDynamicToolCallbacks(entry, {
- execute: { closure: {}, stepId },
+ execute: {
+ callback: (_closure, input) => executeFn(input as Record<string, unknown>),
+ closure: {},
+ },
});
return entry;
}
function stampTestTool(entry: DynamicToolEntry): DynamicToolEntry {
- const executeStepId = `test-step-${++stepCounter}`;
- testRegistry.set(executeStepId, (_closure: unknown, input: unknown, context: unknown) =>
- entry.execute(
- input as Record<string, unknown>,
- context as Parameters<DynamicToolEntry["execute"]>[1],
- ),
- );
const request = entry.approval === undefined ? undefined : resolveApprovalPolicy(entry.approval);
const response =
entry.approval === undefined || typeof entry.approval === "function"
? undefined
: entry.approval.response;
- const approvalRequestStepId = request === undefined ? undefined : `test-step-${++stepCounter}`;
- const approvalResponseStepId = response === undefined ? undefined : `test-step-${++stepCounter}`;
- const toModelOutputStepId =
- entry.toModelOutput === undefined ? undefined : `test-step-${++stepCounter}`;
- if (request !== undefined) {
- testRegistry.set(approvalRequestStepId!, (_closure: unknown, context: unknown) =>
- request(context as ApprovalContext),
- );
- }
- if (response !== undefined) {
- testRegistry.set(approvalResponseStepId!, (_closure: unknown, context: unknown) =>
- response(context as never),
- );
- }
- if (entry.toModelOutput !== undefined) {
- testRegistry.set(toModelOutputStepId!, (_closure: unknown, output: unknown) =>
- entry.toModelOutput!(output),
- );
- }
stampDurableDynamicToolCallbacks(entry, {
- execute: { closure: {}, stepId: executeStepId },
- ...(approvalRequestStepId === undefined
+ execute: {
+ callback: (_closure, input, context) =>
+ entry.execute(
+ input as Record<string, unknown>,
+ context as Parameters<DynamicToolEntry["execute"]>[1],
+ ),
+ closure: {},
+ },
+ ...(request === undefined
? {}
- : { approvalRequest: { closure: {}, stepId: approvalRequestStepId } }),
- ...(approvalResponseStepId === undefined
+ : {
+ approvalRequest: {
+ callback: (_closure, context) => request(context as ApprovalContext),
+ closure: {},
+ },
+ }),
+ ...(response === undefined
? {}
- : { approvalResponse: { closure: {}, stepId: approvalResponseStepId } }),
- ...(toModelOutputStepId === undefined
+ : {
+ approvalResponse: {
+ callback: (_closure, context) => response(context as never),
+ closure: {},
+ },
+ }),
+ ...(entry.toModelOutput === undefined
? {}
- : { toModelOutput: { closure: {}, stepId: toModelOutputStepId } }),
+ : {
+ toModelOutput: {
+ callback: (_closure, output) => entry.toModelOutput!(output),
+ closure: {},
+ },
+ }),
});
return entry;
}
@@ -528,6 +520,49 @@ describe("dispatchDynamicToolEvent", () => {
expect(handler).toHaveBeenCalledOnce();
});
+ it("rebinds missing session callbacks even when the runtime revision is unchanged", async () => {
+ const ctx = createCtx();
+ const handler = vi.fn(() => ({ tool: createReplayableTool("rebound") }));
+ const resolver = createResolver("live", ["session.started"], handler);
+ await dispatchDynamicToolEvent({
+ ctx,
+ resolvers: [resolver],
+ messages: [],
+ event: makeEvent("session.started"),
+ });
+ ctx.set(SessionDynamicToolRuntimeRevisionKey, "deployment:dpl_current");
+ simulateColdStart(ctx);
+
+ // Fresh process: bindings are gone although the bundle did not change.
+ expect(lookupDurableDynamicCallback("tool", "execute")).toBeUndefined();
+
+ await refreshDynamicSessionToolsForRuntimeRevision({
+ ctx,
+ resolvers: [resolver],
+ messages: [],
+ event: createSessionStartedEvent(),
+ runtimeRevision: "deployment:dpl_current",
+ });
+
+ expect(handler).toHaveBeenCalledTimes(2);
+ const [tool] = buildDynamicTools(ctx);
+ await expect(tool!.execute!({}, executeOptions)).resolves.toEqual({ ok: true });
+ });
+
+ it("rejects metadata persisted by the pre-release offset-based format", () => {
+ const entry = defineTool({
+ description: "legacy tool",
+ inputSchema: { type: "object" },
+ execute: async (): Promise<unknown> => ({}),
+ });
+ stampDurableDynamicToolCallbacks(entry, {
+ execute: { closure: {}, stepId: "eve:dynamic-tool//old/execute/0-100" } as never,
+ });
+ expect(() => validateDurableDynamicToolCallbacks("legacy", entry)).toThrow(
+ /pre-release eve version/,
+ );
+ });
+
it("clears removed session resolvers on a new runtime revision", async () => {
const ctx = createCtx();
const oldResolver = createResolver("old", ["session.started"], () => ({
@@ -833,104 +868,89 @@ describe("dispatchDynamicToolEvent", () => {
it("replays session tools from durable metadata on a fresh step", async () => {
const ctx = createCtx();
- // Register a step function so replayDynamicSessionTools can
- // reconstruct the tool on the second step.
- const stepId = "eve:dynamic-tool//__eve_dispatch_rehydrate_test";
- const stepFn = vi.fn((_vars: unknown, input: unknown, toolCtx: unknown) => ({
+ const stepFn = vi.fn((_closure: unknown, input: unknown, toolCtx: unknown) => ({
input,
toolName: (toolCtx as { toolName: string }).toolName,
}));
- const registrySym = Symbol.for("@workflow/core//registeredSteps");
- const registry = getOrCreateStepRegistry(registrySym);
- registry.set(stepId, stepFn);
- try {
- // Build a resolver whose tool entry carries a durable callback descriptor.
- const resolver = createResolver("tenant", ["session.started"], () => {
- const entry = defineTool({
- description: "tenant query",
- inputSchema: { type: "object" },
- execute: async () => ({ ok: true }),
- });
- stampDurableDynamicToolCallbacks(entry, {
- execute: {
- closure: { apiUrl: "https://api.example.com" },
- stepId,
- },
- });
- return { query: entry };
+ // Build a resolver whose tool entry carries a durable callback descriptor.
+ const resolver = createResolver("tenant", ["session.started"], () => {
+ const entry = defineTool({
+ description: "tenant query",
+ inputSchema: { type: "object" },
+ execute: async () => ({ ok: true }),
});
-
- // First step: resolve session tools, metadata is stored durably
- await dispatchDynamicToolEvent({
- ctx,
- resolvers: [resolver],
- messages: [],
- event: makeEvent("session.started"),
+ stampDurableDynamicToolCallbacks(entry, {
+ execute: {
+ callback: stepFn as never,
+ closure: { apiUrl: "https://api.example.com" },
+ },
});
- expect(buildDynamicTools(ctx)).toHaveLength(1);
- expect(ctx.get(SessionDynamicToolMetadataKey)).toHaveLength(1);
- expect(ctx.get(SessionDynamicToolMetadataKey)![0]!.callbacks.execute.stepId).toBe(stepId);
+ return { query: entry };
+ });
- // Simulate workflow step boundary: clear virtual context.
- // Durable metadata survives — buildDynamicTools reads from durable keys.
- ctx.clearVirtualContext();
- expect(ctx.get(SessionDynamicToolMetadataKey)).toHaveLength(1);
+ // First step: resolve session tools, metadata is stored durably and the
+ // callback binds under the final tool name.
+ await dispatchDynamicToolEvent({
+ ctx,
+ resolvers: [resolver],
+ messages: [],
+ event: makeEvent("session.started"),
+ });
+ expect(buildDynamicTools(ctx)).toHaveLength(1);
+ expect(ctx.get(SessionDynamicToolMetadataKey)).toHaveLength(1);
+ expect(ctx.get(SessionDynamicToolMetadataKey)![0]!.callbacks.execute.closure).toEqual({
+ apiUrl: "https://api.example.com",
+ });
- const tools = buildDynamicTools(ctx);
- expect(tools).toHaveLength(1);
- expect(tools[0]!.name).toBe("query");
- await expect(tools[0]!.execute!({}, executeOptions)).resolves.toEqual({
- input: {},
- toolName: "query",
- });
- } finally {
- registry.delete(stepId);
- }
+ // Simulate workflow step boundary: clear virtual context.
+ // Durable metadata survives — buildDynamicTools reads from durable keys.
+ ctx.clearVirtualContext();
+ expect(ctx.get(SessionDynamicToolMetadataKey)).toHaveLength(1);
+
+ const tools = buildDynamicTools(ctx);
+ expect(tools).toHaveLength(1);
+ expect(tools[0]!.name).toBe("query");
+ await expect(tools[0]!.execute!({}, executeOptions)).resolves.toEqual({
+ input: {},
+ toolName: "query",
+ });
});
it("provides inline auth to a replayed session-scoped tool", async () => {
const ctx = createCtx();
- const stepId = "eve:dynamic-tool//__eve_dispatch_auth_rehydrate_test";
const getToken = vi.fn(async () => ({ token: "replayed-token" }));
const auth = { getToken, principalType: "app" as const };
- const stepFn = vi.fn(async (_vars: unknown, _input: unknown, toolCtx: unknown) => {
+ const stepFn = vi.fn(async (_closure: unknown, _input: unknown, toolCtx: unknown) => {
const { token } = await (toolCtx as ToolContext).getToken(auth);
return { token };
});
- const registrySym = Symbol.for("@workflow/core//registeredSteps");
- const registry = getOrCreateStepRegistry(registrySym);
- registry.set(stepId, stepFn);
- try {
- const resolver = createResolver("oauth", ["session.started"], () => {
- const entry = defineTool({
- description: "resolve replayed auth",
- inputSchema: { type: "object" },
- execute: async () => ({ ok: true }),
- });
- stampDurableDynamicToolCallbacks(entry, {
- execute: { closure: {}, stepId },
- });
- return { probe: entry };
+ const resolver = createResolver("oauth", ["session.started"], () => {
+ const entry = defineTool({
+ description: "resolve replayed auth",
+ inputSchema: { type: "object" },
+ execute: async () => ({ ok: true }),
});
-
- await dispatchDynamicToolEvent({
- ctx,
- resolvers: [resolver],
- messages: [],
- event: makeEvent("session.started"),
+ stampDurableDynamicToolCallbacks(entry, {
+ execute: { callback: stepFn as never, closure: {} },
});
- ctx.clearVirtualContext();
+ return { probe: entry };
+ });
- const tool = buildDynamicTools(ctx)[0]!;
- await expect(tool.execute!({}, executeOptions)).resolves.toEqual({
- token: "replayed-token",
- });
- expect(getToken).toHaveBeenCalledOnce();
- } finally {
- registry.delete(stepId);
- }
+ await dispatchDynamicToolEvent({
+ ctx,
+ resolvers: [resolver],
+ messages: [],
+ event: makeEvent("session.started"),
+ });
+ ctx.clearVirtualContext();
+
+ const tool = buildDynamicTools(ctx)[0]!;
+ await expect(tool.execute!({}, executeOptions)).resolves.toEqual({
+ token: "replayed-token",
+ });
+ expect(getToken).toHaveBeenCalledOnce();
});
it("resolver returning null produces no tools", async () => {
@@ -1033,7 +1053,6 @@ describe("framework dynamic tools (no bundler transform)", () => {
const metadata = ctx.get(SessionDynamicToolMetadataKey);
expect(metadata).toHaveLength(1);
- expect(metadata![0]!.callbacks.execute.stepId).toMatch(/^test-step-/);
expect(metadata![0]!.callbacks.execute.closure).toEqual({});
const tools = buildDynamicTools(ctx);
@@ -1067,7 +1086,6 @@ describe("framework dynamic tools (no bundler transform)", () => {
const metadata = ctx.get(TurnDynamicToolMetadataKey);
expect(metadata).toHaveLength(1);
- expect(metadata![0]!.callbacks.execute.stepId).toMatch(/^test-step-/);
ctx.clearVirtualContext();
@@ -1133,8 +1151,6 @@ describe("framework dynamic tools (no bundler transform)", () => {
}),
);
const resolver = createResolver("connection", ["step.started"], () => ({ risky: entry }));
- testRegistry.delete("eve:framework-dynamic:connection:risky");
- testRegistry.delete("eve:dynamic-tool-approval:connection:risky");
await dispatchDynamicToolEvent({
ctx,
@@ -1150,8 +1166,6 @@ describe("framework dynamic tools (no bundler transform)", () => {
await expect(resolveApprovalPolicy(tools[0]!.approval!)(approvalCtx)).resolves.toBe(
"user-approval",
);
- expect(testRegistry.has("eve:framework-dynamic:connection:risky")).toBe(false);
- expect(testRegistry.has("eve:dynamic-tool-approval:connection:risky")).toBe(false);
});
it("replays approval from session-scoped dynamic tools", async () => {
@@ -1192,13 +1206,13 @@ describe("framework dynamic tools (no bundler transform)", () => {
it("replays phase-specific turn metadata", async () => {
const ctx = createCtx();
const approval = vi.fn(() => "user-approval" as const);
- testRegistry.set("legacy-turn-execute", () => ({ ok: true }));
- testRegistry.set("legacy-turn-approval", approval);
+ registerTestCallback("guarded", "execute", () => ({ ok: true }));
+ registerTestCallback("guarded", "approvalRequest", approval);
ctx.set(TurnDynamicToolMetadataKey, [
{
callbacks: {
- approvalRequest: { closure: {}, stepId: "legacy-turn-approval" },
- execute: { closure: {}, stepId: "legacy-turn-execute" },
+ approvalRequest: { closure: {} },
+ execute: { closure: {} },
},
description: "legacy guarded tool",
entryKey: "legacy:guarded",
@@ -1214,19 +1228,24 @@ describe("framework dynamic tools (no bundler transform)", () => {
await expect(
resolveApprovalPolicy(tool.approval)(createApprovalContext({ toolName: "guarded" })),
).resolves.toBe("user-approval");
+ getDynamicCallbackRegistry().delete("guarded");
});
it("uses the first dynamic definition for response authorization", () => {
const ctx = createCtx();
- testRegistry.set("step-execute", () => null);
- testRegistry.set("step-request", () => "user-approval");
- testRegistry.set("step-response", async () => ({ status: "allowed" }) as const);
+ registerTestCallback("guarded", "execute", () => null);
+ registerTestCallback("guarded", "approvalRequest", () => "user-approval");
+ registerTestCallback(
+ "guarded",
+ "approvalResponse",
+ async () => ({ status: "allowed" }) as const,
+ );
ctx.set(StepDynamicToolMetadataKey, [
{
callbacks: {
- approvalRequest: { closure: {}, stepId: "step-request" },
- approvalResponse: { closure: {}, stepId: "step-response" },
- execute: { closure: {}, stepId: "step-execute" },
+ approvalRequest: { closure: {} },
+ approvalResponse: { closure: {} },
+ execute: { closure: {} },
},
description: "step",
entryKey: "step:guarded",
@@ -1238,9 +1257,9 @@ describe("framework dynamic tools (no bundler transform)", () => {
ctx.set(SessionDynamicToolMetadataKey, [
{
callbacks: {
- approvalRequest: { closure: {}, stepId: "session-policy" },
- approvalResponse: { closure: {}, stepId: "session-authorizer" },
- execute: { closure: {}, stepId: "session-execute" },
+ approvalRequest: { closure: {} },
+ approvalResponse: { closure: {} },
+ execute: { closure: {} },
},
description: "session",
entryKey: "session:guarded",
@@ -1256,6 +1275,7 @@ describe("framework dynamic tools (no bundler transform)", () => {
});
expect(tools.get("guarded")?.description).toBe("step");
+ getDynamicCallbackRegistry().delete("guarded");
});
it("rejects an untransformed tool atomically without resolver hydration", async () => {
diff --git a/packages/eve/src/context/dynamic-tool-lifecycle.ts b/packages/eve/src/context/dynamic-tool-lifecycle.ts
index caf197d8c..ccae92af3 100644
--- a/packages/eve/src/context/dynamic-tool-lifecycle.ts
+++ b/packages/eve/src/context/dynamic-tool-lifecycle.ts
@@ -20,9 +20,13 @@ import {
isBrandedToolEntry,
} from "#shared/dynamic-tool-definition.js";
import {
- readDurableDynamicToolCallbacks,
+ hasUnregisteredDurableDynamicCallbacks,
+ type DurableDynamicCallbackPhase,
type DurableDynamicCallbackReference,
type DurableDynamicToolCallbacks,
+ type StampedDurableDynamicCallback,
+ readDurableDynamicToolCallbacks,
+ registerDurableDynamicCallback,
} from "#shared/durable-dynamic-tool-callbacks.js";
import { toErrorMessage } from "#shared/errors.js";
import { parseJsonObject } from "#shared/json.js";
@@ -102,11 +106,11 @@ function readDynamicToolResult(
function validateReference(input: {
readonly name: string;
- readonly phase: keyof DurableDynamicToolCallbacks;
- readonly reference: DurableDynamicCallbackReference | undefined;
+ readonly phase: DurableDynamicCallbackPhase;
+ readonly stamped: StampedDurableDynamicCallback | undefined;
readonly required: boolean;
}): DurableDynamicCallbackReference | undefined {
- if (input.reference === undefined) {
+ if (input.stamped === undefined) {
if (input.required) {
throw new Error(
`Dynamic tool "${input.name}" callback "${input.phase}" does not have a durable descriptor. ` +
@@ -115,38 +119,40 @@ function validateReference(input: {
}
return undefined;
}
- const unknownKeys = Object.keys(input.reference).filter(
- (key) => key !== "closure" && key !== "stepId",
+ const unknownKeys = Object.keys(input.stamped).filter(
+ (key) => key !== "closure" && key !== "callback",
);
+ if (unknownKeys.includes("stepId")) {
+ throw new Error(
+ `Dynamic tool "${input.name}" callback "${input.phase}" was persisted by a pre-release eve ` +
+ "version that identified callbacks by build offset. Start a new session to re-resolve it.",
+ );
+ }
if (unknownKeys.length > 0) {
throw new Error(
`Dynamic tool "${input.name}" has invalid ${input.phase} callback metadata: unknown key(s) ${unknownKeys.join(", ")}.`,
);
}
- if (typeof input.reference.stepId !== "string" || input.reference.stepId.length === 0) {
+ if (typeof input.stamped.callback !== "function") {
throw new Error(
- `Dynamic tool "${input.name}" has invalid ${input.phase} callback metadata: stepId must be a non-empty string.`,
+ `Dynamic tool "${input.name}" callback "${input.phase}" does not have a durable descriptor. ` +
+ "Author the callback inline in transformed source or use an eve durable callback helper.",
);
}
let closure: DurableDynamicCallbackReference["closure"];
try {
- closure = parseJsonObject(input.reference.closure);
+ closure = parseJsonObject(input.stamped.closure);
} catch (error) {
throw new Error(
`Dynamic tool "${input.name}" callback "${input.phase}" has a non-serializable capture. ${toErrorMessage(error)}`,
);
}
- const registry = (globalThis as Record<symbol, Map<string, Function> | undefined>)[
- Symbol.for("@workflow/core//registeredSteps")
- ];
- if (registry?.has(input.reference.stepId) !== true) {
- throw new Error(
- `Dynamic tool "${input.name}" callback "${input.phase}" references ` +
- `"${input.reference.stepId}", but that step function is not registered. ` +
- "Author the callback inline in transformed source or register it from an eve callback helper.",
- );
- }
- return { closure, stepId: input.reference.stepId };
+ registerDurableDynamicCallback({
+ callback: input.stamped.callback,
+ phase: input.phase,
+ toolName: input.name,
+ });
+ return { closure };
}
export function validateDurableDynamicToolCallbacks(
@@ -154,16 +160,16 @@ export function validateDurableDynamicToolCallbacks(
entry: DynamicToolEntry,
): DurableDynamicToolCallbacks {
const raw = readDurableDynamicToolCallbacks(entry) ?? {};
- const unknownKeys = Object.keys(raw).filter(
+ const unknownPhases = Object.keys(raw).filter(
(key) =>
key !== "execute" &&
key !== "approvalRequest" &&
key !== "approvalResponse" &&
key !== "toModelOutput",
);
- if (unknownKeys.length > 0) {
+ if (unknownPhases.length > 0) {
throw new Error(
- `Dynamic tool "${name}" has unknown durable callback phase(s): ${unknownKeys.join(", ")}.`,
+ `Dynamic tool "${name}" has unknown durable callback phase(s): ${unknownPhases.join(", ")}.`,
);
}
@@ -175,25 +181,25 @@ export function validateDurableDynamicToolCallbacks(
const execute = validateReference({
name,
phase: "execute",
- reference: raw.execute,
+ stamped: raw.execute,
required: true,
})!;
const approvalRequest = validateReference({
name,
phase: "approvalRequest",
- reference: raw.approvalRequest,
+ stamped: raw.approvalRequest,
required: hasApproval,
});
const approvalResponse = validateReference({
name,
phase: "approvalResponse",
- reference: raw.approvalResponse,
+ stamped: raw.approvalResponse,
required: hasApprovalResponse,
});
const toModelOutput = validateReference({
name,
phase: "toModelOutput",
- reference: raw.toModelOutput,
+ stamped: raw.toModelOutput,
required: entry.toModelOutput !== undefined,
});
@@ -346,7 +352,11 @@ export async function dispatchDynamicToolEvent(input: {
input.ctx.set(durableKey, [...kept, ...metadata]);
}
-/** Refreshes session-scoped definitions only when the deployed code revision changes. */
+/**
+ * Refreshes session-scoped definitions when the deployed code revision changes
+ * or when persisted callbacks have no registered binding (fresh process after
+ * a crash, or a redeploy), so replay always resolves against current code.
+ */
export async function refreshDynamicSessionToolsForRuntimeRevision(input: {
readonly ctx: ContextContainer;
readonly resolvers: readonly ResolvedDynamicToolResolver[];
@@ -354,7 +364,12 @@ export async function refreshDynamicSessionToolsForRuntimeRevision(input: {
readonly messages: readonly ModelMessage[];
readonly runtimeRevision: string;
}): Promise<void> {
- if (input.ctx.get(SessionDynamicToolRuntimeRevisionKey) === input.runtimeRevision) return;
+ const revisionChanged =
+ input.ctx.get(SessionDynamicToolRuntimeRevisionKey) !== input.runtimeRevision;
+ const needsRebind = hasUnregisteredDurableDynamicCallbacks(
+ input.ctx.get(SessionDynamicToolMetadataKey) ?? [],
+ );
+ if (!revisionChanged && !needsRebind) return;
const matching = input.resolvers.filter((resolver) =>
resolver.eventNames.includes("session.started"),
);
diff --git a/packages/eve/src/execution/workflow-steps.test.ts b/packages/eve/src/execution/workflow-steps.test.ts
index 76c99a783..5d5d74596 100644
--- a/packages/eve/src/execution/workflow-steps.test.ts
+++ b/packages/eve/src/execution/workflow-steps.test.ts
@@ -48,10 +48,7 @@ import { dispatchTurnStep } from "#execution/dispatch-turn-step.js";
import { projectToDurableSession } from "#execution/session.js";
import { buildRuntimeIdentity, createExecutionNodeStep } from "#execution/node-step.js";
import { defineTool } from "#public/definitions/tool.js";
-import {
- registerDurableDynamicCallback,
- stampDurableDynamicCallback,
-} from "#shared/durable-dynamic-tool-callbacks.js";
+import { stampDurableDynamicCallback } from "#shared/durable-dynamic-tool-callbacks.js";
import { dispatchRuntimeActionsStep } from "#execution/dispatch-runtime-actions-step.js";
import { runProxySubagentEventStep } from "#execution/subagent-event-proxy-step.js";
import { readLatestTaskView, sendTaskInboundPayload } from "#execution/tasks/parent/run-parent.js";
@@ -2621,15 +2618,13 @@ describe("turnStep", () => {
},
);
const approval = stampDurableDynamicCallback(() => "not-applicable" as const, {
+ callback: () => "not-applicable",
closure: {},
- stepId: "test:current-tool/approval",
});
const execute = stampDurableDynamicCallback(async () => ({ ok: true }), {
+ callback: async () => ({ ok: true }),
closure: {},
- stepId: "test:current-tool/execute",
});
- registerDurableDynamicCallback("test:current-tool/approval", () => "not-applicable");
- registerDurableDynamicCallback("test:current-tool/execute", async () => ({ ok: true }));
const handler = vi.fn(() => {
lifecycleOrder.push("refresh");
return {
@@ -2706,7 +2701,7 @@ describe("turnStep", () => {
ctx.set(SessionDynamicToolMetadataKey, [
{
callbacks: {
- execute: { closure: {}, stepId: "eve:dynamic-tool//old" },
+ execute: { closure: {} },
},
description: "Stale deployment tool",
entryKey: "old_tool",
diff --git a/packages/eve/src/harness/tool-loop.test.ts b/packages/eve/src/harness/tool-loop.test.ts
index e72884f61..0e171a9c0 100644
--- a/packages/eve/src/harness/tool-loop.test.ts
+++ b/packages/eve/src/harness/tool-loop.test.ts
@@ -37,6 +37,7 @@ import type { InstrumentationStepStartedEventInput } from "#public/instrumentati
import { defineInstructions } from "#public/definitions/instructions.js";
import type { ResolvedDynamicInstructionsResolver } from "#runtime/types.js";
import type { DynamicResolveContext } from "#shared/dynamic-tool-definition.js";
+import { registerDurableDynamicCallback } from "#shared/durable-dynamic-tool-callbacks.js";
import type { RunMode } from "#shared/run-mode.js";
import { compactMessages, shouldCompact } from "#harness/compaction.js";
import { getHarnessEmissionState, isHarnessBetweenTurns } from "#harness/emission.js";
@@ -2175,19 +2176,21 @@ describe("createToolLoopHarness", () => {
sessionId: "test-session",
turn: { id: "turn-test", sequence: 0 },
});
- const registryKey = Symbol.for("@workflow/core//registeredSteps");
- const globals = globalThis as Record<symbol, Map<string, Function> | undefined>;
- const registry = globals[registryKey] ?? new Map<string, Function>();
- globals[registryKey] = registry;
- registry.set("test-step-execute", () => ({ ok: true }));
- registry.set("test-step-approval", (_closure: unknown, approvalContext: unknown) =>
- approval(approvalContext as never),
- );
+ registerDurableDynamicCallback({
+ callback: () => ({ ok: true }),
+ phase: "execute",
+ toolName: "tfl__getLineStatus",
+ });
+ registerDurableDynamicCallback({
+ callback: (_closure: unknown, approvalContext: unknown) => approval(approvalContext as never),
+ phase: "approvalRequest",
+ toolName: "tfl__getLineStatus",
+ });
ctx.set(StepDynamicToolMetadataKey, [
{
callbacks: {
- approvalRequest: { closure: {}, stepId: "test-step-approval" },
- execute: { closure: {}, stepId: "test-step-execute" },
+ approvalRequest: { closure: {} },
+ execute: { closure: {} },
},
description: "Get TfL line status.",
entryKey: "tfl__getLineStatus",
diff --git a/packages/eve/src/internal/workflow-bundle/dynamic-remote-agent-transform.test.ts b/packages/eve/src/internal/workflow-bundle/dynamic-remote-agent-transform.test.ts
index 5d4635901..e74fa0d24 100644
--- a/packages/eve/src/internal/workflow-bundle/dynamic-remote-agent-transform.test.ts
+++ b/packages/eve/src/internal/workflow-bundle/dynamic-remote-agent-transform.test.ts
@@ -139,4 +139,32 @@ export default defineDynamic({
),
).resolves.toBeNull();
});
+
+ it("shares one hoisted declaration across byte-identical credential factories", async () => {
+ const factoryCall = `defineRemoteAgent({
+ auth: async () => ({ headers: { authorization: "Bearer fresh" } }),
+ description: "Remote research.",
+ url: "https://research.example.com",
+ })`;
+ const source = `
+import { defineDynamic, defineRemoteAgent } from "eve";
+
+export default defineDynamic({
+ events: {
+ "session.started": () => ({
+ researcher: ${factoryCall},
+ writer: ${factoryCall},
+ }),
+ },
+});
+`;
+ const code = await transformSource(source);
+
+ const declarations = [...code.matchAll(/function (__eve_dynamic_remote_credentials_\w+)\(/g)];
+ expect(declarations).toHaveLength(1);
+
+ // Both call sites must reference the shared hoisted implementation.
+ const name = declarations[0]![1]!;
+ expect(code.split(name).length - 1).toBeGreaterThanOrEqual(3);
+ });
});
diff --git a/packages/eve/src/internal/workflow-bundle/dynamic-remote-agent-transform.ts b/packages/eve/src/internal/workflow-bundle/dynamic-remote-agent-transform.ts
index 25f243378..f22e3594d 100644
--- a/packages/eve/src/internal/workflow-bundle/dynamic-remote-agent-transform.ts
+++ b/packages/eve/src/internal/workflow-bundle/dynamic-remote-agent-transform.ts
@@ -1,9 +1,12 @@
+import { createHash } from "node:crypto";
+
import { parseWithNitroRolldownAst } from "#internal/bundler/nitro-rolldown.js";
import {
findProperty,
type DynamicToolAstNode as AstNode,
walkNode,
} from "#internal/workflow-bundle/dynamic-tool-ast-references.js";
+import { stableModuleId } from "#internal/workflow-bundle/stable-module-id.js";
interface CredentialsFactoryInfo {
readonly authPropertySource?: string;
@@ -14,8 +17,6 @@ interface CredentialsFactoryInfo {
readonly hoistedName: string;
}
-let transformCounter = 0;
-
/**
* Hoists dynamic remote auth and headers into registered factories so durable
* selections carry only a function id, never credential values or closures.
@@ -33,12 +34,17 @@ export async function transformDynamicRemoteAgentCredentials(
}
const ast = (await parseWithNitroRolldownAst(filename, source)) as AstNode;
- const factories = findCredentialsFactories(source, ast);
+ const factories = findCredentialsFactories(filename, source, ast);
return factories.length === 0 ? null : applyTransform(source, factories);
}
-function findCredentialsFactories(source: string, ast: AstNode): CredentialsFactoryInfo[] {
+function findCredentialsFactories(
+ filename: string,
+ source: string,
+ ast: AstNode,
+): CredentialsFactoryInfo[] {
const factories: CredentialsFactoryInfo[] = [];
+ const moduleId = stableModuleId(filename);
walkNode(ast, (node) => {
if (
@@ -60,13 +66,20 @@ function findCredentialsFactories(source: string, ast: AstNode): CredentialsFact
if (auth === undefined && headers === undefined) {
return false;
}
+ // Content-addressed so the id survives rebuilds and never collides across
+ // modules or transform order; editing the factory itself invalidates it.
+ const callSource = source.slice(node.start, node.end);
+ const hash = createHash("sha256")
+ .update(`${moduleId}//${callSource}`)
+ .digest("hex")
+ .slice(0, 16);
factories.push({
authPropertySource: sliceNode(source, auth),
callEnd: node.end,
- callSource: source.slice(node.start, node.end),
+ callSource,
callStart: node.start,
headersPropertySource: sliceNode(source, headers),
- hoistedName: `__eve_dynamic_remote_credentials_${transformCounter++}`,
+ hoistedName: `__eve_dynamic_remote_credentials_${hash}`,
});
return false;
});
@@ -84,20 +97,27 @@ function applyTransform(
const hoistedFunctions: string[] = [];
const registrations: string[] = [];
+ // Byte-identical factories share one hoisted declaration so the emitted
+ // module never declares the same top-level function twice.
+ const emittedNames = new Set<string>();
+
for (const credentials of factories) {
const properties = [credentials.authPropertySource, credentials.headersPropertySource].filter(
(property) => property !== undefined,
);
const stepId = `eve:dynamic-remote-agent//${credentials.hoistedName}`;
- hoistedFunctions.push(
- `function ${credentials.hoistedName}() {\n` +
- ` return { ${properties.join(", ")} };\n` +
- `}`,
- );
- registrations.push(`${credentials.hoistedName}.stepId = ${JSON.stringify(stepId)};`);
- registrations.push(
- `__eveStepRegistry.set(${JSON.stringify(stepId)}, ${credentials.hoistedName});`,
- );
+ if (!emittedNames.has(credentials.hoistedName)) {
+ emittedNames.add(credentials.hoistedName);
+ hoistedFunctions.push(
+ `function ${credentials.hoistedName}() {\n` +
+ ` return { ${properties.join(", ")} };\n` +
+ `}`,
+ );
+ registrations.push(`${credentials.hoistedName}.stepId = ${JSON.stringify(stepId)};`);
+ registrations.push(
+ `__eveStepRegistry.set(${JSON.stringify(stepId)}, ${credentials.hoistedName});`,
+ );
+ }
replacements.push({
start: credentials.callStart,
end: credentials.callEnd,
diff --git a/packages/eve/src/internal/workflow-bundle/dynamic-tool-transform.test.ts b/packages/eve/src/internal/workflow-bundle/dynamic-tool-transform.test.ts
index 9bfe0bc47..e3871c315 100644
--- a/packages/eve/src/internal/workflow-bundle/dynamic-tool-transform.test.ts
+++ b/packages/eve/src/internal/workflow-bundle/dynamic-tool-transform.test.ts
@@ -3,6 +3,7 @@ import { describe, expect, it, beforeEach } from "vitest";
import { transformDynamicToolExecute } from "./dynamic-tool-transform.js";
import {
collectDurableDynamicToolCallbacks,
+ readDurableDynamicCallback,
stampDurableDynamicToolCallbacks,
} from "#shared/durable-dynamic-tool-callbacks.js";
@@ -26,7 +27,6 @@ async function transformAndEval(
handlerArgs: Record<string, unknown> = {},
): Promise<{
code: string;
- registry: Map<string, Function>;
callHandler: () => Promise<Record<string, unknown>>;
}> {
const result = await transformDynamicToolExecute(filename, source);
@@ -65,12 +65,8 @@ async function transformAndEval(
const evalFn = new Function("defineDynamic", "defineTool", `${code}\nreturn __exported;`);
evalFn(defineDynamic, defineTool);
- const registrySym = Symbol.for("@workflow/core//registeredSteps");
- const registry = (globalThis as Record<symbol, Map<string, Function>>)[registrySym] ?? new Map();
-
return {
code,
- registry,
callHandler: async () => {
if (!capturedHandler.fn) throw new Error("No handler captured");
const event = handlerArgs.event ?? {};
@@ -80,9 +76,17 @@ async function transformAndEval(
};
}
-// Clear step registrations between tests so each assertion observes only its module.
+type StampedCallbacks = Record<string, { callback: Function; closure: Record<string, unknown> }>;
+
+function durableCallbacks(tool: unknown): StampedCallbacks {
+ return (tool as Record<symbol, StampedCallbacks>)[
+ Symbol.for("eve:durable-dynamic-tool-callbacks")
+ ]!;
+}
+
+// Clear resolve-time registrations between tests so each assertion observes only its module.
beforeEach(() => {
- const sym = Symbol.for("@workflow/core//registeredSteps");
+ const sym = Symbol.for("eve:dynamic-tool-callbacks");
const reg = (globalThis as Record<symbol, Map<string, Function> | undefined>)[sym];
if (reg) reg.clear();
});
@@ -130,13 +134,10 @@ export default defineDynamic({
});
`;
- const { callHandler, registry } = await transformAndEval("tools/all-phases.ts", source);
+ const { callHandler } = await transformAndEval("tools/all-phases.ts", source);
const tools = await callHandler();
const guarded = tools.guarded as Record<string | symbol, unknown>;
- const callbacks = guarded[Symbol.for("eve:durable-dynamic-tool-callbacks")] as Record<
- string,
- { stepId: string; closure: Record<string, unknown> }
- >;
+ const callbacks = durableCallbacks(guarded);
expect(Object.keys(callbacks)).toEqual([
"execute",
@@ -148,9 +149,9 @@ export default defineDynamic({
expect(callbacks.approvalRequest!.closure).toEqual({ requestReason: "confirm" });
expect(callbacks.approvalResponse!.closure).toEqual({ allowedResponder: "user-123" });
expect(callbacks.toModelOutput!.closure).toEqual({ projectionPrefix: "visible" });
- expect(new Set(Object.values(callbacks).map((callback) => callback.stepId)).size).toBe(4);
+ expect(new Set(Object.values(callbacks).map((callback) => callback!.callback)).size).toBe(4);
for (const callback of Object.values(callbacks)) {
- expect(registry.has(callback.stepId)).toBe(true);
+ expect(callback!.callback).toBeTypeOf("function");
}
});
@@ -198,12 +199,9 @@ export default defineDynamic({
expect(tool.request).toBeUndefined();
expect(tool.approval).toBeTypeOf("function");
expect(await (tool.approval as Function)({})).toBe("user-approval");
- expect(tool[Symbol.for("eve:durable-dynamic-tool-callbacks")]).toMatchObject({
- approvalRequest: {
- closure: {},
- stepId: expect.stringContaining("/approvalRequest/"),
- },
- });
+ const callbacks = durableCallbacks(tool);
+ expect(callbacks.approvalRequest!.closure).toEqual({});
+ expect(callbacks.approvalRequest!.callback).toBeTypeOf("function");
}
});
@@ -305,15 +303,15 @@ export default defineDynamic({
const tools = await callHandler();
const tool = tools.tool as Record<string | symbol, unknown>;
- // __closureVars should have a snapshot of the config
- const closureVars = tool.__closureVars as Record<string, unknown>;
+ // The stamped closure should have a snapshot of the config
+ const closureVars = durableCallbacks(tool).execute!.closure;
expect(closureVars).toBeDefined();
const config = closureVars.config as Record<string, unknown>;
expect(config.endpoint).toBe("/api/v1");
expect(config.retries).toBe(3);
});
- it("__executeStepFn is registered and callable", async () => {
+ it("stamped execute callback is callable with snapshotted vars", async () => {
const source = `
import { defineDynamic, defineTool } from "eve/tools";
@@ -333,15 +331,13 @@ export default defineDynamic({
});
`;
- const { callHandler, registry } = await transformAndEval("tools/calc.ts", source);
+ const { callHandler } = await transformAndEval("tools/calc.ts", source);
const tools = await callHandler();
const calc = tools.calc as Record<string, unknown>;
- // __executeStepFn should be a function registered in the step registry
- const stepFn = calc.__executeStepFn as Function & { stepId?: string };
+ // The stamped descriptor carries the hoisted implementation
+ const stepFn = durableCallbacks(calc).execute!.callback;
expect(typeof stepFn).toBe("function");
- expect(stepFn.stepId).toBeDefined();
- expect(registry.has(stepFn.stepId!)).toBe(true);
// Calling the step function directly with __vars and input should work
const result = stepFn({ multiplier: 10 }, { x: 5 });
@@ -369,20 +365,20 @@ export default defineDynamic({
});
`;
- const { callHandler, registry } = await transformAndEval("tools/format.ts", source);
+ const { callHandler } = await transformAndEval("tools/format.ts", source);
const tools = await callHandler();
const format = tools.format as Record<string, unknown>;
// Simulate what the replay path does:
- // 1. Get the step function from registry
- const stepFn = format.__executeStepFn as Function & { stepId: string };
- const registeredFn = registry.get(stepFn.stepId)!;
- expect(registeredFn).toBeDefined();
+ // 1. Get the registered implementation from the stamped descriptor
+ const descriptor = durableCallbacks(format).execute!;
+ const registeredFn = descriptor.callback;
+ expect(registeredFn).toBeTypeOf("function");
// 2. Get the serialized closure vars (simulating JSON round-trip)
- const closureVars = JSON.parse(JSON.stringify(format.__closureVars));
+ const closureVars = JSON.parse(JSON.stringify(descriptor.closure));
- // 3. Call the step function with stored vars + new input
+ // 3. Call the implementation with stored vars + new input
const result = registeredFn(closureVars, { value: "hello" });
expect(result).toBe("RESULT::hello");
});
@@ -430,8 +426,8 @@ export default defineDynamic({
});
// Each tool should have a different step function
- const readStepFn = (tools.read_data as Record<string, unknown>).__executeStepFn as Function;
- const writeStepFn = (tools.write_data as Record<string, unknown>).__executeStepFn as Function;
+ const readStepFn = durableCallbacks(tools.read_data).execute!.callback;
+ const writeStepFn = durableCallbacks(tools.write_data).execute!.callback;
expect(readStepFn).not.toBe(writeStepFn);
});
@@ -475,12 +471,12 @@ export default defineDynamic({
const alpha = tools.probe_alpha as Record<string, unknown>;
const beta = tools.probe_beta as Record<string, unknown>;
- expect(alpha.__closureVars).toEqual({});
+ expect(durableCallbacks(alpha).execute!.closure).toEqual({});
expect((alpha.execute as Function)({ q: "one" })).toEqual({
note: "answer from app tools only",
url: "/x/one",
});
- expect(beta.__closureVars).toEqual({
+ expect(durableCallbacks(beta).execute!.closure).toEqual({
cred: { a: 1 },
url: "https://example.com",
});
@@ -519,7 +515,7 @@ export default defineDynamic({
const tool = tools.tool as Record<string, unknown>;
const execute = tool.execute as Function;
- expect(tool.__closureVars).toEqual({
+ expect(durableCallbacks(tool).execute!.closure).toEqual({
fallback: "missing",
field: "value",
});
@@ -551,7 +547,7 @@ export default defineDynamic({
const tools = await callHandler();
const tool = tools.tool as Record<string, unknown>;
- expect(tool.__closureVars).toEqual({ result: "captured" });
+ expect(durableCallbacks(tool).execute!.closure).toEqual({ result: "captured" });
expect((tool.execute as Function)()).toBe("captured");
});
@@ -732,14 +728,12 @@ export default defineDynamic({
`;
const { callHandler, code } = await transformAndEval("tools/action-result-tool.ts", source);
- // Verify the transform injected __executeStepFn
- expect(code).toContain("__executeStepFn");
- expect(code).toContain("__closureVars");
+ // Verify the transform stamped the callback with its hoisted implementation
+ expect(code).toContain("__eveStampDynamicCallback");
const tools = await callHandler();
const billingEntry = tools.billing as Record<string, unknown>;
- expect(billingEntry.__executeStepFn).toBeDefined();
- expect(billingEntry.__closureVars).toBeDefined();
+ expect(readDurableDynamicCallback(billingEntry.execute)?.callback).toBeTypeOf("function");
const execFn = billingEntry.execute as Function;
expect(await execFn()).toEqual({ called: "billing", endpoint: "https://billing.api" });
@@ -791,9 +785,13 @@ export default defineDynamic({
query: "all",
});
- // Both should have __executeStepFn for replay
- expect((tools.search as Record<string, unknown>).__executeStepFn).toBeDefined();
- expect((tools.export as Record<string, unknown>).__executeStepFn).toBeDefined();
+ // Both should have a stamped execute implementation for replay
+ expect(durableCallbacks(tools.search as Record<string, symbol>).execute!.callback).toBeTypeOf(
+ "function",
+ );
+ expect(durableCallbacks(tools.export as Record<string, symbol>).execute!.callback).toBeTypeOf(
+ "function",
+ );
});
it("description computed by a function is captured at event time, not re-evaluated", async () => {
@@ -835,14 +833,8 @@ export default defineDynamic({
// Closure vars are captured at wrapper call time. Alpha was
// created when counter was 1, beta when counter was 2.
- const alphaVars = (tools.alpha as Record<string, unknown>).__closureVars as Record<
- string,
- unknown
- >;
- const betaVars = (tools.beta as Record<string, unknown>).__closureVars as Record<
- string,
- unknown
- >;
+ const alphaVars = durableCallbacks(tools.alpha).execute!.closure;
+ const betaVars = durableCallbacks(tools.beta).execute!.closure;
expect(alphaVars.counter).toBe(1);
expect(betaVars.counter).toBe(2);
});
@@ -1045,18 +1037,17 @@ export default defineDynamic({
});
`;
- const { callHandler, registry } = await transformAndEval("tools/replay.ts", source);
+ const { callHandler } = await transformAndEval("tools/replay.ts", source);
const tools = await callHandler();
const search = tools.search as Record<string, unknown>;
// Live call
const liveResult = (search.execute as Function)({ q: "test" });
- // Replay: serialize → deserialize → call step function
- const stepFn = search.__executeStepFn as Function & { stepId: string };
- const serializedVars = JSON.parse(JSON.stringify(search.__closureVars));
- const registeredFn = registry.get(stepFn.stepId)!;
- const replayResult = registeredFn(serializedVars, { q: "test" });
+ // Replay: serialize → deserialize → call the stamped implementation
+ const descriptor = durableCallbacks(search).execute!;
+ const serializedVars = JSON.parse(JSON.stringify(descriptor.closure));
+ const replayResult = descriptor.callback(serializedVars, { q: "test" });
// Live and replay must produce identical results
expect(replayResult).toEqual(liveResult);
@@ -1738,7 +1729,7 @@ export default defineDynamic({
});
`;
- const { callHandler, registry } = await transformAndEval("tools/var-replay.ts", source);
+ const { callHandler } = await transformAndEval("tools/var-replay.ts", source);
const tools = await callHandler();
const info = tools.info as Record<string, unknown>;
@@ -1747,10 +1738,9 @@ export default defineDynamic({
expect(liveResult).toBe("Acme (us-east)");
// Replay
- const stepFn = info.__executeStepFn as Function & { stepId: string };
- const serializedVars = JSON.parse(JSON.stringify(info.__closureVars));
- const registeredFn = registry.get(stepFn.stepId)!;
- const replayResult = registeredFn(serializedVars);
+ const descriptor = durableCallbacks(info).execute!;
+ const serializedVars = JSON.parse(JSON.stringify(descriptor.closure));
+ const replayResult = descriptor.callback(serializedVars);
expect(replayResult).toBe("Acme (us-east)");
});
@@ -1777,7 +1767,7 @@ export default defineDynamic({
});
`;
- const { callHandler, registry } = await transformAndEval("tools/nested-replay.ts", source);
+ const { callHandler } = await transformAndEval("tools/nested-replay.ts", source);
const tools = await callHandler();
const search = tools.search as Record<string, unknown>;
@@ -1785,10 +1775,9 @@ export default defineDynamic({
const liveResult = (search.execute as Function)({ q: "test" });
// Replay
- const stepFn = search.__executeStepFn as Function & { stepId: string };
- const serializedVars = JSON.parse(JSON.stringify(search.__closureVars));
- const registeredFn = registry.get(stepFn.stepId)!;
- const replayResult = registeredFn(serializedVars, { q: "test" });
+ const descriptor = durableCallbacks(search).execute!;
+ const serializedVars = JSON.parse(JSON.stringify(descriptor.closure));
+ const replayResult = descriptor.callback(serializedVars, { q: "test" });
expect(replayResult).toEqual(liveResult);
expect(replayResult).toEqual({ url: "https://api.example.com/search", query: "test" });
@@ -1936,17 +1925,13 @@ export default defineDynamic({
});
`;
- const { callHandler, registry } = await transformAndEval("lib/module-reference.ts", source);
+ const { callHandler } = await transformAndEval("lib/module-reference.ts", source);
const tools = await callHandler();
const marker = tools.marker as Record<string | symbol, unknown>;
- const callbacks = marker[Symbol.for("eve:durable-dynamic-tool-callbacks")] as Record<
- string,
- { closure: Record<string, unknown>; stepId: string }
- >;
- const execute = callbacks.execute!;
+ const execute = durableCallbacks(marker).execute!;
expect(execute.closure).toEqual({});
- expect(registry.get(execute.stepId)!(execute.closure, { value: "ok" })).toBe("module:ok");
+ expect(execute.callback(execute.closure, { value: "ok" })).toBe("module:ok");
});
it("preserves async generator callbacks", async () => {
@@ -2014,9 +1999,8 @@ export default defineTool({
const before = await transformDynamicToolExecute("agent/lib/target.ts", target);
await transformDynamicToolExecute("agent/lib/unrelated.ts", unrelated);
const after = await transformDynamicToolExecute("agent/lib/target.ts", target);
- const ids = (code: string) => [...new Set(code.match(/eve:dynamic-tool\/\/[^"\s]+/g) ?? [])];
- expect(ids(after!.code)).toEqual(ids(before!.code));
+ expect(after!.code).toBe(before!.code);
});
it("every hoisted function has balanced braces", async () => {
@@ -2067,7 +2051,7 @@ export default defineDynamic({
expect(count).toBeGreaterThanOrEqual(2);
});
- it("every execute replacement includes __executeStepFn and __closureVars", async () => {
+ it("every execute replacement is stamped with its hoisted implementation", async () => {
const source = `
import { defineDynamic, defineTool } from "eve/tools";
@@ -2088,18 +2072,13 @@ export default defineDynamic({
expect(result).not.toBeNull();
const code = result!.code;
- const executeCount = (code.match(/execute:/g) || []).length;
- const stepFnCount = (code.match(/__executeStepFn:/g) || []).length;
- const closureVarsCount = (code.match(/__closureVars:/g) || []).length;
+ const stampedExecuteCount = (code.match(/execute: __eveStampDynamicCallback\(/g) || []).length;
- // Each execute replacement should have exactly one __executeStepFn
- // and one __closureVars sibling
- expect(executeCount).toBe(stepFnCount);
- expect(executeCount).toBe(closureVarsCount);
- expect(executeCount).toBeGreaterThanOrEqual(2);
+ // Each execute replacement should be wrapped in exactly one stamp call
+ expect(stampedExecuteCount).toBe(2);
});
- it("hoisted functions are registered in the step registry before use", async () => {
+ it("stamped wrappers reference hoisted implementations", async () => {
const source = `
import { defineDynamic, defineTool } from "eve/tools";
@@ -2122,12 +2101,15 @@ export default defineDynamic({
expect(result).not.toBeNull();
const code = result!.code;
- // Function definition must come before registry.set
- const fnDefIndex = code.indexOf("function __eve_dynamic_exec_");
- const registrySetIndex = code.indexOf("__eveStepRegistry.set");
- expect(fnDefIndex).toBeLessThan(registrySetIndex);
- expect(fnDefIndex).toBeGreaterThan(-1);
- expect(registrySetIndex).toBeGreaterThan(-1);
+ // Every hoisted function must be defined in the module suffix and
+ // referenced by the live stamped wrapper.
+ const hoistedNames = [...code.matchAll(/function (__eve_dynamic_\w+)\(/g)].map(
+ (match) => match[1]!,
+ );
+ expect(hoistedNames.length).toBeGreaterThanOrEqual(1);
+ for (const name of hoistedNames) {
+ expect(code.split(name).length - 1).toBeGreaterThanOrEqual(2);
+ }
});
it("only vars referenced in execute body are captured in __vars", async () => {
@@ -2234,7 +2216,7 @@ export default defineDynamic({
const result = await transformDynamicToolExecute("tools/singular.ts", source);
expect(result).not.toBeNull();
expect(result!.code).toContain("__eve_dynamic_exec_");
- expect(result!.code).toContain("__eveStepRegistry");
+ expect(result!.code).toContain("__eveStampDynamicCallback");
});
it("preserves imports and module-level declarations", async () => {
diff --git a/packages/eve/src/internal/workflow-bundle/dynamic-tool-transform.ts b/packages/eve/src/internal/workflow-bundle/dynamic-tool-transform.ts
index 85ddd9800..05933330e 100644
--- a/packages/eve/src/internal/workflow-bundle/dynamic-tool-transform.ts
+++ b/packages/eve/src/internal/workflow-bundle/dynamic-tool-transform.ts
@@ -1,12 +1,10 @@
/**
- * Stamps callbacks passed to authored `defineTool()` calls with stable replay
- * descriptors. Each callback is hoisted independently, registered under a
- * module-and-source-coordinate id, and receives only the lexical values its
- * body references.
+ * Stamps callbacks passed to authored `defineTool()` calls with durable replay
+ * descriptors. Each callback body is hoisted into a module-suffix function and
+ * the live callback is stamped with that function plus the lexical values its
+ * body references; identity `(toolName, phase)` is assigned at resolve time.
*/
-import { createHash } from "node:crypto";
-
import { parseWithNitroRolldownAst } from "#internal/bundler/nitro-rolldown.js";
import {
collectReferencedIdentifierNames,
@@ -30,8 +28,6 @@ interface CallbackInfo {
readonly propertyName: CallbackPropertyName;
readonly propEnd: number;
readonly propStart: number;
- readonly sourceEnd: number;
- readonly sourceStart: number;
}
interface ScopeEntry {
@@ -56,7 +52,7 @@ export async function transformDynamicToolExecute(
const callbacks: CallbackInfo[] = [];
walkForCallbacks(source, ast, callbacks, [], defineToolAliases);
- return callbacks.length === 0 ? null : applyTransform(filename, source, callbacks);
+ return callbacks.length === 0 ? null : applyTransform(source, callbacks);
}
// Keep the old export name for backward compatibility with the plugin.
@@ -208,8 +204,6 @@ function collectCallbackProperty(
propertyName,
propEnd: property.end,
propStart: property.start,
- sourceEnd: value.end,
- sourceStart: value.start,
});
return;
}
@@ -227,23 +221,15 @@ function collectCallbackProperty(
propertyName,
propEnd: property.end,
propStart: property.start,
- sourceEnd: value.end,
- sourceStart: value.start,
});
}
}
-function applyTransform(
- filename: string,
- source: string,
- callbacks: readonly CallbackInfo[],
-): { code: string } {
+function applyTransform(source: string, callbacks: readonly CallbackInfo[]): { code: string } {
const replacements: Array<{ start: number; end: number; text: string }> = [];
const hoistedFunctions: string[] = [];
- const registrations: string[] = [];
- const moduleId = stableModuleId(filename);
- for (const callback of callbacks) {
+ for (const [index, callback] of callbacks.entries()) {
const referencedNames = collectReferencedIdentifierNames(callback.bodyNode);
const candidateVars = callback.nestedScopes.flatMap((scope) => [
...scope.params,
@@ -254,13 +240,11 @@ function applyTransform(
(name) => !callbackParamNames.has(name) && referencedNames.has(name),
);
const closure = allVars.length > 0 ? `{ ${allVars.join(", ")} }` : "{}";
- const coordinate = `${String(callback.sourceStart)}-${String(callback.sourceEnd)}`;
const safePhase = callback.phase.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
const hoistedName =
callback.phase === "execute"
- ? `__eve_dynamic_exec_${callback.sourceStart}`
- : `__eve_dynamic_${safePhase}_${callback.sourceStart}`;
- const stepId = `eve:dynamic-tool//${moduleId}/${callback.phase}/${coordinate}`;
+ ? `__eve_dynamic_exec_${index}`
+ : `__eve_dynamic_${safePhase}_${index}`;
const originalParams = callback.params;
const hoistedParams = originalParams ? `__vars, ${originalParams}` : "__vars";
const varsDestructure = allVars.length > 0 ? `const ${closure} = __vars;\n ` : "";
@@ -273,21 +257,13 @@ function applyTransform(
` ${varsDestructure}${bodyContent}\n` +
`}`,
);
- registrations.push(`${hoistedName}.stepId = ${JSON.stringify(stepId)};`);
- registrations.push(`__eveStepRegistry.set(${JSON.stringify(stepId)}, ${hoistedName});`);
const wrapper = createLiveWrapper(callback, hoistedName, closure);
- const stamped = `__eveStampDynamicCallback(${wrapper}, ${JSON.stringify(stepId)}, ${closure})`;
- const replacement = [`${callback.propertyName}: ${stamped}`];
- if (callback.phase === "execute") {
- // Retained for generated-output compatibility while durable runtime
- // metadata uses the phase-specific descriptor above.
- replacement.push(`__executeStepFn: ${hoistedName}`, `__closureVars: ${closure}`);
- }
+ const stamped = `__eveStampDynamicCallback(${wrapper}, ${hoistedName}, ${closure})`;
replacements.push({
end: callback.propEnd,
start: callback.propStart,
- text: replacement.join(",\n "),
+ text: `${callback.propertyName}: ${stamped}`,
});
}
@@ -297,17 +273,13 @@ function applyTransform(
}
const registrySetup = [
- `var __eveStepRegistrySym = Symbol.for("@workflow/core//registeredSteps");`,
- `if (!globalThis[__eveStepRegistrySym]) globalThis[__eveStepRegistrySym] = new Map();`,
- `var __eveStepRegistry = globalThis[__eveStepRegistrySym];`,
`var __eveDurableCallbackSym = Symbol.for("eve:durable-dynamic-callback");`,
- `function __eveStampDynamicCallback(callback, stepId, closure) {`,
- ` Object.defineProperty(callback, __eveDurableCallbackSym, { configurable: true, value: { stepId, closure } });`,
+ `function __eveStampDynamicCallback(callback, impl, closure) {`,
+ ` Object.defineProperty(callback, __eveDurableCallbackSym, { configurable: true, value: { callback: impl, closure } });`,
` return callback;`,
`}`,
].join("\n");
- const suffix = [...hoistedFunctions, ...registrations].join("\n");
- return { code: `${registrySetup}\n${code}\n\n${suffix}\n` };
+ return { code: `${registrySetup}\n${code}\n\n${hoistedFunctions.join("\n")}\n` };
}
function createLiveWrapper(callback: CallbackInfo, hoistedName: string, closure: string): string {
@@ -322,19 +294,6 @@ function createLiveWrapper(callback: CallbackInfo, hoistedName: string, closure:
return `${asyncPrefix}(...__args) => ${awaitPrefix}${hoistedName}(${closure}, ...__args)`;
}
-function stableModuleId(filename: string): string {
- let normalized = filename.replaceAll("\\", "/").replace(/[?#].*$/, "");
- const nodeModules = normalized.lastIndexOf("/node_modules/");
- if (nodeModules >= 0) {
- normalized = normalized.slice(nodeModules + "/node_modules/".length);
- } else {
- const cwd = process.cwd().replaceAll("\\", "/");
- if (normalized.startsWith(`${cwd}/`)) normalized = normalized.slice(cwd.length + 1);
- }
-
- return createHash("sha256").update(normalized).digest("hex").slice(0, 32);
-}
-
function dedupeShadowed(names: readonly string[]): string[] {
const seen = new Set<string>();
const deduped: string[] = [];
diff --git a/packages/eve/src/internal/workflow-bundle/stable-module-id.ts b/packages/eve/src/internal/workflow-bundle/stable-module-id.ts
new file mode 100644
index 000000000..f09f6cf46
--- /dev/null
+++ b/packages/eve/src/internal/workflow-bundle/stable-module-id.ts
@@ -0,0 +1,19 @@
+import { createHash } from "node:crypto";
+
+/**
+ * Content-independent module identity derived from the module path alone, so
+ * ids minted at build time stay comparable across rebuilds that do not move
+ * the file.
+ */
+export function stableModuleId(filename: string): string {
+ let normalized = filename.replaceAll("\\", "/").replace(/[?#].*$/, "");
+ const nodeModules = normalized.lastIndexOf("/node_modules/");
+ if (nodeModules >= 0) {
+ normalized = normalized.slice(nodeModules + "/node_modules/".length);
+ } else {
+ const cwd = process.cwd().replaceAll("\\", "/");
+ if (normalized.startsWith(`${cwd}/`)) normalized = normalized.slice(cwd.length + 1);
+ }
+
+ return createHash("sha256").update(normalized).digest("hex").slice(0, 32);
+}
diff --git a/packages/eve/src/public/tools/approval/approval-helpers.test.ts b/packages/eve/src/public/tools/approval/approval-helpers.test.ts
index 57a059606..b6c637f78 100644
--- a/packages/eve/src/public/tools/approval/approval-helpers.test.ts
+++ b/packages/eve/src/public/tools/approval/approval-helpers.test.ts
@@ -3,41 +3,32 @@ import { describe, expect, it } from "vitest";
import { always, never, once } from "#public/tools/approval/approval-helpers.js";
import { readDurableDynamicCallback } from "#shared/durable-dynamic-tool-callbacks.js";
-function getStepRegistry(): Map<string, Function> {
- return (globalThis as Record<symbol, Map<string, Function> | undefined>)[
- Symbol.for("@workflow/core//registeredSteps")
- ]!;
-}
-
describe("dynamic tool approval helpers", () => {
it.each([
["always", always(), "user-approval"],
["never", never(), "not-applicable"],
] as const)("gives %s a stable replay descriptor", async (_name, policy, expected) => {
const reference = readDurableDynamicCallback(policy);
- expect(reference).toEqual({
- closure: {},
- stepId: expect.stringMatching(/^eve:dynamic-tool-helper\/\/approval\//),
- });
+ expect(reference?.callback).toBeTypeOf("function");
+ expect(reference?.closure).toEqual({});
- expect(await getStepRegistry().get(reference!.stepId)!(reference!.closure, {})).toBe(expected);
+ expect(await reference!.callback(reference!.closure, {} as never)).toBe(expected);
});
it("replays once against the current approval context", async () => {
const reference = readDurableDynamicCallback(once())!;
- const replay = getStepRegistry().get(reference.stepId)!;
expect(
- await replay(reference.closure, {
+ await reference.callback(reference.closure, {
approvedTools: new Set(),
toolName: "guarded",
- }),
+ } as never),
).toBe("user-approval");
expect(
- await replay(reference.closure, {
+ await reference.callback(reference.closure, {
approvedTools: new Set(["guarded"]),
toolName: "guarded",
- }),
+ } as never),
).toBe("not-applicable");
});
});
diff --git a/packages/eve/src/public/tools/approval/approval-helpers.ts b/packages/eve/src/public/tools/approval/approval-helpers.ts
index 4eb519150..0c8de338c 100644
--- a/packages/eve/src/public/tools/approval/approval-helpers.ts
+++ b/packages/eve/src/public/tools/approval/approval-helpers.ts
@@ -1,13 +1,6 @@
import type { ApprovalContext, ApprovalPolicy } from "#public/definitions/approval.js";
import type { JsonObject } from "#shared/json.js";
-import {
- registerDurableDynamicCallback,
- stampDurableDynamicCallback,
-} from "#shared/durable-dynamic-tool-callbacks.js";
-
-const ALWAYS_STEP_ID = "eve:dynamic-tool-helper//approval/always/v1";
-const NEVER_STEP_ID = "eve:dynamic-tool-helper//approval/never/v1";
-const ONCE_STEP_ID = "eve:dynamic-tool-helper//approval/once/v1";
+import { stampDurableDynamicCallback } from "#shared/durable-dynamic-tool-callbacks.js";
function alwaysApproval(_closure: JsonObject): "user-approval" {
return "user-approval";
@@ -24,18 +17,14 @@ function onceApproval(
return context.approvedTools.has(context.toolName) ? "not-applicable" : "user-approval";
}
-registerDurableDynamicCallback(ALWAYS_STEP_ID, alwaysApproval);
-registerDurableDynamicCallback(NEVER_STEP_ID, neverApproval);
-registerDurableDynamicCallback(ONCE_STEP_ID, onceApproval);
-
/**
* Returns an `approval` callback that always requires user approval before
* the tool executes.
*/
export function always<TInput = unknown>(): ApprovalPolicy<TInput> {
return stampDurableDynamicCallback(() => "user-approval", {
+ callback: alwaysApproval,
closure: {},
- stepId: ALWAYS_STEP_ID,
});
}
@@ -45,8 +34,8 @@ export function always<TInput = unknown>(): ApprovalPolicy<TInput> {
*/
export function never<TInput = unknown>(): ApprovalPolicy<TInput> {
return stampDurableDynamicCallback(() => "not-applicable", {
+ callback: neverApproval,
closure: {},
- stepId: NEVER_STEP_ID,
});
}
@@ -61,6 +50,6 @@ export function once<TInput = unknown>(): ApprovalPolicy<TInput> {
return stampDurableDynamicCallback(
({ approvedTools, toolName }) =>
approvedTools.has(toolName) ? "not-applicable" : "user-approval",
- { closure: {}, stepId: ONCE_STEP_ID },
+ { callback: onceApproval, closure: {} },
);
}
diff --git a/packages/eve/src/runtime/framework-tools/connection-search-dynamic.test.ts b/packages/eve/src/runtime/framework-tools/connection-search-dynamic.test.ts
index 1e267bda3..2ce85b3c6 100644
--- a/packages/eve/src/runtime/framework-tools/connection-search-dynamic.test.ts
+++ b/packages/eve/src/runtime/framework-tools/connection-search-dynamic.test.ts
@@ -436,14 +436,11 @@ describe("connection_search", () => {
session: { auth: { current: null, initiator: null }, id: "session-auth-replay" },
} satisfies DynamicResolveContext)) as DynamicToolSet;
const reference = readDurableDynamicToolCallbacks(tools["connection_search"]!)!.execute!;
- const registry = (globalThis as Record<symbol, Map<string, Function> | undefined>)[
- Symbol.for("@workflow/core//registeredSteps")
- ]!;
- return await registry.get(reference.stepId)!(reference.closure, {
+ return await reference.callback(reference.closure, {
connection: "salesforce",
keywords: "accounts",
- });
+ } as never);
});
expect(isAuthorizationSignal(result)).toBe(true);
diff --git a/packages/eve/src/runtime/framework-tools/connection-search-dynamic.ts b/packages/eve/src/runtime/framework-tools/connection-search-dynamic.ts
index 6157369d6..20bdf4b73 100644
--- a/packages/eve/src/runtime/framework-tools/connection-search-dynamic.ts
+++ b/packages/eve/src/runtime/framework-tools/connection-search-dynamic.ts
@@ -23,10 +23,7 @@ import {
} from "#public/definitions/approval.js";
import type { JsonValue } from "#public/types/json.js";
import type { JsonObject } from "#shared/json.js";
-import {
- registerDurableDynamicCallback,
- stampDurableDynamicToolCallbacks,
-} from "#shared/durable-dynamic-tool-callbacks.js";
+import { stampDurableDynamicToolCallbacks } from "#shared/durable-dynamic-tool-callbacks.js";
import { writeCachedToken } from "#runtime/connections/authorization-tokens.js";
import { principalKey, resolveConnectionPrincipal } from "#runtime/connections/principal.js";
import { resolveConnectionAuthorization } from "#runtime/connections/resolve-authorization.js";
@@ -404,14 +401,6 @@ export function extractDiscoveredTools(
return [...byQualifiedName.values()];
}
-const CONNECTION_SEARCH_EXECUTE_STEP_ID = "eve:framework-dynamic//connection-search/execute/v1";
-const DISCOVERED_TOOL_EXECUTE_STEP_ID =
- "eve:framework-dynamic//connection-search/discovered-execute/v1";
-const DISCOVERED_TOOL_APPROVAL_REQUEST_STEP_ID =
- "eve:framework-dynamic//connection-search/discovered-approval-request/v1";
-const DISCOVERED_TOOL_APPROVAL_RESPONSE_STEP_ID =
- "eve:framework-dynamic//connection-search/discovered-approval-response/v1";
-
function readDiscoveredToolClosure(closure: JsonObject): {
readonly connectionName: string;
readonly toolName: string;
@@ -522,20 +511,6 @@ async function authorizeDiscoveredConnectionToolApproval(
: await response(context);
}
-registerDurableDynamicCallback(
- CONNECTION_SEARCH_EXECUTE_STEP_ID,
- (_closure: JsonObject, input: ConnectionSearchInput) => executeConnectionSearch(input),
-);
-registerDurableDynamicCallback(DISCOVERED_TOOL_EXECUTE_STEP_ID, executeDiscoveredConnectionTool);
-registerDurableDynamicCallback(
- DISCOVERED_TOOL_APPROVAL_REQUEST_STEP_ID,
- requestDiscoveredConnectionToolApproval,
-);
-registerDurableDynamicCallback(
- DISCOVERED_TOOL_APPROVAL_RESPONSE_STEP_ID,
- authorizeDiscoveredConnectionToolApproval,
-);
-
// The step-scoped definition re-derives its tools from conversation history.
// After compaction removes old search results, those tools naturally disappear.
const connectionSearchDynamicDefinition = defineDynamic({
@@ -572,7 +547,10 @@ const connectionSearchDynamicDefinition = defineDynamic({
outputSchema: CONNECTION_SEARCH_OUTPUT_SCHEMA,
});
stampDurableDynamicToolCallbacks(connectionSearchTool, {
- execute: { closure: {}, stepId: CONNECTION_SEARCH_EXECUTE_STEP_ID },
+ execute: {
+ callback: (_closure, input) => executeConnectionSearch(input as ConnectionSearchInput),
+ closure: {},
+ },
});
tools["connection_search"] = connectionSearchTool;
@@ -594,13 +572,13 @@ const connectionSearchDynamicDefinition = defineDynamic({
},
});
stampDurableDynamicToolCallbacks(discoveredTool, {
- execute: { closure, stepId: DISCOVERED_TOOL_EXECUTE_STEP_ID },
+ execute: { callback: executeDiscoveredConnectionTool, closure },
...(approval === undefined
? {}
: {
approvalRequest: {
+ callback: requestDiscoveredConnectionToolApproval,
closure,
- stepId: DISCOVERED_TOOL_APPROVAL_REQUEST_STEP_ID,
},
}),
...(approval === undefined ||
@@ -609,8 +587,8 @@ const connectionSearchDynamicDefinition = defineDynamic({
? {}
: {
approvalResponse: {
+ callback: authorizeDiscoveredConnectionToolApproval,
closure,
- stepId: DISCOVERED_TOOL_APPROVAL_RESPONSE_STEP_ID,
},
}),
});
diff --git a/packages/eve/src/shared/durable-dynamic-tool-callbacks.ts b/packages/eve/src/shared/durable-dynamic-tool-callbacks.ts
index 1fa8db4bf..d19e9f3cb 100644
--- a/packages/eve/src/shared/durable-dynamic-tool-callbacks.ts
+++ b/packages/eve/src/shared/durable-dynamic-tool-callbacks.ts
@@ -2,8 +2,20 @@ import type { Approval } from "#public/definitions/approval.js";
import { resolveApprovalPolicy } from "#public/definitions/approval.js";
import type { JsonObject } from "#shared/json.js";
+export type DurableDynamicCallbackPhase =
+ | "approvalRequest"
+ | "approvalResponse"
+ | "execute"
+ | "toModelOutput";
+
+export type DurableDynamicCallbackFn = (closure: JsonObject, ...args: never[]) => unknown;
+
+/**
+ * Persisted binding for one callback phase. Identity is
+ * `(toolName, phase)` — carried by the surrounding metadata — so only the
+ * snapshotted closure values persist.
+ */
export interface DurableDynamicCallbackReference {
- readonly stepId: string;
readonly closure: JsonObject;
}
@@ -14,72 +26,104 @@ export interface DurableDynamicToolCallbacks {
readonly toModelOutput?: DurableDynamicCallbackReference;
}
-const DURABLE_CALLBACK_REFERENCE = Symbol.for("eve:durable-dynamic-callback");
+/** Live descriptor stamped on authored callbacks; `callback` never persists. */
+export interface StampedDurableDynamicCallback {
+ readonly callback: DurableDynamicCallbackFn;
+ readonly closure: JsonObject;
+}
+
+export type LiveDurableDynamicToolCallbacks = Partial<{
+ execute: StampedDurableDynamicCallback;
+ approvalRequest: StampedDurableDynamicCallback;
+ approvalResponse: StampedDurableDynamicCallback;
+ toModelOutput: StampedDurableDynamicCallback;
+}>;
+
+const STAMPED_CALLBACK = Symbol.for("eve:durable-dynamic-callback");
export const DURABLE_DYNAMIC_TOOL_CALLBACKS = Symbol.for("eve:durable-dynamic-tool-callbacks");
-const STEP_REGISTRY = Symbol.for("@workflow/core//registeredSteps");
-type Callback = (...args: never[]) => unknown;
+const REGISTRY = Symbol.for("eve:dynamic-tool-callbacks");
+
+type Registry = Map<string, Map<DurableDynamicCallbackPhase, DurableDynamicCallbackFn>>;
-function getStepRegistry(): Map<string, Function> {
- const global = globalThis as Record<symbol, Map<string, Function> | undefined>;
- const existing = global[STEP_REGISTRY];
+function getRegistry(): Registry {
+ const global = globalThis as Record<symbol, Registry | undefined>;
+ const existing = global[REGISTRY];
if (existing !== undefined) return existing;
- const registry = new Map<string, Function>();
- global[STEP_REGISTRY] = registry;
+ const registry: Registry = new Map();
+ global[REGISTRY] = registry;
return registry;
}
-/** Registers one module-stable replay entry point. Re-registration replaces the same code-owned id. */
-export function registerDurableDynamicCallback<TArgs extends unknown[], TResult>(
- stepId: string,
- callback: (closure: JsonObject, ...args: TArgs) => TResult,
-): void {
- if (stepId.length === 0) {
- throw new Error("A durable dynamic callback step id cannot be empty.");
+/**
+ * Binds the current implementation of one tool callback phase. Re-resolution
+ * replaces the binding, so replay after a redeploy runs the latest code.
+ */
+export function registerDurableDynamicCallback(input: {
+ readonly callback: DurableDynamicCallbackFn;
+ readonly phase: DurableDynamicCallbackPhase;
+ readonly toolName: string;
+}): void {
+ const registry = getRegistry();
+ let phases = registry.get(input.toolName);
+ if (phases === undefined) {
+ phases = new Map();
+ registry.set(input.toolName, phases);
}
- getStepRegistry().set(stepId, callback);
+ phases.set(input.phase, input.callback);
+}
+
+export function lookupDurableDynamicCallback(
+ toolName: string,
+ phase: DurableDynamicCallbackPhase,
+): DurableDynamicCallbackFn | undefined {
+ return getRegistry().get(toolName)?.get(phase);
}
-/** Marks a live callback with the descriptor needed to reconstruct it after a cold start. */
-export function stampDurableDynamicCallback<TCallback extends Callback>(
+/** Invokes a registered callback with its snapshotted closure and live arguments. */
+export function callDurableDynamicCallback(
+ callback: DurableDynamicCallbackFn,
+ closure: JsonObject,
+ ...args: unknown[]
+): unknown {
+ return (callback as (closure: JsonObject, ...args: unknown[]) => unknown)(closure, ...args);
+}
+
+/** True when any persisted callback of these tools has no registered binding. */
+export function hasUnregisteredDurableDynamicCallbacks(
+ metadata: readonly { callbacks: DurableDynamicToolCallbacks; name: string }[],
+): boolean {
+ return metadata.some((entry) =>
+ (Object.keys(entry.callbacks) as DurableDynamicCallbackPhase[]).some(
+ (phase) => lookupDurableDynamicCallback(entry.name, phase) === undefined,
+ ),
+ );
+}
+
+/** Marks a live callback with the descriptor needed to register it at resolve time. */
+export function stampDurableDynamicCallback<TCallback extends (...args: never[]) => unknown>(
callback: TCallback,
- reference: DurableDynamicCallbackReference,
+ descriptor: StampedDurableDynamicCallback,
): TCallback {
- Object.defineProperty(callback, DURABLE_CALLBACK_REFERENCE, {
+ Object.defineProperty(callback, STAMPED_CALLBACK, {
configurable: true,
- value: reference,
+ value: descriptor,
});
return callback;
}
-/** Creates a live callback backed by the same registered function used during durable replay. */
-export function createDurableDynamicCallback<TArgs extends unknown[], TResult>(input: {
- readonly closure: JsonObject;
- readonly callback: (closure: JsonObject, ...args: TArgs) => TResult;
- readonly stepId: string;
-}): (...args: TArgs) => TResult {
- registerDurableDynamicCallback(input.stepId, input.callback);
- const callback = (...args: TArgs) => input.callback(input.closure, ...args);
- return stampDurableDynamicCallback(callback, {
- closure: input.closure,
- stepId: input.stepId,
- });
-}
-
export function readDurableDynamicCallback(
callback: unknown,
-): DurableDynamicCallbackReference | undefined {
+): StampedDurableDynamicCallback | undefined {
if (typeof callback !== "function") return undefined;
- return Reflect.get(callback, DURABLE_CALLBACK_REFERENCE) as
- | DurableDynamicCallbackReference
- | undefined;
+ return Reflect.get(callback, STAMPED_CALLBACK) as StampedDurableDynamicCallback | undefined;
}
/** Copies phase-specific callback descriptors onto a branded tool definition. */
export function stampDurableDynamicToolCallbacks(
definition: object,
- callbacks: Partial<DurableDynamicToolCallbacks>,
+ callbacks: LiveDurableDynamicToolCallbacks,
): void {
Object.defineProperty(definition, DURABLE_DYNAMIC_TOOL_CALLBACKS, {
configurable: true,
@@ -89,9 +133,9 @@ export function stampDurableDynamicToolCallbacks(
export function collectDurableDynamicToolCallbacks(input: {
readonly approval?: Approval<never>;
- readonly execute: Callback;
- readonly toModelOutput?: Callback;
-}): Partial<DurableDynamicToolCallbacks> {
+ readonly execute: (...args: never[]) => unknown;
+ readonly toModelOutput?: (...args: never[]) => unknown;
+}): LiveDurableDynamicToolCallbacks {
const approvalRequest =
input.approval === undefined
? undefined
@@ -103,12 +147,7 @@ export function collectDurableDynamicToolCallbacks(input: {
const execute = readDurableDynamicCallback(input.execute);
const toModelOutput = readDurableDynamicCallback(input.toModelOutput);
- const callbacks: {
- execute?: DurableDynamicCallbackReference;
- approvalRequest?: DurableDynamicCallbackReference;
- approvalResponse?: DurableDynamicCallbackReference;
- toModelOutput?: DurableDynamicCallbackReference;
- } = {};
+ const callbacks: LiveDurableDynamicToolCallbacks = {};
if (execute !== undefined) callbacks.execute = execute;
if (approvalRequest !== undefined) callbacks.approvalRequest = approvalRequest;
if (approvalResponse !== undefined) callbacks.approvalResponse = approvalResponse;
@@ -118,8 +157,8 @@ export function collectDurableDynamicToolCallbacks(input: {
export function readDurableDynamicToolCallbacks(
definition: object,
-): Partial<DurableDynamicToolCallbacks> | undefined {
+): LiveDurableDynamicToolCallbacks | undefined {
return (definition as Record<symbol, unknown>)[DURABLE_DYNAMIC_TOOL_CALLBACKS] as
- | Partial<DurableDynamicToolCallbacks>
+ | LiveDurableDynamicToolCallbacks
| undefined;
}
diff --git a/packages/eve/test/scenarios/dynamic-tool-cold-replay.scenario.test.ts b/packages/eve/test/scenarios/dynamic-tool-cold-replay.scenario.test.ts
index f22894183..4afe9418a 100644
--- a/packages/eve/test/scenarios/dynamic-tool-cold-replay.scenario.test.ts
+++ b/packages/eve/test/scenarios/dynamic-tool-cold-replay.scenario.test.ts
@@ -196,12 +196,18 @@ describe("dynamic tool cold replay", () => {
expect(projection.pid).toBe(execute.pid);
}
+ // The fresh process rebinds persisted callbacks by re-running session
+ // resolvers exactly once (identity is the tool name, so the same
+ // definitions re-register); replay itself never depends on it.
const resolverRunsAfterRestart = (
await readFile(join(app.appRoot, ".dynamic-resolver-runs"), "utf8")
)
.trim()
.split("\n");
- expect(resolverRunsAfterRestart).toEqual(resolverRunsBeforeRestart);
+ expect(resolverRunsAfterRestart).toHaveLength(resolverRunsBeforeRestart.length + 1);
+ expect(resolverRunsAfterRestart.slice(0, resolverRunsBeforeRestart.length)).toEqual(
+ resolverRunsBeforeRestart,
+ );
} finally {
await server.stop();
}
diff --git a/packages/eve/test/scenarios/dynamic-tool-source-edit.scenario.test.ts b/packages/eve/test/scenarios/dynamic-tool-source-edit.scenario.test.ts
new file mode 100644
index 000000000..283d4ef69
--- /dev/null
+++ b/packages/eve/test/scenarios/dynamic-tool-source-edit.scenario.test.ts
@@ -0,0 +1,166 @@
+import { readFile, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+
+import { describe, expect, it } from "vitest";
+
+import { Client } from "../../src/client/index.js";
+import {
+ type ScenarioAppDescriptor,
+ useScenarioApp,
+} from "../../src/internal/testing/scenario-app.js";
+import {
+ DEV_SERVER_SCENARIO_TIMEOUT_MS,
+ TRANSACTIONAL_REBUILD_DESCRIPTOR,
+} from "./dev-server-descriptors.js";
+import { startEveDev, waitForCondition } from "./dev-server-harness.js";
+
+const scenarioApp = useScenarioApp();
+
+function editableFactorySource(build: number): string {
+ return `import { writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { defineTool as tool } from "eve/tools";
+import { z } from "zod";
+
+const BUILD = ${build};
+
+export function createEditableMarkerTool(key: string, version: string) {
+ return tool({
+ description: "Editable marker tool " + key + ".",
+ inputSchema: z.object({}),
+ approval: {
+ request() {
+ return "user-approval";
+ },
+ response() {
+ return { status: "allowed" };
+ },
+ },
+ execute() {
+ const output = { build: BUILD, key, pid: process.pid, version };
+ writeFileSync(
+ join(process.cwd(), ".editable-execute-" + key + ".json"),
+ JSON.stringify(output),
+ );
+ return output;
+ },
+ });
+}
+`;
+}
+
+const EDITABLE_TOOLS_SOURCE = `import { defineDynamic } from "eve/tools";
+import { createEditableMarkerTool } from "../lib/editable-factory.ts";
+
+export default defineDynamic({
+ events: {
+ "session.started": () => ({
+ alpha_marker: createEditableMarkerTool("alpha", "v1"),
+ beta_marker: createEditableMarkerTool("beta", "v1"),
+ }),
+ },
+});
+`;
+
+const EDITABLE_DYNAMIC_DESCRIPTOR: ScenarioAppDescriptor = {
+ ...TRANSACTIONAL_REBUILD_DESCRIPTOR,
+ name: "dynamic-tool-source-edit",
+ files: {
+ ...Object.fromEntries(
+ Object.entries(TRANSACTIONAL_REBUILD_DESCRIPTOR.files).filter(
+ ([path]) => path !== "agent/tools/get_weather.ts" && !path.startsWith("agent/skills/"),
+ ),
+ ),
+ "agent/lib/editable-factory.ts": editableFactorySource(1),
+ "agent/tools/editable-dynamic.ts": EDITABLE_TOOLS_SOURCE,
+ },
+};
+
+interface ExecuteMarker {
+ readonly build: number;
+ readonly key: string;
+ readonly pid: number;
+ readonly version: string;
+}
+
+async function readExecuteMarker(appRoot: string, key: string): Promise<ExecuteMarker> {
+ return JSON.parse(
+ await readFile(join(appRoot, `.editable-execute-${key}.json`), "utf8"),
+ ) as ExecuteMarker;
+}
+
+describe("dynamic tool source edits across a restart", () => {
+ it(
+ "replays parked approvals against the latest code under the same tool identity",
+ async () => {
+ const app = await scenarioApp(EDITABLE_DYNAMIC_DESCRIPTOR);
+ const pinnedEnv = {
+ VERCEL_DEPLOYMENT_ID: "dynamic-tool-source-edit",
+ WORKFLOW_INLINE_OWNERSHIP_LEASE_SECONDS: "1",
+ };
+ let server = await startEveDev(app.appRoot, { env: pinnedEnv });
+
+ try {
+ const client = new Client({ host: server.url });
+ const created = await client.sessions.create({ message: "Hello." });
+ await expect(created.response.result()).resolves.toMatchObject({
+ inputRequests: [],
+ status: "waiting",
+ });
+
+ const waiting = await (
+ await created.session.send("Call tools in parallel: alpha_marker, beta_marker")
+ ).result();
+ expect(waiting.status).toBe("waiting");
+ expect(waiting.inputRequests).toHaveLength(2);
+
+ // Edit the callback module while approvals are parked: pad the top of
+ // the file (shifting every byte offset below — the old identity scheme
+ // resolved parked calls by those offsets) and bump the built-in
+ // constant so the edited body is observable.
+ await writeFile(
+ join(app.appRoot, "agent", "lib", "editable-factory.ts"),
+ "// padding line\n// another padding line\n\n" + editableFactorySource(2),
+ );
+
+ const sessionState = created.session.state;
+
+ await server.crash();
+ await waitForCondition(async () => {
+ try {
+ await readFile(join(app.appRoot, ".eve", "dev-server-state.v1.json"));
+ return false;
+ } catch (error) {
+ return error instanceof Error && "code" in error && error.code === "ENOENT";
+ }
+ }, "The crashed development server did not release its state record.");
+ server = await startEveDev(app.appRoot, { env: pinnedEnv });
+
+ const resumedSession = new Client({ host: server.url }).sessions.attach(
+ sessionState.sessionId,
+ { streamIndex: sessionState.streamIndex },
+ );
+ const resumed = await (
+ await resumedSession.respond(
+ waiting.inputRequests.map((request) => ({
+ optionId: "approve",
+ requestId: request.requestId,
+ })),
+ )
+ ).result();
+ expect(resumed.status).toBe("waiting");
+
+ // Each parked call must run its own tool — never the other one — and
+ // both must run the edited body from the latest code.
+ const alpha = await readExecuteMarker(app.appRoot, "alpha");
+ const beta = await readExecuteMarker(app.appRoot, "beta");
+ expect(alpha).toMatchObject({ build: 2, key: "alpha", version: "v1" });
+ expect(beta).toMatchObject({ build: 2, key: "beta", version: "v1" });
+ expect(alpha.pid).toBe(beta.pid);
+ } finally {
+ await server.stop();
+ }
+ },
+ DEV_SERVER_SCENARIO_TIMEOUT_MS,
+ );
+});