@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
|
@@ -8,12 +8,12 @@ import { any, array, boolean, custom, discriminatedUnion, enum as enum$1, instan
|
|
|
8
8
|
import { isStandardSchemaWithJSON, toStandardSchema } from "@mastra/core/schema";
|
|
9
9
|
import { ZodFirstPartyTypeKind } from "zod/v3";
|
|
10
10
|
import { z as z$2 } from "zod";
|
|
11
|
+
import { inspect, promisify } from "util";
|
|
11
12
|
import { MESSAGE_EMBEDDING_CHARS_PER_TOKEN, MastraMemory, buildMessageEmbeddingRows, chunkMessageText, getMemoryTokenBoundary, getThreadOMMetadata, isAfterMemoryTokenBoundary, isThreadTitlePinned, loadMessageHistory, normalizeMessageHistoryConfig, parseMemoryRequestContext, resolveMaxChunkChars, setThreadOMMetadata, upsertMessageVectors } from "@mastra/core/memory";
|
|
12
13
|
import { Agent, MessageList, isSupportedLanguageModel, tryGenerateWithJsonFallback, tryStreamWithJsonFallback } from "@mastra/core/agent";
|
|
13
14
|
import { ErrorCategory, ErrorDomain, MastraError, classifyProviderError } from "@mastra/core/error";
|
|
14
15
|
import { ModelRouterLanguageModel, modelSupportsAttachments, modelSupportsTemperature, resolveModelConfig } from "@mastra/core/llm";
|
|
15
16
|
import { createTool } from "@mastra/core/tools";
|
|
16
|
-
import { inspect, promisify } from "util";
|
|
17
17
|
import { MASTRA_THREAD_ID_KEY, RequestContext } from "@mastra/core/request-context";
|
|
18
18
|
import { generateEmptyFromSchema } from "@mastra/core/utils";
|
|
19
19
|
import { InMemoryStore } from "@mastra/core/storage";
|
|
@@ -896,7 +896,7 @@ var require_jpeg = /* @__PURE__ */ __commonJSMin$1(((exports) => {
|
|
|
896
896
|
var str2arr = require_utils().str2arr;
|
|
897
897
|
var sliceEq = require_utils().sliceEq;
|
|
898
898
|
var exifOrientation = require_exif_orientation_parser();
|
|
899
|
-
var SIG_JPEG = str2arr("
|
|
899
|
+
var SIG_JPEG = str2arr("\u00FF\u00D8\u00FF");
|
|
900
900
|
var SIG_EXIF = str2arr("Exif\0\0");
|
|
901
901
|
var S_SIGNATURE = 0;
|
|
902
902
|
var S_MARKER_START = 1;
|
|
@@ -1042,7 +1042,7 @@ var require_png = /* @__PURE__ */ __commonJSMin$1(((exports) => {
|
|
|
1042
1042
|
var str2arr = require_utils().str2arr;
|
|
1043
1043
|
var sliceEq = require_utils().sliceEq;
|
|
1044
1044
|
var readUInt32BE = require_read_le_be().readUInt32BE;
|
|
1045
|
-
var SIG_PNG = str2arr("
|
|
1045
|
+
var SIG_PNG = str2arr("\u0089PNG\r\n\n");
|
|
1046
1046
|
var SIG_IHDR = str2arr("IHDR");
|
|
1047
1047
|
function PngParser() {
|
|
1048
1048
|
this.partial_buffer = /* @__PURE__ */ new Uint8Array(24);
|
|
@@ -8655,7 +8655,7 @@ function splitLines(text) {
|
|
|
8655
8655
|
else result.push(result.pop().slice(0, -1));
|
|
8656
8656
|
return result;
|
|
8657
8657
|
}
|
|
8658
|
-
// ../memory/dist/src-
|
|
8658
|
+
// ../memory/dist/src-TRQ73bGO.js
|
|
8659
8659
|
var __defProp$3 = Object.defineProperty;
|
|
8660
8660
|
var __exportAll = (all, no_symbols) => {
|
|
8661
8661
|
let target = {};
|
|
@@ -32876,14 +32876,14 @@ function getRetrievalInstructions(scope = "resource", customInstructions, search
|
|
|
32876
32876
|
The recall tool works across ALL of this user's conversation threads, not just the current one.
|
|
32877
32877
|
|
|
32878
32878
|
- 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.
|
|
32879
|
-
- Use \`mode: "messages"\` for original wording or details behind an observation
|
|
32879
|
+
- 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.
|
|
32880
32880
|
- 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.
|
|
32881
32881
|
|
|
32882
|
-
**If search results look irrelevant, do not give up.** Search only covers content that has been indexed
|
|
32882
|
+
**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
|
|
32883
32883
|
The recall tool works across ALL of this user's conversation threads, not just the current one.
|
|
32884
32884
|
|
|
32885
32885
|
- 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.
|
|
32886
|
-
- Use \`mode: "messages"\` when you know the thread
|
|
32886
|
+
- Use \`mode: "messages"\` when you know the thread \u2014 pass \`threadId\` to read another thread, or a \`cursor\` from an observation-group range.
|
|
32887
32887
|
|
|
32888
32888
|
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
|
|
32889
32889
|
The recall tool is limited to the current conversation thread.
|
|
@@ -32908,7 +32908,7 @@ When searches keep returning the same groups, often as already-in-context refere
|
|
|
32908
32908
|
"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.
|
|
32909
32909
|
|
|
32910
32910
|
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.` : "";
|
|
32911
|
-
const base = `## Recall
|
|
32911
|
+
const base = `## Recall \u2014 looking up source messages
|
|
32912
32912
|
|
|
32913
32913
|
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.
|
|
32914
32914
|
|
|
@@ -32919,13 +32919,13 @@ Groups marked \`kind="reflection"\` (rendered as \`_kind: reflection_\`) are los
|
|
|
32919
32919
|
|
|
32920
32920
|
### When to use recall
|
|
32921
32921
|
- The user asks you to **repeat, show, or reproduce** something from a past conversation
|
|
32922
|
-
- The user asks for **exact content**
|
|
32922
|
+
- The user asks for **exact content** \u2014 code, text, quotes, error messages, URLs, file paths, specific numbers
|
|
32923
32923
|
- 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)
|
|
32924
32924
|
- You want to **verify or expand on** an observation before responding
|
|
32925
32925
|
- 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
|
|
32926
32926
|
- 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
|
|
32927
32927
|
- Relevant details are missing, ambiguous, or conflicting in the current observations${isResource ? `
|
|
32928
|
-
- The user references another conversation that your observations don't cover
|
|
32928
|
+
- 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` : ""}
|
|
32929
32929
|
|
|
32930
32930
|
**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.
|
|
32931
32931
|
|
|
@@ -32960,17 +32960,17 @@ Each range has the format \`startId:endId\` where both are message IDs separated
|
|
|
32960
32960
|
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.
|
|
32961
32961
|
|
|
32962
32962
|
- 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.
|
|
32963
|
-
- Use \`partIndex\` with a cursor to fetch a single part at full detail
|
|
32963
|
+
- 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.
|
|
32964
32964
|
|
|
32965
32965
|
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.
|
|
32966
32966
|
|
|
32967
32967
|
### Following up on truncated parts
|
|
32968
32968
|
Low-detail results may include truncation hints like:
|
|
32969
|
-
\`[truncated
|
|
32969
|
+
\`[truncated \u2014 call recall cursor="..." partIndex=N detail="high" for full content]\`
|
|
32970
32970
|
|
|
32971
32971
|
**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.
|
|
32972
32972
|
|
|
32973
|
-
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
|
|
32973
|
+
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.
|
|
32974
32974
|
|
|
32975
32975
|
### When recall is NOT needed
|
|
32976
32976
|
- The user is asking for a high-level summary and your observations already cover it
|
|
@@ -33365,6 +33365,15 @@ function buildThreadMetadataFromExtractedValues(extractors, values) {
|
|
|
33365
33365
|
async function applyExtractorHooks(opts) {
|
|
33366
33366
|
const values = normalizeExtractedValues(opts.values) ?? {};
|
|
33367
33367
|
const failures = [...opts.failures ?? []];
|
|
33368
|
+
let recentMessages;
|
|
33369
|
+
let recentMessagesResolved = false;
|
|
33370
|
+
const resolveRecentMessages = () => {
|
|
33371
|
+
if (!recentMessagesResolved) {
|
|
33372
|
+
recentMessages = typeof opts.recentMessages === "function" ? opts.recentMessages() : opts.recentMessages;
|
|
33373
|
+
recentMessagesResolved = true;
|
|
33374
|
+
}
|
|
33375
|
+
return recentMessages;
|
|
33376
|
+
};
|
|
33368
33377
|
for (const extractor of opts.extractors) {
|
|
33369
33378
|
const isHook = extractor.mode === "hook";
|
|
33370
33379
|
const hasValue = Object.prototype.hasOwnProperty.call(values, extractor.slug);
|
|
@@ -33384,7 +33393,9 @@ async function applyExtractorHooks(opts) {
|
|
|
33384
33393
|
previous: isHook ? void 0 : opts.previousValues?.[extractor.slug],
|
|
33385
33394
|
current,
|
|
33386
33395
|
rawObservations: opts.rawObservations,
|
|
33387
|
-
recentMessages
|
|
33396
|
+
get recentMessages() {
|
|
33397
|
+
return resolveRecentMessages();
|
|
33398
|
+
},
|
|
33388
33399
|
mainAgent: opts.mainAgent,
|
|
33389
33400
|
memory: opts.memory,
|
|
33390
33401
|
sendSignal: opts.sendSignal,
|
|
@@ -34088,7 +34099,7 @@ const YEAR = String.raw`(?:19|20|21)\d{2}(?!\d)`;
|
|
|
34088
34099
|
const MERIDIEM = String.raw`(?:[AaPp]\.[Mm]\.|[AaPp][Mm]\b)`;
|
|
34089
34100
|
const TIME = String.raw`(?:,?\s+(?:at\s+)?\d{1,2}:\d{2}(?:\s*${MERIDIEM})?|\s+at\s+\d{1,2}\s*${MERIDIEM})`;
|
|
34090
34101
|
const QUALIFIER = String.raw`(?:(?:early|mid|late)[- ](?:to[- ](?:early|mid|late)[- ])?)`;
|
|
34091
|
-
const RANGE_SEP = String.raw`(?:\s*[
|
|
34102
|
+
const RANGE_SEP = String.raw`(?:\s*[\u2013\u2014]\s*|\s*-\s*|\s+(?:to|through|until)\s+)`;
|
|
34092
34103
|
/**
|
|
34093
34104
|
* Dates written into observation text that carry their own year, longest forms first:
|
|
34094
34105
|
* "Mar 1 - Mar 18, 2025", "May 27-28, 2023", "January 10, 2024 at 3:00 PM",
|
|
@@ -34389,15 +34400,15 @@ const SHORT_TOKEN_THRESHOLD = 3;
|
|
|
34389
34400
|
const KANA_CHARS_PER_TOKEN = 1.35;
|
|
34390
34401
|
const DEFAULT_LANGUAGE_CONFIGS = [
|
|
34391
34402
|
{
|
|
34392
|
-
pattern: /[
|
|
34403
|
+
pattern: /[\u00E4\u00F6\u00FC\u00DF\u1E9E]/i,
|
|
34393
34404
|
averageCharsPerToken: 2.6
|
|
34394
34405
|
},
|
|
34395
34406
|
{
|
|
34396
|
-
pattern: /[
|
|
34407
|
+
pattern: /[\u00E9\u00E8\u00EA\u00EB\u00E0\u00E2\u00EE\u00EF\u00F4\u00FB\u00F9\u00FC\u00FF\u00E7\u0153\u00E6\u00E1\u00ED\u00F3\u00FA\u00F1]/i,
|
|
34397
34408
|
averageCharsPerToken: 3
|
|
34398
34409
|
},
|
|
34399
34410
|
{
|
|
34400
|
-
pattern: /[
|
|
34411
|
+
pattern: /[\u0105\u0107\u0119\u0142\u0144\u00F3\u015B\u017A\u017C\u011B\u0161\u010D\u0159\u017E\u00FD\u016F\u00FA\u010F\u0165\u0148]/i,
|
|
34401
34412
|
averageCharsPerToken: 2.5
|
|
34402
34413
|
},
|
|
34403
34414
|
{
|
|
@@ -34485,10 +34496,10 @@ function sanitizeSurrogates(value) {
|
|
|
34485
34496
|
if (next >= 56320 && next <= 57343) {
|
|
34486
34497
|
sanitized += value.charAt(index) + value.charAt(index + 1);
|
|
34487
34498
|
index++;
|
|
34488
|
-
} else sanitized += "
|
|
34499
|
+
} else sanitized += "\uFFFD";
|
|
34489
34500
|
continue;
|
|
34490
34501
|
}
|
|
34491
|
-
sanitized += code >= 56320 && code <= 57343 ? "
|
|
34502
|
+
sanitized += code >= 56320 && code <= 57343 ? "\uFFFD" : value[index];
|
|
34492
34503
|
}
|
|
34493
34504
|
return sanitized;
|
|
34494
34505
|
}
|
|
@@ -34510,7 +34521,7 @@ function truncatePath(path) {
|
|
|
34510
34521
|
const headLength = 50;
|
|
34511
34522
|
const tailLength = 60;
|
|
34512
34523
|
const omitted = path.length - headLength - tailLength;
|
|
34513
|
-
return `${safeSlice(path, headLength)}
|
|
34524
|
+
return `${safeSlice(path, headLength)}\u2026[${omitted} chars; ${stablePathDigest(path)}]\u2026${safeTail(path, tailLength)}`;
|
|
34514
34525
|
}
|
|
34515
34526
|
function formatPath(parent, key, isArray) {
|
|
34516
34527
|
if (isArray) return truncatePath(`${parent}[${key}]`);
|
|
@@ -34619,7 +34630,7 @@ function selectOutlineEntries(entries, limits) {
|
|
|
34619
34630
|
const rendered = joinEntries(selected, marker);
|
|
34620
34631
|
if (fits(rendered, limits)) return rendered;
|
|
34621
34632
|
if (fits(marker, limits)) return marker;
|
|
34622
|
-
return fits("
|
|
34633
|
+
return fits("\u2026", limits) ? "\u2026" : "";
|
|
34623
34634
|
}
|
|
34624
34635
|
function indentPreview(value) {
|
|
34625
34636
|
return value.split("\n").map((line) => ` | ${line}`).join("\n");
|
|
@@ -34662,13 +34673,13 @@ function formatToolArgumentsForObserver(value, options) {
|
|
|
34662
34673
|
if (!isObjectLike$1(value)) {
|
|
34663
34674
|
if (typeof value !== "string" || value.length <= OBSERVER_TOOL_ARGUMENT_INLINE_STRING_MAX_CHARS) {
|
|
34664
34675
|
const primitive = formatPrimitive(value);
|
|
34665
|
-
return fits(primitive, limits) ? primitive : fits("
|
|
34676
|
+
return fits(primitive, limits) ? primitive : fits("\u2026", limits) ? "\u2026" : "";
|
|
34666
34677
|
}
|
|
34667
34678
|
const summary = `<string, ${value.length} characters; preview size-limited>`;
|
|
34668
34679
|
const rendered = appendWithinBudget(summary, formatPreview("preview", value, limits, summary), limits);
|
|
34669
34680
|
if (rendered) return rendered;
|
|
34670
34681
|
if (fits(summary, limits)) return summary;
|
|
34671
|
-
return fits("
|
|
34682
|
+
return fits("\u2026", limits) ? "\u2026" : "";
|
|
34672
34683
|
}
|
|
34673
34684
|
const outline = [];
|
|
34674
34685
|
const previews = [];
|
|
@@ -34912,24 +34923,24 @@ function formatToolResultForObserver(value, options) {
|
|
|
34912
34923
|
const OBSERVER_EXTRACTION_INSTRUCTIONS = `CRITICAL: DISTINGUISH USER ASSERTIONS FROM QUESTIONS
|
|
34913
34924
|
|
|
34914
34925
|
When the user TELLS you something about themselves, mark it as an assertion:
|
|
34915
|
-
- "I have two kids"
|
|
34916
|
-
- "I work at Acme Corp"
|
|
34917
|
-
- "I graduated in 2019"
|
|
34926
|
+
- "I have two kids" \u2192 \u{1F534} (14:30) User stated has two kids
|
|
34927
|
+
- "I work at Acme Corp" \u2192 \u{1F534} (14:31) User stated works at Acme Corp
|
|
34928
|
+
- "I graduated in 2019" \u2192 \u{1F534} (14:32) User stated graduated in 2019
|
|
34918
34929
|
|
|
34919
34930
|
When the user ASKS about something, mark it as a question/request:
|
|
34920
|
-
- "Can you help me with X?"
|
|
34921
|
-
- "What's the best way to do Y?"
|
|
34931
|
+
- "Can you help me with X?" \u2192 \u{1F534} (15:00) User asked help with X
|
|
34932
|
+
- "What's the best way to do Y?" \u2192 \u{1F534} (15:01) User asked best way to do Y
|
|
34922
34933
|
|
|
34923
34934
|
Distinguish between QUESTIONS and STATEMENTS OF INTENT:
|
|
34924
|
-
- "Can you recommend..."
|
|
34925
|
-
- "I'm looking forward to [doing X]"
|
|
34926
|
-
- "I need to [do X]"
|
|
34935
|
+
- "Can you recommend..." \u2192 Question (extract as "User asked...")
|
|
34936
|
+
- "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)")
|
|
34937
|
+
- "I need to [do X]" \u2192 Statement of intent (extract as "User stated they need to [do X] (again, add date if mentioned)")
|
|
34927
34938
|
|
|
34928
34939
|
STATE CHANGES AND UPDATES:
|
|
34929
34940
|
When a user indicates they are changing something, frame it as a state change that supersedes previous information:
|
|
34930
|
-
- "I'm going to start doing X instead of Y"
|
|
34931
|
-
- "I'm switching from A to B"
|
|
34932
|
-
- "I moved my stuff to the new place"
|
|
34941
|
+
- "I'm going to start doing X instead of Y" \u2192 "User will start doing X (changing from Y)"
|
|
34942
|
+
- "I'm switching from A to B" \u2192 "User is switching from A to B"
|
|
34943
|
+
- "I moved my stuff to the new place" \u2192 "User moved their stuff to the new place (no longer at previous location)"
|
|
34933
34944
|
|
|
34934
34945
|
If the new state contradicts or updates previous information, make that explicit:
|
|
34935
34946
|
- BAD: "User plans to use the new method"
|
|
@@ -35020,11 +35031,11 @@ BAD: User got something.
|
|
|
35020
35031
|
GOOD: User purchased / received / was given something. (be specific)
|
|
35021
35032
|
|
|
35022
35033
|
Common clarifications:
|
|
35023
|
-
- "getting" something regularly
|
|
35024
|
-
- "getting" something once
|
|
35025
|
-
- "got"
|
|
35026
|
-
- "signed up"
|
|
35027
|
-
- "stopped getting"
|
|
35034
|
+
- "getting" something regularly \u2192 "subscribed to" or "enrolled in"
|
|
35035
|
+
- "getting" something once \u2192 "purchased" or "acquired"
|
|
35036
|
+
- "got" \u2192 "purchased", "received as gift", "was given", "picked up"
|
|
35037
|
+
- "signed up" \u2192 "enrolled in", "registered for", "subscribed to"
|
|
35038
|
+
- "stopped getting" \u2192 "canceled", "unsubscribed from", "discontinued"
|
|
35028
35039
|
|
|
35029
35040
|
When the assistant interprets or confirms the user's vague language, prefer the assistant's precise terminology.
|
|
35030
35041
|
|
|
@@ -35109,16 +35120,16 @@ AVOIDING REPETITIVE OBSERVATIONS:
|
|
|
35109
35120
|
- Do NOT repeat the same observation across multiple turns if there is no new information.
|
|
35110
35121
|
- 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.
|
|
35111
35122
|
|
|
35112
|
-
Example
|
|
35113
|
-
*
|
|
35114
|
-
*
|
|
35115
|
-
*
|
|
35123
|
+
Example \u2014 BAD (repetitive):
|
|
35124
|
+
* \u{1F7E1} (14:30) Agent used view tool on src/auth.ts
|
|
35125
|
+
* \u{1F7E1} (14:31) Agent used view tool on src/users.ts
|
|
35126
|
+
* \u{1F7E1} (14:32) Agent used view tool on src/routes.ts
|
|
35116
35127
|
|
|
35117
|
-
Example
|
|
35118
|
-
*
|
|
35119
|
-
* -> viewed src/auth.ts
|
|
35120
|
-
* -> viewed src/users.ts
|
|
35121
|
-
* -> viewed src/routes.ts
|
|
35128
|
+
Example \u2014 GOOD (grouped):
|
|
35129
|
+
* \u{1F7E1} (14:30) Agent browsed source files for auth flow
|
|
35130
|
+
* -> viewed src/auth.ts \u2014 found token validation logic
|
|
35131
|
+
* -> viewed src/users.ts \u2014 found user lookup by email
|
|
35132
|
+
* -> viewed src/routes.ts \u2014 found middleware chain
|
|
35122
35133
|
|
|
35123
35134
|
Only add a new observation for a repeated action if the NEW result changes the picture.
|
|
35124
35135
|
|
|
@@ -35131,29 +35142,29 @@ COMPLETION TRACKING:
|
|
|
35131
35142
|
Completion observations are not just summaries. They are explicit memory signals to the assistant that a task, question, or subtask has been resolved.
|
|
35132
35143
|
Without clear completion markers, the assistant may forget that work is already finished and may repeat, reopen, or continue an already-completed task.
|
|
35133
35144
|
|
|
35134
|
-
Use
|
|
35145
|
+
Use \u2705 to answer: "What exactly is now done?"
|
|
35135
35146
|
Choose completion observations that help the assistant know what is finished and should not be reworked unless new information appears.
|
|
35136
35147
|
|
|
35137
|
-
Use
|
|
35148
|
+
Use \u2705 when:
|
|
35138
35149
|
- The user explicitly confirms something worked or was answered ("thanks, that fixed it", "got it", "perfect")
|
|
35139
35150
|
- The assistant provided a definitive, complete answer to a factual question and the user moved on
|
|
35140
35151
|
- A multi-step task reached its stated goal
|
|
35141
35152
|
- The user acknowledged receipt of requested information
|
|
35142
35153
|
- A concrete subtask, fix, deliverable, or implementation step became complete during ongoing work
|
|
35143
35154
|
|
|
35144
|
-
Do NOT use
|
|
35145
|
-
- The assistant merely responded
|
|
35155
|
+
Do NOT use \u2705 when:
|
|
35156
|
+
- The assistant merely responded \u2014 the user might follow up with corrections
|
|
35146
35157
|
- The topic is paused but not resolved ("I'll try that later")
|
|
35147
35158
|
- The user's reaction is ambiguous
|
|
35148
35159
|
|
|
35149
35160
|
FORMAT:
|
|
35150
35161
|
As a sub-bullet under the related observation group:
|
|
35151
|
-
*
|
|
35162
|
+
* \u{1F534} (14:30) User asked how to configure auth middleware
|
|
35152
35163
|
* -> Agent explained JWT setup with code example
|
|
35153
|
-
*
|
|
35164
|
+
* \u2705 User confirmed auth is working
|
|
35154
35165
|
|
|
35155
35166
|
Or as a standalone observation when closing out a broader task:
|
|
35156
|
-
*
|
|
35167
|
+
* \u2705 (14:45) Auth configuration task completed \u2014 user confirmed middleware is working
|
|
35157
35168
|
|
|
35158
35169
|
Completion observations should be terse but specific about WHAT was completed.
|
|
35159
35170
|
Prefer concrete resolved outcomes over abstract workflow status so the assistant remembers what is already done.`;
|
|
@@ -35170,28 +35181,28 @@ buildObserverOutputFormat();
|
|
|
35170
35181
|
*/
|
|
35171
35182
|
function buildObserverOutputFormat(extractors) {
|
|
35172
35183
|
return `Use priority levels:
|
|
35173
|
-
-
|
|
35174
|
-
-
|
|
35175
|
-
-
|
|
35176
|
-
-
|
|
35184
|
+
- \u{1F534} High: explicit user facts, preferences, unresolved goals, critical context
|
|
35185
|
+
- \u{1F7E1} Medium: project details, learned information, tool results
|
|
35186
|
+
- \u{1F7E2} Low: minor details, uncertain observations
|
|
35187
|
+
- \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
|
|
35177
35188
|
|
|
35178
35189
|
Group related observations (like tool sequences) by indenting:
|
|
35179
|
-
*
|
|
35190
|
+
* \u{1F534} (14:33) Agent debugging auth issue
|
|
35180
35191
|
* -> ran git status, found 3 modified files
|
|
35181
35192
|
* -> viewed auth.ts:45-60, found missing null check
|
|
35182
35193
|
* -> applied fix, tests now pass
|
|
35183
|
-
*
|
|
35194
|
+
* \u2705 Tests passing, auth issue resolved
|
|
35184
35195
|
|
|
35185
35196
|
Group observations by date. Within a date, list observations in the order the events happened (not by importance), each with 24-hour time.
|
|
35186
35197
|
|
|
35187
35198
|
<observations>
|
|
35188
35199
|
Date: Dec 4, 2025
|
|
35189
|
-
*
|
|
35190
|
-
*
|
|
35191
|
-
*
|
|
35200
|
+
* \u{1F534} (14:30) User prefers direct answers
|
|
35201
|
+
* \u{1F534} (14:31) Working on feature X
|
|
35202
|
+
* \u{1F7E1} (14:32) User might prefer dark mode
|
|
35192
35203
|
|
|
35193
35204
|
Date: Dec 5, 2025
|
|
35194
|
-
*
|
|
35205
|
+
* \u{1F534} (09:15) Continued work on feature X
|
|
35195
35206
|
</observations>
|
|
35196
35207
|
|
|
35197
35208
|
${buildExtractorOutputSections(extractors ?? []) || (extractors === void 0 ? `
|
|
@@ -35221,9 +35232,9 @@ const OBSERVER_GUIDELINES = `- Be specific enough for the assistant to act on
|
|
|
35221
35232
|
- If the agent calls tools, observe what was called, why, and what was learned
|
|
35222
35233
|
- When observing files with line numbers, include the line number if useful
|
|
35223
35234
|
- If the agent provides a detailed response, observe the contents so it could be repeated
|
|
35224
|
-
- Make sure you start each observation with a priority emoji (
|
|
35225
|
-
- Capture the user's words closely
|
|
35226
|
-
- Treat
|
|
35235
|
+
- Make sure you start each observation with a priority emoji (\u{1F534}, \u{1F7E1}, \u{1F7E2}) or a completion marker (\u2705)
|
|
35236
|
+
- 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}
|
|
35237
|
+
- Treat \u2705 as a memory signal that tells the assistant something is finished and should not be repeated unless new information changes it
|
|
35227
35238
|
- Make completion observations answer "What exactly is now done?"
|
|
35228
35239
|
- Prefer concrete resolved outcomes over meta-level workflow or bookkeeping updates
|
|
35229
35240
|
- When multiple concrete things were completed, capture the concrete completed work rather than collapsing it into a vague progress summary
|
|
@@ -35277,8 +35288,8 @@ For multi-thread output, wrap each thread's observations like this:
|
|
|
35277
35288
|
<observations>
|
|
35278
35289
|
<thread id="thread_id_1">
|
|
35279
35290
|
Date: Dec 4, 2025
|
|
35280
|
-
*
|
|
35281
|
-
*
|
|
35291
|
+
* \u{1F534} (14:30) User prefers direct answers
|
|
35292
|
+
* \u{1F534} (14:31) Working on feature X${currentTaskEnabled ? `
|
|
35282
35293
|
|
|
35283
35294
|
<current-task>
|
|
35284
35295
|
What the agent is currently working on in this thread
|
|
@@ -35291,7 +35302,7 @@ Hint for the agent's next message in this thread
|
|
|
35291
35302
|
|
|
35292
35303
|
<thread id="thread_id_2">
|
|
35293
35304
|
Date: Dec 5, 2025
|
|
35294
|
-
*
|
|
35305
|
+
* \u{1F534} (09:15) User asked about deployment${currentTaskEnabled ? `
|
|
35295
35306
|
|
|
35296
35307
|
<current-task>
|
|
35297
35308
|
Current task for this thread
|
|
@@ -36122,7 +36133,7 @@ function sanitizeObservationLines(observations) {
|
|
|
36122
36133
|
const lines = observations.split("\n");
|
|
36123
36134
|
let changed = false;
|
|
36124
36135
|
for (let i = 0; i < lines.length; i++) if (lines[i].length > MAX_OBSERVATION_LINE_CHARS) {
|
|
36125
|
-
lines[i] = safeSlice(lines[i], MAX_OBSERVATION_LINE_CHARS) + "
|
|
36136
|
+
lines[i] = safeSlice(lines[i], MAX_OBSERVATION_LINE_CHARS) + " \u2026 [truncated]";
|
|
36126
36137
|
changed = true;
|
|
36127
36138
|
}
|
|
36128
36139
|
return changed ? lines.join("\n") : observations;
|
|
@@ -36320,8 +36331,8 @@ function describeDegenerateOutput(text, snippetChars = 400) {
|
|
|
36320
36331
|
*/
|
|
36321
36332
|
function optimizeObservationsForContext(observations) {
|
|
36322
36333
|
let optimized = stripEphemeralAnchorIds(observations);
|
|
36323
|
-
optimized = optimized.replace(
|
|
36324
|
-
optimized = optimized.replace(
|
|
36334
|
+
optimized = optimized.replace(/\uD83D\uDFE1\s*/g, "");
|
|
36335
|
+
optimized = optimized.replace(/\uD83D\uDFE2\s*/g, "");
|
|
36325
36336
|
optimized = optimized.replace(/\s*->\s*/g, " ");
|
|
36326
36337
|
optimized = optimized.replace(/ +/g, " ");
|
|
36327
36338
|
optimized = optimized.replace(/\n{3,}/g, "\n\n");
|
|
@@ -37277,7 +37288,7 @@ async function resolveImageDimensionsAsync(part) {
|
|
|
37277
37288
|
const url = resolveHttpAssetUrl(getObjectValue(part, "image") ?? getObjectValue(part, "data"));
|
|
37278
37289
|
if (!url) return existing;
|
|
37279
37290
|
try {
|
|
37280
|
-
const probeImageSize = (await import("./probe-image-size-
|
|
37291
|
+
const probeImageSize = (await import("./probe-image-size-DZvSdjzK.js").then((m) => /* @__PURE__ */ __toESM$1(m.default, 1))).default;
|
|
37281
37292
|
const probed = await probeImageSize(url, {
|
|
37282
37293
|
open_timeout: REMOTE_IMAGE_PROBE_TIMEOUT_MS,
|
|
37283
37294
|
response_timeout: REMOTE_IMAGE_PROBE_TIMEOUT_MS,
|
|
@@ -38599,8 +38610,8 @@ const updateWorkingMemoryTool = (memoryConfig) => {
|
|
|
38599
38610
|
}
|
|
38600
38611
|
const usesMergeSemantics = Boolean(schema);
|
|
38601
38612
|
const useStateSignals = memoryConfig?.workingMemory?.useStateSignals === true;
|
|
38602
|
-
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
|
|
38603
|
-
const description = schema ? useStateSignals ? `${stateSignalsPreamble} Data is merged with existing memory
|
|
38613
|
+
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.`;
|
|
38614
|
+
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.`;
|
|
38604
38615
|
return createTool({
|
|
38605
38616
|
id: "update-working-memory",
|
|
38606
38617
|
description,
|
|
@@ -39610,8 +39621,8 @@ async function pageGroups({ om, threadId, resourceId, groupId, recordId, directi
|
|
|
39610
39621
|
})).count > 0;
|
|
39611
39622
|
const hasLater = direction === "before" || hasMore;
|
|
39612
39623
|
const newer = hasLater ? null : await newerMessagesNote(page.at(-1).group, countNewerMessages, pagingThreadId);
|
|
39613
|
-
text.unshift(hasEarlier ?
|
|
39614
|
-
text.push(hasLater ?
|
|
39624
|
+
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");
|
|
39625
|
+
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");
|
|
39615
39626
|
text.unshift(`### Observation page\nThread: ${threadTitle || "(untitled)"}\nShowing ${page.length} groups ${requestedDirection === void 0 ? "starting at" : `strictly ${direction}`} \`${groupId}\` (oldest first).`);
|
|
39616
39627
|
return {
|
|
39617
39628
|
results: text.join("\n\n"),
|
|
@@ -39797,7 +39808,7 @@ async function listThreadsForResource({ memory, resourceId, currentThreadId, pag
|
|
|
39797
39808
|
const title = thread.title || "(untitled)";
|
|
39798
39809
|
const updated = formatTimestamp(thread.updatedAt);
|
|
39799
39810
|
const created = formatTimestamp(thread.createdAt);
|
|
39800
|
-
const marker = isCurrent ? "
|
|
39811
|
+
const marker = isCurrent ? " \u2190 current" : "";
|
|
39801
39812
|
lines.push(`- **${title}**${marker}`);
|
|
39802
39813
|
lines.push(` id: ${thread.id}`);
|
|
39803
39814
|
lines.push(` updated: ${updated} | created: ${created}`);
|
|
@@ -39976,7 +39987,7 @@ async function searchMessagesForResource({ memory, om, resourceId, currentThread
|
|
|
39976
39987
|
const groupLine = match.groupId ? `- observation group: ${groupCursor(match.groupId, match.recordId)}` : void 0;
|
|
39977
39988
|
const scoreLine = `- score: ${match.score.toFixed(2)}`;
|
|
39978
39989
|
const prev = i > 0 ? ordered[i - 1].match : void 0;
|
|
39979
|
-
if (om && prev?.groupId && match.groupId && prev.threadId === match.threadId) sections.push(
|
|
39990
|
+
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`);
|
|
39980
39991
|
if (suppression) {
|
|
39981
39992
|
sections.push(`${groupLine}\n thread: ${match.threadId}; ${suppression}`);
|
|
39982
39993
|
continue;
|
|
@@ -40531,7 +40542,7 @@ async function recallAttachmentView({ memory, threadId, resourceId, cursor, part
|
|
|
40531
40542
|
const partType = rawPart?.type;
|
|
40532
40543
|
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.` };
|
|
40533
40544
|
const resolvedAttachment = resolveViewableAttachment(rawPart);
|
|
40534
|
-
if ("note" in resolvedAttachment) return { messages: `${formatAttachmentPart(partType, rawPart)}
|
|
40545
|
+
if ("note" in resolvedAttachment) return { messages: `${formatAttachmentPart(partType, rawPart)} \u2014 ${resolvedAttachment.note}` };
|
|
40535
40546
|
return { content: [{
|
|
40536
40547
|
type: "text",
|
|
40537
40548
|
text: formatAttachmentPart(partType, rawPart)
|
|
@@ -40934,7 +40945,7 @@ const recallTool = (_memoryConfig, options) => {
|
|
|
40934
40945
|
if (!thread) return { error: "Could not resolve current thread." };
|
|
40935
40946
|
if (isResourceScope && resourceId && thread.resourceId !== resourceId) throw new Error("Thread does not belong to the active resource");
|
|
40936
40947
|
return {
|
|
40937
|
-
threads: `- **${thread.title || "(untitled)"}**
|
|
40948
|
+
threads: `- **${thread.title || "(untitled)"}** \u2190 current\n id: ${thread.id}\n updated: ${formatTimestamp(thread.updatedAt)} | created: ${formatTimestamp(thread.createdAt)}`,
|
|
40938
40949
|
count: 1,
|
|
40939
40950
|
page: 0,
|
|
40940
40951
|
hasMore: false
|
|
@@ -41685,9 +41696,9 @@ const suggestedResponseInstructions = `Hint for the agent's immediate next messa
|
|
|
41685
41696
|
- "The assistant should wait for the user to respond before continuing."
|
|
41686
41697
|
- Call the view tool on src/example.ts to continue debugging.`;
|
|
41687
41698
|
const threadTitleInstructions = `A short, noun-phrase title for this conversation (2-5 words). Examples:
|
|
41688
|
-
- "Auth bug fix"
|
|
41689
|
-
- "Dark mode toggle"
|
|
41690
|
-
- "Deployment pipeline setup"
|
|
41699
|
+
- "Auth bug fix" \u2014 not "Fixing the auth bug"
|
|
41700
|
+
- "Dark mode toggle" \u2014 not "User wants dark mode toggle added"
|
|
41701
|
+
- "Deployment pipeline setup" \u2014 not "Setting up deployment pipeline for project"
|
|
41691
41702
|
Only update when the topic meaningfully changes.`;
|
|
41692
41703
|
function createCurrentTaskExtractor() {
|
|
41693
41704
|
return new Extractor({
|
|
@@ -42757,7 +42768,7 @@ var SyncObservationStrategy = class extends ObservationStrategy {
|
|
|
42757
42768
|
failures: result.extractionFailures,
|
|
42758
42769
|
previousValues: this.priorExtractedValues,
|
|
42759
42770
|
rawObservations: result.observations,
|
|
42760
|
-
recentMessages: formatMessagesForObserver(this.opts.messages, {
|
|
42771
|
+
recentMessages: () => formatMessagesForObserver(this.opts.messages, {
|
|
42761
42772
|
maxPartLength: 500,
|
|
42762
42773
|
timeZone: this.opts.record.observedTimezone
|
|
42763
42774
|
}),
|
|
@@ -42981,7 +42992,7 @@ var AsyncBufferObservationStrategy = class extends ObservationStrategy {
|
|
|
42981
42992
|
failures: result.extractionFailures,
|
|
42982
42993
|
previousValues: this.priorExtractedValues,
|
|
42983
42994
|
rawObservations: result.observations,
|
|
42984
|
-
recentMessages: formatMessagesForObserver(messages, {
|
|
42995
|
+
recentMessages: () => formatMessagesForObserver(messages, {
|
|
42985
42996
|
maxPartLength: 500,
|
|
42986
42997
|
timeZone: this.opts.record.observedTimezone
|
|
42987
42998
|
}),
|
|
@@ -43410,7 +43421,7 @@ var ResourceScopedObservationStrategy = class extends ObservationStrategy {
|
|
|
43410
43421
|
failures: result.extractionFailures,
|
|
43411
43422
|
previousValues,
|
|
43412
43423
|
rawObservations: result.observations,
|
|
43413
|
-
recentMessages: formatMessagesForObserver(threadMessages, {
|
|
43424
|
+
recentMessages: () => formatMessagesForObserver(threadMessages, {
|
|
43414
43425
|
maxPartLength: 500,
|
|
43415
43426
|
timeZone: this.opts.record.observedTimezone
|
|
43416
43427
|
}),
|
|
@@ -43739,7 +43750,7 @@ var ObservationStep = class {
|
|
|
43739
43750
|
}
|
|
43740
43751
|
/** Step context from prepare(). Throws if prepare() hasn't been called. */
|
|
43741
43752
|
get context() {
|
|
43742
|
-
if (!this._context) throw new Error("Step not prepared yet
|
|
43753
|
+
if (!this._context) throw new Error("Step not prepared yet \u2014 call prepare() first");
|
|
43743
43754
|
return this._context;
|
|
43744
43755
|
}
|
|
43745
43756
|
/**
|
|
@@ -44159,7 +44170,7 @@ var ObservationStep = class {
|
|
|
44159
44170
|
const messagesToSeal = messageToSeal ? [messageToSeal] : [];
|
|
44160
44171
|
this.turn.abortSignal?.throwIfAborted();
|
|
44161
44172
|
om.sealMessagesForBuffering(messagesToSeal);
|
|
44162
|
-
if (this.seededResponseMessage) omDebug("[OM:observe] skipping response-id rotation
|
|
44173
|
+
if (this.seededResponseMessage) omDebug("[OM:observe] skipping response-id rotation \u2014 step-0 seeded response message holds the active id");
|
|
44163
44174
|
else try {
|
|
44164
44175
|
await this.turn.hooks?.onSyncObservationComplete?.();
|
|
44165
44176
|
} catch (error) {
|
|
@@ -44309,12 +44320,12 @@ var ObservationTurn = class {
|
|
|
44309
44320
|
messageList;
|
|
44310
44321
|
/** The current cached record. Refreshed after mutations (activate/observe/reflect). */
|
|
44311
44322
|
get record() {
|
|
44312
|
-
if (!this._record) throw new Error("Turn not started
|
|
44323
|
+
if (!this._record) throw new Error("Turn not started \u2014 call start() first");
|
|
44313
44324
|
return this._record;
|
|
44314
44325
|
}
|
|
44315
44326
|
/** The context loaded during start(). */
|
|
44316
44327
|
get context() {
|
|
44317
|
-
if (!this._context) throw new Error("Turn not started
|
|
44328
|
+
if (!this._context) throw new Error("Turn not started \u2014 call start() first");
|
|
44318
44329
|
return this._context;
|
|
44319
44330
|
}
|
|
44320
44331
|
/** Whether the turn has been ended and can no longer accept steps. */
|
|
@@ -44383,7 +44394,7 @@ var ObservationTurn = class {
|
|
|
44383
44394
|
* (its output messages will be saved at the start of the new step's prepare()).
|
|
44384
44395
|
*/
|
|
44385
44396
|
step(stepNumber) {
|
|
44386
|
-
if (!this._started) throw new Error("Turn not started
|
|
44397
|
+
if (!this._started) throw new Error("Turn not started \u2014 call start() first");
|
|
44387
44398
|
if (this._ended) throw new Error("Turn already ended");
|
|
44388
44399
|
this._currentStep = new ObservationStep(this, stepNumber);
|
|
44389
44400
|
return this._currentStep;
|
|
@@ -44604,8 +44615,8 @@ When consolidating observations:
|
|
|
44604
44615
|
- 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
|
|
44605
44616
|
- Prefer many short factual lines over prose summaries. Do not replace facts with generalities like "discussed travel plans"
|
|
44606
44617
|
- Combine related items where it makes sense (e.g., "agent called view tool 5 times on file x")
|
|
44607
|
-
- Preserve
|
|
44608
|
-
- Preserve the concrete resolved outcome captured by
|
|
44618
|
+
- Preserve \u2705 completion markers \u2014 they are memory signals that tell the assistant what is already resolved and help prevent repeated work
|
|
44619
|
+
- Preserve the concrete resolved outcome captured by \u2705 markers so the assistant knows what exactly is done
|
|
44609
44620
|
- Condense the wording of older observations more than recent ones, but keep their facts
|
|
44610
44621
|
|
|
44611
44622
|
CRITICAL: USER ASSERTIONS vs QUESTIONS
|
|
@@ -44627,23 +44638,23 @@ When observations contain <thread id="..."> sections:
|
|
|
44627
44638
|
Example input:
|
|
44628
44639
|
<thread id="thread-1">
|
|
44629
44640
|
Date: Dec 4, 2025
|
|
44630
|
-
*
|
|
44631
|
-
*
|
|
44641
|
+
* \u{1F534} (14:30) User prefers TypeScript
|
|
44642
|
+
* \u{1F7E1} (14:35) Working on auth feature
|
|
44632
44643
|
</thread>
|
|
44633
44644
|
<thread id="thread-2">
|
|
44634
44645
|
Date: Dec 4, 2025
|
|
44635
|
-
*
|
|
44636
|
-
*
|
|
44646
|
+
* \u{1F534} (15:00) User prefers TypeScript
|
|
44647
|
+
* \u{1F7E1} (15:05) Debugging API endpoint
|
|
44637
44648
|
</thread>
|
|
44638
44649
|
|
|
44639
44650
|
Example output (consolidated):
|
|
44640
44651
|
Date: Dec 4, 2025
|
|
44641
|
-
*
|
|
44652
|
+
* \u{1F534} (14:30) User prefers TypeScript
|
|
44642
44653
|
<thread id="thread-1">
|
|
44643
|
-
*
|
|
44654
|
+
* \u{1F7E1} (14:35) Working on auth feature
|
|
44644
44655
|
</thread>
|
|
44645
44656
|
<thread id="thread-2">
|
|
44646
|
-
*
|
|
44657
|
+
* \u{1F7E1} (15:05) Debugging API endpoint
|
|
44647
44658
|
</thread>
|
|
44648
44659
|
|
|
44649
44660
|
=== OUTPUT FORMAT ===
|
|
@@ -44674,8 +44685,8 @@ Please re-process with slightly more compression:
|
|
|
44674
44685
|
- Memory is getting long - use a more condensed style throughout
|
|
44675
44686
|
- Combine related items more aggressively but do not lose important specific details of names, places, events, and people
|
|
44676
44687
|
- 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
|
|
44677
|
-
- Preserve
|
|
44678
|
-
- Preserve the concrete resolved outcome captured by
|
|
44688
|
+
- Preserve \u2705 completion markers \u2014 they are memory signals that tell the assistant what is already resolved and help prevent repeated work
|
|
44689
|
+
- Preserve the concrete resolved outcome captured by \u2705 markers so the assistant knows what exactly is done
|
|
44679
44690
|
|
|
44680
44691
|
Aim for a 8/10 detail level.
|
|
44681
44692
|
`,
|
|
@@ -44691,8 +44702,8 @@ Please re-process with much more aggressive compression:
|
|
|
44691
44702
|
- Combine related items aggressively but do not lose important specific details of names, places, events, and people
|
|
44692
44703
|
- 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
|
|
44693
44704
|
- If the same file or module is mentioned across many observations, merge into one entry covering the full arc
|
|
44694
|
-
- Preserve
|
|
44695
|
-
- Preserve the concrete resolved outcome captured by
|
|
44705
|
+
- Preserve \u2705 completion markers \u2014 they are memory signals that tell the assistant what is already resolved and help prevent repeated work
|
|
44706
|
+
- Preserve the concrete resolved outcome captured by \u2705 markers so the assistant knows what exactly is done
|
|
44696
44707
|
- Remove redundant information and merge overlapping observations
|
|
44697
44708
|
|
|
44698
44709
|
Aim for a 6/10 detail level.
|
|
@@ -44703,14 +44714,14 @@ Aim for a 6/10 detail level.
|
|
|
44703
44714
|
Your previous reflections have failed to compress sufficiently after multiple attempts.
|
|
44704
44715
|
|
|
44705
44716
|
Please re-process with maximum compression:
|
|
44706
|
-
- Summarize the oldest observations (first 50-70%) into brief high-level paragraphs
|
|
44717
|
+
- Summarize the oldest observations (first 50-70%) into brief high-level paragraphs \u2014 only key facts, decisions, and outcomes
|
|
44707
44718
|
- For the most recent observations (last 30-50%), retain important details but still use a condensed style
|
|
44708
|
-
- Ruthlessly merge related observations
|
|
44709
|
-
- Combine all tool call sequences (file views, searches, edits, builds) into outcome-only summaries
|
|
44710
|
-
- Drop procedural details (tool calls, retries, intermediate steps)
|
|
44719
|
+
- Ruthlessly merge related observations \u2014 if 10 observations are about the same topic, combine into 1-2 lines
|
|
44720
|
+
- Combine all tool call sequences (file views, searches, edits, builds) into outcome-only summaries \u2014 drop individual steps entirely
|
|
44721
|
+
- Drop procedural details (tool calls, retries, intermediate steps) \u2014 keep only final outcomes
|
|
44711
44722
|
- Drop observations that are no longer relevant or have been superseded by newer information
|
|
44712
|
-
- Preserve
|
|
44713
|
-
- Preserve the concrete resolved outcome captured by
|
|
44723
|
+
- Preserve \u2705 completion markers \u2014 they are memory signals that tell the assistant what is already resolved and help prevent repeated work
|
|
44724
|
+
- Preserve the concrete resolved outcome captured by \u2705 markers so the assistant knows what exactly is done
|
|
44714
44725
|
- Preserve: names, dates, decisions, errors, user preferences, and architectural choices
|
|
44715
44726
|
|
|
44716
44727
|
Aim for a 4/10 detail level.
|
|
@@ -44721,14 +44732,14 @@ Aim for a 4/10 detail level.
|
|
|
44721
44732
|
Multiple compression attempts have failed. The content may already be dense from a prior reflection.
|
|
44722
44733
|
|
|
44723
44734
|
You MUST dramatically reduce the number of observations while keeping the standard observation format (date groups with bullet points and priority emojis):
|
|
44724
|
-
- Tool call observations are the biggest source of bloat. Collapse ALL tool call sequences into outcome-only observations
|
|
44725
|
-
- Never preserve individual tool calls (viewed file X, searched for Y, ran build)
|
|
44735
|
+
- 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")
|
|
44736
|
+
- Never preserve individual tool calls (viewed file X, searched for Y, ran build) \u2014 only preserve what was discovered or accomplished
|
|
44726
44737
|
- Consolidate many related observations into single, more generic observations
|
|
44727
44738
|
- Merge all same-day date groups into at most 2-3 date groups per day
|
|
44728
44739
|
- For older content, each topic or task should be at most 1-2 observations capturing the key outcome
|
|
44729
44740
|
- For recent content, retain more detail but still merge related items aggressively
|
|
44730
44741
|
- If multiple observations describe incremental progress on the same task, keep only the final state
|
|
44731
|
-
- Preserve
|
|
44742
|
+
- Preserve \u2705 completion markers and their outcomes but merge related completions into fewer lines
|
|
44732
44743
|
- Preserve: user preferences, key decisions, architectural choices, and unresolved issues
|
|
44733
44744
|
|
|
44734
44745
|
Aim for a 2/10 detail level. Fewer, more generic observations are better than many specific ones that exceed the budget.
|
|
@@ -45151,7 +45162,7 @@ var ReflectorRunner = class {
|
|
|
45151
45162
|
operationType: "reflection",
|
|
45152
45163
|
startedAt: streamContext.startedAt,
|
|
45153
45164
|
tokensAttempted: originalTokens,
|
|
45154
|
-
error: `Did not compress below threshold (${originalTokens}
|
|
45165
|
+
error: `Did not compress below threshold (${originalTokens} \u2192 ${reflectedTokens}, target: ${targetThreshold}), retrying at level ${currentLevel + 1}`,
|
|
45155
45166
|
retrying: true,
|
|
45156
45167
|
recordId: streamContext.recordId,
|
|
45157
45168
|
threadId: streamContext.threadId
|
|
@@ -45181,7 +45192,7 @@ var ReflectorRunner = class {
|
|
|
45181
45192
|
}
|
|
45182
45193
|
currentLevel = Math.min(currentLevel + 1, maxLevel);
|
|
45183
45194
|
}
|
|
45184
|
-
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)" : ""}
|
|
45195
|
+
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`);
|
|
45185
45196
|
const structuredExtraction = await extractStructuredValues({
|
|
45186
45197
|
agent,
|
|
45187
45198
|
source: "reflector",
|
|
@@ -45322,7 +45333,7 @@ var ReflectorRunner = class {
|
|
|
45322
45333
|
const reflectedObservationLineCount = linesToReflect;
|
|
45323
45334
|
const sliceTokenEstimate = Math.round(avgTokensPerLine * linesToReflect);
|
|
45324
45335
|
const compressionTarget = Math.round(sliceTokenEstimate * .75);
|
|
45325
|
-
omDebug(`[OM:reflect] doAsyncBufferedReflection: slicing observations for reflection
|
|
45336
|
+
omDebug(`[OM:reflect] doAsyncBufferedReflection: slicing observations for reflection \u2014 totalLines=${totalLines}, avgTokPerLine=${avgTokensPerLine.toFixed(1)}, activationPointTokens=${activationPointTokens}, linesToReflect=${linesToReflect}/${totalLines}, sliceTokenEstimate=${sliceTokenEstimate}, compressionTarget=${compressionTarget}`);
|
|
45326
45337
|
omDebug(`[OM:reflect] doAsyncBufferedReflection: starting reflector call, recordId=${currentRecord.id}, observationTokens=${sliceTokenEstimate}, compressionTarget=${compressionTarget} (inputTokens), activeObsLength=${activeObservations.length}, reflectedLineCount=${reflectedObservationLineCount}`);
|
|
45327
45338
|
if (writer) {
|
|
45328
45339
|
const startMarker = createBufferingStartMarker({
|
|
@@ -45494,7 +45505,7 @@ var ReflectorRunner = class {
|
|
|
45494
45505
|
const unreflectedTailTokens = unreflectedContent ? this.tokenCounter.countObservations(unreflectedContent) : 0;
|
|
45495
45506
|
const bufferedReflectionTokens = freshRecord.bufferedReflectionTokens ?? 0;
|
|
45496
45507
|
if (unreflectedTailTokens < bufferedReflectionTokens) {
|
|
45497
|
-
omDebug(`[OM:reflect] tryActivateBufferedReflection: suppressing early ${activationMetadata.triggeredBy} activation
|
|
45508
|
+
omDebug(`[OM:reflect] tryActivateBufferedReflection: suppressing early ${activationMetadata.triggeredBy} activation \u2014 unreflectedTailTokens=${unreflectedTailTokens} < bufferedReflectionTokens=${bufferedReflectionTokens}; keeping buffer for threshold activation`);
|
|
45498
45509
|
return {
|
|
45499
45510
|
status: "suppressed",
|
|
45500
45511
|
reason: "composition"
|
|
@@ -45505,7 +45516,7 @@ var ReflectorRunner = class {
|
|
|
45505
45516
|
const regularActivationTarget = reflectThreshold * (1 - bufferActivation);
|
|
45506
45517
|
const minCombinedTokens = Math.round(regularActivationTarget * EARLY_ACTIVATION_SIZE_FLOOR_RATIO);
|
|
45507
45518
|
if (combinedTokenCount < minCombinedTokens) {
|
|
45508
|
-
omDebug(`[OM:reflect] tryActivateBufferedReflection: suppressing early ${activationMetadata.triggeredBy} activation
|
|
45519
|
+
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`);
|
|
45509
45520
|
return {
|
|
45510
45521
|
status: "suppressed",
|
|
45511
45522
|
reason: "size"
|
|
@@ -45634,7 +45645,7 @@ var ReflectorRunner = class {
|
|
|
45634
45645
|
omDebug(`[OM:reflect] isReflecting=true and active in this process, skipping`);
|
|
45635
45646
|
return;
|
|
45636
45647
|
}
|
|
45637
|
-
omDebug(`[OM:reflect] isReflecting=true but NOT active in this process
|
|
45648
|
+
omDebug(`[OM:reflect] isReflecting=true but NOT active in this process \u2014 stale flag from dead process, clearing`);
|
|
45638
45649
|
await this.storage.setReflectingFlag(record.id, false);
|
|
45639
45650
|
}
|
|
45640
45651
|
if (this.buffering.isAsyncReflectionEnabled()) {
|
|
@@ -45648,15 +45659,15 @@ var ReflectorRunner = class {
|
|
|
45648
45659
|
else {
|
|
45649
45660
|
const activationPoint = reflectThreshold * this.reflectionConfig.bufferActivation;
|
|
45650
45661
|
if (observationTokens < activationPoint) {
|
|
45651
|
-
omDebug(`[OM:reflect] skipping async reflection
|
|
45662
|
+
omDebug(`[OM:reflect] skipping async reflection \u2014 observationTokens (${observationTokens}) below activation point (${activationPoint}), triggered by ${activationTriggeredBy}`);
|
|
45652
45663
|
return;
|
|
45653
45664
|
}
|
|
45654
45665
|
const bufferKey = this.buffering.getReflectionBufferKey(lockKey);
|
|
45655
45666
|
if (this.buffering.isAsyncBufferingInProgress(bufferKey) || BufferingCoordinator.lastBufferedBoundary.has(bufferKey)) {
|
|
45656
|
-
omDebug(`[OM:reflect] skipping async reflection
|
|
45667
|
+
omDebug(`[OM:reflect] skipping async reflection \u2014 reflection buffer already active or present for ${bufferKey}`);
|
|
45657
45668
|
return;
|
|
45658
45669
|
}
|
|
45659
|
-
omDebug(`[OM:reflect] async activation failed, no blockAfter or below it (obsTokens=${observationTokens}, blockAfter=${this.reflectionConfig.blockAfter})
|
|
45670
|
+
omDebug(`[OM:reflect] async activation failed, no blockAfter or below it (obsTokens=${observationTokens}, blockAfter=${this.reflectionConfig.blockAfter}) \u2014 starting background reflection`);
|
|
45660
45671
|
this.startAsyncBufferedReflection(record, observationTokens, lockKey, writer, requestContext, observabilityContext, reflectionHooks, priorExtractedValues, mainAgent, sendSignal, trigger, currentModel);
|
|
45661
45672
|
return;
|
|
45662
45673
|
}
|
|
@@ -45664,7 +45675,7 @@ var ReflectorRunner = class {
|
|
|
45664
45675
|
if (activationTriggeredBy === "threshold") {
|
|
45665
45676
|
const suppressedAtTokens = this.syncReflectionSuppression.get(lockKey);
|
|
45666
45677
|
if (suppressedAtTokens !== void 0 && observationTokens === suppressedAtTokens) {
|
|
45667
|
-
omDebug(`[OM:reflect] skipping sync reflection
|
|
45678
|
+
omDebug(`[OM:reflect] skipping sync reflection \u2014 observations unchanged at ${observationTokens} tokens since the last unproductive attempt; retrying once they change`);
|
|
45668
45679
|
return;
|
|
45669
45680
|
}
|
|
45670
45681
|
}
|
|
@@ -46505,7 +46516,7 @@ var ObservationalMemory = class ObservationalMemory {
|
|
|
46505
46516
|
const asyncBufferingDisabled = config.observation?.bufferTokens === false || config.scope === "resource" && !userExplicitlyConfiguredAsync;
|
|
46506
46517
|
if (isSharedBudget && !asyncBufferingDisabled) {
|
|
46507
46518
|
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).");
|
|
46508
|
-
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
|
|
46519
|
+
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.");
|
|
46509
46520
|
}
|
|
46510
46521
|
const observationActivateAfterIdle = config.observation?.activateAfterIdle ?? config.activateAfterIdle;
|
|
46511
46522
|
const observationActivateAfterIdlePath = config.observation?.activateAfterIdle !== void 0 ? "observation.activateAfterIdle" : "activateAfterIdle";
|
|
@@ -46602,7 +46613,7 @@ var ObservationalMemory = class ObservationalMemory {
|
|
|
46602
46613
|
hasWarnedResourceScopeDeprecation = true;
|
|
46603
46614
|
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");
|
|
46604
46615
|
}
|
|
46605
|
-
omDebug(`[OM:init] new ObservationalMemory instance created
|
|
46616
|
+
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}`);
|
|
46606
46617
|
}
|
|
46607
46618
|
__registerMastra(mastra) {
|
|
46608
46619
|
this.mastra = mastra;
|
|
@@ -46883,7 +46894,7 @@ var ObservationalMemory = class ObservationalMemory {
|
|
|
46883
46894
|
threadId: null,
|
|
46884
46895
|
resourceId: resourceId ?? threadId
|
|
46885
46896
|
};
|
|
46886
|
-
if (!threadId) throw new Error("ObservationalMemory (scope: 'thread') requires a threadId, but received an empty value. This is a bug
|
|
46897
|
+
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.");
|
|
46887
46898
|
return {
|
|
46888
46899
|
threadId,
|
|
46889
46900
|
resourceId: resourceId ?? threadId
|
|
@@ -47194,7 +47205,7 @@ var ObservationalMemory = class ObservationalMemory {
|
|
|
47194
47205
|
const isImportant = new Array(totalCount);
|
|
47195
47206
|
for (let i = 0; i < totalCount; i++) {
|
|
47196
47207
|
lineTokens[i] = this.tokenCounter.countString(lines[i]);
|
|
47197
|
-
isImportant[i] = lines[i].includes("
|
|
47208
|
+
isImportant[i] = lines[i].includes("\u{1F534}") || lines[i].includes("\u2705");
|
|
47198
47209
|
}
|
|
47199
47210
|
const suffixTokens = new Array(totalCount + 1);
|
|
47200
47211
|
suffixTokens[totalCount] = 0;
|
|
@@ -47527,7 +47538,7 @@ ${formattedMessages}
|
|
|
47527
47538
|
resourceId: freshRecord.resourceId ?? void 0
|
|
47528
47539
|
});
|
|
47529
47540
|
} catch (err) {
|
|
47530
|
-
omError("[OM] Failed to persist sealed messages before buffering
|
|
47541
|
+
omError("[OM] Failed to persist sealed messages before buffering \u2014 skipping observation cycle", err);
|
|
47531
47542
|
return;
|
|
47532
47543
|
}
|
|
47533
47544
|
const cycleId = `buffer-obs-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;
|
|
@@ -48677,7 +48688,7 @@ ${formattedMessages}
|
|
|
48677
48688
|
usage: void 0
|
|
48678
48689
|
};
|
|
48679
48690
|
}
|
|
48680
|
-
omDebug(`[OM:reflect] isReflecting=true but NOT active in this process
|
|
48691
|
+
omDebug(`[OM:reflect] isReflecting=true but NOT active in this process \u2014 stale flag from dead process, clearing`);
|
|
48681
48692
|
await this.storage.setReflectingFlag(record.id, false);
|
|
48682
48693
|
}
|
|
48683
48694
|
await this.storage.setReflectingFlag(record.id, true);
|
|
@@ -48911,7 +48922,7 @@ ${formattedMessages}
|
|
|
48911
48922
|
};
|
|
48912
48923
|
const TEMPORAL_GAP_REMINDER_TYPE = "temporal-gap";
|
|
48913
48924
|
function getTemporalGapReminderText(gapText, timestamp) {
|
|
48914
|
-
return `${gapText}
|
|
48925
|
+
return `${gapText} \u2014 ${formatTemporalTimestamp(new Date(timestamp))}`;
|
|
48915
48926
|
}
|
|
48916
48927
|
function getTemporalGapReminderMetadata(message, gapText, gapMs, timestamp) {
|
|
48917
48928
|
const formattedTimestamp = formatTemporalTimestamp(new Date(timestamp));
|
|
@@ -49132,14 +49143,14 @@ var ObservationalMemoryProcessor = class {
|
|
|
49132
49143
|
omDebug(`[OM:processInputStep:ENTER] step=${stepNumber}, hasMastraMemory=${!!requestContext?.get("MastraMemory")}, hasMemoryInfo=${!!messageList?.serialize()?.memoryInfo?.threadId}`);
|
|
49133
49144
|
const context = this.engine.getThreadContext(requestContext, messageList);
|
|
49134
49145
|
if (!context) {
|
|
49135
|
-
omDebug(`[OM:processInputStep:NO-CONTEXT] getThreadContext returned null
|
|
49146
|
+
omDebug(`[OM:processInputStep:NO-CONTEXT] getThreadContext returned null \u2014 returning early`);
|
|
49136
49147
|
return messageList;
|
|
49137
49148
|
}
|
|
49138
49149
|
const gatewayMemoryManaged = await isGatewayMemoryManaged(model);
|
|
49139
49150
|
state[GATEWAY_STATE_KEY] = gatewayMemoryManaged;
|
|
49140
49151
|
if (gatewayMemoryManaged) {
|
|
49141
49152
|
await this.endActiveTurn(state);
|
|
49142
|
-
omDebug(`[OM:processInputStep:GATEWAY] gateway manages memory
|
|
49153
|
+
omDebug(`[OM:processInputStep:GATEWAY] gateway manages memory \u2014 skipping local processing`);
|
|
49143
49154
|
return messageList;
|
|
49144
49155
|
}
|
|
49145
49156
|
const { threadId, resourceId } = context;
|
|
@@ -49360,7 +49371,7 @@ var ObservationalMemoryProcessor = class {
|
|
|
49360
49371
|
if (!context) return;
|
|
49361
49372
|
if (parseMemoryRequestContext(requestContext)?.memoryConfig?.readOnly) return;
|
|
49362
49373
|
state[CONTEXT_OVERFLOW_STEP_KEY] = stepNumber;
|
|
49363
|
-
omDebug(`[OM:processAPIError] context overflow at step ${stepNumber}
|
|
49374
|
+
omDebug(`[OM:processAPIError] context overflow at step ${stepNumber} \u2014 observing pending messages`);
|
|
49364
49375
|
const { threadId, resourceId } = context;
|
|
49365
49376
|
await this.engine.waitForBuffering(threadId, resourceId, void 0, args.abortSignal);
|
|
49366
49377
|
const messages = getObservableMessages(messageList);
|
|
@@ -51959,7 +51970,7 @@ var import_ignore = /* @__PURE__ */ __toESM$1((/* @__PURE__ */ __commonJSMin$1((
|
|
|
51959
51970
|
const SPACE = " ";
|
|
51960
51971
|
const ESCAPE = "\\";
|
|
51961
51972
|
const REGEX_LITERAL_SPECIAL = /[.*+?()[\]{}^$|\\/]/;
|
|
51962
|
-
const BOM = "
|
|
51973
|
+
const BOM = "\uFEFF";
|
|
51963
51974
|
const REGEX_INVALID_TRAILING_BACKSLASH = /(?:[^\\]|^)\\$/;
|
|
51964
51975
|
const REGEX_ANCHORED_GLOBSTAR = /^\/\*{2,}$/;
|
|
51965
51976
|
const REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/;
|
|
@@ -52056,8 +52067,8 @@ var import_ignore = /* @__PURE__ */ __toESM$1((/* @__PURE__ */ __commonJSMin$1((
|
|
|
52056
52067
|
const NEVER_MATCH = "[]";
|
|
52057
52068
|
const PLACEHOLDER = "\0";
|
|
52058
52069
|
const REGEX_RESTORE_PLACEHOLDER = new RegExp(`${PLACEHOLDER}(\\d+)${PLACEHOLDER}`, "g");
|
|
52059
|
-
const TRAILING_WILDCARD = "
|
|
52060
|
-
const TRAILING_DOUBLESTAR = "
|
|
52070
|
+
const TRAILING_WILDCARD = "\uE000";
|
|
52071
|
+
const TRAILING_DOUBLESTAR = "\uE001";
|
|
52061
52072
|
const isReserved = (char) => char === PLACEHOLDER || char === TRAILING_WILDCARD || char === TRAILING_DOUBLESTAR;
|
|
52062
52073
|
const extractBrackets = (pattern) => {
|
|
52063
52074
|
const sources = [];
|
|
@@ -52827,7 +52838,7 @@ async function logGitState(targetPath, label) {
|
|
|
52827
52838
|
const gitStatusResult = await git(targetPath, "status", "--porcelain");
|
|
52828
52839
|
const gitLogResult = await git(targetPath, "log", "--oneline", "-3");
|
|
52829
52840
|
const gitCountResult = await git(targetPath, "rev-list", "--count", "HEAD");
|
|
52830
|
-
console.info(
|
|
52841
|
+
console.info(`\u{1F4CA} Git state ${label}:`);
|
|
52831
52842
|
console.info("Status:", gitStatusResult.stdout.trim() || "Clean working directory");
|
|
52832
52843
|
console.info("Recent commits:", gitLogResult.stdout.trim());
|
|
52833
52844
|
console.info("Total commits:", gitCountResult.stdout.trim());
|
|
@@ -52919,9 +52930,9 @@ async function gitCheckoutBranch(branchName, targetPath) {
|
|
|
52919
52930
|
async function backupAndReplaceFile(sourceFile, targetFile) {
|
|
52920
52931
|
const backupFile = `${targetFile}.backup-${Date.now()}`;
|
|
52921
52932
|
await copyFile(targetFile, backupFile);
|
|
52922
|
-
console.info(
|
|
52933
|
+
console.info(`\u{1F4E6} Created backup: ${basename(backupFile)}`);
|
|
52923
52934
|
await copyFile(sourceFile, targetFile);
|
|
52924
|
-
console.info(
|
|
52935
|
+
console.info(`\u{1F504} Replaced file with template version (backup created)`);
|
|
52925
52936
|
}
|
|
52926
52937
|
async function renameAndCopyFile(sourceFile, targetFile) {
|
|
52927
52938
|
let counter = 1;
|
|
@@ -52935,7 +52946,7 @@ async function renameAndCopyFile(sourceFile, targetFile) {
|
|
|
52935
52946
|
counter++;
|
|
52936
52947
|
}
|
|
52937
52948
|
await copyFile(sourceFile, uniqueTargetFile);
|
|
52938
|
-
console.info(
|
|
52949
|
+
console.info(`\u{1F4DD} Copied with unique name: ${basename(uniqueTargetFile)}`);
|
|
52939
52950
|
return uniqueTargetFile;
|
|
52940
52951
|
}
|
|
52941
52952
|
const isValidMastraLanguageModel = (model) => {
|
|
@@ -52973,7 +52984,7 @@ const mergeGitignoreFiles = (targetContent, templateContent, templateSlug) => {
|
|
|
52973
52984
|
const isNegation = normalized.startsWith("!");
|
|
52974
52985
|
const basePath = isNegation ? normalized.slice(1) : normalized;
|
|
52975
52986
|
if (!(isNegation ? existingEntries.has(basePath) : existingEntries.has("!" + basePath))) newEntries.push(trimmed);
|
|
52976
|
-
else console.info(
|
|
52987
|
+
else console.info(`\u26A0 Skipping conflicting .gitignore rule: ${trimmed} (conflicts with existing rule)`);
|
|
52977
52988
|
}
|
|
52978
52989
|
}
|
|
52979
52990
|
}
|
|
@@ -53003,7 +53014,7 @@ const mergeEnvFiles = (targetContent, templateVariables, templateSlug) => {
|
|
|
53003
53014
|
key,
|
|
53004
53015
|
value
|
|
53005
53016
|
});
|
|
53006
|
-
else console.info(
|
|
53017
|
+
else console.info(`\u26A0 Skipping existing environment variable: ${key} (already exists in .env)`);
|
|
53007
53018
|
if (newVars.length === 0) return targetContent;
|
|
53008
53019
|
const result = [...targetLines];
|
|
53009
53020
|
const lastLine = result[result.length - 1];
|
|
@@ -53058,7 +53069,7 @@ const createModelInstance = async (provider, modelId, version = "v2") => {
|
|
|
53058
53069
|
try {
|
|
53059
53070
|
const providerFn = version === `v1` ? { v1: {
|
|
53060
53071
|
openai: async () => {
|
|
53061
|
-
const { openai } = await import("./dist-
|
|
53072
|
+
const { openai } = await import("./dist-Bz6gINFc.js");
|
|
53062
53073
|
return openai(modelId);
|
|
53063
53074
|
},
|
|
53064
53075
|
anthropic: async () => {
|
|
@@ -53127,25 +53138,25 @@ IF NO PROJECT EXISTS, USE THE MANAGEPROJECT TOOL TO CREATE A NEW PROJECT
|
|
|
53127
53138
|
|
|
53128
53139
|
DO NOT INCLUDE TODOS IN THE CODE, UNLESS SPECIFICALLY ASKED TO DO SO, CREATE REAL WORLD CODE
|
|
53129
53140
|
|
|
53130
|
-
### 1.
|
|
53141
|
+
### 1. \u{1F50D} **UNDERSTAND** (Information Gathering)
|
|
53131
53142
|
- **Explore Mastra Docs**: Use docs tools to understand relevant Mastra patterns and APIs
|
|
53132
53143
|
- **Analyze Project**: Use file exploration to understand existing codebase structure
|
|
53133
53144
|
- **Web Research**: Search for packages, examples, or solutions when docs are insufficient
|
|
53134
53145
|
- **Clarify Requirements**: Ask targeted questions only when critical information is missing
|
|
53135
53146
|
|
|
53136
|
-
### 2.
|
|
53147
|
+
### 2. \u{1F4CB} **PLAN** (Strategy & Design)
|
|
53137
53148
|
- **Architecture**: Design using Mastra conventions (agents, tools, workflows, memory)
|
|
53138
53149
|
- **Dependencies**: Identify required packages and Mastra components
|
|
53139
53150
|
- **Integration**: Plan how to integrate with existing project structure
|
|
53140
53151
|
- **Validation**: Define how to test and verify the implementation
|
|
53141
53152
|
|
|
53142
|
-
### 3.
|
|
53153
|
+
### 3. \u{1F6E0}\uFE0F **BUILD** (Implementation)
|
|
53143
53154
|
- **Install First**: Use \`manageProject\` tool to install required packages
|
|
53144
53155
|
- **Follow Patterns**: Implement using established Mastra conventions
|
|
53145
53156
|
- **Real Code Only**: Build actual working functionality, never mock implementations
|
|
53146
53157
|
- **Environment Setup**: Create proper .env configuration and documentation
|
|
53147
53158
|
|
|
53148
|
-
### 4.
|
|
53159
|
+
### 4. \u2705 **VALIDATE** (Quality Assurance)
|
|
53149
53160
|
- **Code Validation**: Run \`validateCode\` with types and lint checks
|
|
53150
53161
|
- **Testing**: Execute tests if available
|
|
53151
53162
|
- **Server Testing**: Use \`manageServer\` and \`httpRequest\` for API validation
|
|
@@ -53242,23 +53253,23 @@ DO NOT INCLUDE TODOS IN THE CODE, UNLESS SPECIFICALLY ASKED TO DO SO, CREATE REA
|
|
|
53242
53253
|
## Output Requirements
|
|
53243
53254
|
|
|
53244
53255
|
### Code Quality
|
|
53245
|
-
-
|
|
53246
|
-
-
|
|
53247
|
-
-
|
|
53248
|
-
-
|
|
53249
|
-
-
|
|
53256
|
+
- \u2705 TypeScript compilation passes
|
|
53257
|
+
- \u2705 ESLint validation passes
|
|
53258
|
+
- \u2705 Proper error handling implemented
|
|
53259
|
+
- \u2705 Environment variables configured
|
|
53260
|
+
- \u2705 Tests included when appropriate
|
|
53250
53261
|
|
|
53251
53262
|
### Documentation
|
|
53252
|
-
-
|
|
53253
|
-
-
|
|
53254
|
-
-
|
|
53255
|
-
-
|
|
53263
|
+
- \u2705 Clear setup instructions
|
|
53264
|
+
- \u2705 Environment variable documentation
|
|
53265
|
+
- \u2705 Usage examples provided
|
|
53266
|
+
- \u2705 API documentation for custom tools
|
|
53256
53267
|
|
|
53257
53268
|
### Integration
|
|
53258
|
-
-
|
|
53259
|
-
-
|
|
53260
|
-
-
|
|
53261
|
-
-
|
|
53269
|
+
- \u2705 Follows Mastra conventions
|
|
53270
|
+
- \u2705 Integrates with existing project
|
|
53271
|
+
- \u2705 Proper imports and exports
|
|
53272
|
+
- \u2705 Compatible with Mastra ecosystem
|
|
53262
53273
|
|
|
53263
53274
|
## Project Context
|
|
53264
53275
|
|
|
@@ -53805,7 +53816,7 @@ export const mastra = new Mastra({
|
|
|
53805
53816
|
}),
|
|
53806
53817
|
validateCode: createTool({
|
|
53807
53818
|
id: "validate-code",
|
|
53808
|
-
description: "Validates code using a fast hybrid approach: syntax
|
|
53819
|
+
description: "Validates code using a fast hybrid approach: syntax \u2192 semantic \u2192 lint. RECOMMENDED: Always provide specific files for optimal performance and accuracy.",
|
|
53809
53820
|
inputSchema: z$2.object({
|
|
53810
53821
|
projectPath: z$2.string().optional().describe("Path to the project to validate (defaults to current project)"),
|
|
53811
53822
|
validationType: z$2.array(z$2.enum([
|
|
@@ -53815,7 +53826,7 @@ export const mastra = new Mastra({
|
|
|
53815
53826
|
"tests",
|
|
53816
53827
|
"build"
|
|
53817
53828
|
])).describe("Types of validation to perform. Recommended: [\"types\", \"lint\"] for code quality"),
|
|
53818
|
-
files: z$2.array(z$2.string()).optional().describe("RECOMMENDED: Specific files to validate (e.g., files you created/modified). Uses hybrid validation: fast syntax check
|
|
53829
|
+
files: z$2.array(z$2.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.")
|
|
53819
53830
|
}),
|
|
53820
53831
|
outputSchema: z$2.object({
|
|
53821
53832
|
valid: z$2.boolean(),
|
|
@@ -55698,8 +55709,8 @@ For each Mastra project directory you analyze:
|
|
|
55698
55709
|
IMPORTANT - Naming Consistency Rules:
|
|
55699
55710
|
- For ALL unit types (including 'other'), the 'name' field should be the filename WITHOUT extension
|
|
55700
55711
|
- For structured units (agents, workflows, tools, etc.), prefer the actual export name if clearly identifiable
|
|
55701
|
-
- use the base filename without extension for the id (e.g., 'util.ts'
|
|
55702
|
-
- use the relative path from the template root for the file (e.g., 'src/mastra/lib/util.ts'
|
|
55712
|
+
- use the base filename without extension for the id (e.g., 'util.ts' \u2192 name: 'util')
|
|
55713
|
+
- 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')
|
|
55703
55714
|
|
|
55704
55715
|
Return the actual exported names of the units, as well as the file names.`,
|
|
55705
55716
|
name: "Mastra Project Discoverer",
|
|
@@ -56055,7 +56066,7 @@ const programmaticFileCopyStep = createStep({
|
|
|
56055
56066
|
sourceFile: unit.file,
|
|
56056
56067
|
targetFile: `${targetDir}/${convertedFileName}`
|
|
56057
56068
|
});
|
|
56058
|
-
console.info(
|
|
56069
|
+
console.info(`\u23ED\uFE0F Skipped ${unit.kind} "${unit.id}": file already exists`);
|
|
56059
56070
|
continue;
|
|
56060
56071
|
case "backup-and-replace": try {
|
|
56061
56072
|
await backupAndReplaceFile(sourceFile, targetFile);
|
|
@@ -56067,7 +56078,7 @@ const programmaticFileCopyStep = createStep({
|
|
|
56067
56078
|
id: unit.id
|
|
56068
56079
|
}
|
|
56069
56080
|
});
|
|
56070
|
-
console.info(
|
|
56081
|
+
console.info(`\u{1F504} Replaced ${unit.kind} "${unit.id}": ${unit.file} \u2192 ${convertedFileName} (backup created)`);
|
|
56071
56082
|
continue;
|
|
56072
56083
|
} catch (backupError) {
|
|
56073
56084
|
conflicts.push({
|
|
@@ -56091,7 +56102,7 @@ const programmaticFileCopyStep = createStep({
|
|
|
56091
56102
|
id: unit.id
|
|
56092
56103
|
}
|
|
56093
56104
|
});
|
|
56094
|
-
console.info(
|
|
56105
|
+
console.info(`\u{1F4DD} Renamed ${unit.kind} "${unit.id}": ${unit.file} \u2192 ${basename(uniqueTargetFile)}`);
|
|
56095
56106
|
continue;
|
|
56096
56107
|
} catch (renameError) {
|
|
56097
56108
|
conflicts.push({
|
|
@@ -56129,7 +56140,7 @@ const programmaticFileCopyStep = createStep({
|
|
|
56129
56140
|
id: unit.id
|
|
56130
56141
|
}
|
|
56131
56142
|
});
|
|
56132
|
-
console.info(
|
|
56143
|
+
console.info(`\u2713 Copied ${unit.kind} "${unit.id}": ${unit.file} \u2192 ${convertedFileName}`);
|
|
56133
56144
|
} catch (copyError) {
|
|
56134
56145
|
conflicts.push({
|
|
56135
56146
|
unit: {
|
|
@@ -56156,7 +56167,7 @@ const programmaticFileCopyStep = createStep({
|
|
|
56156
56167
|
id: "tsconfig.json"
|
|
56157
56168
|
}
|
|
56158
56169
|
});
|
|
56159
|
-
console.info("
|
|
56170
|
+
console.info("\u2713 Copied tsconfig.json from template to target");
|
|
56160
56171
|
} else {
|
|
56161
56172
|
await writeFile(targetTsconfig, JSON.stringify({
|
|
56162
56173
|
compilerOptions: {
|
|
@@ -56192,7 +56203,7 @@ const programmaticFileCopyStep = createStep({
|
|
|
56192
56203
|
id: "tsconfig.json"
|
|
56193
56204
|
}
|
|
56194
56205
|
});
|
|
56195
|
-
console.info("
|
|
56206
|
+
console.info("\u2713 Generated minimal tsconfig.json in target");
|
|
56196
56207
|
}
|
|
56197
56208
|
}
|
|
56198
56209
|
} catch (e) {
|
|
@@ -56221,7 +56232,7 @@ const programmaticFileCopyStep = createStep({
|
|
|
56221
56232
|
id: "mastra-index"
|
|
56222
56233
|
}
|
|
56223
56234
|
});
|
|
56224
|
-
console.info("
|
|
56235
|
+
console.info("\u2713 Copied Mastra index file from template");
|
|
56225
56236
|
}
|
|
56226
56237
|
}
|
|
56227
56238
|
} catch (e) {
|
|
@@ -56250,7 +56261,7 @@ const programmaticFileCopyStep = createStep({
|
|
|
56250
56261
|
id: "gitignore"
|
|
56251
56262
|
}
|
|
56252
56263
|
});
|
|
56253
|
-
console.info("
|
|
56264
|
+
console.info("\u2713 Copied .gitignore from template to target");
|
|
56254
56265
|
} else {
|
|
56255
56266
|
const targetContent = await readFile(targetGitignore, "utf-8");
|
|
56256
56267
|
const templateContent = await readFile(templateGitignore, "utf-8");
|
|
@@ -56266,8 +56277,8 @@ const programmaticFileCopyStep = createStep({
|
|
|
56266
56277
|
id: "gitignore-merge"
|
|
56267
56278
|
}
|
|
56268
56279
|
});
|
|
56269
|
-
console.info(
|
|
56270
|
-
} else console.info("
|
|
56280
|
+
console.info(`\u2713 Merged template .gitignore entries into existing .gitignore (${addedLines} new entries)`);
|
|
56281
|
+
} else console.info("\u2139 No new .gitignore entries to add from template");
|
|
56271
56282
|
}
|
|
56272
56283
|
}
|
|
56273
56284
|
} catch (e) {
|
|
@@ -56296,7 +56307,7 @@ const programmaticFileCopyStep = createStep({
|
|
|
56296
56307
|
id: "env"
|
|
56297
56308
|
}
|
|
56298
56309
|
});
|
|
56299
|
-
console.info(
|
|
56310
|
+
console.info(`\u2713 Created .env file with ${Object.keys(variables).length} template variables`);
|
|
56300
56311
|
} else {
|
|
56301
56312
|
const targetContent = await readFile(targetEnv, "utf-8");
|
|
56302
56313
|
const mergedContent = mergeEnvFiles(targetContent, variables, slug);
|
|
@@ -56311,8 +56322,8 @@ const programmaticFileCopyStep = createStep({
|
|
|
56311
56322
|
id: "env-merge"
|
|
56312
56323
|
}
|
|
56313
56324
|
});
|
|
56314
|
-
console.info(
|
|
56315
|
-
} else console.info("
|
|
56325
|
+
console.info(`\u2713 Merged new environment variables into existing .env file (${addedLines} new entries)`);
|
|
56326
|
+
} else console.info("\u2139 No new environment variables to add (all already exist in .env)");
|
|
56316
56327
|
}
|
|
56317
56328
|
}
|
|
56318
56329
|
} catch (e) {
|
|
@@ -56329,7 +56340,7 @@ const programmaticFileCopyStep = createStep({
|
|
|
56329
56340
|
if (copiedFiles.length > 0) try {
|
|
56330
56341
|
const fileList = copiedFiles.map((f) => f.destination);
|
|
56331
56342
|
await gitAddAndCommit(targetPath, `feat(template): copy ${copiedFiles.length} files from ${slug}@${commitSha.substring(0, 7)}`, fileList, { skipIfNoStaged: true });
|
|
56332
|
-
console.info(
|
|
56343
|
+
console.info(`\u2713 Committed ${copiedFiles.length} copied files`);
|
|
56333
56344
|
} catch (commitError) {
|
|
56334
56345
|
console.warn("Failed to commit copied files:", commitError);
|
|
56335
56346
|
}
|
|
@@ -56573,7 +56584,7 @@ Start by listing your tasks and work through them systematically!
|
|
|
56573
56584
|
content: toolResult.content || "",
|
|
56574
56585
|
notes: toolResult.notes
|
|
56575
56586
|
});
|
|
56576
|
-
console.info(
|
|
56587
|
+
console.info(`\u{1F4CB} Task completed: ${toolResult.taskId} - ${toolResult.content}`);
|
|
56577
56588
|
}
|
|
56578
56589
|
} catch (parseError) {
|
|
56579
56590
|
console.warn("Failed to parse task management result:", parseError);
|
|
@@ -56625,7 +56636,7 @@ const validationAndFixStep = createStep({
|
|
|
56625
56636
|
const { commitSha, slug, orderedUnits, templateDir, copiedFiles, conflictsResolved, maxIterations = 5 } = inputData;
|
|
56626
56637
|
const targetPath = resolveTargetPath(inputData, requestContext);
|
|
56627
56638
|
if (!(copiedFiles.length > 0 || conflictsResolved && conflictsResolved.length > 0)) {
|
|
56628
|
-
console.info("
|
|
56639
|
+
console.info("\u23ED\uFE0F Skipping validation - no files copied or conflicts resolved");
|
|
56629
56640
|
return {
|
|
56630
56641
|
success: true,
|
|
56631
56642
|
applied: false,
|
|
@@ -56637,7 +56648,7 @@ const validationAndFixStep = createStep({
|
|
|
56637
56648
|
}
|
|
56638
56649
|
};
|
|
56639
56650
|
}
|
|
56640
|
-
console.info(
|
|
56651
|
+
console.info(`\u{1F4CB} Changes detected: ${copiedFiles.length} files copied, ${conflictsResolved?.length || 0} conflicts resolved`);
|
|
56641
56652
|
let currentIteration = 1;
|
|
56642
56653
|
try {
|
|
56643
56654
|
const model = await resolveModel({
|
|
@@ -56729,7 +56740,7 @@ CRITICAL TOOL SELECTION GUIDE:
|
|
|
56729
56740
|
- **writeFile**: ONLY for creating new files that don't exist
|
|
56730
56741
|
Example: creating missing index.ts barrel files
|
|
56731
56742
|
|
|
56732
|
-
CRITICAL WRITEFIL
|
|
56743
|
+
CRITICAL WRITEFIL\u0415 SAFETY RULES:
|
|
56733
56744
|
- ONLY use writeFile for creating NEW files that don't exist
|
|
56734
56745
|
- ALWAYS check with readFile first to verify file doesn't exist
|
|
56735
56746
|
- NEVER use writeFile to overwrite existing files - use multiEdit or replaceLines instead
|
|
@@ -56814,10 +56825,10 @@ Previous iterations may have fixed some issues, so start by re-running validateC
|
|
|
56814
56825
|
if (iterationErrors > 0 && lastValidationResult?.errors) validationResults.lastValidationErrors = lastValidationResult.errors;
|
|
56815
56826
|
console.info(`Iteration ${currentIteration} complete: ${iterationErrors} errors remaining`);
|
|
56816
56827
|
if (iterationErrors === 0) {
|
|
56817
|
-
console.info(
|
|
56828
|
+
console.info(`\u2705 All validation issues resolved in ${currentIteration} iterations!`);
|
|
56818
56829
|
break;
|
|
56819
56830
|
} else if (currentIteration >= maxIterations) {
|
|
56820
|
-
console.info(
|
|
56831
|
+
console.info(`\u26A0\uFE0F Max iterations (${maxIterations}) reached. ${iterationErrors} errors still remaining.`);
|
|
56821
56832
|
break;
|
|
56822
56833
|
}
|
|
56823
56834
|
currentIteration++;
|
|
@@ -56857,7 +56868,7 @@ Previous iterations may have fixed some issues, so start by re-running validateC
|
|
|
56857
56868
|
recursive: true,
|
|
56858
56869
|
force: true
|
|
56859
56870
|
});
|
|
56860
|
-
console.info(
|
|
56871
|
+
console.info(`\u2713 Cleaned up template directory: ${templateDir}`);
|
|
56861
56872
|
} catch (cleanupError) {
|
|
56862
56873
|
console.warn("Failed to cleanup template directory:", cleanupError);
|
|
56863
56874
|
}
|
|
@@ -59951,11 +59962,11 @@ function createPlanningAndApprovalWorkflow() {
|
|
|
59951
59962
|
}
|
|
59952
59963
|
createPlanningAndApprovalWorkflow();
|
|
59953
59964
|
const workflowResearch = `
|
|
59954
|
-
##
|
|
59965
|
+
## \u{1F50D} **COMPREHENSIVE MASTRA WORKFLOW RESEARCH SUMMARY**
|
|
59955
59966
|
|
|
59956
59967
|
Based on extensive research of Mastra documentation and examples, here's essential information for building effective Mastra workflows:
|
|
59957
59968
|
|
|
59958
|
-
###
|
|
59969
|
+
### **\u{1F4CB} WORKFLOW FUNDAMENTALS**
|
|
59959
59970
|
|
|
59960
59971
|
**Core Components:**
|
|
59961
59972
|
- **\`createWorkflow()\`**: Main factory function that creates workflow instances
|
|
@@ -59979,7 +59990,7 @@ const workflow = createWorkflow({
|
|
|
59979
59990
|
.commit(); // CRITICAL: Makes workflow executable
|
|
59980
59991
|
\`\`\`
|
|
59981
59992
|
|
|
59982
|
-
###
|
|
59993
|
+
### **\u{1F527} STEP CREATION PATTERNS**
|
|
59983
59994
|
|
|
59984
59995
|
**Standard Step Definition:**
|
|
59985
59996
|
\`\`\`typescript
|
|
@@ -60003,7 +60014,7 @@ const myStep = createStep({
|
|
|
60003
60014
|
- \`requestContext\`: Runtime dependency injection context
|
|
60004
60015
|
- \`runCount\`: Number of times this step has run (useful for retries)
|
|
60005
60016
|
|
|
60006
|
-
###
|
|
60017
|
+
### **\u{1F504} CONTROL FLOW METHODS**
|
|
60007
60018
|
|
|
60008
60019
|
**Sequential Execution:**
|
|
60009
60020
|
- \`.then(step)\`: Execute steps one after another
|
|
@@ -60025,7 +60036,7 @@ const myStep = createStep({
|
|
|
60025
60036
|
**Data Transformation:**
|
|
60026
60037
|
- \`.map(({ inputData, getStepResult, getInitData }) => transformedData)\`: Transform data between steps
|
|
60027
60038
|
|
|
60028
|
-
###
|
|
60039
|
+
### **\u23F8\uFE0F SUSPEND & RESUME CAPABILITIES**
|
|
60029
60040
|
|
|
60030
60041
|
**For Human-in-the-Loop Workflows:**
|
|
60031
60042
|
\`\`\`typescript
|
|
@@ -60056,7 +60067,7 @@ if (result.status === "suspended") {
|
|
|
60056
60067
|
}
|
|
60057
60068
|
\`\`\`
|
|
60058
60069
|
|
|
60059
|
-
###
|
|
60070
|
+
### **\u{1F6E0}\uFE0F INTEGRATING AGENTS & TOOLS**
|
|
60060
60071
|
|
|
60061
60072
|
**Using Agents in Steps:**
|
|
60062
60073
|
\`\`\`typescript
|
|
@@ -60089,24 +60100,24 @@ const step = createStep({
|
|
|
60089
60100
|
});
|
|
60090
60101
|
\`\`\`
|
|
60091
60102
|
|
|
60092
|
-
###
|
|
60103
|
+
### **\u{1F5C2}\uFE0F PROJECT ORGANIZATION PATTERNS**
|
|
60093
60104
|
|
|
60094
60105
|
**MANDATORY Workflow Organization:**
|
|
60095
60106
|
Each workflow MUST be organized in its own dedicated folder with separated concerns:
|
|
60096
60107
|
|
|
60097
60108
|
\`\`\`
|
|
60098
60109
|
src/mastra/workflows/
|
|
60099
|
-
|
|
60100
|
-
|
|
60101
|
-
|
|
60102
|
-
|
|
60103
|
-
|
|
60104
|
-
|
|
60105
|
-
|
|
60106
|
-
|
|
60107
|
-
|
|
60108
|
-
|
|
60109
|
-
|
|
60110
|
+
\u251C\u2500\u2500 my-workflow-name/ # Kebab-case folder name
|
|
60111
|
+
\u2502 \u251C\u2500\u2500 types.ts # All Zod schemas and TypeScript types
|
|
60112
|
+
\u2502 \u251C\u2500\u2500 steps.ts # All individual step definitions
|
|
60113
|
+
\u2502 \u251C\u2500\u2500 workflow.ts # Main workflow composition and export
|
|
60114
|
+
\u2502 \u2514\u2500\u2500 utils.ts # Helper functions (if needed)
|
|
60115
|
+
\u251C\u2500\u2500 another-workflow/
|
|
60116
|
+
\u2502 \u251C\u2500\u2500 types.ts
|
|
60117
|
+
\u2502 \u251C\u2500\u2500 steps.ts
|
|
60118
|
+
\u2502 \u251C\u2500\u2500 workflow.ts
|
|
60119
|
+
\u2502 \u2514\u2500\u2500 utils.ts
|
|
60120
|
+
\u2514\u2500\u2500 index.ts # Export all workflows
|
|
60110
60121
|
\`\`\`
|
|
60111
60122
|
|
|
60112
60123
|
**CRITICAL File Organization Rules:**
|
|
@@ -60130,7 +60141,7 @@ export const mastra = new Mastra({
|
|
|
60130
60141
|
});
|
|
60131
60142
|
\`\`\`
|
|
60132
60143
|
|
|
60133
|
-
###
|
|
60144
|
+
### **\u{1F4E6} ESSENTIAL DEPENDENCIES**
|
|
60134
60145
|
|
|
60135
60146
|
**Required Packages:**
|
|
60136
60147
|
\`\`\`json
|
|
@@ -60147,7 +60158,7 @@ export const mastra = new Mastra({
|
|
|
60147
60158
|
- \`@ai-sdk/openai\`: For AI model integration
|
|
60148
60159
|
- \`ai\`: For AI SDK functionality
|
|
60149
60160
|
|
|
60150
|
-
###
|
|
60161
|
+
### **\u2705 WORKFLOW BEST PRACTICES**
|
|
60151
60162
|
|
|
60152
60163
|
**Schema Design:**
|
|
60153
60164
|
- Use descriptive property names in schemas
|
|
@@ -60169,7 +60180,7 @@ export const mastra = new Mastra({
|
|
|
60169
60180
|
- Access previous step results with \`getStepResult(stepInstance)\`
|
|
60170
60181
|
- Use \`getInitData()\` to access original workflow input
|
|
60171
60182
|
|
|
60172
|
-
###
|
|
60183
|
+
### **\u{1F680} EXECUTION PATTERNS**
|
|
60173
60184
|
|
|
60174
60185
|
**Running Workflows:**
|
|
60175
60186
|
\`\`\`typescript
|
|
@@ -60192,7 +60203,7 @@ run.watch((event) => console.log(event));
|
|
|
60192
60203
|
- \`"suspended"\`: Paused awaiting input
|
|
60193
60204
|
- \`"failed"\`: Encountered error
|
|
60194
60205
|
|
|
60195
|
-
###
|
|
60206
|
+
### **\u{1F517} ADVANCED FEATURES**
|
|
60196
60207
|
|
|
60197
60208
|
**Nested Workflows:**
|
|
60198
60209
|
- Use workflows as steps: \`.then(otherWorkflow)\`
|
|
@@ -60255,11 +60266,11 @@ CRITICAL WORKFLOW EXECUTION REQUIREMENTS:
|
|
|
60255
60266
|
MANDATORY WORKFLOW FOLDER STRUCTURE:
|
|
60256
60267
|
When ${context.action === "create" ? "creating a new workflow" : "editing a workflow"}, you MUST organize files as follows:
|
|
60257
60268
|
|
|
60258
|
-
|
|
60259
|
-
|
|
60260
|
-
|
|
60261
|
-
|
|
60262
|
-
|
|
60269
|
+
\u{1F4C1} src/mastra/workflows/${context.workflowName?.toLowerCase().replace(/[^a-z0-9]/g, "-") || "new-workflow"}/
|
|
60270
|
+
\u251C\u2500\u2500 \u{1F4C4} types.ts # All Zod schemas and TypeScript types
|
|
60271
|
+
\u251C\u2500\u2500 \u{1F4C4} steps.ts # All individual step definitions
|
|
60272
|
+
\u251C\u2500\u2500 \u{1F4C4} workflow.ts # Main workflow composition and export
|
|
60273
|
+
\u2514\u2500\u2500 \u{1F4C4} utils.ts # Helper functions (if needed)
|
|
60263
60274
|
|
|
60264
60275
|
CRITICAL FILE ORGANIZATION RULES:
|
|
60265
60276
|
- **ALWAYS create a dedicated folder** for the workflow in src/mastra/workflows/
|
|
@@ -60331,7 +60342,7 @@ ${context.resumeData ? `USER PROVIDED ANSWERS: ${JSON.stringify(context.resumeDa
|
|
|
60331
60342
|
},
|
|
60332
60343
|
validation: { instructions: `CRITICAL VALIDATION INSTRUCTIONS:
|
|
60333
60344
|
- When using the validateCode tool, ALWAYS pass the specific files you created or modified using the 'files' parameter
|
|
60334
|
-
- The tool uses a hybrid validation approach: fast syntax checking
|
|
60345
|
+
- The tool uses a hybrid validation approach: fast syntax checking \u2192 semantic type checking \u2192 ESLint
|
|
60335
60346
|
- This is much faster than full project compilation and only shows errors from your specific files
|
|
60336
60347
|
- Example: validateCode({ validationType: ['types', 'lint'], files: ['src/workflows/my-workflow.ts', 'src/agents/my-agent.ts'] })
|
|
60337
60348
|
- ALWAYS validate after creating or modifying files to ensure they compile correctly` }
|