@mastra/server 1.86.0-alpha.7 → 1.86.0-alpha.8
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/dist/{a2a-WPGF38fX.js → a2a-BfWMjFe2.js} +1 -1
- package/dist/{a2a-vSZkdSRE.cjs → a2a-DQIwTZyo.cjs} +1 -1
- package/dist/{agent-builder-C4AIqOxt.js → agent-builder-DpuK5-6A.js} +2 -2
- package/dist/{agent-builder-dZlRNj1k.cjs → agent-builder-NSemjs4B.cjs} +2 -2
- package/dist/{agent-controller-BHJDvCaS.cjs → agent-controller-BP-CFfsg.cjs} +9 -9
- package/dist/{agent-controller-NRR6SK66.js → agent-controller-CzKnfKkw.js} +9 -9
- package/dist/{agent-versions-CwWhEoU5.cjs → agent-versions-0q4KKmLv.cjs} +12 -12
- package/dist/{agent-versions-DfcKpYNW.js → agent-versions-Pml6WNbA.js} +12 -12
- package/dist/{agents-mjQZV5tv.cjs → agents-BO1mcMDf.cjs} +14 -3
- package/dist/{agents-272TP94y.js → agents-YvaBPFiS.js} +14 -3
- package/dist/{api-schema-manifest-DVkepK_s.cjs → api-schema-manifest-016lHJO2.cjs} +1 -1
- package/dist/{api-schema-manifest-BjhiTdNv.js → api-schema-manifest-CAZsA5Lk.js} +1 -1
- package/dist/{catalogue-BTE9b_mr.cjs → catalogue-Cf7Zz7zb.cjs} +11 -11
- package/dist/{catalogue-DH64Duv-.js → catalogue-DN4dvU88.js} +11 -11
- package/dist/{conversations-CXyaNjLR.js → conversations-4ZO0Pjvk.js} +1 -1
- package/dist/{conversations-BWA_---j.cjs → conversations-BaYtooZZ.cjs} +1 -1
- package/dist/{datasets-C1XJLHN8.js → datasets-CYdtUF8e.js} +4 -1
- package/dist/{datasets-hqDd4IUN.cjs → datasets-CZRqni0N.cjs} +4 -1
- package/dist/dist-Bz6gINFc.js +1 -0
- package/dist/{dist-DGwsCtT4.cjs → dist-DaRCrkAU.cjs} +228 -217
- package/dist/{dist-CSffo32A.cjs → dist-uiPbWl5E.cjs} +1 -1
- package/dist/{dist-Bp1bObAq.js → dist-yny1avqv.js} +228 -217
- package/dist/docs/SKILL.md +1 -1
- package/dist/docs/assets/SOURCE_MAP.json +1 -1
- package/dist/docs/references/reference-observability-tracing-advanced-queries.md +20 -0
- package/dist/{dynamic-workflows-DPgV6qtS.cjs → dynamic-workflows-CEKdGcSr.cjs} +4 -4
- package/dist/{dynamic-workflows-DmkCJ4Lp.js → dynamic-workflows-DF9X_oDG.js} +4 -4
- package/dist/{editor-builder-BS2xogE_.cjs → editor-builder-ChYG8YTs.cjs} +1 -1
- package/dist/{editor-builder-BayzCprJ.js → editor-builder-CwsIbd0F.js} +1 -1
- package/dist/{observability-zr7LDCQG.js → observability-URaJnI_U.js} +1 -1
- package/dist/{observability-Cn4P60P4.cjs → observability-zNA_CVaz.cjs} +1 -1
- package/dist/{plans-xGwuiZUd.js → plans-CbR8EDiT.js} +1 -1
- package/dist/{plans-Bes_LVgv.cjs → plans-k3UN9Nd1.cjs} +1 -1
- package/dist/probe-image-size-DZvSdjzK.js +13297 -0
- package/dist/probe-image-size-z8zXmjaH.cjs +13304 -0
- package/dist/{responses-BH567IZf.cjs → responses-B-BKx236.cjs} +1 -1
- package/dist/{responses-CwQO5y2X.js → responses-Blzxy0XP.js} +1 -1
- package/dist/{routes-CrBCJmjc.js → routes-D-I2voQe.js} +16 -16
- package/dist/{routes-6p-xrUIq.cjs → routes-jiZyt9kU.cjs} +16 -16
- package/dist/{schedules-0ceTSdBB.cjs → schedules-CwL28Eca.cjs} +4 -4
- package/dist/{schedules-D_VfFdAH.js → schedules-RWgPeypN.js} +4 -4
- package/dist/{scorer-versions-Bhdvt-cX.cjs → scorer-versions-DK-PGj7-.cjs} +1 -1
- package/dist/{scorer-versions-DhT7Lj33.js → scorer-versions-oJoK2Exw.js} +1 -1
- package/dist/{scores-CXNkN7Bn.cjs → scores-BikU9phm.cjs} +1 -1
- package/dist/{scores-ksmJiJnJ.js → scores-DAv6Uisq.js} +1 -1
- package/dist/server/handlers/a2a.cjs +1 -1
- package/dist/server/handlers/a2a.js +1 -1
- package/dist/server/handlers/agent-builder.cjs +1 -1
- package/dist/server/handlers/agent-builder.js +1 -1
- package/dist/server/handlers/agent-controller.cjs +1 -1
- package/dist/server/handlers/agent-controller.js +1 -1
- package/dist/server/handlers/agent-versions.cjs +1 -1
- package/dist/server/handlers/agent-versions.js +1 -1
- package/dist/server/handlers/agents.cjs +1 -1
- package/dist/server/handlers/agents.js +1 -1
- package/dist/server/handlers/auth.cjs +1 -1
- package/dist/server/handlers/auth.js +1 -1
- package/dist/server/handlers/conversations.cjs +1 -1
- package/dist/server/handlers/conversations.js +1 -1
- package/dist/server/handlers/datasets.cjs +16 -11
- package/dist/server/handlers/datasets.d.ts +6 -0
- package/dist/server/handlers/datasets.js +16 -11
- package/dist/server/handlers/dynamic-workflows.cjs +1 -1
- package/dist/server/handlers/dynamic-workflows.js +1 -1
- package/dist/server/handlers/editor-builder.cjs +1 -1
- package/dist/server/handlers/editor-builder.js +1 -1
- package/dist/server/handlers/favorites-enrichment.cjs +1 -1
- package/dist/server/handlers/favorites-enrichment.js +1 -1
- package/dist/server/handlers/observability.cjs +1 -1
- package/dist/server/handlers/observability.js +1 -1
- package/dist/server/handlers/plans.cjs +1 -1
- package/dist/server/handlers/plans.js +1 -1
- package/dist/server/handlers/responses.cjs +1 -1
- package/dist/server/handlers/responses.js +1 -1
- package/dist/server/handlers/schedules.cjs +1 -1
- package/dist/server/handlers/schedules.js +1 -1
- package/dist/server/handlers/scorer-versions.cjs +1 -1
- package/dist/server/handlers/scorer-versions.js +1 -1
- package/dist/server/handlers/scores.cjs +1 -1
- package/dist/server/handlers/scores.js +1 -1
- package/dist/server/handlers/stored-agent-favorites.cjs +3 -3
- package/dist/server/handlers/stored-agent-favorites.js +3 -3
- package/dist/server/handlers/stored-agents.cjs +2 -2
- package/dist/server/handlers/stored-agents.js +2 -2
- package/dist/server/handlers/stored-scorers.cjs +1 -1
- package/dist/server/handlers/stored-scorers.js +1 -1
- package/dist/server/handlers/stored-skill-favorites.cjs +2 -2
- package/dist/server/handlers/stored-skill-favorites.js +2 -2
- package/dist/server/handlers/stored-skills.cjs +1 -1
- package/dist/server/handlers/stored-skills.js +1 -1
- package/dist/server/handlers/system.cjs +1 -1
- package/dist/server/handlers/system.js +1 -1
- package/dist/server/handlers/tool-providers.cjs +2 -2
- package/dist/server/handlers/tool-providers.js +2 -2
- package/dist/server/handlers/tools.cjs +1 -1
- package/dist/server/handlers/tools.js +1 -1
- package/dist/server/handlers/voice.cjs +1 -1
- package/dist/server/handlers/voice.js +1 -1
- package/dist/server/handlers/workflows.cjs +1 -1
- package/dist/server/handlers/workflows.js +1 -1
- package/dist/server/handlers.cjs +12 -12
- package/dist/server/handlers.js +12 -12
- package/dist/server/schemas/datasets.d.ts +3 -0
- package/dist/server/schemas/index.cjs +6 -6
- package/dist/server/schemas/index.js +6 -6
- package/dist/server/server-adapter/index.cjs +3 -3
- package/dist/server/server-adapter/index.js +3 -3
- package/dist/server/server-adapter/routes/conversations.d.ts +3 -3
- package/dist/server/server-adapter/routes/datasets.d.ts +6 -0
- package/dist/{server-adapter-Ceag3til.cjs → server-adapter-BB2Lw2Ig.cjs} +4 -4
- package/dist/{server-adapter-BGOi-s7x.js → server-adapter-CMJcvkpD.js} +4 -4
- package/dist/{stored-agents-m0Knvv29.cjs → stored-agents-BS4_LGSs.cjs} +32 -32
- package/dist/{stored-agents-DmN_pIIl.js → stored-agents-DcyDMKP2.js} +32 -32
- package/dist/{stored-scorers-2F2k6XSx.js → stored-scorers-Bdz_5k57.js} +1 -1
- package/dist/{stored-scorers-iM2Qq9Nh.cjs → stored-scorers-D8YYszOj.cjs} +1 -1
- package/dist/{tool-providers-Cq3vFqgE.js → tool-providers-BN2Ni06Z.js} +2 -2
- package/dist/{tool-providers-BVwRJTtB.cjs → tool-providers-BeiSkVHu.cjs} +2 -2
- package/dist/{tools-DLZ7go-n.cjs → tools-CoamSJif.cjs} +1 -1
- package/dist/{tools-CY44YtDW.js → tools-DsSk01Ti.js} +1 -1
- package/dist/{voice-DTjrAgqg.js → voice-BFh2Zx5m.js} +1 -1
- package/dist/{voice-NaerSeVQ.cjs → voice-CquR7YyA.cjs} +1 -1
- package/dist/{workflows-gIKukZ1O.cjs → workflows-CHKSHV4f.cjs} +33 -0
- package/dist/{workflows-D3QrUMfm.js → workflows-D5bfbang.js} +33 -0
- package/package.json +3 -3
- package/dist/dist-Bn0zFASI.js +0 -1
- package/dist/probe-image-size-BR5MlnnJ.cjs +0 -13304
- package/dist/probe-image-size-DBCcUUw_.js +0 -13297
|
@@ -7,12 +7,12 @@ zod_v4 = require_rolldown_runtime.__toESM(zod_v4, 1);
|
|
|
7
7
|
let _mastra_core_schema = require("@mastra/core/schema");
|
|
8
8
|
let zod_v3 = require("zod/v3");
|
|
9
9
|
let zod = require("zod");
|
|
10
|
+
let util = require("util");
|
|
10
11
|
let _mastra_core_memory = require("@mastra/core/memory");
|
|
11
12
|
let _mastra_core_agent = require("@mastra/core/agent");
|
|
12
13
|
let _mastra_core_error = require("@mastra/core/error");
|
|
13
14
|
let _mastra_core_llm = require("@mastra/core/llm");
|
|
14
15
|
let _mastra_core_tools = require("@mastra/core/tools");
|
|
15
|
-
let util = require("util");
|
|
16
16
|
let _mastra_core_request_context = require("@mastra/core/request-context");
|
|
17
17
|
let _mastra_core_utils = require("@mastra/core/utils");
|
|
18
18
|
let _mastra_core_storage = require("@mastra/core/storage");
|
|
@@ -897,7 +897,7 @@ var require_jpeg = /* @__PURE__ */ require_rolldown_runtime.__commonJSMin(((expo
|
|
|
897
897
|
var str2arr = require_utils().str2arr;
|
|
898
898
|
var sliceEq = require_utils().sliceEq;
|
|
899
899
|
var exifOrientation = require_exif_orientation_parser();
|
|
900
|
-
var SIG_JPEG = str2arr("
|
|
900
|
+
var SIG_JPEG = str2arr("\u00FF\u00D8\u00FF");
|
|
901
901
|
var SIG_EXIF = str2arr("Exif\0\0");
|
|
902
902
|
var S_SIGNATURE = 0;
|
|
903
903
|
var S_MARKER_START = 1;
|
|
@@ -1043,7 +1043,7 @@ var require_png = /* @__PURE__ */ require_rolldown_runtime.__commonJSMin(((expor
|
|
|
1043
1043
|
var str2arr = require_utils().str2arr;
|
|
1044
1044
|
var sliceEq = require_utils().sliceEq;
|
|
1045
1045
|
var readUInt32BE = require_read_le_be().readUInt32BE;
|
|
1046
|
-
var SIG_PNG = str2arr("
|
|
1046
|
+
var SIG_PNG = str2arr("\u0089PNG\r\n\n");
|
|
1047
1047
|
var SIG_IHDR = str2arr("IHDR");
|
|
1048
1048
|
function PngParser() {
|
|
1049
1049
|
this.partial_buffer = /* @__PURE__ */ new Uint8Array(24);
|
|
@@ -8656,7 +8656,7 @@ function splitLines(text) {
|
|
|
8656
8656
|
else result.push(result.pop().slice(0, -1));
|
|
8657
8657
|
return result;
|
|
8658
8658
|
}
|
|
8659
|
-
// ../memory/dist/src-
|
|
8659
|
+
// ../memory/dist/src-TRQ73bGO.js
|
|
8660
8660
|
var __defProp$3 = Object.defineProperty;
|
|
8661
8661
|
var __exportAll = (all, no_symbols) => {
|
|
8662
8662
|
let target = {};
|
|
@@ -32877,14 +32877,14 @@ function getRetrievalInstructions(scope = "resource", customInstructions, search
|
|
|
32877
32877
|
The recall tool works across ALL of this user's conversation threads, not just the current one.
|
|
32878
32878
|
|
|
32879
32879
|
- Use \`mode: "search"\` with a \`query\` to find relevant history, even when you already know the thread. Each result includes its thread ID, observation group ID, and source message range.
|
|
32880
|
-
- Use \`mode: "messages"\` for original wording or details behind an observation
|
|
32880
|
+
- Use \`mode: "messages"\` for original wording or details behind an observation \u2014 pass \`threadId\` to read another thread and a \`cursor\` from the source message range.
|
|
32881
32881
|
- Use \`mode: "threads"\` to list the user's threads (IDs, titles, dates) when you need to discover where something was discussed. Use \`before\`/\`after\` to narrow by date.
|
|
32882
32882
|
|
|
32883
|
-
**If search results look irrelevant, do not give up.** Search only covers content that has been indexed
|
|
32883
|
+
**If search results look irrelevant, do not give up.** Search only covers content that has been indexed \u2014 a short or recent conversation may exist in raw message history before any observation of it was created. When search returns nothing suitable but the user is clearly referring to a past conversation, call \`mode: "threads"\` to find candidate threads (titles and dates are strong clues), then read them with \`mode: "messages"\`. Use a useful hit as an entry point to the surrounding history rather than treating it as the whole answer.` : `### Choosing a mode
|
|
32884
32884
|
The recall tool works across ALL of this user's conversation threads, not just the current one.
|
|
32885
32885
|
|
|
32886
32886
|
- Use \`mode: "threads"\` to list the user's threads (IDs, titles, dates) when you need to discover where something was discussed. Use \`before\`/\`after\` to narrow by date.
|
|
32887
|
-
- Use \`mode: "messages"\` when you know the thread
|
|
32887
|
+
- Use \`mode: "messages"\` when you know the thread \u2014 pass \`threadId\` to read another thread, or a \`cursor\` from an observation-group range.
|
|
32888
32888
|
|
|
32889
32889
|
When the user refers to a past conversation you don't have a cursor for, call \`mode: "threads"\` to find candidate threads (titles and dates are strong clues), then read them with \`mode: "messages"\`. Raw history may exist for threads that have no observations yet.` : `### Choosing a mode
|
|
32890
32890
|
The recall tool is limited to the current conversation thread.
|
|
@@ -32909,7 +32909,7 @@ When searches keep returning the same groups, often as already-in-context refere
|
|
|
32909
32909
|
"Excerpt already in current context" marks a hit whose text an earlier search result already shows. "Group already in current context" marks a group that is already in your observations or whose source messages are still in the conversation. "Source range overlaps current context" marks a group whose source messages are still in the conversation. Search keeps these references and tries lower-ranked matches to fill the requested number of excerpts. This backfill is bounded: fewer excerpts do not mean history is exhausted. Use the evidence already present rather than repeating the same lookup. You can still ${pagingEnabled ? "page a referenced group" : "read a referenced group's source messages"} when you need all of it, or search again if that context is no longer available.
|
|
32910
32910
|
|
|
32911
32911
|
If search still finds nothing useful, browse raw messages${isResource ? " or discover other threads" : " in this thread"} before concluding the information is unavailable. Raw history may exist for threads that have no observations yet.` : "";
|
|
32912
|
-
const base = `## Recall
|
|
32912
|
+
const base = `## Recall \u2014 looking up source messages
|
|
32913
32913
|
|
|
32914
32914
|
Your memory contains observation groups with IDs and source message ranges, shown as \`## Group\` headings with \`_range: startId:endId\` or as \`<observation-group>\` tags. Use the **recall** tool to recover retained original observations and source messages.
|
|
32915
32915
|
|
|
@@ -32920,13 +32920,13 @@ Groups marked \`kind="reflection"\` (rendered as \`_kind: reflection_\`) are los
|
|
|
32920
32920
|
|
|
32921
32921
|
### When to use recall
|
|
32922
32922
|
- The user asks you to **repeat, show, or reproduce** something from a past conversation
|
|
32923
|
-
- The user asks for **exact content**
|
|
32923
|
+
- The user asks for **exact content** \u2014 code, text, quotes, error messages, URLs, file paths, specific numbers
|
|
32924
32924
|
- Your observations mention something but your memory lacks the detail needed to fully answer (e.g. you know a blog post was shared but only have a summary of it)
|
|
32925
32925
|
- You want to **verify or expand on** an observation before responding
|
|
32926
32926
|
- The answer depends on historical dates, order, or duration: verify both event dates and that they refer to the events the user means. Distinguish a plan, an actual start, a later update, and a repeated mention instead of choosing a nearby date from a summary
|
|
32927
32927
|
- An observation records something the assistant proposed, such as a schedule, date, or plan, and your observations don't show what the user decided. Read the raw messages around it to find the user's decision before treating the proposal as what happened
|
|
32928
32928
|
- Relevant details are missing, ambiguous, or conflicting in the current observations${isResource ? `
|
|
32929
|
-
- The user references another conversation that your observations don't cover
|
|
32929
|
+
- The user references another conversation that your observations don't cover \u2014 even if you have no observations yet, their other threads may contain it` : ""}
|
|
32930
32930
|
|
|
32931
32931
|
**Default to using recall when the user references specific past content.** Your observations capture the gist, not the details. If there's any doubt whether your memory is complete enough, use recall.
|
|
32932
32932
|
|
|
@@ -32961,17 +32961,17 @@ Each range has the format \`startId:endId\` where both are message IDs separated
|
|
|
32961
32961
|
In \`mode: "messages"\`, recall returns **low** detail by default: truncated text and tool names only. Each message shows its ID and each part has a positional index like \`[p0]\`, \`[p1]\`, etc.
|
|
32962
32962
|
|
|
32963
32963
|
- Use \`detail: "high"\` to get full message content including tool arguments and results. This will only return the high detail version of a single message part at a time.
|
|
32964
|
-
- Use \`partIndex\` with a cursor to fetch a single part at full detail
|
|
32964
|
+
- Use \`partIndex\` with a cursor to fetch a single part at full detail \u2014 for example, to read one specific tool result or code block without loading every part.
|
|
32965
32965
|
|
|
32966
32966
|
If the result says \`truncated: true\`, the output was cut to fit the token budget. You can paginate or use \`partIndex\` to target specific content. If a single part is itself too large, follow the returned \`nextCharOffset\` as described below.
|
|
32967
32967
|
|
|
32968
32968
|
### Following up on truncated parts
|
|
32969
32969
|
Low-detail results may include truncation hints like:
|
|
32970
|
-
\`[truncated
|
|
32970
|
+
\`[truncated \u2014 call recall cursor="..." partIndex=N detail="high" for full content]\`
|
|
32971
32971
|
|
|
32972
32972
|
**When you see these hints and need the full content, make the exact call described in the hint.** This is the normal workflow: first recall at low detail to scan, then drill into specific parts at high detail. Do not stop at the low-detail result if the user asked for exact content.
|
|
32973
32973
|
|
|
32974
|
-
If a single part is larger than the token budget, the \`partIndex\` result is \`truncated: true\` and includes \`nextCharOffset\`. Repeat the same call with \`charOffset\` set to that exact value to read the next chunk from where the previous one ended. Keep following \`nextCharOffset\` until the result no longer includes it
|
|
32974
|
+
If a single part is larger than the token budget, the \`partIndex\` result is \`truncated: true\` and includes \`nextCharOffset\`. Repeat the same call with \`charOffset\` set to that exact value to read the next chunk from where the previous one ended. Keep following \`nextCharOffset\` until the result no longer includes it \u2014 the chunks together contain the full part. Retrying without \`charOffset\` returns the same prefix again.
|
|
32975
32975
|
|
|
32976
32976
|
### When recall is NOT needed
|
|
32977
32977
|
- The user is asking for a high-level summary and your observations already cover it
|
|
@@ -33366,6 +33366,15 @@ function buildThreadMetadataFromExtractedValues(extractors, values) {
|
|
|
33366
33366
|
async function applyExtractorHooks(opts) {
|
|
33367
33367
|
const values = normalizeExtractedValues(opts.values) ?? {};
|
|
33368
33368
|
const failures = [...opts.failures ?? []];
|
|
33369
|
+
let recentMessages;
|
|
33370
|
+
let recentMessagesResolved = false;
|
|
33371
|
+
const resolveRecentMessages = () => {
|
|
33372
|
+
if (!recentMessagesResolved) {
|
|
33373
|
+
recentMessages = typeof opts.recentMessages === "function" ? opts.recentMessages() : opts.recentMessages;
|
|
33374
|
+
recentMessagesResolved = true;
|
|
33375
|
+
}
|
|
33376
|
+
return recentMessages;
|
|
33377
|
+
};
|
|
33369
33378
|
for (const extractor of opts.extractors) {
|
|
33370
33379
|
const isHook = extractor.mode === "hook";
|
|
33371
33380
|
const hasValue = Object.prototype.hasOwnProperty.call(values, extractor.slug);
|
|
@@ -33385,7 +33394,9 @@ async function applyExtractorHooks(opts) {
|
|
|
33385
33394
|
previous: isHook ? void 0 : opts.previousValues?.[extractor.slug],
|
|
33386
33395
|
current,
|
|
33387
33396
|
rawObservations: opts.rawObservations,
|
|
33388
|
-
recentMessages
|
|
33397
|
+
get recentMessages() {
|
|
33398
|
+
return resolveRecentMessages();
|
|
33399
|
+
},
|
|
33389
33400
|
mainAgent: opts.mainAgent,
|
|
33390
33401
|
memory: opts.memory,
|
|
33391
33402
|
sendSignal: opts.sendSignal,
|
|
@@ -34089,7 +34100,7 @@ const YEAR = String.raw`(?:19|20|21)\d{2}(?!\d)`;
|
|
|
34089
34100
|
const MERIDIEM = String.raw`(?:[AaPp]\.[Mm]\.|[AaPp][Mm]\b)`;
|
|
34090
34101
|
const TIME = String.raw`(?:,?\s+(?:at\s+)?\d{1,2}:\d{2}(?:\s*${MERIDIEM})?|\s+at\s+\d{1,2}\s*${MERIDIEM})`;
|
|
34091
34102
|
const QUALIFIER = String.raw`(?:(?:early|mid|late)[- ](?:to[- ](?:early|mid|late)[- ])?)`;
|
|
34092
|
-
const RANGE_SEP = String.raw`(?:\s*[
|
|
34103
|
+
const RANGE_SEP = String.raw`(?:\s*[\u2013\u2014]\s*|\s*-\s*|\s+(?:to|through|until)\s+)`;
|
|
34093
34104
|
/**
|
|
34094
34105
|
* Dates written into observation text that carry their own year, longest forms first:
|
|
34095
34106
|
* "Mar 1 - Mar 18, 2025", "May 27-28, 2023", "January 10, 2024 at 3:00 PM",
|
|
@@ -34390,15 +34401,15 @@ const SHORT_TOKEN_THRESHOLD = 3;
|
|
|
34390
34401
|
const KANA_CHARS_PER_TOKEN = 1.35;
|
|
34391
34402
|
const DEFAULT_LANGUAGE_CONFIGS = [
|
|
34392
34403
|
{
|
|
34393
|
-
pattern: /[
|
|
34404
|
+
pattern: /[\u00E4\u00F6\u00FC\u00DF\u1E9E]/i,
|
|
34394
34405
|
averageCharsPerToken: 2.6
|
|
34395
34406
|
},
|
|
34396
34407
|
{
|
|
34397
|
-
pattern: /[
|
|
34408
|
+
pattern: /[\u00E9\u00E8\u00EA\u00EB\u00E0\u00E2\u00EE\u00EF\u00F4\u00FB\u00F9\u00FC\u00FF\u00E7\u0153\u00E6\u00E1\u00ED\u00F3\u00FA\u00F1]/i,
|
|
34398
34409
|
averageCharsPerToken: 3
|
|
34399
34410
|
},
|
|
34400
34411
|
{
|
|
34401
|
-
pattern: /[
|
|
34412
|
+
pattern: /[\u0105\u0107\u0119\u0142\u0144\u00F3\u015B\u017A\u017C\u011B\u0161\u010D\u0159\u017E\u00FD\u016F\u00FA\u010F\u0165\u0148]/i,
|
|
34402
34413
|
averageCharsPerToken: 2.5
|
|
34403
34414
|
},
|
|
34404
34415
|
{
|
|
@@ -34486,10 +34497,10 @@ function sanitizeSurrogates(value) {
|
|
|
34486
34497
|
if (next >= 56320 && next <= 57343) {
|
|
34487
34498
|
sanitized += value.charAt(index) + value.charAt(index + 1);
|
|
34488
34499
|
index++;
|
|
34489
|
-
} else sanitized += "
|
|
34500
|
+
} else sanitized += "\uFFFD";
|
|
34490
34501
|
continue;
|
|
34491
34502
|
}
|
|
34492
|
-
sanitized += code >= 56320 && code <= 57343 ? "
|
|
34503
|
+
sanitized += code >= 56320 && code <= 57343 ? "\uFFFD" : value[index];
|
|
34493
34504
|
}
|
|
34494
34505
|
return sanitized;
|
|
34495
34506
|
}
|
|
@@ -34511,7 +34522,7 @@ function truncatePath(path) {
|
|
|
34511
34522
|
const headLength = 50;
|
|
34512
34523
|
const tailLength = 60;
|
|
34513
34524
|
const omitted = path.length - headLength - tailLength;
|
|
34514
|
-
return `${safeSlice(path, headLength)}
|
|
34525
|
+
return `${safeSlice(path, headLength)}\u2026[${omitted} chars; ${stablePathDigest(path)}]\u2026${safeTail(path, tailLength)}`;
|
|
34515
34526
|
}
|
|
34516
34527
|
function formatPath(parent, key, isArray) {
|
|
34517
34528
|
if (isArray) return truncatePath(`${parent}[${key}]`);
|
|
@@ -34620,7 +34631,7 @@ function selectOutlineEntries(entries, limits) {
|
|
|
34620
34631
|
const rendered = joinEntries(selected, marker);
|
|
34621
34632
|
if (fits(rendered, limits)) return rendered;
|
|
34622
34633
|
if (fits(marker, limits)) return marker;
|
|
34623
|
-
return fits("
|
|
34634
|
+
return fits("\u2026", limits) ? "\u2026" : "";
|
|
34624
34635
|
}
|
|
34625
34636
|
function indentPreview(value) {
|
|
34626
34637
|
return value.split("\n").map((line) => ` | ${line}`).join("\n");
|
|
@@ -34663,13 +34674,13 @@ function formatToolArgumentsForObserver(value, options) {
|
|
|
34663
34674
|
if (!isObjectLike$1(value)) {
|
|
34664
34675
|
if (typeof value !== "string" || value.length <= OBSERVER_TOOL_ARGUMENT_INLINE_STRING_MAX_CHARS) {
|
|
34665
34676
|
const primitive = formatPrimitive(value);
|
|
34666
|
-
return fits(primitive, limits) ? primitive : fits("
|
|
34677
|
+
return fits(primitive, limits) ? primitive : fits("\u2026", limits) ? "\u2026" : "";
|
|
34667
34678
|
}
|
|
34668
34679
|
const summary = `<string, ${value.length} characters; preview size-limited>`;
|
|
34669
34680
|
const rendered = appendWithinBudget(summary, formatPreview("preview", value, limits, summary), limits);
|
|
34670
34681
|
if (rendered) return rendered;
|
|
34671
34682
|
if (fits(summary, limits)) return summary;
|
|
34672
|
-
return fits("
|
|
34683
|
+
return fits("\u2026", limits) ? "\u2026" : "";
|
|
34673
34684
|
}
|
|
34674
34685
|
const outline = [];
|
|
34675
34686
|
const previews = [];
|
|
@@ -34913,24 +34924,24 @@ function formatToolResultForObserver(value, options) {
|
|
|
34913
34924
|
const OBSERVER_EXTRACTION_INSTRUCTIONS = `CRITICAL: DISTINGUISH USER ASSERTIONS FROM QUESTIONS
|
|
34914
34925
|
|
|
34915
34926
|
When the user TELLS you something about themselves, mark it as an assertion:
|
|
34916
|
-
- "I have two kids"
|
|
34917
|
-
- "I work at Acme Corp"
|
|
34918
|
-
- "I graduated in 2019"
|
|
34927
|
+
- "I have two kids" \u2192 \u{1F534} (14:30) User stated has two kids
|
|
34928
|
+
- "I work at Acme Corp" \u2192 \u{1F534} (14:31) User stated works at Acme Corp
|
|
34929
|
+
- "I graduated in 2019" \u2192 \u{1F534} (14:32) User stated graduated in 2019
|
|
34919
34930
|
|
|
34920
34931
|
When the user ASKS about something, mark it as a question/request:
|
|
34921
|
-
- "Can you help me with X?"
|
|
34922
|
-
- "What's the best way to do Y?"
|
|
34932
|
+
- "Can you help me with X?" \u2192 \u{1F534} (15:00) User asked help with X
|
|
34933
|
+
- "What's the best way to do Y?" \u2192 \u{1F534} (15:01) User asked best way to do Y
|
|
34923
34934
|
|
|
34924
34935
|
Distinguish between QUESTIONS and STATEMENTS OF INTENT:
|
|
34925
|
-
- "Can you recommend..."
|
|
34926
|
-
- "I'm looking forward to [doing X]"
|
|
34927
|
-
- "I need to [do X]"
|
|
34936
|
+
- "Can you recommend..." \u2192 Question (extract as "User asked...")
|
|
34937
|
+
- "I'm looking forward to [doing X]" \u2192 Statement of intent (extract as "User stated they will [do X] (include estimated/actual date if mentioned)")
|
|
34938
|
+
- "I need to [do X]" \u2192 Statement of intent (extract as "User stated they need to [do X] (again, add date if mentioned)")
|
|
34928
34939
|
|
|
34929
34940
|
STATE CHANGES AND UPDATES:
|
|
34930
34941
|
When a user indicates they are changing something, frame it as a state change that supersedes previous information:
|
|
34931
|
-
- "I'm going to start doing X instead of Y"
|
|
34932
|
-
- "I'm switching from A to B"
|
|
34933
|
-
- "I moved my stuff to the new place"
|
|
34942
|
+
- "I'm going to start doing X instead of Y" \u2192 "User will start doing X (changing from Y)"
|
|
34943
|
+
- "I'm switching from A to B" \u2192 "User is switching from A to B"
|
|
34944
|
+
- "I moved my stuff to the new place" \u2192 "User moved their stuff to the new place (no longer at previous location)"
|
|
34934
34945
|
|
|
34935
34946
|
If the new state contradicts or updates previous information, make that explicit:
|
|
34936
34947
|
- BAD: "User plans to use the new method"
|
|
@@ -35021,11 +35032,11 @@ BAD: User got something.
|
|
|
35021
35032
|
GOOD: User purchased / received / was given something. (be specific)
|
|
35022
35033
|
|
|
35023
35034
|
Common clarifications:
|
|
35024
|
-
- "getting" something regularly
|
|
35025
|
-
- "getting" something once
|
|
35026
|
-
- "got"
|
|
35027
|
-
- "signed up"
|
|
35028
|
-
- "stopped getting"
|
|
35035
|
+
- "getting" something regularly \u2192 "subscribed to" or "enrolled in"
|
|
35036
|
+
- "getting" something once \u2192 "purchased" or "acquired"
|
|
35037
|
+
- "got" \u2192 "purchased", "received as gift", "was given", "picked up"
|
|
35038
|
+
- "signed up" \u2192 "enrolled in", "registered for", "subscribed to"
|
|
35039
|
+
- "stopped getting" \u2192 "canceled", "unsubscribed from", "discontinued"
|
|
35029
35040
|
|
|
35030
35041
|
When the assistant interprets or confirms the user's vague language, prefer the assistant's precise terminology.
|
|
35031
35042
|
|
|
@@ -35110,16 +35121,16 @@ AVOIDING REPETITIVE OBSERVATIONS:
|
|
|
35110
35121
|
- Do NOT repeat the same observation across multiple turns if there is no new information.
|
|
35111
35122
|
- When the agent performs repeated similar actions (e.g., browsing files, running the same tool type multiple times), group them into a single parent observation with sub-bullets for each new result.
|
|
35112
35123
|
|
|
35113
|
-
Example
|
|
35114
|
-
*
|
|
35115
|
-
*
|
|
35116
|
-
*
|
|
35124
|
+
Example \u2014 BAD (repetitive):
|
|
35125
|
+
* \u{1F7E1} (14:30) Agent used view tool on src/auth.ts
|
|
35126
|
+
* \u{1F7E1} (14:31) Agent used view tool on src/users.ts
|
|
35127
|
+
* \u{1F7E1} (14:32) Agent used view tool on src/routes.ts
|
|
35117
35128
|
|
|
35118
|
-
Example
|
|
35119
|
-
*
|
|
35120
|
-
* -> viewed src/auth.ts
|
|
35121
|
-
* -> viewed src/users.ts
|
|
35122
|
-
* -> viewed src/routes.ts
|
|
35129
|
+
Example \u2014 GOOD (grouped):
|
|
35130
|
+
* \u{1F7E1} (14:30) Agent browsed source files for auth flow
|
|
35131
|
+
* -> viewed src/auth.ts \u2014 found token validation logic
|
|
35132
|
+
* -> viewed src/users.ts \u2014 found user lookup by email
|
|
35133
|
+
* -> viewed src/routes.ts \u2014 found middleware chain
|
|
35123
35134
|
|
|
35124
35135
|
Only add a new observation for a repeated action if the NEW result changes the picture.
|
|
35125
35136
|
|
|
@@ -35132,29 +35143,29 @@ COMPLETION TRACKING:
|
|
|
35132
35143
|
Completion observations are not just summaries. They are explicit memory signals to the assistant that a task, question, or subtask has been resolved.
|
|
35133
35144
|
Without clear completion markers, the assistant may forget that work is already finished and may repeat, reopen, or continue an already-completed task.
|
|
35134
35145
|
|
|
35135
|
-
Use
|
|
35146
|
+
Use \u2705 to answer: "What exactly is now done?"
|
|
35136
35147
|
Choose completion observations that help the assistant know what is finished and should not be reworked unless new information appears.
|
|
35137
35148
|
|
|
35138
|
-
Use
|
|
35149
|
+
Use \u2705 when:
|
|
35139
35150
|
- The user explicitly confirms something worked or was answered ("thanks, that fixed it", "got it", "perfect")
|
|
35140
35151
|
- The assistant provided a definitive, complete answer to a factual question and the user moved on
|
|
35141
35152
|
- A multi-step task reached its stated goal
|
|
35142
35153
|
- The user acknowledged receipt of requested information
|
|
35143
35154
|
- A concrete subtask, fix, deliverable, or implementation step became complete during ongoing work
|
|
35144
35155
|
|
|
35145
|
-
Do NOT use
|
|
35146
|
-
- The assistant merely responded
|
|
35156
|
+
Do NOT use \u2705 when:
|
|
35157
|
+
- The assistant merely responded \u2014 the user might follow up with corrections
|
|
35147
35158
|
- The topic is paused but not resolved ("I'll try that later")
|
|
35148
35159
|
- The user's reaction is ambiguous
|
|
35149
35160
|
|
|
35150
35161
|
FORMAT:
|
|
35151
35162
|
As a sub-bullet under the related observation group:
|
|
35152
|
-
*
|
|
35163
|
+
* \u{1F534} (14:30) User asked how to configure auth middleware
|
|
35153
35164
|
* -> Agent explained JWT setup with code example
|
|
35154
|
-
*
|
|
35165
|
+
* \u2705 User confirmed auth is working
|
|
35155
35166
|
|
|
35156
35167
|
Or as a standalone observation when closing out a broader task:
|
|
35157
|
-
*
|
|
35168
|
+
* \u2705 (14:45) Auth configuration task completed \u2014 user confirmed middleware is working
|
|
35158
35169
|
|
|
35159
35170
|
Completion observations should be terse but specific about WHAT was completed.
|
|
35160
35171
|
Prefer concrete resolved outcomes over abstract workflow status so the assistant remembers what is already done.`;
|
|
@@ -35171,28 +35182,28 @@ buildObserverOutputFormat();
|
|
|
35171
35182
|
*/
|
|
35172
35183
|
function buildObserverOutputFormat(extractors) {
|
|
35173
35184
|
return `Use priority levels:
|
|
35174
|
-
-
|
|
35175
|
-
-
|
|
35176
|
-
-
|
|
35177
|
-
-
|
|
35185
|
+
- \u{1F534} High: explicit user facts, preferences, unresolved goals, critical context
|
|
35186
|
+
- \u{1F7E1} Medium: project details, learned information, tool results
|
|
35187
|
+
- \u{1F7E2} Low: minor details, uncertain observations
|
|
35188
|
+
- \u2705 Completed: concrete task finished, question answered, issue resolved, goal achieved, or subtask completed in a way that helps the assistant know it is done
|
|
35178
35189
|
|
|
35179
35190
|
Group related observations (like tool sequences) by indenting:
|
|
35180
|
-
*
|
|
35191
|
+
* \u{1F534} (14:33) Agent debugging auth issue
|
|
35181
35192
|
* -> ran git status, found 3 modified files
|
|
35182
35193
|
* -> viewed auth.ts:45-60, found missing null check
|
|
35183
35194
|
* -> applied fix, tests now pass
|
|
35184
|
-
*
|
|
35195
|
+
* \u2705 Tests passing, auth issue resolved
|
|
35185
35196
|
|
|
35186
35197
|
Group observations by date. Within a date, list observations in the order the events happened (not by importance), each with 24-hour time.
|
|
35187
35198
|
|
|
35188
35199
|
<observations>
|
|
35189
35200
|
Date: Dec 4, 2025
|
|
35190
|
-
*
|
|
35191
|
-
*
|
|
35192
|
-
*
|
|
35201
|
+
* \u{1F534} (14:30) User prefers direct answers
|
|
35202
|
+
* \u{1F534} (14:31) Working on feature X
|
|
35203
|
+
* \u{1F7E1} (14:32) User might prefer dark mode
|
|
35193
35204
|
|
|
35194
35205
|
Date: Dec 5, 2025
|
|
35195
|
-
*
|
|
35206
|
+
* \u{1F534} (09:15) Continued work on feature X
|
|
35196
35207
|
</observations>
|
|
35197
35208
|
|
|
35198
35209
|
${buildExtractorOutputSections(extractors ?? []) || (extractors === void 0 ? `
|
|
@@ -35222,9 +35233,9 @@ const OBSERVER_GUIDELINES = `- Be specific enough for the assistant to act on
|
|
|
35222
35233
|
- If the agent calls tools, observe what was called, why, and what was learned
|
|
35223
35234
|
- When observing files with line numbers, include the line number if useful
|
|
35224
35235
|
- If the agent provides a detailed response, observe the contents so it could be repeated
|
|
35225
|
-
- Make sure you start each observation with a priority emoji (
|
|
35226
|
-
- Capture the user's words closely
|
|
35227
|
-
- Treat
|
|
35236
|
+
- Make sure you start each observation with a priority emoji (\u{1F534}, \u{1F7E1}, \u{1F7E2}) or a completion marker (\u2705)
|
|
35237
|
+
- Capture the user's words closely \u2014 short/medium messages near-verbatim, long messages summarized with key quotes. User confirmations or explicit resolved outcomes should be \u2705 when they clearly signal something is done; unresolved or critical user facts remain \u{1F534}
|
|
35238
|
+
- Treat \u2705 as a memory signal that tells the assistant something is finished and should not be repeated unless new information changes it
|
|
35228
35239
|
- Make completion observations answer "What exactly is now done?"
|
|
35229
35240
|
- Prefer concrete resolved outcomes over meta-level workflow or bookkeeping updates
|
|
35230
35241
|
- When multiple concrete things were completed, capture the concrete completed work rather than collapsing it into a vague progress summary
|
|
@@ -35278,8 +35289,8 @@ For multi-thread output, wrap each thread's observations like this:
|
|
|
35278
35289
|
<observations>
|
|
35279
35290
|
<thread id="thread_id_1">
|
|
35280
35291
|
Date: Dec 4, 2025
|
|
35281
|
-
*
|
|
35282
|
-
*
|
|
35292
|
+
* \u{1F534} (14:30) User prefers direct answers
|
|
35293
|
+
* \u{1F534} (14:31) Working on feature X${currentTaskEnabled ? `
|
|
35283
35294
|
|
|
35284
35295
|
<current-task>
|
|
35285
35296
|
What the agent is currently working on in this thread
|
|
@@ -35292,7 +35303,7 @@ Hint for the agent's next message in this thread
|
|
|
35292
35303
|
|
|
35293
35304
|
<thread id="thread_id_2">
|
|
35294
35305
|
Date: Dec 5, 2025
|
|
35295
|
-
*
|
|
35306
|
+
* \u{1F534} (09:15) User asked about deployment${currentTaskEnabled ? `
|
|
35296
35307
|
|
|
35297
35308
|
<current-task>
|
|
35298
35309
|
Current task for this thread
|
|
@@ -36123,7 +36134,7 @@ function sanitizeObservationLines(observations) {
|
|
|
36123
36134
|
const lines = observations.split("\n");
|
|
36124
36135
|
let changed = false;
|
|
36125
36136
|
for (let i = 0; i < lines.length; i++) if (lines[i].length > MAX_OBSERVATION_LINE_CHARS) {
|
|
36126
|
-
lines[i] = safeSlice(lines[i], MAX_OBSERVATION_LINE_CHARS) + "
|
|
36137
|
+
lines[i] = safeSlice(lines[i], MAX_OBSERVATION_LINE_CHARS) + " \u2026 [truncated]";
|
|
36127
36138
|
changed = true;
|
|
36128
36139
|
}
|
|
36129
36140
|
return changed ? lines.join("\n") : observations;
|
|
@@ -36321,8 +36332,8 @@ function describeDegenerateOutput(text, snippetChars = 400) {
|
|
|
36321
36332
|
*/
|
|
36322
36333
|
function optimizeObservationsForContext(observations) {
|
|
36323
36334
|
let optimized = stripEphemeralAnchorIds(observations);
|
|
36324
|
-
optimized = optimized.replace(
|
|
36325
|
-
optimized = optimized.replace(
|
|
36335
|
+
optimized = optimized.replace(/\uD83D\uDFE1\s*/g, "");
|
|
36336
|
+
optimized = optimized.replace(/\uD83D\uDFE2\s*/g, "");
|
|
36326
36337
|
optimized = optimized.replace(/\s*->\s*/g, " ");
|
|
36327
36338
|
optimized = optimized.replace(/ +/g, " ");
|
|
36328
36339
|
optimized = optimized.replace(/\n{3,}/g, "\n\n");
|
|
@@ -37278,7 +37289,7 @@ async function resolveImageDimensionsAsync(part) {
|
|
|
37278
37289
|
const url = resolveHttpAssetUrl(getObjectValue(part, "image") ?? getObjectValue(part, "data"));
|
|
37279
37290
|
if (!url) return existing;
|
|
37280
37291
|
try {
|
|
37281
|
-
const probeImageSize = (await Promise.resolve().then(() => /* @__PURE__ */ require_rolldown_runtime.__toESM(require("./probe-image-size-
|
|
37292
|
+
const probeImageSize = (await Promise.resolve().then(() => /* @__PURE__ */ require_rolldown_runtime.__toESM(require("./probe-image-size-z8zXmjaH.cjs").default, 1))).default;
|
|
37282
37293
|
const probed = await probeImageSize(url, {
|
|
37283
37294
|
open_timeout: REMOTE_IMAGE_PROBE_TIMEOUT_MS,
|
|
37284
37295
|
response_timeout: REMOTE_IMAGE_PROBE_TIMEOUT_MS,
|
|
@@ -38600,8 +38611,8 @@ const updateWorkingMemoryTool = (memoryConfig) => {
|
|
|
38600
38611
|
}
|
|
38601
38612
|
const usesMergeSemantics = Boolean(schema);
|
|
38602
38613
|
const useStateSignals = memoryConfig?.workingMemory?.useStateSignals === true;
|
|
38603
|
-
const stateSignalsPreamble = `The current working memory state is delivered to you each turn by the system inside a <working-memory>...</working-memory> block. That block is system-emitted state, NOT something the user typed
|
|
38604
|
-
const description = schema ? useStateSignals ? `${stateSignalsPreamble} Data is merged with existing memory
|
|
38614
|
+
const stateSignalsPreamble = `The current working memory state is delivered to you each turn by the system inside a <working-memory>...</working-memory> block. That block is system-emitted state, NOT something the user typed \u2014 never describe it as the user sharing it. Read from it directly when answering. Only call this tool when the user provides genuinely NEW or CHANGED facts that should be persisted; do NOT call it to re-save unchanged data.`;
|
|
38615
|
+
const description = schema ? useStateSignals ? `${stateSignalsPreamble} Data is merged with existing memory \u2014 only include fields you want to add or update.` : `Update the working memory with new information. Data is merged with existing memory - only include fields you want to add or update. To preserve existing data, omit the field entirely. Arrays are replaced entirely when provided, so pass the complete array or omit it to keep the existing values.` : useStateSignals ? `${stateSignalsPreamble} Pass the full updated Markdown blob as a string in the memory field.` : `Update the working memory with new information. Any data not included will be overwritten. Always pass data as string to the memory field. Never pass an object.`;
|
|
38605
38616
|
return (0, _mastra_core_tools.createTool)({
|
|
38606
38617
|
id: "update-working-memory",
|
|
38607
38618
|
description,
|
|
@@ -39611,8 +39622,8 @@ async function pageGroups({ om, threadId, resourceId, groupId, recordId, directi
|
|
|
39611
39622
|
})).count > 0;
|
|
39612
39623
|
const hasLater = direction === "before" || hasMore;
|
|
39613
39624
|
const newer = hasLater ? null : await newerMessagesNote(page.at(-1).group, countNewerMessages, pagingThreadId);
|
|
39614
|
-
text.unshift(hasEarlier ?
|
|
39615
|
-
text.push(hasLater ?
|
|
39625
|
+
text.unshift(hasEarlier ? `\u2014 Browse earlier: ${pagingCall(page[0].group.id, "before", pagingThreadId, page[0].record.id)} \u2014` : "\u2014 Start of retained observation history for this thread. \u2014");
|
|
39626
|
+
text.push(hasLater ? `\u2014 Browse later: ${pagingCall(page.at(-1).group.id, "after", pagingThreadId, page.at(-1).record.id)} \u2014` : newer ? `\u2014 End of observation history for this thread. ${newer} \u2014` : "\u2014 End of retained observation history for this thread. \u2014");
|
|
39616
39627
|
text.unshift(`### Observation page\nThread: ${threadTitle || "(untitled)"}\nShowing ${page.length} groups ${requestedDirection === void 0 ? "starting at" : `strictly ${direction}`} \`${groupId}\` (oldest first).`);
|
|
39617
39628
|
return {
|
|
39618
39629
|
results: text.join("\n\n"),
|
|
@@ -39798,7 +39809,7 @@ async function listThreadsForResource({ memory, resourceId, currentThreadId, pag
|
|
|
39798
39809
|
const title = thread.title || "(untitled)";
|
|
39799
39810
|
const updated = formatTimestamp(thread.updatedAt);
|
|
39800
39811
|
const created = formatTimestamp(thread.createdAt);
|
|
39801
|
-
const marker = isCurrent ? "
|
|
39812
|
+
const marker = isCurrent ? " \u2190 current" : "";
|
|
39802
39813
|
lines.push(`- **${title}**${marker}`);
|
|
39803
39814
|
lines.push(` id: ${thread.id}`);
|
|
39804
39815
|
lines.push(` updated: ${updated} | created: ${created}`);
|
|
@@ -39977,7 +39988,7 @@ async function searchMessagesForResource({ memory, om, resourceId, currentThread
|
|
|
39977
39988
|
const groupLine = match.groupId ? `- observation group: ${groupCursor(match.groupId, match.recordId)}` : void 0;
|
|
39978
39989
|
const scoreLine = `- score: ${match.score.toFixed(2)}`;
|
|
39979
39990
|
const prev = i > 0 ? ordered[i - 1].match : void 0;
|
|
39980
|
-
if (om && prev?.groupId && match.groupId && prev.threadId === match.threadId) sections.push(
|
|
39991
|
+
if (om && prev?.groupId && match.groupId && prev.threadId === match.threadId) sections.push(`\u2014 Observation groups may be hidden between these results; continue with ${pagingCall(prev.groupId, "after", includeThreadId ? prev.threadId : void 0, prev.recordId)} \u2014`);
|
|
39981
39992
|
if (suppression) {
|
|
39982
39993
|
sections.push(`${groupLine}\n thread: ${match.threadId}; ${suppression}`);
|
|
39983
39994
|
continue;
|
|
@@ -40532,7 +40543,7 @@ async function recallAttachmentView({ memory, threadId, resourceId, cursor, part
|
|
|
40532
40543
|
const partType = rawPart?.type;
|
|
40533
40544
|
if (!rawPart || partType !== "image" && partType !== "file") return { messages: `Part ${partIndex} of message ${cursor} is ${rawPart ? `a ${partType ?? "unknown"}-type part` : "missing"}, not an attachment. Call recall with the same cursor and partIndex without viewAttachment to read it.` };
|
|
40534
40545
|
const resolvedAttachment = resolveViewableAttachment(rawPart);
|
|
40535
|
-
if ("note" in resolvedAttachment) return { messages: `${formatAttachmentPart(partType, rawPart)}
|
|
40546
|
+
if ("note" in resolvedAttachment) return { messages: `${formatAttachmentPart(partType, rawPart)} \u2014 ${resolvedAttachment.note}` };
|
|
40536
40547
|
return { content: [{
|
|
40537
40548
|
type: "text",
|
|
40538
40549
|
text: formatAttachmentPart(partType, rawPart)
|
|
@@ -40935,7 +40946,7 @@ const recallTool = (_memoryConfig, options) => {
|
|
|
40935
40946
|
if (!thread) return { error: "Could not resolve current thread." };
|
|
40936
40947
|
if (isResourceScope && resourceId && thread.resourceId !== resourceId) throw new Error("Thread does not belong to the active resource");
|
|
40937
40948
|
return {
|
|
40938
|
-
threads: `- **${thread.title || "(untitled)"}**
|
|
40949
|
+
threads: `- **${thread.title || "(untitled)"}** \u2190 current\n id: ${thread.id}\n updated: ${formatTimestamp(thread.updatedAt)} | created: ${formatTimestamp(thread.createdAt)}`,
|
|
40939
40950
|
count: 1,
|
|
40940
40951
|
page: 0,
|
|
40941
40952
|
hasMore: false
|
|
@@ -41686,9 +41697,9 @@ const suggestedResponseInstructions = `Hint for the agent's immediate next messa
|
|
|
41686
41697
|
- "The assistant should wait for the user to respond before continuing."
|
|
41687
41698
|
- Call the view tool on src/example.ts to continue debugging.`;
|
|
41688
41699
|
const threadTitleInstructions = `A short, noun-phrase title for this conversation (2-5 words). Examples:
|
|
41689
|
-
- "Auth bug fix"
|
|
41690
|
-
- "Dark mode toggle"
|
|
41691
|
-
- "Deployment pipeline setup"
|
|
41700
|
+
- "Auth bug fix" \u2014 not "Fixing the auth bug"
|
|
41701
|
+
- "Dark mode toggle" \u2014 not "User wants dark mode toggle added"
|
|
41702
|
+
- "Deployment pipeline setup" \u2014 not "Setting up deployment pipeline for project"
|
|
41692
41703
|
Only update when the topic meaningfully changes.`;
|
|
41693
41704
|
function createCurrentTaskExtractor() {
|
|
41694
41705
|
return new Extractor({
|
|
@@ -42758,7 +42769,7 @@ var SyncObservationStrategy = class extends ObservationStrategy {
|
|
|
42758
42769
|
failures: result.extractionFailures,
|
|
42759
42770
|
previousValues: this.priorExtractedValues,
|
|
42760
42771
|
rawObservations: result.observations,
|
|
42761
|
-
recentMessages: formatMessagesForObserver(this.opts.messages, {
|
|
42772
|
+
recentMessages: () => formatMessagesForObserver(this.opts.messages, {
|
|
42762
42773
|
maxPartLength: 500,
|
|
42763
42774
|
timeZone: this.opts.record.observedTimezone
|
|
42764
42775
|
}),
|
|
@@ -42982,7 +42993,7 @@ var AsyncBufferObservationStrategy = class extends ObservationStrategy {
|
|
|
42982
42993
|
failures: result.extractionFailures,
|
|
42983
42994
|
previousValues: this.priorExtractedValues,
|
|
42984
42995
|
rawObservations: result.observations,
|
|
42985
|
-
recentMessages: formatMessagesForObserver(messages, {
|
|
42996
|
+
recentMessages: () => formatMessagesForObserver(messages, {
|
|
42986
42997
|
maxPartLength: 500,
|
|
42987
42998
|
timeZone: this.opts.record.observedTimezone
|
|
42988
42999
|
}),
|
|
@@ -43411,7 +43422,7 @@ var ResourceScopedObservationStrategy = class extends ObservationStrategy {
|
|
|
43411
43422
|
failures: result.extractionFailures,
|
|
43412
43423
|
previousValues,
|
|
43413
43424
|
rawObservations: result.observations,
|
|
43414
|
-
recentMessages: formatMessagesForObserver(threadMessages, {
|
|
43425
|
+
recentMessages: () => formatMessagesForObserver(threadMessages, {
|
|
43415
43426
|
maxPartLength: 500,
|
|
43416
43427
|
timeZone: this.opts.record.observedTimezone
|
|
43417
43428
|
}),
|
|
@@ -43740,7 +43751,7 @@ var ObservationStep = class {
|
|
|
43740
43751
|
}
|
|
43741
43752
|
/** Step context from prepare(). Throws if prepare() hasn't been called. */
|
|
43742
43753
|
get context() {
|
|
43743
|
-
if (!this._context) throw new Error("Step not prepared yet
|
|
43754
|
+
if (!this._context) throw new Error("Step not prepared yet \u2014 call prepare() first");
|
|
43744
43755
|
return this._context;
|
|
43745
43756
|
}
|
|
43746
43757
|
/**
|
|
@@ -44160,7 +44171,7 @@ var ObservationStep = class {
|
|
|
44160
44171
|
const messagesToSeal = messageToSeal ? [messageToSeal] : [];
|
|
44161
44172
|
this.turn.abortSignal?.throwIfAborted();
|
|
44162
44173
|
om.sealMessagesForBuffering(messagesToSeal);
|
|
44163
|
-
if (this.seededResponseMessage) omDebug("[OM:observe] skipping response-id rotation
|
|
44174
|
+
if (this.seededResponseMessage) omDebug("[OM:observe] skipping response-id rotation \u2014 step-0 seeded response message holds the active id");
|
|
44164
44175
|
else try {
|
|
44165
44176
|
await this.turn.hooks?.onSyncObservationComplete?.();
|
|
44166
44177
|
} catch (error) {
|
|
@@ -44310,12 +44321,12 @@ var ObservationTurn = class {
|
|
|
44310
44321
|
messageList;
|
|
44311
44322
|
/** The current cached record. Refreshed after mutations (activate/observe/reflect). */
|
|
44312
44323
|
get record() {
|
|
44313
|
-
if (!this._record) throw new Error("Turn not started
|
|
44324
|
+
if (!this._record) throw new Error("Turn not started \u2014 call start() first");
|
|
44314
44325
|
return this._record;
|
|
44315
44326
|
}
|
|
44316
44327
|
/** The context loaded during start(). */
|
|
44317
44328
|
get context() {
|
|
44318
|
-
if (!this._context) throw new Error("Turn not started
|
|
44329
|
+
if (!this._context) throw new Error("Turn not started \u2014 call start() first");
|
|
44319
44330
|
return this._context;
|
|
44320
44331
|
}
|
|
44321
44332
|
/** Whether the turn has been ended and can no longer accept steps. */
|
|
@@ -44384,7 +44395,7 @@ var ObservationTurn = class {
|
|
|
44384
44395
|
* (its output messages will be saved at the start of the new step's prepare()).
|
|
44385
44396
|
*/
|
|
44386
44397
|
step(stepNumber) {
|
|
44387
|
-
if (!this._started) throw new Error("Turn not started
|
|
44398
|
+
if (!this._started) throw new Error("Turn not started \u2014 call start() first");
|
|
44388
44399
|
if (this._ended) throw new Error("Turn already ended");
|
|
44389
44400
|
this._currentStep = new ObservationStep(this, stepNumber);
|
|
44390
44401
|
return this._currentStep;
|
|
@@ -44605,8 +44616,8 @@ When consolidating observations:
|
|
|
44605
44616
|
- Keep what the user explicitly said they have never done, do not know, or refused, and keep every stated preference, rule, and instruction with its meaning intact
|
|
44606
44617
|
- Prefer many short factual lines over prose summaries. Do not replace facts with generalities like "discussed travel plans"
|
|
44607
44618
|
- Combine related items where it makes sense (e.g., "agent called view tool 5 times on file x")
|
|
44608
|
-
- Preserve
|
|
44609
|
-
- Preserve the concrete resolved outcome captured by
|
|
44619
|
+
- Preserve \u2705 completion markers \u2014 they are memory signals that tell the assistant what is already resolved and help prevent repeated work
|
|
44620
|
+
- Preserve the concrete resolved outcome captured by \u2705 markers so the assistant knows what exactly is done
|
|
44610
44621
|
- Condense the wording of older observations more than recent ones, but keep their facts
|
|
44611
44622
|
|
|
44612
44623
|
CRITICAL: USER ASSERTIONS vs QUESTIONS
|
|
@@ -44628,23 +44639,23 @@ When observations contain <thread id="..."> sections:
|
|
|
44628
44639
|
Example input:
|
|
44629
44640
|
<thread id="thread-1">
|
|
44630
44641
|
Date: Dec 4, 2025
|
|
44631
|
-
*
|
|
44632
|
-
*
|
|
44642
|
+
* \u{1F534} (14:30) User prefers TypeScript
|
|
44643
|
+
* \u{1F7E1} (14:35) Working on auth feature
|
|
44633
44644
|
</thread>
|
|
44634
44645
|
<thread id="thread-2">
|
|
44635
44646
|
Date: Dec 4, 2025
|
|
44636
|
-
*
|
|
44637
|
-
*
|
|
44647
|
+
* \u{1F534} (15:00) User prefers TypeScript
|
|
44648
|
+
* \u{1F7E1} (15:05) Debugging API endpoint
|
|
44638
44649
|
</thread>
|
|
44639
44650
|
|
|
44640
44651
|
Example output (consolidated):
|
|
44641
44652
|
Date: Dec 4, 2025
|
|
44642
|
-
*
|
|
44653
|
+
* \u{1F534} (14:30) User prefers TypeScript
|
|
44643
44654
|
<thread id="thread-1">
|
|
44644
|
-
*
|
|
44655
|
+
* \u{1F7E1} (14:35) Working on auth feature
|
|
44645
44656
|
</thread>
|
|
44646
44657
|
<thread id="thread-2">
|
|
44647
|
-
*
|
|
44658
|
+
* \u{1F7E1} (15:05) Debugging API endpoint
|
|
44648
44659
|
</thread>
|
|
44649
44660
|
|
|
44650
44661
|
=== OUTPUT FORMAT ===
|
|
@@ -44675,8 +44686,8 @@ Please re-process with slightly more compression:
|
|
|
44675
44686
|
- Memory is getting long - use a more condensed style throughout
|
|
44676
44687
|
- Combine related items more aggressively but do not lose important specific details of names, places, events, and people
|
|
44677
44688
|
- Combine repeated similar tool calls (e.g. multiple file views, searches, or edits in the same area) into a single summary line describing what was explored/changed and the outcome
|
|
44678
|
-
- Preserve
|
|
44679
|
-
- Preserve the concrete resolved outcome captured by
|
|
44689
|
+
- Preserve \u2705 completion markers \u2014 they are memory signals that tell the assistant what is already resolved and help prevent repeated work
|
|
44690
|
+
- Preserve the concrete resolved outcome captured by \u2705 markers so the assistant knows what exactly is done
|
|
44680
44691
|
|
|
44681
44692
|
Aim for a 8/10 detail level.
|
|
44682
44693
|
`,
|
|
@@ -44692,8 +44703,8 @@ Please re-process with much more aggressive compression:
|
|
|
44692
44703
|
- Combine related items aggressively but do not lose important specific details of names, places, events, and people
|
|
44693
44704
|
- Combine repeated similar tool calls (e.g. multiple file views, searches, or edits in the same area) into a single summary line describing what was explored/changed and the outcome
|
|
44694
44705
|
- If the same file or module is mentioned across many observations, merge into one entry covering the full arc
|
|
44695
|
-
- Preserve
|
|
44696
|
-
- Preserve the concrete resolved outcome captured by
|
|
44706
|
+
- Preserve \u2705 completion markers \u2014 they are memory signals that tell the assistant what is already resolved and help prevent repeated work
|
|
44707
|
+
- Preserve the concrete resolved outcome captured by \u2705 markers so the assistant knows what exactly is done
|
|
44697
44708
|
- Remove redundant information and merge overlapping observations
|
|
44698
44709
|
|
|
44699
44710
|
Aim for a 6/10 detail level.
|
|
@@ -44704,14 +44715,14 @@ Aim for a 6/10 detail level.
|
|
|
44704
44715
|
Your previous reflections have failed to compress sufficiently after multiple attempts.
|
|
44705
44716
|
|
|
44706
44717
|
Please re-process with maximum compression:
|
|
44707
|
-
- Summarize the oldest observations (first 50-70%) into brief high-level paragraphs
|
|
44718
|
+
- Summarize the oldest observations (first 50-70%) into brief high-level paragraphs \u2014 only key facts, decisions, and outcomes
|
|
44708
44719
|
- For the most recent observations (last 30-50%), retain important details but still use a condensed style
|
|
44709
|
-
- Ruthlessly merge related observations
|
|
44710
|
-
- Combine all tool call sequences (file views, searches, edits, builds) into outcome-only summaries
|
|
44711
|
-
- Drop procedural details (tool calls, retries, intermediate steps)
|
|
44720
|
+
- Ruthlessly merge related observations \u2014 if 10 observations are about the same topic, combine into 1-2 lines
|
|
44721
|
+
- Combine all tool call sequences (file views, searches, edits, builds) into outcome-only summaries \u2014 drop individual steps entirely
|
|
44722
|
+
- Drop procedural details (tool calls, retries, intermediate steps) \u2014 keep only final outcomes
|
|
44712
44723
|
- Drop observations that are no longer relevant or have been superseded by newer information
|
|
44713
|
-
- Preserve
|
|
44714
|
-
- Preserve the concrete resolved outcome captured by
|
|
44724
|
+
- Preserve \u2705 completion markers \u2014 they are memory signals that tell the assistant what is already resolved and help prevent repeated work
|
|
44725
|
+
- Preserve the concrete resolved outcome captured by \u2705 markers so the assistant knows what exactly is done
|
|
44715
44726
|
- Preserve: names, dates, decisions, errors, user preferences, and architectural choices
|
|
44716
44727
|
|
|
44717
44728
|
Aim for a 4/10 detail level.
|
|
@@ -44722,14 +44733,14 @@ Aim for a 4/10 detail level.
|
|
|
44722
44733
|
Multiple compression attempts have failed. The content may already be dense from a prior reflection.
|
|
44723
44734
|
|
|
44724
44735
|
You MUST dramatically reduce the number of observations while keeping the standard observation format (date groups with bullet points and priority emojis):
|
|
44725
|
-
- Tool call observations are the biggest source of bloat. Collapse ALL tool call sequences into outcome-only observations
|
|
44726
|
-
- Never preserve individual tool calls (viewed file X, searched for Y, ran build)
|
|
44736
|
+
- Tool call observations are the biggest source of bloat. Collapse ALL tool call sequences into outcome-only observations \u2014 e.g. 10 observations about viewing/searching/editing files become 1 observation about what was actually learned or achieved (e.g. "Investigated auth module and found token validation was skipping expiry check")
|
|
44737
|
+
- Never preserve individual tool calls (viewed file X, searched for Y, ran build) \u2014 only preserve what was discovered or accomplished
|
|
44727
44738
|
- Consolidate many related observations into single, more generic observations
|
|
44728
44739
|
- Merge all same-day date groups into at most 2-3 date groups per day
|
|
44729
44740
|
- For older content, each topic or task should be at most 1-2 observations capturing the key outcome
|
|
44730
44741
|
- For recent content, retain more detail but still merge related items aggressively
|
|
44731
44742
|
- If multiple observations describe incremental progress on the same task, keep only the final state
|
|
44732
|
-
- Preserve
|
|
44743
|
+
- Preserve \u2705 completion markers and their outcomes but merge related completions into fewer lines
|
|
44733
44744
|
- Preserve: user preferences, key decisions, architectural choices, and unresolved issues
|
|
44734
44745
|
|
|
44735
44746
|
Aim for a 2/10 detail level. Fewer, more generic observations are better than many specific ones that exceed the budget.
|
|
@@ -45152,7 +45163,7 @@ var ReflectorRunner = class {
|
|
|
45152
45163
|
operationType: "reflection",
|
|
45153
45164
|
startedAt: streamContext.startedAt,
|
|
45154
45165
|
tokensAttempted: originalTokens,
|
|
45155
|
-
error: `Did not compress below threshold (${originalTokens}
|
|
45166
|
+
error: `Did not compress below threshold (${originalTokens} \u2192 ${reflectedTokens}, target: ${targetThreshold}), retrying at level ${currentLevel + 1}`,
|
|
45156
45167
|
retrying: true,
|
|
45157
45168
|
recordId: streamContext.recordId,
|
|
45158
45169
|
threadId: streamContext.threadId
|
|
@@ -45182,7 +45193,7 @@ var ReflectorRunner = class {
|
|
|
45182
45193
|
}
|
|
45183
45194
|
currentLevel = Math.min(currentLevel + 1, maxLevel);
|
|
45184
45195
|
}
|
|
45185
|
-
if (observations.trim().length > 0 && parsed.observations.trim().length === 0) throw new Error(`Reflector produced empty output after ${attemptNumber} attempt(s)${parsed.degenerate ? " (degenerate repetition)" : ""}
|
|
45196
|
+
if (observations.trim().length > 0 && parsed.observations.trim().length === 0) throw new Error(`Reflector produced empty output after ${attemptNumber} attempt(s)${parsed.degenerate ? " (degenerate repetition)" : ""} \u2014 refusing to commit an empty reflection over ${originalTokens} observation tokens`);
|
|
45186
45197
|
const structuredExtraction = await extractStructuredValues({
|
|
45187
45198
|
agent,
|
|
45188
45199
|
source: "reflector",
|
|
@@ -45323,7 +45334,7 @@ var ReflectorRunner = class {
|
|
|
45323
45334
|
const reflectedObservationLineCount = linesToReflect;
|
|
45324
45335
|
const sliceTokenEstimate = Math.round(avgTokensPerLine * linesToReflect);
|
|
45325
45336
|
const compressionTarget = Math.round(sliceTokenEstimate * .75);
|
|
45326
|
-
omDebug(`[OM:reflect] doAsyncBufferedReflection: slicing observations for reflection
|
|
45337
|
+
omDebug(`[OM:reflect] doAsyncBufferedReflection: slicing observations for reflection \u2014 totalLines=${totalLines}, avgTokPerLine=${avgTokensPerLine.toFixed(1)}, activationPointTokens=${activationPointTokens}, linesToReflect=${linesToReflect}/${totalLines}, sliceTokenEstimate=${sliceTokenEstimate}, compressionTarget=${compressionTarget}`);
|
|
45327
45338
|
omDebug(`[OM:reflect] doAsyncBufferedReflection: starting reflector call, recordId=${currentRecord.id}, observationTokens=${sliceTokenEstimate}, compressionTarget=${compressionTarget} (inputTokens), activeObsLength=${activeObservations.length}, reflectedLineCount=${reflectedObservationLineCount}`);
|
|
45328
45339
|
if (writer) {
|
|
45329
45340
|
const startMarker = createBufferingStartMarker({
|
|
@@ -45495,7 +45506,7 @@ var ReflectorRunner = class {
|
|
|
45495
45506
|
const unreflectedTailTokens = unreflectedContent ? this.tokenCounter.countObservations(unreflectedContent) : 0;
|
|
45496
45507
|
const bufferedReflectionTokens = freshRecord.bufferedReflectionTokens ?? 0;
|
|
45497
45508
|
if (unreflectedTailTokens < bufferedReflectionTokens) {
|
|
45498
|
-
omDebug(`[OM:reflect] tryActivateBufferedReflection: suppressing early ${activationMetadata.triggeredBy} activation
|
|
45509
|
+
omDebug(`[OM:reflect] tryActivateBufferedReflection: suppressing early ${activationMetadata.triggeredBy} activation \u2014 unreflectedTailTokens=${unreflectedTailTokens} < bufferedReflectionTokens=${bufferedReflectionTokens}; keeping buffer for threshold activation`);
|
|
45499
45510
|
return {
|
|
45500
45511
|
status: "suppressed",
|
|
45501
45512
|
reason: "composition"
|
|
@@ -45506,7 +45517,7 @@ var ReflectorRunner = class {
|
|
|
45506
45517
|
const regularActivationTarget = reflectThreshold * (1 - bufferActivation);
|
|
45507
45518
|
const minCombinedTokens = Math.round(regularActivationTarget * EARLY_ACTIVATION_SIZE_FLOOR_RATIO);
|
|
45508
45519
|
if (combinedTokenCount < minCombinedTokens) {
|
|
45509
|
-
omDebug(`[OM:reflect] tryActivateBufferedReflection: suppressing early ${activationMetadata.triggeredBy} activation
|
|
45520
|
+
omDebug(`[OM:reflect] tryActivateBufferedReflection: suppressing early ${activationMetadata.triggeredBy} activation \u2014 combinedTokenCount=${combinedTokenCount} < minCombinedTokens=${minCombinedTokens} (${EARLY_ACTIVATION_SIZE_FLOOR_RATIO * 100}% of regular activation target ${Math.round(regularActivationTarget)}, threshold=${reflectThreshold}, bufferActivation=${bufferActivation}); keeping buffer for threshold activation`);
|
|
45510
45521
|
return {
|
|
45511
45522
|
status: "suppressed",
|
|
45512
45523
|
reason: "size"
|
|
@@ -45635,7 +45646,7 @@ var ReflectorRunner = class {
|
|
|
45635
45646
|
omDebug(`[OM:reflect] isReflecting=true and active in this process, skipping`);
|
|
45636
45647
|
return;
|
|
45637
45648
|
}
|
|
45638
|
-
omDebug(`[OM:reflect] isReflecting=true but NOT active in this process
|
|
45649
|
+
omDebug(`[OM:reflect] isReflecting=true but NOT active in this process \u2014 stale flag from dead process, clearing`);
|
|
45639
45650
|
await this.storage.setReflectingFlag(record.id, false);
|
|
45640
45651
|
}
|
|
45641
45652
|
if (this.buffering.isAsyncReflectionEnabled()) {
|
|
@@ -45649,15 +45660,15 @@ var ReflectorRunner = class {
|
|
|
45649
45660
|
else {
|
|
45650
45661
|
const activationPoint = reflectThreshold * this.reflectionConfig.bufferActivation;
|
|
45651
45662
|
if (observationTokens < activationPoint) {
|
|
45652
|
-
omDebug(`[OM:reflect] skipping async reflection
|
|
45663
|
+
omDebug(`[OM:reflect] skipping async reflection \u2014 observationTokens (${observationTokens}) below activation point (${activationPoint}), triggered by ${activationTriggeredBy}`);
|
|
45653
45664
|
return;
|
|
45654
45665
|
}
|
|
45655
45666
|
const bufferKey = this.buffering.getReflectionBufferKey(lockKey);
|
|
45656
45667
|
if (this.buffering.isAsyncBufferingInProgress(bufferKey) || BufferingCoordinator.lastBufferedBoundary.has(bufferKey)) {
|
|
45657
|
-
omDebug(`[OM:reflect] skipping async reflection
|
|
45668
|
+
omDebug(`[OM:reflect] skipping async reflection \u2014 reflection buffer already active or present for ${bufferKey}`);
|
|
45658
45669
|
return;
|
|
45659
45670
|
}
|
|
45660
|
-
omDebug(`[OM:reflect] async activation failed, no blockAfter or below it (obsTokens=${observationTokens}, blockAfter=${this.reflectionConfig.blockAfter})
|
|
45671
|
+
omDebug(`[OM:reflect] async activation failed, no blockAfter or below it (obsTokens=${observationTokens}, blockAfter=${this.reflectionConfig.blockAfter}) \u2014 starting background reflection`);
|
|
45661
45672
|
this.startAsyncBufferedReflection(record, observationTokens, lockKey, writer, requestContext, observabilityContext, reflectionHooks, priorExtractedValues, mainAgent, sendSignal, trigger, currentModel);
|
|
45662
45673
|
return;
|
|
45663
45674
|
}
|
|
@@ -45665,7 +45676,7 @@ var ReflectorRunner = class {
|
|
|
45665
45676
|
if (activationTriggeredBy === "threshold") {
|
|
45666
45677
|
const suppressedAtTokens = this.syncReflectionSuppression.get(lockKey);
|
|
45667
45678
|
if (suppressedAtTokens !== void 0 && observationTokens === suppressedAtTokens) {
|
|
45668
|
-
omDebug(`[OM:reflect] skipping sync reflection
|
|
45679
|
+
omDebug(`[OM:reflect] skipping sync reflection \u2014 observations unchanged at ${observationTokens} tokens since the last unproductive attempt; retrying once they change`);
|
|
45669
45680
|
return;
|
|
45670
45681
|
}
|
|
45671
45682
|
}
|
|
@@ -46506,7 +46517,7 @@ var ObservationalMemory = class ObservationalMemory {
|
|
|
46506
46517
|
const asyncBufferingDisabled = config.observation?.bufferTokens === false || config.scope === "resource" && !userExplicitlyConfiguredAsync;
|
|
46507
46518
|
if (isSharedBudget && !asyncBufferingDisabled) {
|
|
46508
46519
|
if (userExplicitlyConfiguredAsync) throw new Error("shareTokenBudget requires async buffering to be disabled (this is a temporary limitation). Add observation: { bufferTokens: false } to your config:\n\n observationalMemory: {\n shareTokenBudget: true,\n observation: { bufferTokens: false },\n }\n\nRemove any other async buffering settings (bufferTokens, bufferActivation, blockAfter).");
|
|
46509
|
-
else throw new Error("shareTokenBudget requires async buffering to be disabled (this is a temporary limitation). Add observation: { bufferTokens: false } to your config:\n\n observationalMemory: {\n shareTokenBudget: true,\n observation: { bufferTokens: false },\n }\n\nAsync buffering is enabled by default
|
|
46520
|
+
else throw new Error("shareTokenBudget requires async buffering to be disabled (this is a temporary limitation). Add observation: { bufferTokens: false } to your config:\n\n observationalMemory: {\n shareTokenBudget: true,\n observation: { bufferTokens: false },\n }\n\nAsync buffering is enabled by default \u2014 this opt-out is only needed when using shareTokenBudget.");
|
|
46510
46521
|
}
|
|
46511
46522
|
const observationActivateAfterIdle = config.observation?.activateAfterIdle ?? config.activateAfterIdle;
|
|
46512
46523
|
const observationActivateAfterIdlePath = config.observation?.activateAfterIdle !== void 0 ? "observation.activateAfterIdle" : "activateAfterIdle";
|
|
@@ -46603,7 +46614,7 @@ var ObservationalMemory = class ObservationalMemory {
|
|
|
46603
46614
|
hasWarnedResourceScopeDeprecation = true;
|
|
46604
46615
|
console.warn("[Mastra] Observational memory `scope: 'resource'` is deprecated and will be removed in a future release because it works much worse than thread scope for prompt caching and agent understanding. Remove `scope` to use the default thread scope, and enable `retrieval` for cross-thread recall. See https://mastra.ai/docs/memory/observational-memory#resource-scope-deprecated");
|
|
46605
46616
|
}
|
|
46606
|
-
omDebug(`[OM:init] new ObservationalMemory instance created
|
|
46617
|
+
omDebug(`[OM:init] new ObservationalMemory instance created \u2014 scope=${this.scope}, messageTokens=${JSON.stringify(this.observationConfig.messageTokens)}, obsAsyncEnabled=${this.buffering.isAsyncObservationEnabled()}, bufferTokens=${this.observationConfig.bufferTokens}, bufferActivation=${this.observationConfig.bufferActivation}, blockAfter=${this.observationConfig.blockAfter}, reflectionTokens=${this.reflectionConfig.observationTokens}, refAsyncEnabled=${this.buffering.isAsyncReflectionEnabled()}, refAsyncActivation=${this.reflectionConfig.bufferActivation}, refBlockAfter=${this.reflectionConfig.blockAfter}`);
|
|
46607
46618
|
}
|
|
46608
46619
|
__registerMastra(mastra) {
|
|
46609
46620
|
this.mastra = mastra;
|
|
@@ -46884,7 +46895,7 @@ var ObservationalMemory = class ObservationalMemory {
|
|
|
46884
46895
|
threadId: null,
|
|
46885
46896
|
resourceId: resourceId ?? threadId
|
|
46886
46897
|
};
|
|
46887
|
-
if (!threadId) throw new Error("ObservationalMemory (scope: 'thread') requires a threadId, but received an empty value. This is a bug
|
|
46898
|
+
if (!threadId) throw new Error("ObservationalMemory (scope: 'thread') requires a threadId, but received an empty value. This is a bug \u2014 getThreadContext should have caught this earlier.");
|
|
46888
46899
|
return {
|
|
46889
46900
|
threadId,
|
|
46890
46901
|
resourceId: resourceId ?? threadId
|
|
@@ -47195,7 +47206,7 @@ var ObservationalMemory = class ObservationalMemory {
|
|
|
47195
47206
|
const isImportant = new Array(totalCount);
|
|
47196
47207
|
for (let i = 0; i < totalCount; i++) {
|
|
47197
47208
|
lineTokens[i] = this.tokenCounter.countString(lines[i]);
|
|
47198
|
-
isImportant[i] = lines[i].includes("
|
|
47209
|
+
isImportant[i] = lines[i].includes("\u{1F534}") || lines[i].includes("\u2705");
|
|
47199
47210
|
}
|
|
47200
47211
|
const suffixTokens = new Array(totalCount + 1);
|
|
47201
47212
|
suffixTokens[totalCount] = 0;
|
|
@@ -47528,7 +47539,7 @@ ${formattedMessages}
|
|
|
47528
47539
|
resourceId: freshRecord.resourceId ?? void 0
|
|
47529
47540
|
});
|
|
47530
47541
|
} catch (err) {
|
|
47531
|
-
omError("[OM] Failed to persist sealed messages before buffering
|
|
47542
|
+
omError("[OM] Failed to persist sealed messages before buffering \u2014 skipping observation cycle", err);
|
|
47532
47543
|
return;
|
|
47533
47544
|
}
|
|
47534
47545
|
const cycleId = `buffer-obs-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;
|
|
@@ -48678,7 +48689,7 @@ ${formattedMessages}
|
|
|
48678
48689
|
usage: void 0
|
|
48679
48690
|
};
|
|
48680
48691
|
}
|
|
48681
|
-
omDebug(`[OM:reflect] isReflecting=true but NOT active in this process
|
|
48692
|
+
omDebug(`[OM:reflect] isReflecting=true but NOT active in this process \u2014 stale flag from dead process, clearing`);
|
|
48682
48693
|
await this.storage.setReflectingFlag(record.id, false);
|
|
48683
48694
|
}
|
|
48684
48695
|
await this.storage.setReflectingFlag(record.id, true);
|
|
@@ -48912,7 +48923,7 @@ ${formattedMessages}
|
|
|
48912
48923
|
};
|
|
48913
48924
|
const TEMPORAL_GAP_REMINDER_TYPE = "temporal-gap";
|
|
48914
48925
|
function getTemporalGapReminderText(gapText, timestamp) {
|
|
48915
|
-
return `${gapText}
|
|
48926
|
+
return `${gapText} \u2014 ${formatTemporalTimestamp(new Date(timestamp))}`;
|
|
48916
48927
|
}
|
|
48917
48928
|
function getTemporalGapReminderMetadata(message, gapText, gapMs, timestamp) {
|
|
48918
48929
|
const formattedTimestamp = formatTemporalTimestamp(new Date(timestamp));
|
|
@@ -49133,14 +49144,14 @@ var ObservationalMemoryProcessor = class {
|
|
|
49133
49144
|
omDebug(`[OM:processInputStep:ENTER] step=${stepNumber}, hasMastraMemory=${!!requestContext?.get("MastraMemory")}, hasMemoryInfo=${!!messageList?.serialize()?.memoryInfo?.threadId}`);
|
|
49134
49145
|
const context = this.engine.getThreadContext(requestContext, messageList);
|
|
49135
49146
|
if (!context) {
|
|
49136
|
-
omDebug(`[OM:processInputStep:NO-CONTEXT] getThreadContext returned null
|
|
49147
|
+
omDebug(`[OM:processInputStep:NO-CONTEXT] getThreadContext returned null \u2014 returning early`);
|
|
49137
49148
|
return messageList;
|
|
49138
49149
|
}
|
|
49139
49150
|
const gatewayMemoryManaged = await isGatewayMemoryManaged(model);
|
|
49140
49151
|
state[GATEWAY_STATE_KEY] = gatewayMemoryManaged;
|
|
49141
49152
|
if (gatewayMemoryManaged) {
|
|
49142
49153
|
await this.endActiveTurn(state);
|
|
49143
|
-
omDebug(`[OM:processInputStep:GATEWAY] gateway manages memory
|
|
49154
|
+
omDebug(`[OM:processInputStep:GATEWAY] gateway manages memory \u2014 skipping local processing`);
|
|
49144
49155
|
return messageList;
|
|
49145
49156
|
}
|
|
49146
49157
|
const { threadId, resourceId } = context;
|
|
@@ -49361,7 +49372,7 @@ var ObservationalMemoryProcessor = class {
|
|
|
49361
49372
|
if (!context) return;
|
|
49362
49373
|
if ((0, _mastra_core_memory.parseMemoryRequestContext)(requestContext)?.memoryConfig?.readOnly) return;
|
|
49363
49374
|
state[CONTEXT_OVERFLOW_STEP_KEY] = stepNumber;
|
|
49364
|
-
omDebug(`[OM:processAPIError] context overflow at step ${stepNumber}
|
|
49375
|
+
omDebug(`[OM:processAPIError] context overflow at step ${stepNumber} \u2014 observing pending messages`);
|
|
49365
49376
|
const { threadId, resourceId } = context;
|
|
49366
49377
|
await this.engine.waitForBuffering(threadId, resourceId, void 0, args.abortSignal);
|
|
49367
49378
|
const messages = getObservableMessages(messageList);
|
|
@@ -51960,7 +51971,7 @@ var require_ignore = /* @__PURE__ */ require_rolldown_runtime.__commonJSMin(((ex
|
|
|
51960
51971
|
const SPACE = " ";
|
|
51961
51972
|
const ESCAPE = "\\";
|
|
51962
51973
|
const REGEX_LITERAL_SPECIAL = /[.*+?()[\]{}^$|\\/]/;
|
|
51963
|
-
const BOM = "
|
|
51974
|
+
const BOM = "\uFEFF";
|
|
51964
51975
|
const REGEX_INVALID_TRAILING_BACKSLASH = /(?:[^\\]|^)\\$/;
|
|
51965
51976
|
const REGEX_ANCHORED_GLOBSTAR = /^\/\*{2,}$/;
|
|
51966
51977
|
const REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/;
|
|
@@ -52057,8 +52068,8 @@ var require_ignore = /* @__PURE__ */ require_rolldown_runtime.__commonJSMin(((ex
|
|
|
52057
52068
|
const NEVER_MATCH = "[]";
|
|
52058
52069
|
const PLACEHOLDER = "\0";
|
|
52059
52070
|
const REGEX_RESTORE_PLACEHOLDER = new RegExp(`${PLACEHOLDER}(\\d+)${PLACEHOLDER}`, "g");
|
|
52060
|
-
const TRAILING_WILDCARD = "
|
|
52061
|
-
const TRAILING_DOUBLESTAR = "
|
|
52071
|
+
const TRAILING_WILDCARD = "\uE000";
|
|
52072
|
+
const TRAILING_DOUBLESTAR = "\uE001";
|
|
52062
52073
|
const isReserved = (char) => char === PLACEHOLDER || char === TRAILING_WILDCARD || char === TRAILING_DOUBLESTAR;
|
|
52063
52074
|
const extractBrackets = (pattern) => {
|
|
52064
52075
|
const sources = [];
|
|
@@ -52830,7 +52841,7 @@ async function logGitState(targetPath, label) {
|
|
|
52830
52841
|
const gitStatusResult = await git(targetPath, "status", "--porcelain");
|
|
52831
52842
|
const gitLogResult = await git(targetPath, "log", "--oneline", "-3");
|
|
52832
52843
|
const gitCountResult = await git(targetPath, "rev-list", "--count", "HEAD");
|
|
52833
|
-
console.info(
|
|
52844
|
+
console.info(`\u{1F4CA} Git state ${label}:`);
|
|
52834
52845
|
console.info("Status:", gitStatusResult.stdout.trim() || "Clean working directory");
|
|
52835
52846
|
console.info("Recent commits:", gitLogResult.stdout.trim());
|
|
52836
52847
|
console.info("Total commits:", gitCountResult.stdout.trim());
|
|
@@ -52922,9 +52933,9 @@ async function gitCheckoutBranch(branchName, targetPath) {
|
|
|
52922
52933
|
async function backupAndReplaceFile(sourceFile, targetFile) {
|
|
52923
52934
|
const backupFile = `${targetFile}.backup-${Date.now()}`;
|
|
52924
52935
|
await (0, fs_promises.copyFile)(targetFile, backupFile);
|
|
52925
|
-
console.info(
|
|
52936
|
+
console.info(`\u{1F4E6} Created backup: ${(0, path.basename)(backupFile)}`);
|
|
52926
52937
|
await (0, fs_promises.copyFile)(sourceFile, targetFile);
|
|
52927
|
-
console.info(
|
|
52938
|
+
console.info(`\u{1F504} Replaced file with template version (backup created)`);
|
|
52928
52939
|
}
|
|
52929
52940
|
async function renameAndCopyFile(sourceFile, targetFile) {
|
|
52930
52941
|
let counter = 1;
|
|
@@ -52938,7 +52949,7 @@ async function renameAndCopyFile(sourceFile, targetFile) {
|
|
|
52938
52949
|
counter++;
|
|
52939
52950
|
}
|
|
52940
52951
|
await (0, fs_promises.copyFile)(sourceFile, uniqueTargetFile);
|
|
52941
|
-
console.info(
|
|
52952
|
+
console.info(`\u{1F4DD} Copied with unique name: ${(0, path.basename)(uniqueTargetFile)}`);
|
|
52942
52953
|
return uniqueTargetFile;
|
|
52943
52954
|
}
|
|
52944
52955
|
const isValidMastraLanguageModel = (model) => {
|
|
@@ -52976,7 +52987,7 @@ const mergeGitignoreFiles = (targetContent, templateContent, templateSlug) => {
|
|
|
52976
52987
|
const isNegation = normalized.startsWith("!");
|
|
52977
52988
|
const basePath = isNegation ? normalized.slice(1) : normalized;
|
|
52978
52989
|
if (!(isNegation ? existingEntries.has(basePath) : existingEntries.has("!" + basePath))) newEntries.push(trimmed);
|
|
52979
|
-
else console.info(
|
|
52990
|
+
else console.info(`\u26A0 Skipping conflicting .gitignore rule: ${trimmed} (conflicts with existing rule)`);
|
|
52980
52991
|
}
|
|
52981
52992
|
}
|
|
52982
52993
|
}
|
|
@@ -53006,7 +53017,7 @@ const mergeEnvFiles = (targetContent, templateVariables, templateSlug) => {
|
|
|
53006
53017
|
key,
|
|
53007
53018
|
value
|
|
53008
53019
|
});
|
|
53009
|
-
else console.info(
|
|
53020
|
+
else console.info(`\u26A0 Skipping existing environment variable: ${key} (already exists in .env)`);
|
|
53010
53021
|
if (newVars.length === 0) return targetContent;
|
|
53011
53022
|
const result = [...targetLines];
|
|
53012
53023
|
const lastLine = result[result.length - 1];
|
|
@@ -53061,7 +53072,7 @@ const createModelInstance = async (provider, modelId, version = "v2") => {
|
|
|
53061
53072
|
try {
|
|
53062
53073
|
const providerFn = version === `v1` ? { v1: {
|
|
53063
53074
|
openai: async () => {
|
|
53064
|
-
const { openai } = await Promise.resolve().then(() => require("./dist-
|
|
53075
|
+
const { openai } = await Promise.resolve().then(() => require("./dist-uiPbWl5E.cjs"));
|
|
53065
53076
|
return openai(modelId);
|
|
53066
53077
|
},
|
|
53067
53078
|
anthropic: async () => {
|
|
@@ -53130,25 +53141,25 @@ IF NO PROJECT EXISTS, USE THE MANAGEPROJECT TOOL TO CREATE A NEW PROJECT
|
|
|
53130
53141
|
|
|
53131
53142
|
DO NOT INCLUDE TODOS IN THE CODE, UNLESS SPECIFICALLY ASKED TO DO SO, CREATE REAL WORLD CODE
|
|
53132
53143
|
|
|
53133
|
-
### 1.
|
|
53144
|
+
### 1. \u{1F50D} **UNDERSTAND** (Information Gathering)
|
|
53134
53145
|
- **Explore Mastra Docs**: Use docs tools to understand relevant Mastra patterns and APIs
|
|
53135
53146
|
- **Analyze Project**: Use file exploration to understand existing codebase structure
|
|
53136
53147
|
- **Web Research**: Search for packages, examples, or solutions when docs are insufficient
|
|
53137
53148
|
- **Clarify Requirements**: Ask targeted questions only when critical information is missing
|
|
53138
53149
|
|
|
53139
|
-
### 2.
|
|
53150
|
+
### 2. \u{1F4CB} **PLAN** (Strategy & Design)
|
|
53140
53151
|
- **Architecture**: Design using Mastra conventions (agents, tools, workflows, memory)
|
|
53141
53152
|
- **Dependencies**: Identify required packages and Mastra components
|
|
53142
53153
|
- **Integration**: Plan how to integrate with existing project structure
|
|
53143
53154
|
- **Validation**: Define how to test and verify the implementation
|
|
53144
53155
|
|
|
53145
|
-
### 3.
|
|
53156
|
+
### 3. \u{1F6E0}\uFE0F **BUILD** (Implementation)
|
|
53146
53157
|
- **Install First**: Use \`manageProject\` tool to install required packages
|
|
53147
53158
|
- **Follow Patterns**: Implement using established Mastra conventions
|
|
53148
53159
|
- **Real Code Only**: Build actual working functionality, never mock implementations
|
|
53149
53160
|
- **Environment Setup**: Create proper .env configuration and documentation
|
|
53150
53161
|
|
|
53151
|
-
### 4.
|
|
53162
|
+
### 4. \u2705 **VALIDATE** (Quality Assurance)
|
|
53152
53163
|
- **Code Validation**: Run \`validateCode\` with types and lint checks
|
|
53153
53164
|
- **Testing**: Execute tests if available
|
|
53154
53165
|
- **Server Testing**: Use \`manageServer\` and \`httpRequest\` for API validation
|
|
@@ -53245,23 +53256,23 @@ DO NOT INCLUDE TODOS IN THE CODE, UNLESS SPECIFICALLY ASKED TO DO SO, CREATE REA
|
|
|
53245
53256
|
## Output Requirements
|
|
53246
53257
|
|
|
53247
53258
|
### Code Quality
|
|
53248
|
-
-
|
|
53249
|
-
-
|
|
53250
|
-
-
|
|
53251
|
-
-
|
|
53252
|
-
-
|
|
53259
|
+
- \u2705 TypeScript compilation passes
|
|
53260
|
+
- \u2705 ESLint validation passes
|
|
53261
|
+
- \u2705 Proper error handling implemented
|
|
53262
|
+
- \u2705 Environment variables configured
|
|
53263
|
+
- \u2705 Tests included when appropriate
|
|
53253
53264
|
|
|
53254
53265
|
### Documentation
|
|
53255
|
-
-
|
|
53256
|
-
-
|
|
53257
|
-
-
|
|
53258
|
-
-
|
|
53266
|
+
- \u2705 Clear setup instructions
|
|
53267
|
+
- \u2705 Environment variable documentation
|
|
53268
|
+
- \u2705 Usage examples provided
|
|
53269
|
+
- \u2705 API documentation for custom tools
|
|
53259
53270
|
|
|
53260
53271
|
### Integration
|
|
53261
|
-
-
|
|
53262
|
-
-
|
|
53263
|
-
-
|
|
53264
|
-
-
|
|
53272
|
+
- \u2705 Follows Mastra conventions
|
|
53273
|
+
- \u2705 Integrates with existing project
|
|
53274
|
+
- \u2705 Proper imports and exports
|
|
53275
|
+
- \u2705 Compatible with Mastra ecosystem
|
|
53265
53276
|
|
|
53266
53277
|
## Project Context
|
|
53267
53278
|
|
|
@@ -53808,7 +53819,7 @@ export const mastra = new Mastra({
|
|
|
53808
53819
|
}),
|
|
53809
53820
|
validateCode: (0, _mastra_core_tools.createTool)({
|
|
53810
53821
|
id: "validate-code",
|
|
53811
|
-
description: "Validates code using a fast hybrid approach: syntax
|
|
53822
|
+
description: "Validates code using a fast hybrid approach: syntax \u2192 semantic \u2192 lint. RECOMMENDED: Always provide specific files for optimal performance and accuracy.",
|
|
53812
53823
|
inputSchema: zod.z.object({
|
|
53813
53824
|
projectPath: zod.z.string().optional().describe("Path to the project to validate (defaults to current project)"),
|
|
53814
53825
|
validationType: zod.z.array(zod.z.enum([
|
|
@@ -53818,7 +53829,7 @@ export const mastra = new Mastra({
|
|
|
53818
53829
|
"tests",
|
|
53819
53830
|
"build"
|
|
53820
53831
|
])).describe("Types of validation to perform. Recommended: [\"types\", \"lint\"] for code quality"),
|
|
53821
|
-
files: zod.z.array(zod.z.string()).optional().describe("RECOMMENDED: Specific files to validate (e.g., files you created/modified). Uses hybrid validation: fast syntax check
|
|
53832
|
+
files: zod.z.array(zod.z.string()).optional().describe("RECOMMENDED: Specific files to validate (e.g., files you created/modified). Uses hybrid validation: fast syntax check \u2192 semantic types \u2192 ESLint. Without files, falls back to slower CLI validation.")
|
|
53822
53833
|
}),
|
|
53823
53834
|
outputSchema: zod.z.object({
|
|
53824
53835
|
valid: zod.z.boolean(),
|
|
@@ -55701,8 +55712,8 @@ For each Mastra project directory you analyze:
|
|
|
55701
55712
|
IMPORTANT - Naming Consistency Rules:
|
|
55702
55713
|
- For ALL unit types (including 'other'), the 'name' field should be the filename WITHOUT extension
|
|
55703
55714
|
- For structured units (agents, workflows, tools, etc.), prefer the actual export name if clearly identifiable
|
|
55704
|
-
- use the base filename without extension for the id (e.g., 'util.ts'
|
|
55705
|
-
- use the relative path from the template root for the file (e.g., 'src/mastra/lib/util.ts'
|
|
55715
|
+
- use the base filename without extension for the id (e.g., 'util.ts' \u2192 name: 'util')
|
|
55716
|
+
- use the relative path from the template root for the file (e.g., 'src/mastra/lib/util.ts' \u2192 file: 'src/mastra/lib/util.ts')
|
|
55706
55717
|
|
|
55707
55718
|
Return the actual exported names of the units, as well as the file names.`,
|
|
55708
55719
|
name: "Mastra Project Discoverer",
|
|
@@ -56058,7 +56069,7 @@ const programmaticFileCopyStep = (0, _mastra_core_workflows.createStep)({
|
|
|
56058
56069
|
sourceFile: unit.file,
|
|
56059
56070
|
targetFile: `${targetDir}/${convertedFileName}`
|
|
56060
56071
|
});
|
|
56061
|
-
console.info(
|
|
56072
|
+
console.info(`\u23ED\uFE0F Skipped ${unit.kind} "${unit.id}": file already exists`);
|
|
56062
56073
|
continue;
|
|
56063
56074
|
case "backup-and-replace": try {
|
|
56064
56075
|
await backupAndReplaceFile(sourceFile, targetFile);
|
|
@@ -56070,7 +56081,7 @@ const programmaticFileCopyStep = (0, _mastra_core_workflows.createStep)({
|
|
|
56070
56081
|
id: unit.id
|
|
56071
56082
|
}
|
|
56072
56083
|
});
|
|
56073
|
-
console.info(
|
|
56084
|
+
console.info(`\u{1F504} Replaced ${unit.kind} "${unit.id}": ${unit.file} \u2192 ${convertedFileName} (backup created)`);
|
|
56074
56085
|
continue;
|
|
56075
56086
|
} catch (backupError) {
|
|
56076
56087
|
conflicts.push({
|
|
@@ -56094,7 +56105,7 @@ const programmaticFileCopyStep = (0, _mastra_core_workflows.createStep)({
|
|
|
56094
56105
|
id: unit.id
|
|
56095
56106
|
}
|
|
56096
56107
|
});
|
|
56097
|
-
console.info(
|
|
56108
|
+
console.info(`\u{1F4DD} Renamed ${unit.kind} "${unit.id}": ${unit.file} \u2192 ${(0, path.basename)(uniqueTargetFile)}`);
|
|
56098
56109
|
continue;
|
|
56099
56110
|
} catch (renameError) {
|
|
56100
56111
|
conflicts.push({
|
|
@@ -56132,7 +56143,7 @@ const programmaticFileCopyStep = (0, _mastra_core_workflows.createStep)({
|
|
|
56132
56143
|
id: unit.id
|
|
56133
56144
|
}
|
|
56134
56145
|
});
|
|
56135
|
-
console.info(
|
|
56146
|
+
console.info(`\u2713 Copied ${unit.kind} "${unit.id}": ${unit.file} \u2192 ${convertedFileName}`);
|
|
56136
56147
|
} catch (copyError) {
|
|
56137
56148
|
conflicts.push({
|
|
56138
56149
|
unit: {
|
|
@@ -56159,7 +56170,7 @@ const programmaticFileCopyStep = (0, _mastra_core_workflows.createStep)({
|
|
|
56159
56170
|
id: "tsconfig.json"
|
|
56160
56171
|
}
|
|
56161
56172
|
});
|
|
56162
|
-
console.info("
|
|
56173
|
+
console.info("\u2713 Copied tsconfig.json from template to target");
|
|
56163
56174
|
} else {
|
|
56164
56175
|
await (0, fs_promises.writeFile)(targetTsconfig, JSON.stringify({
|
|
56165
56176
|
compilerOptions: {
|
|
@@ -56195,7 +56206,7 @@ const programmaticFileCopyStep = (0, _mastra_core_workflows.createStep)({
|
|
|
56195
56206
|
id: "tsconfig.json"
|
|
56196
56207
|
}
|
|
56197
56208
|
});
|
|
56198
|
-
console.info("
|
|
56209
|
+
console.info("\u2713 Generated minimal tsconfig.json in target");
|
|
56199
56210
|
}
|
|
56200
56211
|
}
|
|
56201
56212
|
} catch (e) {
|
|
@@ -56224,7 +56235,7 @@ const programmaticFileCopyStep = (0, _mastra_core_workflows.createStep)({
|
|
|
56224
56235
|
id: "mastra-index"
|
|
56225
56236
|
}
|
|
56226
56237
|
});
|
|
56227
|
-
console.info("
|
|
56238
|
+
console.info("\u2713 Copied Mastra index file from template");
|
|
56228
56239
|
}
|
|
56229
56240
|
}
|
|
56230
56241
|
} catch (e) {
|
|
@@ -56253,7 +56264,7 @@ const programmaticFileCopyStep = (0, _mastra_core_workflows.createStep)({
|
|
|
56253
56264
|
id: "gitignore"
|
|
56254
56265
|
}
|
|
56255
56266
|
});
|
|
56256
|
-
console.info("
|
|
56267
|
+
console.info("\u2713 Copied .gitignore from template to target");
|
|
56257
56268
|
} else {
|
|
56258
56269
|
const targetContent = await (0, fs_promises.readFile)(targetGitignore, "utf-8");
|
|
56259
56270
|
const templateContent = await (0, fs_promises.readFile)(templateGitignore, "utf-8");
|
|
@@ -56269,8 +56280,8 @@ const programmaticFileCopyStep = (0, _mastra_core_workflows.createStep)({
|
|
|
56269
56280
|
id: "gitignore-merge"
|
|
56270
56281
|
}
|
|
56271
56282
|
});
|
|
56272
|
-
console.info(
|
|
56273
|
-
} else console.info("
|
|
56283
|
+
console.info(`\u2713 Merged template .gitignore entries into existing .gitignore (${addedLines} new entries)`);
|
|
56284
|
+
} else console.info("\u2139 No new .gitignore entries to add from template");
|
|
56274
56285
|
}
|
|
56275
56286
|
}
|
|
56276
56287
|
} catch (e) {
|
|
@@ -56299,7 +56310,7 @@ const programmaticFileCopyStep = (0, _mastra_core_workflows.createStep)({
|
|
|
56299
56310
|
id: "env"
|
|
56300
56311
|
}
|
|
56301
56312
|
});
|
|
56302
|
-
console.info(
|
|
56313
|
+
console.info(`\u2713 Created .env file with ${Object.keys(variables).length} template variables`);
|
|
56303
56314
|
} else {
|
|
56304
56315
|
const targetContent = await (0, fs_promises.readFile)(targetEnv, "utf-8");
|
|
56305
56316
|
const mergedContent = mergeEnvFiles(targetContent, variables, slug);
|
|
@@ -56314,8 +56325,8 @@ const programmaticFileCopyStep = (0, _mastra_core_workflows.createStep)({
|
|
|
56314
56325
|
id: "env-merge"
|
|
56315
56326
|
}
|
|
56316
56327
|
});
|
|
56317
|
-
console.info(
|
|
56318
|
-
} else console.info("
|
|
56328
|
+
console.info(`\u2713 Merged new environment variables into existing .env file (${addedLines} new entries)`);
|
|
56329
|
+
} else console.info("\u2139 No new environment variables to add (all already exist in .env)");
|
|
56319
56330
|
}
|
|
56320
56331
|
}
|
|
56321
56332
|
} catch (e) {
|
|
@@ -56332,7 +56343,7 @@ const programmaticFileCopyStep = (0, _mastra_core_workflows.createStep)({
|
|
|
56332
56343
|
if (copiedFiles.length > 0) try {
|
|
56333
56344
|
const fileList = copiedFiles.map((f) => f.destination);
|
|
56334
56345
|
await gitAddAndCommit(targetPath, `feat(template): copy ${copiedFiles.length} files from ${slug}@${commitSha.substring(0, 7)}`, fileList, { skipIfNoStaged: true });
|
|
56335
|
-
console.info(
|
|
56346
|
+
console.info(`\u2713 Committed ${copiedFiles.length} copied files`);
|
|
56336
56347
|
} catch (commitError) {
|
|
56337
56348
|
console.warn("Failed to commit copied files:", commitError);
|
|
56338
56349
|
}
|
|
@@ -56576,7 +56587,7 @@ Start by listing your tasks and work through them systematically!
|
|
|
56576
56587
|
content: toolResult.content || "",
|
|
56577
56588
|
notes: toolResult.notes
|
|
56578
56589
|
});
|
|
56579
|
-
console.info(
|
|
56590
|
+
console.info(`\u{1F4CB} Task completed: ${toolResult.taskId} - ${toolResult.content}`);
|
|
56580
56591
|
}
|
|
56581
56592
|
} catch (parseError) {
|
|
56582
56593
|
console.warn("Failed to parse task management result:", parseError);
|
|
@@ -56628,7 +56639,7 @@ const validationAndFixStep = (0, _mastra_core_workflows.createStep)({
|
|
|
56628
56639
|
const { commitSha, slug, orderedUnits, templateDir, copiedFiles, conflictsResolved, maxIterations = 5 } = inputData;
|
|
56629
56640
|
const targetPath = resolveTargetPath(inputData, requestContext);
|
|
56630
56641
|
if (!(copiedFiles.length > 0 || conflictsResolved && conflictsResolved.length > 0)) {
|
|
56631
|
-
console.info("
|
|
56642
|
+
console.info("\u23ED\uFE0F Skipping validation - no files copied or conflicts resolved");
|
|
56632
56643
|
return {
|
|
56633
56644
|
success: true,
|
|
56634
56645
|
applied: false,
|
|
@@ -56640,7 +56651,7 @@ const validationAndFixStep = (0, _mastra_core_workflows.createStep)({
|
|
|
56640
56651
|
}
|
|
56641
56652
|
};
|
|
56642
56653
|
}
|
|
56643
|
-
console.info(
|
|
56654
|
+
console.info(`\u{1F4CB} Changes detected: ${copiedFiles.length} files copied, ${conflictsResolved?.length || 0} conflicts resolved`);
|
|
56644
56655
|
let currentIteration = 1;
|
|
56645
56656
|
try {
|
|
56646
56657
|
const model = await resolveModel({
|
|
@@ -56732,7 +56743,7 @@ CRITICAL TOOL SELECTION GUIDE:
|
|
|
56732
56743
|
- **writeFile**: ONLY for creating new files that don't exist
|
|
56733
56744
|
Example: creating missing index.ts barrel files
|
|
56734
56745
|
|
|
56735
|
-
CRITICAL WRITEFIL
|
|
56746
|
+
CRITICAL WRITEFIL\u0415 SAFETY RULES:
|
|
56736
56747
|
- ONLY use writeFile for creating NEW files that don't exist
|
|
56737
56748
|
- ALWAYS check with readFile first to verify file doesn't exist
|
|
56738
56749
|
- NEVER use writeFile to overwrite existing files - use multiEdit or replaceLines instead
|
|
@@ -56817,10 +56828,10 @@ Previous iterations may have fixed some issues, so start by re-running validateC
|
|
|
56817
56828
|
if (iterationErrors > 0 && lastValidationResult?.errors) validationResults.lastValidationErrors = lastValidationResult.errors;
|
|
56818
56829
|
console.info(`Iteration ${currentIteration} complete: ${iterationErrors} errors remaining`);
|
|
56819
56830
|
if (iterationErrors === 0) {
|
|
56820
|
-
console.info(
|
|
56831
|
+
console.info(`\u2705 All validation issues resolved in ${currentIteration} iterations!`);
|
|
56821
56832
|
break;
|
|
56822
56833
|
} else if (currentIteration >= maxIterations) {
|
|
56823
|
-
console.info(
|
|
56834
|
+
console.info(`\u26A0\uFE0F Max iterations (${maxIterations}) reached. ${iterationErrors} errors still remaining.`);
|
|
56824
56835
|
break;
|
|
56825
56836
|
}
|
|
56826
56837
|
currentIteration++;
|
|
@@ -56860,7 +56871,7 @@ Previous iterations may have fixed some issues, so start by re-running validateC
|
|
|
56860
56871
|
recursive: true,
|
|
56861
56872
|
force: true
|
|
56862
56873
|
});
|
|
56863
|
-
console.info(
|
|
56874
|
+
console.info(`\u2713 Cleaned up template directory: ${templateDir}`);
|
|
56864
56875
|
} catch (cleanupError) {
|
|
56865
56876
|
console.warn("Failed to cleanup template directory:", cleanupError);
|
|
56866
56877
|
}
|
|
@@ -59954,11 +59965,11 @@ function createPlanningAndApprovalWorkflow() {
|
|
|
59954
59965
|
}
|
|
59955
59966
|
createPlanningAndApprovalWorkflow();
|
|
59956
59967
|
const workflowResearch = `
|
|
59957
|
-
##
|
|
59968
|
+
## \u{1F50D} **COMPREHENSIVE MASTRA WORKFLOW RESEARCH SUMMARY**
|
|
59958
59969
|
|
|
59959
59970
|
Based on extensive research of Mastra documentation and examples, here's essential information for building effective Mastra workflows:
|
|
59960
59971
|
|
|
59961
|
-
###
|
|
59972
|
+
### **\u{1F4CB} WORKFLOW FUNDAMENTALS**
|
|
59962
59973
|
|
|
59963
59974
|
**Core Components:**
|
|
59964
59975
|
- **\`createWorkflow()\`**: Main factory function that creates workflow instances
|
|
@@ -59982,7 +59993,7 @@ const workflow = createWorkflow({
|
|
|
59982
59993
|
.commit(); // CRITICAL: Makes workflow executable
|
|
59983
59994
|
\`\`\`
|
|
59984
59995
|
|
|
59985
|
-
###
|
|
59996
|
+
### **\u{1F527} STEP CREATION PATTERNS**
|
|
59986
59997
|
|
|
59987
59998
|
**Standard Step Definition:**
|
|
59988
59999
|
\`\`\`typescript
|
|
@@ -60006,7 +60017,7 @@ const myStep = createStep({
|
|
|
60006
60017
|
- \`requestContext\`: Runtime dependency injection context
|
|
60007
60018
|
- \`runCount\`: Number of times this step has run (useful for retries)
|
|
60008
60019
|
|
|
60009
|
-
###
|
|
60020
|
+
### **\u{1F504} CONTROL FLOW METHODS**
|
|
60010
60021
|
|
|
60011
60022
|
**Sequential Execution:**
|
|
60012
60023
|
- \`.then(step)\`: Execute steps one after another
|
|
@@ -60028,7 +60039,7 @@ const myStep = createStep({
|
|
|
60028
60039
|
**Data Transformation:**
|
|
60029
60040
|
- \`.map(({ inputData, getStepResult, getInitData }) => transformedData)\`: Transform data between steps
|
|
60030
60041
|
|
|
60031
|
-
###
|
|
60042
|
+
### **\u23F8\uFE0F SUSPEND & RESUME CAPABILITIES**
|
|
60032
60043
|
|
|
60033
60044
|
**For Human-in-the-Loop Workflows:**
|
|
60034
60045
|
\`\`\`typescript
|
|
@@ -60059,7 +60070,7 @@ if (result.status === "suspended") {
|
|
|
60059
60070
|
}
|
|
60060
60071
|
\`\`\`
|
|
60061
60072
|
|
|
60062
|
-
###
|
|
60073
|
+
### **\u{1F6E0}\uFE0F INTEGRATING AGENTS & TOOLS**
|
|
60063
60074
|
|
|
60064
60075
|
**Using Agents in Steps:**
|
|
60065
60076
|
\`\`\`typescript
|
|
@@ -60092,24 +60103,24 @@ const step = createStep({
|
|
|
60092
60103
|
});
|
|
60093
60104
|
\`\`\`
|
|
60094
60105
|
|
|
60095
|
-
###
|
|
60106
|
+
### **\u{1F5C2}\uFE0F PROJECT ORGANIZATION PATTERNS**
|
|
60096
60107
|
|
|
60097
60108
|
**MANDATORY Workflow Organization:**
|
|
60098
60109
|
Each workflow MUST be organized in its own dedicated folder with separated concerns:
|
|
60099
60110
|
|
|
60100
60111
|
\`\`\`
|
|
60101
60112
|
src/mastra/workflows/
|
|
60102
|
-
|
|
60103
|
-
|
|
60104
|
-
|
|
60105
|
-
|
|
60106
|
-
|
|
60107
|
-
|
|
60108
|
-
|
|
60109
|
-
|
|
60110
|
-
|
|
60111
|
-
|
|
60112
|
-
|
|
60113
|
+
\u251C\u2500\u2500 my-workflow-name/ # Kebab-case folder name
|
|
60114
|
+
\u2502 \u251C\u2500\u2500 types.ts # All Zod schemas and TypeScript types
|
|
60115
|
+
\u2502 \u251C\u2500\u2500 steps.ts # All individual step definitions
|
|
60116
|
+
\u2502 \u251C\u2500\u2500 workflow.ts # Main workflow composition and export
|
|
60117
|
+
\u2502 \u2514\u2500\u2500 utils.ts # Helper functions (if needed)
|
|
60118
|
+
\u251C\u2500\u2500 another-workflow/
|
|
60119
|
+
\u2502 \u251C\u2500\u2500 types.ts
|
|
60120
|
+
\u2502 \u251C\u2500\u2500 steps.ts
|
|
60121
|
+
\u2502 \u251C\u2500\u2500 workflow.ts
|
|
60122
|
+
\u2502 \u2514\u2500\u2500 utils.ts
|
|
60123
|
+
\u2514\u2500\u2500 index.ts # Export all workflows
|
|
60113
60124
|
\`\`\`
|
|
60114
60125
|
|
|
60115
60126
|
**CRITICAL File Organization Rules:**
|
|
@@ -60133,7 +60144,7 @@ export const mastra = new Mastra({
|
|
|
60133
60144
|
});
|
|
60134
60145
|
\`\`\`
|
|
60135
60146
|
|
|
60136
|
-
###
|
|
60147
|
+
### **\u{1F4E6} ESSENTIAL DEPENDENCIES**
|
|
60137
60148
|
|
|
60138
60149
|
**Required Packages:**
|
|
60139
60150
|
\`\`\`json
|
|
@@ -60150,7 +60161,7 @@ export const mastra = new Mastra({
|
|
|
60150
60161
|
- \`@ai-sdk/openai\`: For AI model integration
|
|
60151
60162
|
- \`ai\`: For AI SDK functionality
|
|
60152
60163
|
|
|
60153
|
-
###
|
|
60164
|
+
### **\u2705 WORKFLOW BEST PRACTICES**
|
|
60154
60165
|
|
|
60155
60166
|
**Schema Design:**
|
|
60156
60167
|
- Use descriptive property names in schemas
|
|
@@ -60172,7 +60183,7 @@ export const mastra = new Mastra({
|
|
|
60172
60183
|
- Access previous step results with \`getStepResult(stepInstance)\`
|
|
60173
60184
|
- Use \`getInitData()\` to access original workflow input
|
|
60174
60185
|
|
|
60175
|
-
###
|
|
60186
|
+
### **\u{1F680} EXECUTION PATTERNS**
|
|
60176
60187
|
|
|
60177
60188
|
**Running Workflows:**
|
|
60178
60189
|
\`\`\`typescript
|
|
@@ -60195,7 +60206,7 @@ run.watch((event) => console.log(event));
|
|
|
60195
60206
|
- \`"suspended"\`: Paused awaiting input
|
|
60196
60207
|
- \`"failed"\`: Encountered error
|
|
60197
60208
|
|
|
60198
|
-
###
|
|
60209
|
+
### **\u{1F517} ADVANCED FEATURES**
|
|
60199
60210
|
|
|
60200
60211
|
**Nested Workflows:**
|
|
60201
60212
|
- Use workflows as steps: \`.then(otherWorkflow)\`
|
|
@@ -60258,11 +60269,11 @@ CRITICAL WORKFLOW EXECUTION REQUIREMENTS:
|
|
|
60258
60269
|
MANDATORY WORKFLOW FOLDER STRUCTURE:
|
|
60259
60270
|
When ${context.action === "create" ? "creating a new workflow" : "editing a workflow"}, you MUST organize files as follows:
|
|
60260
60271
|
|
|
60261
|
-
|
|
60262
|
-
|
|
60263
|
-
|
|
60264
|
-
|
|
60265
|
-
|
|
60272
|
+
\u{1F4C1} src/mastra/workflows/${context.workflowName?.toLowerCase().replace(/[^a-z0-9]/g, "-") || "new-workflow"}/
|
|
60273
|
+
\u251C\u2500\u2500 \u{1F4C4} types.ts # All Zod schemas and TypeScript types
|
|
60274
|
+
\u251C\u2500\u2500 \u{1F4C4} steps.ts # All individual step definitions
|
|
60275
|
+
\u251C\u2500\u2500 \u{1F4C4} workflow.ts # Main workflow composition and export
|
|
60276
|
+
\u2514\u2500\u2500 \u{1F4C4} utils.ts # Helper functions (if needed)
|
|
60266
60277
|
|
|
60267
60278
|
CRITICAL FILE ORGANIZATION RULES:
|
|
60268
60279
|
- **ALWAYS create a dedicated folder** for the workflow in src/mastra/workflows/
|
|
@@ -60334,7 +60345,7 @@ ${context.resumeData ? `USER PROVIDED ANSWERS: ${JSON.stringify(context.resumeDa
|
|
|
60334
60345
|
},
|
|
60335
60346
|
validation: { instructions: `CRITICAL VALIDATION INSTRUCTIONS:
|
|
60336
60347
|
- When using the validateCode tool, ALWAYS pass the specific files you created or modified using the 'files' parameter
|
|
60337
|
-
- The tool uses a hybrid validation approach: fast syntax checking
|
|
60348
|
+
- The tool uses a hybrid validation approach: fast syntax checking \u2192 semantic type checking \u2192 ESLint
|
|
60338
60349
|
- This is much faster than full project compilation and only shows errors from your specific files
|
|
60339
60350
|
- Example: validateCode({ validationType: ['types', 'lint'], files: ['src/workflows/my-workflow.ts', 'src/agents/my-agent.ts'] })
|
|
60340
60351
|
- ALWAYS validate after creating or modifying files to ensure they compile correctly` }
|