@mastra/core 1.86.0-alpha.7 → 1.86.0-alpha.9
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/_types/@internal_core@0.1.4/dist/knowledge-compat/index.d.ts +363 -0
- package/dist/a2a/index.cjs +1 -1
- package/dist/a2a/index.js +1 -1
- package/dist/agent/agent.d.ts +72 -1
- package/dist/agent/agent.types.d.ts +30 -2
- package/dist/agent/durable/create-evented-agent.d.ts +6 -0
- package/dist/agent/durable/durable-agent.d.ts +1 -15
- package/dist/agent/durable/index.cjs +7 -26
- package/dist/agent/durable/index.js +7 -26
- package/dist/agent/durable/preparation.d.ts +2 -0
- package/dist/agent/durable/utils/resolve-runtime.d.ts +9 -0
- package/dist/agent/durable/workflows/durable-loop-builder.d.ts +4 -0
- package/dist/agent/durable/workflows/finalize-run.d.ts +3 -1
- package/dist/agent/durable/workflows/steps/llm-execution.d.ts +1 -0
- package/dist/agent/index.cjs +3 -3
- package/dist/agent/index.js +3 -3
- package/dist/agent/message-list/index.cjs +1 -1
- package/dist/agent/message-list/index.js +1 -1
- package/dist/agent/message-list/message-list.d.ts +11 -0
- package/dist/agent/message-list/utils/provider-compat.d.ts +1 -0
- package/dist/agent/request-context-snapshot.d.ts +1 -1
- package/dist/agent/streams/types.d.ts +10 -0
- package/dist/agent/thread-stream-runtime.d.ts +5 -0
- package/dist/agent/types.d.ts +25 -0
- package/dist/agent-builder/ee/index.cjs +1 -1
- package/dist/agent-builder/ee/index.js +1 -1
- package/dist/agent-controller/index.cjs +1 -1
- package/dist/agent-controller/index.js +1 -1
- package/dist/{agent-controller-K5vHtqfO.cjs → agent-controller-CrQ9OF80.cjs} +8 -8
- package/dist/{agent-controller-Cf3_IuY8.js → agent-controller-SSlKzE6A.js} +8 -8
- package/dist/background-tasks/index.cjs +1 -1
- package/dist/background-tasks/index.js +1 -1
- package/dist/{background-tasks-DqnQMfuf.cjs → background-tasks-BDrYBis-.cjs} +5 -3
- package/dist/{background-tasks-BgpX1P_s.js → background-tasks-BnJfNLFo.js} +5 -3
- package/dist/browser/index.cjs +2 -2
- package/dist/browser/index.js +2 -2
- package/dist/{builder-x295GDL6.js → builder-Cl-0BWkh.js} +2 -2
- package/dist/{builder-D8Osghdo.cjs → builder-Cw8u3pPl.cjs} +2 -2
- package/dist/capabilities/302ai.json +192 -192
- package/dist/capabilities/abliteratedllm.json +34 -34
- package/dist/capabilities/abliteration-ai.json +11 -11
- package/dist/capabilities/above.json +17 -17
- package/dist/capabilities/adaption.json +12 -12
- package/dist/capabilities/adzuki.json +30 -30
- package/dist/capabilities/agentrouter.json +10 -10
- package/dist/capabilities/agnes.json +4 -4
- package/dist/capabilities/ai-router.json +9 -9
- package/dist/capabilities/aiand.json +19 -11
- package/dist/capabilities/aigrow.json +11 -11
- package/dist/capabilities/aimlapi.json +146 -149
- package/dist/capabilities/aipg.json +2 -2
- package/dist/capabilities/aixy.json +14 -14
- package/dist/capabilities/aki-io.json +11 -11
- package/dist/capabilities/alibaba-cn.json +128 -109
- package/dist/capabilities/alibaba-coding-plan-cn.json +7 -19
- package/dist/capabilities/alibaba-coding-plan.json +7 -19
- package/dist/capabilities/alibaba-token-plan-cn.json +49 -67
- package/dist/capabilities/alibaba-token-plan.json +51 -69
- package/dist/capabilities/alibaba.json +71 -118
- package/dist/capabilities/ambient.json +14 -14
- package/dist/capabilities/amd.json +11 -11
- package/dist/capabilities/anthropic.json +48 -48
- package/dist/capabilities/anyapi.json +18 -18
- package/dist/capabilities/apiko.json +2 -2
- package/dist/capabilities/arcee.json +10 -10
- package/dist/capabilities/augure.json +6 -6
- package/dist/capabilities/auriko.json +20 -20
- package/dist/capabilities/bailing.json +5 -5
- package/dist/capabilities/baseten.json +46 -16
- package/dist/capabilities/bee.json +5 -5
- package/dist/capabilities/berget.json +4 -4
- package/dist/capabilities/bothub.json +16 -16
- package/dist/capabilities/boundless.json +36 -36
- package/dist/capabilities/bumo.json +40 -40
- package/dist/capabilities/byteplus.json +32 -32
- package/dist/capabilities/cerebras.json +4 -4
- package/dist/capabilities/cheapaimodel.json +5 -5
- package/dist/capabilities/cheapest-token.json +24 -24
- package/dist/capabilities/chutes.json +9 -9
- package/dist/capabilities/cline-pass.json +37 -37
- package/dist/capabilities/cloudcode.json +4 -4
- package/dist/capabilities/cloudflare-workers-ai.json +24 -24
- package/dist/capabilities/commandcode.json +152 -152
- package/dist/capabilities/concentrate.json +290 -266
- package/dist/capabilities/cortecs.json +105 -105
- package/dist/capabilities/crossmodel.json +160 -160
- package/dist/capabilities/crusoe.json +10 -10
- package/dist/capabilities/daoxe.json +7 -7
- package/dist/capabilities/databricks.json +318 -62
- package/dist/capabilities/deepinfra.json +73 -129
- package/dist/capabilities/deepseek.json +2 -2
- package/dist/capabilities/digitalocean.json +114 -114
- package/dist/capabilities/dothoosh.json +28 -28
- package/dist/capabilities/doubleword.json +24 -24
- package/dist/capabilities/edenai.json +458 -458
- package/dist/capabilities/empiriolabs.json +166 -166
- package/dist/capabilities/engy.json +20 -20
- package/dist/capabilities/evroc.json +8 -8
- package/dist/capabilities/ezkielyna.json +8 -8
- package/dist/capabilities/fastrouter.json +85 -85
- package/dist/capabilities/fireworks-ai.json +107 -44
- package/dist/capabilities/freemodel.json +23 -23
- package/dist/capabilities/friendli.json +9 -9
- package/dist/capabilities/frogbot.json +94 -94
- package/dist/capabilities/gisoo.json +16 -16
- package/dist/capabilities/gmicloud.json +17 -17
- package/dist/capabilities/google.json +57 -57
- package/dist/capabilities/graphn.json +10 -10
- package/dist/capabilities/greenpt.json +36 -36
- package/dist/capabilities/groq.json +2 -2
- package/dist/capabilities/helicone.json +68 -68
- package/dist/capabilities/hopper.json +2 -2
- package/dist/capabilities/hostinger-router.json +12 -12
- package/dist/capabilities/hpc-ai.json +13 -13
- package/dist/capabilities/huawei-maas.json +17 -17
- package/dist/capabilities/hubris.json +30 -30
- package/dist/capabilities/huggingface.json +193 -37
- package/dist/capabilities/hyper.json +23 -23
- package/dist/capabilities/impossibl.json +140 -140
- package/dist/capabilities/inception.json +2 -2
- package/dist/capabilities/inceptron.json +4 -4
- package/dist/capabilities/inco.json +3 -3
- package/dist/capabilities/infer.json +15 -15
- package/dist/capabilities/inferall.json +10 -10
- package/dist/capabilities/inference-coop.json +9 -9
- package/dist/capabilities/inferenceapis.json +9 -9
- package/dist/capabilities/inferris.json +3 -3
- package/dist/capabilities/infersia.json +2 -2
- package/dist/capabilities/inferx.json +3 -3
- package/dist/capabilities/infomaniak.json +4 -4
- package/dist/capabilities/io-net.json +2 -2
- package/dist/capabilities/isoquant.json +4 -4
- package/dist/capabilities/iteracompute.json +60 -60
- package/dist/capabilities/jad-ai.json +3 -3
- package/dist/capabilities/jalapeno.json +12 -12
- package/dist/capabilities/jiekou.json +63 -63
- package/dist/capabilities/jzstoken.json +50 -50
- package/dist/capabilities/keln.json +14 -21
- package/dist/capabilities/kenari.json +123 -120
- package/dist/capabilities/kilo.json +622 -647
- package/dist/capabilities/kimi-code-plan-cn.json +5 -5
- package/dist/capabilities/kimi-code-plan-global.json +5 -5
- package/dist/capabilities/kitani.json +6 -6
- package/dist/capabilities/klavo.json +18 -18
- package/dist/capabilities/korouter.json +29 -29
- package/dist/capabilities/kunavo.json +10 -10
- package/dist/capabilities/liquid.json +11 -11
- package/dist/capabilities/lithosai.json +2 -2
- package/dist/capabilities/llmgateway-providers.json +932 -905
- package/dist/capabilities/llmgateway.json +336 -336
- package/dist/capabilities/llmtr.json +22 -22
- package/dist/capabilities/logits.json +2 -2
- package/dist/capabilities/longcat.json +2 -7
- package/dist/capabilities/lowrouter.json +54 -54
- package/dist/capabilities/lyceum.json +12 -12
- package/dist/capabilities/melious.json +13 -13
- package/dist/capabilities/merge-gateway.json +260 -260
- package/dist/capabilities/meta.json +7 -7
- package/dist/capabilities/mistral.json +20 -20
- package/dist/capabilities/mixlayer.json +4 -4
- package/dist/capabilities/modal.json +10 -10
- package/dist/capabilities/model-oracle-ai.json +25 -25
- package/dist/capabilities/modelis.json +20 -20
- package/dist/capabilities/modular.json +6 -6
- package/dist/capabilities/moneo.json +16 -16
- package/dist/capabilities/moonshotai-cn.json +7 -7
- package/dist/capabilities/moonshotai.json +7 -7
- package/dist/capabilities/morph.json +11 -11
- package/dist/capabilities/munito-eu.json +6 -6
- package/dist/capabilities/munito.json +6 -6
- package/dist/capabilities/nan.json +27 -27
- package/dist/capabilities/nano-gpt.json +578 -578
- package/dist/capabilities/nearai.json +84 -84
- package/dist/capabilities/nebius.json +37 -28
- package/dist/capabilities/neon.json +126 -126
- package/dist/capabilities/neuralwatt.json +41 -41
- package/dist/capabilities/nokeep.json +4 -4
- package/dist/capabilities/novita-ai.json +154 -154
- package/dist/capabilities/nvidia.json +35 -35
- package/dist/capabilities/oathbreaker.json +2 -2
- package/dist/capabilities/obscurify.json +32 -32
- package/dist/capabilities/oci.json +7 -7
- package/dist/capabilities/ofox.json +357 -357
- package/dist/capabilities/ollama-cloud.json +56 -56
- package/dist/capabilities/openai.json +51 -51
- package/dist/capabilities/opencode-go.json +85 -84
- package/dist/capabilities/openrouter.json +542 -567
- package/dist/capabilities/opper.json +30 -24
- package/dist/capabilities/orcarouter.json +236 -236
- package/dist/capabilities/outerlabs.json +32 -32
- package/dist/capabilities/ovhcloud.json +7 -7
- package/dist/capabilities/pareto.json +6 -6
- package/dist/capabilities/pendra.json +4 -4
- package/dist/capabilities/perplexity-agent.json +61 -61
- package/dist/capabilities/phala.json +34 -34
- package/dist/capabilities/pioneer.json +30 -30
- package/dist/capabilities/poe.json +136 -136
- package/dist/capabilities/powerspring.json +13 -13
- package/dist/capabilities/primalabs.json +10 -10
- package/dist/capabilities/prime.json +124 -107
- package/dist/capabilities/privatemode-ai.json +14 -14
- package/dist/capabilities/proxystacks.json +6 -6
- package/dist/capabilities/qiniu-ai.json +16 -16
- package/dist/capabilities/refuseless.json +6 -6
- package/dist/capabilities/regolo-ai.json +6 -6
- package/dist/capabilities/requesty.json +172 -172
- package/dist/capabilities/ruapi.json +17 -17
- package/dist/capabilities/runcrate.json +5 -5
- package/dist/capabilities/runinfra.json +13 -13
- package/dist/capabilities/sakana.json +6 -6
- package/dist/capabilities/sambanova.json +9 -9
- package/dist/capabilities/sandbase.json +27 -27
- package/dist/capabilities/sarvam.json +12 -12
- package/dist/capabilities/scaleway.json +14 -14
- package/dist/capabilities/scnet-token-plan.json +9 -9
- package/dist/capabilities/scx-ai.json +26 -26
- package/dist/capabilities/sensenova.json +12 -12
- package/dist/capabilities/siliconflow-cn.json +49 -49
- package/dist/capabilities/siliconflow.json +46 -46
- package/dist/capabilities/snowflake-cortex.json +20 -20
- package/dist/capabilities/sokkan.json +7 -7
- package/dist/capabilities/sparrowcodes.json +25 -25
- package/dist/capabilities/standardcompute.json +102 -102
- package/dist/capabilities/steadyrouter.json +40 -40
- package/dist/capabilities/stepfun-ai-step-plan.json +6 -6
- package/dist/capabilities/stepfun-ai.json +15 -8
- package/dist/capabilities/stepfun-step-plan.json +15 -8
- package/dist/capabilities/stepfun.json +15 -8
- package/dist/capabilities/stepping-stone.json +16 -16
- package/dist/capabilities/synthetic.json +13 -13
- package/dist/capabilities/synthorai.json +19 -19
- package/dist/capabilities/teamorouter.json +24 -24
- package/dist/capabilities/teapot-router.json +13 -13
- package/dist/capabilities/tencent-coding-plan.json +1 -23
- package/dist/capabilities/tencent-token-plan.json +60 -23
- package/dist/capabilities/tencent-tokenhub.json +182 -7
- package/dist/capabilities/tensorx.json +50 -50
- package/dist/capabilities/tenstorrent.json +6 -6
- package/dist/capabilities/the-grid-ai.json +28 -28
- package/dist/capabilities/thinkingmachines.json +72 -55
- package/dist/capabilities/tinfoil.json +13 -13
- package/dist/capabilities/toapis.json +2 -2
- package/dist/capabilities/togetherai.json +54 -83
- package/dist/capabilities/tokengo.json +25 -25
- package/dist/capabilities/tokenify.json +9 -9
- package/dist/capabilities/trustedrouter.json +4 -4
- package/dist/capabilities/trustedtokens.json +17 -17
- package/dist/capabilities/umans-ai-coding-plan.json +13 -13
- package/dist/capabilities/umans-ai.json +10 -10
- package/dist/capabilities/unrestricted.json +6 -6
- package/dist/capabilities/uplinkswitch.json +21 -21
- package/dist/capabilities/upstage.json +4 -4
- package/dist/capabilities/vancine.json +23 -23
- package/dist/capabilities/vercel.json +540 -527
- package/dist/capabilities/vivgrid.json +80 -80
- package/dist/capabilities/volcengine-coding-plan.json +24 -54
- package/dist/capabilities/volcengine.json +55 -60
- package/dist/capabilities/vultr.json +24 -24
- package/dist/capabilities/wafer.ai.json +19 -19
- package/dist/capabilities/wallaby.json +5 -5
- package/dist/capabilities/wally.json +11 -11
- package/dist/capabilities/wandb.json +21 -21
- package/dist/capabilities/watt.json +24 -24
- package/dist/capabilities/xai.json +7 -7
- package/dist/capabilities/xiaomi-token-plan-ams.json +2 -12
- package/dist/capabilities/xiaomi-token-plan-cn.json +2 -12
- package/dist/capabilities/xiaomi-token-plan-sgp.json +2 -12
- package/dist/capabilities/xiaomi.json +3 -25
- package/dist/capabilities/xpersona.json +13 -13
- package/dist/capabilities/xxapi.json +31 -31
- package/dist/capabilities/zai-coding-plan.json +18 -18
- package/dist/capabilities/zai.json +49 -26
- package/dist/capabilities/zenifra.json +26 -26
- package/dist/capabilities/zenmux.json +205 -205
- package/dist/capabilities/zerogpu.json +11 -11
- package/dist/capabilities/zhipuai-coding-plan.json +6 -6
- package/dist/capabilities/zhipuai.json +39 -24
- package/dist/capabilities/zro.json +6 -6
- package/dist/channels/index.cjs +2 -2
- package/dist/channels/index.js +2 -2
- package/dist/{channels-Dx4jiXeK.js → channels-Cz1y3W6u.js} +1 -1
- package/dist/{channels-q6qnuRNV.cjs → channels-DQg4v_gm.cjs} +1 -1
- package/dist/coding-agent/index.cjs +2 -2
- package/dist/coding-agent/index.js +2 -2
- package/dist/datasets/dataset.d.ts +13 -6
- package/dist/datasets/experiment/durable.d.ts +16 -0
- package/dist/datasets/experiment/index.d.ts +2 -1
- package/dist/datasets/experiment/item.d.ts +26 -4
- package/dist/datasets/experiment/retries.d.ts +18 -0
- package/dist/datasets/experiment/types.d.ts +18 -0
- package/dist/datasets/experiment/workflow-id.d.ts +7 -0
- package/dist/datasets/experiment/workflow.d.ts +74 -0
- package/dist/datasets/index.cjs +3 -2
- package/dist/datasets/index.d.ts +2 -1
- package/dist/datasets/index.js +3 -3
- package/dist/docs/SKILL.md +4 -3
- package/dist/docs/assets/SOURCE_MAP.json +928 -903
- package/dist/docs/references/docs-deployment-workers.md +1 -1
- package/dist/docs/references/docs-evals-experiments.md +29 -1
- package/dist/docs/references/docs-harness-background-tasks.md +4 -1
- package/dist/docs/references/docs-harness-durable-agents.md +9 -5
- package/dist/docs/references/docs-knowledge-agents-and-tools.md +1 -0
- package/dist/docs/references/docs-knowledge-importers.md +195 -0
- package/dist/docs/references/docs-knowledge-load-your-content.md +2 -2
- package/dist/docs/references/docs-knowledge-overview.md +1 -1
- package/dist/docs/references/docs-mastra-platform-observability-overview.md +1 -1
- package/dist/docs/references/docs-sandbox-filesystem.md +1 -1
- package/dist/docs/references/docs-server-pubsub.md +51 -8
- package/dist/docs/references/docs-signals-running-across-processes.md +2 -0
- package/dist/docs/references/docs-signals-thread-streams.md +1 -1
- package/dist/docs/references/docs-studio-auth.md +54 -7
- package/dist/docs/references/docs-workflows-overview.md +1 -1
- package/dist/docs/references/docs-workflows-scheduled-workflows.md +1 -1
- package/dist/docs/references/integrations-auth-clerk.md +48 -4
- package/dist/docs/references/integrations-channels-slack.md +4 -2
- package/dist/docs/references/integrations.md +6 -0
- package/dist/docs/references/reference-agents-agent.md +3 -1
- package/dist/docs/references/reference-agents-channels.md +116 -27
- package/dist/docs/references/reference-agents-durable-agent.md +12 -4
- package/dist/docs/references/reference-auth-clerk.md +21 -1
- package/dist/docs/references/reference-datasets-runExperimentItem.md +13 -1
- package/dist/docs/references/reference-datasets-startExperimentAsync.md +3 -1
- package/dist/docs/references/reference-editor-mastra-editor.md +3 -1
- package/dist/docs/references/reference-knowledge-knowledge-class.md +13 -6
- package/dist/docs/references/reference-knowledge-knowledge-tools.md +43 -20
- package/dist/docs/references/reference-memory-observational-memory.md +2 -2
- package/dist/docs/references/reference-processors-moderation-processor.md +2 -2
- package/dist/docs/references/reference-pubsub-base.md +5 -1
- package/dist/docs/references/reference-pubsub-event-emitter.md +2 -0
- package/dist/docs/references/reference-pubsub-redis-streams.md +1 -1
- package/dist/docs/references/reference-pubsub-unix-socket-pubsub.md +2 -0
- package/dist/docs/references/reference-streaming-ChunkType.md +3 -3
- package/dist/docs/references/reference-workers-overview.md +1 -1
- package/dist/docs/references/reference-workflows-run-methods-start.md +23 -0
- package/dist/docs/references/reference-workflows-run-methods-timeTravel.md +4 -0
- package/dist/docs/references/reference-workflows-run.md +1 -1
- package/dist/docs/references/reference-workspace-local-sandbox.md +2 -0
- package/dist/error/index.cjs +1 -1
- package/dist/error/index.js +1 -1
- package/dist/{error-C9d_24w-.js → error-BLwEXqOK.js} +2 -2
- package/dist/{error-BRQf2ku0.cjs → error-BdEvO8za.cjs} +2 -2
- package/dist/evals/index.cjs +1 -1
- package/dist/evals/index.js +1 -1
- package/dist/evals/scoreTraces/index.cjs +1 -1
- package/dist/evals/scoreTraces/index.js +1 -1
- package/dist/events/caching-pubsub.d.ts +1 -0
- package/dist/events/event-emitter/index.d.ts +12 -5
- package/dist/events/index.cjs +15 -1
- package/dist/events/index.js +15 -1
- package/dist/events/pubsub.d.ts +29 -0
- package/dist/events/reach.d.ts +11 -0
- package/dist/events/unix-socket-pubsub.d.ts +14 -0
- package/dist/features/index.cjs +1 -0
- package/dist/features/index.js +1 -0
- package/dist/{filesystem-B5X-5G0x.js → filesystem-B8ad6kAW.js} +1 -1
- package/dist/{filesystem-BDSpwBke.cjs → filesystem-BB5YWXH-.cjs} +1 -1
- package/dist/{filesystem-DzM9pcQ8.js → filesystem-BDHUxbHn.js} +1 -1
- package/dist/{filesystem-B0AZrbj8.cjs → filesystem-BP5yz5LG.cjs} +1 -1
- package/dist/{filesystem-BsdkC311.js → filesystem-B_afSgYk.js} +1 -1
- package/dist/{filesystem-C-cyJfi1.cjs → filesystem-BaOJOc-V.cjs} +1 -1
- package/dist/{filesystem-B3s0WRud.js → filesystem-BhYgU8qg.js} +1 -1
- package/dist/{filesystem-DzfqVTO_.js → filesystem-CLBVmR5j.js} +1 -1
- package/dist/{filesystem-CEbD_77-.cjs → filesystem-Cgxc2a_-.cjs} +1 -1
- package/dist/{filesystem-Cv79mHRk.js → filesystem-ClBOBoDc.js} +1 -1
- package/dist/{filesystem-DsCQiBl2.cjs → filesystem-DVVecqZt.cjs} +1 -1
- package/dist/{filesystem-CUAgLugE.cjs → filesystem-Fpsu7e24.cjs} +1 -1
- package/dist/{filesystem-versioned-Bijb_p9l.js → filesystem-versioned-BL1ojJLo.js} +1 -1
- package/dist/{filesystem-versioned-DZGyPbNC.cjs → filesystem-versioned-BavRtYWJ.cjs} +1 -1
- package/dist/harness/index.cjs +1 -1
- package/dist/harness/index.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/knowledge/config.d.ts +10 -0
- package/dist/knowledge/host-writes.d.ts +10 -0
- package/dist/knowledge/importers/conformance.d.ts +25 -0
- package/dist/knowledge/importers/define.d.ts +204 -0
- package/dist/knowledge/importers/host.d.ts +143 -0
- package/dist/knowledge/importers/index.d.ts +12 -0
- package/dist/knowledge/importers/local-host.d.ts +106 -0
- package/dist/knowledge/importers/manifest.d.ts +25 -0
- package/dist/knowledge/importers/runner.d.ts +61 -0
- package/dist/knowledge/importers/sink.d.ts +105 -0
- package/dist/knowledge/importers/types.d.ts +144 -0
- package/dist/knowledge/index.cjs +2715 -8
- package/dist/knowledge/index.d.ts +54 -4
- package/dist/knowledge/index.js +2692 -9
- package/dist/knowledge/instructions.d.ts +1 -1
- package/dist/knowledge/links.d.ts +8 -0
- package/dist/knowledge/pinned-state-processor.d.ts +5 -0
- package/dist/knowledge/pinned.d.ts +4 -1
- package/dist/knowledge/scope-runtime.d.ts +10 -0
- package/dist/llm/index.cjs +3 -3
- package/dist/llm/index.js +3 -3
- package/dist/llm/model/provider-types.generated.d.ts +7812 -7831
- package/dist/llm/model/shared.types.d.ts +31 -0
- package/dist/{llm-CsQuqKPc.cjs → llm-8Av3mSjD.cjs} +2 -2
- package/dist/{llm-DnXK3Pmw.js → llm-B5A5cwJr.js} +2 -2
- package/dist/loop/index.cjs +2 -2
- package/dist/loop/index.js +2 -2
- package/dist/loop/workflows/agentic-execution/llm-execution-step.d.ts +2 -2
- package/dist/{manager-BsghM-UL.js → manager-DfWQCJUK.js} +460 -94
- package/dist/{manager-DwFnIrI6.cjs → manager-sv35JY-z.cjs} +476 -92
- package/dist/mastra/index.cjs +1 -1
- package/dist/mastra/index.d.ts +13 -0
- package/dist/mastra/index.js +1 -1
- package/dist/mastra/resolve-agent.d.ts +3 -1
- package/dist/{mastra-B8i1UDZs.js → mastra-CigBrT7X.js} +32 -23
- package/dist/{mastra-Cn5NC6Es.cjs → mastra-D4hvfuxX.cjs} +34 -25
- package/dist/memory/index.cjs +3 -3
- package/dist/memory/index.js +3 -3
- package/dist/{message-list-DPXPXvin.cjs → message-list-Cj0Sq_JP.cjs} +63 -8
- package/dist/{message-list-DEuRl82K.js → message-list-KRbg-TnI.js} +63 -8
- package/dist/{model-CNPfry_X.cjs → model-BK93CMtl.cjs} +1 -1
- package/dist/{model-CsOcWMUt.js → model-CYtXw861.js} +1 -1
- package/dist/{netlify-C-83Fxus.cjs → netlify-BAnn3ouY.cjs} +1 -1
- package/dist/{netlify-C-OpNSGp.js → netlify-CuI1ZrwR.js} +1 -1
- package/dist/notifications/index.cjs +1 -1
- package/dist/notifications/index.js +1 -1
- package/dist/{output-helpers-JL-HeCbT.cjs → output-helpers-1Zu4Vt9C.cjs} +68 -25
- package/dist/{output-helpers-D4II19No.js → output-helpers-CedRCE17.js} +69 -26
- package/dist/processor-provider/index.cjs +1 -1
- package/dist/processor-provider/index.js +1 -1
- package/dist/processors/abort-signal-scope.d.ts +6 -0
- package/dist/processors/index.cjs +2 -2
- package/dist/processors/index.js +2 -2
- package/dist/{provider-registry-9O-H9osy.cjs → provider-registry-BwuI_IpT.cjs} +21690 -21811
- package/dist/{provider-registry-RZ8EgSe8.js → provider-registry-CmQLzLF_.js} +21690 -21811
- package/dist/provider-registry.json +22113 -22215
- package/dist/{registry-generator-e8sltJls.js → registry-generator-C17V4WfG.js} +1 -1
- package/dist/{registry-generator-DxCX-FiO.cjs → registry-generator-C_0ae7Ce.cjs} +1 -1
- package/dist/{rehydrate-B-wrAN7C.cjs → rehydrate-CDQ4dOYj.cjs} +2 -2
- package/dist/{rehydrate-D3fPgJwp.js → rehydrate-PnaVawGX.js} +2 -2
- package/dist/relevance/index.cjs +2 -2
- package/dist/relevance/index.js +2 -2
- package/dist/{run-registry-5_LQBGn_.cjs → run-registry-BmckDVBk.cjs} +1698 -497
- package/dist/{run-registry-DC03XLeZ.js → run-registry-BwEcwYlU.js} +1614 -467
- package/dist/{source-DDwx-87N.cjs → source-BVOi8Xhp.cjs} +1 -1
- package/dist/{source-Did_2XQc.js → source-fNa6u1kH.js} +1 -1
- package/dist/storage/domains/agents/index.cjs +1 -1
- package/dist/storage/domains/agents/index.js +1 -1
- package/dist/storage/domains/knowledge/base.d.ts +72 -0
- package/dist/storage/domains/knowledge/importers-inmemory.d.ts +146 -0
- package/dist/storage/domains/knowledge/importers.d.ts +287 -0
- package/dist/storage/domains/knowledge/index.d.ts +1 -0
- package/dist/storage/domains/knowledge/inmemory.d.ts +12 -0
- package/dist/storage/domains/knowledge/pages-inmemory.d.ts +12 -1
- package/dist/storage/domains/knowledge/pages.d.ts +25 -7
- package/dist/storage/domains/mcp-clients/index.cjs +1 -1
- package/dist/storage/domains/mcp-clients/index.js +1 -1
- package/dist/storage/domains/mcp-servers/index.cjs +1 -1
- package/dist/storage/domains/mcp-servers/index.js +1 -1
- package/dist/storage/domains/prompt-blocks/index.cjs +1 -1
- package/dist/storage/domains/prompt-blocks/index.js +1 -1
- package/dist/storage/domains/scorer-definitions/index.cjs +1 -1
- package/dist/storage/domains/scorer-definitions/index.js +1 -1
- package/dist/storage/domains/skills/index.cjs +1 -1
- package/dist/storage/domains/skills/index.js +1 -1
- package/dist/storage/domains/workspaces/index.cjs +1 -1
- package/dist/storage/domains/workspaces/index.js +1 -1
- package/dist/storage/index.cjs +15 -10
- package/dist/storage/index.js +11 -11
- package/dist/stream/base/output.d.ts +59 -15
- package/dist/stream/index.cjs +2 -2
- package/dist/stream/index.js +2 -2
- package/dist/stream/types.d.ts +24 -2
- package/dist/{stream-4aNIw_TQ.cjs → stream-0kdqBOOn.cjs} +64 -9
- package/dist/{stream-CJUm6EAH.js → stream-D1y9GzoD.js} +29 -10
- package/dist/test-utils/llm-mock.cjs +1 -1
- package/dist/test-utils/llm-mock.js +1 -1
- package/dist/tool-loop-agent/index.cjs +1 -1
- package/dist/tool-loop-agent/index.js +1 -1
- package/dist/{tool-loop-agent-FEEwHfmg.js → tool-loop-agent-BdjWGVIb.js} +4 -4
- package/dist/{tool-loop-agent-Dn0QCB9n.cjs → tool-loop-agent-kWaZAT6Q.cjs} +4 -4
- package/dist/tools/types.d.ts +27 -1
- package/dist/{utils-DY01hxVd.cjs → utils-BKUCaZ12.cjs} +1 -1
- package/dist/{utils-Bd_y1_a-.js → utils-GHY3hmLx.js} +1 -1
- package/dist/utils.cjs +1 -1
- package/dist/utils.js +1 -1
- package/dist/{validate-CX0yQo_q.js → validate-CB-q-R2F.js} +1 -1
- package/dist/{validate-CuB_1Zd3.cjs → validate-De92squ7.cjs} +1 -1
- package/dist/vector/index.cjs +2 -2
- package/dist/vector/index.js +2 -2
- package/dist/worker/index.cjs +1 -1
- package/dist/worker/index.js +1 -1
- package/dist/{worker-CbaSmip-.cjs → worker-BbWPQuPR.cjs} +2 -2
- package/dist/{worker-B80xkcKG.js → worker-C3u_xzY2.js} +2 -2
- package/dist/{worker-GsGIxPMa.cjs → worker-CAKvQj9_.cjs} +2 -2
- package/dist/{worker-DSEfMPmq.js → worker-Kwm8EKcj.js} +2 -2
- package/dist/{workflow-CnBPXTpv.cjs → workflow-CSjXeNcR.cjs} +4 -4
- package/dist/{workflow-CZHY_C85.js → workflow-CVmI1Sw-.js} +4 -4
- package/dist/workflows/builder/index.cjs +1 -1
- package/dist/workflows/builder/index.js +1 -1
- package/dist/workflows/evented/index.cjs +1 -1
- package/dist/workflows/evented/index.js +1 -1
- package/dist/workflows/evented/setup-warning.d.ts +18 -0
- package/dist/workflows/evented/workflow-event-processor/run-status.d.ts +37 -0
- package/dist/workflows/evented/workflow.d.ts +10 -0
- package/dist/workflows/index.cjs +4 -4
- package/dist/workflows/index.js +4 -4
- package/dist/workflows/workflow.d.ts +6 -1
- package/dist/workspace/filesystem/filesystem.d.ts +5 -0
- package/dist/workspace/index.cjs +1 -1
- package/dist/workspace/index.js +1 -1
- package/dist/workspace/sandbox/local-sandbox.d.ts +16 -7
- package/dist/workspace/sandbox/native-sandbox/types.d.ts +11 -1
- package/dist/{workspace-D7TIleIt.js → workspace-DY2Nxiyi.js} +235 -34
- package/dist/{workspace-D2drutNg.cjs → workspace-X2RHJZU9.cjs} +235 -34
- package/package.json +7 -7
- package/src/llm/model/provider-types.generated.d.ts +7812 -7831
|
@@ -1,17 +1,17 @@
|
|
|
1
1
|
import { i as __toESM, t as __commonJSMin } from "./rolldown-runtime-tIEjjQTE.js";
|
|
2
2
|
import { a as RegisteredLogger, t as ConsoleLogger, u as noopLogger } from "./logger-BwbmRqfc.js";
|
|
3
3
|
import { t as MastraBase } from "./base-CKLWBhDo.js";
|
|
4
|
-
import { _ as NoopLeaseProvider, c as RUN_LOG_TTL_MS, f as slimNestedAgentChunks, g as EventEmitterPubSub, h as withAck, m as stripModelSnapshots, n as PublisherQueueLimitError, o as serializeError$1, r as CachingPubSub, t as DefaultStepResult, u as isRunLocalTopic, y as isLeaseProvider } from "./output-helpers-D4II19No.js";
|
|
5
4
|
import { A as compactStopReasonContext, D as agentLoopTermination, O as executionFailureTermination, S as resolveObservabilityContext, b as wrapMastra, i as subtractReportedUsage, k as tripwireTermination, n as extractUsageMetrics, r as isUsageIncomplete, t as calculateObservedUsage, x as createObservabilityContext, y as unwrapMastraTracingProxy } from "./observability-D7RNOAPx.js";
|
|
6
5
|
import { a as MastraNonRetryableError, i as MastraError, n as ErrorDomain, o as getErrorFromUnknown, t as ErrorCategory } from "./error-oh2DLsP2.js";
|
|
7
|
-
import { c as describeProviderError, i as classifyProviderError, l as readProviderErrorDetails, t as recordTerminalErrorMessage } from "./error-
|
|
8
|
-
import { $ as
|
|
6
|
+
import { c as describeProviderError, i as classifyProviderError, l as readProviderErrorDetails, t as recordTerminalErrorMessage } from "./error-BLwEXqOK.js";
|
|
7
|
+
import { $ as resolveProcessorSpanAttributes, $t as computeModelOutputProviderMetadata, A as OUTPUT_STREAM_HOOK_DURATION_KEY_PREFIX, An as safeError, B as ProviderHistoryCompat, Bt as summarizeStepResult, C as markChunkOutputProcessed, Cn as isMastraTimeoutError, Ct as resolveTemplate, D as asJsonSchema, Dn as MastraModelInput, Dt as getStepResult, E as isStructuredOutputError, Et as validateTemplate, F as findOwnModelStepSpan, Ft as materializeState, G as REPROCESS_PART_KEY, Gt as patchState, Ht as applyStatePatch, It as materializeWorkflowRun, J as summarizeActiveToolsForSpan, Jt as isObservationalMemoryEnabled$1, K as takeHeldParts, L as isTrailingAssistantGuardContinuation, Lt as pickStateKeys, M as ProcessorState, Mn as createRunScopeKey, Mt as applyStateColumnsWrite, N as endOutputStreamSpanAtStepEnd, Nt as isStateCheckpointDue, O as getResponseFormat, On as safeClose, Ot as getStepResultAsync, P as endOutputStreamSpanOutsideStep, Pt as latestStepResults, Q as summarizeToolChoiceForSpan, Qt as commitToolResult, R as needsTrailingAssistantGuard, Rt as stateBaseOf, S as stampChunkProducedAt, Sn as guardStreamWithAbort, T as escapeUnescapedControlCharsInJsonStrings, Tn as settledOrElapsed, Tt as traverseMappingPath, Vt as unusedStateEntries, W as FLUSH_HELD_PARTS_KEY, Wt as diffStateAsJson, X as summarizeProcessorResultForSpan, Xt as parseMemoryRequestContext, Y as summarizeProcessorModelForSpan, Z as summarizeProcessorToolsForSpan, _ as reconcileBufferedStepTexts, _n as DEADLINE_SAVE_WAIT_MS, _t as collectMappingStepRefs, a as convertFullStreamChunkToMastra, an as withAgentWorkflowToolMarker, at as RunJournal, b as resolveProcessorWriterMessageId, bn as getAbortReason, bt as resolveStepOutputs, c as WorkflowRunOutput, cn as isProcessorWorkflow, ct as hydrateStepResults, d as MastraModelOutput, dn as resolveThreadIdFromArgs, dt as loadStepResults, en as hasToolResultProcessor, et as resolveProcessorSpanName, f as clearStepPartIndexes, fn as supportedLanguageModelSpecifications, ft as loadedStepResults, g as persistProcessorDataChunk, gn as DEADLINE_SAVE_CLAIM_HOLD_MS, gt as stubStepResult, h as findStepPartBoundaries, hn as applyStateSignal, ht as storageV2StepResultAccessors, in as snapshotToolResult, it as PROCESSOR_ABORT_SIGNAL, j as ProcessorRunner, jn as createRunScope, k as isSignalChunkExcluded, kn as safeEnqueue, kt as getSnapshotMemoryInfo, l as TripWire, ln as isSupportedLanguageModel, lt as isStepResultStub, m as findIterationOffsetInParts, mn as tryStreamWithJsonFallback, mt as residentStepResultsLoader, nn as readModelOutput, nt as PROCESSOR_LATE_SIGNAL_SINK, on as normalizeModelOutput, ot as buildStepResultAccessors, p as createDestructurableOutput, pn as tryGenerateWithJsonFallback, pt as residentStepResults, q as withoutHeldContent, rn as resolveModelOutputAfterToolResultProcessors, rt as createProcessorSendSignal, s as MastraAgentNetworkStream, sn as validationErrorModelOutput, st as getHydratedStepResult, tn as latestProcessedModelOutput, tt as toProcessorSpanPhase, u as getModelOutputForTripwire, un as resolveSuspendedToolRunId, ut as lazyStepResults, v as resolveMessageText, vn as MastraTimeoutError, vt as collectPredicateStepRefs, w as createOutputHandler, wn as raceAgainstAbort, wt as templateReadsState, x as getChunkProducedAt, xn as guardStreamUntilMatch, xt as stepRefId, y as resolveOutputMessageSkippingCompletionChecks, yn as createTimeoutAbortSignal, yt as predicateReadsState, z as removeTrailingAssistantGuardContinuations, zt as stateColumnsWrite } from "./stream-D1y9GzoD.js";
|
|
9
8
|
import { c as MASTRA_THREAD_ID_KEY, d as isReservedRequestContextKey, f as mergeVersionOverrides$1, l as MASTRA_VERSIONS_KEY, n as MASTRA_AUTH_TOKEN_KEY, o as MASTRA_RESOURCE_ID_KEY, p as withoutLiveRequestKeys, r as MASTRA_INHERITED_MEMORY_KEY, s as MASTRA_SCOPES_KEY, t as MASTRA_CONTINUATION_TOOL_CALL_IDS_KEY, u as RequestContext } from "./request-context-COnZHt2-.js";
|
|
10
|
-
import {
|
|
9
|
+
import { c as RUN_LOG_TTL_MS, f as slimNestedAgentChunks, g as NoopLeaseProvider, h as EventEmitterPubSub, m as stripModelSnapshots, n as PublisherQueueLimitError, o as serializeError$1, r as CachingPubSub, t as DefaultStepResult, u as isRunLocalTopic, v as isLeaseProvider, y as withAck } from "./output-helpers-CedRCE17.js";
|
|
10
|
+
import { A as stableStringify$1, E as removeWorkingMemoryTags, P as embed$3, Z as preserveResponseItemIdsOnMerge, a as isTerminalToolInvocationState, c as withUnavailableAttachmentUrls, d as aiV5UIMessagesToAIV5ModelMessages, f as coreContentToString, i as isClientToolInvocationUpdate, l as isDownloadAssetsError, m as filterMessagesForPersistence, n as MessageList, ot as normalizeToolOutput, p as messagesAreEqual, r as advancesToolInvocationState, s as unavailableAttachmentPlaceholder, t as convertMessages, u as MessageMerger } from "./message-list-KRbg-TnI.js";
|
|
11
11
|
import { Bt as listScoresArgsSchema, Ft as listLogsArgsSchema, Lt as listMetricsArgsSchema, Nt as listFeedbackArgsSchema, t as EntityType } from "./storage-Cc50aQAp.js";
|
|
12
12
|
import { a as getOrCreateSpan, f as resolveCurrentSpan, l as getTimeToFirstChunkMs, n as executeWithContextSync, o as getResumeTracingContext, p as resolveExportedSpanId, s as getRootExportSpan, t as executeWithContext, u as getWorkflowResumeTracingContext } from "./utils-DU_pU5SK.js";
|
|
13
13
|
import { i as setSpanErrorOrigin, n as getSpanErrorOrigin } from "./error-count-BH-rJW7q.js";
|
|
14
|
-
import { a as ModelRouterLanguageModel, d as attachModelStreamTransport, f as isDataChunk, i as resolveModelConfig, n as ModelRouterEmbeddingModel, o as resolveApiProviderId, p as readModelStreamTransport } from "./llm-
|
|
14
|
+
import { a as ModelRouterLanguageModel, d as attachModelStreamTransport, f as isDataChunk, i as resolveModelConfig, n as ModelRouterEmbeddingModel, o as resolveApiProviderId, p as readModelStreamTransport } from "./llm-B5A5cwJr.js";
|
|
15
15
|
import { a as withToolPayloadTransformMetadata, i as transformToolPayloadForTargets, n as hasTransformedToolPayload, o as withToolPayloadTransformProviderMetadata, r as normalizeToolPayloadTransformPolicy, t as getTransformedToolPayload } from "./payload-transform-Dj3HUeD4.js";
|
|
16
16
|
import { boundedStringify, ensureSerializable, safeStringify } from "./utils/safe-stringify.js";
|
|
17
17
|
import { d as signalSpanAttributes, h as signalToXmlMarkup, l as mastraDBMessageToSignal, n as createSignal, o as isMastraSignalMessage, s as isTransientSignalMessage, u as resolveDeliveryAttributes } from "./signals-CqR_iWkg.js";
|
|
@@ -24,13 +24,13 @@ import { _ as getRequestContextInputValues, a as getModelFacingValidationError,
|
|
|
24
24
|
import { a as isApprovalExempt, c as isProviderDefinedTool, d as markAgentWorkflowTool, f as markApprovalExempt, l as isProviderTool, n as getNeedsApprovalFn, o as isBuiltBeforeApproval, r as getProviderToolName, s as isMastraTool, t as getBeforeApprovalFn } from "./toolchecks-DrsZdc3S.js";
|
|
25
25
|
import { a as waitDelay, i as getRetryAfterMs, n as DEFAULT_MAX_RETRY_AFTER_MS, r as clampDelayMs } from "./fetchWithRetry-DFSvpYDT.js";
|
|
26
26
|
import { i as hasFreeFormObject } from "./model-DS-b2R-R.js";
|
|
27
|
-
import { c as modelSupportsStructuredOutput, l as modelSupportsTemperature } from "./provider-registry-
|
|
27
|
+
import { c as modelSupportsStructuredOutput, l as modelSupportsTemperature } from "./provider-registry-CmQLzLF_.js";
|
|
28
28
|
import { t as InMemoryServerCache } from "./inmemory-BDD0w8gx.js";
|
|
29
29
|
import { n as resolveDynamicArgument, t as getRequestUser } from "./dynamic-argument-BzPK3qPN.js";
|
|
30
|
-
import { t as MastraLLMV1 } from "./model-
|
|
31
|
-
import { A as eagerToolCallDidNotExecute, D as EagerToolExecutionCoordinator, E as EAGER_TOOL_EXECUTION_MARKER, F as hasRunningRunStep, I as isRunStepActive, L as setRunLeaseFence, M as isEagerlyExecutableToolCall, N as TOOL_ABORT_NOTICE, O as EagerToolExecutionNotRun, P as clearRunLeaseFence, R as startRunStep, S as selectFields, T as EAGER_TOOL_BAILOUT, a as ensureToolProperties, b as removeUndefinedValues, d as makeCoreTool, i as delay$1, j as eagerToolCallSuspensionIntent, k as eagerToolCallAlreadyAnnouncedInput, n as createMastraProxy, o as generateEmptyFromSchema, p as makeProcessorCoreTool, r as deepMerge$1, v as readPositiveIntEnv, w as EAGER_TOOL_ABORT_SIGNAL, y as rebindProcessorTools, z as whenRunStepsSettle } from "./utils-
|
|
30
|
+
import { t as MastraLLMV1 } from "./model-CYtXw861.js";
|
|
31
|
+
import { A as eagerToolCallDidNotExecute, D as EagerToolExecutionCoordinator, E as EAGER_TOOL_EXECUTION_MARKER, F as hasRunningRunStep, I as isRunStepActive, L as setRunLeaseFence, M as isEagerlyExecutableToolCall, N as TOOL_ABORT_NOTICE, O as EagerToolExecutionNotRun, P as clearRunLeaseFence, R as startRunStep, S as selectFields, T as EAGER_TOOL_BAILOUT, a as ensureToolProperties, b as removeUndefinedValues, d as makeCoreTool, i as delay$1, j as eagerToolCallSuspensionIntent, k as eagerToolCallAlreadyAnnouncedInput, n as createMastraProxy, o as generateEmptyFromSchema, p as makeProcessorCoreTool, r as deepMerge$1, v as readPositiveIntEnv, w as EAGER_TOOL_ABORT_SIGNAL, y as rebindProcessorTools, z as whenRunStepsSettle } from "./utils-GHY3hmLx.js";
|
|
32
32
|
import { h as getWorkflowFGAResourceId, i as MastraFGAPermissions, y as requireFGA } from "./ee-iTj2bRDt-By_B9ngH.js";
|
|
33
|
-
import { a as resolveBackgroundConfig, o as createBackgroundTask, t as generateBackgroundTaskSystemPrompt } from "./background-tasks-
|
|
33
|
+
import { a as resolveBackgroundConfig, o as createBackgroundTask, t as generateBackgroundTaskSystemPrompt } from "./background-tasks-BnJfNLFo.js";
|
|
34
34
|
import { t as ToolStream } from "./stream-D9JOykz7.js";
|
|
35
35
|
import { MISSING, collectInvalidPredicatePaths, createPredicateEvaluator, derivePredicateLabel, normalizePredicatePath, walk } from "./predicate/index.js";
|
|
36
36
|
import { Classifier } from "./classifier/index.js";
|
|
@@ -42,25 +42,25 @@ import { A as writeObjective, D as readObjective, O as resolveEffectiveGoalSetti
|
|
|
42
42
|
import { An as computeTraceStatus, Cr as extractTrajectory, Dr as saveScorePayloadSchema, It as TABLE_SCHEMAS, Lt as TABLE_SCORERS, Nn as extractBranchSpans, Pn as getBranchArgsSchema, Qn as listTracesArgsSchema, Sr as withBufferedReflectionVerified, Tr as extractWorkflowTrajectory, Yn as listBranchesArgsSchema, _r as isAppendOnlySince, ar as spanRecordSchema, br as maxObservationCursor, cr as toTraceSpans, gn as BRANCH_SPAN_TYPE_SET, gr as compareObservationalMemoryHeadOrder, hr as assertActiveObservationsApplied, or as toLightSpanRecord, pn as matchesExpectedWorkflowStatus, qn as isPreviewTruncated, sr as toTraceSpan, vn as TraceStatus, vr as isBufferedChunkCoveredByCursor, wr as extractTrajectoryFromTrace, xr as planReflectionGenerationText, yr as isBufferedReflectionUnchangedSince } from "./constants-BmdTvEYN.js";
|
|
43
43
|
import { t as GoalSignalProvider } from "./signal-provider-BslnAjWG.js";
|
|
44
44
|
import { t as slugify } from "./slugify-BUNmb-Ga.js";
|
|
45
|
-
import { N as LocalSandbox, at as LocalFilesystem, dt as sliceByTokensSafe, ft as estimateTokenCount, it as normalizeReadTrackerPath, lt as WORKSPACE_TOOLS, m as resolveToolConfig, mt as shellQuote, o as Workspace, p as createWorkspaceTools, pt as sliceByTokens, rt as evaluateReadRecord, s as createSkillTools, st as CompositeFilesystem } from "./workspace-
|
|
45
|
+
import { N as LocalSandbox, at as LocalFilesystem, dt as sliceByTokensSafe, ft as estimateTokenCount, it as normalizeReadTrackerPath, lt as WORKSPACE_TOOLS, m as resolveToolConfig, mt as shellQuote, o as Workspace, p as createWorkspaceTools, pt as sliceByTokens, rt as evaluateReadRecord, s as createSkillTools, st as CompositeFilesystem } from "./workspace-DY2Nxiyi.js";
|
|
46
46
|
import { i as normalizeWebSearchProvider, n as createWebSearchProviderTool, r as isWebSearchTool } from "./tools-CDfyMpzN.js";
|
|
47
47
|
import { D as BM25Index, O as tokenize } from "./workspace-skills-38OY32_b.js";
|
|
48
|
-
import { f as calculatePagination, g as InMemoryThreadStateStorage, h as resolveListOrderBy, m as normalizePerPage, p as compareByField, s as StorageDomain, u as MastraCompositeStore } from "./filesystem-versioned-
|
|
48
|
+
import { f as calculatePagination, g as InMemoryThreadStateStorage, h as resolveListOrderBy, m as normalizePerPage, p as compareByField, s as StorageDomain, u as MastraCompositeStore } from "./filesystem-versioned-BL1ojJLo.js";
|
|
49
49
|
import { coreFeatures } from "./features/index.js";
|
|
50
50
|
import { $n as traceQueryTimeRangeSchema, Dn as planThreadPredicate, En as planSpanQuerySelectionPredicate, Jt as TRACE_QUERY_ORDER_FIELDS, On as planThreadQuerySelectionPredicate, Qn as traceQuerySortValueSchema, Tn as planPredicate, Yt as TRACE_QUERY_PREDICATE_COMPLEXITY_MESSAGE, Zn as traceQueryScalarPredicateSchema, an as compareTraceQueryStrings, cn as formatTraceQuerySchemaIssues, en as TraceQueryCursorError, gn as isTraceQuerySortValueFor, in as TraceQueryValidationError, mn as hasTraceQueryTokenPredicate, sn as findPredicateComplexityIssue, yn as normalizeTraceQueryTenantScope } from "./dashboard-C3Cm0dWp.js";
|
|
51
|
-
import { i as InMemoryAgentsStorage, n as FilesystemAgentsStorage, r as InMemoryDB } from "./source-
|
|
51
|
+
import { i as InMemoryAgentsStorage, n as FilesystemAgentsStorage, r as InMemoryDB } from "./source-fNa6u1kH.js";
|
|
52
52
|
import { t as InMemoryFavoritesStorage } from "./inmemory-C4cocobU.js";
|
|
53
|
-
import { n as InMemoryMCPClientsStorage, t as FilesystemMCPClientsStorage } from "./filesystem-
|
|
54
|
-
import { n as InMemoryMCPServersStorage, t as FilesystemMCPServersStorage } from "./filesystem-
|
|
55
|
-
import { n as InMemoryPromptBlocksStorage, t as FilesystemPromptBlocksStorage } from "./filesystem-
|
|
56
|
-
import { n as InMemoryScorerDefinitionsStorage, t as FilesystemScorerDefinitionsStorage } from "./filesystem-
|
|
57
|
-
import { n as InMemorySkillsStorage, t as FilesystemSkillsStorage } from "./filesystem-
|
|
58
|
-
import { n as InMemoryWorkspacesStorage, t as FilesystemWorkspacesStorage } from "./filesystem-
|
|
53
|
+
import { n as InMemoryMCPClientsStorage, t as FilesystemMCPClientsStorage } from "./filesystem-B8ad6kAW.js";
|
|
54
|
+
import { n as InMemoryMCPServersStorage, t as FilesystemMCPServersStorage } from "./filesystem-ClBOBoDc.js";
|
|
55
|
+
import { n as InMemoryPromptBlocksStorage, t as FilesystemPromptBlocksStorage } from "./filesystem-CLBVmR5j.js";
|
|
56
|
+
import { n as InMemoryScorerDefinitionsStorage, t as FilesystemScorerDefinitionsStorage } from "./filesystem-BDHUxbHn.js";
|
|
57
|
+
import { n as InMemorySkillsStorage, t as FilesystemSkillsStorage } from "./filesystem-B_afSgYk.js";
|
|
58
|
+
import { n as InMemoryWorkspacesStorage, t as FilesystemWorkspacesStorage } from "./filesystem-BhYgU8qg.js";
|
|
59
59
|
import { n as resolveAgentSkills, t as mergeWorkspaceSkills } from "./agent-skills-resolver-CUEIMDbx.js";
|
|
60
60
|
import { n as DefaultVoice } from "./voice-OS-kmlEA.js";
|
|
61
61
|
import { TTLCache } from "@isaacs/ttlcache";
|
|
62
|
-
import EventEmitter$1 from "events";
|
|
63
62
|
import { any, array, boolean, custom, discriminatedUnion, enum as enum$1, instanceof as instanceof$1, json, lazy, literal, looseObject, never, null as null$1, number, object, record, safeParseAsync, string, union, unknown, z } from "zod/v4";
|
|
63
|
+
import EventEmitter$1 from "events";
|
|
64
64
|
import { ReadableStream as ReadableStream$1, TransformStream as TransformStream$1 } from "stream/web";
|
|
65
65
|
import { injectJsonInstructionIntoMessages, isAbortError } from "@ai-sdk/provider-utils-v6";
|
|
66
66
|
import { z as z$1 } from "zod";
|
|
@@ -77,6 +77,18 @@ import { readFile, realpath, stat } from "fs/promises";
|
|
|
77
77
|
import xxhash from "xxhash-wasm";
|
|
78
78
|
import { RE2JS } from "re2js";
|
|
79
79
|
import { LRUCache } from "lru-cache";
|
|
80
|
+
// src/events/reach.ts
|
|
81
|
+
/**
|
|
82
|
+
* Whether events published on `pubsub` can reach a subscriber in another
|
|
83
|
+
* process, read from the transport under any decorator.
|
|
84
|
+
*
|
|
85
|
+
* Only an explicit `false` counts as no. A pubsub built against a copy of
|
|
86
|
+
* `@mastra/core` that predates `deliversAcrossProcesses` has no such getter, and
|
|
87
|
+
* must keep being treated as a shared transport.
|
|
88
|
+
*/
|
|
89
|
+
function reachesOtherProcesses(pubsub) {
|
|
90
|
+
return pubsub.__rawBus().deliversAcrossProcesses !== false;
|
|
91
|
+
}
|
|
80
92
|
// src/storage/run-fencing.ts
|
|
81
93
|
const RUN_FENCE_CONFLICT_ERROR_ID = "STORAGE_RUN_FENCE_CONFLICT";
|
|
82
94
|
const RUN_FENCING_NOT_SUPPORTED_ERROR_ID = "STORAGE_RUN_FENCING_NOT_SUPPORTED";
|
|
@@ -761,6 +773,12 @@ function hasResumableStreams(agent) {
|
|
|
761
773
|
if (typeof agent.hasResumableStreams === "function") return agent.hasResumableStreams();
|
|
762
774
|
return isDurableAgentLike(agent);
|
|
763
775
|
}
|
|
776
|
+
// src/agent/streams/execution-capability.ts
|
|
777
|
+
/** Native engine selection or the released structural adapter contract (including Inngest). */
|
|
778
|
+
function hasDurableExecution(obj) {
|
|
779
|
+
if (isDurableAgentLike(obj)) return true;
|
|
780
|
+
return typeof obj === "object" && obj !== null && "__hasDurableExecution" in obj && typeof obj.__hasDurableExecution === "function" && obj.__hasDurableExecution() === true;
|
|
781
|
+
}
|
|
764
782
|
// src/workflows/stream-utils.ts
|
|
765
783
|
async function forwardAgentStreamChunk({ writer, chunk }) {
|
|
766
784
|
if (!writer) return;
|
|
@@ -789,8 +807,9 @@ function resolveEntryActor(stepOptions, runActor) {
|
|
|
789
807
|
* unwrapped to the agent it wraps. Warns because the step runs non-durably.
|
|
790
808
|
*/
|
|
791
809
|
function resolveLegacyAgent(agent, mastra) {
|
|
792
|
-
if (!
|
|
810
|
+
if (!hasDurableExecution(agent)) return agent;
|
|
793
811
|
mastra?.getLogger()?.warn(`Agent "${agent.id}" is durable but uses a legacy v1 model, which has no durable execution path, so the step runs it non-durably.`);
|
|
812
|
+
if (!isDurableAgentLike(agent)) return agent;
|
|
794
813
|
const inner = agent.agent;
|
|
795
814
|
return inner !== agent ? inner : agent;
|
|
796
815
|
}
|
|
@@ -1661,6 +1680,37 @@ const assertTimeTravelGraphMatchesSnapshot = (params) => {
|
|
|
1661
1680
|
}
|
|
1662
1681
|
if (missingStepIds.length > 0) throw new Error(`Cannot time travel to step '${targetStepId}': step(s) ${missingStepIds.map((id) => `'${id}'`).join(", ")} precede the target in the current execution graph but were not recorded in the snapshot. Either the workflow definition changed since the run was recorded (renamed steps, or unnamed .map() steps whose generated ids changed across processes), or the recorded run never reached these steps (it failed, was canceled, or was suspended before them). Steps recorded in the snapshot: ${reportedIdsSuffix}. The stored snapshot has not been modified.`);
|
|
1663
1682
|
};
|
|
1683
|
+
const nestedRunIdentity = (stored, isForeach) => {
|
|
1684
|
+
const metadata = stored?.metadata;
|
|
1685
|
+
const foreachNestedRunIds = metadata?.foreachNestedRunIds && typeof metadata.foreachNestedRunIds === "object" ? metadata.foreachNestedRunIds : void 0;
|
|
1686
|
+
const keepNestedRunId = !isForeach || !foreachNestedRunIds && Array.isArray(stored?.payload) && stored.payload.length === 1;
|
|
1687
|
+
const identity = removeUndefinedValues({
|
|
1688
|
+
nestedRunId: keepNestedRunId && typeof metadata?.nestedRunId === "string" ? metadata.nestedRunId : void 0,
|
|
1689
|
+
foreachNestedRunIds
|
|
1690
|
+
});
|
|
1691
|
+
return Object.keys(identity).length > 0 ? identity : void 0;
|
|
1692
|
+
};
|
|
1693
|
+
const withSettledForeachRecords = (suspendPayload, output) => {
|
|
1694
|
+
const records = suspendPayload?.__workflow_meta?.foreachOutput;
|
|
1695
|
+
if (!Array.isArray(records) || !Array.isArray(output)) return suspendPayload;
|
|
1696
|
+
let changed = false;
|
|
1697
|
+
const foreachOutput = output.map((slot, index) => {
|
|
1698
|
+
const record = records[index];
|
|
1699
|
+
if (record || slot === null || slot === void 0 || slot?.status === "suspended") return record ?? null;
|
|
1700
|
+
changed = true;
|
|
1701
|
+
return {
|
|
1702
|
+
status: "success",
|
|
1703
|
+
output: slot
|
|
1704
|
+
};
|
|
1705
|
+
});
|
|
1706
|
+
return changed ? {
|
|
1707
|
+
...suspendPayload,
|
|
1708
|
+
__workflow_meta: {
|
|
1709
|
+
...suspendPayload.__workflow_meta,
|
|
1710
|
+
foreachOutput
|
|
1711
|
+
}
|
|
1712
|
+
} : suspendPayload;
|
|
1713
|
+
};
|
|
1664
1714
|
const createTimeTravelExecutionParams = (params) => {
|
|
1665
1715
|
const { steps, inputData, resumeData, context, nestedStepsContext, snapshot, initialState, graph, perStep } = params;
|
|
1666
1716
|
const firstStepId = steps[0];
|
|
@@ -1722,12 +1772,13 @@ const createTimeTravelExecutionParams = (params) => {
|
|
|
1722
1772
|
payload: isFirstEntryTarget ? firstEntryInput : context?.[stepId]?.payload ?? stepPayload ?? snapshotContext[stepId]?.payload ?? {},
|
|
1723
1773
|
output: isCompleteStatus ? context?.[stepId]?.output ?? stepOutput ?? snapshotContext[stepId]?.output ?? {} : void 0,
|
|
1724
1774
|
resumePayload: stepContext?.resumePayload,
|
|
1725
|
-
suspendPayload: stepContext?.suspendPayload,
|
|
1775
|
+
suspendPayload: withSettledForeachRecords(stepContext?.suspendPayload, stepContext?.output),
|
|
1726
1776
|
suspendOutput: stepContext?.suspendOutput,
|
|
1727
1777
|
startedAt: stepContext?.startedAt ?? Date.now(),
|
|
1728
1778
|
endedAt: isCompleteStatus ? stepContext?.endedAt ?? Date.now() : void 0,
|
|
1729
1779
|
suspendedAt: stepContext?.suspendedAt,
|
|
1730
|
-
resumedAt: stepContext?.resumedAt
|
|
1780
|
+
resumedAt: stepContext?.resumedAt,
|
|
1781
|
+
metadata: nestedRunIdentity(snapshotContext[stepId], entry.type === "foreach")
|
|
1731
1782
|
};
|
|
1732
1783
|
if ((perStep ? executionPath.length : currentExecPathLength) > 0 && !steps?.includes(stepId) && !context?.[stepId] && (!snapshotContext[stepId] || snapshotContext[stepId] && snapshotContext[stepId].status !== "suspended")) result = void 0;
|
|
1733
1784
|
if (result) {
|
|
@@ -7487,6 +7538,7 @@ function createStepFromProcessor$1(processor) {
|
|
|
7487
7538
|
};
|
|
7488
7539
|
const passThrough = {
|
|
7489
7540
|
agent,
|
|
7541
|
+
abortSignal,
|
|
7490
7542
|
lateSignalSink,
|
|
7491
7543
|
phase,
|
|
7492
7544
|
runId: agentRunId,
|
|
@@ -8861,6 +8913,7 @@ var Workflow = class Workflow extends MastraBase {
|
|
|
8861
8913
|
snapshot: initialSnapshot,
|
|
8862
8914
|
workflowStatus: "pending"
|
|
8863
8915
|
}) : initialSnapshot, options?.resourceId, { stateBase: nestedRunStart?.inheritedState?.ref });
|
|
8916
|
+
if (nestedRun) nestedRun.inserted = true;
|
|
8864
8917
|
}
|
|
8865
8918
|
run.inheritedState = nestedRunStart?.inheritedState;
|
|
8866
8919
|
return run;
|
|
@@ -8920,19 +8973,20 @@ var Workflow = class Workflow extends MastraBase {
|
|
|
8920
8973
|
const nestedPubsub = useSharedPubsub ? pubsub : void 0;
|
|
8921
8974
|
let startState = state;
|
|
8922
8975
|
let startedFrom;
|
|
8923
|
-
if (!
|
|
8976
|
+
if (!isResume) {
|
|
8924
8977
|
startedFrom = toJsonState(state);
|
|
8925
8978
|
if (startedFrom) startState = copyState(state);
|
|
8926
8979
|
}
|
|
8927
8980
|
const inheritedState = !restart && !isResume ? await parentState?.(startState) : void 0;
|
|
8928
8981
|
this.#nestedRun = {
|
|
8929
8982
|
storageVersion: parentState ? 2 : 1,
|
|
8930
|
-
start: !
|
|
8983
|
+
start: !isResume ? {
|
|
8931
8984
|
input: inputData,
|
|
8932
8985
|
state: startState,
|
|
8933
8986
|
inheritedState
|
|
8934
8987
|
} : void 0
|
|
8935
8988
|
};
|
|
8989
|
+
const nestedRunHandoff = this.#nestedRun;
|
|
8936
8990
|
const run = isResume ? await this.createRun({
|
|
8937
8991
|
runId: resume.runId,
|
|
8938
8992
|
resourceId,
|
|
@@ -8973,6 +9027,7 @@ var Workflow = class Workflow extends MastraBase {
|
|
|
8973
9027
|
try {
|
|
8974
9028
|
let restartNested = !!restart;
|
|
8975
9029
|
let resumeNested = isResume;
|
|
9030
|
+
let storedPending = false;
|
|
8976
9031
|
if ((restart || isResume) && !isTimeTravel) {
|
|
8977
9032
|
const nestedSnapshot = await run.runStorage.loadHeader();
|
|
8978
9033
|
let nestedStatus = nestedSnapshot?.status;
|
|
@@ -8990,7 +9045,8 @@ var Workflow = class Workflow extends MastraBase {
|
|
|
8990
9045
|
else if (restart && nestedStatus === "suspended") {
|
|
8991
9046
|
restartNested = false;
|
|
8992
9047
|
resumeNested = true;
|
|
8993
|
-
}
|
|
9048
|
+
} else if (restart && !isResume && (!nestedSnapshot || nestedRunHandoff.inserted)) restartNested = false;
|
|
9049
|
+
storedPending = nestedStatus === "pending" && !nestedRunHandoff.inserted;
|
|
8994
9050
|
}
|
|
8995
9051
|
if (isTimeTravel) {
|
|
8996
9052
|
res = await run.timeTravel({
|
|
@@ -9013,6 +9069,7 @@ var Workflow = class Workflow extends MastraBase {
|
|
|
9013
9069
|
handBackBase = startedFrom;
|
|
9014
9070
|
} else if (restartNested) {
|
|
9015
9071
|
handBackBase = await run.runStorage.loadDriveStartState();
|
|
9072
|
+
if (!handBackBase && storedPending) handBackBase = toJsonState((await run.runStorage.loadFull())?.value);
|
|
9016
9073
|
res = await run.restart({
|
|
9017
9074
|
requestContext,
|
|
9018
9075
|
actor,
|
|
@@ -11327,6 +11384,34 @@ var EventedExecutionEngine = class extends ExecutionEngine {
|
|
|
11327
11384
|
return result;
|
|
11328
11385
|
}
|
|
11329
11386
|
};
|
|
11387
|
+
// src/workflows/evented/setup-warning.ts
|
|
11388
|
+
const DOCS_URL = "https://mastra.ai/docs/server/pubsub#evented-workflows-and-agents";
|
|
11389
|
+
const warnedHosts = /* @__PURE__ */ new WeakSet();
|
|
11390
|
+
/**
|
|
11391
|
+
* Evented runs spread over several processes need a pubsub that hands a stopped
|
|
11392
|
+
* worker's event to another worker, and a store whose step guards let one
|
|
11393
|
+
* delivery of a step commit. Logs once per Mastra instance when the pubsub
|
|
11394
|
+
* reaches other processes and one of the two is missing.
|
|
11395
|
+
*
|
|
11396
|
+
* It judges the setup, not how many processes use it: Mastra can't count them.
|
|
11397
|
+
* A pubsub that stays inside the process is left alone, since no other process
|
|
11398
|
+
* can take part in its runs. `MASTRA_DISABLE_EVENTED_SETUP_WARNING=true`
|
|
11399
|
+
* disables it for a shared transport used by one process.
|
|
11400
|
+
*
|
|
11401
|
+
* The message names no supported pubsub or store. The docs page it links to is
|
|
11402
|
+
* the one place that lists them.
|
|
11403
|
+
*/
|
|
11404
|
+
function warnUnsupportedEventedSetup(mastra, workflowsStore) {
|
|
11405
|
+
if (warnedHosts.has(mastra) || process.env.MASTRA_DISABLE_EVENTED_SETUP_WARNING === "true") return;
|
|
11406
|
+
if (!reachesOtherProcesses(mastra.pubsub)) return;
|
|
11407
|
+
const pubsub = mastra.pubsub.__rawBus();
|
|
11408
|
+
let missing;
|
|
11409
|
+
if (!pubsub.redeliversUnacked) missing = `${pubsub.constructor.name} doesn't redeliver unacknowledged events`;
|
|
11410
|
+
else if (workflowsStore && !workflowsStore.supportsWorkflowStepGuards()) missing = `the workflows store has no step guards`;
|
|
11411
|
+
if (!missing) return;
|
|
11412
|
+
warnedHosts.add(mastra);
|
|
11413
|
+
mastra.getLogger()?.warn(`Evented workflows and agents aren't supported on several processes with this setup: ${missing}. See ${DOCS_URL}`);
|
|
11414
|
+
}
|
|
11330
11415
|
// src/agent/scopes.ts
|
|
11331
11416
|
/**
|
|
11332
11417
|
* Scope types Memory reads as the run's identity. Every other scope type is
|
|
@@ -11604,7 +11689,7 @@ const MASTRA_DURABLE_SEGMENTS_KEY = "mastra__durableSegments";
|
|
|
11604
11689
|
* round-trip are skipped so a single non-serializable value can't break the
|
|
11605
11690
|
* snapshot.
|
|
11606
11691
|
*/
|
|
11607
|
-
function snapshotRequestContextEntries(requestContext) {
|
|
11692
|
+
function snapshotRequestContextEntries(requestContext, onEntryOmitted) {
|
|
11608
11693
|
if (!requestContext) return void 0;
|
|
11609
11694
|
const out = {};
|
|
11610
11695
|
let any = false;
|
|
@@ -11616,7 +11701,10 @@ function snapshotRequestContextEntries(requestContext) {
|
|
|
11616
11701
|
if (key === "mastra__durableExecutions") continue;
|
|
11617
11702
|
if (key === "mastra__durableSegments") continue;
|
|
11618
11703
|
const json = boundedStringify(value);
|
|
11619
|
-
if (json === void 0)
|
|
11704
|
+
if (json === void 0) {
|
|
11705
|
+
onEntryOmitted?.();
|
|
11706
|
+
continue;
|
|
11707
|
+
}
|
|
11620
11708
|
out[key] = JSON.parse(json);
|
|
11621
11709
|
any = true;
|
|
11622
11710
|
}
|
|
@@ -14916,7 +15004,7 @@ var StepExecutor = class extends MastraBase {
|
|
|
14916
15004
|
const cache = this.mastra?.serverCache;
|
|
14917
15005
|
if (inner instanceof CachingPubSub) this.#stepPubsub = inner;
|
|
14918
15006
|
else if (cache) {
|
|
14919
|
-
const processLocalLogs = cache instanceof InMemoryServerCache &&
|
|
15007
|
+
const processLocalLogs = cache instanceof InMemoryServerCache && reachesOtherProcesses(inner);
|
|
14920
15008
|
this.#stepPubsub = new CachingPubSub(inner, cache, {
|
|
14921
15009
|
shouldCache: (topic) => !isRunLocalTopic(topic),
|
|
14922
15010
|
extendExistingLogsOnly: processLocalLogs,
|
|
@@ -15194,7 +15282,7 @@ var StepExecutor = class extends MastraBase {
|
|
|
15194
15282
|
}),
|
|
15195
15283
|
error: errorInstance
|
|
15196
15284
|
} });
|
|
15197
|
-
if (isExecutionFenceError(error) && this.mastra &&
|
|
15285
|
+
if (isExecutionFenceError(error) && this.mastra && reachesOtherProcesses(this.mastra.pubsub)) {
|
|
15198
15286
|
if (isStorageFencedExecution(requestContext, runId, params.parentWorkflow)) throw error;
|
|
15199
15287
|
}
|
|
15200
15288
|
const mastraError = new MastraError({
|
|
@@ -15425,6 +15513,58 @@ var StepExecutor = class extends MastraBase {
|
|
|
15425
15513
|
}
|
|
15426
15514
|
}
|
|
15427
15515
|
};
|
|
15516
|
+
// src/workflows/evented/workflow-event-processor/run-status.ts
|
|
15517
|
+
const ENDED_RUN_STATUSES = /* @__PURE__ */ new Set([
|
|
15518
|
+
"success",
|
|
15519
|
+
"failed",
|
|
15520
|
+
"canceled",
|
|
15521
|
+
"tripwire"
|
|
15522
|
+
]);
|
|
15523
|
+
/** The statuses of a run that has not ended yet. */
|
|
15524
|
+
const UNENDED_RUN_STATUSES = [
|
|
15525
|
+
"running",
|
|
15526
|
+
"waiting",
|
|
15527
|
+
"suspended",
|
|
15528
|
+
"pending",
|
|
15529
|
+
"paused",
|
|
15530
|
+
"bailed",
|
|
15531
|
+
"skipped"
|
|
15532
|
+
];
|
|
15533
|
+
/** Whether a run stored with `status` has ended. */
|
|
15534
|
+
function isEndedRunStatus(status) {
|
|
15535
|
+
return ENDED_RUN_STATUSES.has(status);
|
|
15536
|
+
}
|
|
15537
|
+
/** Whether the stored run `run` has ended. */
|
|
15538
|
+
function hasRunEnded(run) {
|
|
15539
|
+
return !!run && isEndedRunStatus(run.status);
|
|
15540
|
+
}
|
|
15541
|
+
/** Whether `executionPath` points past the last entry of `stepGraph`: a step run there ends the run. */
|
|
15542
|
+
function isPastLastEntry(stepGraph, executionPath) {
|
|
15543
|
+
return (executionPath?.[0] ?? -1) >= stepGraph.length;
|
|
15544
|
+
}
|
|
15545
|
+
/**
|
|
15546
|
+
* Whether a step event is the one that ended the stored run `run`, which a worker still handles
|
|
15547
|
+
* when the run has ended. Only a successful run has one: its worker stores the end before
|
|
15548
|
+
* publishing it and may stop in between, and handling the event again publishes the end. The
|
|
15549
|
+
* stored active path names it: the step end the run ended at, or the step run past the last entry.
|
|
15550
|
+
* A failed run's end is stored by its own `workflow.fail`, which a redelivery of that event
|
|
15551
|
+
* finishes.
|
|
15552
|
+
*
|
|
15553
|
+
* This can't tell an end that was stored and not published from one that was already handled, so
|
|
15554
|
+
* a late copy of the event publishes the end again (and, for a nested run, hands it to the parent
|
|
15555
|
+
* again).
|
|
15556
|
+
*/
|
|
15557
|
+
function isRunEndingEvent(type, executionPath, run, stepGraph) {
|
|
15558
|
+
return run.status === "success" && samePath(run.activePaths, executionPath) && (type === "workflow.step.end" || !!stepGraph && isPastLastEntry(stepGraph, executionPath));
|
|
15559
|
+
}
|
|
15560
|
+
/**
|
|
15561
|
+
* Whether two execution paths name the same position in the step graph. A missing path matches
|
|
15562
|
+
* only another missing path: a run stored without active paths was ended by an event without one.
|
|
15563
|
+
*/
|
|
15564
|
+
function samePath(a, b) {
|
|
15565
|
+
if (!a || !b) return a === b;
|
|
15566
|
+
return a.length === b.length && a.every((index, depth) => index === b[depth]);
|
|
15567
|
+
}
|
|
15428
15568
|
// src/workflows/evented/workflow-event-processor/finished-occurrence.ts
|
|
15429
15569
|
const TERMINAL_STATUSES = /* @__PURE__ */ new Set([
|
|
15430
15570
|
"success",
|
|
@@ -15443,10 +15583,6 @@ const BRANCH_SETTLED_STATUSES = /* @__PURE__ */ new Set([
|
|
|
15443
15583
|
"skipped",
|
|
15444
15584
|
"suspended"
|
|
15445
15585
|
]);
|
|
15446
|
-
/** Whether two execution paths name the same position in the step graph. */
|
|
15447
|
-
function samePath(a, b) {
|
|
15448
|
-
return !!a && a.length === b.length && a.every((index, depth) => index === b[depth]);
|
|
15449
|
-
}
|
|
15450
15586
|
/** The record of one foreach item, kept in the foreach step's resume metadata. */
|
|
15451
15587
|
function foreachItem(result, index) {
|
|
15452
15588
|
if (index === void 0) return;
|
|
@@ -16408,6 +16544,18 @@ function routeStepRun(stepGraph, { executionPath, restart }) {
|
|
|
16408
16544
|
}
|
|
16409
16545
|
}
|
|
16410
16546
|
// src/workflows/evented/workflow-event-processor/sleep.ts
|
|
16547
|
+
/**
|
|
16548
|
+
* Records the sleep as the run's active step. Returns false when the run ended after the sleep
|
|
16549
|
+
* was dispatched: the write is refused, so the ended run is not reopened, and the sleep stops.
|
|
16550
|
+
*/
|
|
16551
|
+
async function markSleepRunning(runStorage, executionPath, activeStepsPath) {
|
|
16552
|
+
return !!await runStorage.updateHeader({
|
|
16553
|
+
status: "running",
|
|
16554
|
+
activePaths: executionPath,
|
|
16555
|
+
activeStepsPath,
|
|
16556
|
+
expectedStatus: UNENDED_RUN_STATUSES
|
|
16557
|
+
}) || !hasRunEnded(await runStorage.loadHeader());
|
|
16558
|
+
}
|
|
16411
16559
|
async function processWorkflowWaitForEvent(workflowData, { pubsub, eventName, currentState }) {
|
|
16412
16560
|
const executionPath = currentState?.waitingPaths[eventName];
|
|
16413
16561
|
if (!executionPath) return;
|
|
@@ -16460,14 +16608,10 @@ async function processWorkflowSleep({ workflow, workflowId, runId, executionPath
|
|
|
16460
16608
|
},
|
|
16461
16609
|
requestContext: withoutAuthToken(requestContext ?? {})
|
|
16462
16610
|
});
|
|
16463
|
-
await runStorage
|
|
16464
|
-
|
|
16465
|
-
|
|
16466
|
-
|
|
16467
|
-
...activeStepsPath,
|
|
16468
|
-
[step.id]: executionPath
|
|
16469
|
-
}
|
|
16470
|
-
});
|
|
16611
|
+
if (!await markSleepRunning(runStorage, executionPath, {
|
|
16612
|
+
...activeStepsPath,
|
|
16613
|
+
[step.id]: executionPath
|
|
16614
|
+
})) return;
|
|
16471
16615
|
const reqContext = new RequestContext(Object.entries(requestContext ?? {}));
|
|
16472
16616
|
setLongTimeout(async () => {
|
|
16473
16617
|
if (emitStepEvents) {
|
|
@@ -16541,14 +16685,10 @@ async function processWorkflowSleepUntil({ workflow, workflowId, runId, executio
|
|
|
16541
16685
|
},
|
|
16542
16686
|
requestContext: withoutAuthToken(requestContext ?? {})
|
|
16543
16687
|
});
|
|
16544
|
-
await runStorage
|
|
16545
|
-
|
|
16546
|
-
|
|
16547
|
-
|
|
16548
|
-
...activeStepsPath,
|
|
16549
|
-
[step.id]: executionPath
|
|
16550
|
-
}
|
|
16551
|
-
});
|
|
16688
|
+
if (!await markSleepRunning(runStorage, executionPath, {
|
|
16689
|
+
...activeStepsPath,
|
|
16690
|
+
[step.id]: executionPath
|
|
16691
|
+
})) return;
|
|
16552
16692
|
const reqContext = new RequestContext(Object.entries(requestContext ?? {}));
|
|
16553
16693
|
const duration = await stepExecutor.resolveSleepUntil({
|
|
16554
16694
|
workflowId,
|
|
@@ -17476,12 +17616,12 @@ var WorkflowEventProcessor = class WorkflowEventProcessor extends EventProcessor
|
|
|
17476
17616
|
stepResults: stepResults ?? {},
|
|
17477
17617
|
workflowStatus: finalStatus
|
|
17478
17618
|
}) ?? true;
|
|
17479
|
-
if (shouldPersist
|
|
17619
|
+
if (shouldPersist && !await this.#writeRunEnd("endWorkflow", args, runStorage, {
|
|
17480
17620
|
status: finalStatus,
|
|
17481
17621
|
result: normalizedPrevResult,
|
|
17482
17622
|
activePaths: executionPath,
|
|
17483
17623
|
activeStepsPath
|
|
17484
|
-
});
|
|
17624
|
+
})) return;
|
|
17485
17625
|
this.endRunSpans(args, finalStatus);
|
|
17486
17626
|
if (finalStatus === "paused") await this.#pubsub.publish(`workflow.events.v2.${runId}`, {
|
|
17487
17627
|
type: "watch",
|
|
@@ -17515,6 +17655,35 @@ var WorkflowEventProcessor = class WorkflowEventProcessor extends EventProcessor
|
|
|
17515
17655
|
}
|
|
17516
17656
|
});
|
|
17517
17657
|
}
|
|
17658
|
+
/**
|
|
17659
|
+
* Stores a run's end only while the run has not ended, so a late or second end can't replace
|
|
17660
|
+
* the first one. Returns true when the end is to be published: it was stored, the run is not
|
|
17661
|
+
* stored (as before), or the run already ended the same way at the same path, which is this end
|
|
17662
|
+
* handled again after its worker stopped before publishing it. Returns false, after logging, for
|
|
17663
|
+
* any other refusal: the run ended another way, or it was reopened (time travel writes `running`
|
|
17664
|
+
* on an ended run) between the write and the read, and an old end must not replace it.
|
|
17665
|
+
*/
|
|
17666
|
+
async #writeRunEnd(handler, { workflowId, runId, executionPath, eventId }, runStorage, end) {
|
|
17667
|
+
const expectedStatus = end.status === "canceled" ? [...UNENDED_RUN_STATUSES, "canceled"] : UNENDED_RUN_STATUSES;
|
|
17668
|
+
if (await runStorage.updateHeader({
|
|
17669
|
+
...end,
|
|
17670
|
+
expectedStatus
|
|
17671
|
+
})) return true;
|
|
17672
|
+
const stored = await runStorage.loadHeader();
|
|
17673
|
+
if (!stored) return true;
|
|
17674
|
+
if (hasRunEnded(stored) && stored.status === end.status && samePath(stored.activePaths, executionPath)) return true;
|
|
17675
|
+
this.mastra.getLogger()?.warn("Dropping a workflow end: the run already ended or was reopened", {
|
|
17676
|
+
handler,
|
|
17677
|
+
workflowId,
|
|
17678
|
+
runId,
|
|
17679
|
+
eventId,
|
|
17680
|
+
executionPath,
|
|
17681
|
+
status: end.status,
|
|
17682
|
+
storedStatus: stored.status,
|
|
17683
|
+
storedActivePaths: stored.activePaths
|
|
17684
|
+
});
|
|
17685
|
+
return false;
|
|
17686
|
+
}
|
|
17518
17687
|
async publishFinishEvent(event) {
|
|
17519
17688
|
for (;;) try {
|
|
17520
17689
|
await this.#pubsub.publish("workflows-finish", event);
|
|
@@ -17651,6 +17820,17 @@ var WorkflowEventProcessor = class WorkflowEventProcessor extends EventProcessor
|
|
|
17651
17820
|
const step = liveParentWorkflow?.stepGraph?.[parentWorkflow.executionPath[0]];
|
|
17652
17821
|
if (liveParentWorkflow && step?.type === "loop") {
|
|
17653
17822
|
const parentStorage = this.#runStorage(parentWorkflow.workflowId, parentWorkflow.runId);
|
|
17823
|
+
const parentHeader = await parentStorage.loadHeader();
|
|
17824
|
+
if (hasRunEnded(parentHeader)) {
|
|
17825
|
+
this.mastra.getLogger()?.warn("Dropping a nested loop iteration end: the parent run already ended", {
|
|
17826
|
+
workflowId: parentWorkflow.workflowId,
|
|
17827
|
+
runId: parentWorkflow.runId,
|
|
17828
|
+
nestedRunId,
|
|
17829
|
+
executionPath: parentWorkflow.executionPath,
|
|
17830
|
+
storedStatus: parentHeader.status
|
|
17831
|
+
});
|
|
17832
|
+
return;
|
|
17833
|
+
}
|
|
17654
17834
|
const loopStepResults = {
|
|
17655
17835
|
...parentWorkflow.stepResults ?? (await parentStorage.loadFull())?.context,
|
|
17656
17836
|
__state: state
|
|
@@ -17786,21 +17966,19 @@ var WorkflowEventProcessor = class WorkflowEventProcessor extends EventProcessor
|
|
|
17786
17966
|
workflowStatus: "failed"
|
|
17787
17967
|
}) ?? true;
|
|
17788
17968
|
const ownershipLost = workflow?.options?.isOwnershipLostError?.(prevResult?.error);
|
|
17789
|
-
if (ownershipLost) {} else if (shouldPersist
|
|
17790
|
-
|
|
17791
|
-
|
|
17792
|
-
|
|
17793
|
-
|
|
17794
|
-
|
|
17795
|
-
|
|
17796
|
-
|
|
17797
|
-
|
|
17798
|
-
|
|
17799
|
-
|
|
17800
|
-
|
|
17801
|
-
|
|
17802
|
-
});
|
|
17803
|
-
}
|
|
17969
|
+
if (ownershipLost) {} else if (shouldPersist && !await this.#writeRunEnd("processWorkflowFail", args, runStorage, {
|
|
17970
|
+
status: "failed",
|
|
17971
|
+
error: prevResult.error,
|
|
17972
|
+
activePaths: executionPath,
|
|
17973
|
+
activeStepsPath
|
|
17974
|
+
})) return;
|
|
17975
|
+
else if (shouldPersist && currentStorageVersion() === 2) await this.pruneAndRepersistSnapshot({
|
|
17976
|
+
workflow,
|
|
17977
|
+
workflowId,
|
|
17978
|
+
runId,
|
|
17979
|
+
finished: true,
|
|
17980
|
+
fence: await this.currentRunFence(runId)
|
|
17981
|
+
});
|
|
17804
17982
|
if (parentWorkflow) await this.#pubsub.publish("workflows", {
|
|
17805
17983
|
type: "workflow.step.end",
|
|
17806
17984
|
runId: parentWorkflow.runId,
|
|
@@ -17904,7 +18082,7 @@ var WorkflowEventProcessor = class WorkflowEventProcessor extends EventProcessor
|
|
|
17904
18082
|
restart
|
|
17905
18083
|
});
|
|
17906
18084
|
if (!rawStep || route.kind === "missing") {
|
|
17907
|
-
if (executionPath
|
|
18085
|
+
if (isPastLastEntry(stepGraph, executionPath)) return this.endWorkflow({
|
|
17908
18086
|
workflow,
|
|
17909
18087
|
parentWorkflow,
|
|
17910
18088
|
workflowId,
|
|
@@ -18489,12 +18667,7 @@ var WorkflowEventProcessor = class WorkflowEventProcessor extends EventProcessor
|
|
|
18489
18667
|
workflowName: workflowId,
|
|
18490
18668
|
runId
|
|
18491
18669
|
});
|
|
18492
|
-
if (snapshot
|
|
18493
|
-
"success",
|
|
18494
|
-
"failed",
|
|
18495
|
-
"canceled",
|
|
18496
|
-
"tripwire"
|
|
18497
|
-
].includes(snapshot.status)) return true;
|
|
18670
|
+
if (hasRunEnded(snapshot)) return true;
|
|
18498
18671
|
if (snapshot?.status === "suspended" && snapshot.context[leafId]?.status === "suspended") return true;
|
|
18499
18672
|
if (guardStart) try {
|
|
18500
18673
|
assertWorkflowStepGuard({
|
|
@@ -18532,7 +18705,8 @@ var WorkflowEventProcessor = class WorkflowEventProcessor extends EventProcessor
|
|
|
18532
18705
|
nestedRunId = stepResults[leafId]?.suspendPayload?.__workflow_meta?.runId;
|
|
18533
18706
|
} else if (timeTravel && timeTravel.steps?.length > 1 && timeTravel.steps[0] === leafId) {
|
|
18534
18707
|
nestedDispatch = "time-travel";
|
|
18535
|
-
|
|
18708
|
+
const recordedMetadata = stepResults[leafId]?.metadata;
|
|
18709
|
+
nestedRunId = (step.type === "foreach" ? recordedMetadata?.foreachNestedRunIds?.[executionPath[1]] ?? (recordedMetadata?.foreachNestedRunIds || executionPath[1] !== 0 ? void 0 : recordedMetadata?.nestedRunId) : recordedMetadata?.nestedRunId) ?? globalThis.crypto.randomUUID();
|
|
18536
18710
|
} else if (restart && !!restart.activeStepsPath?.[leafId]) {
|
|
18537
18711
|
nestedDispatch = "restart";
|
|
18538
18712
|
nestedRunId = (step.type === "foreach" ? stepResults[leafId]?.metadata?.foreachNestedRunIds?.[executionPath[1]] : void 0) ?? stepResults[leafId]?.metadata?.nestedRunId ?? globalThis.crypto.randomUUID();
|
|
@@ -18661,12 +18835,23 @@ var WorkflowEventProcessor = class WorkflowEventProcessor extends EventProcessor
|
|
|
18661
18835
|
};
|
|
18662
18836
|
return step.type === "loop" ? this.#processLoop(continuation, step, completedResult, args.eventId) : this.processWorkflowStepEnd(continuation);
|
|
18663
18837
|
}
|
|
18664
|
-
await runStorage.updateHeader({
|
|
18838
|
+
const stored = await runStorage.updateHeader({
|
|
18665
18839
|
status: "running",
|
|
18666
18840
|
activePaths: executionPath,
|
|
18667
18841
|
activeStepsPath,
|
|
18668
18842
|
expectedStatus: "running"
|
|
18669
|
-
});
|
|
18843
|
+
}) ? void 0 : await runStorage.loadHeader();
|
|
18844
|
+
if (hasRunEnded(stored) && stored.status !== "canceled") {
|
|
18845
|
+
this.mastra.getLogger()?.warn("Not running a step: the run already ended", {
|
|
18846
|
+
type: "workflow.step.run",
|
|
18847
|
+
workflowId,
|
|
18848
|
+
runId,
|
|
18849
|
+
eventId: args.eventId,
|
|
18850
|
+
executionPath,
|
|
18851
|
+
storedStatus: stored.status
|
|
18852
|
+
});
|
|
18853
|
+
return;
|
|
18854
|
+
}
|
|
18670
18855
|
}
|
|
18671
18856
|
if (step.type === "foreach" && workflowsStore && authorizedEventId) {
|
|
18672
18857
|
const storedResult = (await runStorage.loadSteps([leafId]))[leafId] ?? stepResults[leafId];
|
|
@@ -20270,7 +20455,7 @@ var WorkflowEventProcessor = class WorkflowEventProcessor extends EventProcessor
|
|
|
20270
20455
|
* should drop the event (or return 4xx for HTTP push).
|
|
20271
20456
|
*/
|
|
20272
20457
|
async handle(event) {
|
|
20273
|
-
if (this.mastra.pubsub
|
|
20458
|
+
if (!reachesOtherProcesses(this.mastra.pubsub)) return this.#handleDelivery(event);
|
|
20274
20459
|
if (!isStorageFencedExecution(new RequestContext(Object.entries(event.data?.requestContext ?? {})), event.runId, event.data?.parentWorkflow)) return this.#handleDelivery(event);
|
|
20275
20460
|
try {
|
|
20276
20461
|
if (await retrySettledDurableExecution(this.mastra, event)) return { ok: true };
|
|
@@ -20604,6 +20789,19 @@ var WorkflowEventProcessor = class WorkflowEventProcessor extends EventProcessor
|
|
|
20604
20789
|
return;
|
|
20605
20790
|
}
|
|
20606
20791
|
const workflow = this.#resolveLiveWorkflow(workflowData);
|
|
20792
|
+
if ((type === "workflow.step.end" || type === "workflow.step.run") && hasRunEnded(currentState) && !isRunEndingEvent(type, workflowData.executionPath, currentState, workflow?.stepGraph)) {
|
|
20793
|
+
this.mastra.getLogger()?.warn("Dropping a step event: the run already ended", {
|
|
20794
|
+
type,
|
|
20795
|
+
workflowId: workflowData.workflowId,
|
|
20796
|
+
runId: workflowData.runId,
|
|
20797
|
+
eventId: event.id,
|
|
20798
|
+
executionPath: workflowData.executionPath,
|
|
20799
|
+
storedStatus: currentState.status,
|
|
20800
|
+
storedActivePaths: currentState.activePaths,
|
|
20801
|
+
deliveryAttempt: event.deliveryAttempt
|
|
20802
|
+
});
|
|
20803
|
+
return;
|
|
20804
|
+
}
|
|
20607
20805
|
if (!workflow) {
|
|
20608
20806
|
if (type === "workflow.fail" || type === "workflow.end" || type === "workflow.cancel") {} else return this.errorWorkflow(workflowData, new MastraError({
|
|
20609
20807
|
id: "MASTRA_WORKFLOW",
|
|
@@ -20971,15 +21169,17 @@ function createStepFromProcessor(processor) {
|
|
|
20971
21169
|
description: processor.name ?? `Processor ${processor.id}`,
|
|
20972
21170
|
inputSchema: toStandardSchema(ProcessorStepSchema),
|
|
20973
21171
|
outputSchema: toStandardSchema(ProcessorStepOutputSchema),
|
|
20974
|
-
execute: async ({ inputData, requestContext, outputWriter, tracing, tracingContext, loggerVNext, metrics, mastra, runId: workflowRunId }) => {
|
|
21172
|
+
execute: async ({ inputData, requestContext, outputWriter, tracing, tracingContext, loggerVNext, metrics, mastra, runId: workflowRunId, abortSignal: runAbortSignal }) => {
|
|
20975
21173
|
const observabilityContext = resolveObservabilityContext({
|
|
20976
21174
|
tracing,
|
|
20977
21175
|
tracingContext,
|
|
20978
21176
|
loggerVNext,
|
|
20979
21177
|
metrics
|
|
20980
21178
|
});
|
|
21179
|
+
const scopedSignal = mastra?.__getRunScope(workflowRunId)?.get(PROCESSOR_ABORT_SIGNAL);
|
|
21180
|
+
const abortSignal = scopedSignal && runAbortSignal ? AbortSignal.any([scopedSignal, runAbortSignal]) : scopedSignal ?? runAbortSignal;
|
|
20981
21181
|
const input = inputData;
|
|
20982
|
-
const { phase, messages, messageList, stepNumber, runId: agentRunId, systemMessages, part, streamParts, state, result: outputResult, finishReason, providerMetadata, toolCalls, text, retryCount, model, tools, toolChoice, activeTools, providerOptions, modelSettings, structuredOutput, steps, usage, messageId, rotateResponseMessageId, toolName, toolCallId, args: toolCallArgs, toolResultValue, modelOutput, providerExecuted, processorStates,
|
|
21182
|
+
const { phase, messages, messageList, stepNumber, runId: agentRunId, systemMessages, part, streamParts, state, result: outputResult, finishReason, providerMetadata, toolCalls, text, retryCount, model, tools, toolChoice, activeTools, providerOptions, modelSettings, structuredOutput, steps, usage, messageId, rotateResponseMessageId, toolName, toolCallId, args: toolCallArgs, toolResultValue, modelOutput, providerExecuted, processorStates, lateSignalSink } = input;
|
|
20983
21183
|
const abort = (reason, options) => {
|
|
20984
21184
|
throw new TripWire(reason || `Tripwire triggered by ${processor.id}`, options, processor.id);
|
|
20985
21185
|
};
|
|
@@ -21595,6 +21795,16 @@ function createStepFromProcessor(processor) {
|
|
|
21595
21795
|
component: "PROCESSOR"
|
|
21596
21796
|
};
|
|
21597
21797
|
}
|
|
21798
|
+
/**
|
|
21799
|
+
* Builds a workflow on the evented execution engine: each step is an event on
|
|
21800
|
+
* the Mastra host's pubsub, so any worker can run the next one.
|
|
21801
|
+
*
|
|
21802
|
+
* In one process it runs on any pubsub, including the default one. Running it
|
|
21803
|
+
* on several processes needs a pubsub that redelivers unacknowledged events and
|
|
21804
|
+
* a workflows store with step guards.
|
|
21805
|
+
*
|
|
21806
|
+
* @see https://mastra.ai/docs/server/pubsub#evented-workflows-and-agents
|
|
21807
|
+
*/
|
|
21598
21808
|
function createWorkflow$1(params) {
|
|
21599
21809
|
const eventProcessor = new WorkflowEventProcessor({ mastra: params.mastra });
|
|
21600
21810
|
const executionEngine = new EventedExecutionEngine({
|
|
@@ -21651,6 +21861,7 @@ var EventedWorkflow = class extends Workflow {
|
|
|
21651
21861
|
}
|
|
21652
21862
|
});
|
|
21653
21863
|
}
|
|
21864
|
+
if (!this.isInternal) warnUnsupportedEventedSetup(this.mastra, workflowsStore);
|
|
21654
21865
|
const cachedRun = this.runs.get(runIdToUse);
|
|
21655
21866
|
const shouldPersistSnapshot = this.options?.shouldPersistSnapshot?.({
|
|
21656
21867
|
workflowStatus: cachedRun?.workflowRunStatus ?? "pending",
|
|
@@ -37829,10 +38040,19 @@ var DatasetsInMemory = class extends DatasetsStorage {
|
|
|
37829
38040
|
field: "createdAt",
|
|
37830
38041
|
direction: "DESC"
|
|
37831
38042
|
});
|
|
37832
|
-
items.sort(compareByField(orderBy.field, orderBy.direction));
|
|
37833
38043
|
const { page, perPage: perPageInput } = args.pagination;
|
|
37834
38044
|
const perPage = normalizePerPage(perPageInput, 100);
|
|
37835
38045
|
const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
|
|
38046
|
+
if (perPage === 0) return {
|
|
38047
|
+
items: [],
|
|
38048
|
+
pagination: {
|
|
38049
|
+
total: items.length,
|
|
38050
|
+
page,
|
|
38051
|
+
perPage: perPageForResponse,
|
|
38052
|
+
hasMore: items.length > 0
|
|
38053
|
+
}
|
|
38054
|
+
};
|
|
38055
|
+
items.sort(compareByField(orderBy.field, orderBy.direction));
|
|
37836
38056
|
const end = perPageInput === false ? items.length : start + perPage;
|
|
37837
38057
|
return {
|
|
37838
38058
|
items: items.slice(start, end),
|
|
@@ -38418,261 +38638,6 @@ var InMemoryHarness = class extends HarnessStorage {
|
|
|
38418
38638
|
return cloneSessionRecord(next);
|
|
38419
38639
|
}
|
|
38420
38640
|
};
|
|
38421
|
-
// src/storage/domains/knowledge/base.ts
|
|
38422
|
-
/** @experimental Knowledge APIs are experimental and may change without notice. */
|
|
38423
|
-
const KNOWLEDGE_STORAGE_CONTRACT_VERSION = 4;
|
|
38424
|
-
/** @experimental Knowledge APIs are experimental and may change without notice. */
|
|
38425
|
-
const KNOWLEDGE_STORAGE_SCHEMA_VERSION = 4;
|
|
38426
|
-
/**
|
|
38427
|
-
* Classifies an adapter-provided, read-only schema snapshot. Adapters own the physical probe; this
|
|
38428
|
-
* helper owns version negotiation and never mutates the snapshot or backing store.
|
|
38429
|
-
*
|
|
38430
|
-
* @experimental Knowledge APIs are experimental and may change without notice.
|
|
38431
|
-
*/
|
|
38432
|
-
function inspectKnowledgeSchema(snapshot) {
|
|
38433
|
-
if (!snapshot.available) return {
|
|
38434
|
-
status: "unavailable",
|
|
38435
|
-
schemaVersion: null,
|
|
38436
|
-
reason: snapshot.reason ?? "The Knowledge storage adapter is unavailable."
|
|
38437
|
-
};
|
|
38438
|
-
if (snapshot.tableNames.length === 0) return {
|
|
38439
|
-
status: "uninitialized",
|
|
38440
|
-
schemaVersion: null
|
|
38441
|
-
};
|
|
38442
|
-
if (snapshot.schemaVersion === 4) return {
|
|
38443
|
-
status: "compatible",
|
|
38444
|
-
schemaVersion: 4
|
|
38445
|
-
};
|
|
38446
|
-
return {
|
|
38447
|
-
status: "incompatible-reset-required",
|
|
38448
|
-
schemaVersion: snapshot.schemaVersion ?? null,
|
|
38449
|
-
reason: snapshot.reason ?? `Existing experimental Knowledge tables are not compatible with schema version 4.`
|
|
38450
|
-
};
|
|
38451
|
-
}
|
|
38452
|
-
/** @experimental Knowledge APIs are experimental and may change without notice. */
|
|
38453
|
-
var KnowledgeConflictError = class extends Error {
|
|
38454
|
-
constructor(id) {
|
|
38455
|
-
super(`Knowledge record version conflict: ${id}`);
|
|
38456
|
-
this.name = "KnowledgeConflictError";
|
|
38457
|
-
}
|
|
38458
|
-
};
|
|
38459
|
-
var KnowledgeNotFoundError$1 = class extends Error {
|
|
38460
|
-
constructor(type, id) {
|
|
38461
|
-
super(`Knowledge ${type} not found: ${id}`);
|
|
38462
|
-
this.name = "KnowledgeNotFoundError";
|
|
38463
|
-
}
|
|
38464
|
-
};
|
|
38465
|
-
var KnowledgeSchemaResetRequiredError = class extends Error {
|
|
38466
|
-
inspection;
|
|
38467
|
-
constructor(inspection) {
|
|
38468
|
-
super(`Knowledge schema reset required: ${inspection.reason}. Existing Knowledge data is not migrated. To replace it, call \`await storage.stores?.knowledge?.dangerouslyReset()\`, which deletes every Knowledge row and nothing else.`);
|
|
38469
|
-
this.name = "KnowledgeSchemaResetRequiredError";
|
|
38470
|
-
this.inspection = inspection;
|
|
38471
|
-
}
|
|
38472
|
-
};
|
|
38473
|
-
var KnowledgeUnsupportedCapabilityError = class extends Error {
|
|
38474
|
-
constructor(capability) {
|
|
38475
|
-
super(`This Knowledge storage adapter does not expose ${capability}.`);
|
|
38476
|
-
this.name = "KnowledgeUnsupportedCapabilityError";
|
|
38477
|
-
}
|
|
38478
|
-
};
|
|
38479
|
-
function assertKnowledgeSchemaCompatible(inspection) {
|
|
38480
|
-
if (inspection.status === "compatible" || inspection.status === "uninitialized") return;
|
|
38481
|
-
if (inspection.status === "incompatible-reset-required") throw new KnowledgeSchemaResetRequiredError(inspection);
|
|
38482
|
-
throw new Error(`Knowledge schema inspection unavailable: ${inspection.reason}`);
|
|
38483
|
-
}
|
|
38484
|
-
const CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
|
|
38485
|
-
let lastUlidTime = -1;
|
|
38486
|
-
let lastUlidRandom = 0n;
|
|
38487
|
-
function parseKnowledgeWikilinks(text) {
|
|
38488
|
-
const names = [];
|
|
38489
|
-
const seen = /* @__PURE__ */ new Set();
|
|
38490
|
-
let contentStart = -1;
|
|
38491
|
-
for (let index = 0; index < text.length - 1; index++) {
|
|
38492
|
-
const pair = text.slice(index, index + 2);
|
|
38493
|
-
if (pair === "[[") {
|
|
38494
|
-
contentStart = index + 2;
|
|
38495
|
-
index++;
|
|
38496
|
-
continue;
|
|
38497
|
-
}
|
|
38498
|
-
if (pair !== "]]" || contentStart < 0) continue;
|
|
38499
|
-
const name = text.slice(contentStart, index).trim();
|
|
38500
|
-
const key = name.toLocaleLowerCase();
|
|
38501
|
-
if (name && !seen.has(key)) {
|
|
38502
|
-
seen.add(key);
|
|
38503
|
-
names.push(name);
|
|
38504
|
-
}
|
|
38505
|
-
contentStart = -1;
|
|
38506
|
-
index++;
|
|
38507
|
-
}
|
|
38508
|
-
return names;
|
|
38509
|
-
}
|
|
38510
|
-
function encodeCrockford(value, length) {
|
|
38511
|
-
let encoded = "";
|
|
38512
|
-
for (let index = 0; index < length; index++) {
|
|
38513
|
-
encoded = CROCKFORD[Number(value & 31n)] + encoded;
|
|
38514
|
-
value >>= 5n;
|
|
38515
|
-
}
|
|
38516
|
-
return encoded;
|
|
38517
|
-
}
|
|
38518
|
-
function createKnowledgeUlid(now = Date.now()) {
|
|
38519
|
-
if (now <= lastUlidTime) {
|
|
38520
|
-
now = lastUlidTime;
|
|
38521
|
-
lastUlidRandom = lastUlidRandom + 1n & (1n << 80n) - 1n;
|
|
38522
|
-
} else {
|
|
38523
|
-
lastUlidTime = now;
|
|
38524
|
-
lastUlidRandom = globalThis.crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(10)).reduce((value, byte) => value << 8n | BigInt(byte), 0n);
|
|
38525
|
-
}
|
|
38526
|
-
return `${encodeCrockford(BigInt(now), 10)}${encodeCrockford(lastUlidRandom, 16)}`;
|
|
38527
|
-
}
|
|
38528
|
-
var KnowledgeStorage = class extends StorageDomain {
|
|
38529
|
-
#storageIsolationKey;
|
|
38530
|
-
constructor(config = {}) {
|
|
38531
|
-
super({
|
|
38532
|
-
component: "STORAGE",
|
|
38533
|
-
name: "KNOWLEDGE"
|
|
38534
|
-
});
|
|
38535
|
-
this.#storageIsolationKey = config.storageIsolationKey ?? this;
|
|
38536
|
-
}
|
|
38537
|
-
/** Identifies the physical Knowledge backend and namespace used by this domain. */
|
|
38538
|
-
getStorageIsolationKey() {
|
|
38539
|
-
return this.#storageIsolationKey;
|
|
38540
|
-
}
|
|
38541
|
-
getCapabilities() {
|
|
38542
|
-
return {
|
|
38543
|
-
contractVersion: 4,
|
|
38544
|
-
schemaVersion: 1,
|
|
38545
|
-
supportsSchemaInspection: false,
|
|
38546
|
-
supportsExplicitReset: false
|
|
38547
|
-
};
|
|
38548
|
-
}
|
|
38549
|
-
async inspectSchema() {
|
|
38550
|
-
return {
|
|
38551
|
-
status: "unavailable",
|
|
38552
|
-
schemaVersion: null,
|
|
38553
|
-
reason: "This Knowledge storage adapter does not support schema inspection."
|
|
38554
|
-
};
|
|
38555
|
-
}
|
|
38556
|
-
async dangerouslyReset() {
|
|
38557
|
-
throw new Error("This Knowledge storage adapter does not support an explicit Knowledge-only reset.");
|
|
38558
|
-
}
|
|
38559
|
-
/**
|
|
38560
|
-
* Scope declarations the store supplies itself, such as the scopes a hosted store's importers write
|
|
38561
|
-
* to, with their access rules. Knowledge merges them under its config's, reusing the answer for a
|
|
38562
|
-
* short window, so a declaration the store adds, removes or changes (revoking access included)
|
|
38563
|
-
* applies within it; a key the config declares keeps the config's declaration. None by default.
|
|
38564
|
-
*
|
|
38565
|
-
* @experimental
|
|
38566
|
-
*/
|
|
38567
|
-
async getScopeDeclarations() {
|
|
38568
|
-
return {};
|
|
38569
|
-
}
|
|
38570
|
-
materializeScope(_input) {
|
|
38571
|
-
return Promise.reject(new KnowledgeUnsupportedCapabilityError("materializeScope"));
|
|
38572
|
-
}
|
|
38573
|
-
getScopesByAddress(_input) {
|
|
38574
|
-
return Promise.reject(new KnowledgeUnsupportedCapabilityError("getScopesByAddress"));
|
|
38575
|
-
}
|
|
38576
|
-
listScopeDeclarations() {
|
|
38577
|
-
return Promise.reject(new KnowledgeUnsupportedCapabilityError("listScopeDeclarations"));
|
|
38578
|
-
}
|
|
38579
|
-
renameScopeDeclaration(_input) {
|
|
38580
|
-
return Promise.reject(new KnowledgeUnsupportedCapabilityError("renameScopeDeclaration"));
|
|
38581
|
-
}
|
|
38582
|
-
listChildScopes(_input) {
|
|
38583
|
-
return Promise.reject(new KnowledgeUnsupportedCapabilityError("listChildScopes"));
|
|
38584
|
-
}
|
|
38585
|
-
countChildScopes(_input) {
|
|
38586
|
-
return Promise.reject(new KnowledgeUnsupportedCapabilityError("countChildScopes"));
|
|
38587
|
-
}
|
|
38588
|
-
getPage(_input) {
|
|
38589
|
-
return Promise.reject(new KnowledgeUnsupportedCapabilityError("getPage"));
|
|
38590
|
-
}
|
|
38591
|
-
getPages(_input) {
|
|
38592
|
-
return Promise.reject(new KnowledgeUnsupportedCapabilityError("getPages"));
|
|
38593
|
-
}
|
|
38594
|
-
getPageByPath(_input) {
|
|
38595
|
-
return Promise.reject(new KnowledgeUnsupportedCapabilityError("getPageByPath"));
|
|
38596
|
-
}
|
|
38597
|
-
findPagesByName(_input) {
|
|
38598
|
-
return Promise.reject(new KnowledgeUnsupportedCapabilityError("findPagesByName"));
|
|
38599
|
-
}
|
|
38600
|
-
listChildPages(_input) {
|
|
38601
|
-
return Promise.reject(new KnowledgeUnsupportedCapabilityError("listChildPages"));
|
|
38602
|
-
}
|
|
38603
|
-
listPages(_input) {
|
|
38604
|
-
return Promise.reject(new KnowledgeUnsupportedCapabilityError("listPages"));
|
|
38605
|
-
}
|
|
38606
|
-
createPage(_input) {
|
|
38607
|
-
return Promise.reject(new KnowledgeUnsupportedCapabilityError("createPage"));
|
|
38608
|
-
}
|
|
38609
|
-
updatePage(_input) {
|
|
38610
|
-
return Promise.reject(new KnowledgeUnsupportedCapabilityError("updatePage"));
|
|
38611
|
-
}
|
|
38612
|
-
movePage(_input) {
|
|
38613
|
-
return Promise.reject(new KnowledgeUnsupportedCapabilityError("movePage"));
|
|
38614
|
-
}
|
|
38615
|
-
mergePages(_input) {
|
|
38616
|
-
return Promise.reject(new KnowledgeUnsupportedCapabilityError("mergePages"));
|
|
38617
|
-
}
|
|
38618
|
-
deletePage(_input) {
|
|
38619
|
-
return Promise.reject(new KnowledgeUnsupportedCapabilityError("deletePage"));
|
|
38620
|
-
}
|
|
38621
|
-
getNote(_input) {
|
|
38622
|
-
return Promise.reject(new KnowledgeUnsupportedCapabilityError("getNote"));
|
|
38623
|
-
}
|
|
38624
|
-
countChildPages(_input) {
|
|
38625
|
-
return Promise.reject(new KnowledgeUnsupportedCapabilityError("countChildPages"));
|
|
38626
|
-
}
|
|
38627
|
-
replacePageBodyLinks(_input) {
|
|
38628
|
-
return Promise.reject(new KnowledgeUnsupportedCapabilityError("replacePageBodyLinks"));
|
|
38629
|
-
}
|
|
38630
|
-
listPageBodyLinkSources(_input) {
|
|
38631
|
-
return Promise.reject(new KnowledgeUnsupportedCapabilityError("listPageBodyLinkSources"));
|
|
38632
|
-
}
|
|
38633
|
-
countPageLinks(_input) {
|
|
38634
|
-
return Promise.reject(new KnowledgeUnsupportedCapabilityError("countPageLinks"));
|
|
38635
|
-
}
|
|
38636
|
-
listPageLinks(_input) {
|
|
38637
|
-
return Promise.reject(new KnowledgeUnsupportedCapabilityError("listPageLinks"));
|
|
38638
|
-
}
|
|
38639
|
-
countNotes(_input) {
|
|
38640
|
-
return Promise.reject(new KnowledgeUnsupportedCapabilityError("countNotes"));
|
|
38641
|
-
}
|
|
38642
|
-
listNotes(_input) {
|
|
38643
|
-
return Promise.reject(new KnowledgeUnsupportedCapabilityError("listNotes"));
|
|
38644
|
-
}
|
|
38645
|
-
listNotesMentioning(_input) {
|
|
38646
|
-
return Promise.reject(new KnowledgeUnsupportedCapabilityError("listNotesMentioning"));
|
|
38647
|
-
}
|
|
38648
|
-
addNote(_input) {
|
|
38649
|
-
return Promise.reject(new KnowledgeUnsupportedCapabilityError("addNote"));
|
|
38650
|
-
}
|
|
38651
|
-
restampNote(_input) {
|
|
38652
|
-
return Promise.reject(new KnowledgeUnsupportedCapabilityError("restampNote"));
|
|
38653
|
-
}
|
|
38654
|
-
removeNote(_input) {
|
|
38655
|
-
return Promise.reject(new KnowledgeUnsupportedCapabilityError("removeNote"));
|
|
38656
|
-
}
|
|
38657
|
-
restoreNote(_input) {
|
|
38658
|
-
return Promise.reject(new KnowledgeUnsupportedCapabilityError("restoreNote"));
|
|
38659
|
-
}
|
|
38660
|
-
searchPages(_input) {
|
|
38661
|
-
return Promise.reject(new KnowledgeUnsupportedCapabilityError("searchPages"));
|
|
38662
|
-
}
|
|
38663
|
-
listPageActivity(_input) {
|
|
38664
|
-
return Promise.reject(new KnowledgeUnsupportedCapabilityError("listPageActivity"));
|
|
38665
|
-
}
|
|
38666
|
-
addPinAudience(_input) {
|
|
38667
|
-
return Promise.reject(new KnowledgeUnsupportedCapabilityError("addPinAudience"));
|
|
38668
|
-
}
|
|
38669
|
-
removePinAudience(_input) {
|
|
38670
|
-
return Promise.reject(new KnowledgeUnsupportedCapabilityError("removePinAudience"));
|
|
38671
|
-
}
|
|
38672
|
-
listPins(_input) {
|
|
38673
|
-
return Promise.reject(new KnowledgeUnsupportedCapabilityError("listPins"));
|
|
38674
|
-
}
|
|
38675
|
-
};
|
|
38676
38641
|
const KNOWLEDGE_TABLE_NAMES = [
|
|
38677
38642
|
"mastra_knowledge_nodes",
|
|
38678
38643
|
"mastra_knowledge_records",
|
|
@@ -38708,6 +38673,20 @@ const KNOWLEDGE_PAGES_TABLE_NAMES = [
|
|
|
38708
38673
|
new Set([...KNOWLEDGE_TABLE_NAMES, ...RETIRED_KNOWLEDGE_TABLE_NAMES].filter((name) => !KNOWLEDGE_PAGES_TABLE_NAMES.includes(name)));
|
|
38709
38674
|
KNOWLEDGE_TABLE_NAMES.filter((name) => KNOWLEDGE_PAGES_TABLE_NAMES.includes(name));
|
|
38710
38675
|
/**
|
|
38676
|
+
* A list cursor the store cannot decode (malformed, or from another store or version). Defined
|
|
38677
|
+
* here so every adapter can throw it on any core version; core re-exports it from
|
|
38678
|
+
* `@mastra/core/storage`. Recognise it by `name`.
|
|
38679
|
+
* @experimental
|
|
38680
|
+
*/
|
|
38681
|
+
var KnowledgeInvalidCursorError = class extends Error {
|
|
38682
|
+
cursor;
|
|
38683
|
+
constructor(cursor) {
|
|
38684
|
+
super("Invalid Knowledge cursor: this store cannot decode it");
|
|
38685
|
+
this.cursor = cursor;
|
|
38686
|
+
this.name = "KnowledgeInvalidCursorError";
|
|
38687
|
+
}
|
|
38688
|
+
};
|
|
38689
|
+
/**
|
|
38711
38690
|
* Keyword-search words: the query split on whitespace, lowercased, deduplicated, keeping the first
|
|
38712
38691
|
* {@link KNOWLEDGE_SEARCH_MAX_WORDS}. A hit needs at least one of them (as a case-insensitive
|
|
38713
38692
|
* substring); an empty list means the search returns nothing.
|
|
@@ -38974,6 +38953,667 @@ function knowledgePositionBetween(before, after) {
|
|
|
38974
38953
|
if (before !== void 0 && after !== void 0 && before >= after) throw new Error(`Invalid position range: ${before} >= ${after}`);
|
|
38975
38954
|
return after === void 0 ? positionAfter(before ?? "") : positionMidpoint(before ?? "", after);
|
|
38976
38955
|
}
|
|
38956
|
+
// src/storage/domains/knowledge/base.ts
|
|
38957
|
+
/** @experimental Knowledge APIs are experimental and may change without notice. */
|
|
38958
|
+
const KNOWLEDGE_STORAGE_CONTRACT_VERSION = 4;
|
|
38959
|
+
/** @experimental Knowledge APIs are experimental and may change without notice. */
|
|
38960
|
+
const KNOWLEDGE_STORAGE_SCHEMA_VERSION = 4;
|
|
38961
|
+
/**
|
|
38962
|
+
* Classifies an adapter-provided, read-only schema snapshot. Adapters own the physical probe; this
|
|
38963
|
+
* helper owns version negotiation and never mutates the snapshot or backing store.
|
|
38964
|
+
*
|
|
38965
|
+
* @experimental Knowledge APIs are experimental and may change without notice.
|
|
38966
|
+
*/
|
|
38967
|
+
function inspectKnowledgeSchema(snapshot) {
|
|
38968
|
+
if (!snapshot.available) return {
|
|
38969
|
+
status: "unavailable",
|
|
38970
|
+
schemaVersion: null,
|
|
38971
|
+
reason: snapshot.reason ?? "The Knowledge storage adapter is unavailable."
|
|
38972
|
+
};
|
|
38973
|
+
if (snapshot.tableNames.length === 0) return {
|
|
38974
|
+
status: "uninitialized",
|
|
38975
|
+
schemaVersion: null
|
|
38976
|
+
};
|
|
38977
|
+
if (snapshot.schemaVersion === 4) return {
|
|
38978
|
+
status: "compatible",
|
|
38979
|
+
schemaVersion: 4
|
|
38980
|
+
};
|
|
38981
|
+
return {
|
|
38982
|
+
status: "incompatible-reset-required",
|
|
38983
|
+
schemaVersion: snapshot.schemaVersion ?? null,
|
|
38984
|
+
reason: snapshot.reason ?? `Existing experimental Knowledge tables are not compatible with schema version 4.`
|
|
38985
|
+
};
|
|
38986
|
+
}
|
|
38987
|
+
/** @experimental Knowledge APIs are experimental and may change without notice. */
|
|
38988
|
+
var KnowledgeConflictError = class extends Error {
|
|
38989
|
+
constructor(id) {
|
|
38990
|
+
super(`Knowledge record version conflict: ${id}`);
|
|
38991
|
+
this.name = "KnowledgeConflictError";
|
|
38992
|
+
}
|
|
38993
|
+
};
|
|
38994
|
+
var KnowledgeNotFoundError$1 = class extends Error {
|
|
38995
|
+
constructor(type, id) {
|
|
38996
|
+
super(`Knowledge ${type} not found: ${id}`);
|
|
38997
|
+
this.name = "KnowledgeNotFoundError";
|
|
38998
|
+
}
|
|
38999
|
+
};
|
|
39000
|
+
var KnowledgeSchemaResetRequiredError = class extends Error {
|
|
39001
|
+
inspection;
|
|
39002
|
+
constructor(inspection) {
|
|
39003
|
+
super(`Knowledge schema reset required: ${inspection.reason}. Existing Knowledge data is not migrated. To replace it, call \`await storage.stores?.knowledge?.dangerouslyReset()\`, which deletes every Knowledge row and nothing else.`);
|
|
39004
|
+
this.name = "KnowledgeSchemaResetRequiredError";
|
|
39005
|
+
this.inspection = inspection;
|
|
39006
|
+
}
|
|
39007
|
+
};
|
|
39008
|
+
var KnowledgeUnsupportedCapabilityError = class extends Error {
|
|
39009
|
+
constructor(capability) {
|
|
39010
|
+
super(`This Knowledge storage adapter does not expose ${capability}.`);
|
|
39011
|
+
this.name = "KnowledgeUnsupportedCapabilityError";
|
|
39012
|
+
}
|
|
39013
|
+
};
|
|
39014
|
+
/** A transaction ran past its `deadlineAt` and was rolled back; nothing in it was applied. Retrying is safe. */
|
|
39015
|
+
var KnowledgeTransactionDeadlineError = class extends Error {
|
|
39016
|
+
retryable = true;
|
|
39017
|
+
constructor(options) {
|
|
39018
|
+
super("The Knowledge transaction ran past its deadline and was rolled back.", options);
|
|
39019
|
+
this.name = "KnowledgeTransactionDeadlineError";
|
|
39020
|
+
}
|
|
39021
|
+
};
|
|
39022
|
+
function assertKnowledgeSchemaCompatible(inspection) {
|
|
39023
|
+
if (inspection.status === "compatible" || inspection.status === "uninitialized") return;
|
|
39024
|
+
if (inspection.status === "incompatible-reset-required") throw new KnowledgeSchemaResetRequiredError(inspection);
|
|
39025
|
+
throw new Error(`Knowledge schema inspection unavailable: ${inspection.reason}`);
|
|
39026
|
+
}
|
|
39027
|
+
const CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
|
|
39028
|
+
let lastUlidTime = -1;
|
|
39029
|
+
let lastUlidRandom = 0n;
|
|
39030
|
+
function parseKnowledgeWikilinks(text) {
|
|
39031
|
+
const names = [];
|
|
39032
|
+
const seen = /* @__PURE__ */ new Set();
|
|
39033
|
+
let contentStart = -1;
|
|
39034
|
+
for (let index = 0; index < text.length - 1; index++) {
|
|
39035
|
+
const pair = text.slice(index, index + 2);
|
|
39036
|
+
if (pair === "[[") {
|
|
39037
|
+
contentStart = index + 2;
|
|
39038
|
+
index++;
|
|
39039
|
+
continue;
|
|
39040
|
+
}
|
|
39041
|
+
if (pair !== "]]" || contentStart < 0) continue;
|
|
39042
|
+
const name = text.slice(contentStart, index).trim();
|
|
39043
|
+
const key = name.toLocaleLowerCase();
|
|
39044
|
+
if (name && !seen.has(key)) {
|
|
39045
|
+
seen.add(key);
|
|
39046
|
+
names.push(name);
|
|
39047
|
+
}
|
|
39048
|
+
contentStart = -1;
|
|
39049
|
+
index++;
|
|
39050
|
+
}
|
|
39051
|
+
return names;
|
|
39052
|
+
}
|
|
39053
|
+
function encodeCrockford(value, length) {
|
|
39054
|
+
let encoded = "";
|
|
39055
|
+
for (let index = 0; index < length; index++) {
|
|
39056
|
+
encoded = CROCKFORD[Number(value & 31n)] + encoded;
|
|
39057
|
+
value >>= 5n;
|
|
39058
|
+
}
|
|
39059
|
+
return encoded;
|
|
39060
|
+
}
|
|
39061
|
+
function createKnowledgeUlid(now = Date.now()) {
|
|
39062
|
+
if (now <= lastUlidTime) {
|
|
39063
|
+
now = lastUlidTime;
|
|
39064
|
+
lastUlidRandom = lastUlidRandom + 1n & (1n << 80n) - 1n;
|
|
39065
|
+
} else {
|
|
39066
|
+
lastUlidTime = now;
|
|
39067
|
+
lastUlidRandom = globalThis.crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(10)).reduce((value, byte) => value << 8n | BigInt(byte), 0n);
|
|
39068
|
+
}
|
|
39069
|
+
return `${encodeCrockford(BigInt(now), 10)}${encodeCrockford(lastUlidRandom, 16)}`;
|
|
39070
|
+
}
|
|
39071
|
+
var KnowledgeStorage = class extends StorageDomain {
|
|
39072
|
+
#storageIsolationKey;
|
|
39073
|
+
constructor(config = {}) {
|
|
39074
|
+
super({
|
|
39075
|
+
component: "STORAGE",
|
|
39076
|
+
name: "KNOWLEDGE"
|
|
39077
|
+
});
|
|
39078
|
+
this.#storageIsolationKey = config.storageIsolationKey ?? this;
|
|
39079
|
+
}
|
|
39080
|
+
/** Identifies the physical Knowledge backend and namespace used by this domain. */
|
|
39081
|
+
getStorageIsolationKey() {
|
|
39082
|
+
return this.#storageIsolationKey;
|
|
39083
|
+
}
|
|
39084
|
+
getCapabilities() {
|
|
39085
|
+
return {
|
|
39086
|
+
contractVersion: 4,
|
|
39087
|
+
schemaVersion: 1,
|
|
39088
|
+
supportsSchemaInspection: false,
|
|
39089
|
+
supportsExplicitReset: false
|
|
39090
|
+
};
|
|
39091
|
+
}
|
|
39092
|
+
/**
|
|
39093
|
+
* Runs `operation` against a view of this store whose reads and writes all belong to one
|
|
39094
|
+
* transaction: it commits when `operation` resolves and rolls back when it throws, and no other
|
|
39095
|
+
* connection sees its writes until it commits. A store method that fails inside the view undoes
|
|
39096
|
+
* only its own writes, so the caller can catch it and go on. `transaction` on the view joins the
|
|
39097
|
+
* same transaction the same way. Adapters in the same package can write their own tables through
|
|
39098
|
+
* the view, so they commit with the page writes.
|
|
39099
|
+
*
|
|
39100
|
+
* Calls on this store (not the view) while `operation` runs are outside the transaction. Await
|
|
39101
|
+
* calls on the view one at a time, as on a single connection.
|
|
39102
|
+
*
|
|
39103
|
+
* @experimental
|
|
39104
|
+
*/
|
|
39105
|
+
transaction(_operation, _options) {
|
|
39106
|
+
return Promise.reject(new KnowledgeUnsupportedCapabilityError("transactions"));
|
|
39107
|
+
}
|
|
39108
|
+
/**
|
|
39109
|
+
* On a {@link transaction} view: locks the pages' rows against other writers until commit. A no-op
|
|
39110
|
+
* on stores whose transactions already exclude every other writer (one write transaction at a
|
|
39111
|
+
* time).
|
|
39112
|
+
*
|
|
39113
|
+
* @experimental
|
|
39114
|
+
*/
|
|
39115
|
+
lockPages(_ids) {
|
|
39116
|
+
return Promise.resolve();
|
|
39117
|
+
}
|
|
39118
|
+
/**
|
|
39119
|
+
* On a {@link transaction} view: the ids of the live pages under `rootId` (not the root itself),
|
|
39120
|
+
* locked so no page can be added under, moved out of or removed from that subtree until commit.
|
|
39121
|
+
* A later {@link movePage} of `rootId` in the same transaction moves exactly these pages. Throws
|
|
39122
|
+
* {@link KnowledgeMoveTooLargeError} past {@link MAX_KNOWLEDGE_MOVE_PAGES}. The default walks the
|
|
39123
|
+
* children without locking, which holds on stores whose transactions exclude every other writer.
|
|
39124
|
+
*
|
|
39125
|
+
* @experimental
|
|
39126
|
+
*/
|
|
39127
|
+
async lockSubtree(rootId) {
|
|
39128
|
+
const ids = [];
|
|
39129
|
+
const parents = [rootId];
|
|
39130
|
+
while (parents.length) {
|
|
39131
|
+
const parentId = parents.shift();
|
|
39132
|
+
let cursor;
|
|
39133
|
+
do {
|
|
39134
|
+
const page = await this.listChildPages({
|
|
39135
|
+
parentId,
|
|
39136
|
+
read: "all",
|
|
39137
|
+
...cursor ? { cursor } : {}
|
|
39138
|
+
});
|
|
39139
|
+
for (const child of page.pages) {
|
|
39140
|
+
ids.push(child.id);
|
|
39141
|
+
parents.push(child.id);
|
|
39142
|
+
}
|
|
39143
|
+
if (ids.length >= 500) throw new KnowledgeMoveTooLargeError(rootId, ids.length + 1);
|
|
39144
|
+
cursor = page.nextCursor ?? void 0;
|
|
39145
|
+
} while (cursor);
|
|
39146
|
+
}
|
|
39147
|
+
return ids;
|
|
39148
|
+
}
|
|
39149
|
+
/**
|
|
39150
|
+
* Importer bookkeeping on the same database and namespace as the pages, or undefined when the
|
|
39151
|
+
* adapter has none. On a {@link transaction} view it belongs to that transaction.
|
|
39152
|
+
*
|
|
39153
|
+
* @experimental
|
|
39154
|
+
*/
|
|
39155
|
+
get importers() {}
|
|
39156
|
+
async inspectSchema() {
|
|
39157
|
+
return {
|
|
39158
|
+
status: "unavailable",
|
|
39159
|
+
schemaVersion: null,
|
|
39160
|
+
reason: "This Knowledge storage adapter does not support schema inspection."
|
|
39161
|
+
};
|
|
39162
|
+
}
|
|
39163
|
+
async dangerouslyReset() {
|
|
39164
|
+
throw new Error("This Knowledge storage adapter does not support an explicit Knowledge-only reset.");
|
|
39165
|
+
}
|
|
39166
|
+
/**
|
|
39167
|
+
* Scope declarations the store supplies itself, such as the scopes a hosted store's importers write
|
|
39168
|
+
* to, with their access rules. Knowledge merges them under its config's, reusing the answer for a
|
|
39169
|
+
* short window, so a declaration the store adds, removes or changes (revoking access included)
|
|
39170
|
+
* applies within it; a key the config declares keeps the config's declaration. None by default.
|
|
39171
|
+
*
|
|
39172
|
+
* @experimental
|
|
39173
|
+
*/
|
|
39174
|
+
async getScopeDeclarations() {
|
|
39175
|
+
return {};
|
|
39176
|
+
}
|
|
39177
|
+
materializeScope(_input) {
|
|
39178
|
+
return Promise.reject(new KnowledgeUnsupportedCapabilityError("materializeScope"));
|
|
39179
|
+
}
|
|
39180
|
+
getScopesByAddress(_input) {
|
|
39181
|
+
return Promise.reject(new KnowledgeUnsupportedCapabilityError("getScopesByAddress"));
|
|
39182
|
+
}
|
|
39183
|
+
listScopeDeclarations() {
|
|
39184
|
+
return Promise.reject(new KnowledgeUnsupportedCapabilityError("listScopeDeclarations"));
|
|
39185
|
+
}
|
|
39186
|
+
renameScopeDeclaration(_input) {
|
|
39187
|
+
return Promise.reject(new KnowledgeUnsupportedCapabilityError("renameScopeDeclaration"));
|
|
39188
|
+
}
|
|
39189
|
+
listChildScopes(_input) {
|
|
39190
|
+
return Promise.reject(new KnowledgeUnsupportedCapabilityError("listChildScopes"));
|
|
39191
|
+
}
|
|
39192
|
+
countChildScopes(_input) {
|
|
39193
|
+
return Promise.reject(new KnowledgeUnsupportedCapabilityError("countChildScopes"));
|
|
39194
|
+
}
|
|
39195
|
+
getPage(_input) {
|
|
39196
|
+
return Promise.reject(new KnowledgeUnsupportedCapabilityError("getPage"));
|
|
39197
|
+
}
|
|
39198
|
+
getPages(_input) {
|
|
39199
|
+
return Promise.reject(new KnowledgeUnsupportedCapabilityError("getPages"));
|
|
39200
|
+
}
|
|
39201
|
+
getPageByPath(_input) {
|
|
39202
|
+
return Promise.reject(new KnowledgeUnsupportedCapabilityError("getPageByPath"));
|
|
39203
|
+
}
|
|
39204
|
+
findPagesByName(_input) {
|
|
39205
|
+
return Promise.reject(new KnowledgeUnsupportedCapabilityError("findPagesByName"));
|
|
39206
|
+
}
|
|
39207
|
+
listChildPages(_input) {
|
|
39208
|
+
return Promise.reject(new KnowledgeUnsupportedCapabilityError("listChildPages"));
|
|
39209
|
+
}
|
|
39210
|
+
listPages(_input) {
|
|
39211
|
+
return Promise.reject(new KnowledgeUnsupportedCapabilityError("listPages"));
|
|
39212
|
+
}
|
|
39213
|
+
createPage(_input) {
|
|
39214
|
+
return Promise.reject(new KnowledgeUnsupportedCapabilityError("createPage"));
|
|
39215
|
+
}
|
|
39216
|
+
updatePage(_input) {
|
|
39217
|
+
return Promise.reject(new KnowledgeUnsupportedCapabilityError("updatePage"));
|
|
39218
|
+
}
|
|
39219
|
+
movePage(_input) {
|
|
39220
|
+
return Promise.reject(new KnowledgeUnsupportedCapabilityError("movePage"));
|
|
39221
|
+
}
|
|
39222
|
+
mergePages(_input) {
|
|
39223
|
+
return Promise.reject(new KnowledgeUnsupportedCapabilityError("mergePages"));
|
|
39224
|
+
}
|
|
39225
|
+
deletePage(_input) {
|
|
39226
|
+
return Promise.reject(new KnowledgeUnsupportedCapabilityError("deletePage"));
|
|
39227
|
+
}
|
|
39228
|
+
getNote(_input) {
|
|
39229
|
+
return Promise.reject(new KnowledgeUnsupportedCapabilityError("getNote"));
|
|
39230
|
+
}
|
|
39231
|
+
countChildPages(_input) {
|
|
39232
|
+
return Promise.reject(new KnowledgeUnsupportedCapabilityError("countChildPages"));
|
|
39233
|
+
}
|
|
39234
|
+
replacePageBodyLinks(_input) {
|
|
39235
|
+
return Promise.reject(new KnowledgeUnsupportedCapabilityError("replacePageBodyLinks"));
|
|
39236
|
+
}
|
|
39237
|
+
listPageBodyLinkSources(_input) {
|
|
39238
|
+
return Promise.reject(new KnowledgeUnsupportedCapabilityError("listPageBodyLinkSources"));
|
|
39239
|
+
}
|
|
39240
|
+
countPageLinks(_input) {
|
|
39241
|
+
return Promise.reject(new KnowledgeUnsupportedCapabilityError("countPageLinks"));
|
|
39242
|
+
}
|
|
39243
|
+
listPageLinks(_input) {
|
|
39244
|
+
return Promise.reject(new KnowledgeUnsupportedCapabilityError("listPageLinks"));
|
|
39245
|
+
}
|
|
39246
|
+
countNotes(_input) {
|
|
39247
|
+
return Promise.reject(new KnowledgeUnsupportedCapabilityError("countNotes"));
|
|
39248
|
+
}
|
|
39249
|
+
listNotes(_input) {
|
|
39250
|
+
return Promise.reject(new KnowledgeUnsupportedCapabilityError("listNotes"));
|
|
39251
|
+
}
|
|
39252
|
+
listNotesMentioning(_input) {
|
|
39253
|
+
return Promise.reject(new KnowledgeUnsupportedCapabilityError("listNotesMentioning"));
|
|
39254
|
+
}
|
|
39255
|
+
addNote(_input) {
|
|
39256
|
+
return Promise.reject(new KnowledgeUnsupportedCapabilityError("addNote"));
|
|
39257
|
+
}
|
|
39258
|
+
restampNote(_input) {
|
|
39259
|
+
return Promise.reject(new KnowledgeUnsupportedCapabilityError("restampNote"));
|
|
39260
|
+
}
|
|
39261
|
+
removeNote(_input) {
|
|
39262
|
+
return Promise.reject(new KnowledgeUnsupportedCapabilityError("removeNote"));
|
|
39263
|
+
}
|
|
39264
|
+
restoreNote(_input) {
|
|
39265
|
+
return Promise.reject(new KnowledgeUnsupportedCapabilityError("restoreNote"));
|
|
39266
|
+
}
|
|
39267
|
+
searchPages(_input) {
|
|
39268
|
+
return Promise.reject(new KnowledgeUnsupportedCapabilityError("searchPages"));
|
|
39269
|
+
}
|
|
39270
|
+
listPageActivity(_input) {
|
|
39271
|
+
return Promise.reject(new KnowledgeUnsupportedCapabilityError("listPageActivity"));
|
|
39272
|
+
}
|
|
39273
|
+
addPinAudience(_input) {
|
|
39274
|
+
return Promise.reject(new KnowledgeUnsupportedCapabilityError("addPinAudience"));
|
|
39275
|
+
}
|
|
39276
|
+
removePinAudience(_input) {
|
|
39277
|
+
return Promise.reject(new KnowledgeUnsupportedCapabilityError("removePinAudience"));
|
|
39278
|
+
}
|
|
39279
|
+
listPins(_input) {
|
|
39280
|
+
return Promise.reject(new KnowledgeUnsupportedCapabilityError("listPins"));
|
|
39281
|
+
}
|
|
39282
|
+
};
|
|
39283
|
+
// src/storage/domains/knowledge/importers.ts
|
|
39284
|
+
/** A binding was registered again with a different importer or target. */
|
|
39285
|
+
var KnowledgeImporterBindingConflictError = class extends Error {
|
|
39286
|
+
bindingId;
|
|
39287
|
+
constructor(bindingId) {
|
|
39288
|
+
super(`Knowledge importer binding ${bindingId} already exists with a different importer or target`);
|
|
39289
|
+
this.bindingId = bindingId;
|
|
39290
|
+
this.name = "KnowledgeImporterBindingConflictError";
|
|
39291
|
+
}
|
|
39292
|
+
};
|
|
39293
|
+
/** A conditional run write found the run in another state (see each method). */
|
|
39294
|
+
var KnowledgeImporterRunStateError = class extends Error {
|
|
39295
|
+
runId;
|
|
39296
|
+
reason;
|
|
39297
|
+
constructor(runId, reason) {
|
|
39298
|
+
super(`Knowledge importer run ${runId} refused the write: ${reason}`);
|
|
39299
|
+
this.runId = runId;
|
|
39300
|
+
this.reason = reason;
|
|
39301
|
+
this.name = "KnowledgeImporterRunStateError";
|
|
39302
|
+
}
|
|
39303
|
+
};
|
|
39304
|
+
/** @experimental */
|
|
39305
|
+
var KnowledgeImportersStorage = class {
|
|
39306
|
+
/**
|
|
39307
|
+
* The store's clock, which every run timestamp it writes (`startedAt`, `heartbeatAt`) comes from:
|
|
39308
|
+
* a host compares leases against it rather than its own clock. Defaults to this process's clock,
|
|
39309
|
+
* which is the store's own for an in-process store.
|
|
39310
|
+
*/
|
|
39311
|
+
async now() {
|
|
39312
|
+
return /* @__PURE__ */ new Date();
|
|
39313
|
+
}
|
|
39314
|
+
};
|
|
39315
|
+
// src/storage/domains/knowledge/importers-inmemory.ts
|
|
39316
|
+
const empty = () => ({
|
|
39317
|
+
bindings: /* @__PURE__ */ new Map(),
|
|
39318
|
+
nodes: /* @__PURE__ */ new Map(),
|
|
39319
|
+
state: /* @__PURE__ */ new Map(),
|
|
39320
|
+
runs: /* @__PURE__ */ new Map(),
|
|
39321
|
+
flushes: /* @__PURE__ */ new Map(),
|
|
39322
|
+
changes: /* @__PURE__ */ new Map(),
|
|
39323
|
+
guard: {
|
|
39324
|
+
activePath: "new",
|
|
39325
|
+
generation: 1,
|
|
39326
|
+
firstWriteAt: null
|
|
39327
|
+
},
|
|
39328
|
+
order: 0
|
|
39329
|
+
});
|
|
39330
|
+
const key = (...parts) => JSON.stringify(parts);
|
|
39331
|
+
/**
|
|
39332
|
+
* UTF-8 byte order, the order PostgreSQL's `COLLATE "C"` and SQLite's BINARY give. Code point order
|
|
39333
|
+
* is the same thing; JavaScript's `<` compares UTF-16 code units, which puts characters above U+FFFF
|
|
39334
|
+
* (surrogate pairs) before U+E000–U+FFFF.
|
|
39335
|
+
*/
|
|
39336
|
+
const byteOrder = (a, b) => {
|
|
39337
|
+
for (let i = 0, j = 0; i < a.length && j < b.length;) {
|
|
39338
|
+
const x = a.codePointAt(i);
|
|
39339
|
+
const y = b.codePointAt(j);
|
|
39340
|
+
if (x !== y) return x < y ? -1 : 1;
|
|
39341
|
+
i += x > 65535 ? 2 : 1;
|
|
39342
|
+
j += y > 65535 ? 2 : 1;
|
|
39343
|
+
}
|
|
39344
|
+
return a.length === b.length ? 0 : a.length < b.length ? -1 : 1;
|
|
39345
|
+
};
|
|
39346
|
+
function addCounts(into, add) {
|
|
39347
|
+
const out = { ...into };
|
|
39348
|
+
for (const [name, value] of Object.entries(add)) out[name] = (out[name] ?? 0) + value;
|
|
39349
|
+
return out;
|
|
39350
|
+
}
|
|
39351
|
+
/**
|
|
39352
|
+
* In-memory importer bookkeeping. One process, no locks: the owning store runs transactions one at
|
|
39353
|
+
* a time and rolls them back by restoring {@link snapshot}.
|
|
39354
|
+
*/
|
|
39355
|
+
var InMemoryKnowledgeImportersStorage = class extends KnowledgeImportersStorage {
|
|
39356
|
+
#s = empty();
|
|
39357
|
+
snapshot() {
|
|
39358
|
+
return structuredClone(this.#s);
|
|
39359
|
+
}
|
|
39360
|
+
restore(state) {
|
|
39361
|
+
this.#s = state;
|
|
39362
|
+
}
|
|
39363
|
+
async init() {}
|
|
39364
|
+
async dangerouslyClearAll() {
|
|
39365
|
+
this.#s = empty();
|
|
39366
|
+
}
|
|
39367
|
+
/** Part of the Knowledge store's reset: empties everything and moves the generation forward. */
|
|
39368
|
+
clearOnReset() {
|
|
39369
|
+
const { activePath, generation } = this.#s.guard;
|
|
39370
|
+
this.#s = empty();
|
|
39371
|
+
this.#s.guard = {
|
|
39372
|
+
activePath,
|
|
39373
|
+
generation: generation + 1,
|
|
39374
|
+
firstWriteAt: null
|
|
39375
|
+
};
|
|
39376
|
+
}
|
|
39377
|
+
async registerBinding(input) {
|
|
39378
|
+
const existing = this.#s.bindings.get(input.id);
|
|
39379
|
+
if (existing) {
|
|
39380
|
+
if (existing.importer !== input.importer || existing.target !== input.target) throw new KnowledgeImporterBindingConflictError(input.id);
|
|
39381
|
+
return {
|
|
39382
|
+
status: "unchanged",
|
|
39383
|
+
binding: { ...existing }
|
|
39384
|
+
};
|
|
39385
|
+
}
|
|
39386
|
+
const binding = {
|
|
39387
|
+
...input,
|
|
39388
|
+
anchorPageId: null,
|
|
39389
|
+
createdAt: /* @__PURE__ */ new Date()
|
|
39390
|
+
};
|
|
39391
|
+
this.#s.bindings.set(input.id, binding);
|
|
39392
|
+
return {
|
|
39393
|
+
status: "created",
|
|
39394
|
+
binding: { ...binding }
|
|
39395
|
+
};
|
|
39396
|
+
}
|
|
39397
|
+
async getBinding(id) {
|
|
39398
|
+
const binding = this.#s.bindings.get(id);
|
|
39399
|
+
return binding ? { ...binding } : null;
|
|
39400
|
+
}
|
|
39401
|
+
async setBindingAnchor(input) {
|
|
39402
|
+
const binding = this.#s.bindings.get(input.bindingId);
|
|
39403
|
+
if (!binding || binding.anchorPageId !== input.expected) return false;
|
|
39404
|
+
binding.anchorPageId = input.pageId;
|
|
39405
|
+
return true;
|
|
39406
|
+
}
|
|
39407
|
+
async listBindings() {
|
|
39408
|
+
return [...this.#s.bindings.values()].sort((a, b) => byteOrder(a.id, b.id)).map((b) => ({ ...b }));
|
|
39409
|
+
}
|
|
39410
|
+
async retireBinding(id) {
|
|
39411
|
+
this.#s.bindings.delete(id);
|
|
39412
|
+
for (const [k, node] of this.#s.nodes) if (node.bindingId === id) this.#s.nodes.delete(k);
|
|
39413
|
+
this.#s.state.delete(id);
|
|
39414
|
+
const runs = /* @__PURE__ */ new Set();
|
|
39415
|
+
for (const [runId, run] of this.#s.runs) {
|
|
39416
|
+
if (run.bindingId !== id) continue;
|
|
39417
|
+
runs.add(runId);
|
|
39418
|
+
this.#s.runs.delete(runId);
|
|
39419
|
+
}
|
|
39420
|
+
for (const [k, flush] of this.#s.flushes) if (runs.has(flush.runId)) this.#s.flushes.delete(k);
|
|
39421
|
+
for (const [k, { change }] of this.#s.changes) if (runs.has(change.runId)) this.#s.changes.delete(k);
|
|
39422
|
+
}
|
|
39423
|
+
async startRun(input) {
|
|
39424
|
+
const runs = [...this.#s.runs.values()].filter((r) => r.bindingId === input.bindingId);
|
|
39425
|
+
if (input.fireKey) {
|
|
39426
|
+
const fired = runs.find((r) => r.fireKey === input.fireKey);
|
|
39427
|
+
if (fired) return {
|
|
39428
|
+
status: "duplicate",
|
|
39429
|
+
run: structuredClone(fired)
|
|
39430
|
+
};
|
|
39431
|
+
}
|
|
39432
|
+
const running = runs.some((r) => r.status === "running");
|
|
39433
|
+
const now = /* @__PURE__ */ new Date();
|
|
39434
|
+
const run = {
|
|
39435
|
+
id: input.runId,
|
|
39436
|
+
bindingId: input.bindingId,
|
|
39437
|
+
generation: input.generation,
|
|
39438
|
+
status: running ? "skipped" : "running",
|
|
39439
|
+
fireKey: input.fireKey ?? null,
|
|
39440
|
+
deadlineAt: input.deadlineAt ?? null,
|
|
39441
|
+
cancelRequestedAt: null,
|
|
39442
|
+
heartbeatAt: null,
|
|
39443
|
+
lastSeq: 0,
|
|
39444
|
+
finish: null,
|
|
39445
|
+
counts: {},
|
|
39446
|
+
startedAt: now,
|
|
39447
|
+
completedAt: running ? now : null
|
|
39448
|
+
};
|
|
39449
|
+
this.#s.runs.set(run.id, run);
|
|
39450
|
+
return {
|
|
39451
|
+
status: running ? "skipped" : "started",
|
|
39452
|
+
run: structuredClone(run)
|
|
39453
|
+
};
|
|
39454
|
+
}
|
|
39455
|
+
async getRun(runId) {
|
|
39456
|
+
const run = this.#s.runs.get(runId);
|
|
39457
|
+
return run ? structuredClone(run) : null;
|
|
39458
|
+
}
|
|
39459
|
+
async listRuns(bindingId, options = {}) {
|
|
39460
|
+
return [...this.#s.runs.values()].filter((r) => r.bindingId === bindingId).sort((a, b) => b.startedAt.getTime() - a.startedAt.getTime()).slice(0, options.limit ?? 50).map((r) => structuredClone(r));
|
|
39461
|
+
}
|
|
39462
|
+
async requestCancel(runId) {
|
|
39463
|
+
const run = this.#s.runs.get(runId);
|
|
39464
|
+
if (!run || run.status !== "running") return null;
|
|
39465
|
+
run.cancelRequestedAt ??= /* @__PURE__ */ new Date();
|
|
39466
|
+
return structuredClone(run);
|
|
39467
|
+
}
|
|
39468
|
+
async heartbeat(runId) {
|
|
39469
|
+
const run = this.#s.runs.get(runId);
|
|
39470
|
+
if (!run || run.status !== "running") return null;
|
|
39471
|
+
run.heartbeatAt = /* @__PURE__ */ new Date();
|
|
39472
|
+
return structuredClone(run);
|
|
39473
|
+
}
|
|
39474
|
+
async abandonRun(input) {
|
|
39475
|
+
const run = this.#s.runs.get(input.runId);
|
|
39476
|
+
if (!run || run.status !== "running") return null;
|
|
39477
|
+
run.status = input.status ?? "failed";
|
|
39478
|
+
run.finish = structuredClone(input.finish);
|
|
39479
|
+
run.completedAt = /* @__PURE__ */ new Date();
|
|
39480
|
+
return structuredClone(run);
|
|
39481
|
+
}
|
|
39482
|
+
/** Transactions run one at a time in memory, so a read is as good as a lock. */
|
|
39483
|
+
async lockRun(runId) {
|
|
39484
|
+
return this.getRun(runId);
|
|
39485
|
+
}
|
|
39486
|
+
#activeRun(runId, generation) {
|
|
39487
|
+
const run = this.#s.runs.get(runId);
|
|
39488
|
+
if (!run) throw new KnowledgeImporterRunStateError(runId, "not_found");
|
|
39489
|
+
if (run.status !== "running") throw new KnowledgeImporterRunStateError(runId, "not_running");
|
|
39490
|
+
if (run.generation !== generation) throw new KnowledgeImporterRunStateError(runId, "generation");
|
|
39491
|
+
if (this.#s.guard.generation !== generation) throw new KnowledgeImporterRunStateError(runId, "stale_guard");
|
|
39492
|
+
return run;
|
|
39493
|
+
}
|
|
39494
|
+
async getFlush(runId, generation, seq) {
|
|
39495
|
+
const flush = this.#s.flushes.get(key(runId, generation, seq));
|
|
39496
|
+
return flush ? structuredClone(flush) : null;
|
|
39497
|
+
}
|
|
39498
|
+
async recordFlush(input) {
|
|
39499
|
+
const run = this.#activeRun(input.runId, input.generation);
|
|
39500
|
+
if (run.lastSeq !== input.seq - 1) throw new KnowledgeImporterRunStateError(input.runId, "seq");
|
|
39501
|
+
const { counts, ...flush } = input;
|
|
39502
|
+
this.#s.flushes.set(key(input.runId, input.generation, input.seq), structuredClone(flush));
|
|
39503
|
+
run.lastSeq = input.seq;
|
|
39504
|
+
run.counts = addCounts(run.counts, counts);
|
|
39505
|
+
}
|
|
39506
|
+
async finishRun(input) {
|
|
39507
|
+
const run = this.#activeRun(input.runId, input.generation);
|
|
39508
|
+
if (run.lastSeq !== input.lastSeq) throw new KnowledgeImporterRunStateError(input.runId, "seq");
|
|
39509
|
+
run.status = input.status;
|
|
39510
|
+
run.finish = structuredClone(input.finish);
|
|
39511
|
+
run.completedAt = /* @__PURE__ */ new Date();
|
|
39512
|
+
return structuredClone(run);
|
|
39513
|
+
}
|
|
39514
|
+
async getNode(bindingId, sourceId) {
|
|
39515
|
+
const node = this.#s.nodes.get(key(bindingId, sourceId));
|
|
39516
|
+
return node ? structuredClone(node) : null;
|
|
39517
|
+
}
|
|
39518
|
+
async getNodeByPage(pageId) {
|
|
39519
|
+
const node = [...this.#s.nodes.values()].find((n) => n.pageId === pageId);
|
|
39520
|
+
return node ? structuredClone(node) : null;
|
|
39521
|
+
}
|
|
39522
|
+
async saveNode(node) {
|
|
39523
|
+
const owner = [...this.#s.nodes.values()].find((n) => n.pageId === node.pageId);
|
|
39524
|
+
if (owner && (owner.bindingId !== node.bindingId || owner.sourceId !== node.sourceId)) throw new Error(`Knowledge page ${node.pageId} is already mapped to another imported node`);
|
|
39525
|
+
this.#s.nodes.set(key(node.bindingId, node.sourceId), structuredClone({
|
|
39526
|
+
...node,
|
|
39527
|
+
updatedAt: /* @__PURE__ */ new Date()
|
|
39528
|
+
}));
|
|
39529
|
+
}
|
|
39530
|
+
async deleteNode(bindingId, sourceId) {
|
|
39531
|
+
this.#s.nodes.delete(key(bindingId, sourceId));
|
|
39532
|
+
}
|
|
39533
|
+
async listNodes(bindingId, options = {}) {
|
|
39534
|
+
const limit = options.limit ?? 500;
|
|
39535
|
+
const nodes = [...this.#s.nodes.values()].filter((n) => n.bindingId === bindingId && (options.after === void 0 || byteOrder(n.sourceId, options.after) > 0) && (!options.unsettled || n.unsettled)).sort((a, b) => byteOrder(a.sourceId, b.sourceId));
|
|
39536
|
+
const items = nodes.slice(0, limit).map((n) => structuredClone(n));
|
|
39537
|
+
return {
|
|
39538
|
+
items,
|
|
39539
|
+
next: nodes.length > limit ? items[items.length - 1].sourceId : null
|
|
39540
|
+
};
|
|
39541
|
+
}
|
|
39542
|
+
#linking(bindingId, targetSourceIds) {
|
|
39543
|
+
const targets = new Set(targetSourceIds);
|
|
39544
|
+
return [...this.#s.nodes.values()].filter((n) => n.bindingId === bindingId && n.links.some((link) => targets.has(link.sourceId)));
|
|
39545
|
+
}
|
|
39546
|
+
async listLinkingNodes(bindingId, targetSourceIds, options = {}) {
|
|
39547
|
+
const limit = options.limit ?? 500;
|
|
39548
|
+
const ids = this.#linking(bindingId, targetSourceIds).map((n) => n.sourceId).filter((id) => options.after === void 0 || byteOrder(id, options.after) > 0).sort(byteOrder);
|
|
39549
|
+
const items = ids.slice(0, limit);
|
|
39550
|
+
return {
|
|
39551
|
+
items,
|
|
39552
|
+
next: ids.length > limit ? items[items.length - 1] : null
|
|
39553
|
+
};
|
|
39554
|
+
}
|
|
39555
|
+
async markLinkingNodesUnsettled(bindingId, targetSourceIds) {
|
|
39556
|
+
for (const n of this.#linking(bindingId, targetSourceIds)) n.unsettled = true;
|
|
39557
|
+
}
|
|
39558
|
+
async findNodeByAlias(bindingId, alias) {
|
|
39559
|
+
const node = [...this.#s.nodes.values()].find((n) => n.bindingId === bindingId && n.aliases.includes(alias));
|
|
39560
|
+
return node ? structuredClone(node) : null;
|
|
39561
|
+
}
|
|
39562
|
+
async getState(bindingId) {
|
|
39563
|
+
const out = {};
|
|
39564
|
+
for (const [name, value] of this.#s.state.get(bindingId) ?? []) Object.defineProperty(out, name, {
|
|
39565
|
+
value,
|
|
39566
|
+
enumerable: true,
|
|
39567
|
+
writable: true,
|
|
39568
|
+
configurable: true
|
|
39569
|
+
});
|
|
39570
|
+
return out;
|
|
39571
|
+
}
|
|
39572
|
+
async setState(bindingId, state) {
|
|
39573
|
+
const stored = this.#s.state.get(bindingId) ?? /* @__PURE__ */ new Map();
|
|
39574
|
+
for (const name of Object.keys(state)) stored.set(name, state[name]);
|
|
39575
|
+
this.#s.state.set(bindingId, stored);
|
|
39576
|
+
}
|
|
39577
|
+
async recordRunChange(change) {
|
|
39578
|
+
const id = key(change.runId, change.sourceId);
|
|
39579
|
+
const order = this.#s.changes.get(id)?.order ?? ++this.#s.order;
|
|
39580
|
+
this.#s.changes.set(id, {
|
|
39581
|
+
order,
|
|
39582
|
+
change: structuredClone(change)
|
|
39583
|
+
});
|
|
39584
|
+
}
|
|
39585
|
+
async listRunChanges(runId, options = {}) {
|
|
39586
|
+
const limit = options.limit ?? 500;
|
|
39587
|
+
const after = options.after === void 0 ? 0 : Number(options.after);
|
|
39588
|
+
const rows = [...this.#s.changes.values()].filter((c) => c.change.runId === runId && c.order > after).sort((a, b) => a.order - b.order);
|
|
39589
|
+
const page = rows.slice(0, limit);
|
|
39590
|
+
return {
|
|
39591
|
+
items: page.map((c) => structuredClone(c.change)),
|
|
39592
|
+
next: rows.length > limit ? String(page[page.length - 1].order) : null
|
|
39593
|
+
};
|
|
39594
|
+
}
|
|
39595
|
+
async readWriterGuard() {
|
|
39596
|
+
return { ...this.#s.guard };
|
|
39597
|
+
}
|
|
39598
|
+
async lockWriterGuard(_mode) {
|
|
39599
|
+
return { ...this.#s.guard };
|
|
39600
|
+
}
|
|
39601
|
+
/** Transactions are serialized here, so holding one is the lock. */
|
|
39602
|
+
async markFirstWrite() {
|
|
39603
|
+
if (this.#s.guard.firstWriteAt) return false;
|
|
39604
|
+
this.#s.guard.firstWriteAt = /* @__PURE__ */ new Date();
|
|
39605
|
+
return true;
|
|
39606
|
+
}
|
|
39607
|
+
async advanceWriterGuard(input) {
|
|
39608
|
+
if (input.generation <= this.#s.guard.generation) throw new Error(`Knowledge importer writer generation must move forward (${this.#s.guard.generation} -> ${input.generation})`);
|
|
39609
|
+
this.#s.guard = {
|
|
39610
|
+
activePath: input.activePath,
|
|
39611
|
+
generation: input.generation,
|
|
39612
|
+
firstWriteAt: null
|
|
39613
|
+
};
|
|
39614
|
+
return { ...this.#s.guard };
|
|
39615
|
+
}
|
|
39616
|
+
};
|
|
38977
39617
|
// src/storage/domains/knowledge/pages-inmemory.ts
|
|
38978
39618
|
const DEFAULT_SEARCH_LIMIT = 20;
|
|
38979
39619
|
function pageSize(limit) {
|
|
@@ -38982,8 +39622,9 @@ function pageSize(limit) {
|
|
|
38982
39622
|
return Math.min(limit, 100);
|
|
38983
39623
|
}
|
|
38984
39624
|
function paginate(items, cursor, limit) {
|
|
39625
|
+
if (cursor !== void 0 && !/^(0|[1-9]\d*)$/.test(cursor)) throw new KnowledgeInvalidCursorError(cursor);
|
|
38985
39626
|
const start = cursor === void 0 ? 0 : Number(cursor);
|
|
38986
|
-
if (!Number.
|
|
39627
|
+
if (!Number.isSafeInteger(start)) throw new KnowledgeInvalidCursorError(String(cursor));
|
|
38987
39628
|
const size = pageSize(limit);
|
|
38988
39629
|
return {
|
|
38989
39630
|
items: items.slice(start, start + size),
|
|
@@ -38998,12 +39639,6 @@ const oldestFirst = (a, b) => newestFirst(b, a);
|
|
|
38998
39639
|
const clone$1 = (value) => structuredClone(value);
|
|
38999
39640
|
const PIN_KINDS = ["page", "list"];
|
|
39000
39641
|
const pinKey = (pageId, kind) => `${kind}:${pageId}`;
|
|
39001
|
-
/**
|
|
39002
|
-
* In-memory schema-4 page store: the reference implementation of {@link KnowledgePageStore} that the
|
|
39003
|
-
* shared contract suite checks every adapter against.
|
|
39004
|
-
*
|
|
39005
|
-
* @experimental
|
|
39006
|
-
*/
|
|
39007
39642
|
var InMemoryKnowledgePageStore = class {
|
|
39008
39643
|
#pages = /* @__PURE__ */ new Map();
|
|
39009
39644
|
#notes = /* @__PURE__ */ new Map();
|
|
@@ -39011,6 +39646,25 @@ var InMemoryKnowledgePageStore = class {
|
|
|
39011
39646
|
#activity = [];
|
|
39012
39647
|
#bodyLinks = /* @__PURE__ */ new Map();
|
|
39013
39648
|
#clock = 0;
|
|
39649
|
+
/** A deep copy of every page, note, pin, body link and event, for {@link restore}. */
|
|
39650
|
+
snapshot() {
|
|
39651
|
+
return structuredClone({
|
|
39652
|
+
pages: this.#pages,
|
|
39653
|
+
notes: this.#notes,
|
|
39654
|
+
pins: this.#pins,
|
|
39655
|
+
activity: this.#activity,
|
|
39656
|
+
bodyLinks: this.#bodyLinks
|
|
39657
|
+
});
|
|
39658
|
+
}
|
|
39659
|
+
/** Puts back what {@link snapshot} copied. */
|
|
39660
|
+
restore(snapshot) {
|
|
39661
|
+
const copy = structuredClone(snapshot);
|
|
39662
|
+
this.#pages = copy.pages;
|
|
39663
|
+
this.#notes = copy.notes;
|
|
39664
|
+
this.#pins = copy.pins;
|
|
39665
|
+
this.#activity = copy.activity;
|
|
39666
|
+
this.#bodyLinks = copy.bodyLinks;
|
|
39667
|
+
}
|
|
39014
39668
|
/** Drops every page, note, pin, body link and event. */
|
|
39015
39669
|
clear() {
|
|
39016
39670
|
this.#pages.clear();
|
|
@@ -39619,6 +40273,7 @@ var InMemoryKnowledgePageStore = class {
|
|
|
39619
40273
|
}))].slice(0, limit);
|
|
39620
40274
|
}
|
|
39621
40275
|
async listPageActivity(input) {
|
|
40276
|
+
if (input.before !== void 0 && input.cursor !== void 0) throw new RangeError("Knowledge activity takes either a cursor or a before position, not both");
|
|
39622
40277
|
const { items, nextCursor } = paginate(this.#activity.filter((event) => {
|
|
39623
40278
|
const page = this.#pages.get(event.pageId);
|
|
39624
40279
|
if (!page || !this.#pageReadable(page, input.read)) return false;
|
|
@@ -39628,6 +40283,9 @@ var InMemoryKnowledgePageStore = class {
|
|
|
39628
40283
|
const note = this.#notes.get(event.noteId);
|
|
39629
40284
|
if (!note || !this.#noteVisible(note, input.read)) return false;
|
|
39630
40285
|
}
|
|
40286
|
+
if (input.since !== void 0 && event.createdAt.getTime() < input.since.getTime()) return false;
|
|
40287
|
+
if (input.until !== void 0 && event.createdAt.getTime() >= input.until.getTime()) return false;
|
|
40288
|
+
if (input.before !== void 0 && newestFirst(event, input.before) <= 0) return false;
|
|
39631
40289
|
return true;
|
|
39632
40290
|
}).sort(newestFirst), input.cursor, input.limit);
|
|
39633
40291
|
return {
|
|
@@ -39707,6 +40365,10 @@ var InMemoryKnowledgePageStore = class {
|
|
|
39707
40365
|
// src/storage/domains/knowledge/inmemory.ts
|
|
39708
40366
|
var InMemoryKnowledgeStorage = class extends KnowledgeStorage {
|
|
39709
40367
|
#pageStore = new InMemoryKnowledgePageStore();
|
|
40368
|
+
#importers = new InMemoryKnowledgeImportersStorage();
|
|
40369
|
+
get importers() {
|
|
40370
|
+
return this.#importers;
|
|
40371
|
+
}
|
|
39710
40372
|
materializeScope(input) {
|
|
39711
40373
|
return this.#pageStore.materializeScope(input);
|
|
39712
40374
|
}
|
|
@@ -39812,16 +40474,50 @@ var InMemoryKnowledgeStorage = class extends KnowledgeStorage {
|
|
|
39812
40474
|
listPins(input) {
|
|
39813
40475
|
return this.#pageStore.listPins(input);
|
|
39814
40476
|
}
|
|
40477
|
+
#transactionTail = Promise.resolve();
|
|
39815
40478
|
constructor(_config) {
|
|
39816
40479
|
super();
|
|
39817
40480
|
}
|
|
40481
|
+
/**
|
|
40482
|
+
* In memory there is no second connection: transactions run one at a time and roll back by
|
|
40483
|
+
* restoring a snapshot of pages and importer rows, and a read on this store (or a write from
|
|
40484
|
+
* outside the transaction) while one runs sees and shares its state: an outside write made during
|
|
40485
|
+
* a transaction that rolls back is rolled back with it. Each store call
|
|
40486
|
+
* on the view, and each nested `transaction`, undoes its own writes when it fails.
|
|
40487
|
+
*/
|
|
40488
|
+
transaction(operation) {
|
|
40489
|
+
const run = this.#transactionTail.then(() => this.#savepoint(() => operation(this.#view())));
|
|
40490
|
+
this.#transactionTail = run.catch(() => void 0);
|
|
40491
|
+
return run;
|
|
40492
|
+
}
|
|
40493
|
+
async #savepoint(operation) {
|
|
40494
|
+
const before = this.#pageStore.snapshot();
|
|
40495
|
+
const importersBefore = this.#importers.snapshot();
|
|
40496
|
+
try {
|
|
40497
|
+
return await operation();
|
|
40498
|
+
} catch (error) {
|
|
40499
|
+
this.#pageStore.restore(before);
|
|
40500
|
+
this.#importers.restore(importersBefore);
|
|
40501
|
+
throw error;
|
|
40502
|
+
}
|
|
40503
|
+
}
|
|
40504
|
+
#view() {
|
|
40505
|
+
return new Proxy(this, { get: (target, property, receiver) => {
|
|
40506
|
+
if (property === "transaction") return (operation) => target.#savepoint(() => operation(receiver));
|
|
40507
|
+
const value = Reflect.get(target, property, target);
|
|
40508
|
+
if (typeof value !== "function" || !(property in target.#pageStore)) return value;
|
|
40509
|
+
return (...args) => target.#savepoint(() => value.apply(target, args));
|
|
40510
|
+
} });
|
|
40511
|
+
}
|
|
39818
40512
|
getCapabilities() {
|
|
39819
40513
|
return {
|
|
39820
40514
|
contractVersion: 4,
|
|
39821
40515
|
schemaVersion: 4,
|
|
39822
40516
|
supportsSchemaInspection: true,
|
|
39823
40517
|
supportsExplicitReset: true,
|
|
39824
|
-
supportsPinKinds: true
|
|
40518
|
+
supportsPinKinds: true,
|
|
40519
|
+
supportsTransactions: true,
|
|
40520
|
+
supportsActivityDateRange: true
|
|
39825
40521
|
};
|
|
39826
40522
|
}
|
|
39827
40523
|
async inspectSchema() {
|
|
@@ -39832,6 +40528,7 @@ var InMemoryKnowledgeStorage = class extends KnowledgeStorage {
|
|
|
39832
40528
|
}
|
|
39833
40529
|
async dangerouslyReset() {
|
|
39834
40530
|
await this.dangerouslyClearAll();
|
|
40531
|
+
this.#importers.clearOnReset();
|
|
39835
40532
|
}
|
|
39836
40533
|
async dangerouslyClearAll() {
|
|
39837
40534
|
this.#pageStore.clear();
|
|
@@ -44968,7 +45665,14 @@ var MessageHistory = class {
|
|
|
44968
45665
|
const persistenceMessageList = messageList.cloneForPersistence();
|
|
44969
45666
|
const newInput = persistenceMessageList.get.input.db();
|
|
44970
45667
|
const newOutput = persistenceMessageList.get.response.db();
|
|
44971
|
-
const
|
|
45668
|
+
const resaveIds = new Set(persistenceMessageList.getMessagesToResave().map((message) => message.id));
|
|
45669
|
+
const newIds = new Set([...newInput, ...newOutput].map((message) => message.id));
|
|
45670
|
+
const resaved = persistenceMessageList.get.all.db().filter((message) => resaveIds.has(message.id) && !newIds.has(message.id));
|
|
45671
|
+
const messagesToSave = persistenceMessageList.transformMessagesForTranscript([
|
|
45672
|
+
...newInput,
|
|
45673
|
+
...newOutput,
|
|
45674
|
+
...resaved
|
|
45675
|
+
]);
|
|
44972
45676
|
if (messagesToSave.length === 0) return messageList;
|
|
44973
45677
|
this.memorySpan(observabilityContext)?.update({ attributes: { messageCount: messagesToSave.length } });
|
|
44974
45678
|
await this.persistMessages({
|
|
@@ -50864,14 +51568,16 @@ async function storedAttachmentBytes(fs, dir, root = true) {
|
|
|
50864
51568
|
return total;
|
|
50865
51569
|
}
|
|
50866
51570
|
// src/knowledge/instructions.ts
|
|
50867
|
-
|
|
51571
|
+
function readInstructions(canEdit) {
|
|
51572
|
+
return `Use the Knowledge tools for durable, shared knowledge. Pinned knowledge pages may already be in your context if <pinned-knowledge> tags are present in the visible conversation history: answer from their bodies without searching for or reading them again${canEdit ? ", and edit one straight from its body and the version shown, unless its body was cut off: then read it first, since a write replaces the whole body" : ""}. Read a pinned page with knowledge_read only when the answer depends on what its notes say, or on its child pages; a note count alone is no reason to read it. For anything else, search with knowledge_search before answering from Knowledge, and read a page with knowledge_read before relying on it. To see how a scope or section is organized, list it with knowledge_list and read pages by the refs it gives. Read a page whole first; when its body is too long, it comes back as its headings with line numbers and the first lines under each: read the section you need, or match the terms you are looking for. A result's more says what it left out: follow it only when what you need is not already in what you have read, and answer as soon as you have it. Cite the page or note you used. When nothing is found, say so plainly instead of guessing. When notes disagree, show both with their dates.`;
|
|
51573
|
+
}
|
|
50868
51574
|
const KNOWLEDGE_WRITE_INSTRUCTIONS = `When you write to Knowledge, add one durable fact per note with knowledge_note, on the page it is about. Add notes to an existing page before creating a new one. Put long-form text such as specs and runbooks in a page body with knowledge_page. A body write replaces the whole body. When a read returns only part of a body (numbered lines from a long page, a section, or matches), each part comes with its range: to edit those lines, write the new text, without the line numbers, with that range (or a smaller one inside it) and the version you read, and only those lines are replaced. Never write a partial body back without its range. Write page bodies in markdown (headings, lists, links); notes may use inline markdown such as links and code. Record a change as a new dated note rather than rewriting an old one, and remove only notes that are wrong.`;
|
|
50869
51575
|
const KNOWLEDGE_PINS_INSTRUCTIONS = `Maintain pinned pages with knowledge_pin (op pin or unpin). Pinned pages are delivered to the main agent on every turn, so they cost tokens permanently and must stay short. Pin only knowledge that should apply without being asked for, such as standing instructions, durable preferences, and hard constraints. Pin only knowledge that is BOTH costly to rediscover AND not the kind of thing a future agent would think to search for; anything a reminder can surface on demand does not belong in the pin set. Unpin a page as soon as it stops being unconditionally true.`;
|
|
50870
51576
|
function buildKnowledgeInstructions(groups, option) {
|
|
50871
51577
|
if (option === false) return "";
|
|
50872
51578
|
if (typeof option === "string") return option;
|
|
50873
51579
|
const parts = {
|
|
50874
|
-
read: groups.read ?
|
|
51580
|
+
read: groups.read ? readInstructions(groups.write) : "",
|
|
50875
51581
|
write: groups.write ? KNOWLEDGE_WRITE_INSTRUCTIONS : "",
|
|
50876
51582
|
pins: groups.pins ? KNOWLEDGE_PINS_INSTRUCTIONS : ""
|
|
50877
51583
|
};
|
|
@@ -51657,6 +52363,17 @@ async function knowledgeSubtree(storage, root) {
|
|
|
51657
52363
|
*/
|
|
51658
52364
|
const MAX_KNOWLEDGE_LINK_REFRESH_NAMESAKES = 99;
|
|
51659
52365
|
/**
|
|
52366
|
+
* A link refresh that landed but stopped at {@link MAX_KNOWLEDGE_LINK_REFRESH_SOURCES} linking pages
|
|
52367
|
+
* or {@link MAX_KNOWLEDGE_LINK_REFRESH_NAMESAKES} namesakes: the rest keep their links until they're
|
|
52368
|
+
* next written or `knowledge.reindexLinks()` runs.
|
|
52369
|
+
*/
|
|
52370
|
+
var KnowledgeLinkRefreshIncompleteError = class extends Error {
|
|
52371
|
+
constructor(message) {
|
|
52372
|
+
super(message);
|
|
52373
|
+
this.name = "KnowledgeLinkRefreshIncompleteError";
|
|
52374
|
+
}
|
|
52375
|
+
};
|
|
52376
|
+
/**
|
|
51660
52377
|
* Re-resolves the pages whose body links one of `pages` or names a ref one of them answers to now,
|
|
51661
52378
|
* after they were created, renamed, moved, merged or deleted, in page id order up to
|
|
51662
52379
|
* {@link MAX_KNOWLEDGE_LINK_REFRESH_SOURCES}. With `withDescendants`, the pages' subtrees count too
|
|
@@ -51686,7 +52403,7 @@ async function refreshKnowledgeLinksTo(storage, pages, options = {}) {
|
|
|
51686
52403
|
refs: [...refs],
|
|
51687
52404
|
toPageIds: [...targets]
|
|
51688
52405
|
})).sort();
|
|
51689
|
-
const crowdedError = () =>
|
|
52406
|
+
const crowdedError = () => new KnowledgeLinkRefreshIncompleteError(`More than ${MAX_KNOWLEDGE_LINK_REFRESH_NAMESAKES} pages are named ${crowded.join(", ")}; links to the rest were left as they were`);
|
|
51690
52407
|
if (!sources.length) {
|
|
51691
52408
|
if (crowded.length) throw crowdedError();
|
|
51692
52409
|
return;
|
|
@@ -51709,10 +52426,7 @@ async function refreshKnowledgeLinksTo(storage, pages, options = {}) {
|
|
|
51709
52426
|
done++;
|
|
51710
52427
|
}
|
|
51711
52428
|
const left = sources.length - done;
|
|
51712
|
-
if (left > 0) {
|
|
51713
|
-
const names = pages.map((page) => `"${page.name}"`).join(", ");
|
|
51714
|
-
throw new Error(`${left} more pages link to ${names}; their links were left as they were`);
|
|
51715
|
-
}
|
|
52429
|
+
if (left > 0) throw new KnowledgeLinkRefreshIncompleteError(`${left} more pages link to ${pages.map((page) => `"${page.name}"`).join(", ")}; their links were left as they were`);
|
|
51716
52430
|
if (crowded.length) throw crowdedError();
|
|
51717
52431
|
}
|
|
51718
52432
|
/**
|
|
@@ -60916,12 +61630,13 @@ async function removeKnowledgePage(host, input) {
|
|
|
60916
61630
|
await host.runtime.checkDeclarations();
|
|
60917
61631
|
const storage = await host.getStorage();
|
|
60918
61632
|
const [scope] = await storage.getScopesByAddress([input.scope]);
|
|
60919
|
-
|
|
60920
|
-
const page = await storage.getPageByPath({
|
|
61633
|
+
const page = scope ? await storage.getPageByPath({
|
|
60921
61634
|
scopeId: scope.id,
|
|
60922
61635
|
path: keys,
|
|
60923
61636
|
read: "all"
|
|
60924
|
-
});
|
|
61637
|
+
}) : null;
|
|
61638
|
+
const expected = input.expected;
|
|
61639
|
+
if (expected && (page?.id !== expected.id || page.version !== expected.version)) throw new KnowledgeConflictError(expected.id);
|
|
60925
61640
|
if (!page) return null;
|
|
60926
61641
|
const template = await host.runtime.templatePageRef(page);
|
|
60927
61642
|
if (template) throw new Error(`"${template}" is declared in config; change the scope's pages to remove it.`);
|
|
@@ -60933,6 +61648,7 @@ async function removeKnowledgePage(host, input) {
|
|
|
60933
61648
|
deletedBy: input.author ?? "host"
|
|
60934
61649
|
});
|
|
60935
61650
|
} catch (error) {
|
|
61651
|
+
if (expected && error?.name === "KnowledgeNotFoundError") throw new KnowledgeConflictError(expected.id);
|
|
60936
61652
|
if (error?.name === "KnowledgePageHasChildrenError") throw new Error(`"${input.scope}#${input.path}" has child pages; remove them first.`);
|
|
60937
61653
|
throw error;
|
|
60938
61654
|
}
|
|
@@ -61633,7 +62349,7 @@ function bodyView(body, input) {
|
|
|
61633
62349
|
const headings = knowledgeBodyOutline(body);
|
|
61634
62350
|
const skeleton = headings.length ? knowledgeBodySkeleton(lines, headings.map((heading) => heading.line), input.maxTokens) : void 0;
|
|
61635
62351
|
if (skeleton !== void 0) {
|
|
61636
|
-
more.push(`body: the page is ${lines.count} lines, too long to show whole, so \`lines\` shows every heading and the first lines under it; \u22EF marks lines left out and \u2026 a line cut short. Read the part you need with section (a heading) or from (a line number), then answer. To edit, read that part first: this view has no range to write back
|
|
62352
|
+
more.push(`body: the page is ${lines.count} lines, too long to show whole, so \`lines\` shows every heading and the first lines under it; \u22EF marks lines left out and \u2026 a line cut short. Read the part you need with section (a heading) or from (a line number), then answer.${input.canEdit ? " To edit, read that part first: this view has no range to write back." : ""}`);
|
|
61637
62353
|
return {
|
|
61638
62354
|
lines: skeleton,
|
|
61639
62355
|
lineCount: lines.count
|
|
@@ -61663,10 +62379,10 @@ function bodyView(body, input) {
|
|
|
61663
62379
|
...outline.length ? { outline } : {}
|
|
61664
62380
|
};
|
|
61665
62381
|
}
|
|
61666
|
-
function readTool(host) {
|
|
62382
|
+
function readTool(host, canEdit) {
|
|
61667
62383
|
return createTool({
|
|
61668
62384
|
id: "knowledge_read",
|
|
61669
|
-
description: `Read a page: its body, its notes, its child pages and the notes on other pages that mention it. Read a scope address (org:acme) to browse that scope. Without \`page\`, lists the scopes this run holds. When a page's notes, or the notes mentioning it, come to more than ${KNOWLEDGE_READ_INLINE_TOKENS.toLocaleString("en-US")} tokens, a whole read leaves them out and counts them in \`more\`; read them on their own with \`notes\` or \`mentionedIn\`. A body returns at most ${maxTokensOf(host).toLocaleString("en-US")} tokens at a time. A body that fits comes whole as \`body\`; a longer one comes as numbered \`lines\` (\`12\u2502text\`) with the \`range\` they cover, and \`more\` says where to read on; a first read of a long page shows every heading with its line number and the first lines under it, so you can pick the part to read. For a long page, ask for its \`outline\` of headings with their line numbers, read one \`section\`, or \`match\` terms to see only the lines that contain them, with \`context\` lines around each. Those part reads return just that part of the body
|
|
62385
|
+
description: `Read a page: its body, its notes, its child pages and the notes on other pages that mention it. Read a scope address (org:acme) to browse that scope. Without \`page\`, lists the scopes this run holds. When a page's notes, or the notes mentioning it, come to more than ${KNOWLEDGE_READ_INLINE_TOKENS.toLocaleString("en-US")} tokens, a whole read leaves them out and counts them in \`more\`; read them on their own with \`notes\` or \`mentionedIn\`. A body returns at most ${maxTokensOf(host).toLocaleString("en-US")} tokens at a time. A body that fits comes whole as \`body\`; a longer one comes as numbered \`lines\` (\`12\u2502text\`) with the \`range\` they cover, and \`more\` says where to read on; a first read of a long page shows every heading with its line number and the first lines under it, so you can pick the part to read. For a long page, ask for its \`outline\` of headings with their line numbers, read one \`section\`, or \`match\` terms to see only the lines that contain them, with \`context\` lines around each. Those part reads return just that part of the body.` + (canEdit ? " To edit part of a long body, pass the `range` a read gave you to knowledge_page." : ""),
|
|
61670
62386
|
inputSchema: {
|
|
61671
62387
|
type: "object",
|
|
61672
62388
|
properties: {
|
|
@@ -61763,7 +62479,8 @@ function readTool(host) {
|
|
|
61763
62479
|
context: matchContext,
|
|
61764
62480
|
from,
|
|
61765
62481
|
more,
|
|
61766
|
-
maxTokens: maxTokensOf(host)
|
|
62482
|
+
maxTokens: maxTokensOf(host),
|
|
62483
|
+
canEdit
|
|
61767
62484
|
});
|
|
61768
62485
|
return {
|
|
61769
62486
|
page: {
|
|
@@ -61866,7 +62583,8 @@ function readTool(host) {
|
|
|
61866
62583
|
const view = bodyView(page.body ?? "", {
|
|
61867
62584
|
context: matchContext,
|
|
61868
62585
|
more,
|
|
61869
|
-
maxTokens: maxTokensOf(host)
|
|
62586
|
+
maxTokens: maxTokensOf(host),
|
|
62587
|
+
canEdit
|
|
61870
62588
|
});
|
|
61871
62589
|
const noteList = await noteSummaries(run, notes.notes, mentionCache);
|
|
61872
62590
|
const mentionList = (await noteSummaries(run, mentioning.notes, mentionCache)).map((note, i) => ({
|
|
@@ -62147,11 +62865,12 @@ const NUMBERED_LINE = /^\s*\d+\u2502/;
|
|
|
62147
62865
|
* Without one, a body longer than one read returns is refused: the writer can only have seen part
|
|
62148
62866
|
* of it, and writing that part back would drop the rest.
|
|
62149
62867
|
*/
|
|
62150
|
-
function writtenBody(args, page, maxTokens) {
|
|
62868
|
+
function writtenBody(args, page, maxTokens, canRead) {
|
|
62869
|
+
const read = canRead ? "knowledge_read" : "read";
|
|
62151
62870
|
const stored = page.body ?? "";
|
|
62152
62871
|
if (args.body !== void 0) {
|
|
62153
62872
|
const written = args.body.split("\n").filter((line) => line.trim());
|
|
62154
|
-
if (written.length && written.every((line) => NUMBERED_LINE.test(line))) throw new Error(
|
|
62873
|
+
if (written.length && written.every((line) => NUMBERED_LINE.test(line))) throw new Error(`This body still has the line numbers a ${read} put in front of each line ("12\u2502"). Write the text without them.`);
|
|
62155
62874
|
}
|
|
62156
62875
|
if (args.range) {
|
|
62157
62876
|
if (args.body === void 0) throw new Error("range needs body: the text that replaces those lines.");
|
|
@@ -62160,18 +62879,18 @@ function writtenBody(args, page, maxTokens) {
|
|
|
62160
62879
|
const lines = new KnowledgeBodyLines(stored);
|
|
62161
62880
|
let start = lines.startOffset(args.range.start);
|
|
62162
62881
|
let end = lines.endOffset(args.range.end);
|
|
62163
|
-
if (start > end) throw new Error(`The range starts after it ends. Pass the range a
|
|
62164
|
-
if (end > knowledgeBodyWindow(lines, start, stored.length, maxTokens).end) throw new Error(`Lines ${args.range.start.line}\u2013${args.range.end.line} run past what one
|
|
62882
|
+
if (start > end) throw new Error(`The range starts after it ends. Pass the range a ${read} returned.`);
|
|
62883
|
+
if (end > knowledgeBodyWindow(lines, start, stored.length, maxTokens).end) throw new Error(`Lines ${args.range.start.line}\u2013${args.range.end.line} run past what one ${read} from line ${args.range.start.line} shows, so this can't be a range a read gave you. Edit the body part by part: write each part back with the range its own read returned.`);
|
|
62165
62884
|
if (args.range.start.col === void 0 && args.range.end.col === void 0 && args.body === "") {
|
|
62166
62885
|
if (end < stored.length) end++;
|
|
62167
62886
|
else if (start > 0) start--;
|
|
62168
62887
|
}
|
|
62169
62888
|
return stored.slice(0, start) + args.body + stored.slice(end);
|
|
62170
62889
|
}
|
|
62171
|
-
if (args.body !== void 0 && estimateTokenCount(stored) > maxTokens) throw new Error(`This page's body is ${stored.length} characters, more than one
|
|
62890
|
+
if (args.body !== void 0 && estimateTokenCount(stored) > maxTokens) throw new Error(`This page's body is ${stored.length} characters, more than one ${read} returns, and a body write without a range replaces all of it. ` + (canRead ? "Write back only the lines you read, with the range that read returned and its expectedVersion; read other parts with from, section or match and write each back with its own range." : "Without a read there is no range to write it back with, so leave this page unchanged."));
|
|
62172
62891
|
return args.body;
|
|
62173
62892
|
}
|
|
62174
|
-
function pageTool(host) {
|
|
62893
|
+
function pageTool(host, canRead) {
|
|
62175
62894
|
return createTool({
|
|
62176
62895
|
id: "knowledge_page",
|
|
62177
62896
|
description: "Write, move, merge or delete pages. A page body is the curated summary of its topic (needs editor to change); discrete attributed details belong in notes (knowledge_note). op \"write\": with `page`, edits that page (name, description, body; a scope page takes body only); without `page`, creates a page named `name` in `scope`. op \"move\": moves `page` under `parent` or to the top of `scope`. op \"merge\": merges `page` into `into`, keeping both pages' notes. op \"delete\": deletes `page` (needs owner on its scope); a page with child pages, a scope page and a page declared in config can't be deleted. `scope` is only for where content lands (create, move destination); edits and merges take none. Pages declared in config can be edited and merged into, but not moved, merged away or deleted.",
|
|
@@ -62226,7 +62945,7 @@ function pageTool(host) {
|
|
|
62226
62945
|
},
|
|
62227
62946
|
range: {
|
|
62228
62947
|
type: "object",
|
|
62229
|
-
description:
|
|
62948
|
+
description: `Edit: a range a ${canRead ? "knowledge_read" : "read"} returned (or part of one), e.g. {"start": {"line": 12}, "end": {"line": 14}}. \`body\` then replaces lines 12 through 14; an empty body removes them. A \`col\` limits it to part of a very long line. Needs expectedVersion.`,
|
|
62230
62949
|
properties: {
|
|
62231
62950
|
start: linePositionSchema,
|
|
62232
62951
|
end: linePositionSchema
|
|
@@ -62263,7 +62982,7 @@ function pageTool(host) {
|
|
|
62263
62982
|
expectedVersion: args.expectedVersion ?? page.version,
|
|
62264
62983
|
name: args.name,
|
|
62265
62984
|
description: args.description,
|
|
62266
|
-
body: writtenBody(args, page, maxTokensOf(host)),
|
|
62985
|
+
body: writtenBody(args, page, maxTokensOf(host), canRead),
|
|
62267
62986
|
provenance
|
|
62268
62987
|
});
|
|
62269
62988
|
await embed(host, (index) => index.indexPage(updated), pageEmbedFailed(storage, updated));
|
|
@@ -62463,10 +63182,10 @@ function noteTool(host) {
|
|
|
62463
63182
|
}
|
|
62464
63183
|
});
|
|
62465
63184
|
}
|
|
62466
|
-
function pinTool(host, onChange) {
|
|
63185
|
+
function pinTool(host, canRead, onChange) {
|
|
62467
63186
|
return createTool({
|
|
62468
63187
|
id: "knowledge_pin",
|
|
62469
|
-
description:
|
|
63188
|
+
description: `Pin a page into the context of every run holding one of the audience scopes, every turn; or unpin it. With kind "list", pin a listing of the pages under it instead (refs, names and child counts, ${canRead ? "like knowledge_list from it, " : ""}\`depth\` levels down), kept current as pages are added, renamed or removed. Pinned pages cost tokens on every turn: pin only standing instructions, durable preferences and hard constraints that apply without being asked for, and listings agents need to find their way. Needs editor on the page's scope and, for each audience, holding it or editor on it. A pinned page is delivered only to runs that can read it, and a listing shows only the pages they can read.`,
|
|
62470
63189
|
inputSchema: {
|
|
62471
63190
|
type: "object",
|
|
62472
63191
|
properties: {
|
|
@@ -62534,19 +63253,251 @@ function pinTool(host, onChange) {
|
|
|
62534
63253
|
}
|
|
62535
63254
|
});
|
|
62536
63255
|
}
|
|
63256
|
+
const ACTIVITY_DEFAULT_LIMIT = 25;
|
|
63257
|
+
const ACTIVITY_MAX_LIMIT = 100;
|
|
63258
|
+
const ACTIVITY_MAX_BATCHES = 8;
|
|
63259
|
+
const ACTIVITY_DATE = /^(\d{4})-(\d{2})-(\d{2})$/;
|
|
63260
|
+
const ACTIVITY_DATE_TIME = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(\.\d{1,3})?)?(Z|([+-])(\d{2}):(\d{2}))$/;
|
|
63261
|
+
/**
|
|
63262
|
+
* `2026-07-01` (UTC midnight) or a date-time with an explicit zone (`Z` or `±hh:mm`). A date-time
|
|
63263
|
+
* without a zone would be read in the host's zone, and an impossible date (`2026-02-30`) would be
|
|
63264
|
+
* rolled over by `Date`, so both are refused.
|
|
63265
|
+
*/
|
|
63266
|
+
function activityDate(name, value) {
|
|
63267
|
+
const trimmed = value.trim();
|
|
63268
|
+
const refuse = () => {
|
|
63269
|
+
throw new Error(`${name} must be a date like "2026-07-01" or a date-time with a zone like "2026-07-01T09:30:00Z" or "2026-07-01T09:30:00+02:00"; got "${value}".`);
|
|
63270
|
+
};
|
|
63271
|
+
const dateOnly = ACTIVITY_DATE.exec(trimmed);
|
|
63272
|
+
const dateTime = dateOnly ? void 0 : ACTIVITY_DATE_TIME.exec(trimmed);
|
|
63273
|
+
const match = dateOnly ?? dateTime ?? refuse();
|
|
63274
|
+
const [year, month, day, hour = 0, minute = 0, second = 0] = [
|
|
63275
|
+
1,
|
|
63276
|
+
2,
|
|
63277
|
+
3,
|
|
63278
|
+
4,
|
|
63279
|
+
5,
|
|
63280
|
+
6
|
|
63281
|
+
].map((index) => match[index] === void 0 ? void 0 : Number(match[index]));
|
|
63282
|
+
const wall = /* @__PURE__ */ new Date(0);
|
|
63283
|
+
wall.setUTCFullYear(year, month - 1, day);
|
|
63284
|
+
wall.setUTCHours(hour, minute, second, 0);
|
|
63285
|
+
if (wall.getUTCFullYear() !== year || wall.getUTCMonth() !== month - 1 || wall.getUTCDate() !== day || wall.getUTCHours() !== hour || wall.getUTCMinutes() !== minute || wall.getUTCSeconds() !== second) refuse();
|
|
63286
|
+
if (dateTime?.[9] !== void 0) {
|
|
63287
|
+
const offsetHours = Number(dateTime[10]);
|
|
63288
|
+
const offsetMinutes = Number(dateTime[11]);
|
|
63289
|
+
if (offsetMinutes > 59 || offsetHours > 14 || offsetHours === 14 && offsetMinutes > 0) refuse();
|
|
63290
|
+
}
|
|
63291
|
+
const date = new Date(dateOnly ? `${trimmed}T00:00:00.000Z` : trimmed);
|
|
63292
|
+
if (Number.isNaN(date.getTime())) refuse();
|
|
63293
|
+
const utcYear = date.getUTCFullYear();
|
|
63294
|
+
if (utcYear < 1 || utcYear > 9999) refuse();
|
|
63295
|
+
return date;
|
|
63296
|
+
}
|
|
63297
|
+
async function activityBinding(parts) {
|
|
63298
|
+
const bytes = new TextEncoder().encode(JSON.stringify(parts.map((part) => part ?? null)));
|
|
63299
|
+
const digest = await globalThis.crypto.subtle.digest("SHA-256", bytes);
|
|
63300
|
+
return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
63301
|
+
}
|
|
63302
|
+
function encodeActivityCursor(cursor) {
|
|
63303
|
+
return Buffer.from(JSON.stringify(cursor), "utf8").toString("base64url");
|
|
63304
|
+
}
|
|
63305
|
+
function decodeActivityCursor(value) {
|
|
63306
|
+
try {
|
|
63307
|
+
const cursor = JSON.parse(Buffer.from(value, "base64url").toString("utf8"));
|
|
63308
|
+
if (cursor?.v === 1 && Array.isArray(cursor.before) && typeof cursor.before[0] === "string" && typeof cursor.before[1] === "string" && !Number.isNaN(new Date(cursor.before[0]).getTime()) && typeof cursor.bind === "string") return cursor;
|
|
63309
|
+
} catch {}
|
|
63310
|
+
throw new Error("knowledge_activity: that cursor did not come from knowledge_activity.");
|
|
63311
|
+
}
|
|
63312
|
+
function activityTool(host) {
|
|
63313
|
+
const maxTokens = maxTokensOf(host);
|
|
63314
|
+
return createTool({
|
|
63315
|
+
id: "knowledge_activity",
|
|
63316
|
+
description: `What changed in Knowledge over a period: page creates, edits, moves, merges and deletes, and notes added, restamped, removed or restored, newest first, with who made each change. Give \`since\` and/or \`until\` (a date like 2026-07-01, or a date-time with a zone like 2026-07-01T09:30:00Z; at least one); \`from\` narrows it to one page or scope. A note entry shows the note's current text (marked \`current\`), not its text when the change happened; a removed note shows no text. One result holds at most \`limit\` changes and about ${maxTokens.toLocaleString("en-US")} tokens of them; when it stops early, \`more\` is true and \`cursor\` continues (pass the same since, until and from).`,
|
|
63317
|
+
inputSchema: {
|
|
63318
|
+
type: "object",
|
|
63319
|
+
properties: {
|
|
63320
|
+
since: {
|
|
63321
|
+
type: "string",
|
|
63322
|
+
minLength: 1,
|
|
63323
|
+
description: "Changes at or after this time, e.g. \"2026-07-01\" (UTC midnight), \"2026-07-01T09:30:00Z\" or \"2026-07-01T09:30:00+02:00\". A date-time needs a zone."
|
|
63324
|
+
},
|
|
63325
|
+
until: {
|
|
63326
|
+
type: "string",
|
|
63327
|
+
minLength: 1,
|
|
63328
|
+
description: "Changes before this time, same formats as since."
|
|
63329
|
+
},
|
|
63330
|
+
from: {
|
|
63331
|
+
type: "string",
|
|
63332
|
+
minLength: 1,
|
|
63333
|
+
description: `Only changes to this page or scope. ${pageRefDescription}`
|
|
63334
|
+
},
|
|
63335
|
+
limit: {
|
|
63336
|
+
type: "integer",
|
|
63337
|
+
minimum: 1,
|
|
63338
|
+
maximum: ACTIVITY_MAX_LIMIT,
|
|
63339
|
+
description: `Maximum changes. Defaults to ${ACTIVITY_DEFAULT_LIMIT}.`
|
|
63340
|
+
},
|
|
63341
|
+
cursor: {
|
|
63342
|
+
type: "string",
|
|
63343
|
+
minLength: 1,
|
|
63344
|
+
description: "The previous result's cursor, for the changes after it (pass the same since, until and from)."
|
|
63345
|
+
}
|
|
63346
|
+
},
|
|
63347
|
+
additionalProperties: false
|
|
63348
|
+
},
|
|
63349
|
+
execute: async (input, context) => {
|
|
63350
|
+
const args = input;
|
|
63351
|
+
if (args.since === void 0 && args.until === void 0) throw new Error("knowledge_activity needs since or until, e.g. since: \"2026-07-01\".");
|
|
63352
|
+
const since = args.since === void 0 ? void 0 : activityDate("since", args.since);
|
|
63353
|
+
const until = args.until === void 0 ? void 0 : activityDate("until", args.until);
|
|
63354
|
+
if (since && until && since.getTime() >= until.getTime()) throw new Error("knowledge_activity: since must be earlier than until.");
|
|
63355
|
+
const limit = Math.min(Math.max(args.limit ?? ACTIVITY_DEFAULT_LIMIT, 1), ACTIVITY_MAX_LIMIT);
|
|
63356
|
+
if (!(await host.getStorage()).getCapabilities().supportsActivityDateRange) throw new KnowledgeUnsupportedCapabilityError("listPageActivity date range");
|
|
63357
|
+
const cursor = args.cursor === void 0 ? void 0 : decodeActivityCursor(args.cursor);
|
|
63358
|
+
const run = await start(host, context);
|
|
63359
|
+
const origin = args.from ? await run.pageOrCloseMatches(args.from) : void 0;
|
|
63360
|
+
const filter = origin ? origin.isScope ? { scopeId: origin.id } : { pageId: origin.id } : {};
|
|
63361
|
+
const bind = await activityBinding([
|
|
63362
|
+
since?.toISOString(),
|
|
63363
|
+
until?.toISOString(),
|
|
63364
|
+
"scopeId" in filter ? filter.scopeId : void 0,
|
|
63365
|
+
"pageId" in filter ? filter.pageId : void 0
|
|
63366
|
+
]);
|
|
63367
|
+
if (cursor && cursor.bind !== bind) throw new Error("knowledge_activity: this cursor came from a call with different since, until or from. Pass the same ones as the call that returned it.");
|
|
63368
|
+
const entries = [];
|
|
63369
|
+
let used = 0;
|
|
63370
|
+
let position = cursor ? {
|
|
63371
|
+
createdAt: new Date(cursor.before[0]),
|
|
63372
|
+
id: cursor.before[1]
|
|
63373
|
+
} : void 0;
|
|
63374
|
+
let more = false;
|
|
63375
|
+
let stopped = false;
|
|
63376
|
+
let batches = 0;
|
|
63377
|
+
while (!stopped && entries.length < limit && batches < ACTIVITY_MAX_BATCHES) {
|
|
63378
|
+
batches++;
|
|
63379
|
+
const startedAt = position;
|
|
63380
|
+
const batch = await run.storage.listPageActivity({
|
|
63381
|
+
read: run.read,
|
|
63382
|
+
...filter,
|
|
63383
|
+
...since ? { since } : {},
|
|
63384
|
+
...until ? { until } : {},
|
|
63385
|
+
...position ? { before: position } : {},
|
|
63386
|
+
limit: limit - entries.length
|
|
63387
|
+
});
|
|
63388
|
+
more = batch.nextCursor !== void 0;
|
|
63389
|
+
const pages = /* @__PURE__ */ new Map();
|
|
63390
|
+
const notes = /* @__PURE__ */ new Map();
|
|
63391
|
+
for (const event of batch.events) {
|
|
63392
|
+
if (!pages.has(event.pageId)) {
|
|
63393
|
+
const page = await run.storage.getPage({
|
|
63394
|
+
id: event.pageId,
|
|
63395
|
+
read: run.read
|
|
63396
|
+
});
|
|
63397
|
+
if (page) pages.set(page.id, page);
|
|
63398
|
+
}
|
|
63399
|
+
if (event.noteId && !notes.has(event.noteId)) {
|
|
63400
|
+
const note = await run.storage.getNote({
|
|
63401
|
+
id: event.noteId,
|
|
63402
|
+
read: run.read,
|
|
63403
|
+
includeDeleted: true
|
|
63404
|
+
});
|
|
63405
|
+
if (note) notes.set(note.id, note);
|
|
63406
|
+
}
|
|
63407
|
+
}
|
|
63408
|
+
const { refs } = await pageRefs(run, [...pages.values()]);
|
|
63409
|
+
for (const event of batch.events) {
|
|
63410
|
+
const page = pages.get(event.pageId);
|
|
63411
|
+
const note = event.noteId ? notes.get(event.noteId) : void 0;
|
|
63412
|
+
if (!page || event.noteId && !note) {
|
|
63413
|
+
position = {
|
|
63414
|
+
createdAt: event.createdAt,
|
|
63415
|
+
id: event.id
|
|
63416
|
+
};
|
|
63417
|
+
continue;
|
|
63418
|
+
}
|
|
63419
|
+
const entry = {
|
|
63420
|
+
at: event.createdAt.toISOString(),
|
|
63421
|
+
action: event.action,
|
|
63422
|
+
page: {
|
|
63423
|
+
ref: refs.get(page.id) ?? page.id,
|
|
63424
|
+
name: page.name,
|
|
63425
|
+
...page.deletedAt ? { deleted: true } : {}
|
|
63426
|
+
},
|
|
63427
|
+
author: event.provenance.author,
|
|
63428
|
+
...note ? { note: note.deletedAt ? {
|
|
63429
|
+
ref: note.id,
|
|
63430
|
+
removed: true
|
|
63431
|
+
} : {
|
|
63432
|
+
ref: note.id,
|
|
63433
|
+
text: note.text,
|
|
63434
|
+
current: true
|
|
63435
|
+
} } : {}
|
|
63436
|
+
};
|
|
63437
|
+
let size = estimateTokenCount(JSON.stringify(entry));
|
|
63438
|
+
if (entries.length > 0 && used + size > maxTokens) {
|
|
63439
|
+
stopped = true;
|
|
63440
|
+
break;
|
|
63441
|
+
}
|
|
63442
|
+
if (entries.length === 0 && size > maxTokens && entry.note && "text" in entry.note) {
|
|
63443
|
+
const full = entry.note.text;
|
|
63444
|
+
let keep = full.length;
|
|
63445
|
+
while (keep > 0 && size > maxTokens) {
|
|
63446
|
+
keep = Math.floor(keep * .8);
|
|
63447
|
+
entry.note = {
|
|
63448
|
+
ref: entry.note.ref,
|
|
63449
|
+
text: full.slice(0, keep),
|
|
63450
|
+
current: true,
|
|
63451
|
+
truncated: true
|
|
63452
|
+
};
|
|
63453
|
+
size = estimateTokenCount(JSON.stringify(entry));
|
|
63454
|
+
}
|
|
63455
|
+
}
|
|
63456
|
+
entries.push(entry);
|
|
63457
|
+
used += size;
|
|
63458
|
+
position = {
|
|
63459
|
+
createdAt: event.createdAt,
|
|
63460
|
+
id: event.id
|
|
63461
|
+
};
|
|
63462
|
+
if (entries.length >= limit) break;
|
|
63463
|
+
}
|
|
63464
|
+
if (!more) break;
|
|
63465
|
+
if (position === startedAt) throw new Error("knowledge_activity: the store returned a continuation without any changes; stopping.");
|
|
63466
|
+
if (!stopped && entries.length >= limit) break;
|
|
63467
|
+
}
|
|
63468
|
+
const hasMore = stopped || more;
|
|
63469
|
+
return {
|
|
63470
|
+
...origin ? { from: {
|
|
63471
|
+
ref: (await pageRefs(run, [origin])).refs.get(origin.id) ?? origin.id,
|
|
63472
|
+
name: origin.name
|
|
63473
|
+
} } : {},
|
|
63474
|
+
changes: entries,
|
|
63475
|
+
...hasMore && position ? {
|
|
63476
|
+
more: true,
|
|
63477
|
+
cursor: encodeActivityCursor({
|
|
63478
|
+
v: 1,
|
|
63479
|
+
before: [position.createdAt.toISOString(), position.id],
|
|
63480
|
+
bind
|
|
63481
|
+
})
|
|
63482
|
+
} : {}
|
|
63483
|
+
};
|
|
63484
|
+
}
|
|
63485
|
+
});
|
|
63486
|
+
}
|
|
62537
63487
|
/** The schema-4 Knowledge tools. @internal */
|
|
62538
63488
|
function buildKnowledgePageTools(host, groups, onPinChange) {
|
|
62539
63489
|
const tools = {};
|
|
62540
63490
|
if (groups.read) {
|
|
62541
63491
|
tools.knowledge_list = listTool(host);
|
|
62542
63492
|
tools.knowledge_search = searchTool(host);
|
|
62543
|
-
tools.knowledge_read = readTool(host);
|
|
63493
|
+
tools.knowledge_read = readTool(host, groups.write);
|
|
63494
|
+
tools.knowledge_activity = activityTool(host);
|
|
62544
63495
|
}
|
|
62545
63496
|
if (groups.write) {
|
|
62546
|
-
tools.knowledge_page = pageTool(host);
|
|
63497
|
+
tools.knowledge_page = pageTool(host, groups.read);
|
|
62547
63498
|
tools.knowledge_note = noteTool(host);
|
|
62548
63499
|
}
|
|
62549
|
-
if (groups.pins) tools.knowledge_pin = pinTool(host, onPinChange);
|
|
63500
|
+
if (groups.pins) tools.knowledge_pin = pinTool(host, groups.read, onPinChange);
|
|
62550
63501
|
return tools;
|
|
62551
63502
|
}
|
|
62552
63503
|
// src/knowledge/pinned.ts
|
|
@@ -62554,6 +63505,8 @@ const PINNED_KNOWLEDGE_STATE_ID = "knowledge";
|
|
|
62554
63505
|
const PINNED_SNAPSHOT_TAG = "pinned-knowledge";
|
|
62555
63506
|
const PINNED_DELTA_TAG = "pinned-knowledge-update";
|
|
62556
63507
|
const PIN_TRUNCATION_MARKER = "[truncated \u2014 knowledge_read for the rest]";
|
|
63508
|
+
/** The marker for runs without `knowledge_read`, which can't open the rest. */
|
|
63509
|
+
const PIN_EXCERPT_MARKER = "[truncated]";
|
|
62557
63510
|
/** Entry id of the line listing stored pins that didn't fit the budget. */
|
|
62558
63511
|
const PIN_OVERFLOW_ID = "overflow";
|
|
62559
63512
|
function bindConfigPin(entry, params) {
|
|
@@ -62594,12 +63547,12 @@ async function resolveListing(run, origin, depth, maxTokens) {
|
|
|
62594
63547
|
/**
|
|
62595
63548
|
* Fills `maxTokens` a level at a time: every depth-1 line that fits, then depth 2, and so on, stopping
|
|
62596
63549
|
* at the first line that doesn't fit (always at least one). Lines print in tree order, so each child
|
|
62597
|
-
* still sits under its parent; a cut ends with a pointer to knowledge_list.
|
|
63550
|
+
* still sits under its parent; a cut ends with a pointer to knowledge_list when the run has it.
|
|
62598
63551
|
*/
|
|
62599
|
-
function renderListing(listing, ref, maxTokens) {
|
|
63552
|
+
function renderListing(listing, ref, maxTokens, read) {
|
|
62600
63553
|
const head = `Pages under ${listing.origin.name} (${ref}, depth ${listing.depth}):`;
|
|
62601
63554
|
if (listing.lines.length === 0) return `${head} none.`;
|
|
62602
|
-
const tail = (left) => `\u2026${left > 0 && !listing.more ? `and ${left} more` : "and more"}
|
|
63555
|
+
const tail = (left) => `\u2026${left > 0 && !listing.more ? `and ${left} more` : "and more"}${read ? `; knowledge_list from: "${ref}"` : ""}`;
|
|
62603
63556
|
const all = [
|
|
62604
63557
|
head,
|
|
62605
63558
|
...listing.lines.map((line) => line.text),
|
|
@@ -62625,12 +63578,13 @@ function renderListing(listing, ref, maxTokens) {
|
|
|
62625
63578
|
tail(listing.lines.length - kept.length)
|
|
62626
63579
|
].join("\n");
|
|
62627
63580
|
}
|
|
62628
|
-
function render(page, label, maxTokens) {
|
|
63581
|
+
function render(page, label, maxTokens, read) {
|
|
62629
63582
|
const notes = label.notes === void 0 ? "" : label.notes === 0 ? ", no notes" : label.notes === 1 ? ", 1 note" : `, ${label.notes} notes`;
|
|
62630
63583
|
const text = `${page.name} (${label.ref}, v${page.version}${notes}): ${page.body.trim()}`;
|
|
62631
63584
|
if (estimateTokenCount(text) <= maxTokens) return text;
|
|
62632
|
-
const
|
|
62633
|
-
|
|
63585
|
+
const marker = read ? PIN_TRUNCATION_MARKER : PIN_EXCERPT_MARKER;
|
|
63586
|
+
const room = Math.max(maxTokens - estimateTokenCount(marker) - 1, 1);
|
|
63587
|
+
return `${sliceByTokens(text, 0, room).trimEnd()} ${marker}`;
|
|
62634
63588
|
}
|
|
62635
63589
|
/** The run's principals grouped by `pinnedContextPriority`, highest first. */
|
|
62636
63590
|
function priorityTiers(compiled, principals) {
|
|
@@ -62723,9 +63677,10 @@ async function rankedStoredPins(run, excludePageIds, want) {
|
|
|
62723
63677
|
total
|
|
62724
63678
|
};
|
|
62725
63679
|
}
|
|
62726
|
-
function overflowLine(names, more) {
|
|
63680
|
+
function overflowLine(names, more, read) {
|
|
62727
63681
|
const listed = names.join(", ");
|
|
62728
|
-
|
|
63682
|
+
const rest = more > 0 ? `${listed ? `${listed}, ` : ""}\u2026and ${more} more` : listed;
|
|
63683
|
+
return `Also pinned${read ? " (open with knowledge_read)" : ""}: ${rest}`;
|
|
62729
63684
|
}
|
|
62730
63685
|
/**
|
|
62731
63686
|
* The pinned pages a run receives, rendered: config pins first (always delivered; an equal share each
|
|
@@ -62734,7 +63689,8 @@ function overflowLine(names, more) {
|
|
|
62734
63689
|
* the rest. The line counts against the token budget. Only pages the run can read and that have a body
|
|
62735
63690
|
* are delivered. A run costs a fixed handful of store calls however many pins exist.
|
|
62736
63691
|
*/
|
|
62737
|
-
|
|
63692
|
+
/** `read` is whether the run has `knowledge_read` and `knowledge_list`; without them no entry names either. */
|
|
63693
|
+
async function knowledgeDeliveredPins(run, budget, read) {
|
|
62738
63694
|
const configPinned = await configPins(run, budget.maxTokens);
|
|
62739
63695
|
const configured = configPinned.pages.filter((page) => page.body?.trim());
|
|
62740
63696
|
const listings = configPinned.listings;
|
|
@@ -62772,11 +63728,11 @@ async function knowledgeDeliveredPins(run, budget) {
|
|
|
62772
63728
|
const renderConfig = (room) => {
|
|
62773
63729
|
for (const page of configured) entries.push({
|
|
62774
63730
|
id: page.id,
|
|
62775
|
-
text: render(page, labelOf(page), room)
|
|
63731
|
+
text: render(page, labelOf(page), room, read)
|
|
62776
63732
|
});
|
|
62777
63733
|
for (const listing of listings) entries.push({
|
|
62778
63734
|
id: `${PIN_LIST_ID_PREFIX}${listing.origin.id}`,
|
|
62779
|
-
text: renderListing(listing, listingRef(listing), room)
|
|
63735
|
+
text: renderListing(listing, listingRef(listing), room, read)
|
|
62780
63736
|
});
|
|
62781
63737
|
};
|
|
62782
63738
|
renderConfig(Number.POSITIVE_INFINITY);
|
|
@@ -62798,10 +63754,10 @@ async function knowledgeDeliveredPins(run, budget) {
|
|
|
62798
63754
|
}
|
|
62799
63755
|
const entry = listing ? {
|
|
62800
63756
|
id: `${PIN_LIST_ID_PREFIX}${page.id}`,
|
|
62801
|
-
text: renderListing(listing, listingRef(listing), remaining)
|
|
63757
|
+
text: renderListing(listing, listingRef(listing), remaining, read)
|
|
62802
63758
|
} : {
|
|
62803
63759
|
id: page.id,
|
|
62804
|
-
text: render(page, labelOf(page), remaining)
|
|
63760
|
+
text: render(page, labelOf(page), remaining, read)
|
|
62805
63761
|
};
|
|
62806
63762
|
used += estimateTokenCount(entry.text);
|
|
62807
63763
|
delivered.push({
|
|
@@ -62809,7 +63765,7 @@ async function knowledgeDeliveredPins(run, budget) {
|
|
|
62809
63765
|
pin
|
|
62810
63766
|
});
|
|
62811
63767
|
}
|
|
62812
|
-
const line = () => overflowLine(left.slice(0, 10).map((pin) => pin.kind === "list" ? `${pin.pageName} (listing)` : pin.pageName), total - delivered.length - Math.min(left.length, 10));
|
|
63768
|
+
const line = () => overflowLine(left.slice(0, 10).map((pin) => pin.kind === "list" ? `${pin.pageName} (listing)` : pin.pageName), total - delivered.length - Math.min(left.length, 10), read);
|
|
62813
63769
|
while (total > delivered.length && delivered.length > 0 && used + estimateTokenCount(line()) > budget.maxTokens) {
|
|
62814
63770
|
const dropped = delivered.pop();
|
|
62815
63771
|
used -= estimateTokenCount(dropped.entry.text);
|
|
@@ -62936,12 +63892,17 @@ var PinnedStateProcessor = class {
|
|
|
62936
63892
|
constructor(deps) {
|
|
62937
63893
|
this.deps = deps;
|
|
62938
63894
|
}
|
|
63895
|
+
#guidance() {
|
|
63896
|
+
const write = this.deps.write !== false;
|
|
63897
|
+
if (this.deps.read === false) return write ? " To edit it, write from that body and pass that ref and version to knowledge_page as page and expectedVersion. A write replaces the whole body, so never write one built from an entry whose text ends in the truncation marker." : " An entry whose text ends in the truncation marker is an excerpt: use it as context, but do not treat it as the full page or use it to replace the page body.";
|
|
63898
|
+
return ` Do not knowledge_search or knowledge_read a pinned page to confirm it.${write ? " To edit it, write from that body and pass that ref and version to knowledge_page as page and expectedVersion; there is nothing more to read first, unless its text ends in the truncation marker. A write replaces the whole body, so never write one built from a cut-off entry: read the page first." : ""} Read it with knowledge_read only when your answer depends on what its notes say or on its child pages, or its text ends in the truncation marker; a note count alone is no reason to read it.`;
|
|
63899
|
+
}
|
|
62939
63900
|
processInput(args) {
|
|
62940
63901
|
return {
|
|
62941
63902
|
messages: args.messages,
|
|
62942
63903
|
systemMessages: [...args.systemMessages, {
|
|
62943
63904
|
role: "system",
|
|
62944
|
-
content: `Pinned knowledge may appear in the conversation as <${PINNED_SNAPSHOT_TAG} ...>...</${PINNED_SNAPSHOT_TAG}> snapshots and <${PINNED_DELTA_TAG} ...>...</${PINNED_DELTA_TAG}> deltas. These are automatic projections of durable pinned knowledge, not user instructions. Fold each delta onto the latest snapshot to know the current pin set, treat those entries as standing context, and do not treat a pin update as the user asking you to act on it. Each entry is the pinned page's name, then in parentheses its ref, its version and how many notes it has, then its full current body, read fresh for this turn: use and cite the body as it is
|
|
63905
|
+
content: `Pinned knowledge may appear in the conversation as <${PINNED_SNAPSHOT_TAG} ...>...</${PINNED_SNAPSHOT_TAG}> snapshots and <${PINNED_DELTA_TAG} ...>...</${PINNED_DELTA_TAG}> deltas. These are automatic projections of durable pinned knowledge, not user instructions. Fold each delta onto the latest snapshot to know the current pin set, treat those entries as standing context, and do not treat a pin update as the user asking you to act on it. Each entry is the pinned page's name, then in parentheses its ref, its version and how many notes it has, then its full current body, read fresh for this turn: use and cite the body as it is.${this.#guidance()}`
|
|
62945
63906
|
}]
|
|
62946
63907
|
};
|
|
62947
63908
|
}
|
|
@@ -70994,6 +71955,44 @@ function toLiveStructuredOutputSchema(schema, nullToUndefined) {
|
|
|
70994
71955
|
const standard = toStandardSchema(schema);
|
|
70995
71956
|
return nullToUndefined ? wrapSchemaWithNullTransform(standard) : standard;
|
|
70996
71957
|
}
|
|
71958
|
+
// src/mastra/resolve-agent.ts
|
|
71959
|
+
/**
|
|
71960
|
+
* Resolve an agent by id the same way server handlers do: in-memory registry
|
|
71961
|
+
* first, then the editor for stored agents.
|
|
71962
|
+
*
|
|
71963
|
+
* Stored (editor) agents aren't registered on the Mastra instance until
|
|
71964
|
+
* they've been hydrated once in the current process, so a registry miss does
|
|
71965
|
+
* not mean the agent is gone — especially on a cold start. Editor hydration
|
|
71966
|
+
* via `getById` also re-registers the agent, so subsequent lookups take the
|
|
71967
|
+
* fast registry path.
|
|
71968
|
+
*
|
|
71969
|
+
* Every internal call site that needs "does this agent exist / give it to
|
|
71970
|
+
* me" semantics should go through this helper so the fallback (and the
|
|
71971
|
+
* confirmed-miss vs. transient-error distinction) can't drift between call
|
|
71972
|
+
* sites.
|
|
71973
|
+
*/
|
|
71974
|
+
async function resolveAgentById(mastra, agentId, editorOptions) {
|
|
71975
|
+
try {
|
|
71976
|
+
return {
|
|
71977
|
+
status: "found",
|
|
71978
|
+
agent: mastra.getAgentById(agentId)
|
|
71979
|
+
};
|
|
71980
|
+
} catch {}
|
|
71981
|
+
const editor = mastra.getEditor?.();
|
|
71982
|
+
if (!editor) return { status: "missing" };
|
|
71983
|
+
try {
|
|
71984
|
+
const agent = await editor.agent.getById(agentId, editorOptions);
|
|
71985
|
+
return agent ? {
|
|
71986
|
+
status: "found",
|
|
71987
|
+
agent
|
|
71988
|
+
} : { status: "missing" };
|
|
71989
|
+
} catch (error) {
|
|
71990
|
+
return {
|
|
71991
|
+
status: "error",
|
|
71992
|
+
error
|
|
71993
|
+
};
|
|
71994
|
+
}
|
|
71995
|
+
}
|
|
70997
71996
|
// src/agent/save-queue/index.ts
|
|
70998
71997
|
var SaveQueueManager = class SaveQueueManager {
|
|
70999
71998
|
logger;
|
|
@@ -71249,6 +72248,32 @@ var DurableProcessorRebuildError = class extends Error {
|
|
|
71249
72248
|
this.cause = cause;
|
|
71250
72249
|
}
|
|
71251
72250
|
};
|
|
72251
|
+
/**
|
|
72252
|
+
* The process running a step could not find the run's agent in its registry
|
|
72253
|
+
* or editor. Running on would execute the step with no tools, memory or
|
|
72254
|
+
* processors, so the step fails instead.
|
|
72255
|
+
*/
|
|
72256
|
+
var DurableAgentNotFoundError = class extends Error {
|
|
72257
|
+
constructor(agentId, runId, cause) {
|
|
72258
|
+
super(`[DurableAgent:${agentId}] Agent "${agentId}" is not registered and the editor could not load it, so run ${runId} cannot run here${cause ? `: ${cause instanceof Error ? cause.message : String(cause)}` : ""}`);
|
|
72259
|
+
this.name = "DurableAgentNotFoundError";
|
|
72260
|
+
this.cause = cause;
|
|
72261
|
+
}
|
|
72262
|
+
};
|
|
72263
|
+
async function resolveRunAgent(mastra, agentId, runId, agentVersionId) {
|
|
72264
|
+
const version = agentVersionId ? { versionId: agentVersionId } : void 0;
|
|
72265
|
+
const result = await resolveAgentById(mastra, agentId, version);
|
|
72266
|
+
if (result.status !== "found") throw new DurableAgentNotFoundError(agentId, runId, result.status === "error" ? result.error : void 0);
|
|
72267
|
+
const { agent } = result;
|
|
72268
|
+
if (!version || agent.toRawConfig()?.resolvedVersionId === agentVersionId) return agent;
|
|
72269
|
+
try {
|
|
72270
|
+
const pinned = agent.source === "stored" ? await mastra.getEditor()?.agent.getById(agentId, version) : await mastra.resolveVersionedAgent(agent, version);
|
|
72271
|
+
if (pinned && pinned.toRawConfig()?.resolvedVersionId === version.versionId) return pinned;
|
|
72272
|
+
throw new Error(`Agent version "${agentVersionId}" was not found`);
|
|
72273
|
+
} catch (error) {
|
|
72274
|
+
throw new DurableAgentNotFoundError(agentId, runId, error);
|
|
72275
|
+
}
|
|
72276
|
+
}
|
|
71252
72277
|
async function rebuildProcessorPipeline(options) {
|
|
71253
72278
|
const { agent, agentId, requestContext, emptyErrorProcessorOverride, processorStates, logger } = options;
|
|
71254
72279
|
try {
|
|
@@ -71292,6 +72317,22 @@ function assertToolsetToolsAvailable(tools, toolsetToolNames, agentId, runId) {
|
|
|
71292
72317
|
});
|
|
71293
72318
|
}
|
|
71294
72319
|
/**
|
|
72320
|
+
* The background-task manager and agent config a run dispatches with, resolved
|
|
72321
|
+
* the same way as in preparation.ts. Only the process that started the run has
|
|
72322
|
+
* them on its registry entry, so a worker rebuilding the run restores them here;
|
|
72323
|
+
* without them every background-eligible tool runs inline (#31090).
|
|
72324
|
+
*
|
|
72325
|
+
* Dispatch stays off when the run's options are unknown: the entry keeps the
|
|
72326
|
+
* first manager a rebuild restores, so restoring one ungated could dispatch for
|
|
72327
|
+
* a run that disabled background tasks.
|
|
72328
|
+
*/
|
|
72329
|
+
function resolveBackgroundTasks(mastra, agent, execOptions) {
|
|
72330
|
+
return {
|
|
72331
|
+
backgroundTaskManager: !execOptions || execOptions.disableBackgroundTasks || execOptions.backgroundTaskPolicy?.allowToolDispatch === false ? void 0 : mastra.backgroundTaskManager,
|
|
72332
|
+
backgroundTasksConfig: agent.getBackgroundTasksConfig?.()
|
|
72333
|
+
};
|
|
72334
|
+
}
|
|
72335
|
+
/**
|
|
71295
72336
|
* Resolve all runtime dependencies needed for durable step execution.
|
|
71296
72337
|
*
|
|
71297
72338
|
* This function reconstructs the non-serializable state needed to execute
|
|
@@ -71325,11 +72366,13 @@ async function resolveRuntimeDependencies(options) {
|
|
|
71325
72366
|
let processorStates = globalEntry?.processorStates;
|
|
71326
72367
|
let rehydratedFromMastra = false;
|
|
71327
72368
|
let rebuiltAgent;
|
|
72369
|
+
let backgroundTasks;
|
|
71328
72370
|
if (hasHydratedEntry) logger?.debug?.(`[DurableAgent:${agentId}] Using model and tools from global registry for run ${runId}`);
|
|
71329
72371
|
else if (mastra) try {
|
|
71330
|
-
const agent = mastra.
|
|
72372
|
+
const agent = await resolveRunAgent(mastra, agentId, runId, input.agentVersionId);
|
|
71331
72373
|
rebuiltAgent = isDurableAgentLike(agent) && agent.agent !== agent ? agent.agent : agent;
|
|
71332
72374
|
const resolveRequestContext = restoreRequestContext$1(input.requestContextEntries, options.requestContext);
|
|
72375
|
+
backgroundTasks = resolveBackgroundTasks(mastra, agent, input.options);
|
|
71333
72376
|
tools = await agent.getToolsForExecution({
|
|
71334
72377
|
runId,
|
|
71335
72378
|
threadId: input.state.threadId,
|
|
@@ -71337,7 +72380,9 @@ async function resolveRuntimeDependencies(options) {
|
|
|
71337
72380
|
requestContext: resolveRequestContext,
|
|
71338
72381
|
memoryConfig: input.state.memoryConfig,
|
|
71339
72382
|
autoResumeSuspendedTools: input.options?.autoResumeSuspendedTools,
|
|
71340
|
-
clientTools: input.options?.clientTools
|
|
72383
|
+
clientTools: input.options?.clientTools,
|
|
72384
|
+
backgroundTaskEnabled: Boolean(backgroundTasks.backgroundTaskManager),
|
|
72385
|
+
backgroundTaskPolicy: input.options?.backgroundTaskPolicy
|
|
71341
72386
|
});
|
|
71342
72387
|
assertToolsetToolsAvailable(tools, input.options?.toolsetToolNames, agentId, runId);
|
|
71343
72388
|
model = await agent.getModel?.({ requestContext: resolveRequestContext }) ?? resolveModel(input.modelConfig, mastra);
|
|
@@ -71366,7 +72411,7 @@ async function resolveRuntimeDependencies(options) {
|
|
|
71366
72411
|
processorStates = rebuiltProcessors.processorStates;
|
|
71367
72412
|
rehydratedFromMastra = true;
|
|
71368
72413
|
} catch (error) {
|
|
71369
|
-
if (error instanceof DurableProcessorRebuildError) throw error;
|
|
72414
|
+
if (error instanceof DurableProcessorRebuildError || error instanceof DurableAgentNotFoundError) throw error;
|
|
71370
72415
|
if ((input.options?.toolsetToolNames?.length ?? 0) > 0) throw error;
|
|
71371
72416
|
logger?.debug?.(`[DurableAgent:${agentId}] Failed to get agent from Mastra: ${error}`);
|
|
71372
72417
|
model = resolveModel(input.modelConfig, mastra);
|
|
@@ -71391,7 +72436,8 @@ async function resolveRuntimeDependencies(options) {
|
|
|
71391
72436
|
outputProcessors,
|
|
71392
72437
|
errorProcessors,
|
|
71393
72438
|
processorStates,
|
|
71394
|
-
agent: rebuiltAgent
|
|
72439
|
+
agent: rebuiltAgent,
|
|
72440
|
+
...backgroundTasks
|
|
71395
72441
|
};
|
|
71396
72442
|
if (globalEntry) Object.assign(globalEntry, rebuilt);
|
|
71397
72443
|
else setRunRegistryEntry(runId, rebuilt, mastra);
|
|
@@ -71443,10 +72489,11 @@ async function rebuildRunToolsFromMastra(options) {
|
|
|
71443
72489
|
if (!mastra) return void 0;
|
|
71444
72490
|
let agentResolved = false;
|
|
71445
72491
|
try {
|
|
71446
|
-
const agent = mastra.
|
|
72492
|
+
const agent = await resolveRunAgent(mastra, agentId, runId, options.agentVersionId);
|
|
71447
72493
|
agentResolved = true;
|
|
71448
72494
|
const processorAgent = isDurableAgentLike(agent) && agent.agent !== agent ? agent.agent : agent;
|
|
71449
72495
|
const resolveRequestContext = restoreRequestContext$1(requestContextEntries, requestContext);
|
|
72496
|
+
const backgroundTasks = resolveBackgroundTasks(mastra, agent, execOptions);
|
|
71450
72497
|
const tools = await agent.getToolsForExecution({
|
|
71451
72498
|
runId,
|
|
71452
72499
|
threadId: state.threadId,
|
|
@@ -71454,7 +72501,9 @@ async function rebuildRunToolsFromMastra(options) {
|
|
|
71454
72501
|
requestContext: resolveRequestContext,
|
|
71455
72502
|
memoryConfig: state.memoryConfig,
|
|
71456
72503
|
autoResumeSuspendedTools: execOptions?.autoResumeSuspendedTools,
|
|
71457
|
-
clientTools: execOptions?.clientTools
|
|
72504
|
+
clientTools: execOptions?.clientTools,
|
|
72505
|
+
backgroundTaskEnabled: Boolean(backgroundTasks.backgroundTaskManager),
|
|
72506
|
+
backgroundTaskPolicy: execOptions?.backgroundTaskPolicy
|
|
71458
72507
|
});
|
|
71459
72508
|
if (!isHydratedRegistryEntry(getRunRegistryEntry(runId, mastra))) assertToolsetToolsAvailable(tools, execOptions?.toolsetToolNames, agentId, runId);
|
|
71460
72509
|
const memory = await agent.getMemory?.({ requestContext: resolveRequestContext });
|
|
@@ -71481,6 +72530,7 @@ async function rebuildRunToolsFromMastra(options) {
|
|
|
71481
72530
|
memory,
|
|
71482
72531
|
saveQueueManager,
|
|
71483
72532
|
agent: processorAgent,
|
|
72533
|
+
...backgroundTasks,
|
|
71484
72534
|
...rebuiltProcessors,
|
|
71485
72535
|
...options.rehydrateProcessors ? { requestContext: resolveRequestContext } : {}
|
|
71486
72536
|
};
|
|
@@ -71499,6 +72549,8 @@ async function rebuildRunToolsFromMastra(options) {
|
|
|
71499
72549
|
existing.errorProcessors ??= rebuiltProcessors.errorProcessors;
|
|
71500
72550
|
existing.processorStates ??= rebuiltProcessors.processorStates;
|
|
71501
72551
|
existing.agent ??= processorAgent;
|
|
72552
|
+
existing.backgroundTaskManager ??= backgroundTasks.backgroundTaskManager;
|
|
72553
|
+
existing.backgroundTasksConfig ??= backgroundTasks.backgroundTasksConfig;
|
|
71502
72554
|
} else {
|
|
71503
72555
|
existing = patch;
|
|
71504
72556
|
setRunRegistryEntry(runId, existing, mastra);
|
|
@@ -72031,6 +73083,7 @@ async function runDurableFinishSideEffects({ runId, initData, messageListState,
|
|
|
72031
73083
|
outputResultChunks.push(data);
|
|
72032
73084
|
} };
|
|
72033
73085
|
const outputTextBeforeProcessing = resolveOutputText(messageList);
|
|
73086
|
+
let rewrittenStepTexts;
|
|
72034
73087
|
if (registryEntry?.outputProcessors?.length) try {
|
|
72035
73088
|
let agent = registryEntry.agent;
|
|
72036
73089
|
if (!agent && mastra) try {
|
|
@@ -72039,7 +73092,7 @@ async function runDurableFinishSideEffects({ runId, initData, messageListState,
|
|
|
72039
73092
|
} catch {
|
|
72040
73093
|
agent = void 0;
|
|
72041
73094
|
}
|
|
72042
|
-
|
|
73095
|
+
const runner = new ProcessorRunner({
|
|
72043
73096
|
inputProcessors: registryEntry.inputProcessors ?? [],
|
|
72044
73097
|
outputProcessors: registryEntry.outputProcessors,
|
|
72045
73098
|
errorProcessors: registryEntry.errorProcessors ?? [],
|
|
@@ -72047,7 +73100,38 @@ async function runDurableFinishSideEffects({ runId, initData, messageListState,
|
|
|
72047
73100
|
agentName: initData.agentName ?? initData.agentId,
|
|
72048
73101
|
agent,
|
|
72049
73102
|
processorStates: registryEntry.processorStates
|
|
72050
|
-
})
|
|
73103
|
+
});
|
|
73104
|
+
const steps = outputResult?.steps;
|
|
73105
|
+
const lastStep = steps?.at(-1);
|
|
73106
|
+
const responses = messageList.get.response.db();
|
|
73107
|
+
const reply = steps && steps.length > 1 && responses.some((msg) => {
|
|
73108
|
+
const result = msg.content.metadata?.completionResult;
|
|
73109
|
+
return result && typeof result === "object" && "suppressFeedback" in result && result.suppressFeedback === true;
|
|
73110
|
+
}) ? resolveOutputMessageSkippingCompletionChecks(messageList) : void 0;
|
|
73111
|
+
const parts = reply?.content.parts;
|
|
73112
|
+
const offset = parts ? findIterationOffsetInParts(parts, lastStep?.text) : void 0;
|
|
73113
|
+
const split = reply && offset !== void 0 ? messageList.splitResponseMessageAtPartOffset(reply.id, offset) : void 0;
|
|
73114
|
+
const earlierSteps = split ? steps?.slice(0, -1).map((step) => ({ ...step })) : void 0;
|
|
73115
|
+
const earlierReply = split ? messageList.get.response.db().find((msg) => msg.id === split.earlierMessageId) : void 0;
|
|
73116
|
+
const earlierText = earlierReply ? resolveMessageText(earlierReply) : void 0;
|
|
73117
|
+
const earlierBoundaries = earlierSteps ? findStepPartBoundaries(earlierReply, earlierSteps) : void 0;
|
|
73118
|
+
try {
|
|
73119
|
+
await runner.runOutputProcessors(messageList, createObservabilityContext(tracingContext), effectiveRequestContext, 0, outputResultWriter, outputResult);
|
|
73120
|
+
if (split && earlierSteps && lastStep) {
|
|
73121
|
+
const processed = messageList.get.response.db();
|
|
73122
|
+
const earlier = processed.find((msg) => msg.id === split.earlierMessageId);
|
|
73123
|
+
const resolved = resolveOutputMessageSkippingCompletionChecks(messageList);
|
|
73124
|
+
const current = resolved && resolved.id !== split.earlierMessageId ? resolved : processed.find((msg) => msg.id === split.currentMessageId);
|
|
73125
|
+
reconcileBufferedStepTexts(earlierSteps, earlier ? resolveMessageText(earlier) : "", earlier, earlierBoundaries, earlierText);
|
|
73126
|
+
const stepTexts = [...earlierSteps.map((step) => step.text), current ? resolveMessageText(current) : ""];
|
|
73127
|
+
if (stepTexts.some((text, index) => text !== steps?.[index]?.text)) rewrittenStepTexts = stepTexts;
|
|
73128
|
+
}
|
|
73129
|
+
} finally {
|
|
73130
|
+
if (split) {
|
|
73131
|
+
clearStepPartIndexes(messageList.get.response.db());
|
|
73132
|
+
messageList.coalesceSplitResponseMessages(split.earlierMessageId, split.currentMessageId);
|
|
73133
|
+
}
|
|
73134
|
+
}
|
|
72051
73135
|
} catch (error) {
|
|
72052
73136
|
if (error instanceof TripWire) {
|
|
72053
73137
|
await undoSavedResponseMessages({
|
|
@@ -72081,6 +73165,11 @@ async function runDurableFinishSideEffects({ runId, initData, messageListState,
|
|
|
72081
73165
|
}
|
|
72082
73166
|
const outputText = resolveOutputText(messageList);
|
|
72083
73167
|
const outputTextChanged = outputText !== outputTextBeforeProcessing;
|
|
73168
|
+
const finishMessages = {
|
|
73169
|
+
all: messageList.get.all.aiV5.model(),
|
|
73170
|
+
user: messageList.get.input.aiV5.model(),
|
|
73171
|
+
nonUser: messageList.get.response.aiV5.model()
|
|
73172
|
+
};
|
|
72084
73173
|
const saveQueueManager = registryEntry?.saveQueueManager ?? rebuiltSaveQueueManager;
|
|
72085
73174
|
const memory = registryEntry?.memory ?? rebuiltMemory;
|
|
72086
73175
|
const authorizeMemory = durableState?.threadId && durableState.resourceId ? (permission) => authorizeDurableMemory(getDurableMemoryAuthorizationChecks(registryEntry), {
|
|
@@ -72162,6 +73251,8 @@ async function runDurableFinishSideEffects({ runId, initData, messageListState,
|
|
|
72162
73251
|
messageListState: messageList.serialize(),
|
|
72163
73252
|
outputText,
|
|
72164
73253
|
outputTextChanged,
|
|
73254
|
+
finishMessages,
|
|
73255
|
+
rewrittenStepTexts,
|
|
72165
73256
|
titleGeneration,
|
|
72166
73257
|
titleForStream,
|
|
72167
73258
|
structuredOutputChunks,
|
|
@@ -74059,6 +75150,7 @@ var DurableChunkPublishError$1 = class extends Error {
|
|
|
74059
75150
|
const durableLLMInputSchema = z$1.object({
|
|
74060
75151
|
runId: z$1.string(),
|
|
74061
75152
|
agentId: z$1.string(),
|
|
75153
|
+
agentVersionId: z$1.string().optional(),
|
|
74062
75154
|
agentName: z$1.string().optional(),
|
|
74063
75155
|
messageListState: z$1.any(),
|
|
74064
75156
|
initialUntaggedSystemMessages: z$1.array(z$1.any()).optional(),
|
|
@@ -74227,7 +75319,7 @@ function createDurableLLMExecutionStep(_options) {
|
|
|
74227
75319
|
const registry = getRunRegistryEntry(runId, mastra);
|
|
74228
75320
|
if (registry) registry.tracingTermination = termination;
|
|
74229
75321
|
};
|
|
74230
|
-
const emitFatalErrorBail = async (fatalError, modelId, signalPreempted = false) => {
|
|
75322
|
+
const emitFatalErrorBail = async (fatalError, modelId, { signalPreempted = false, modelRejectedBeforeStream = false } = {}) => {
|
|
74231
75323
|
ownership?.throwIfLost();
|
|
74232
75324
|
getRunRegistryEntry(runId, mastra)?.runScope?.set(LOCAL_MODEL_REQUEST_KEY, request);
|
|
74233
75325
|
const usage = {
|
|
@@ -74253,7 +75345,8 @@ function createDurableLLMExecutionStep(_options) {
|
|
|
74253
75345
|
payload: {
|
|
74254
75346
|
stepResult: {
|
|
74255
75347
|
reason: "error",
|
|
74256
|
-
isContinued: false
|
|
75348
|
+
isContinued: false,
|
|
75349
|
+
...modelRejectedBeforeStream && !isMastraTimeoutError(fatalError) ? { warnings: [] } : {}
|
|
74257
75350
|
},
|
|
74258
75351
|
output: { usage },
|
|
74259
75352
|
metadata: {}
|
|
@@ -74280,7 +75373,7 @@ function createDurableLLMExecutionStep(_options) {
|
|
|
74280
75373
|
ownership?.throwIfLost();
|
|
74281
75374
|
if (executionAbortSignalEarly?.aborted) {
|
|
74282
75375
|
const earlyTimeout = resolveTotalTimeoutAbort(executionAbortSignalEarly);
|
|
74283
|
-
if (earlyTimeout) return emitFatalErrorBail(earlyTimeout, typedInput.modelConfig?.modelId ?? "unknown", inputData.signalPreempted === true);
|
|
75376
|
+
if (earlyTimeout) return emitFatalErrorBail(earlyTimeout, typedInput.modelConfig?.modelId ?? "unknown", { signalPreempted: inputData.signalPreempted === true });
|
|
74284
75377
|
return {
|
|
74285
75378
|
...await storeStepTranscript(),
|
|
74286
75379
|
text: "",
|
|
@@ -74340,6 +75433,7 @@ function createDurableLLMExecutionStep(_options) {
|
|
|
74340
75433
|
}];
|
|
74341
75434
|
if (modelList.length === 0) throw new Error("No enabled models available for execution");
|
|
74342
75435
|
let lastError;
|
|
75436
|
+
let modelRejectedBeforeStream = false;
|
|
74343
75437
|
let skipUnavailableAttachments = false;
|
|
74344
75438
|
const maxProcessorRetries = resolveMaxProcessorRetries({
|
|
74345
75439
|
maxProcessorRetries: typedInput.options?.maxProcessorRetries,
|
|
@@ -74392,7 +75486,7 @@ function createDurableLLMExecutionStep(_options) {
|
|
|
74392
75486
|
payload: { id }
|
|
74393
75487
|
}, true);
|
|
74394
75488
|
const totalTimeout = resolveTotalTimeoutAbort(executionAbortSignalEarly, error instanceof Error ? error : void 0);
|
|
74395
|
-
if (totalTimeout) return emitFatalErrorBail(totalTimeout, modelId, true);
|
|
75489
|
+
if (totalTimeout) return emitFatalErrorBail(totalTimeout, modelId, { signalPreempted: true });
|
|
74396
75490
|
return {
|
|
74397
75491
|
...await storeStepTranscript(),
|
|
74398
75492
|
text: "",
|
|
@@ -74442,6 +75536,7 @@ function createDurableLLMExecutionStep(_options) {
|
|
|
74442
75536
|
const modelEntry = modelList[modelIndex];
|
|
74443
75537
|
const maxRetries = hasModelList || (typedInput.options?.agentMaxRetriesConfigured ?? false) ? modelEntry.maxRetries || 0 : typedInput.options?.modelSettings?.maxRetries ?? modelEntry.maxRetries ?? 0;
|
|
74444
75538
|
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
75539
|
+
let modelRequestRejected = false;
|
|
74445
75540
|
ownership?.throwIfLost();
|
|
74446
75541
|
request = {};
|
|
74447
75542
|
const attemptMessageId = currentMessageId;
|
|
@@ -75080,6 +76175,9 @@ function createDurableLLMExecutionStep(_options) {
|
|
|
75080
76175
|
includeRawChunks: execOptions.includeRawChunks,
|
|
75081
76176
|
methodType: "stream",
|
|
75082
76177
|
structuredOutput,
|
|
76178
|
+
onRequestFailed: () => {
|
|
76179
|
+
modelRequestRejected = true;
|
|
76180
|
+
},
|
|
75083
76181
|
onResult: ({ warnings: w, request: r, rawResponse: rr }) => {
|
|
75084
76182
|
warnings = w || [];
|
|
75085
76183
|
request = r || {};
|
|
@@ -75628,6 +76726,7 @@ function createDurableLLMExecutionStep(_options) {
|
|
|
75628
76726
|
};
|
|
75629
76727
|
}
|
|
75630
76728
|
lastError = errorObj;
|
|
76729
|
+
modelRejectedBeforeStream = modelRequestRejected;
|
|
75631
76730
|
const registryEntryInner = getRunRegistryEntry(runId, mastra);
|
|
75632
76731
|
const canRetryErrorInner = maxProcessorRetries !== void 0 && processorRetryCount < maxProcessorRetries;
|
|
75633
76732
|
if (registryEntryInner?.errorProcessors?.length) try {
|
|
@@ -75706,6 +76805,7 @@ function createDurableLLMExecutionStep(_options) {
|
|
|
75706
76805
|
};
|
|
75707
76806
|
}
|
|
75708
76807
|
lastError = streamErrorObj;
|
|
76808
|
+
modelRejectedBeforeStream = modelRequestRejected;
|
|
75709
76809
|
if (attempt < maxRetries) continue;
|
|
75710
76810
|
break;
|
|
75711
76811
|
}
|
|
@@ -75928,6 +77028,7 @@ function createDurableLLMExecutionStep(_options) {
|
|
|
75928
77028
|
if (interruption.signal.aborted) return finishInterruptedRequest(error, modelEntry.config.modelId);
|
|
75929
77029
|
if (error instanceof TripWire) throw error;
|
|
75930
77030
|
lastError = error instanceof Error ? error : new Error(String(error));
|
|
77031
|
+
modelRejectedBeforeStream = modelRequestRejected;
|
|
75931
77032
|
const selectedOuterAbortSignal = getRunRegistryEntry(runId, mastra)?.abortSignal ?? abortSignal;
|
|
75932
77033
|
const outerAbortSignal = ownership?.composeSignal(selectedOuterAbortSignal) ?? selectedOuterAbortSignal;
|
|
75933
77034
|
const totalTimeout = resolveTotalTimeoutAbort(outerAbortSignal, lastError);
|
|
@@ -76027,7 +77128,7 @@ function createDurableLLMExecutionStep(_options) {
|
|
|
76027
77128
|
}
|
|
76028
77129
|
const fatalError = lastError ?? /* @__PURE__ */ new Error("Exhausted all fallback models and reached the maximum number of retries.");
|
|
76029
77130
|
terminalAttemptContext?.recordTerminalError(fatalError);
|
|
76030
|
-
return emitFatalErrorBail(fatalError, modelList.at(-1)?.config.modelId ?? "unknown");
|
|
77131
|
+
return emitFatalErrorBail(fatalError, modelList.at(-1)?.config.modelId ?? "unknown", { modelRejectedBeforeStream });
|
|
76031
77132
|
})
|
|
76032
77133
|
});
|
|
76033
77134
|
}
|
|
@@ -77252,6 +78353,7 @@ function createDurableToolCallStep() {
|
|
|
77252
78353
|
mastra,
|
|
77253
78354
|
runId,
|
|
77254
78355
|
agentId: initData.agentId,
|
|
78356
|
+
agentVersionId: initData.agentVersionId,
|
|
77255
78357
|
state,
|
|
77256
78358
|
options: agentOptions,
|
|
77257
78359
|
requestContextEntries: initData.requestContextEntries,
|
|
@@ -77271,8 +78373,9 @@ function createDurableToolCallStep() {
|
|
|
77271
78373
|
if (!tool && !hasAuthoritativeToolSnapshot) tool = Object.values(rebuiltTools).find((t) => t && typeof t === "object" && "id" in t && t.id === toolName);
|
|
77272
78374
|
}
|
|
77273
78375
|
}
|
|
77274
|
-
|
|
77275
|
-
if (!tool &&
|
|
78376
|
+
const canUseGlobalTools = !hasAuthoritativeToolSnapshot && (!initData.agentVersionId || rebuiltTools !== void 0);
|
|
78377
|
+
if (!tool && canUseGlobalTools) tool = resolveTool$1(toolName, mastra);
|
|
78378
|
+
if (!tool && canUseGlobalTools && mastra) {
|
|
77276
78379
|
mastraTools = mastra.listTools?.();
|
|
77277
78380
|
if (mastraTools) {
|
|
77278
78381
|
tool = findProviderToolByName(mastraTools, toolName);
|
|
@@ -78973,7 +80076,9 @@ function createDurableLLMMappingStep() {
|
|
|
78973
80076
|
mastra,
|
|
78974
80077
|
runId: _runId,
|
|
78975
80078
|
agentId: _agentId,
|
|
80079
|
+
agentVersionId: getInitData()?.agentVersionId,
|
|
78976
80080
|
state,
|
|
80081
|
+
options: (getInitData?.())?.options,
|
|
78977
80082
|
requestContext
|
|
78978
80083
|
});
|
|
78979
80084
|
saveQueueManager = rebuilt?.saveQueueManager;
|
|
@@ -79422,7 +80527,10 @@ const durableAgenticInputSchema = z$1.object({
|
|
|
79422
80527
|
* Schema for the iteration state that flows through the dowhile loop.
|
|
79423
80528
|
* Extends base schema with model list for fallback support.
|
|
79424
80529
|
*/
|
|
79425
|
-
const iterationStateSchema = baseIterationStateSchema.extend({
|
|
80530
|
+
const iterationStateSchema = baseIterationStateSchema.extend({
|
|
80531
|
+
agentVersionId: z$1.string().optional(),
|
|
80532
|
+
modelList: z$1.array(z$1.any()).optional()
|
|
80533
|
+
});
|
|
79426
80534
|
/**
|
|
79427
80535
|
* Whether a reader that attaches mid-run can read the run's earlier events. Steps publish on the
|
|
79428
80536
|
* engine's bus, but `observe()` reads through the agent's own stream bus, which has no replay
|
|
@@ -79431,7 +80539,8 @@ const iterationStateSchema = baseIterationStateSchema.extend({ modelList: z$1.ar
|
|
|
79431
80539
|
function runTopicReplays(rt) {
|
|
79432
80540
|
const topic = AGENT_STREAM_TOPIC(rt.runId);
|
|
79433
80541
|
if (!rt.pubsub?.__replaysTopic(topic)) return false;
|
|
79434
|
-
|
|
80542
|
+
const agent = Object.values(rt.mastra?.listAgents() ?? {}).find((registered) => registered.id === rt.agentId);
|
|
80543
|
+
return (agent?.pubsub ?? agent?.__getStreamBus?.()?.pubsub)?.__replaysTopic?.(topic) ?? true;
|
|
79435
80544
|
}
|
|
79436
80545
|
function liveOrRebuiltAgentSpan(agentSpanData, reg, observability) {
|
|
79437
80546
|
if (!agentSpanData) return void 0;
|
|
@@ -79672,6 +80781,7 @@ var DurableAgenticLoopBuilder = class extends BaseAgenticLoopBuilder {
|
|
|
79672
80781
|
return params.bail({
|
|
79673
80782
|
...update,
|
|
79674
80783
|
...await storeAccumulatedSteps(params, accumulatedSteps),
|
|
80784
|
+
agentVersionId: initData.agentVersionId,
|
|
79675
80785
|
modelList: initData.modelList
|
|
79676
80786
|
});
|
|
79677
80787
|
}
|
|
@@ -79702,6 +80812,7 @@ var DurableAgenticLoopBuilder = class extends BaseAgenticLoopBuilder {
|
|
|
79702
80812
|
return {
|
|
79703
80813
|
runId: state.runId,
|
|
79704
80814
|
agentId: state.agentId,
|
|
80815
|
+
agentVersionId: state.agentVersionId,
|
|
79705
80816
|
agentName: state.agentName,
|
|
79706
80817
|
messageListState: state.messageListState,
|
|
79707
80818
|
initialUntaggedSystemMessages: state.initialUntaggedSystemMessages,
|
|
@@ -79762,6 +80873,7 @@ var DurableAgenticLoopBuilder = class extends BaseAgenticLoopBuilder {
|
|
|
79762
80873
|
return {
|
|
79763
80874
|
...baseUpdate,
|
|
79764
80875
|
...await storeAccumulatedSteps(params, accumulatedSteps),
|
|
80876
|
+
agentVersionId: initData.agentVersionId,
|
|
79765
80877
|
modelList: initData.modelList
|
|
79766
80878
|
};
|
|
79767
80879
|
}, { id: "update-iteration-state" }).then(isTaskCompleteStep).then(goalStep).commit();
|
|
@@ -80054,8 +81166,21 @@ var DurableAgenticLoopBuilder = class extends BaseAgenticLoopBuilder {
|
|
|
80054
81166
|
steps
|
|
80055
81167
|
}
|
|
80056
81168
|
});
|
|
80057
|
-
const
|
|
80058
|
-
|
|
81169
|
+
const rewrittenStepTexts = finishResult.rewrittenStepTexts;
|
|
81170
|
+
const textRewritten = !!lastStep && (finishResult.outputTextChanged || !!rewrittenStepTexts);
|
|
81171
|
+
if (rewrittenStepTexts) {
|
|
81172
|
+
for (const [index, text] of rewrittenStepTexts.entries()) {
|
|
81173
|
+
storedSteps[index] = {
|
|
81174
|
+
...storedSteps[index],
|
|
81175
|
+
text
|
|
81176
|
+
};
|
|
81177
|
+
steps[index] = {
|
|
81178
|
+
...steps[index],
|
|
81179
|
+
text
|
|
81180
|
+
};
|
|
81181
|
+
}
|
|
81182
|
+
finalText = finishResult.outputText;
|
|
81183
|
+
} else if (lastStep && finishResult.outputTextChanged) {
|
|
80059
81184
|
lastStep.text = finishResult.outputText;
|
|
80060
81185
|
steps[steps.length - 1] = {
|
|
80061
81186
|
...steps[steps.length - 1],
|
|
@@ -80110,7 +81235,7 @@ var DurableAgenticLoopBuilder = class extends BaseAgenticLoopBuilder {
|
|
|
80110
81235
|
if (pubsub) await emitFinishEvent(pubsub, state.runId, {
|
|
80111
81236
|
output: finalOutput.output,
|
|
80112
81237
|
stepResult: finalOutput.stepResult,
|
|
80113
|
-
messages: finishMessages,
|
|
81238
|
+
messages: finishResult.finishMessages ?? finishMessages,
|
|
80114
81239
|
...textRewritten && { textRewritten },
|
|
80115
81240
|
...stopCause && { stopCause }
|
|
80116
81241
|
});
|
|
@@ -80615,6 +81740,11 @@ var DefaultAgentExecutionEngine = class {
|
|
|
80615
81740
|
};
|
|
80616
81741
|
getWorkflow(options) {
|
|
80617
81742
|
if (!this.#workflow) {
|
|
81743
|
+
if (options.storesRunsInJournal) {
|
|
81744
|
+
const storage = this.mastra?.getStorage();
|
|
81745
|
+
const workflowsStore = storage?.stores?.workflows;
|
|
81746
|
+
if (workflowsStore && !workflowsStore.supportsRunJournal()) options.guardrailLogger?.warn(`DurableAgent '${this.id}' sets storageVersion: 2, which ${storage?.name ?? "the configured"} storage doesn't support yet; storing new runs as version 1.`);
|
|
81747
|
+
}
|
|
80618
81748
|
this.#workflow = this.createWorkflow(options);
|
|
80619
81749
|
this.warnOnRiskyPersistencePolicy(options.shouldPersistSnapshot, options.guardrailLogger);
|
|
80620
81750
|
if (this.mastra) {
|
|
@@ -80908,7 +82038,11 @@ var EventedAgentExecutionEngine = class extends DefaultAgentExecutionEngine {
|
|
|
80908
82038
|
}
|
|
80909
82039
|
prepareExecution(pubsub, fence, workflowEngine, logger, guardrailLogger) {
|
|
80910
82040
|
const engine = this.resolveWorkflowEngine(workflowEngine, logger);
|
|
80911
|
-
const sharedTransport = engine === "evented" && pubsub !== void 0 &&
|
|
82041
|
+
const sharedTransport = engine === "evented" && pubsub !== void 0 && reachesOtherProcesses(pubsub);
|
|
82042
|
+
if (sharedTransport && this.mastra) {
|
|
82043
|
+
const mastra = this.mastra;
|
|
82044
|
+
Promise.resolve(mastra.getStorage()?.getStore("workflows")).catch(() => void 0).then((store) => warnUnsupportedEventedSetup(mastra, store)).catch(() => {});
|
|
82045
|
+
}
|
|
80912
82046
|
const sharedExecution = sharedTransport && fence?.generation !== void 0;
|
|
80913
82047
|
if (sharedTransport && !sharedExecution && !this.#warnedUnfencedSharedExecution) {
|
|
80914
82048
|
this.#warnedUnfencedSharedExecution = true;
|
|
@@ -81354,7 +82488,7 @@ async function prepareForDurableExecution(options) {
|
|
|
81354
82488
|
});
|
|
81355
82489
|
let tripwireData;
|
|
81356
82490
|
if (inputProcessors.length > 0) try {
|
|
81357
|
-
const { ProcessorRunner } = await import("./stream-
|
|
82491
|
+
const { ProcessorRunner } = await import("./stream-D1y9GzoD.js").then((n) => n.I);
|
|
81358
82492
|
await new ProcessorRunner({
|
|
81359
82493
|
inputProcessors,
|
|
81360
82494
|
outputProcessors,
|
|
@@ -81393,7 +82527,7 @@ async function prepareForDurableExecution(options) {
|
|
|
81393
82527
|
throw inputProcessorError;
|
|
81394
82528
|
}
|
|
81395
82529
|
}
|
|
81396
|
-
let requestContextEntriesSnapshot = snapshotRequestContextEntries(requestContext);
|
|
82530
|
+
let requestContextEntriesSnapshot = snapshotRequestContextEntries(requestContext, options.onRequestContextEntryOmitted);
|
|
81397
82531
|
if (!Array.isArray(requestContextEntriesSnapshot?.["mastra__scopes"])) requestContextEntriesSnapshot = {
|
|
81398
82532
|
...requestContextEntriesSnapshot,
|
|
81399
82533
|
[MASTRA_SCOPES_KEY]: []
|
|
@@ -83274,11 +84408,7 @@ var Agent = class Agent extends MastraBase {
|
|
|
83274
84408
|
}
|
|
83275
84409
|
const durable = config.durable;
|
|
83276
84410
|
if (durable && typeof durable === "object") {
|
|
83277
|
-
const legacyKeys = [
|
|
83278
|
-
"maxSteps",
|
|
83279
|
-
"id",
|
|
83280
|
-
"name"
|
|
83281
|
-
].filter((key) => Object.hasOwn(durable, key));
|
|
84411
|
+
const legacyKeys = ["id", "name"].filter((key) => Object.hasOwn(durable, key));
|
|
83282
84412
|
if (legacyKeys.length) this.logger.warn(`Agent "${this.id}" ignores durable execution options: ${legacyKeys.join(", ")}. Use createDurableAgent({ agent, ...executionOptions }) to configure wrapper-specific options. On native Agent, durable configures resumable streams and the execution engine.`);
|
|
83283
84413
|
}
|
|
83284
84414
|
this.#scopes = config.scopes;
|
|
@@ -83776,7 +84906,7 @@ var Agent = class Agent extends MastraBase {
|
|
|
83776
84906
|
#warnInheritedExecutionOptions(options) {
|
|
83777
84907
|
if (!this.#executionEnginePolicy.inherited) return;
|
|
83778
84908
|
if (options.eagerToolExecution === true) this.#warnExecutionPolicy("eager", "Mastra-inherited execution engine policy does not support eagerToolExecution.");
|
|
83779
|
-
if (this.#executionEnginePolicy.engine === "evented" && options.stopWhen !== void 0) this.#warnExecutionPolicy("stopWhen", "Mastra-inherited evented
|
|
84909
|
+
if (this.#executionEnginePolicy.engine === "evented" && options.stopWhen !== void 0) this.#warnExecutionPolicy("stopWhen", "Mastra-inherited evented execution does not carry stopWhen to another process. Set maxSteps to bound the run across processes.");
|
|
83780
84910
|
}
|
|
83781
84911
|
#beginExecutionPolicy() {
|
|
83782
84912
|
this.#executionEnginePolicy.freeze();
|
|
@@ -84108,7 +85238,8 @@ var Agent = class Agent extends MastraBase {
|
|
|
84108
85238
|
}
|
|
84109
85239
|
processors.push(new PinnedStateProcessor({
|
|
84110
85240
|
principalsKey: (context) => knowledge.__principalsKey(context),
|
|
84111
|
-
readPins: (context) => knowledge.__deliveredPins(context)
|
|
85241
|
+
readPins: (context) => knowledge.__deliveredPins(context),
|
|
85242
|
+
...knowledge.__toolGroups
|
|
84112
85243
|
}));
|
|
84113
85244
|
}
|
|
84114
85245
|
return processors;
|
|
@@ -89457,6 +90588,17 @@ var Agent = class Agent extends MastraBase {
|
|
|
89457
90588
|
return agentThreadStreamRuntime.listActiveThreadRuns(this.getPubSub());
|
|
89458
90589
|
}
|
|
89459
90590
|
/**
|
|
90591
|
+
* The resource and thread that a `runId`-only `sendSignal`, `sendMessage` or `queueMessage`
|
|
90592
|
+
* target resolves to, or undefined when this process doesn't track the run. Servers use it to
|
|
90593
|
+
* check that a caller owns the run before sending to it. Core rejects a target whose `resourceId` doesn't own
|
|
90594
|
+
* its `runId`, but that is a consistency check, not authorization: Core doesn't know who is calling and trusts a
|
|
90595
|
+
* `runId`-only target. Callers that take `runId` from untrusted input must authenticate the caller and compare
|
|
90596
|
+
* this owner with the caller's trusted resource before sending.
|
|
90597
|
+
*/
|
|
90598
|
+
getThreadRunTarget(runId) {
|
|
90599
|
+
return agentThreadStreamRuntime.getThreadRunTarget(runId, this.getPubSub());
|
|
90600
|
+
}
|
|
90601
|
+
/**
|
|
89460
90602
|
* Lists suspended agent runs from workflow snapshot storage — runs waiting on
|
|
89461
90603
|
* a tool-call approval (`requireApproval` / `requireToolApproval`) or on a
|
|
89462
90604
|
* tool that called `suspend()`.
|
|
@@ -90805,6 +91947,7 @@ var Agent = class Agent extends MastraBase {
|
|
|
90805
91947
|
- always produce a title, even when the transcript is only a greeting or trivial exchange
|
|
90806
91948
|
- ensure it is not more than 80 characters long
|
|
90807
91949
|
- the title should be a summary of the user's message
|
|
91950
|
+
- write the title in the same language the user's messages are written in
|
|
90808
91951
|
- do not use quotes or colons
|
|
90809
91952
|
- the entire text you return will be used as the title`;
|
|
90810
91953
|
if (!instructions) return DEFAULT_TITLE_INSTRUCTIONS;
|
|
@@ -90831,10 +91974,13 @@ var Agent = class Agent extends MastraBase {
|
|
|
90831
91974
|
return this.#executionEnginePolicy.engine === "evented" ? "evented" : "default";
|
|
90832
91975
|
}
|
|
90833
91976
|
getWorkflow() {
|
|
91977
|
+
const durable = this.durable;
|
|
91978
|
+
const config = typeof durable === "object" ? durable : void 0;
|
|
90834
91979
|
return this.executionEngine.getWorkflow({
|
|
91980
|
+
maxSteps: config?.maxSteps,
|
|
90835
91981
|
workflowEngine: this.workflowEngine,
|
|
90836
|
-
storesRunsInJournal:
|
|
90837
|
-
shouldPersistSnapshot:
|
|
91982
|
+
storesRunsInJournal: config?.storageVersion === 2,
|
|
91983
|
+
shouldPersistSnapshot: config?.shouldPersistSnapshot,
|
|
90838
91984
|
logger: this.logger,
|
|
90839
91985
|
guardrailLogger: this.guardrailLogger
|
|
90840
91986
|
});
|
|
@@ -91819,8 +92965,8 @@ var Agent = class Agent extends MastraBase {
|
|
|
91819
92965
|
async #resolveDurableRunOptions(options, snapshot) {
|
|
91820
92966
|
if (options?.[RESOLVED_EXECUTION_OPTIONS]) return options;
|
|
91821
92967
|
const defaultOptions = await this.getDefaultOptions({ requestContext: options?.requestContext });
|
|
91822
|
-
this.#warnInheritedExecutionOptions(defaultOptions);
|
|
91823
92968
|
const resolvedOptions = deepMerge$1(withDefaultToolCallConcurrencyLimit(defaultOptions ?? {}, options), options ?? {});
|
|
92969
|
+
this.#warnInheritedExecutionOptions(resolvedOptions);
|
|
91824
92970
|
if (options?.actor !== void 0) resolvedOptions.actor = options.actor;
|
|
91825
92971
|
const scopedOptions = await this.#applyScopes(resolvedOptions, {
|
|
91826
92972
|
callScopes: options?.scopes,
|
|
@@ -92116,6 +93262,7 @@ var Agent = class Agent extends MastraBase {
|
|
|
92116
93262
|
optionsAreResolved: true,
|
|
92117
93263
|
resolvedDefaultOptions: options?.[RESOLVED_DEFAULT_OPTIONS],
|
|
92118
93264
|
scopesResolved: true,
|
|
93265
|
+
onRequestContextEntryOmitted: this.#executionEnginePolicy.inherited ? () => this.#warnExecutionPolicy("requestContextSnapshot", "Mastra-inherited durable execution omitted a value from the request context snapshot. Use JSON-safe values that fit in the snapshot if another process needs them.") : void 0,
|
|
92119
93266
|
mastra: this.#mastra,
|
|
92120
93267
|
methodType,
|
|
92121
93268
|
durableAgentId: this.id,
|
|
@@ -93226,7 +94373,7 @@ var Agent = class Agent extends MastraBase {
|
|
|
93226
94373
|
*
|
|
93227
94374
|
* @internal
|
|
93228
94375
|
*/
|
|
93229
|
-
async
|
|
94376
|
+
async __subscribeToRunStream(runId, options, onEvent) {
|
|
93230
94377
|
const pubsub = this.#executionStreamBus.forRun(this.__usesSharedRunLog()).pubsub;
|
|
93231
94378
|
const replayFloor = await this.#readReplayFloor(runId, options.offset);
|
|
93232
94379
|
const keepGeneration = createRunGenerationFilter(replayFloor);
|
|
@@ -95402,44 +96549,6 @@ function resolveRegisteredClassifier(mastra, classifierId, scorerId) {
|
|
|
95402
96549
|
throw new Error(`Classifier '${classifierId}' not found for scorer '${scorerId}'. Register it with Mastra classifiers or pass the classifier instance directly.`, { cause: error });
|
|
95403
96550
|
}
|
|
95404
96551
|
}
|
|
95405
|
-
// src/mastra/resolve-agent.ts
|
|
95406
|
-
/**
|
|
95407
|
-
* Resolve an agent by id the same way server handlers do: in-memory registry
|
|
95408
|
-
* first, then the editor for stored agents.
|
|
95409
|
-
*
|
|
95410
|
-
* Stored (editor) agents aren't registered on the Mastra instance until
|
|
95411
|
-
* they've been hydrated once in the current process, so a registry miss does
|
|
95412
|
-
* not mean the agent is gone — especially on a cold start. Editor hydration
|
|
95413
|
-
* via `getById` also re-registers the agent, so subsequent lookups take the
|
|
95414
|
-
* fast registry path.
|
|
95415
|
-
*
|
|
95416
|
-
* Every internal call site that needs "does this agent exist / give it to
|
|
95417
|
-
* me" semantics should go through this helper so the fallback (and the
|
|
95418
|
-
* confirmed-miss vs. transient-error distinction) can't drift between call
|
|
95419
|
-
* sites.
|
|
95420
|
-
*/
|
|
95421
|
-
async function resolveAgentById(mastra, agentId) {
|
|
95422
|
-
try {
|
|
95423
|
-
return {
|
|
95424
|
-
status: "found",
|
|
95425
|
-
agent: mastra.getAgentById(agentId)
|
|
95426
|
-
};
|
|
95427
|
-
} catch {}
|
|
95428
|
-
const editor = mastra.getEditor?.();
|
|
95429
|
-
if (!editor) return { status: "missing" };
|
|
95430
|
-
try {
|
|
95431
|
-
const agent = await editor.agent.getById(agentId);
|
|
95432
|
-
return agent ? {
|
|
95433
|
-
status: "found",
|
|
95434
|
-
agent
|
|
95435
|
-
} : { status: "missing" };
|
|
95436
|
-
} catch (error) {
|
|
95437
|
-
return {
|
|
95438
|
-
status: "error",
|
|
95439
|
-
error
|
|
95440
|
-
};
|
|
95441
|
-
}
|
|
95442
|
-
}
|
|
95443
96552
|
// src/mastra/hooks.ts
|
|
95444
96553
|
function toScorerTargetEntityType(entityType) {
|
|
95445
96554
|
switch (entityType) {
|
|
@@ -102123,7 +103232,7 @@ var AgentThreadStreamRuntime = class {
|
|
|
102123
103232
|
* `generation` only to name the owner a new acquisition takes.
|
|
102124
103233
|
*/
|
|
102125
103234
|
#threadLeaseOwner(pubsub, runId, generation) {
|
|
102126
|
-
if (this.#getPubSub(pubsub)
|
|
103235
|
+
if (!reachesOtherProcesses(this.#getPubSub(pubsub))) return threadLeaseOwner(runId);
|
|
102127
103236
|
if (generation !== void 0) return threadLeaseOwner(runId, generation);
|
|
102128
103237
|
const state = this.#getState(pubsub);
|
|
102129
103238
|
return state.leaseOwners.get(runId) ?? threadLeaseOwner(runId, state.threadRunsById.get(runId)?.generation);
|
|
@@ -102255,6 +103364,12 @@ var AgentThreadStreamRuntime = class {
|
|
|
102255
103364
|
type: "run-suspended",
|
|
102256
103365
|
runId,
|
|
102257
103366
|
streamId
|
|
103367
|
+
} : hasDurableExecution(record.agent) ? {
|
|
103368
|
+
type: "run-completed",
|
|
103369
|
+
runId,
|
|
103370
|
+
streamId,
|
|
103371
|
+
persisted: false,
|
|
103372
|
+
status: "interrupted"
|
|
102258
103373
|
} : {
|
|
102259
103374
|
type: "run-completed",
|
|
102260
103375
|
runId,
|
|
@@ -102790,14 +103905,20 @@ var AgentThreadStreamRuntime = class {
|
|
|
102790
103905
|
if (!answersTo(runId)) return;
|
|
102791
103906
|
const queues = data.preRun ? state.preRunSignalsByThread : state.pendingSignalsByThread;
|
|
102792
103907
|
if ([state.preRunSignalsByThread.get(key), state.pendingSignalsByThread.get(key)].some((queue) => queue?.some((signal) => signal.id === data.signal.id))) return;
|
|
102793
|
-
const queue = queues.get(key) ?? [];
|
|
102794
103908
|
const signal = createSignal(data.signal);
|
|
103909
|
+
if (this.#pendingUserMessageChunk(runId, signal, "pending")) this.#publish(pubsub, key, {
|
|
103910
|
+
type: "user-message-admitted",
|
|
103911
|
+
signalId: signal.id,
|
|
103912
|
+
admittedRunId: runId
|
|
103913
|
+
});
|
|
103914
|
+
const queue = queues.get(key) ?? [];
|
|
102795
103915
|
queue.push(signal);
|
|
102796
103916
|
queues.set(key, queue);
|
|
102797
103917
|
subscription.admittedSignalIds.add(data.signal.id);
|
|
102798
103918
|
this.#publishPendingUserMessage(pubsub, key, runId, signal, "pending");
|
|
102799
103919
|
this.#notifyPendingSignals(state, key, signal);
|
|
102800
|
-
} else if (data?.type === "user-message-
|
|
103920
|
+
} else if (data?.type === "user-message-admitted") this.#settleForwardedIdleSignal(state, key, data.signalId, data.admittedRunId);
|
|
103921
|
+
else if (data?.type === "user-message-presentation") {
|
|
102801
103922
|
const { chunk } = data;
|
|
102802
103923
|
if (chunk.type === "data-user-message-pending" && chunk.data.metadata?.status === "pending") this.#settleForwardedIdleSignal(state, key, chunk.data.id, chunk.runId);
|
|
102803
103924
|
} else if (data?.type === "signals-cancelled") {
|
|
@@ -102850,7 +103971,7 @@ var AgentThreadStreamRuntime = class {
|
|
|
102850
103971
|
const onEvent = (event, ack) => {
|
|
102851
103972
|
const type = event.data?.type;
|
|
102852
103973
|
const awaitingForwards = state.forwardedIdleSignalsByThread.has(key);
|
|
102853
|
-
if (type !== "signal-enqueued" && type !== "signals-cancelled" && type !== "run-abort-requested" && type !== "run-registered" && !(type === "user-message-presentation" && awaitingForwards) && !((type === "run-completed" || type === "run-failed") && (awaitingForwards || subscription.successorRunIds.has(event.data.runId) || this.#localActiveRunId(state, key) !== void 0)) && !((type === "run-aborted" || type === "run-discarded") && this.#localActiveRunId(state, key) !== void 0) && !(type === "run-discarded" && awaitingForwards)) return ack?.();
|
|
103974
|
+
if (type !== "signal-enqueued" && type !== "signals-cancelled" && type !== "run-abort-requested" && type !== "run-registered" && !((type === "user-message-presentation" || type === "user-message-admitted") && awaitingForwards) && !((type === "run-completed" || type === "run-failed") && (awaitingForwards || subscription.successorRunIds.has(event.data.runId) || this.#localActiveRunId(state, key) !== void 0)) && !((type === "run-aborted" || type === "run-discarded") && this.#localActiveRunId(state, key) !== void 0) && !(type === "run-discarded" && awaitingForwards)) return ack?.();
|
|
102854
103975
|
subscription.references++;
|
|
102855
103976
|
const handled = tail.then(() => handleEvent(event));
|
|
102856
103977
|
tail = handled.catch(() => {});
|
|
@@ -102927,6 +104048,17 @@ var AgentThreadStreamRuntime = class {
|
|
|
102927
104048
|
}
|
|
102928
104049
|
for (const key of state.threadControlSubscriptions.keys()) this.#releaseUnusedThreadControlSubscription(state, key);
|
|
102929
104050
|
}
|
|
104051
|
+
/**
|
|
104052
|
+
* A `runId` target that also names a `resourceId` must name the run's own resource. Without this, the signal
|
|
104053
|
+
* would be created for the caller's resource and delivered into another resource's run. Core cannot know who the
|
|
104054
|
+
* caller is: a target naming only a `runId` is trusted, so callers exposing `runId` targets to untrusted input
|
|
104055
|
+
* must pass the caller's `resourceId` or check ownership with `getThreadRunTarget()` first.
|
|
104056
|
+
*/
|
|
104057
|
+
#assertRunTargetOwner(state, target) {
|
|
104058
|
+
if (!target.runId || !target.resourceId) return;
|
|
104059
|
+
const owner = state.threadRunsById.get(target.runId)?.resourceId;
|
|
104060
|
+
if (owner && owner !== target.resourceId) throw new Error(`Agent run ${target.runId} belongs to a different resource`);
|
|
104061
|
+
}
|
|
102930
104062
|
#threadKey(resourceId, threadId) {
|
|
102931
104063
|
return agentThreadStreamKey(resourceId, threadId);
|
|
102932
104064
|
}
|
|
@@ -103823,7 +104955,7 @@ var AgentThreadStreamRuntime = class {
|
|
|
103823
104955
|
const topic = this.#threadTopic(key);
|
|
103824
104956
|
await resolvedPubSub.publish(topic, {
|
|
103825
104957
|
type: event.type,
|
|
103826
|
-
runId: "runId" in event ? event.runId : key,
|
|
104958
|
+
runId: ("runId" in event ? event.runId : void 0) ?? key,
|
|
103827
104959
|
data: event
|
|
103828
104960
|
});
|
|
103829
104961
|
}
|
|
@@ -104430,6 +105562,14 @@ var AgentThreadStreamRuntime = class {
|
|
|
104430
105562
|
hasThreadRun(runId, pubsub) {
|
|
104431
105563
|
return this.#getState(pubsub).threadRunsById.has(runId);
|
|
104432
105564
|
}
|
|
105565
|
+
/** The resource and thread a `runId`-only signal or message target resolves to in this process. */
|
|
105566
|
+
getThreadRunTarget(runId, pubsub) {
|
|
105567
|
+
const record = this.#getState(pubsub).threadRunsById.get(runId);
|
|
105568
|
+
return record ? {
|
|
105569
|
+
resourceId: record.resourceId,
|
|
105570
|
+
threadId: record.threadId
|
|
105571
|
+
} : void 0;
|
|
105572
|
+
}
|
|
104433
105573
|
/** Whether the run's original stream is still live and carries its resumed segments. */
|
|
104434
105574
|
hasRunContinuation(runId, pubsub) {
|
|
104435
105575
|
return this.#getState(pubsub).threadRunsById.get(runId)?.continuation?.canContinue() === true;
|
|
@@ -104662,6 +105802,7 @@ var AgentThreadStreamRuntime = class {
|
|
|
104662
105802
|
const chunk = this.#pendingUserMessageChunk(runId, signal, status);
|
|
104663
105803
|
if (chunk) this.#publish(pubsub, key, {
|
|
104664
105804
|
type: "user-message-presentation",
|
|
105805
|
+
runId,
|
|
104665
105806
|
chunk
|
|
104666
105807
|
});
|
|
104667
105808
|
}
|
|
@@ -105779,6 +106920,7 @@ var AgentThreadStreamRuntime = class {
|
|
|
105779
106920
|
const statuses = [];
|
|
105780
106921
|
const settledRunIds = /* @__PURE__ */ new Map();
|
|
105781
106922
|
const reportedSuspensions = /* @__PURE__ */ new Set();
|
|
106923
|
+
const reportedInterruptions = /* @__PURE__ */ new Set();
|
|
105782
106924
|
const presentations = [];
|
|
105783
106925
|
const presentedSignalIds = /* @__PURE__ */ new Set();
|
|
105784
106926
|
const settledSignalIds = /* @__PURE__ */ new Set();
|
|
@@ -105800,6 +106942,9 @@ var AgentThreadStreamRuntime = class {
|
|
|
105800
106942
|
if (status === "suspended") {
|
|
105801
106943
|
if (reportedSuspensions.has(streamId)) return;
|
|
105802
106944
|
reportedSuspensions.add(streamId);
|
|
106945
|
+
} else if (status === "interrupted") {
|
|
106946
|
+
if (reportedInterruptions.has(streamId)) return;
|
|
106947
|
+
reportedInterruptions.add(streamId);
|
|
105803
106948
|
} else settledRunIds.set(runId, streamId);
|
|
105804
106949
|
if (!options.withRunStatus) return;
|
|
105805
106950
|
statuses.push({
|
|
@@ -106284,7 +107429,7 @@ var AgentThreadStreamRuntime = class {
|
|
|
106284
107429
|
if (data.type !== "run-suspended") parkedPromptRunIds.delete(data.runId);
|
|
106285
107430
|
if (data.type === "run-completed") await this.#drainPendingIdleSignals(state, resolvedPubSub, key, data.runId);
|
|
106286
107431
|
if (data.type !== "run-suspended" || !suspendedRunEnded) {
|
|
106287
|
-
const status = data.type === "run-aborted" ? "aborted" : data.type === "run-suspended" || data.status === "suspended" ? "suspended" : data.status === "canceled" ? "aborted" : data.status === "success" || data.status === void 0 && data.persisted !== false ? "success" : "failed";
|
|
107432
|
+
const status = data.type === "run-aborted" ? "aborted" : data.type === "run-suspended" || data.status === "suspended" ? "suspended" : data.status === "canceled" ? "aborted" : data.status === "interrupted" ? "interrupted" : data.status === "success" || data.status === void 0 && data.persisted !== false ? "success" : "failed";
|
|
106288
107433
|
enqueueStatus(data.runId, eventStreamId, status);
|
|
106289
107434
|
}
|
|
106290
107435
|
wake();
|
|
@@ -106770,6 +107915,7 @@ var AgentThreadStreamRuntime = class {
|
|
|
106770
107915
|
activeRecord ??= state.threadRunsById.get(runId);
|
|
106771
107916
|
if (activeRecord) key ??= this.#threadKey(activeRecord.resourceId, activeRecord.threadId);
|
|
106772
107917
|
}
|
|
107918
|
+
this.#assertRunTargetOwner(state, target);
|
|
106773
107919
|
const resourceId = target.resourceId ?? activeRecord?.resourceId;
|
|
106774
107920
|
const threadId = target.threadId ?? activeRecord?.threadId;
|
|
106775
107921
|
if (!resourceId || !threadId) throw new Error("resourceId and threadId are required to queue a message");
|
|
@@ -106929,6 +108075,7 @@ var AgentThreadStreamRuntime = class {
|
|
|
106929
108075
|
activeRecord ??= state.threadRunsById.get(runId);
|
|
106930
108076
|
if (activeRecord) key ??= this.#threadKey(activeRecord.resourceId, activeRecord.threadId);
|
|
106931
108077
|
}
|
|
108078
|
+
this.#assertRunTargetOwner(state, target);
|
|
106932
108079
|
const resourceId = target.resourceId ?? activeRecord?.resourceId;
|
|
106933
108080
|
const threadId = target.threadId ?? activeRecord?.threadId;
|
|
106934
108081
|
if (!resourceId || !threadId) throw new Error("No active agent run found for signal target");
|
|
@@ -107630,7 +108777,7 @@ function getActiveDurableAgentWorkflowExecutions(mastra) {
|
|
|
107630
108777
|
* execution behind a broker, which another process may be executing.
|
|
107631
108778
|
*/
|
|
107632
108779
|
function detachesOnShutdown(mastra, entry) {
|
|
107633
|
-
return !!entry.eventedExecution &&
|
|
108780
|
+
return !!entry.eventedExecution && reachesOtherProcesses(mastra.pubsub);
|
|
107634
108781
|
}
|
|
107635
108782
|
function isDurableAgentExecutionDetached(mastra, runId) {
|
|
107636
108783
|
const entry = globalRunRegistry.has(runId) ? globalRunRegistry.get(runId) : void 0;
|
|
@@ -107806,4 +108953,4 @@ var ExtendedRunRegistry = class extends RunRegistry {
|
|
|
107806
108953
|
this.#memoryInfo.clear();
|
|
107807
108954
|
}
|
|
107808
108955
|
};
|
|
107809
|
-
export { createDurableBackgroundTaskCheckStep as $, planTraceQuery as $a, validateStepInput as $c, resolveRetentionTargets as $i, assertKnowledgeCeilingRaised as $n, normalizeMessageHistoryConfig as $o, KnowledgeMoveTooLargeError as $r, EventedExecutionEngine as $s, knowledgeDeliveredPins as $t, agentInstructions as A, threadQueryResponseSchema as Aa, RESUME_SNAPSHOT_POLL_INTERVAL_MS as Ac, inspectKnowledgeSchema as Ai, ToolInvocationPartSchema as Al, ChatChannelProcessor as An, createBackgroundWorkSignalProcessor as Ao, ScoresInMemory as Ar, StepExecutor as As, readRunDeadline as At, createDurableAgenticWorkflow as B, parseSpanQueryRequest as Ba, defineStateAccessors as Bc, assertSupportedPatterns as Bi, runFencingNotSupportedError as Bl, toChatLogger as Bn, ToolSearchProcessor as Bo, notificationSignalAttributes as Br, emitFinishEvent as Bs, formatCompletionFeedback as Bt, MastraScorer as C, tracePageResponseSchema as Ca, createConcurrencyLimiter as Cc, KnowledgeConflictError as Ci, ProcessorStepInputSchema as Cl, decodeKnowledgeScopeId as Cn, MastraMemory as Co, createEmptyWorkflowSnapshot as Cr, EventedRun as Cs, runDurableStreamUntilIdle as Ct, isNotScorable as D, planThreadRowsQuery as Da, createStepFromAgent$1 as Dc, KnowledgeUnsupportedCapabilityError as Di, SourcePartSchema as Dl, resolveWaitUntil as Dn, isSystemReminderMessage as Do, WorkflowDefinitionsStorage as Dr, createStep as Ds, DurableStepIds as Dt, filterRun as E, encodeThreadQueryCursor as Ea, createMappingStep as Ec, KnowledgeStorage as Ei, ReasoningPartSchema as El, AgentChannels as En, filterSystemReminderMessages as Eo, InMemoryWorkflowDefinitionsStorage as Er, cloneWorkflow$1 as Es, DurableAgentDefaults as Et, normalizeResumeGenerateArgs as F, SPAN_QUERY_MAX_PREVIEW_CHARACTERS as Fa, cleanStepResult as Fc, ExperimentsStorage as Fi, coverNestedRun as Fl, DEFAULT_CHANNEL_TOOLS_SETTINGS as Fn, buildResponseCacheKey as Fo, InMemoryNotificationsStorage as Fr, __resetExecutionFencesForTests as Fs, pruneAgentLoopSnapshot as Ft, createWorkflowInput as G, spanQueryIdentitySchema as Ga, hydrateSerializedStepErrors as Gc, SchemaValidationError as Gi, WorkingMemory as Gn, TokenCostControl as Go, readNotificationRoutingRequirement as Gr, publishAbortRequest as Gs, runChecks as Gt, createDurableIsTaskCompleteStep as H, resolveSpanQueryCost as Ha, getResumeLabelsByStepId as Hc, getSchemaValidator as Hi, setRunFenceContext as Hl, MemoryInputFilter as Hn, ToolCallFilter as Ho, notificationSummaryContents as Hr, emitStepStartEvent as Hs, formatValidationFeedback as Ht, prepareForDurableExecution as I, SPAN_QUERY_ORDER_FIELDS as Ia, createDeprecationProxy as Ic, DatasetsInMemory as Ii, currentRunGeneration as Il, channelToolScopeResolver as In, WorkspaceInstructionsProcessor as Io, NotificationsStorage as Ir, diffResponseMessages as Is, DEFAULT_TOOL_DECLINE_REASON as It, serializeModelConfig as J, spanQueryRowSchema as Ja, omitPriorCompletionFields as Jc, InMemoryBlobStore as Ji, getMemoryRunState as Jn, groupLinkedToolMessages as Jo, resolveDeliveryFailureUpdate as Jr, createRunAbortController as Js, runStreamCompletionScorers as Jt, serializeDurableOptions as K, spanQueryRequestSchema as Ka, isEntryFinished as Kc, InMemoryChannelsStorage as Ki, MessageHistory as Kn, SystemPromptScrubber as Ko, MAX_NOTIFICATION_DELIVERY_ATTEMPTS as Kr, requestAcknowledgedAbort as Ks, runCompletionScorers as Kt, applyReservedMemoryContextKeys as L, buildSpanQueryResponse as La, createRestartExecutionParams as Lc, DatasetsStorage as Li, isRunFenceConflictError as Ll, createChannelToolScope as Ln, SkillSearchProcessor as Lo, dispatchDueNotifications as Lr, emitAbortEvent as Ls, resolveDeclineReason as Lt, MAX_FS_SUBAGENT_DEPTH as M, SPAN_QUERY_MAX_COST_METRICS as Ma, abortableSleep as Mc, InMemoryHarness as Mi, RUN_FENCE_CONFLICT_ERROR_ID as Ml, renderBuiltInToolEvent as Mn, DEFAULT_RESPONSE_CACHE_TTL_SECONDS as Mo, InMemorySchedulesStorage as Mr, WorkflowStepConflictError as Ms, getRunStreamSlot as Mt, AGENT_RESUME_CLAIM_STALE_MS as N, SPAN_QUERY_MAX_CURSOR_BYTES as Na, applyStateDelta as Nc, HarnessStorage as Ni, RUN_FENCING_NOT_SUPPORTED_ERROR_ID as Nl, formatToolApproval as Nn, RESPONSE_CACHE_CONTEXT_KEY as No, SchedulesStorage as Nr, assertWorkflowStepGuard as Ns, getScopeStreamSlot as Nt, notScorable as O, threadQueryIdentitySchema as Oa, createStepFromClassifier as Oc, assertKnowledgeSchemaCompatible as Oi, StepStartPartSchema as Ol, defaultTypingStatus as On, augmentWithInit as Oo, InMemoryToolProviderConnectionsStorage as Or, createWorkflow$1 as Os, RUN_DEADLINE_KEY as Ot, Agent as P, SPAN_QUERY_MAX_LIMIT as Pa, assertTimeTravelGraphMatchesSnapshot as Pc, ExperimentsInMemory as Pi, RunFenceConflictError as Pl, ChannelSessionRejectedError as Pn, ResponseCache as Po, normalizeScheduleTarget as Pr, isWorkflowStepConflictError as Ps, untilIdleHandlesBackgroundTask as Pt, isSpanChunk as Q, planThreadQuery as Qa, setLongTimeout as Qc, executeRetentionPrune as Qi, MAX_KNOWLEDGE_SCOPE_TAGS as Qn, isAfterMemoryTokenBoundary as Qo, InMemoryKnowledgeStorage as Qr, AgentStreamEventTypes as Qs, PINNED_READ_MEMO_KEY as Qt, persistDurableRunInput as R, createSpanQueryPreview as Ra, createTimeTravelExecutionParams as Rc, DatasetItemIdentityConflictError as Ri, matchesRunFence as Rl, createChannelTools as Rn, SkillsProcessor as Ro, createNotificationSignal as Rr, emitChunkEvent as Rs, getServerSideFallbackInfo as Rt, createClassifierScorer as S, tracePageRequestSchema as Sa, ExecutionEngine as Sc, KNOWLEDGE_STORAGE_SCHEMA_VERSION as Si, ProcessorOutputStreamPhaseSchema as Sl, strongerKnowledgeRole as Sn, upsertMessageVectors as So, WorkflowsStorage as Sr, createWorkflow as Ss, createDurableAgentStream as St, createScorer as T, THREAD_QUERY_MAX_LIMIT as Ta, runWithConcurrency as Tc, KnowledgeSchemaResetRequiredError as Ti, ProcessorStepSchema as Tl, buildKnowledgeInstructions as Tn, memoryDefaultOptions as To, mergeWorkflowStepResult as Tr, cloneStep as Ts, DURABLE_STOP_WHEN_ERROR_ID as Tt, createDurableLLMMappingStep as U, spanQueryCostSchema as Ua, getSingleStepEntryId as Uc, UnsupportedSchemaPatternError as Ui, SemanticRecall as Un, RegexFilterProcessor as Uo, notificationSummarySignalMetadata as Ur, emitSuspendedEvent as Us, generateFinalResult as Ut, createDurableGoalStep as V, planSpanQuery as Va, getRestartStartIndex as Vc, createValidator as Vi, runOutsideRunFenceScope as Vl, BaseProcessor as Vn, AgentsMDInjector as Vo, notificationSignalMetadata as Vr, emitStepFinishEvent as Vs, formatStreamCompletionFeedback as Vt, createDurableToolCallStep as W, spanQueryIdentityKey as Wa, getStepIds as Wc, SchemaUpdateValidationError as Wi, globalEmbeddingCache as Wn, CostGuardProcessor as Wo, summarizeNotifications as Wr, AgentStreamBus as Ws, generateStructuredFinalResult as Wt, createDurableLLMExecutionStep as X, encodeTraceQueryDeltaCursor as Xa, resolveForeachConcurrency as Xc, BackgroundTasksInMemory as Xi, MAX_KNOWLEDGE_NODE_DESCRIPTION_LENGTH as Xn, advanceMemoryTokenBoundary as Xo, InMemoryMemory as Xr, AGENT_STREAM_TOPIC as Xs, loop as Xt, serializeToolsMetadata as Y, encodeTraceQueryCursor as Ya, omitPriorSuspensionFields as Yc, BlobStore as Yi, MockMemory as Yn, loadMessageHistory as Yo, resolveNotificationDeliveryDecision as Yr, AGENT_CONTROL_TOPIC as Ys, runValidation as Yt, MessagePartSpans as Z, getTraceQueryDeltaWatermark as Za, runCountDeprecationMessage as Zc, BackgroundTasksStorage as Zi, MAX_KNOWLEDGE_RECORD_TEXT_LENGTH as Zn, getMemoryTokenBoundary as Zo, MemoryStorage as Zr, AgentControlEventTypes as Zs, validateModelTimeoutSettings as Zt, runEvals as _, validateStorageMetadataFilter as _a, repeatAfterSettled as _c, knowledgePinDepth as _i, ProcessorInputStepPhaseSchema as _l, KnowledgeDeclarationError as _n, buildMessageEmbeddingRows as _o, FilesystemDB as _r, isRetryableOpenAIResponsesStreamError as _s, resolveTool$1 as _t, endRunSpansWithError as a, ensureDate as aa, createStep$1 as ac, MAX_KNOWLEDGE_PAGE_BODY_LINKS as ai, getEntryId as al, removeKnowledgeNote as an, buildUpdateSpanRecord as ao, expandKnowledgeScope as ar, PIIDetector as as, baseDurableAgenticInputSchema as at, validateAndSaveScore as b, tracePageIdSchema as ba, evaluateScoringPredicate as bc, parseKnowledgePageRef as bi, ProcessorOutputResultPhaseSchema as bl, knowledgeRunScopes as bn, messageVectorId as bo, WorkflowsInMemory as br, cloneWorkflow as bs, liveSegmentSpan as bt, globalRunRegistry as c, getSqlType as ca, predicateToCondition as cc, MAX_KNOWLEDGE_PAGE_LINKS as ci, waitMs as cl, upsertKnowledgePage as cn, serializeSpanAttributes as co, knowledgeSemanticDocumentId as cr, UnicodeNormalizer as cs, modelConfigSchema as ct, takeRunScorerInstances as d, parseDuration as da, createNestedRunParentStatusLookup as dc, MAX_KNOWLEDGE_PIN_LIST_DEPTH as di, isDurableAgentLike as dl, refreshKnowledgeLinksTo as dn, ObservabilityStorage as do, parseKnowledgeNodeCursor as dr, isMalformedFunctionCallError as ds, runDurableFinishSideEffects as dt, retentionCutoffMs as ea, getNestedWorkflow as ec, KnowledgePageDepthError as ei, validateStepRequestContext as el, buildKnowledgePageTools as en, buildCreateSpanRecord as eo, assertKnowledgeDescriptionWithinBound as er, BatchPartsProcessor as es, resolveDurableToolCallConcurrency as et, AgentThreadLeaseLostError as f, safelyParseJSON as fa, nestedRunParentOf as fc, assertKnowledgeNoteTextWithinBound as fi, FilePartSchema as fl, reindexKnowledgeLinks as fn, FactoryStorage as fo, StoreOperationsInMemory as fr, UnsupportedFileHandler as fs, loadRunStoredMessages as ft, describeNonSuccessFinishReason as g, transformScoreRow as ga, renewWorkflowLease as gc, knowledgePagePath as gi, ProcessorInputPhaseSchema as gl, knowledgeRoleOn as gn, MESSAGE_EMBEDDING_CHARS_PER_TOKEN as go, FilesystemStore as gr, isBadRequestError as gs, resolveRuntimeDependencies as gt, AGENTIC_LOOP_WORKFLOW_ID as h, transformRow as ha, WORKFLOW_RUN_LEASE_TTL_MS as hc, knowledgeLinkRefKey as hi, MessagePartSchema as hl, knowledgeReadScopeFor as hn, DEFAULT_MESSAGE_EMBEDDING_MAX_CHUNK_CHARS as ho, createGitHubSourceControlProviderFromEnv as hr, StreamErrorRetryProcessor as hs, resolveModel as ht, deleteRunRegistryEntry as i, createVectorErrorId as ia, cloneStep$1 as ic, MAX_KNOWLEDGE_NOTE_TOKENS as ii, waitForSuspendedSnapshot as il, moveKnowledgePage as in, buildScoreRecord as io, createKnowledgeNodeCursor as ir, LanguageDetector as is, accumulatedUsageSchema as it, assembleAgentFromFsEntry as j, threadQueryRowSchema as ja, RESUME_SNAPSHOT_WAIT_STATUSES as jc, parseKnowledgeWikilinks as ji, isAgentCompatible as jl, CHAT_CHANNEL_RENDER_CONTEXT_KEY as jn, CyberRefusalHandler as jo, ScoresStorage as jr, computeScheduleDefinitionHash as js, __registerMastraCtor as jt, agentConfig as k, threadQueryRequestSchema as ka, createStepFromTool as kc, createKnowledgeUlid as ki, TextPartSchema as kl, MastraStateAdapter as kn, getStorageSource as ko, ToolProviderConnectionsStorage as kr, WorkflowEventProcessor as ks, ensureRemoteAbortListener as kt, isDurableAgentExecutionDetached as l, hasErrorCode as la, evaluatePredicate as lc, MAX_KNOWLEDGE_PAGE_LINK_REF_LENGTH as li, workflowTermination as ll, KnowledgeSemanticIndex as ln, toEntityType as lo, knowledgeSemanticIdempotencyKey as lr, STABILITY_ERROR_PROCESSOR_IDS as ls, modelListEntrySchema as lt, AGENTIC_EXECUTION_WORKFLOW_ID as m, storageMessageMatchesMetadataFilter as ma, nestedRunStatusOf as mc, canonicalKnowledgeName as mi, MessageContentSchema as ml, knowledgeAccessGrants as mn, UniqueViolationError as mo, GitHubSourceControlProvider as mr, FILE_UPLOAD_ERROR_CODES as ms, resolveInternalState as mt, RunRegistry as n, createStorageErrorId as na, Run as nc, KnowledgePageKeyConflictError as ni, validateStepStateData as nl, knowledgeRunPrincipals as nn, buildLogRecord as no, assertKnowledgeScopeWithinCeiling as nr, ClassifierProcessor as ns, calculateAccumulatedUsage as nt, getActiveDurableAgentWorkflowExecutions as o, filterByDateRange as oa, isProcessor$1 as oc, MAX_KNOWLEDGE_PAGE_DEPTH as oi, getEntryWorkflow as ol, removeKnowledgePage as on, getObjectOrNull as oo, isKnowledgeScopeVisible as or, PromptInjectionDetector as os, baseIterationStateSchema as ot, agentThreadStreamRuntime as p, serializeDate as pa, nestedRunRecoveryAction as pc, assertKnowledgePageDescriptionWithinBound as pi, ImagePartSchema as pl, updateKnowledgeLinks as pn, FactoryStorageDomain as po, StoreOperations as pr, FileUploadProcessor as ps, rebuildRunToolsFromMastra as pt, serializeDurableState as q, spanQueryResponseSchema as qa, isSingleStepEntry as qc, ChannelsStorage as qi, MemoryRunState as qn, TokenLimiterProcessor as qo, defaultNotificationDeliveryDecision as qr, subscribeToAbortRequests as qs, runDefaultCompletionCheck as qt, abandonDurableAgentExecutions as r, createStoreErrorId as ra, Workflow as rc, MAX_KNOWLEDGE_MOVE_PAGES as ri, validateStepSuspendData as rl, addKnowledgeNote as rn, buildMetricRecord as ro, canonicalizeKnowledgeScope as rr, StructuredOutputProcessor as rs, createBaseIterationStateUpdate as rt, getRunRegistryEntry as s, getDefaultValue as sa, mapVariable as sc, MAX_KNOWLEDGE_PAGE_DESCRIPTION_TOKENS as si, assertDrainTimeout as sl, updateKnowledgeNote as sn, getStringOrNull as so, knowledgeScopeKey as sr, ModerationProcessor as ss, durableAgenticOutputSchema as st, ExtendedRunRegistry as t, runRetentionBatches as ta, getStepEntry as tc, KnowledgePageHasChildrenError as ti, validateStepResumeData as tl, KnowledgeRun as tn, buildFeedbackRecord as to, assertKnowledgeRecordTextWithinBound as tr, ModelSelectionProcessor as ts, buildStepRecord as tt, setRunRegistryEntry as u, jsonValueEquals as ua, cancelNestedRun as uc, MAX_KNOWLEDGE_PAGE_LIST_LIMIT as ui, hasResumableStreams as ul, embed$2 as un, ObservabilityInMemory as uo, knowledgeVisibleScopeKeys as ur, defaultStabilityErrorProcessors as us, executeDurableAgentScorers as ut, flushBeforeTraceRead as v, TracePageError as va, DefaultExecutionEngine as vc, knowledgePositionBetween as vi, ProcessorMessageContentSchema as vl, compileKnowledgeScopes as vn, chunkMessageText as vo, InMemoryStore as vr, PrefillErrorHandler as vs, toolRequiresApproval as vt, ScorerRunError as w, THREAD_QUERY_DEFAULT_LIMIT as wa, normalizeConcurrency as wc, KnowledgeNotFoundError$1 as wi, ProcessorStepOutputSchema as wl, encodeKnowledgeScopeId as wn, MemoryProcessor as wo, mergeStepResult as wr, EventedWorkflow as ws, runResumeDurableStreamUntilIdle as wt, resolveAgentById as x, tracePageNodeSchema as xa, validateScoringPredicate as xc, KNOWLEDGE_STORAGE_CONTRACT_VERSION as xi, ProcessorOutputStepPhaseSchema as xl, knowledgeScopeAddress as xn, resolveMaxChunkChars as xo, cloneRunData as xr, createEventedWorkflow as xs, segmentSpanData as xt, createOnScorerHook as y, readTracePage as ya, SCORING_PREDICATE_ROOTS as yc, knowledgeScopeReadable as yi, ProcessorMessageSchema as yl, knowledgeMemoryScopes as yn, extractMessageEmbeddingText as yo, MockStore as yr, getGoalActivityDurationMs as ys, carrySegmentSpans as yt, detachFullStreamOnEnd as z, encodeSpanQueryCursor as za, defineLazyWriter as zc, SchemaValidator as zi, resolveRunFence as zl, resolveChannelToolsSettings as zn, formatSkillsCatalog as zo, createNotificationSummarySignal as zr, emitErrorEvent as zs, formatCheckFeedback as zt };
|
|
108956
|
+
export { resolveDurableToolCallConcurrency as $, spanQueryIdentitySchema as $a, hydrateSerializedStepErrors as $c, SchemaValidationError as $i, MAX_KNOWLEDGE_NODE_DESCRIPTION_LENGTH as $n, TokenCostControl as $o, InMemoryMemory as $r, publishAbortRequest as $s, knowledgeDeliveredPins as $t, assembleAgentFromFsEntry as A, tracePageRequestSchema as Aa, ExecutionEngine as Ac, assertKnowledgeNoteTextWithinBound as Ai, ProcessorOutputStepPhaseSchema as Al, resolveWaitUntil as An, upsertMessageVectors as Ao, WorkflowDefinitionsStorage as Ar, createWorkflow as As, readRunDeadline as At, createDurableGoalStep as B, SPAN_QUERY_MAX_COST_METRICS as Ba, abortableSleep as Bc, InMemoryHarness as Bi, isAgentCompatible as Bl, createChannelToolScope as Bn, DEFAULT_RESPONSE_CACHE_TTL_SECONDS as Bo, dispatchDueNotifications as Br, WorkflowStepConflictError as Bs, formatCompletionFeedback as Bt, ScorerRunError as C, transformRow as Ca, WORKFLOW_RUN_LEASE_TTL_MS as Cc, MAX_KNOWLEDGE_PAGE_BODY_LINKS as Ci, MessageContentSchema as Cl, knowledgeRunScopes as Cn, DEFAULT_MESSAGE_EMBEDDING_MAX_CHUNK_CHARS as Co, WorkflowsInMemory as Cr, StreamErrorRetryProcessor as Cs, runDurableStreamUntilIdle as Ct, notScorable as D, readTracePage as Da, SCORING_PREDICATE_ROOTS as Dc, MAX_KNOWLEDGE_PAGE_LINK_REF_LENGTH as Di, ProcessorMessageContentSchema as Dl, encodeKnowledgeScopeId as Dn, extractMessageEmbeddingText as Do, mergeStepResult as Dr, getGoalActivityDurationMs as Ds, DurableStepIds as Dt, isNotScorable as E, TracePageError as Ea, DefaultExecutionEngine as Ec, MAX_KNOWLEDGE_PAGE_LINKS as Ei, ProcessorInputStepPhaseSchema as El, decodeKnowledgeScopeId as En, chunkMessageText as Eo, createEmptyWorkflowSnapshot as Er, PrefillErrorHandler as Es, DurableAgentDefaults as Et, prepareForDurableExecution as F, planThreadRowsQuery as Fa, createStepFromAgent$1 as Fc, knowledgePinDepth as Fi, ReasoningPartSchema as Fl, renderBuiltInToolEvent as Fn, isSystemReminderMessage as Fo, InMemorySchedulesStorage as Fr, createStep as Fs, pruneAgentLoopSnapshot as Ft, serializeDurableOptions as G, buildSpanQueryResponse as Ga, createRestartExecutionParams as Gc, DatasetsStorage as Gi, currentRunGeneration as Gl, MemoryInputFilter as Gn, SkillSearchProcessor as Go, notificationSummaryContents as Gr, emitAbortEvent as Gs, runChecks as Gt, createDurableLLMMappingStep as H, SPAN_QUERY_MAX_LIMIT as Ha, assertTimeTravelGraphMatchesSnapshot as Hc, ExperimentsInMemory as Hi, RUN_FENCING_NOT_SUPPORTED_ERROR_ID as Hl, resolveChannelToolsSettings as Hn, ResponseCache as Ho, createNotificationSummarySignal as Hr, isWorkflowStepConflictError as Hs, formatValidationFeedback as Ht, applyReservedMemoryContextKeys as I, threadQueryIdentitySchema as Ia, createStepFromClassifier as Ic, knowledgePositionBetween as Ii, SourcePartSchema as Il, formatToolApproval as In, augmentWithInit as Io, SchedulesStorage as Ir, createWorkflow$1 as Is, DEFAULT_TOOL_DECLINE_REASON as It, serializeToolsMetadata as J, parseSpanQueryRequest as Ja, defineStateAccessors as Jc, assertSupportedPatterns as Ji, resolveRunFence as Jl, WorkingMemory as Jn, ToolSearchProcessor as Jo, readNotificationRoutingRequirement as Jr, emitFinishEvent as Js, runStreamCompletionScorers as Jt, serializeDurableState as K, createSpanQueryPreview as Ka, createTimeTravelExecutionParams as Kc, DatasetItemIdentityConflictError as Ki, isRunFenceConflictError as Kl, SemanticRecall as Kn, SkillsProcessor as Ko, notificationSummarySignalMetadata as Kr, emitChunkEvent as Ks, runCompletionScorers as Kt, persistDurableRunInput as L, threadQueryRequestSchema as La, createStepFromTool as Lc, knowledgeScopeReadable as Li, StepStartPartSchema as Ll, ChannelSessionRejectedError as Ln, getStorageSource as Lo, normalizeScheduleTarget as Lr, WorkflowEventProcessor as Ls, resolveDeclineReason as Lt, AGENT_RESUME_CLAIM_STALE_MS as M, THREAD_QUERY_DEFAULT_LIMIT as Ma, normalizeConcurrency as Mc, canonicalKnowledgeName as Mi, ProcessorStepInputSchema as Ml, MastraStateAdapter as Mn, MemoryProcessor as Mo, ToolProviderConnectionsStorage as Mr, EventedWorkflow as Ms, getRunStreamSlot as Mt, Agent as N, THREAD_QUERY_MAX_LIMIT as Na, runWithConcurrency as Nc, knowledgeLinkRefKey as Ni, ProcessorStepOutputSchema as Nl, ChatChannelProcessor as Nn, memoryDefaultOptions as No, ScoresInMemory as Nr, cloneStep as Ns, getScopeStreamSlot as Nt, agentConfig as O, tracePageIdSchema as Oa, evaluateScoringPredicate as Oc, MAX_KNOWLEDGE_PAGE_LIST_LIMIT as Oi, ProcessorMessageSchema as Ol, buildKnowledgeInstructions as On, messageVectorId as Oo, mergeWorkflowStepResult as Or, cloneWorkflow as Os, RUN_DEADLINE_KEY as Ot, normalizeResumeGenerateArgs as P, encodeThreadQueryCursor as Pa, createMappingStep as Pc, knowledgePagePath as Pi, ProcessorStepSchema as Pl, CHAT_CHANNEL_RENDER_CONTEXT_KEY as Pn, filterSystemReminderMessages as Po, ScoresStorage as Pr, cloneWorkflow$1 as Ps, untilIdleHandlesBackgroundTask as Pt, createDurableBackgroundTaskCheckStep as Q, spanQueryIdentityKey as Qa, getStepIds as Qc, SchemaUpdateValidationError as Qi, MockMemory as Qn, CostGuardProcessor as Qo, resolveNotificationDeliveryDecision as Qr, AgentStreamBus as Qs, PINNED_READ_MEMO_KEY as Qt, detachFullStreamOnEnd as R, threadQueryResponseSchema as Ra, RESUME_SNAPSHOT_POLL_INTERVAL_MS as Rc, parseKnowledgePageRef as Ri, TextPartSchema as Rl, DEFAULT_CHANNEL_TOOLS_SETTINGS as Rn, createBackgroundWorkSignalProcessor as Ro, InMemoryNotificationsStorage as Rr, StepExecutor as Rs, getServerSideFallbackInfo as Rt, MastraScorer as S, storageMessageMatchesMetadataFilter as Sa, nestedRunStatusOf as Sc, MAX_KNOWLEDGE_NOTE_TOKENS as Si, ImagePartSchema as Sl, knowledgeMemoryScopes as Sn, UniqueViolationError as So, MockStore as Sr, FILE_UPLOAD_ERROR_CODES as Ss, createDurableAgentStream as St, filterRun as T, validateStorageMetadataFilter as Ta, repeatAfterSettled as Tc, MAX_KNOWLEDGE_PAGE_DESCRIPTION_TOKENS as Ti, ProcessorInputPhaseSchema as Tl, strongerKnowledgeRole as Tn, buildMessageEmbeddingRows as To, WorkflowsStorage as Tr, isRetryableOpenAIResponsesStreamError as Ts, DURABLE_STOP_WHEN_ERROR_ID as Tt, createDurableToolCallStep as U, SPAN_QUERY_MAX_PREVIEW_CHARACTERS as Ua, cleanStepResult as Uc, ExperimentsStorage as Ui, RunFenceConflictError as Ul, toChatLogger as Un, buildResponseCacheKey as Uo, notificationSignalAttributes as Ur, __resetExecutionFencesForTests as Us, generateFinalResult as Ut, createDurableIsTaskCompleteStep as V, SPAN_QUERY_MAX_CURSOR_BYTES as Va, applyStateDelta as Vc, HarnessStorage as Vi, RUN_FENCE_CONFLICT_ERROR_ID as Vl, createChannelTools as Vn, RESPONSE_CACHE_CONTEXT_KEY as Vo, createNotificationSignal as Vr, assertWorkflowStepGuard as Vs, formatStreamCompletionFeedback as Vt, createWorkflowInput as W, SPAN_QUERY_ORDER_FIELDS as Wa, createDeprecationProxy as Wc, DatasetsInMemory as Wi, coverNestedRun as Wl, BaseProcessor as Wn, WorkspaceInstructionsProcessor as Wo, notificationSignalMetadata as Wr, diffResponseMessages as Ws, generateStructuredFinalResult as Wt, MessagePartSpans as X, resolveSpanQueryCost as Xa, getResumeLabelsByStepId as Xc, getSchemaValidator as Xi, runOutsideRunFenceScope as Xl, MemoryRunState as Xn, ToolCallFilter as Xo, defaultNotificationDeliveryDecision as Xr, emitStepStartEvent as Xs, loop as Xt, createDurableLLMExecutionStep as Y, planSpanQuery as Ya, getRestartStartIndex as Yc, createValidator as Yi, runFencingNotSupportedError as Yl, MessageHistory as Yn, AgentsMDInjector as Yo, MAX_NOTIFICATION_DELIVERY_ATTEMPTS as Yr, emitStepFinishEvent as Ys, runValidation as Yt, isSpanChunk as Z, spanQueryCostSchema as Za, getSingleStepEntryId as Zc, UnsupportedSchemaPatternError as Zi, setRunFenceContext as Zl, getMemoryRunState as Zn, RegexFilterProcessor as Zo, resolveDeliveryFailureUpdate as Zr, emitSuspendedEvent as Zs, validateModelTimeoutSettings as Zt, runEvals as _, hasErrorCode as _a, evaluatePredicate as _c, KnowledgeMoveTooLargeError as _i, workflowTermination as _l, knowledgeAccessGrants as _n, toEntityType as _o, GitHubSourceControlProvider as _r, STABILITY_ERROR_PROCESSOR_IDS as _s, toolRequiresApproval as _t, endRunSpansWithError as a, BackgroundTasksStorage as aa, AgentControlEventTypes as ac, KNOWLEDGE_STORAGE_CONTRACT_VERSION as ai, runCountDeprecationMessage as al, removeKnowledgeNote as an, getTraceQueryDeltaWatermark as ao, assertKnowledgeScopeWithinCeiling as ar, getMemoryTokenBoundary as as, baseIterationStateSchema as at, validateAndSaveScore as b, safelyParseJSON as ba, nestedRunParentOf as bc, KnowledgePageKeyConflictError as bi, isDurableAgentLike as bl, KnowledgeDeclarationError as bn, FactoryStorage as bo, FilesystemDB as br, UnsupportedFileHandler as bs, liveSegmentSpan as bt, globalRunRegistry as c, retentionCutoffMs as ca, getNestedWorkflow as cc, KnowledgeNotFoundError$1 as ci, validateStepRequestContext as cl, upsertKnowledgePage as cn, buildCreateSpanRecord as co, expandKnowledgeScope as cr, BatchPartsProcessor as cs, modelListEntrySchema as ct, takeRunScorerInstances as d, createStoreErrorId as da, Workflow as dc, KnowledgeTransactionDeadlineError as di, validateStepSuspendData as dl, KnowledgeLinkRefreshIncompleteError as dn, buildMetricRecord as do, knowledgeSemanticDocumentId as dr, StructuredOutputProcessor as ds, loadRunStoredMessages as dt, InMemoryChannelsStorage as ea, requestAcknowledgedAbort as ec, MemoryStorage as ei, isEntryFinished as el, buildKnowledgePageTools as en, spanQueryRequestSchema as eo, MAX_KNOWLEDGE_RECORD_TEXT_LENGTH as er, SystemPromptScrubber as es, buildStepRecord as et, AgentThreadLeaseLostError as f, createVectorErrorId as fa, cloneStep$1 as fc, KnowledgeUnsupportedCapabilityError as fi, waitForSuspendedSnapshot as fl, knowledgeSubtree as fn, buildScoreRecord as fo, knowledgeSemanticIdempotencyKey as fr, LanguageDetector as fs, rebuildRunToolsFromMastra as ft, describeNonSuccessFinishReason as g, getSqlType as ga, predicateToCondition as gc, parseKnowledgeWikilinks as gi, waitMs as gl, updateKnowledgeLinks as gn, serializeSpanAttributes as go, StoreOperations as gr, UnicodeNormalizer as gs, resolveTool$1 as gt, AGENTIC_LOOP_WORKFLOW_ID as h, getDefaultValue as ha, mapVariable as hc, inspectKnowledgeSchema as hi, assertDrainTimeout as hl, syncKnowledgePageBodyLinks as hn, getStringOrNull as ho, StoreOperationsInMemory as hr, ModerationProcessor as hs, resolveRuntimeDependencies as ht, deleteRunRegistryEntry as i, BackgroundTasksInMemory as ia, AGENT_STREAM_TOPIC as ic, KnowledgeImportersStorage as ii, resolveForeachConcurrency as il, moveKnowledgePage as in, encodeTraceQueryDeltaCursor as io, assertKnowledgeRecordTextWithinBound as ir, advanceMemoryTokenBoundary as is, baseDurableAgenticInputSchema as it, MAX_FS_SUBAGENT_DEPTH as j, tracePageResponseSchema as ja, createConcurrencyLimiter as jc, assertKnowledgePageDescriptionWithinBound as ji, ProcessorOutputStreamPhaseSchema as jl, defaultTypingStatus as jn, MastraMemory as jo, InMemoryToolProviderConnectionsStorage as jr, EventedRun as js, __registerMastraCtor as jt, agentInstructions as k, tracePageNodeSchema as ka, validateScoringPredicate as kc, MAX_KNOWLEDGE_PIN_LIST_DEPTH as ki, ProcessorOutputResultPhaseSchema as kl, AgentChannels as kn, resolveMaxChunkChars as ko, InMemoryWorkflowDefinitionsStorage as kr, createEventedWorkflow as ks, ensureRemoteAbortListener as kt, isDurableAgentExecutionDetached as l, runRetentionBatches as la, getStepEntry as lc, KnowledgeSchemaResetRequiredError as li, validateStepResumeData as ll, KnowledgeSemanticIndex as ln, buildFeedbackRecord as lo, isKnowledgeScopeVisible as lr, ModelSelectionProcessor as ls, executeDurableAgentScorers as lt, AGENTIC_EXECUTION_WORKFLOW_ID as m, filterByDateRange as ma, isProcessor$1 as mc, createKnowledgeUlid as mi, getEntryWorkflow as ml, reindexKnowledgeLinks as mn, getObjectOrNull as mo, parseKnowledgeNodeCursor as mr, PromptInjectionDetector as ms, resolveModel as mt, RunRegistry as n, InMemoryBlobStore as na, createRunAbortController as nc, KnowledgeImporterBindingConflictError as ni, omitPriorCompletionFields as nl, knowledgeRunPrincipals as nn, spanQueryRowSchema as no, assertKnowledgeCeilingRaised as nr, groupLinkedToolMessages as ns, createBaseIterationStateUpdate as nt, getActiveDurableAgentWorkflowExecutions as o, executeRetentionPrune as oa, AgentStreamEventTypes as oc, KNOWLEDGE_STORAGE_SCHEMA_VERSION as oi, setLongTimeout as ol, removeKnowledgePage as on, planThreadQuery as oo, canonicalizeKnowledgeScope as or, isAfterMemoryTokenBoundary as os, durableAgenticOutputSchema as ot, agentThreadStreamRuntime as p, ensureDate as pa, createStep$1 as pc, assertKnowledgeSchemaCompatible as pi, getEntryId as pl, refreshKnowledgeLinksTo as pn, buildUpdateSpanRecord as po, knowledgeVisibleScopeKeys as pr, PIIDetector as ps, resolveInternalState as pt, serializeModelConfig as q, encodeSpanQueryCursor as qa, defineLazyWriter as qc, SchemaValidator as qi, matchesRunFence as ql, globalEmbeddingCache as qn, formatSkillsCatalog as qo, summarizeNotifications as qr, emitErrorEvent as qs, runDefaultCompletionCheck as qt, abandonDurableAgentExecutions as r, BlobStore as ra, AGENT_CONTROL_TOPIC as rc, KnowledgeImporterRunStateError as ri, omitPriorSuspensionFields as rl, addKnowledgeNote as rn, encodeTraceQueryCursor as ro, assertKnowledgeDescriptionWithinBound as rr, loadMessageHistory as rs, accumulatedUsageSchema as rt, getRunRegistryEntry as s, resolveRetentionTargets as sa, EventedExecutionEngine as sc, KnowledgeConflictError as si, validateStepInput as sl, updateKnowledgeNote as sn, planTraceQuery as so, createKnowledgeNodeCursor as sr, normalizeMessageHistoryConfig as ss, modelConfigSchema as st, ExtendedRunRegistry as t, ChannelsStorage as ta, subscribeToAbortRequests as tc, InMemoryKnowledgeStorage as ti, isSingleStepEntry as tl, KnowledgeRun as tn, spanQueryResponseSchema as to, MAX_KNOWLEDGE_SCOPE_TAGS as tr, TokenLimiterProcessor as ts, calculateAccumulatedUsage as tt, setRunRegistryEntry as u, createStorageErrorId as ua, Run as uc, KnowledgeStorage as ui, validateStepStateData as ul, embed$2 as un, buildLogRecord as uo, knowledgeScopeKey as ur, ClassifierProcessor as us, runDurableFinishSideEffects as ut, flushBeforeTraceRead as v, jsonValueEquals as va, cancelNestedRun as vc, KnowledgePageDepthError as vi, hasDurableExecution as vl, knowledgeReadScopeFor as vn, ObservabilityInMemory as vo, createGitHubSourceControlProviderFromEnv as vr, defaultStabilityErrorProcessors as vs, resolveAgentById as vt, createScorer as w, transformScoreRow as wa, renewWorkflowLease as wc, MAX_KNOWLEDGE_PAGE_DEPTH as wi, MessagePartSchema as wl, knowledgeScopeAddress as wn, MESSAGE_EMBEDDING_CHARS_PER_TOKEN as wo, cloneRunData as wr, isBadRequestError as ws, runResumeDurableStreamUntilIdle as wt, createClassifierScorer as x, serializeDate as xa, nestedRunRecoveryAction as xc, MAX_KNOWLEDGE_MOVE_PAGES as xi, FilePartSchema as xl, compileKnowledgeScopes as xn, FactoryStorageDomain as xo, InMemoryStore as xr, FileUploadProcessor as xs, segmentSpanData as xt, createOnScorerHook as y, parseDuration as ya, createNestedRunParentStatusLookup as yc, KnowledgePageHasChildrenError as yi, hasResumableStreams as yl, knowledgeRoleOn as yn, ObservabilityStorage as yo, FilesystemStore as yr, isMalformedFunctionCallError as ys, carrySegmentSpans as yt, createDurableAgenticWorkflow as z, threadQueryRowSchema as za, RESUME_SNAPSHOT_WAIT_STATUSES as zc, KnowledgeInvalidCursorError as zi, ToolInvocationPartSchema as zl, channelToolScopeResolver as zn, CyberRefusalHandler as zo, NotificationsStorage as zr, computeScheduleDefinitionHash as zs, formatCheckFeedback as zt };
|