Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): let tools end a turn without a reply (#4062)

Andrew Barba5a5561aadbe9
diff --git a/.changeset/tool-ends-turn-no-reply.md b/.changeset/tool-ends-turn-no-reply.md
new file mode 100644
index 000000000..857bd13ab
--- /dev/null
+++ b/.changeset/tool-ends-turn-no-reply.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Tools can now end a turn without a reply. Set `endsTurn: true` on a `defineTool` tool whose action is the whole answer, such as a reaction: once every call in the model's step succeeds, the turn completes with no final message, so channels and schedule sends post nothing. With `true`, eve appends a sentence to the tool's model-facing description saying the call ends the turn; pass a function instead to decide from the `execute` output. The new opt-in `no_reply` tool (`eve add tool/no_reply`, or `noReply()` from `eve/tools/no_reply`) uses it to let the agent stay quiet, for example when a scheduled check finds nothing to report. Slack now clears its thread status when a turn completes.
diff --git a/apps/docs/registry.json b/apps/docs/registry.json
index ab4fc7243..04b63d808 100644
--- a/apps/docs/registry.json
+++ b/apps/docs/registry.json
@@ -463,6 +463,19 @@
}
]
},
+ {
+ "name": "tool/no_reply",
+ "type": "registry:item",
+ "title": "No Reply",
+ "description": "End the turn without sending a reply.",
+ "files": [
+ {
+ "path": "registry/tools/no_reply.ts",
+ "type": "registry:file",
+ "target": "agent/tools/no_reply.ts"
+ }
+ ]
+ },
{
"name": "connection/browser-use",
"type": "registry:item",
diff --git a/apps/docs/registry/tools/no_reply.ts b/apps/docs/registry/tools/no_reply.ts
new file mode 100644
index 000000000..4e18ed0ae
--- /dev/null
+++ b/apps/docs/registry/tools/no_reply.ts
@@ -0,0 +1,3 @@
+import { noReply } from "eve/tools/no_reply";
+
+export default noReply();
diff --git a/docs/concepts/built-in-tools.md b/docs/concepts/built-in-tools.md
index d69454b04..2a472c139 100644
--- a/docs/concepts/built-in-tools.md
+++ b/docs/concepts/built-in-tools.md
@@ -359,6 +359,22 @@ export default defineTool({
Remove the file to remove the tool. `disableTool()` is unnecessary because `grep` is not added by default.
+### `no_reply`
+
+`no_reply` ends the turn without a reply. Use it when a scheduled check finds nothing to report, or when an action the agent already took is the whole answer. The model calls it with an optional `{ reason }`, which stays in the session history and traces and is never sent. The turn completes without a final message, so channels and schedule sends post nothing, and later turns see that the agent chose to stay quiet. Add it:
+
+```sh
+eve add tool/no_reply
+```
+
+```ts title="agent/tools/no_reply.ts"
+import { noReply } from "eve/tools/no_reply";
+
+export default noReply();
+```
+
+`no_reply` is a `defineTool` tool with [`endsTurn: true`](/docs/tools#end-the-turn-after-a-tool-call), so the turn ends only when no other tool runs in the same step. Only root sessions receive it. Slack clears the thread status when the turn completes. Remove the file to remove the tool.
+
### `sleep`
`sleep` pauses and durably resumes the current turn. The model calls it with `{ seconds }`; the wait does not hold an application runtime open. Concurrent calls run in parallel, and the turn resumes after the longest wait. A steering message, the default for a new message, ends the wait early: `sleep` returns `{ interrupted: true }`, which the model reads as `Stopped early because a new message arrived.`, followed by the message. Add it:
diff --git a/docs/reference/typescript-api.md b/docs/reference/typescript-api.md
index 56f5b08c4..98ffb077d 100644
--- a/docs/reference/typescript-api.md
+++ b/docs/reference/typescript-api.md
@@ -57,7 +57,7 @@ export default defineTool({
| `mockModel` | `eve/evals` | Deterministic fixture agent models | [Evals](../evals/overview) |
| `useEveAgent` | `eve/react`, `eve/vue`, `eve/svelte` | frontend | [Frontend](../guides/frontend/overview) |
-Tool-wide authoring helpers and types such as `defineTool`, `defineWorkflowTool`, `defineDurableCallback`, `defineDurableSchema`, `defineDynamic`, `disableTool`, and `ToolLabelDefinition` come from `eve/tools`. Capability-specific definitions and helpers use their own subpaths (see [Built-in tools](../concepts/built-in-tools)): reusable definitions such as `bash` and `glob` come from `eve/tools/<name>`, `webSearch` comes from `eve/tools/web_search`, `agentRouter` comes from `eve/tools/agent-router`, `sleep` comes from `eve/tools/sleep`, and approval policies and types come from `eve/tools/approval`. The route verbs `GET`/`HEAD`/`POST`/`PUT`/`PATCH`/`DELETE`/`OPTIONS`/`WS` plus `disableRoute` come from `eve/channels`, and the channel auth helpers `localDev`/`vercelOidc`/`placeholderAuth` come from `eve/channels/auth`.
+Tool-wide authoring helpers and types such as `defineTool`, `defineWorkflowTool`, `defineDurableCallback`, `defineDurableSchema`, `defineDynamic`, `disableTool`, and `ToolLabelDefinition` come from `eve/tools`. Capability-specific definitions and helpers use their own subpaths (see [Built-in tools](../concepts/built-in-tools)): reusable definitions such as `bash` and `glob` come from `eve/tools/<name>`, `webSearch` comes from `eve/tools/web_search`, `agentRouter` comes from `eve/tools/agent-router`, `sleep` comes from `eve/tools/sleep`, `noReply` comes from `eve/tools/no_reply`, and approval policies and types come from `eve/tools/approval`. The route verbs `GET`/`HEAD`/`POST`/`PUT`/`PATCH`/`DELETE`/`OPTIONS`/`WS` plus `disableRoute` come from `eve/channels`, and the channel auth helpers `localDev`/`vercelOidc`/`placeholderAuth` come from `eve/channels/auth`.
`AgentReasoningDefinition` is exported from `eve` for the top-level `defineAgent({ reasoning })` setting. `AgentLimitsDefinition` is exported for `defineAgent({ limits })`. `AgentWorkflowDefinition`, `AgentWorkflowRetentionDefinition`, and `AgentWorkflowWorldDefinition` are exported from `eve` for the `defineAgent({ experimental: { workflow } })` config shape. `WebSearchToolInput` and `WebSearchProvider` are exported from `eve/tools/web_search`.
@@ -108,7 +108,7 @@ import template from "../../prompts/template.txt?raw";
| `ctx.getToken(provider)` | Resolve a bearer token for an inline auth provider such as `connect("...")` |
| `ctx.requireAuth(provider)` | Evict and re-authorize an inline provider, commonly after a downstream `401` |
-Tool definitions accept `availableInSubagents: false` to restrict the tool to top-level root sessions. Authored workflow bodies also receive `ctx.agents`, a replay-stable map of callable-agent metadata, and `ctx.agent(name)`, which returns an `AgentSession` whose `send(message, options?)` resolves to a response with `result()`. A `"use step"` helper that receives the context directly should type it as `WorkflowStepToolContext`, which excludes `agents`, `agent`, and `ask`. The root-copy `agent` entry has an empty description when the root omits `description`. See [Workflows as tools](../tools/workflows#delegate-work-ctxagent) for the workflow-only context.
+Tool definitions accept `availableInSubagents: false` to restrict the tool to top-level root sessions. `defineTool` definitions accept `endsTurn: true`, or a function that receives the `execute` output, to end the turn without a reply after a successful call; see [Tools](../tools#end-the-turn-after-a-tool-call). Authored workflow bodies also receive `ctx.agents`, a replay-stable map of callable-agent metadata, and `ctx.agent(name)`, which returns an `AgentSession` whose `send(message, options?)` resolves to a response with `result()`. A `"use step"` helper that receives the context directly should type it as `WorkflowStepToolContext`, which excludes `agents`, `agent`, and `ask`. The root-copy `agent` entry has an empty description when the root omits `description`. See [Workflows as tools](../tools/workflows#delegate-work-ctxagent) for the workflow-only context.
## Imports at a glance
@@ -122,6 +122,7 @@ Tool definitions accept `availableInSubagents: false` to restrict the tool to to
| `eve/tools/web_search` | Provider-managed `webSearch` configuration |
| `eve/tools/workflow` | Runtime-generated `workflow` tool factory |
| `eve/tools/sleep` | Opt-in durable `sleep` tool |
+| `eve/tools/no_reply` | Opt-in `noReply` tool factory |
| `eve/connections` | `defineMcpClientConnection`, `defineOpenAPIConnection`, `defineDynamic` |
| `eve/channels` | `defineChannel`, `disableRoute`, route verbs |
| `eve/channels/eve` | `eveChannel` |
diff --git a/docs/schedules.mdx b/docs/schedules.mdx
index c802c60ca..873bd7e4b 100644
--- a/docs/schedules.mdx
+++ b/docs/schedules.mdx
@@ -77,7 +77,7 @@ export default defineSchedule({
});
```
-Every run delivers the agent's reply to the channel. To skip a run when there is nothing to report, check that condition in the handler before calling `send`.
+Every run delivers the agent's reply to the channel. To skip a run when there is nothing to report, check that condition in the handler before calling `send`. When only the agent can tell, add the opt-in [`no_reply`](/docs/concepts/built-in-tools#no_reply) tool and ask the agent to call it when there is nothing to report; the run then posts nothing.
- `to(channel, target).send(message, { auth })`: starts a session on another channel. It has the same contract as a route handler's `ctx.to(...)` handle.
- `waitUntil(promise)`: extends the cron task's lifetime so the parked session and any in-flight fetches settle before the task ends. Wrap the `send` call in it.
diff --git a/docs/tools/overview.mdx b/docs/tools/overview.mdx
index 3493eb1c0..68ed54d54 100644
--- a/docs/tools/overview.mdx
+++ b/docs/tools/overview.mdx
@@ -60,6 +60,52 @@ The option defaults to `true` and works with `defineTool` and `defineWorkflowToo
Compiled tools preserve Zod schema composition, including input and output schemas imported from helper modules. Durable replay metadata stays separate from the original schema, so adding it does not mutate shared schema objects.
+### End the turn after a tool call
+
+Set `endsTurn: true` when a successful call is the whole answer, such as reacting to a message. eve ends the turn after the call instead of calling the model again, so the turn completes without a final message and channels post no reply:
+
+```ts title="agent/tools/react.ts"
+export default defineTool({
+ description: "React to the current message. Use this when a reaction is the whole answer.",
+ endsTurn: true,
+ inputSchema: z.object({ emoji: z.string() }),
+ async execute({ emoji }) {
+ await addReaction(emoji);
+ return { emoji };
+ },
+});
+```
+
+With `endsTurn: true`, eve tells the model that the call ends its turn by appending this sentence, after a blank line, to the description the model sees:
+
+```text
+Calling this tool ends your turn once it succeeds: do not write a reply or call other tools in the same step. If it fails, you will see the error and can continue.
+```
+
+Write `description` for what the tool does and when to use it, and leave the turn-ending rule to eve. The appended sentence is not part of the tool definition, so `eve info` shows the description as you wrote it.
+
+To decide from the result instead, pass a function. eve calls it with the output of `execute` after each successful call, and the call ends the turn only when the function returns `true` or resolves to `true`. If the function throws or rejects, eve logs a warning and the turn continues as though it returned `false`:
+
+```ts title="agent/tools/react.ts"
+export default defineTool({
+ description:
+ "React to the current message. When the reaction posts, your turn ends; otherwise, reply in text.",
+ inputSchema: z.object({ emoji: z.string() }),
+ async execute({ emoji }) {
+ return { posted: await addReaction(emoji) };
+ },
+ endsTurn: (output) => output.posted,
+});
+```
+
+Declare `endsTurn` after `execute`, as above, so TypeScript infers `output` from what `execute` returns. With an `outputSchema`, `output` takes that schema's type wherever `endsTurn` appears.
+
+eve does not append the sentence for a function, because whether the call ends the turn is known only after it runs. Describe the behavior in `description` when the model needs to know it.
+
+The turn ends only when every tool call in the model's step can end the turn and succeeds, and every `endsTurn` function returns `true`. Otherwise the model receives the results and continues as usual. Text the model writes before the call is narration, so channels do not post it as the reply. While [tasks](/docs/tools/tasks) are still working, the turn waits for them and then calls the model again.
+
+eve ignores `endsTurn` in delegated sessions, which must return a reply to their caller, and on turns that request structured output; the model does not see the appended sentence there, and eve does not call an `endsTurn` function. `defineWorkflowTool` rejects `endsTurn` at build time. Dynamic tool entries accept `endsTurn: true` or `false`; eve rejects a function when the resolver returns the entry, because dynamic tool metadata is stored durably. To end a turn without taking any other action, add the opt-in [`no_reply`](/docs/concepts/built-in-tools#no_reply) tool.
+
### Label tool activity
Use `label.start(input)` to describe a call in user-facing activity. The callback receives the validated tool input, so it can select the useful fields without exposing the full argument object:
diff --git a/e2e/fixtures/agent-tools/agent/agent.ts b/e2e/fixtures/agent-tools/agent/agent.ts
index 71e9541ae..ec92ec7da 100644
--- a/e2e/fixtures/agent-tools/agent/agent.ts
+++ b/e2e/fixtures/agent-tools/agent/agent.ts
@@ -17,6 +17,24 @@ const base = e2eAgentConfig({
}
return "Context messages checked.";
}
+ if (request.lastUserMessage?.includes("`no_reply`")) {
+ const roles = request.messages.map((message) => message.role);
+ if (roles.lastIndexOf("tool") <= roles.lastIndexOf("user")) {
+ return {
+ toolCalls: [{ name: "no_reply", input: { reason: "The note needs no answer." } }],
+ };
+ }
+ // Reached only if `no_reply` failed to end the turn; the eval then sees a reply.
+ return "Replied after no_reply.";
+ }
+ if (request.lastUserMessage?.includes("`react_to_note`")) {
+ const roles = request.messages.map((message) => message.role);
+ if (roles.lastIndexOf("tool") <= roles.lastIndexOf("user")) {
+ const emoji = request.lastUserMessage.includes("rocket") ? "rocket" : "tada";
+ return { toolCalls: [{ name: "react_to_note", input: { emoji } }] };
+ }
+ return "The rocket reaction isn't allowed in the team channel, so nothing was posted.";
+ }
if (request.lastUserMessage?.includes("`schema_validate`")) {
const roles = request.messages.map((message) => message.role);
if (roles.lastIndexOf("tool") <= roles.lastIndexOf("user")) {
diff --git a/e2e/fixtures/agent-tools/agent/tools/no_reply.ts b/e2e/fixtures/agent-tools/agent/tools/no_reply.ts
new file mode 100644
index 000000000..4e18ed0ae
--- /dev/null
+++ b/e2e/fixtures/agent-tools/agent/tools/no_reply.ts
@@ -0,0 +1,3 @@
+import { noReply } from "eve/tools/no_reply";
+
+export default noReply();
diff --git a/e2e/fixtures/agent-tools/agent/tools/react_to_note.ts b/e2e/fixtures/agent-tools/agent/tools/react_to_note.ts
new file mode 100644
index 000000000..867f5df45
--- /dev/null
+++ b/e2e/fixtures/agent-tools/agent/tools/react_to_note.ts
@@ -0,0 +1,17 @@
+import { defineTool } from "eve/tools";
+import { z } from "zod";
+
+// Covers `endsTurn` as a function of the execute output
+// (`evals/static-tools/ends-turn-function.eval.ts`): a posted reaction ends the
+// turn, and a reaction the team channel doesn't allow leaves the model to reply.
+export default defineTool({
+ description:
+ "Smoke-test fixture: reacts to a team note with an emoji. Only call when the user explicitly asks to use `react_to_note`. When the reaction posts, your turn ends; when it doesn't, tell the user.",
+ inputSchema: z.object({
+ emoji: z.string().min(1).describe("The emoji name, such as tada."),
+ }),
+ async execute({ emoji }) {
+ return { emoji, posted: emoji === "tada" };
+ },
+ endsTurn: (output) => output.posted,
+});
diff --git a/e2e/fixtures/agent-tools/evals/static-tools/ends-turn-function.eval.ts b/e2e/fixtures/agent-tools/evals/static-tools/ends-turn-function.eval.ts
new file mode 100644
index 000000000..97095cc66
--- /dev/null
+++ b/e2e/fixtures/agent-tools/evals/static-tools/ends-turn-function.eval.ts
@@ -0,0 +1,33 @@
+import { defineEval } from "eve/evals";
+import { satisfies } from "eve/evals/expect";
+
+// `endsTurn` as a function of the execute output: a posted reaction ends the
+// turn without a reply, and a reaction that doesn't post lets the model reply.
+export default defineEval({
+ description: "An endsTurn function decides from the tool's output whether the turn ends.",
+ async test(t) {
+ const posted = await t.send(
+ "Alice shared that the release shipped this morning. Celebrate it with the `react_to_note` tool using the tada emoji.",
+ );
+ posted.expectOk();
+ posted.requireToolCall("react_to_note");
+ t.check(
+ posted.message,
+ satisfies((message) => message === undefined, "a posted reaction sends no reply"),
+ );
+
+ const refused = await posted.session.send(
+ "Bob would also like to add a rocket reaction to Alice's note with the `react_to_note` tool. Let him know how it went.",
+ );
+ refused.expectOk();
+ refused.requireToolCall("react_to_note");
+ t.check(
+ refused.message,
+ satisfies(
+ (message) => typeof message === "string" && message.trim().length > 0,
+ "a reaction that doesn't post gets a reply",
+ ),
+ );
+ t.succeeded();
+ },
+});
diff --git a/e2e/fixtures/agent-tools/evals/static-tools/no-reply.eval.ts b/e2e/fixtures/agent-tools/evals/static-tools/no-reply.eval.ts
new file mode 100644
index 000000000..99dd78b5a
--- /dev/null
+++ b/e2e/fixtures/agent-tools/evals/static-tools/no-reply.eval.ts
@@ -0,0 +1,32 @@
+import { defineEval } from "eve/evals";
+import { satisfies } from "eve/evals/expect";
+
+// A turn that ends with the opt-in `no_reply` tool completes without a final
+// message, and the session keeps answering later turns normally.
+export default defineEval({
+ description: "The no_reply tool ends a turn without a reply.",
+ async test(t) {
+ const quiet = await t.send(
+ "Alice is logging a routine note for the team: the nightly backup finished on schedule. The note needs no answer, so end your turn with the `no_reply` tool instead of writing a message.",
+ );
+ quiet.expectOk();
+ quiet.requireToolCall("no_reply");
+ t.check(
+ quiet.message,
+ satisfies((message) => message === undefined, "the turn sends no reply"),
+ );
+
+ const followUp = await quiet.session.send(
+ "Bob is catching up on the thread. What did Alice's note say about the nightly backup?",
+ );
+ followUp.expectOk();
+ t.check(
+ followUp.message,
+ satisfies(
+ (message) => typeof message === "string" && /backup/iu.test(message),
+ "the next turn replies normally",
+ ),
+ );
+ t.succeeded();
+ },
+});
diff --git a/packages/eve/extension-contracts/compatibility/dynamicTool/v65.ts b/packages/eve/extension-contracts/compatibility/dynamicTool/v65.ts
new file mode 100644
index 000000000..9446b1479
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/dynamicTool/v65.ts
@@ -0,0 +1,14 @@
+import { defineDynamic, defineTool } from "#public/tools/index.js";
+
+// Epoch 65 dynamic tool entries had no `endsTurn`; epoch 66 adds it as optional.
+export default defineDynamic({
+ events: {
+ "turn.started": () => ({
+ acknowledge: defineTool({
+ description: "Acknowledge the message.",
+ inputSchema: { type: "object", properties: {} },
+ execute: () => "acknowledged",
+ }),
+ }),
+ },
+});
diff --git a/packages/eve/extension-contracts/compatibility/dynamicTool/v66.ts b/packages/eve/extension-contracts/compatibility/dynamicTool/v66.ts
new file mode 100644
index 000000000..6c5714359
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/dynamicTool/v66.ts
@@ -0,0 +1,16 @@
+import { defineDynamic, defineTool } from "#public/tools/index.js";
+
+// Epoch 66 dynamic tool entries accepted only a boolean `endsTurn`; epoch 67
+// widens the type to match `defineTool`. A boolean still works as before.
+export default defineDynamic({
+ events: {
+ "turn.started": () => ({
+ acknowledge: defineTool({
+ description: "Acknowledge the message.",
+ endsTurn: true,
+ inputSchema: { type: "object", properties: {} },
+ execute: () => "acknowledged",
+ }),
+ }),
+ },
+});
diff --git a/packages/eve/extension-contracts/compatibility/tool/v68.ts b/packages/eve/extension-contracts/compatibility/tool/v68.ts
new file mode 100644
index 000000000..9c3b3dc13
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/tool/v68.ts
@@ -0,0 +1,11 @@
+import { z } from "zod";
+import { defineTool } from "#public/tools/index.js";
+
+// Epoch 68 tool definitions had no `endsTurn`; epoch 69 adds it as optional to
+// every defineTool overload. A tool that omits it continues the turn as before.
+export default defineTool({
+ description: "Add a reaction to the current message.",
+ inputSchema: z.object({ emoji: z.string() }),
+ outputSchema: z.object({ emoji: z.string() }),
+ execute: ({ emoji }) => ({ emoji }),
+});
diff --git a/packages/eve/extension-contracts/compatibility/tool/v69.ts b/packages/eve/extension-contracts/compatibility/tool/v69.ts
new file mode 100644
index 000000000..ad711ef6b
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/tool/v69.ts
@@ -0,0 +1,12 @@
+import { z } from "zod";
+import { defineTool } from "#public/tools/index.js";
+
+// Epoch 69 `endsTurn` accepted only a boolean; epoch 70 also accepts a function
+// of the execute output. A boolean still ends the turn as before.
+export default defineTool({
+ description: "Add a reaction to the current message.",
+ endsTurn: true,
+ inputSchema: z.object({ emoji: z.string() }),
+ outputSchema: z.object({ emoji: z.string() }),
+ execute: ({ emoji }) => ({ emoji }),
+});
diff --git a/packages/eve/extension-contracts/reports/dynamicTool/v66.json b/packages/eve/extension-contracts/reports/dynamicTool/v66.json
new file mode 100644
index 000000000..a558429fd
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/dynamicTool/v66.json
@@ -0,0 +1,16 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "dynamicTool",
+ "epoch": 66,
+ "sha256": "dfaabeb372d324a8be804d6e2abc3a08df0df630f50ff32b3c9abfaa27acac8a",
+ "exports": [
+ "DynamicToolEntry",
+ "DynamicToolEvents",
+ "DynamicToolResult",
+ "DynamicToolSet",
+ "auto",
+ "defineDurableCallback",
+ "defineDurableSchema",
+ "defineDynamic"
+ ]
+}
diff --git a/packages/eve/extension-contracts/reports/dynamicTool/v67.json b/packages/eve/extension-contracts/reports/dynamicTool/v67.json
new file mode 100644
index 000000000..707d8af2f
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/dynamicTool/v67.json
@@ -0,0 +1,16 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "dynamicTool",
+ "epoch": 67,
+ "sha256": "133437a64e81abf707eb2473e4bc25f3b52af19b3dba38cb4bc863ec68c8a379",
+ "exports": [
+ "DynamicToolEntry",
+ "DynamicToolEvents",
+ "DynamicToolResult",
+ "DynamicToolSet",
+ "auto",
+ "defineDurableCallback",
+ "defineDurableSchema",
+ "defineDynamic"
+ ]
+}
diff --git a/packages/eve/extension-contracts/reports/tool/v69.json b/packages/eve/extension-contracts/reports/tool/v69.json
new file mode 100644
index 000000000..0183f379c
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/tool/v69.json
@@ -0,0 +1,29 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "tool",
+ "epoch": 69,
+ "sha256": "aafc5be535f409974b1770c62c2d60dc79139374280f192686cfb9f390de42fa",
+ "exports": [
+ "AgentRouterInput",
+ "AgentRouterTool",
+ "WorkflowStepToolContext",
+ "WorkflowTool",
+ "WorkflowToolDefinition",
+ "WorkflowToolInput",
+ "WorkflowToolOptions",
+ "agentRouter",
+ "defaultWebSearch",
+ "defineTool",
+ "defineWorkflowTool",
+ "disableTool",
+ "evaluate",
+ "isDisabledToolSentinel",
+ "isWebSearchToolDefinition",
+ "serializeModelInputSchema",
+ "toolOutput",
+ "toolOutputPart",
+ "toolResultFrom",
+ "webSearch",
+ "workflow"
+ ]
+}
diff --git a/packages/eve/extension-contracts/reports/tool/v70.json b/packages/eve/extension-contracts/reports/tool/v70.json
new file mode 100644
index 000000000..768e91c2b
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/tool/v70.json
@@ -0,0 +1,29 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "tool",
+ "epoch": 70,
+ "sha256": "684ad1ed85cae9dac2e48818f9a2e8fe705a0286b2683fb12d9ea6af670ef558",
+ "exports": [
+ "AgentRouterInput",
+ "AgentRouterTool",
+ "WorkflowStepToolContext",
+ "WorkflowTool",
+ "WorkflowToolDefinition",
+ "WorkflowToolInput",
+ "WorkflowToolOptions",
+ "agentRouter",
+ "defaultWebSearch",
+ "defineTool",
+ "defineWorkflowTool",
+ "disableTool",
+ "evaluate",
+ "isDisabledToolSentinel",
+ "isWebSearchToolDefinition",
+ "serializeModelInputSchema",
+ "toolOutput",
+ "toolOutputPart",
+ "toolResultFrom",
+ "webSearch",
+ "workflow"
+ ]
+}
diff --git a/packages/eve/package.json b/packages/eve/package.json
index 1bdbcd8e1..f51ed6631 100644
--- a/packages/eve/package.json
+++ b/packages/eve/package.json
@@ -137,6 +137,11 @@
"import": "./dist/src/public/tools/sleep.js",
"default": "./dist/src/public/tools/sleep.js"
},
+ "./tools/no_reply": {
+ "types": "./dist/src/public/tools/no-reply.d.ts",
+ "import": "./dist/src/public/tools/no-reply.js",
+ "default": "./dist/src/public/tools/no-reply.js"
+ },
"./tools": {
"types": "./dist/src/public/tools/index.d.ts",
"import": "./dist/src/public/tools/index.js",
diff --git a/packages/eve/src/compiler/extension-compatibility.ts b/packages/eve/src/compiler/extension-compatibility.ts
index 4b2a12cdd..f358cb557 100644
--- a/packages/eve/src/compiler/extension-compatibility.ts
+++ b/packages/eve/src/compiler/extension-compatibility.ts
@@ -22,10 +22,10 @@ interface ExtensionCapabilityContract {
const EXTENSION_CAPABILITY_CONTRACTS = {
extension: { current: 1, supported: [1], dropped: {} },
tool: {
- current: 68,
+ current: 70,
supported: [
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 29, 30, 31, 32, 34, 35, 54, 55, 63, 64, 65, 66, 67,
- 68,
+ 68, 69, 70,
],
dropped: {
14: "TaskExec.delegated was removed; migrate to workflow-backed background tools",
@@ -72,10 +72,10 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
},
},
dynamicTool: {
- current: 65,
+ current: 67,
supported: [
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 22, 31, 32, 33, 52, 54,
- 60, 61, 62, 63, 64, 65,
+ 60, 61, 62, 63, 64, 65, 66, 67,
],
dropped: {
21: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",
diff --git a/packages/eve/src/context/build-dynamic-tools.ts b/packages/eve/src/context/build-dynamic-tools.ts
index 25d981fe3..c83912e1e 100644
--- a/packages/eve/src/context/build-dynamic-tools.ts
+++ b/packages/eve/src/context/build-dynamic-tools.ts
@@ -142,6 +142,7 @@ export function replayDynamicTools(
} = {
availableInSubagents: entry.availableInSubagents,
description: entry.description,
+ endsTurn: entry.endsTurn,
execute: createToolExecuteWithAuth({
scope: entry.name,
execute: (input, context) => {
diff --git a/packages/eve/src/context/dynamic-tool-lifecycle.test.ts b/packages/eve/src/context/dynamic-tool-lifecycle.test.ts
index 4d78a0c85..c9b28f985 100644
--- a/packages/eve/src/context/dynamic-tool-lifecycle.test.ts
+++ b/packages/eve/src/context/dynamic-tool-lifecycle.test.ts
@@ -1431,6 +1431,42 @@ describe("dispatchDynamicToolEvent", () => {
);
});
+ it("keeps endsTurn: true on a replayed dynamic tool", async () => {
+ const ctx = createCtx();
+ const resolver = createResolver("react", ["session.started"], () =>
+ Object.assign(createReplayableTool(), { endsTurn: true }),
+ );
+
+ await dispatchDynamicToolEvent({
+ ctx,
+ resolvers: [resolver],
+ messages: [],
+ event: makeEvent("session.started"),
+ });
+
+ expect(buildDynamicTools(ctx)[0]?.endsTurn).toBe(true);
+ });
+
+ it("rejects an endsTurn function, which durable dynamic metadata cannot hold", async () => {
+ const logs = captureLogRecords();
+ const ctx = createCtx();
+ const resolver = createResolver("react", ["session.started"], () =>
+ Object.assign(createReplayableTool(), { endsTurn: () => true }),
+ );
+
+ await dispatchDynamicToolEvent({
+ ctx,
+ resolvers: [resolver],
+ messages: [],
+ event: makeEvent("session.started"),
+ });
+
+ expect(buildDynamicTools(ctx)).toHaveLength(0);
+ expect(JSON.stringify(logs.records)).toContain(
+ 'Dynamic tool \\"react\\" sets endsTurn to a function, which dynamic tools do not support.',
+ );
+ });
+
it("uses file slug when handler returns a single entry", async () => {
const ctx = createCtx();
const resolver = createResolver("analytics", ["session.started"], () => createReplayableTool());
diff --git a/packages/eve/src/context/dynamic-tool-lifecycle.ts b/packages/eve/src/context/dynamic-tool-lifecycle.ts
index 8002b42c2..e645e8d3f 100644
--- a/packages/eve/src/context/dynamic-tool-lifecycle.ts
+++ b/packages/eve/src/context/dynamic-tool-lifecycle.ts
@@ -323,6 +323,7 @@ function createMetadata(input: {
name: input.name,
}),
description: input.entry.description,
+ endsTurn: readDynamicEndsTurn(input.name, input.entry.endsTurn) || undefined,
entryKey: input.entryKey,
inputSchema: serializeInputSchema(input.entry.inputSchema),
name: input.name,
@@ -331,6 +332,16 @@ function createMetadata(input: {
};
}
+/** Dynamic tool metadata is durable, so it can hold only a literal `endsTurn`. */
+function readDynamicEndsTurn(name: string, endsTurn: DynamicToolEntry["endsTurn"]): boolean {
+ if (typeof endsTurn === "function") {
+ throw new Error(
+ `Dynamic tool "${name}" sets endsTurn to a function, which dynamic tools do not support. Set endsTurn to true or false; the resolver runs for each event, so it can decide then.`,
+ );
+ }
+ return endsTurn === true;
+}
+
interface ResolvedDynamicToolEvent {
readonly metadata: readonly CurrentDynamicToolMetadata[];
}
diff --git a/packages/eve/src/context/dynamic-tool-metadata.ts b/packages/eve/src/context/dynamic-tool-metadata.ts
index 9fdbfc001..8087c8be5 100644
--- a/packages/eve/src/context/dynamic-tool-metadata.ts
+++ b/packages/eve/src/context/dynamic-tool-metadata.ts
@@ -5,6 +5,7 @@ interface DynamicToolMetadataBase {
readonly availableInSubagents?: boolean;
readonly name: string;
readonly description: string;
+ readonly endsTurn?: boolean;
readonly inputSchema: JsonObject;
readonly outputSchema?: JsonObject;
readonly resolverSlug: string;
diff --git a/packages/eve/src/execution/node-step.ts b/packages/eve/src/execution/node-step.ts
index 666a0fe0a..8637530e7 100644
--- a/packages/eve/src/execution/node-step.ts
+++ b/packages/eve/src/execution/node-step.ts
@@ -262,6 +262,7 @@ function createRegisteredHarnessToolDefinition(input: {
approvalKey: def.approvalKey,
behavior: input.behavior,
description: def.description,
+ endsTurn: def.endsTurn,
executeInput: def.executeInput,
execute: resolveAuthoredExecute({
rawExecute,
diff --git a/packages/eve/src/harness/action-result-helpers.ts b/packages/eve/src/harness/action-result-helpers.ts
index e96a0c5ff..4f8d5fc16 100644
--- a/packages/eve/src/harness/action-result-helpers.ts
+++ b/packages/eve/src/harness/action-result-helpers.ts
@@ -169,7 +169,7 @@ function toolResultOutputToJsonValue(input: {
);
}
-function isToolResultError(output: ToolResultPart["output"]): boolean {
+export function isToolResultError(output: ToolResultPart["output"]): boolean {
return (
output.type === "error-json" ||
output.type === "error-text" ||
diff --git a/packages/eve/src/harness/execute-tool.ts b/packages/eve/src/harness/execute-tool.ts
index cc0f5a9c9..7ba33bebd 100644
--- a/packages/eve/src/harness/execute-tool.ts
+++ b/packages/eve/src/harness/execute-tool.ts
@@ -1,7 +1,11 @@
import type { FlexibleSchema } from "ai";
import type { Approval } from "#approval/definition.js";
-import type { InternalToolLabelDefinition, ToolExecuteOptions } from "#tools/definition.js";
+import type {
+ InternalToolDefinition,
+ InternalToolLabelDefinition,
+ ToolExecuteOptions,
+} from "#tools/definition.js";
import type { JsonValue } from "#shared/json.js";
import type { PreparedToolBehavior } from "#tools/behavior.js";
@@ -14,6 +18,8 @@ export interface HarnessToolDefinition {
readonly approvalKey?: (toolInput: Readonly<Record<string, unknown>>) => string;
readonly behavior?: PreparedToolBehavior;
readonly description: string;
+ /** A successful call ends the turn without a final reply; see `ToolDefinition.endsTurn`. */
+ readonly endsTurn?: InternalToolDefinition["endsTurn"];
readonly execute?: (input: any, options: ToolExecuteOptions) => any;
/** Optional JSON input substituted when this tool starts its workflow body. */
readonly executeInput?: (input: unknown) => JsonValue;
diff --git a/packages/eve/src/harness/tool-loop.test.ts b/packages/eve/src/harness/tool-loop.test.ts
index 86a31ec5a..d24656a72 100644
--- a/packages/eve/src/harness/tool-loop.test.ts
+++ b/packages/eve/src/harness/tool-loop.test.ts
@@ -2438,6 +2438,197 @@ describe("createToolLoopHarness", () => {
expect(result.session.outputSchema).toBeUndefined();
});
+ describe("endsTurn tools", () => {
+ const reacted = { type: "text", value: "reacted" } as const;
+ const tools = new Map([
+ ...createTestConfig().tools,
+ [
+ "react",
+ {
+ description: "Reacts to the message.",
+ endsTurn: true,
+ execute: vi.fn().mockResolvedValue("reacted"),
+ inputSchema: jsonSchema({ type: "object" }),
+ name: "react",
+ },
+ ],
+ ]);
+
+ function stepCalling(
+ calls: readonly {
+ readonly executeOutput?: unknown;
+ readonly name: string;
+ readonly output: { readonly type: "error-text" | "text"; readonly value: string };
+ }[],
+ ): Record<string, unknown> {
+ const toolCalls = calls.map((call, index) => ({
+ input: {},
+ toolCallId: `call-${index}`,
+ toolName: call.name,
+ }));
+ return {
+ finishReason: "tool-calls",
+ response: {
+ messages: [
+ {
+ content: [
+ { text: "Reacting now.", type: "text" },
+ ...toolCalls.map((toolCall) => ({ ...toolCall, type: "tool-call" })),
+ ],
+ role: "assistant",
+ },
+ {
+ content: calls.map((call, index) => ({
+ output: call.output,
+ toolCallId: `call-${index}`,
+ toolName: call.name,
+ type: "tool-result",
+ })),
+ role: "tool",
+ },
+ ],
+ },
+ text: "Reacting now.",
+ toolCalls,
+ toolResults: calls.flatMap((call, index) =>
+ call.output.type === "error-text"
+ ? []
+ : [
+ {
+ input: {},
+ output: call.executeOutput ?? call.output.value,
+ toolCallId: `call-${index}`,
+ toolName: call.name,
+ },
+ ],
+ ),
+ };
+ }
+
+ function toolsWithReactEndsTurn(endsTurn: (output: unknown) => boolean | Promise<boolean>) {
+ return new Map([...tools, ["react", { ...tools.get("react")!, endsTurn }]]);
+ }
+
+ it("ends the turn without a reply when every call in the step ends the turn", async () => {
+ setupMockAgent(stepCalling([{ name: "react", output: reacted }]));
+ const { emit, events } = createEventCollector();
+ const runStep = createToolLoopHarness(createTestConfig(emit, { tools }));
+
+ const result = await runStep(createTestSession(), { message: "Thanks, that fixed it!" });
+
+ expect(result.next).toBeNull();
+ expect(result.settledTurn).toEqual({ output: "" });
+ // The narration before the call stays interim, so no channel posts it.
+ expect(
+ events.flatMap((event) =>
+ event.type === "message.completed" ? [event.data.finishReason] : [],
+ ),
+ ).toEqual(["tool-calls"]);
+ expect(getCompatibilityEventTypes(events).slice(-2)).toEqual([
+ "turn.completed",
+ "session.waiting",
+ ]);
+ expect(result.session.history.at(-1)).toMatchObject({ role: "tool" });
+ });
+
+ it.each([
+ {
+ calls: [{ name: "react", output: { type: "error-text", value: "Reaction rejected." } }],
+ case: "the call fails",
+ },
+ {
+ calls: [
+ { name: "react", output: reacted },
+ { name: "add", output: { type: "text", value: "42" } },
+ ],
+ case: "another tool shares the step",
+ },
+ {
+ calls: [{ name: "react", output: reacted }],
+ case: "the session is delegated",
+ delegated: true,
+ },
+ {
+ calls: [{ name: "react", output: reacted }],
+ case: "the turn requests structured output",
+ outputSchema: { properties: {}, type: "object" },
+ },
+ ] as const)("continues the turn when $case", async ({ calls, ...options }) => {
+ setupMockAgent(stepCalling(calls));
+ const runStep = createToolLoopHarness(createTestConfig(undefined, { tools }));
+ const ctx = new ContextContainer();
+ if ("delegated" in options) setDelegatedParent(ctx);
+ const outputSchema = "outputSchema" in options ? options.outputSchema : undefined;
+
+ const result = await contextStorage.run(ctx, () =>
+ runStep(createTestSession({ outputSchema }), { message: "Thanks, that fixed it!" }),
+ );
+
+ expect(result.next).toBe(runStep);
+ expect(result.settledTurn).toBeUndefined();
+ });
+
+ it.each([
+ {
+ case: "a root session",
+ description:
+ "Reacts to the message.\n\nCalling this tool ends your turn once it succeeds: do not write a reply or call other tools in the same step. If it fails, you will see the error and can continue.",
+ },
+ { case: "a delegated session", delegated: true, description: "Reacts to the message." },
+ {
+ case: "a structured-output turn",
+ description: "Reacts to the message.",
+ outputSchema: { properties: {}, type: "object" },
+ },
+ { case: "an endsTurn function", description: "Reacts to the message.", endsTurnFn: true },
+ ] as const)("appends the turn-ending note only for endsTurn: true: $case", async (row) => {
+ setupMockAgent({
+ finishReason: "stop",
+ response: { messages: [{ content: "Glad it helped!", role: "assistant" }] },
+ text: "Glad it helped!",
+ toolCalls: [],
+ toolResults: [],
+ });
+ const runStep = createToolLoopHarness(
+ createTestConfig(undefined, {
+ tools: "endsTurnFn" in row ? toolsWithReactEndsTurn(() => true) : tools,
+ }),
+ );
+ const ctx = new ContextContainer();
+ if ("delegated" in row) setDelegatedParent(ctx);
+ const outputSchema = "outputSchema" in row ? row.outputSchema : undefined;
+
+ await contextStorage.run(ctx, () =>
+ runStep(createTestSession({ outputSchema }), { message: "Thanks, that fixed it!" }),
+ );
+
+ const agentTools = vi.mocked(ToolLoopAgent).mock.calls[0]?.[0]?.tools;
+ expect(agentTools?.react?.description).toBe(row.description);
+ expect(agentTools?.add?.description).toBe("Adds numbers");
+ });
+
+ it.each([true, false, "throws"] as const)(
+ "passes the execute output to an endsTurn function, which %s",
+ async (decision) => {
+ const endsTurn = vi.fn(async () => {
+ if (decision === "throws") throw new Error("lookup failed");
+ return decision;
+ });
+ setupMockAgent(
+ stepCalling([{ executeOutput: { emoji: "tada" }, name: "react", output: reacted }]),
+ );
+ const runStep = createToolLoopHarness(
+ createTestConfig(undefined, { tools: toolsWithReactEndsTurn(endsTurn) }),
+ );
+
+ const result = await runStep(createTestSession(), { message: "Thanks, that fixed it!" });
+
+ expect(endsTurn).toHaveBeenCalledExactlyOnceWith({ emoji: "tada" });
+ expect(result.next).toBe(decision === true ? null : runStep);
+ },
+ );
+ });
+
it("parks a conversation when requested structured output is not fulfilled", async () => {
setupMockAgent({
finishReason: "stop",
diff --git a/packages/eve/src/harness/tool-loop.ts b/packages/eve/src/harness/tool-loop.ts
index 12de740a7..0b64bfb52 100644
--- a/packages/eve/src/harness/tool-loop.ts
+++ b/packages/eve/src/harness/tool-loop.ts
@@ -113,7 +113,10 @@ import {
renderPendingApprovalsInstruction,
renderPendingApprovalsSnippet,
} from "#harness/hitl/approval-prompt.js";
-import { createToolResultMessagePartFromToolError } from "#harness/action-result-helpers.js";
+import {
+ createToolResultMessagePartFromToolError,
+ isToolResultError,
+} from "#harness/action-result-helpers.js";
import { activeTurnId } from "#harness/active-turn-id.js";
import {
clearTurnClientContextState,
@@ -1261,6 +1264,7 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
*/
// The tools advertised to the latest model call; they decide which tool calls defer.
let modelCallCoordinationTools = config.tools;
+ let modelCallEndsTurnTools: EndsTurnTools = new Map();
const createRequestMessages = () => {
// Persist framework announcements before the new input, or after earlier
// tool results on a continuation, so later requests retain the full prefix.
@@ -1448,6 +1452,23 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
});
session = advertisedModelTools.session;
const modelTools = advertisedModelTools.modelTools;
+ // `endsTurn` applies only in root, unstructured turns. Only a literal
+ // `true` is described to the model; a function decides from each result.
+ const endsTurnTools = new Map<string, NonNullable<HarnessToolDefinition["endsTurn"]>>();
+ if (!hasDelegatedCaller && session.outputSchema === undefined) {
+ for (const [name, modelTool] of Object.entries(modelTools)) {
+ const endsTurn = presentationTools.get(name)?.endsTurn;
+ if (modelTool.type === "provider" || endsTurn === undefined || endsTurn === false) {
+ continue;
+ }
+ endsTurnTools.set(name, endsTurn);
+ if (endsTurn === true) {
+ modelTool.description =
+ `${modelTool.description ?? ""}\n\n${ENDS_TURN_TOOL_NOTE}`.trimStart();
+ }
+ }
+ }
+ modelCallEndsTurnTools = endsTurnTools;
const effectiveTools = marker ? applyLastToolCacheBreakpoint(modelTools, marker) : modelTools;
for (const tool of Object.values(effectiveTools)) {
@@ -1992,6 +2013,7 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
runStep,
session,
coordinationTools: modelCallCoordinationTools,
+ endsTurnTools: modelCallEndsTurnTools,
});
} catch (error) {
throwIfTurnAborted(config.abortSignal);
@@ -2522,6 +2544,8 @@ async function handleStepResult(input: {
readonly result: HarnessStepResult;
readonly runStep: StepFn;
readonly coordinationTools: HarnessToolMap;
+ /** Tools that can end the turn in this step, with their `endsTurn` option. */
+ readonly endsTurnTools: EndsTurnTools;
readonly session: HarnessSession;
}): Promise<StepResult> {
const { config, emit, promptMessages, result, runStep } = input;
@@ -2817,9 +2841,10 @@ async function handleStepResult(input: {
};
}
+ const endsTurn = await stepEndsTurn(result, continuationMessages, input.endsTurnTools);
const continueLoop =
(!calledFinalOutput || finalOutputRejected) &&
- (responseTail.at(-1)?.role === "tool" ||
+ ((responseTail.at(-1)?.role === "tool" && !endsTurn) ||
normalizedProviderHistory.outcomeEndsResponse ||
hasRunnableDeferredStepInput(nextSession));
const holdsTurn = !continueLoop && workingTasks.length > 0;
@@ -2852,8 +2877,72 @@ async function handleStepResult(input: {
result,
schema: nextSession.outputSchema,
session: nextSession,
- stepOutput,
+ // Text written before an `endsTurn` call was narration, not the reply.
+ stepOutput: endsTurn ? null : stepOutput,
+ });
+}
+
+/** Appended to the model-facing description of every tool with `endsTurn: true`. */
+const ENDS_TURN_TOOL_NOTE =
+ "Calling this tool ends your turn once it succeeds: do not write a reply or call other tools in the same step. If it fails, you will see the error and can continue.";
+
+type EndsTurnTools = ReadonlyMap<string, NonNullable<HarnessToolDefinition["endsTurn"]>>;
+
+/**
+ * Whether the step ends the turn: every tool call targets a tool that can end
+ * the turn and succeeded, and each `endsTurn` function accepts its call's
+ * `execute` output. A failed or invalid call lets the model recover instead.
+ */
+async function stepEndsTurn(
+ result: HarnessStepResult,
+ responseMessages: readonly ModelMessage[],
+ endsTurnTools: EndsTurnTools,
+): Promise<boolean> {
+ const toolCalls = result.toolCalls ?? [];
+ if (toolCalls.length === 0) return false;
+ const outputs = new Map<string, ToolResultPart["output"]>();
+ for (const message of responseMessages) {
+ if (message.role !== "tool") continue;
+ for (const part of message.content) {
+ if (part.type === "tool-result") outputs.set(part.toolCallId, part.output);
+ }
+ }
+ const succeeded = toolCalls.every((toolCall) => {
+ const output = outputs.get(toolCall.toolCallId);
+ return (
+ endsTurnTools.has(toolCall.toolName) && output !== undefined && !isToolResultError(output)
+ );
});
+ if (!succeeded) return false;
+ const executeOutputs = new Map(
+ (result.toolResults ?? []).map((toolResult) => [toolResult.toolCallId, toolResult.output]),
+ );
+ for (const toolCall of toolCalls) {
+ const endsTurn = endsTurnTools.get(toolCall.toolName);
+ if (typeof endsTurn !== "function") continue;
+ if (!(await callEndsTurn(endsTurn, executeOutputs.get(toolCall.toolCallId), toolCall))) {
+ return false;
+ }
+ }
+ return true;
+}
+
+/** A throwing `endsTurn` function keeps the turn going rather than failing it. */
+async function callEndsTurn(
+ endsTurn: (output: unknown) => boolean | Promise<boolean>,
+ output: unknown,
+ toolCall: { readonly toolCallId: string; readonly toolName: string },
+): Promise<boolean> {
+ try {
+ return (await endsTurn(output)) === true;
+ } catch (error) {
+ log.warn("endsTurn threw; continuing the turn", {
+ callId: toolCall.toolCallId,
+ error,
+ toolName: toolCall.toolName,
+ });
+ return false;
+ }
}
function isDeferredHarnessTool(tool: HarnessToolDefinition | undefined): boolean {
diff --git a/packages/eve/src/internal/authored-definition/schema-backed.test.ts b/packages/eve/src/internal/authored-definition/schema-backed.test.ts
index 6d7ed0396..031261865 100644
--- a/packages/eve/src/internal/authored-definition/schema-backed.test.ts
+++ b/packages/eve/src/internal/authored-definition/schema-backed.test.ts
@@ -31,10 +31,11 @@ describe("normalizeToolDefinition", () => {
expect(typeof entry.definition.execute).toBe("function");
});
- it("preserves subagent visibility", () => {
+ it("preserves subagent visibility and turn ending", () => {
const tool = defineTool({
availableInSubagents: false,
description: "Runs only in a root session.",
+ endsTurn: true,
inputSchema: z.object({}),
execute: () => null,
});
@@ -44,6 +45,24 @@ describe("normalizeToolDefinition", () => {
expect(entry.kind).toBe("tool");
if (entry.kind !== "tool") throw new Error("expected tool kind");
expect(entry.definition.availableInSubagents).toBe(false);
+ expect(entry.definition.endsTurn).toBe(true);
+ });
+
+ it("accepts an endsTurn function and rejects other endsTurn values", () => {
+ const endsTurn = (output: unknown) => output === null;
+ const tool = defineTool({
+ description: "Decides from its result.",
+ endsTurn,
+ inputSchema: z.object({}),
+ execute: () => null,
+ });
+
+ const entry = normalizeToolDefinition(tool, FAILURE_MESSAGE);
+
+ expect(entry.kind === "tool" && entry.definition.endsTurn).toBe(endsTurn);
+ expect(() => normalizeToolDefinition({ ...tool, endsTurn: "yes" }, FAILURE_MESSAGE)).toThrow(
+ FAILURE_MESSAGE,
+ );
});
it("normalizes a tool with a Zod 3 input schema", () => {
diff --git a/packages/eve/src/internal/authored-definition/schema-backed.ts b/packages/eve/src/internal/authored-definition/schema-backed.ts
index 4fe359aa6..400e407e8 100644
--- a/packages/eve/src/internal/authored-definition/schema-backed.ts
+++ b/packages/eve/src/internal/authored-definition/schema-backed.ts
@@ -122,10 +122,16 @@ export function normalizeToolDefinition(value: unknown, message: string): Normal
`${message} Workflow executors require defineWorkflowTool() from "eve/tools". Replace defineTool() or the bare tool object with defineWorkflowTool().`,
);
}
+ if (workflow !== undefined && record.endsTurn !== undefined) {
+ throw new Error(
+ `${message} "endsTurn" is not supported on defineWorkflowTool(). Workflow tools resume the turn when they finish; use defineTool() for a tool that ends the turn.`,
+ );
+ }
expectOnlyKnownKeys(
record,
[
"availableInSubagents",
+ "endsTurn",
"label",
"auth",
"description",
@@ -158,6 +164,12 @@ export function normalizeToolDefinition(value: unknown, message: string): Normal
? undefined
: expectBoolean(record.availableInSubagents, message),
description: expectString(record.description, message),
+ endsTurn:
+ record.endsTurn === undefined || typeof record.endsTurn === "boolean"
+ ? record.endsTurn
+ : (expectFunction(record.endsTurn, message) as (
+ output: unknown,
+ ) => boolean | Promise<boolean>),
hasApproval: record.approval !== undefined,
hasExecute,
hasModelOutputProjection: record.toModelOutput !== undefined,
diff --git a/packages/eve/src/public/channels/slack/defaults.test.ts b/packages/eve/src/public/channels/slack/defaults.test.ts
index 0307aaf1e..e3619bf9c 100644
--- a/packages/eve/src/public/channels/slack/defaults.test.ts
+++ b/packages/eve/src/public/channels/slack/defaults.test.ts
@@ -754,3 +754,16 @@ describe("defaultEvents authorization.completed", () => {
expect(postEphemeral).not.toHaveBeenCalled();
});
});
+
+describe("defaultEvents turn.completed", () => {
+ it("clears the thread status when a turn ends without a reply", async () => {
+ const { channel, post, startTyping } = buildChannelStub();
+ const turn = { sequence: 0, turnId: "turn_0" };
+
+ await defaultEvents["turn.started"]!(turn, channel, sessionCtx);
+ await defaultEvents["turn.completed"]!({ ...turn, sequence: 1 }, channel, sessionCtx);
+
+ expect(startTyping.mock.calls).toEqual([["Working..."], []]);
+ expect(post).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/eve/src/public/channels/slack/defaults.ts b/packages/eve/src/public/channels/slack/defaults.ts
index 8461765cc..06bb3ca73 100644
--- a/packages/eve/src/public/channels/slack/defaults.ts
+++ b/packages/eve/src/public/channels/slack/defaults.ts
@@ -422,6 +422,12 @@ export const defaultEvents: SlackChannelInternalEvents = {
await channel.thread.startTyping("Working...");
},
+ // A reply clears the status, but a turn ended by an `endsTurn` tool posts
+ // none, and Slack would otherwise show the status until it times out.
+ async "turn.completed"(_event, channel, _ctx) {
+ await channel.thread.startTyping();
+ },
+
async "reasoning.appended"(event, channel, _ctx) {
const current = reasoningByState.get(channel.state);
const continuesCurrentBlock =
diff --git a/packages/eve/src/public/tools/no-reply.ts b/packages/eve/src/public/tools/no-reply.ts
new file mode 100644
index 000000000..4d6a06278
--- /dev/null
+++ b/packages/eve/src/public/tools/no-reply.ts
@@ -0,0 +1 @@
+export { type NoReplyToolInput, noReply } from "#tools/provided/no-reply.js";
diff --git a/packages/eve/src/runtime/resolve-tool.ts b/packages/eve/src/runtime/resolve-tool.ts
index b3105fe44..5fdad276f 100644
--- a/packages/eve/src/runtime/resolve-tool.ts
+++ b/packages/eve/src/runtime/resolve-tool.ts
@@ -124,7 +124,7 @@ export async function resolveToolDefinition(
*/
type OptionalResolvedFields = {
-readonly [
- K in "label" | "approval" | "approvalKey" | "toModelOutput"
+ K in "label" | "approval" | "approvalKey" | "endsTurn" | "toModelOutput"
]?: ResolvedToolDefinition[K];
};
@@ -180,6 +180,16 @@ function extractOptionalHooks(
) as ResolvedToolDefinition["approvalKey"];
}
+ if (record.endsTurn !== undefined) {
+ optional.endsTurn =
+ typeof record.endsTurn === "boolean"
+ ? record.endsTurn
+ : (expectFunction(
+ record.endsTurn,
+ describe(definition, "to provide endsTurn as a boolean or a function"),
+ ) as ResolvedToolDefinition["endsTurn"]);
+ }
+
if (record.toModelOutput !== undefined) {
optional.toModelOutput = expectFunction(
record.toModelOutput,
diff --git a/packages/eve/src/tools/definition.ts b/packages/eve/src/tools/definition.ts
index 123844633..009163572 100644
--- a/packages/eve/src/tools/definition.ts
+++ b/packages/eve/src/tools/definition.ts
@@ -59,6 +59,7 @@ export interface InternalToolLabelDefinition {
}
export interface InternalToolDefinition extends ToolDefinitionBase {
+ readonly endsTurn?: ToolDefinition["endsTurn"];
label?: InternalToolLabelDefinition;
name: string;
inputSchema: JsonObject | null;
@@ -224,6 +225,25 @@ export interface ToolDefinition<TInput = unknown, TOutput = unknown> extends Pub
TOutput
> {
execute(input: TInput, ctx: ToolContext): Promise<TOutput> | TOutput | AsyncIterable<TOutput>;
+ /**
+ * Ends the turn after this tool succeeds, without another model call and
+ * without a final reply. Use it for a tool whose action is the whole
+ * answer, such as reacting to a message. The turn ends only when every
+ * tool call in the model's step ends the turn and succeeds; a failed call
+ * lets the model recover. Ignored in delegated sessions, which must return
+ * a reply to their caller, and on turns that request structured output.
+ * With `true`, eve appends a sentence to the description the model sees
+ * telling it the call ends its turn, so write `description` for what the
+ * tool does.
+ *
+ * Pass a function to decide from the result. eve calls it with the output
+ * of `execute` after each successful call, and the call ends the turn only
+ * when it returns `true`; if it throws, the turn continues as though it
+ * returned `false`. The model sees no appended sentence, so describe
+ * when the call ends the turn in `description` if the model needs to know.
+ * Defaults to `false`.
+ */
+ endsTurn?: boolean | ((output: TOutput) => boolean | Promise<boolean>);
/**
* Optional per-tool approval gate. The return value determines whether
* user approval is required before executing this tool.
@@ -274,6 +294,7 @@ export function defineTool<
| AsyncIterable<StandardJSONSchemaV1.InferOutput<TOutputSchema>>,
>(definition: {
description: ToolDefinition<unknown, unknown>["description"];
+ endsTurn?: ToolDefinition<unknown, StandardJSONSchemaV1.InferOutput<TOutputSchema>>["endsTurn"];
inputSchema: TInputSchema;
outputSchema: TOutputSchema;
execute(input: StandardSchemaV1.InferOutput<TInputSchema>, ctx: ToolContext): TReturn;
@@ -297,6 +318,7 @@ export function defineTool<
TReturn,
>(definition: {
description: ToolDefinition<unknown, unknown>["description"];
+ endsTurn?: ToolDefinition<unknown, ToolOutputFromExecuteReturn<TReturn>>["endsTurn"];
inputSchema: TSchema;
outputSchema?: JsonObject;
execute(input: StandardSchemaV1.InferOutput<TSchema>, ctx: ToolContext): TReturn;
@@ -320,6 +342,7 @@ export function defineTool<
| AsyncIterable<StandardJSONSchemaV1.InferOutput<TOutputSchema>>,
>(definition: {
description: ToolDefinition<unknown, unknown>["description"];
+ endsTurn?: ToolDefinition<unknown, StandardJSONSchemaV1.InferOutput<TOutputSchema>>["endsTurn"];
inputSchema: JsonObject;
outputSchema: TOutputSchema;
execute(input: Record<string, unknown>, ctx: ToolContext): TReturn;
@@ -340,6 +363,7 @@ export function defineTool<
>;
export function defineTool<TReturn>(definition: {
description: ToolDefinition<unknown, unknown>["description"];
+ endsTurn?: ToolDefinition<unknown, ToolOutputFromExecuteReturn<TReturn>>["endsTurn"];
inputSchema: JsonObject;
outputSchema?: JsonObject;
execute(input: Record<string, unknown>, ctx: ToolContext): TReturn;
diff --git a/packages/eve/src/tools/dynamic.ts b/packages/eve/src/tools/dynamic.ts
index ce63a51e4..91a010a6a 100644
--- a/packages/eve/src/tools/dynamic.ts
+++ b/packages/eve/src/tools/dynamic.ts
@@ -25,6 +25,12 @@ export interface DynamicToolEntry<TInput = Record<string, unknown>, TOutput = an
readonly availableInSubagents?: boolean;
readonly label?: ToolLabelDefinition<TInput, TOutput>;
readonly description: string;
+ /**
+ * Ends the turn after a successful call, as `endsTurn: true` on
+ * `defineTool`. Dynamic tools accept only `true` or `false`: eve rejects a
+ * function when the resolver returns this entry.
+ */
+ readonly endsTurn?: boolean | ((output: TOutput) => boolean | Promise<boolean>);
readonly inputSchema: PublicToolInputSchema<TInput>;
readonly outputSchema?: PublicToolOutputSchema<TOutput>;
execute(input: TInput, ctx: ToolContext): TOutput | Promise<TOutput>;
diff --git a/packages/eve/src/tools/provided/no-reply.ts b/packages/eve/src/tools/provided/no-reply.ts
new file mode 100644
index 000000000..ae9e49fae
--- /dev/null
+++ b/packages/eve/src/tools/provided/no-reply.ts
@@ -0,0 +1,42 @@
+import { defineTool, type ToolDefinition } from "#public/tools/index.js";
+
+const NO_REPLY_TOOL_DESCRIPTION =
+ "End your turn without sending a reply. Use this when nothing needs to be said, such as when a scheduled check finds nothing to report or an action you already took is the whole answer.";
+
+export interface NoReplyToolInput {
+ reason?: string;
+}
+
+/**
+ * Defines the opt-in `no_reply` tool, which ends the turn without a reply.
+ *
+ * Export it from `agent/tools/no_reply.ts`:
+ *
+ * ```ts
+ * import { noReply } from "eve/tools/no_reply";
+ *
+ * export default noReply();
+ * ```
+ *
+ * A turn that ends with `no_reply` completes without a final message, so
+ * channels and schedules post nothing. Only root sessions receive it.
+ */
+export function noReply(): ToolDefinition<NoReplyToolInput, string> {
+ return defineTool<NoReplyToolInput, string>({
+ availableInSubagents: false,
+ description: NO_REPLY_TOOL_DESCRIPTION,
+ endsTurn: true,
+ execute: () => "No reply was sent.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ reason: {
+ type: "string",
+ description:
+ "Why no reply is needed. Kept in the session history and traces; never sent.",
+ },
+ },
+ additionalProperties: false,
+ },
+ });
+}
diff --git a/packages/eve/src/tools/workflow-definition.test.ts b/packages/eve/src/tools/workflow-definition.test.ts
index 0dab1f448..67d13c4f4 100644
--- a/packages/eve/src/tools/workflow-definition.test.ts
+++ b/packages/eve/src/tools/workflow-definition.test.ts
@@ -168,4 +168,15 @@ describe("defineWorkflowTool", () => {
),
).toThrow("Workflow executors require defineWorkflowTool()");
});
+
+ it("rejects endsTurn on a workflow tool, which resumes the turn when it finishes", () => {
+ const execute = Object.assign(async () => 1, { workflowId: "workflow//test//execute" });
+ const definition = Object.assign(
+ defineWorkflowTool({ description: "Workflow", inputSchema: {}, execute }),
+ { endsTurn: true },
+ );
+ expect(() => normalizeToolDefinition(definition, "Invalid tool.")).toThrow(
+ '"endsTurn" is not supported on defineWorkflowTool()',
+ );
+ });
});