@mastra/memory 0.0.0-error-handler-fix-20251020202607 → 0.0.0-esbuild-bundle-worker-20260807182016
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +4656 -3
- package/LICENSE.md +15 -0
- package/README.md +26 -1
- package/dist/_types/@internal_ai-sdk-v4/dist/index.d.ts +7450 -0
- package/dist/docs/SKILL.md +62 -0
- package/dist/docs/assets/SOURCE_MAP.json +11 -0
- package/dist/docs/references/docs-agents-agent-approval.md +664 -0
- package/dist/docs/references/docs-agents-networks.md +184 -0
- package/dist/docs/references/docs-capabilities-subagents.md +454 -0
- package/dist/docs/references/docs-evals-evals-with-memory.md +146 -0
- package/dist/docs/references/docs-long-running-agents-background-tasks.md +382 -0
- package/dist/docs/references/docs-long-running-agents-goals.md +118 -0
- package/dist/docs/references/docs-memory-memory-processors.md +385 -0
- package/dist/docs/references/docs-memory-message-history.md +348 -0
- package/dist/docs/references/docs-memory-multi-user-threads.md +208 -0
- package/dist/docs/references/docs-memory-observational-memory.md +835 -0
- package/dist/docs/references/docs-memory-overview.md +266 -0
- package/dist/docs/references/docs-memory-semantic-recall.md +401 -0
- package/dist/docs/references/docs-memory-working-memory.md +431 -0
- package/dist/docs/references/docs-storage-overview.md +214 -0
- package/dist/docs/references/reference-core-getMemory.md +51 -0
- package/dist/docs/references/reference-core-listMemory.md +57 -0
- package/dist/docs/references/reference-file-based-agents-memory.md +58 -0
- package/dist/docs/references/reference-memory-clone-utilities.md +203 -0
- package/dist/docs/references/reference-memory-cloneThread.md +173 -0
- package/dist/docs/references/reference-memory-createThread.md +70 -0
- package/dist/docs/references/reference-memory-getThreadById.md +26 -0
- package/dist/docs/references/reference-memory-listThreads.md +147 -0
- package/dist/docs/references/reference-memory-memory-class.md +148 -0
- package/dist/docs/references/reference-memory-observational-memory.md +877 -0
- package/dist/docs/references/reference-memory-summarizeConversation.md +99 -0
- package/dist/docs/references/reference-memory-summarizeThread.md +93 -0
- package/dist/docs/references/reference-processors-token-limiter-processor.md +158 -0
- package/dist/docs/references/reference-storage-dsql.md +430 -0
- package/dist/docs/references/reference-storage-dynamodb.md +284 -0
- package/dist/docs/references/reference-storage-libsql.md +143 -0
- package/dist/docs/references/reference-storage-mongodb.md +267 -0
- package/dist/docs/references/reference-storage-postgresql.md +531 -0
- package/dist/docs/references/reference-storage-redis.md +268 -0
- package/dist/docs/references/reference-storage-upstash.md +162 -0
- package/dist/docs/references/reference-vectors-libsql.md +307 -0
- package/dist/docs/references/reference-vectors-mongodb.md +567 -0
- package/dist/docs/references/reference-vectors-pg.md +430 -0
- package/dist/docs/references/reference-vectors-upstash.md +296 -0
- package/dist/index.cjs +35 -893
- package/dist/index.d.ts +465 -62
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -887
- package/dist/processors/index.cjs +32 -165
- package/dist/processors/index.d.ts +1 -2
- package/dist/processors/index.d.ts.map +1 -1
- package/dist/processors/index.js +2 -158
- package/dist/processors/observational-memory/activation-ttl.d.ts +4 -0
- package/dist/processors/observational-memory/activation-ttl.d.ts.map +1 -0
- package/dist/processors/observational-memory/anchor-ids.d.ts +4 -0
- package/dist/processors/observational-memory/anchor-ids.d.ts.map +1 -0
- package/dist/processors/observational-memory/buffering-coordinator.d.ts +61 -0
- package/dist/processors/observational-memory/buffering-coordinator.d.ts.map +1 -0
- package/dist/processors/observational-memory/built-in-extractors.d.ts +15 -0
- package/dist/processors/observational-memory/built-in-extractors.d.ts.map +1 -0
- package/dist/processors/observational-memory/constants.d.ts +74 -0
- package/dist/processors/observational-memory/constants.d.ts.map +1 -0
- package/dist/processors/observational-memory/date-utils.d.ts +41 -0
- package/dist/processors/observational-memory/date-utils.d.ts.map +1 -0
- package/dist/processors/observational-memory/debug.d.ts +3 -0
- package/dist/processors/observational-memory/debug.d.ts.map +1 -0
- package/dist/processors/observational-memory/extracted-values.d.ts +44 -0
- package/dist/processors/observational-memory/extracted-values.d.ts.map +1 -0
- package/dist/processors/observational-memory/extraction-runner.d.ts +22 -0
- package/dist/processors/observational-memory/extraction-runner.d.ts.map +1 -0
- package/dist/processors/observational-memory/extractor.d.ts +76 -0
- package/dist/processors/observational-memory/extractor.d.ts.map +1 -0
- package/dist/processors/observational-memory/index.d.ts +30 -0
- package/dist/processors/observational-memory/index.d.ts.map +1 -0
- package/dist/processors/observational-memory/internal-request-context.d.ts +17 -0
- package/dist/processors/observational-memory/internal-request-context.d.ts.map +1 -0
- package/dist/processors/observational-memory/markers.d.ts +118 -0
- package/dist/processors/observational-memory/markers.d.ts.map +1 -0
- package/dist/processors/observational-memory/message-utils.d.ts +83 -0
- package/dist/processors/observational-memory/message-utils.d.ts.map +1 -0
- package/dist/processors/observational-memory/model-by-input-tokens.d.ts +14 -0
- package/dist/processors/observational-memory/model-by-input-tokens.d.ts.map +1 -0
- package/dist/processors/observational-memory/model-context.d.ts +2 -0
- package/dist/processors/observational-memory/model-context.d.ts.map +1 -0
- package/dist/processors/observational-memory/observation-groups.d.ts +15 -0
- package/dist/processors/observational-memory/observation-groups.d.ts.map +1 -0
- package/dist/processors/observational-memory/observation-strategies/async-buffer.d.ts +39 -0
- package/dist/processors/observational-memory/observation-strategies/async-buffer.d.ts.map +1 -0
- package/dist/processors/observational-memory/observation-strategies/base.d.ts +122 -0
- package/dist/processors/observational-memory/observation-strategies/base.d.ts.map +1 -0
- package/dist/processors/observational-memory/observation-strategies/index.d.ts +7 -0
- package/dist/processors/observational-memory/observation-strategies/index.d.ts.map +1 -0
- package/dist/processors/observational-memory/observation-strategies/resource-scoped.d.ts +43 -0
- package/dist/processors/observational-memory/observation-strategies/resource-scoped.d.ts.map +1 -0
- package/dist/processors/observational-memory/observation-strategies/sync.d.ts +41 -0
- package/dist/processors/observational-memory/observation-strategies/sync.d.ts.map +1 -0
- package/dist/processors/observational-memory/observation-strategies/types.d.ts +103 -0
- package/dist/processors/observational-memory/observation-strategies/types.d.ts.map +1 -0
- package/dist/processors/observational-memory/observation-turn/index.d.ts +4 -0
- package/dist/processors/observational-memory/observation-turn/index.d.ts.map +1 -0
- package/dist/processors/observational-memory/observation-turn/load-memory-context.d.ts +9 -0
- package/dist/processors/observational-memory/observation-turn/load-memory-context.d.ts.map +1 -0
- package/dist/processors/observational-memory/observation-turn/step.d.ts +53 -0
- package/dist/processors/observational-memory/observation-turn/step.d.ts.map +1 -0
- package/dist/processors/observational-memory/observation-turn/turn.d.ts +139 -0
- package/dist/processors/observational-memory/observation-turn/turn.d.ts.map +1 -0
- package/dist/processors/observational-memory/observation-turn/types.d.ts +46 -0
- package/dist/processors/observational-memory/observation-turn/types.d.ts.map +1 -0
- package/dist/processors/observational-memory/observation-utils.d.ts +16 -0
- package/dist/processors/observational-memory/observation-utils.d.ts.map +1 -0
- package/dist/processors/observational-memory/observational-memory.d.ts +930 -0
- package/dist/processors/observational-memory/observational-memory.d.ts.map +1 -0
- package/dist/processors/observational-memory/observer-agent.d.ts +190 -0
- package/dist/processors/observational-memory/observer-agent.d.ts.map +1 -0
- package/dist/processors/observational-memory/observer-runner.d.ts +141 -0
- package/dist/processors/observational-memory/observer-runner.d.ts.map +1 -0
- package/dist/processors/observational-memory/operation-registry.d.ts +14 -0
- package/dist/processors/observational-memory/operation-registry.d.ts.map +1 -0
- package/dist/processors/observational-memory/processor.d.ts +70 -0
- package/dist/processors/observational-memory/processor.d.ts.map +1 -0
- package/dist/processors/observational-memory/reflector-agent.d.ts +62 -0
- package/dist/processors/observational-memory/reflector-agent.d.ts.map +1 -0
- package/dist/processors/observational-memory/reflector-runner.d.ts +133 -0
- package/dist/processors/observational-memory/reflector-runner.d.ts.map +1 -0
- package/dist/processors/observational-memory/repro-capture.d.ts +33 -0
- package/dist/processors/observational-memory/repro-capture.d.ts.map +1 -0
- package/dist/processors/observational-memory/retry.d.ts +63 -0
- package/dist/processors/observational-memory/retry.d.ts.map +1 -0
- package/dist/processors/observational-memory/string-utils.d.ts +13 -0
- package/dist/processors/observational-memory/string-utils.d.ts.map +1 -0
- package/dist/processors/observational-memory/summarize.d.ts +92 -0
- package/dist/processors/observational-memory/summarize.d.ts.map +1 -0
- package/dist/processors/observational-memory/temporal-markers.d.ts +4 -0
- package/dist/processors/observational-memory/temporal-markers.d.ts.map +1 -0
- package/dist/processors/observational-memory/temporary-memory.d.ts +8 -0
- package/dist/processors/observational-memory/temporary-memory.d.ts.map +1 -0
- package/dist/processors/observational-memory/thresholds.d.ts +52 -0
- package/dist/processors/observational-memory/thresholds.d.ts.map +1 -0
- package/dist/processors/observational-memory/token-counter.d.ts +57 -0
- package/dist/processors/observational-memory/token-counter.d.ts.map +1 -0
- package/dist/processors/observational-memory/tool-result-helpers.d.ts +12 -0
- package/dist/processors/observational-memory/tool-result-helpers.d.ts.map +1 -0
- package/dist/processors/observational-memory/tracing.d.ts +17 -0
- package/dist/processors/observational-memory/tracing.d.ts.map +1 -0
- package/dist/processors/observational-memory/types.d.ts +997 -0
- package/dist/processors/observational-memory/types.d.ts.map +1 -0
- package/dist/processors/observational-memory/working-memory-extractor.d.ts +5 -0
- package/dist/processors/observational-memory/working-memory-extractor.d.ts.map +1 -0
- package/dist/processors/working-memory-state/index.d.ts +2 -0
- package/dist/processors/working-memory-state/index.d.ts.map +1 -0
- package/dist/processors/working-memory-state/processor.d.ts +53 -0
- package/dist/processors/working-memory-state/processor.d.ts.map +1 -0
- package/dist/src-C1tlhGeW.js +28559 -0
- package/dist/src-C1tlhGeW.js.map +1 -0
- package/dist/src-DqoifKIy.cjs +28813 -0
- package/dist/src-DqoifKIy.cjs.map +1 -0
- package/dist/tools/om-tools.d.ts +172 -0
- package/dist/tools/om-tools.d.ts.map +1 -0
- package/dist/tools/working-memory.d.ts +33 -28
- package/dist/tools/working-memory.d.ts.map +1 -1
- package/package.json +36 -28
- package/dist/index.cjs.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/processors/index.cjs.map +0 -1
- package/dist/processors/index.js.map +0 -1
- package/dist/processors/token-limiter.d.ts +0 -32
- package/dist/processors/token-limiter.d.ts.map +0 -1
- package/dist/processors/tool-call-filter.d.ts +0 -20
- package/dist/processors/tool-call-filter.d.ts.map +0 -1
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
> Discover all available pages from the documentation index: https://mastra.ai/llms.txt
|
|
2
|
+
|
|
3
|
+
# Evals with memory
|
|
4
|
+
|
|
5
|
+
Agents that use memory in `thread` scope, including observational memory, require a thread ID at run time. When an eval invokes the agent without one, you'll see:
|
|
6
|
+
|
|
7
|
+
```text
|
|
8
|
+
ObservationalMemory (scope: 'thread') requires a threadId, but none was found in RequestContext or MessageList.
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
This page covers the three working patterns for running Mastra evals against memory-enabled agents, what each path supports, and which one to pick. A complete runnable repro for all three approaches lives in [`examples/evals-with-memory`](https://github.com/mastra-ai/mastra/tree/main/examples/evals-with-memory).
|
|
12
|
+
|
|
13
|
+
## When to use which approach
|
|
14
|
+
|
|
15
|
+
| Goal | Approach |
|
|
16
|
+
| ------------------------------------------------ | ----------------------------------------------------------------------------------------- |
|
|
17
|
+
| One shared conversation across every item | [`runEvals` with global `targetOptions.memory`](#shared-thread-with-runevals) |
|
|
18
|
+
| One independent thread per item, focused CI loop | [`runEvals` per item](#per-item-threads-with-runevals) |
|
|
19
|
+
| Per-item threads driven by a stored `Dataset` | [`dataset.startExperiment` with an inline task](#dataset-experiments-with-an-inline-task) |
|
|
20
|
+
|
|
21
|
+
Pre-seeding `RequestContext` with `MastraMemory` **isn't** a supported way to drive memory into an agent. Thread resolution reads `args.memory.thread`, `RequestContext.MastraMemory` is populated by `prepare-memory-step` after the agent has already resolved its thread.
|
|
22
|
+
|
|
23
|
+
## Shared thread with `runEvals`
|
|
24
|
+
|
|
25
|
+
`runEvals` accepts `targetOptions`, which is forwarded to `agent.generate()`. Passing `memory: { thread, resource }` runs every data item against the same thread, useful for testing recall across a multi-turn conversation.
|
|
26
|
+
|
|
27
|
+
```typescript
|
|
28
|
+
import { runEvals } from '@mastra/core/evals'
|
|
29
|
+
import { supportAgent } from './support-agent'
|
|
30
|
+
import { recallScorer } from '../scorers/recall-scorer'
|
|
31
|
+
|
|
32
|
+
const memory = await supportAgent.getMemory()
|
|
33
|
+
await memory!.createThread({ threadId: 'eval-thread', resourceId: 'ci-user' })
|
|
34
|
+
|
|
35
|
+
const result = await runEvals({
|
|
36
|
+
target: supportAgent,
|
|
37
|
+
scorers: [recallScorer],
|
|
38
|
+
targetOptions: {
|
|
39
|
+
memory: { thread: 'eval-thread', resource: 'ci-user' },
|
|
40
|
+
},
|
|
41
|
+
data: [
|
|
42
|
+
{ input: 'My order number is 12345' },
|
|
43
|
+
{ input: 'What is my order number?', groundTruth: '12345' },
|
|
44
|
+
],
|
|
45
|
+
})
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
`targetOptions` is **global per call**. No per-item override on `RunEvalsDataItem` is available today.
|
|
49
|
+
|
|
50
|
+
## Per-item threads with `runEvals`
|
|
51
|
+
|
|
52
|
+
When each data item needs its own thread (the common CI shape), call `runEvals` once per item with a unique `targetOptions.memory` and aggregate the scores yourself.
|
|
53
|
+
|
|
54
|
+
```typescript
|
|
55
|
+
import { randomUUID } from 'node:crypto'
|
|
56
|
+
import { runEvals } from '@mastra/core/evals'
|
|
57
|
+
import { supportAgent } from './support-agent'
|
|
58
|
+
import { recallScorer } from '../scorers/recall-scorer'
|
|
59
|
+
|
|
60
|
+
const memory = await supportAgent.getMemory()
|
|
61
|
+
const resourceId = 'ci-user'
|
|
62
|
+
|
|
63
|
+
const items = [
|
|
64
|
+
{ input: 'Cats are mammals', groundTruth: 'mammals' },
|
|
65
|
+
{ input: 'Dogs are mammals too', groundTruth: 'mammals' },
|
|
66
|
+
]
|
|
67
|
+
|
|
68
|
+
// `runEvals` returns `{ scores: Record<string, number>; summary: { totalItems } }`.
|
|
69
|
+
const scores: number[] = []
|
|
70
|
+
for (const item of items) {
|
|
71
|
+
const threadId = `eval-${randomUUID()}`
|
|
72
|
+
await memory!.createThread({ threadId, resourceId, title: item.input })
|
|
73
|
+
|
|
74
|
+
const result = await runEvals({
|
|
75
|
+
target: supportAgent,
|
|
76
|
+
scorers: [recallScorer],
|
|
77
|
+
targetOptions: { memory: { thread: threadId, resource: resourceId } },
|
|
78
|
+
data: [item],
|
|
79
|
+
})
|
|
80
|
+
|
|
81
|
+
scores.push(result.scores[recallScorer.id])
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const average = scores.reduce((a, b) => a + b, 0) / scores.length
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
> **Note:** Create the thread before running the eval. Observational memory in `thread` scope reads from a record that must already exist.
|
|
88
|
+
|
|
89
|
+
## Dataset experiments with an inline task
|
|
90
|
+
|
|
91
|
+
`dataset.startExperiment({ target: agent })` **doesn't** forward a `memory` option to the agent, only `requestContext`. To run a stored dataset against a memory-enabled agent, use an inline `task` function and stash `{ threadId, resourceId }` in each item's `metadata`. The scorer pipeline still runs as normal.
|
|
92
|
+
|
|
93
|
+
```typescript
|
|
94
|
+
import { randomUUID } from 'node:crypto'
|
|
95
|
+
import { mastra } from '../index'
|
|
96
|
+
import { supportAgent } from '../agents/support-agent'
|
|
97
|
+
import { recallScorer } from '../scorers/recall-scorer'
|
|
98
|
+
|
|
99
|
+
const memory = await supportAgent.getMemory()
|
|
100
|
+
const resourceId = 'ci-user'
|
|
101
|
+
|
|
102
|
+
const items = [
|
|
103
|
+
{ input: 'Cats are mammals', groundTruth: 'mammals', thread: `ds-${randomUUID()}` },
|
|
104
|
+
{ input: 'Dogs are mammals too', groundTruth: 'mammals', thread: `ds-${randomUUID()}` },
|
|
105
|
+
]
|
|
106
|
+
|
|
107
|
+
for (const it of items) {
|
|
108
|
+
await memory!.createThread({ threadId: it.thread, resourceId, title: it.input })
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const dataset = await mastra.datasets.create({
|
|
112
|
+
name: 'support-recall',
|
|
113
|
+
description: 'Per-item memory via inline task + item metadata',
|
|
114
|
+
})
|
|
115
|
+
|
|
116
|
+
await dataset.addItems({
|
|
117
|
+
items: items.map(it => ({
|
|
118
|
+
input: it.input,
|
|
119
|
+
groundTruth: it.groundTruth,
|
|
120
|
+
metadata: { threadId: it.thread, resourceId },
|
|
121
|
+
})),
|
|
122
|
+
})
|
|
123
|
+
|
|
124
|
+
const summary = await dataset.startExperiment({
|
|
125
|
+
scorers: [recallScorer],
|
|
126
|
+
task: async ({ input, metadata }) => {
|
|
127
|
+
const { threadId, resourceId: rid } = (metadata ?? {}) as {
|
|
128
|
+
threadId: string
|
|
129
|
+
resourceId: string
|
|
130
|
+
}
|
|
131
|
+
const result = await supportAgent.generate(input as string, {
|
|
132
|
+
memory: { thread: threadId, resource: rid },
|
|
133
|
+
})
|
|
134
|
+
return result.text
|
|
135
|
+
},
|
|
136
|
+
})
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
The inline `task` receives the item's `metadata`, so each row can drive its own thread without changing the agent or any scorer. Visit [runEvals reference](https://mastra.ai/reference/evals/run-evals) and [Dataset reference](https://mastra.ai/reference/datasets/dataset) for full configuration.
|
|
140
|
+
|
|
141
|
+
## Related
|
|
142
|
+
|
|
143
|
+
- [Running scorers in CI](https://mastra.ai/docs/evals/running-in-ci)
|
|
144
|
+
- [Running experiments](https://mastra.ai/docs/datasets/running-experiments)
|
|
145
|
+
- [Observational memory](https://mastra.ai/docs/memory/observational-memory)
|
|
146
|
+
- [runEvals API reference](https://mastra.ai/reference/evals/run-evals)
|
|
@@ -0,0 +1,382 @@
|
|
|
1
|
+
> Discover all available pages from the documentation index: https://mastra.ai/llms.txt
|
|
2
|
+
|
|
3
|
+
# Background tasks
|
|
4
|
+
|
|
5
|
+
**Added in:** `@mastra/core@1.29.0`
|
|
6
|
+
|
|
7
|
+
Background tasks let an agent dispatch a long-running tool call without blocking the agentic loop. The tool returns an immediate acknowledgement, the LLM continues responding, and the task runs to completion in the background. When it finishes, its result is written to memory and if you use `stream()` with the [`untilIdle`](https://mastra.ai/reference/streaming/agents/stream) option the agent is re-invoked automatically so the result is processed in the same call.
|
|
8
|
+
|
|
9
|
+
## When to use background tasks
|
|
10
|
+
|
|
11
|
+
Use background tasks when a tool call may take long enough that the user shouldn't wait for it before seeing a response. Common cases:
|
|
12
|
+
|
|
13
|
+
- Subagent delegations that themselves run multi-step research or writing.
|
|
14
|
+
- Tool calls that hit slow external services, queues, or large data jobs.
|
|
15
|
+
- Workflows triggered from a tool call that may take minutes to complete.
|
|
16
|
+
|
|
17
|
+
For tool calls that return quickly, foreground execution using `agent.stream()` and `agent.generate()` is simpler.
|
|
18
|
+
|
|
19
|
+
> **Note:** Background tasks require a configured [storage](https://mastra.ai/docs/storage/overview) backend on the Mastra instance. Tasks are persisted so they survive process restarts.
|
|
20
|
+
|
|
21
|
+
## Quickstart
|
|
22
|
+
|
|
23
|
+
Background tasks are off by default. Enable them by setting `backgroundTasks.enabled` on the Mastra instance:
|
|
24
|
+
|
|
25
|
+
```typescript
|
|
26
|
+
import { Mastra } from '@mastra/core'
|
|
27
|
+
import { LibSQLStore } from '@mastra/libsql'
|
|
28
|
+
|
|
29
|
+
export const mastra = new Mastra({
|
|
30
|
+
storage: new LibSQLStore({ id: 'storage', url: 'file:mastra.db' }),
|
|
31
|
+
backgroundTasks: {
|
|
32
|
+
enabled: true,
|
|
33
|
+
globalConcurrency: 10,
|
|
34
|
+
perAgentConcurrency: 5,
|
|
35
|
+
backpressure: 'queue',
|
|
36
|
+
defaultTimeoutMs: 300_000,
|
|
37
|
+
},
|
|
38
|
+
})
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
The full set of options is listed in the [backgroundTasks configuration reference](https://mastra.ai/reference/configuration).
|
|
42
|
+
|
|
43
|
+
## Run a tool in the background
|
|
44
|
+
|
|
45
|
+
Enabling the manager doesn't run anything in the background by itself as every tool defaults to foreground execution. Tools opt in at one of two layers:
|
|
46
|
+
|
|
47
|
+
1. **Tool-level config**: the tool itself declares it as background-eligible.
|
|
48
|
+
2. **Agent-level config**: the agent declares which of its tools are background-eligible.
|
|
49
|
+
|
|
50
|
+
Once a tool has opted in, the LLM can optionally include a `_background` field in the tool arguments to override the resolved config for a specific call (timeout, retries, or to flip the call back to foreground).
|
|
51
|
+
|
|
52
|
+
### Tool-level
|
|
53
|
+
|
|
54
|
+
Set `background.enabled: true` on the tool definition. Tools opted in at this layer run in the background whenever called by an agent that has the manager enabled.
|
|
55
|
+
|
|
56
|
+
```typescript
|
|
57
|
+
import { createTool } from '@mastra/core/tools'
|
|
58
|
+
import { z } from 'zod'
|
|
59
|
+
|
|
60
|
+
export const researchTool = createTool({
|
|
61
|
+
id: 'research',
|
|
62
|
+
description: 'Run a long research job',
|
|
63
|
+
inputSchema: z.object({ topic: z.string() }),
|
|
64
|
+
background: {
|
|
65
|
+
enabled: true,
|
|
66
|
+
timeoutMs: 600_000,
|
|
67
|
+
maxRetries: 1,
|
|
68
|
+
},
|
|
69
|
+
execute: async ({ topic }) => {
|
|
70
|
+
// Run the research job for topic
|
|
71
|
+
},
|
|
72
|
+
})
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
### Agent-level
|
|
76
|
+
|
|
77
|
+
Use `backgroundTasks.tools` on the agent to opt in specific tools or override timeouts for individual tools, or alternatively run all background-eligible tools in the background. Use `disabled: true` to short-circuit background dispatch for the agent entirely.
|
|
78
|
+
|
|
79
|
+
```typescript
|
|
80
|
+
import { Agent } from '@mastra/core/agent'
|
|
81
|
+
|
|
82
|
+
export const researcher = new Agent({
|
|
83
|
+
id: 'researcher',
|
|
84
|
+
instructions: 'You research topics and answer questions.',
|
|
85
|
+
model: 'openai/gpt-5.6-sol',
|
|
86
|
+
tools: { researchTool, summarizeTool },
|
|
87
|
+
backgroundTasks: {
|
|
88
|
+
tools: {
|
|
89
|
+
researchTool: { enabled: true, timeoutMs: 600_000 },
|
|
90
|
+
summarizeTool: false,
|
|
91
|
+
},
|
|
92
|
+
},
|
|
93
|
+
})
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
Set `tools: 'all'` to opt in every tool the agent has.
|
|
97
|
+
|
|
98
|
+
### LLM per-call override
|
|
99
|
+
|
|
100
|
+
When a tool is registered on an agent that has background tasks enabled, the model can include a `_background` field in the tool arguments to override the resolved configuration for that specific call. The model only includes what it wants to override, all fields in `_background` are optional. The override is stripped from the arguments before the tool runs.
|
|
101
|
+
|
|
102
|
+
```json
|
|
103
|
+
{
|
|
104
|
+
"topic": "solana",
|
|
105
|
+
"_background": { "enabled": true, "timeoutMs": 900_000 }
|
|
106
|
+
}
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
The `_background` override is a _modifier_ on tools the developer has already opted in at the tool or agent layer, it's not a standalone opt-in. If a tool hasn't been opted in, `_background.enabled: true` from the model is ignored and the tool runs in the foreground. This keeps deterministic, foreground-only tools (calculators, lookups, schema validators) from being silently dispatched as tasks.
|
|
110
|
+
|
|
111
|
+
### Resolution order
|
|
112
|
+
|
|
113
|
+
When a tool call is dispatched, the resolved background config is computed in this priority order:
|
|
114
|
+
|
|
115
|
+
1. Agent-level `backgroundTasks.tools` entry for the tool.
|
|
116
|
+
2. Tool-level `background` config.
|
|
117
|
+
3. LLM `_background.enabled` override (only used to enable background dispatch when the tool was opted in at one of the layers above).
|
|
118
|
+
4. Manager defaults (`defaultTimeoutMs`, `defaultRetries`).
|
|
119
|
+
|
|
120
|
+
If the agent has `backgroundTasks.disabled: true`, every tool call runs synchronously regardless of the layers above.
|
|
121
|
+
|
|
122
|
+
## Background tasks related stream chunks
|
|
123
|
+
|
|
124
|
+
When a tool call dispatches as a background task, two streams may surface lifecycle events for it: the agent's own stream and the [`backgroundTaskManager.stream()`](https://mastra.ai/docs/long-running-agents/background-tasks) SSE stream. Each stream covers a different set of chunk types:
|
|
125
|
+
|
|
126
|
+
| Chunk type | When it fires | Emitted by |
|
|
127
|
+
| --------------------------- | -------------------------------------------------------------------------------------- | -------------- |
|
|
128
|
+
| `background-task-started` | The task has been enqueued and assigned a `taskId`. | Agent stream |
|
|
129
|
+
| `background-task-running` | The task picked up a worker and started executing. | Manager stream |
|
|
130
|
+
| `background-task-progress` | Shows number of running background tasks. | Agent stream |
|
|
131
|
+
| `background-task-output` | A streamed output chunk from the task's `execute`. | Manager stream |
|
|
132
|
+
| `background-task-completed` | The task finished successfully. The `payload.result` matches the eventual tool result. | Manager stream |
|
|
133
|
+
| `background-task-failed` | The task threw or timed out. | Manager stream |
|
|
134
|
+
| `background-task-cancelled` | The task was cancelled before completing. | Manager stream |
|
|
135
|
+
| `background-task-suspended` | The tool called `suspend()` from inside its execute. | Manager stream |
|
|
136
|
+
| `background-task-resumed` | A suspended task was resumed via `manager.resume(taskId, resumeData)`. | Manager stream |
|
|
137
|
+
|
|
138
|
+
`agent.stream().fullStream` only emits the agent-loop chunks (`background-task-started`, `background-task-progress`) on its own. `agent.stream()` with `untilIdle: true` emits the same two chunks and additionally subscribes to the manager pubsub for the run's memory scope and pipes the seven manager chunks (`background-task-running`, `background-task-output`, `background-task-completed`, `background-task-failed`, `background-task-cancelled`, `background-task-suspended`, `background-task-resumed`) into the same `fullStream`.
|
|
139
|
+
|
|
140
|
+
`backgroundTaskManager.stream()` only emits the seven manager chunks.
|
|
141
|
+
|
|
142
|
+
The full payload shapes are documented in the [background task chunks reference](https://mastra.ai/reference/streaming/ChunkType).
|
|
143
|
+
|
|
144
|
+
## Keep the agent stream open with `untilIdle`
|
|
145
|
+
|
|
146
|
+
`agent.stream()` returns once the LLM emits a final response even if a background task is still running. Pass `untilIdle: true` when you want the stream to stay open until every dispatched background task has completed and the LLM has had a chance to respond to the result:
|
|
147
|
+
|
|
148
|
+
```typescript
|
|
149
|
+
const stream = await agent.stream('Research solana for me', {
|
|
150
|
+
memory: { thread: 't1', resource: 'u1' },
|
|
151
|
+
untilIdle: true,
|
|
152
|
+
})
|
|
153
|
+
|
|
154
|
+
for await (const chunk of stream.fullStream) {
|
|
155
|
+
// chunks from the initial turn AND any continuation turns triggered by
|
|
156
|
+
// background task completions flow through here
|
|
157
|
+
}
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
When a background task completes, the result is injected into the agent memory, `stream()` re-enters the agentic loop so the LLM can react to it. The stream closes when no tasks are running and no completions are queued.
|
|
161
|
+
|
|
162
|
+
Customize the idle timeout by passing an object instead of `true`. The timer only runs while the wrapper is between turns, so a slow first token won't close the stream. The default is 5 minutes:
|
|
163
|
+
|
|
164
|
+
```typescript
|
|
165
|
+
const stream = await agent.stream('Research solana for me', {
|
|
166
|
+
memory: { thread: 't1', resource: 'u1' },
|
|
167
|
+
untilIdle: { maxIdleMs: 30_000 },
|
|
168
|
+
})
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
Visit [`Agent.stream()`](https://mastra.ai/reference/streaming/agents/stream) for the full API.
|
|
172
|
+
|
|
173
|
+
### Aggregate properties
|
|
174
|
+
|
|
175
|
+
`stream()` with `untilIdle` returns a `MastraModelOutput` that looks like the one from a regular `stream()` call, but `fullStream` alone spans the initial turn and any auto-continuations. Aggregate properties (`text`, `toolCalls`, `toolResults`, `finishReason`, `messageList`, `getFullOutput()`) still resolve against the **first turn's** internal buffer. If you need an aggregate view across continuations, consume `fullStream` yourself and accumulate.
|
|
176
|
+
|
|
177
|
+
## Subagents in the background
|
|
178
|
+
|
|
179
|
+
Subagent invocations are dispatched as tool calls under the hood, so the same background configuration applies. The recommended pattern is to opt each subagent in on the supervisor, it's clearer and lets you tune `timeoutMs` per subagent in one place:
|
|
180
|
+
|
|
181
|
+
```typescript
|
|
182
|
+
import { Agent } from '@mastra/core/agent'
|
|
183
|
+
|
|
184
|
+
const supervisor = new Agent({
|
|
185
|
+
id: 'supervisor',
|
|
186
|
+
instructions: 'Coordinate research and writing using the available agents.',
|
|
187
|
+
model: 'openai/gpt-5.6-sol',
|
|
188
|
+
agents: { researchAgent, writingAgent },
|
|
189
|
+
backgroundTasks: {
|
|
190
|
+
tools: {
|
|
191
|
+
researchAgent: { enabled: true, timeoutMs: 900_000 },
|
|
192
|
+
writingAgent: { enabled: true, timeoutMs: 900_000 },
|
|
193
|
+
},
|
|
194
|
+
},
|
|
195
|
+
})
|
|
196
|
+
|
|
197
|
+
const stream = await supervisor.stream('Research AI in education and write an article', {
|
|
198
|
+
memory: { thread: 't1', resource: 'u1' },
|
|
199
|
+
untilIdle: true,
|
|
200
|
+
})
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
### Inheriting from the subagent
|
|
204
|
+
|
|
205
|
+
If a subagent isn't listed under the supervisor's `backgroundTasks.tools` but has background-eligible tools of its own (either via tool-level `background.enabled: true` or its own `backgroundTasks.tools` entry) the framework still dispatches the entire subagent invocation as a background task. The supervisor inherits the subagent's intent: the subagent itself becomes the background task, and its inner tools run in the foreground inside the subagent's loop.
|
|
206
|
+
|
|
207
|
+
The background config used for the inherited dispatch (for example `waitTimeoutMs`) is derived from the subagent's own `backgroundTasks` config.
|
|
208
|
+
|
|
209
|
+
```typescript
|
|
210
|
+
const researchAgent = new Agent({
|
|
211
|
+
id: 'research-agent',
|
|
212
|
+
description: 'Gathers factual information.',
|
|
213
|
+
model: 'openai/gpt-5-mini',
|
|
214
|
+
tools: { deepResearchTool },
|
|
215
|
+
backgroundTasks: {
|
|
216
|
+
tools: {
|
|
217
|
+
deepResearchTool: { enabled: true, timeoutMs: 600_000 },
|
|
218
|
+
},
|
|
219
|
+
waitTimeoutMs: 900_000,
|
|
220
|
+
},
|
|
221
|
+
})
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
When this `researchAgent` is delegated to from a supervisor that has no backgroundTask configuration for the `researchAgent`, the supervisor still dispatches the whole `researchAgent` invocation as a background task, and `deepResearchTool` runs in the foreground inside that invocation, instead of dispatching its own nested background task.
|
|
225
|
+
|
|
226
|
+
Use this pattern when you want a subagent to behave consistently in the background regardless of which supervisor invokes it. Use the supervisor-side opt-in (above) when you want to tune background behavior centrally per supervisor.
|
|
227
|
+
|
|
228
|
+
## Suspending and resuming
|
|
229
|
+
|
|
230
|
+
A background task can pause itself mid-execution and wait for an external signal before continuing. This is useful for human approvals, webhooks, or any flow where the next step depends on data that arrives later.
|
|
231
|
+
|
|
232
|
+
A tool calls `suspend(data)` from inside its `execute`, which:
|
|
233
|
+
|
|
234
|
+
- Persists `status: 'suspended'` and the `data` payload on the task record.
|
|
235
|
+
- Saves the workflow snapshot so the run survives process restarts.
|
|
236
|
+
- Emits a `background-task-suspended` chunk on the manager stream.
|
|
237
|
+
- Releases the concurrency slot so other tasks can run.
|
|
238
|
+
|
|
239
|
+
Resume the task with `mastra.backgroundTaskManager.resume(taskId, resumeData)`. The `resumeData` arrives in the tool's `execute` options on the resumed run, and the task transitions back to `running`.
|
|
240
|
+
|
|
241
|
+
```typescript
|
|
242
|
+
import { createTool } from '@mastra/core/tools'
|
|
243
|
+
import { z } from 'zod'
|
|
244
|
+
|
|
245
|
+
export const reviewTool = createTool({
|
|
246
|
+
id: 'review',
|
|
247
|
+
description: 'Submit a draft for human review.',
|
|
248
|
+
inputSchema: z.object({ draft: z.string() }),
|
|
249
|
+
outputSchema: z.object({ approvedBy: z.string(), edits: z.string().optional() }),
|
|
250
|
+
background: { enabled: true },
|
|
251
|
+
execute: async ({ draft }, context) => {
|
|
252
|
+
const { suspend, resumeData } = context.agent
|
|
253
|
+
if (!resumeData) {
|
|
254
|
+
await suspend?.({ awaiting: 'approval', draft })
|
|
255
|
+
return { approvedBy: '', edits: undefined }
|
|
256
|
+
}
|
|
257
|
+
const { reviewer, edits } = resumeData as { reviewer: string; edits?: string }
|
|
258
|
+
return { approvedBy: reviewer, edits }
|
|
259
|
+
},
|
|
260
|
+
})
|
|
261
|
+
```
|
|
262
|
+
|
|
263
|
+
The first invocation of `execute` sees `resumeData === undefined` and calls `suspend`. After the task is resumed, the runtime restarts the tool with `resumeData` populated. The `if` condition is false, so the tool returns its real result.
|
|
264
|
+
|
|
265
|
+
To resume the task once an approval arrives:
|
|
266
|
+
|
|
267
|
+
```typescript
|
|
268
|
+
await mastra.backgroundTaskManager?.resume(taskId, {
|
|
269
|
+
reviewer: 'alice@example.com',
|
|
270
|
+
edits: 'Reworded paragraph 3.',
|
|
271
|
+
})
|
|
272
|
+
```
|
|
273
|
+
|
|
274
|
+
### What happens to the agent loop
|
|
275
|
+
|
|
276
|
+
When a task suspends mid-`stream()` with `untilIdle`, the wrapper treats it as terminal for the current iteration and closes. To continue the agent immediately when the resume payload is in hand, call `agent.resumeStream(resumeData, { runId, toolCallId, memory, untilIdle: true })`: the resumed bg task runs to completion, its result is added to the message list, and the agent runs a follow-up turn, all on the same SSE connection. If you'd rather drive the resume out-of-band, call `mastra.backgroundTaskManager.resume(taskId, resumeData)` directly and the result still writes into the thread for the next user turn to pick up.
|
|
277
|
+
|
|
278
|
+
### Re-registering the executor on resume
|
|
279
|
+
|
|
280
|
+
The manager keeps tool executors in process memory. If the process restarts while a task is suspended, the executor closure is gone, the caller of `resume()` must re-register it first via `manager.registerTaskContext(taskId, ...)`. Tasks dispatched and resumed inside the same process don't need this.
|
|
281
|
+
|
|
282
|
+
### Cancelling a suspended task
|
|
283
|
+
|
|
284
|
+
`manager.cancel(taskId)` works against suspended tasks the same way it works for running ones. The row changes to `cancelled` and the workflow snapshot is cleaned up. A `task.cancelled` event then fires.
|
|
285
|
+
|
|
286
|
+
## Lifecycle callbacks
|
|
287
|
+
|
|
288
|
+
Each layer can register terminal-state callbacks. They don't replace one another, and success/failure hooks fire for their outcomes:
|
|
289
|
+
|
|
290
|
+
- Tool-level `background.onComplete` / `onFailed`: scoped to one tool.
|
|
291
|
+
- Agent-level `backgroundTasks.onTaskComplete` / `onTaskFailed`: scoped to all tasks dispatched by this agent.
|
|
292
|
+
- Manager-level `onTaskComplete` / `onTaskFailed`: scoped globally.
|
|
293
|
+
|
|
294
|
+
```typescript
|
|
295
|
+
export const mastra = new Mastra({
|
|
296
|
+
storage,
|
|
297
|
+
backgroundTasks: {
|
|
298
|
+
enabled: true,
|
|
299
|
+
onTaskComplete: task => {
|
|
300
|
+
logger.info('Background task complete', { taskId: task.id, toolName: task.toolName })
|
|
301
|
+
},
|
|
302
|
+
onTaskFailed: task => {
|
|
303
|
+
logger.error('Background task failed', { taskId: task.id, error: task.error })
|
|
304
|
+
},
|
|
305
|
+
},
|
|
306
|
+
})
|
|
307
|
+
```
|
|
308
|
+
|
|
309
|
+
## Streaming
|
|
310
|
+
|
|
311
|
+
### Subscribe to all task events
|
|
312
|
+
|
|
313
|
+
Calling `stream()` with no filter returns a stream of every task event in the system. On connection, the stream emits a snapshot of all currently running tasks, then forwards live events as they happen.
|
|
314
|
+
|
|
315
|
+
```typescript
|
|
316
|
+
const bgManager = mastra.backgroundTaskManager
|
|
317
|
+
if (!bgManager) throw new Error('Background tasks are not enabled')
|
|
318
|
+
|
|
319
|
+
const controller = new AbortController()
|
|
320
|
+
const stream = bgManager.stream({ abortSignal: controller.signal })
|
|
321
|
+
|
|
322
|
+
for await (const chunk of stream) {
|
|
323
|
+
switch (chunk.type) {
|
|
324
|
+
case 'background-task-running':
|
|
325
|
+
console.log('started', chunk.payload.taskId, chunk.payload.toolName)
|
|
326
|
+
break
|
|
327
|
+
case 'background-task-completed':
|
|
328
|
+
console.log('done', chunk.payload.taskId, chunk.payload.result)
|
|
329
|
+
break
|
|
330
|
+
case 'background-task-failed':
|
|
331
|
+
console.error('failed', chunk.payload.taskId, chunk.payload.error)
|
|
332
|
+
break
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
```
|
|
336
|
+
|
|
337
|
+
The stream stays open until the caller's `AbortSignal` fires. Always pass an `abortSignal` so you can disconnect cleanly.
|
|
338
|
+
|
|
339
|
+
### Filter the stream
|
|
340
|
+
|
|
341
|
+
Pass any combination of filter options to narrow the events you receive. Filters apply to both the initial snapshot and the live event subscription.
|
|
342
|
+
|
|
343
|
+
```typescript
|
|
344
|
+
const stream = bgManager.stream({
|
|
345
|
+
agentId: 'researcher',
|
|
346
|
+
threadId: 't1',
|
|
347
|
+
resourceId: 'u1',
|
|
348
|
+
abortSignal: controller.signal,
|
|
349
|
+
})
|
|
350
|
+
```
|
|
351
|
+
|
|
352
|
+
| Filter | Description |
|
|
353
|
+
| ------------- | --------------------------------------------------- |
|
|
354
|
+
| `agentId` | Only events from tasks dispatched by this agent |
|
|
355
|
+
| `runId` | Only events from this specific agent run |
|
|
356
|
+
| `threadId` | Only events from tasks scoped to this memory thread |
|
|
357
|
+
| `resourceId` | Only events from tasks scoped to this resource |
|
|
358
|
+
| `taskId` | Only events for a single task |
|
|
359
|
+
| `abortSignal` | Closes the stream when the signal aborts |
|
|
360
|
+
|
|
361
|
+
### Look up task state directly
|
|
362
|
+
|
|
363
|
+
For one-off lookups instead of a live stream, use `getTask` and `listTasks`:
|
|
364
|
+
|
|
365
|
+
```typescript
|
|
366
|
+
const task = await mastra.backgroundTaskManager?.getTask(taskId)
|
|
367
|
+
const { tasks, total } = await mastra.backgroundTaskManager?.listTasks({
|
|
368
|
+
status: 'running',
|
|
369
|
+
agentId: 'researcher',
|
|
370
|
+
})
|
|
371
|
+
```
|
|
372
|
+
|
|
373
|
+
These read from storage rather than the pubsub stream, so they're suitable for paginated lists and detail views.
|
|
374
|
+
|
|
375
|
+
## Related
|
|
376
|
+
|
|
377
|
+
- [`Agent.stream()` reference](https://mastra.ai/reference/streaming/agents/stream)
|
|
378
|
+
- [backgroundTasks configuration reference](https://mastra.ai/reference/configuration)
|
|
379
|
+
- [Durable agents](https://mastra.ai/docs/long-running-agents/durable-agents)
|
|
380
|
+
- [Supervisor agents](https://mastra.ai/docs/capabilities/subagents)
|
|
381
|
+
- [Stream chunk types](https://mastra.ai/reference/streaming/ChunkType)
|
|
382
|
+
- [Storage](https://mastra.ai/docs/storage/overview)
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
> Discover all available pages from the documentation index: https://mastra.ai/llms.txt
|
|
2
|
+
|
|
3
|
+
# Goals
|
|
4
|
+
|
|
5
|
+
**Added in:** `@mastra/core@1.42.0`
|
|
6
|
+
|
|
7
|
+
> **Beta:** The Goals feature is in beta stage and subject to breaking changes in minor versions until it graduates from its beta status.
|
|
8
|
+
|
|
9
|
+
A goal is a durable, thread-scoped objective: a standing instruction the agent keeps working toward across loop iterations until a judge model decides it's satisfied or a run budget is exhausted.
|
|
10
|
+
|
|
11
|
+
The objective is persisted in thread state, so it survives reloads and is evaluated in-loop, even when a new message arrives in the middle of an already-running turn.
|
|
12
|
+
|
|
13
|
+
Goals build on the same machinery as [`isTaskComplete`](https://mastra.ai/docs/capabilities/subagents): an LLM-as-judge scores the agent's output each iteration and gates the loop. The difference is that a goal is **durable** (stored in thread state, not passed per call) and is set and updated through `Agent` methods rather than per-`stream()` options.
|
|
14
|
+
|
|
15
|
+
## When to use goals
|
|
16
|
+
|
|
17
|
+
Use a goal when you want an agent to keep working toward a single objective across many iterations and messages, without re-supplying the success criteria on every call:
|
|
18
|
+
|
|
19
|
+
- A standing objective the agent should pursue until a judge says it's done.
|
|
20
|
+
- Work that should continue across mid-run messages (a message delivered into a live run is still judged against the goal).
|
|
21
|
+
- An objective that must persist across thread reloads or process restarts.
|
|
22
|
+
|
|
23
|
+
For a one-off completion check within a single `stream()` call, use [`isTaskComplete`](https://mastra.ai/docs/capabilities/subagents) instead.
|
|
24
|
+
|
|
25
|
+
## Quickstart
|
|
26
|
+
|
|
27
|
+
Goals require a configured [storage](https://mastra.ai/docs/storage/overview) backend and a memory-backed thread. Add a `goal` config to the agent, a judge model is required for the goal to do anything, then set an objective for a thread:
|
|
28
|
+
|
|
29
|
+
```typescript
|
|
30
|
+
import { Agent } from '@mastra/core/agent'
|
|
31
|
+
|
|
32
|
+
const worker = new Agent({
|
|
33
|
+
id: 'worker',
|
|
34
|
+
name: 'worker',
|
|
35
|
+
instructions: 'You complete software tasks end to end.',
|
|
36
|
+
model: 'openai/gpt-5.6-sol',
|
|
37
|
+
memory,
|
|
38
|
+
goal: {
|
|
39
|
+
judge: 'openai/gpt-5-mini',
|
|
40
|
+
maxRuns: 50,
|
|
41
|
+
},
|
|
42
|
+
})
|
|
43
|
+
|
|
44
|
+
// Set the durable objective for a thread.
|
|
45
|
+
await worker.setObjective('Add and test a /health endpoint', {
|
|
46
|
+
threadId,
|
|
47
|
+
resourceId,
|
|
48
|
+
})
|
|
49
|
+
|
|
50
|
+
// The objective is judged each iteration until it's complete or maxRuns is hit.
|
|
51
|
+
const stream = await worker.stream('Start working on the goal', {
|
|
52
|
+
memory: { thread: threadId, resource: resourceId },
|
|
53
|
+
})
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
The `goal` config auto-registers the state-signal projection, so the model always sees the current objective as `<current-objective>` in its context without extra setup.
|
|
57
|
+
|
|
58
|
+
## How the goal step works
|
|
59
|
+
|
|
60
|
+
A goal step runs inside the agentic execution loop, right after `isTaskComplete`. On a real candidate answer it scores the conversation against the objective and gates the loop:
|
|
61
|
+
|
|
62
|
+
- **Not satisfied, budget remaining** → the loop continues. Per-evaluation feedback is injected so the agent iterates.
|
|
63
|
+
- **Satisfied** → the loop stops and the objective is marked `done`.
|
|
64
|
+
- **Budget exhausted** (`runsUsed >= maxRuns`) → the loop stops and the objective is marked `paused`. Raise `maxRuns`, then resume the objective to continue.
|
|
65
|
+
|
|
66
|
+
The step is a no-op for background-task, mid-tool-loop, and working-memory-only iterations, the same gating as `isTaskComplete`.
|
|
67
|
+
|
|
68
|
+
**The judge model is the activation switch.** If no judge resolves (neither the per-objective override nor the agent's `goal.judge`), the goal step performs no scoring or budget consumption and emits no `goal` chunk.
|
|
69
|
+
|
|
70
|
+
Effective settings resolve as per-objective record value → agent `goal` config → built-in default (`maxRuns` `50`, a default judge prompt).
|
|
71
|
+
|
|
72
|
+
By default the step uses a built-in LLM-as-judge scorer that returns `1` when the objective is achieved and `0` otherwise. Supply your own scorer with `goal.scorer` to customize judging.
|
|
73
|
+
|
|
74
|
+
```typescript
|
|
75
|
+
const worker = new Agent({
|
|
76
|
+
id: 'worker',
|
|
77
|
+
name: 'worker',
|
|
78
|
+
instructions: 'You complete software tasks end to end.',
|
|
79
|
+
model: 'openai/gpt-5.6-sol',
|
|
80
|
+
memory,
|
|
81
|
+
goal: {
|
|
82
|
+
// A resolver function lets you inject provider credentials and read the
|
|
83
|
+
// current judge selection at runtime; returning `undefined` keeps the
|
|
84
|
+
// goal step a no-op.
|
|
85
|
+
judge: ({ requestContext }) => resolveJudgeModel(requestContext),
|
|
86
|
+
maxRuns: 30,
|
|
87
|
+
prompt: 'Only mark the goal complete when tests pass.',
|
|
88
|
+
},
|
|
89
|
+
})
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
Each evaluation emits a typed `goal` stream chunk (`GoalEvaluationPayload`: `objective`, `iteration`, `maxRuns`, `passed`, `status`, `results`, `reason`, `duration`, `timedOut`, `maxRunsReached`, `suppressFeedback`) so a UI can show goal progress mid-run.
|
|
93
|
+
|
|
94
|
+
## Managing the objective
|
|
95
|
+
|
|
96
|
+
Control the objective for a thread with `Agent` methods. All of them no-op when the run isn't memory-backed (they require storage and a `threadId`):
|
|
97
|
+
|
|
98
|
+
```typescript
|
|
99
|
+
// Read the current objective record.
|
|
100
|
+
const record = await worker.getObjective({ threadId })
|
|
101
|
+
|
|
102
|
+
// Update options on the active objective (only provided fields are written;
|
|
103
|
+
// unset fields fall back to the agent's `goal` config).
|
|
104
|
+
await worker.updateObjectiveOptions({ threadId, maxRuns: 100 })
|
|
105
|
+
|
|
106
|
+
// Drop the objective.
|
|
107
|
+
await worker.clearObjective({ threadId })
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
Objective records include an optional `activeDurationMs` value for user interfaces that display active pursuit time. Mastra advances this value while an agent runs toward an active objective and checkpoints it when the run ends or waits for tool approval. Missing values represent zero, and the duration measures agent execution rather than the goal's wall-clock age.
|
|
111
|
+
|
|
112
|
+
Per-objective values written by `setObjective` / `updateObjectiveOptions` take precedence over the agent's `goal` config, and that precedence is remembered in thread state. See the [`GoalEvaluationPayload` in the ChunkType reference](https://mastra.ai/reference/streaming/ChunkType) for the full goal chunk shape.
|
|
113
|
+
|
|
114
|
+
## Related
|
|
115
|
+
|
|
116
|
+
- [Supervisor agents](https://mastra.ai/docs/capabilities/subagents): `isTaskComplete` and the rubric scorer
|
|
117
|
+
- [Signal providers](https://mastra.ai/docs/long-running-agents/signal-providers): how the objective is projected into context
|
|
118
|
+
- [Memory storage](https://mastra.ai/docs/storage/overview): the storage backend goals require
|