@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
package/dist/knowledge/index.cjs
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
2
|
const require_base = require("../base-BIzR1D3_.cjs");
|
|
3
|
-
const require_run_registry = require("../run-registry-
|
|
3
|
+
const require_run_registry = require("../run-registry-BmckDVBk.cjs");
|
|
4
|
+
const require_tool = require("../tool-CYlT2UA-.cjs");
|
|
4
5
|
let crypto = require("crypto");
|
|
6
|
+
let _mastra_schema_compat_schema = require("@mastra/schema-compat/schema");
|
|
5
7
|
// src/knowledge/changes.ts
|
|
6
8
|
const page = (op) => (result) => {
|
|
7
9
|
const { id, scopeId } = result;
|
|
@@ -111,6 +113,2595 @@ function emitKnowledgeChanges(storage, emit, listening, onError) {
|
|
|
111
113
|
};
|
|
112
114
|
} });
|
|
113
115
|
}
|
|
116
|
+
// src/knowledge/importers/host.ts
|
|
117
|
+
/** A host refused a flush or a finish (409 over HTTP). Retrying the same request won't help. @experimental */
|
|
118
|
+
var KnowledgeImporterHostConflictError = class extends Error {
|
|
119
|
+
code;
|
|
120
|
+
status = 409;
|
|
121
|
+
constructor(code, message) {
|
|
122
|
+
super(message);
|
|
123
|
+
this.code = code;
|
|
124
|
+
this.name = "KnowledgeImporterHostConflictError";
|
|
125
|
+
}
|
|
126
|
+
};
|
|
127
|
+
const KNOWLEDGE_IMPORTER_ERROR_CODES = [
|
|
128
|
+
"source_auth_failed",
|
|
129
|
+
"source_unreachable",
|
|
130
|
+
"source_rate_limited",
|
|
131
|
+
"source_bad_response",
|
|
132
|
+
"source_not_found",
|
|
133
|
+
"settings_invalid",
|
|
134
|
+
"credential_missing",
|
|
135
|
+
"importer_missing_from_deploy",
|
|
136
|
+
"importer_error",
|
|
137
|
+
"stopped",
|
|
138
|
+
"lease_expired",
|
|
139
|
+
"deadline_exceeded"
|
|
140
|
+
];
|
|
141
|
+
/**
|
|
142
|
+
* The finish request as a host stores and compares it: missing optional fields become null.
|
|
143
|
+
* Throws a TypeError for a request no host should accept.
|
|
144
|
+
*/
|
|
145
|
+
function normalizeKnowledgeImporterFinish(request) {
|
|
146
|
+
const { outcome, backlog, lastSeq, error } = request;
|
|
147
|
+
if (outcome !== "succeeded" && outcome !== "failed" && outcome !== "canceled") throw new TypeError(`Unknown importer run outcome "${String(outcome)}".`);
|
|
148
|
+
if (typeof backlog !== "boolean") throw new TypeError("Importer finish needs backlog: true or false.");
|
|
149
|
+
if (backlog && outcome !== "succeeded") throw new TypeError("Only a succeeded importer run can report backlog.");
|
|
150
|
+
if (!Number.isSafeInteger(lastSeq) || lastSeq < 0) throw new TypeError("Importer finish needs lastSeq >= 0.");
|
|
151
|
+
const hasError = error !== void 0 && error !== null;
|
|
152
|
+
if (outcome === "failed" !== hasError) throw new TypeError("A failed importer run needs an error code, and only a failed run has one.");
|
|
153
|
+
if (!hasError) return {
|
|
154
|
+
outcome,
|
|
155
|
+
backlog,
|
|
156
|
+
lastSeq,
|
|
157
|
+
error: null
|
|
158
|
+
};
|
|
159
|
+
if (!isPlainObject$1(error)) throw new TypeError("Importer finish error must be an object.");
|
|
160
|
+
const unknownErrorKeys = Object.keys(error).filter((key) => ![
|
|
161
|
+
"code",
|
|
162
|
+
"retryable",
|
|
163
|
+
"httpStatus"
|
|
164
|
+
].includes(key));
|
|
165
|
+
if (unknownErrorKeys.length) throw new TypeError(`Importer finish error has unknown field "${unknownErrorKeys[0]}".`);
|
|
166
|
+
if (!KNOWLEDGE_IMPORTER_ERROR_CODES.includes(error.code)) throw new TypeError(`Unknown importer error code "${String(error.code)}".`);
|
|
167
|
+
if (error.retryable !== void 0 && typeof error.retryable !== "boolean") throw new TypeError("Importer error retryable must be a boolean.");
|
|
168
|
+
const { httpStatus } = error;
|
|
169
|
+
if (httpStatus !== void 0 && (!Number.isInteger(httpStatus) || httpStatus < 100 || httpStatus > 599)) throw new TypeError("Importer error httpStatus must be an HTTP status code.");
|
|
170
|
+
return {
|
|
171
|
+
outcome,
|
|
172
|
+
backlog,
|
|
173
|
+
lastSeq,
|
|
174
|
+
error: {
|
|
175
|
+
code: error.code,
|
|
176
|
+
retryable: error.retryable ?? null,
|
|
177
|
+
httpStatus: httpStatus ?? null
|
|
178
|
+
}
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* RFC 8785 (JCS) canonical JSON: object members sorted by UTF-16 code units, no whitespace, numbers
|
|
183
|
+
* and strings as ECMAScript serializes them. Members whose value is undefined are left out, as
|
|
184
|
+
* JSON.stringify leaves them out of what goes over the wire; array holes and undefined items are
|
|
185
|
+
* null, as JSON.stringify writes them. Strings with a lone UTF-16 surrogate are refused (RFC 8785
|
|
186
|
+
* §3.2.2.2).
|
|
187
|
+
*/
|
|
188
|
+
function canonicalJson(value) {
|
|
189
|
+
if (value === null) return "null";
|
|
190
|
+
switch (typeof value) {
|
|
191
|
+
case "boolean": return value ? "true" : "false";
|
|
192
|
+
case "number":
|
|
193
|
+
if (!Number.isFinite(value)) throw new TypeError("Canonical JSON has no NaN or Infinity.");
|
|
194
|
+
return JSON.stringify(value);
|
|
195
|
+
case "string": return JSON.stringify(wellFormed(value));
|
|
196
|
+
case "object": {
|
|
197
|
+
if (Array.isArray(value)) {
|
|
198
|
+
const items = [];
|
|
199
|
+
for (let index = 0; index < value.length; index++) {
|
|
200
|
+
const item = value[index];
|
|
201
|
+
items.push(item === void 0 ? "null" : canonicalJson(item));
|
|
202
|
+
}
|
|
203
|
+
return `[${items.join(",")}]`;
|
|
204
|
+
}
|
|
205
|
+
const record = value;
|
|
206
|
+
return `{${Object.keys(record).filter((key) => record[key] !== void 0).sort().map((key) => `${JSON.stringify(wellFormed(key))}:${canonicalJson(record[key])}`).join(",")}}`;
|
|
207
|
+
}
|
|
208
|
+
default: throw new TypeError(`Canonical JSON can't hold a ${typeof value}.`);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* A flush's digest: lowercase hex SHA-256 of the canonical JSON of `{ ops, state }`, with an absent
|
|
213
|
+
* `state` as null. Runners send it; hosts recompute it from the body they received. The body is
|
|
214
|
+
* checked with `parseKnowledgeImporterFlushBody` first, so only payloads that survive a JSON round
|
|
215
|
+
* trip unchanged get a digest.
|
|
216
|
+
*/
|
|
217
|
+
async function knowledgeImporterFlushDigest(flush) {
|
|
218
|
+
const { ops, state } = parseKnowledgeImporterFlushBody(flush);
|
|
219
|
+
const bytes = new TextEncoder().encode(canonicalJson({
|
|
220
|
+
ops,
|
|
221
|
+
state: state ?? null
|
|
222
|
+
}));
|
|
223
|
+
const hash = await globalThis.crypto.subtle.digest("SHA-256", bytes);
|
|
224
|
+
return Array.from(new Uint8Array(hash), (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
225
|
+
}
|
|
226
|
+
function isPlainObject$1(value) {
|
|
227
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
|
|
228
|
+
const proto = Object.getPrototypeOf(value);
|
|
229
|
+
return proto === Object.prototype || proto === null;
|
|
230
|
+
}
|
|
231
|
+
const LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;
|
|
232
|
+
function wellFormed(value) {
|
|
233
|
+
if (LONE_SURROGATE.test(value)) throw new TypeError("Canonical JSON refuses strings with a lone UTF-16 surrogate.");
|
|
234
|
+
return value;
|
|
235
|
+
}
|
|
236
|
+
const DECLARATION_FIELDS = {
|
|
237
|
+
sourceId: {
|
|
238
|
+
kind: "nonEmpty",
|
|
239
|
+
required: true
|
|
240
|
+
},
|
|
241
|
+
kind: { kind: "string" },
|
|
242
|
+
title: {
|
|
243
|
+
kind: "string",
|
|
244
|
+
required: true
|
|
245
|
+
},
|
|
246
|
+
parent: { kind: "nullableString" },
|
|
247
|
+
fallbackParent: { kind: "nonEmpty" }
|
|
248
|
+
};
|
|
249
|
+
const ITEM_FIELDS = {
|
|
250
|
+
...DECLARATION_FIELDS,
|
|
251
|
+
description: { kind: "string" },
|
|
252
|
+
body: {
|
|
253
|
+
kind: "string",
|
|
254
|
+
required: true
|
|
255
|
+
},
|
|
256
|
+
links: { kind: "links" },
|
|
257
|
+
aliases: { kind: "aliases" }
|
|
258
|
+
};
|
|
259
|
+
function checkString(value, where, nonEmpty = false) {
|
|
260
|
+
if (typeof value !== "string") throw new TypeError(`${where} must be a string.`);
|
|
261
|
+
if (nonEmpty && !value) throw new TypeError(`${where} must not be empty.`);
|
|
262
|
+
return wellFormed(value);
|
|
263
|
+
}
|
|
264
|
+
function checkDenseArray(value, where) {
|
|
265
|
+
if (!Array.isArray(value)) throw new TypeError(`${where} must be an array.`);
|
|
266
|
+
for (let index = 0; index < value.length; index++) if (!(index in value)) throw new TypeError(`${where}[${index}] is empty.`);
|
|
267
|
+
return value;
|
|
268
|
+
}
|
|
269
|
+
function checkFields(value, fields, where) {
|
|
270
|
+
if (!isPlainObject$1(value)) throw new TypeError(`${where} must be an object.`);
|
|
271
|
+
const out = Object.create(null);
|
|
272
|
+
for (const key of Object.keys(value)) if (!Object.hasOwn(fields, key)) throw new TypeError(`${where} has unknown field "${key}".`);
|
|
273
|
+
for (const [key, { kind, required }] of Object.entries(fields)) {
|
|
274
|
+
const field = value[key];
|
|
275
|
+
const at = `${where}.${key}`;
|
|
276
|
+
if (field === void 0) {
|
|
277
|
+
if (required) throw new TypeError(`${at} is required.`);
|
|
278
|
+
continue;
|
|
279
|
+
}
|
|
280
|
+
switch (kind) {
|
|
281
|
+
case "string":
|
|
282
|
+
out[key] = checkString(field, at);
|
|
283
|
+
break;
|
|
284
|
+
case "nonEmpty":
|
|
285
|
+
out[key] = checkString(field, at, true);
|
|
286
|
+
break;
|
|
287
|
+
case "nullableString":
|
|
288
|
+
out[key] = field === null ? null : checkString(field, at, true);
|
|
289
|
+
break;
|
|
290
|
+
case "aliases":
|
|
291
|
+
out[key] = checkDenseArray(field, at).map((alias, index) => checkString(alias, `${at}[${index}]`, true));
|
|
292
|
+
break;
|
|
293
|
+
case "links": out[key] = checkDenseArray(field, at).map((link, index) => checkFields(link, {
|
|
294
|
+
sourceId: {
|
|
295
|
+
kind: "nonEmpty",
|
|
296
|
+
required: true
|
|
297
|
+
},
|
|
298
|
+
rel: { kind: "string" }
|
|
299
|
+
}, `${at}[${index}]`));
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
return { ...out };
|
|
303
|
+
}
|
|
304
|
+
/**
|
|
305
|
+
* Checks a flush body the way every host and runner must before hashing or applying it: known ops
|
|
306
|
+
* and fields only, strings where strings belong, no array holes, no lone surrogates, string-only
|
|
307
|
+
* state. Returns a copy with undefined optional fields left out, so what passes hashes the same
|
|
308
|
+
* before and after a JSON round trip. Throws a TypeError otherwise.
|
|
309
|
+
*
|
|
310
|
+
* @experimental
|
|
311
|
+
*/
|
|
312
|
+
function parseKnowledgeImporterFlushBody(body) {
|
|
313
|
+
const ops = checkDenseArray(body.ops, "ops").map((op, index) => {
|
|
314
|
+
const where = `ops[${index}]`;
|
|
315
|
+
if (!isPlainObject$1(op)) throw new TypeError(`${where} must be an object.`);
|
|
316
|
+
switch (op.op) {
|
|
317
|
+
case "upsert":
|
|
318
|
+
case "declare": {
|
|
319
|
+
const extra = Object.keys(op).find((key) => key !== "op" && key !== "item");
|
|
320
|
+
if (extra) throw new TypeError(`${where} has unknown field "${extra}".`);
|
|
321
|
+
const fields = op.op === "upsert" ? ITEM_FIELDS : DECLARATION_FIELDS;
|
|
322
|
+
return {
|
|
323
|
+
op: op.op,
|
|
324
|
+
item: checkFields(op.item, fields, `${where}.item`)
|
|
325
|
+
};
|
|
326
|
+
}
|
|
327
|
+
case "remove": {
|
|
328
|
+
const extra = Object.keys(op).find((key) => key !== "op" && key !== "sourceId");
|
|
329
|
+
if (extra) throw new TypeError(`${where} has unknown field "${extra}".`);
|
|
330
|
+
return {
|
|
331
|
+
op: "remove",
|
|
332
|
+
sourceId: checkString(op.sourceId, `${where}.sourceId`, true)
|
|
333
|
+
};
|
|
334
|
+
}
|
|
335
|
+
default: throw new TypeError(`${where}.op must be "upsert", "declare" or "remove".`);
|
|
336
|
+
}
|
|
337
|
+
});
|
|
338
|
+
if (body.state === void 0 || body.state === null) return { ops };
|
|
339
|
+
if (!isPlainObject$1(body.state)) throw new TypeError("state must be an object of strings.");
|
|
340
|
+
return {
|
|
341
|
+
ops,
|
|
342
|
+
state: Object.fromEntries(Object.entries(body.state).map(([key, value]) => [wellFormed(key), checkString(value, `state.${key}`)]))
|
|
343
|
+
};
|
|
344
|
+
}
|
|
345
|
+
// src/knowledge/importers/manifest.ts
|
|
346
|
+
/** The settings schema of an importer with no settings: an empty object. */
|
|
347
|
+
const EMPTY_KNOWLEDGE_IMPORTER_SETTINGS_SCHEMA = {
|
|
348
|
+
type: "object",
|
|
349
|
+
properties: {},
|
|
350
|
+
additionalProperties: false
|
|
351
|
+
};
|
|
352
|
+
/** Every `$ref` in a schema, so a manifest can refuse ones that point outside the schema. */
|
|
353
|
+
function jsonSchemaRefs(schema, refs = []) {
|
|
354
|
+
if (Array.isArray(schema)) for (const item of schema) jsonSchemaRefs(item, refs);
|
|
355
|
+
else if (schema && typeof schema === "object") for (const [key, value] of Object.entries(schema)) if (key === "$ref" && typeof value === "string") refs.push(value);
|
|
356
|
+
else jsonSchemaRefs(value, refs);
|
|
357
|
+
return refs;
|
|
358
|
+
}
|
|
359
|
+
// src/knowledge/importers/define.ts
|
|
360
|
+
/**
|
|
361
|
+
* The base every importer extends through {@link KnowledgeImporter}. An instance is one binding;
|
|
362
|
+
* `import` is called once per pass of a run.
|
|
363
|
+
*
|
|
364
|
+
* @experimental
|
|
365
|
+
*/
|
|
366
|
+
var KnowledgeImporterBase = class {
|
|
367
|
+
/** What the instance was constructed with, as the host sees a binding. */
|
|
368
|
+
binding;
|
|
369
|
+
constructor(binding) {
|
|
370
|
+
const definition = new.target.definition;
|
|
371
|
+
if (!definition) throw new KnowledgeImporterDefinitionError("Importer classes extend KnowledgeImporter({ ... }).");
|
|
372
|
+
const input = binding;
|
|
373
|
+
if (typeof input?.id !== "string" || !input.id.trim()) throw new KnowledgeImporterDefinitionError(`A "${definition.id}" importer binding needs an id.`);
|
|
374
|
+
if (typeof input.target !== "string" || !input.target.trim()) throw new KnowledgeImporterDefinitionError(`Importer binding "${input.id}" needs a target ("<scope>#<path>").`);
|
|
375
|
+
this.binding = Object.freeze({
|
|
376
|
+
id: input.id,
|
|
377
|
+
importer: definition.id,
|
|
378
|
+
target: input.target,
|
|
379
|
+
settings: input.settings ?? {},
|
|
380
|
+
credentials: { ...definition.checkCredentials(input.credentials) }
|
|
381
|
+
});
|
|
382
|
+
}
|
|
383
|
+
};
|
|
384
|
+
/** A definition, a registry or a binding's settings or credentials are invalid. @experimental */
|
|
385
|
+
var KnowledgeImporterDefinitionError = class extends Error {
|
|
386
|
+
constructor(message) {
|
|
387
|
+
super(message);
|
|
388
|
+
this.name = "KnowledgeImporterDefinitionError";
|
|
389
|
+
}
|
|
390
|
+
};
|
|
391
|
+
/** A binding's settings don't match the importer's schema (run error code `settings_invalid`). @experimental */
|
|
392
|
+
var KnowledgeImporterSettingsError = class extends KnowledgeImporterDefinitionError {
|
|
393
|
+
errors;
|
|
394
|
+
constructor(message, errors) {
|
|
395
|
+
super(message);
|
|
396
|
+
this.errors = errors;
|
|
397
|
+
this.name = "KnowledgeImporterSettingsError";
|
|
398
|
+
}
|
|
399
|
+
};
|
|
400
|
+
/** A binding is missing a credential or supplies an undeclared one (run error code `credential_missing`). @experimental */
|
|
401
|
+
var KnowledgeImporterCredentialsError = class extends KnowledgeImporterDefinitionError {
|
|
402
|
+
constructor(message) {
|
|
403
|
+
super(message);
|
|
404
|
+
this.name = "KnowledgeImporterCredentialsError";
|
|
405
|
+
}
|
|
406
|
+
};
|
|
407
|
+
/** The source answered with an error status. The runner maps the status to the run's error code. @experimental */
|
|
408
|
+
var KnowledgeImporterSourceError = class extends Error {
|
|
409
|
+
status;
|
|
410
|
+
constructor(message, status) {
|
|
411
|
+
super(message);
|
|
412
|
+
this.status = status;
|
|
413
|
+
this.name = "KnowledgeImporterSourceError";
|
|
414
|
+
}
|
|
415
|
+
};
|
|
416
|
+
/**
|
|
417
|
+
* The host failed, not the source: a fetch proxy or relay, or a remote host's flush, heartbeat or
|
|
418
|
+
* finish. Never a sign an item is gone. `status` is the HTTP status when there was a response;
|
|
419
|
+
* absent for a network error. @experimental
|
|
420
|
+
*/
|
|
421
|
+
var KnowledgeImporterHostError = class extends Error {
|
|
422
|
+
status;
|
|
423
|
+
constructor(message, status) {
|
|
424
|
+
super(message);
|
|
425
|
+
this.status = status;
|
|
426
|
+
this.name = "KnowledgeImporterHostError";
|
|
427
|
+
}
|
|
428
|
+
};
|
|
429
|
+
const IMPORTER_ID = /^[a-z][a-z0-9_-]{0,63}$/;
|
|
430
|
+
const SLOT_NAME = /^[A-Za-z][A-Za-z0-9_]{0,63}$/;
|
|
431
|
+
function checkIconUrl(id, iconUrl) {
|
|
432
|
+
if (/^data:image\//.test(iconUrl)) return;
|
|
433
|
+
let protocol;
|
|
434
|
+
try {
|
|
435
|
+
protocol = new URL(iconUrl).protocol;
|
|
436
|
+
} catch {
|
|
437
|
+
protocol = "";
|
|
438
|
+
}
|
|
439
|
+
if (protocol !== "https:" && protocol !== "http:") throw new KnowledgeImporterDefinitionError(`Importer "${id}" iconUrl must be an http(s) URL or a data:image/ URI.`);
|
|
440
|
+
}
|
|
441
|
+
/**
|
|
442
|
+
* The base class of an importer: code that reads a source and writes it into Knowledge as items.
|
|
443
|
+
* The class declares what it is (id, label, settings schema, credential slots); each instance is
|
|
444
|
+
* one binding (where it writes, with which settings and credentials).
|
|
445
|
+
*
|
|
446
|
+
* ```ts
|
|
447
|
+
* class HelpSpotImporter extends KnowledgeImporter({
|
|
448
|
+
* id: 'helpspot',
|
|
449
|
+
* label: 'HelpSpot',
|
|
450
|
+
* settings: z.object({ baseUrl: z.url() }),
|
|
451
|
+
* credentials: { apiKey: { description: 'HelpSpot API token' } },
|
|
452
|
+
* }) {
|
|
453
|
+
* async import(ctx) {
|
|
454
|
+
* // read ctx.state.get('cursor'), ctx.items.upsert(...), ctx.state.set('cursor', ...)
|
|
455
|
+
* }
|
|
456
|
+
* }
|
|
457
|
+
*
|
|
458
|
+
* new HelpSpotImporter({ id: 'support', target: 'docs#support', settings: { baseUrl }, credentials: { apiKey } });
|
|
459
|
+
* ```
|
|
460
|
+
*
|
|
461
|
+
* Invalid declarations throw `KnowledgeImporterDefinitionError` here, not at the first run.
|
|
462
|
+
*
|
|
463
|
+
* @experimental
|
|
464
|
+
*/
|
|
465
|
+
function KnowledgeImporter(input) {
|
|
466
|
+
const definition = defineImporter(input);
|
|
467
|
+
class Importer extends KnowledgeImporterBase {
|
|
468
|
+
static id = definition.id;
|
|
469
|
+
static definition = definition;
|
|
470
|
+
static toManifest() {
|
|
471
|
+
return definition.toManifest();
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
return Importer;
|
|
475
|
+
}
|
|
476
|
+
function defineImporter(input) {
|
|
477
|
+
const { id, label, description, iconUrl } = input ?? {};
|
|
478
|
+
if (typeof id !== "string" || !IMPORTER_ID.test(id)) throw new KnowledgeImporterDefinitionError(`Importer id "${String(id)}" must be 1-64 lowercase letters, digits, "-" or "_", starting with a letter.`);
|
|
479
|
+
if (typeof label !== "string" || !label.trim()) throw new KnowledgeImporterDefinitionError(`Importer "${id}" needs a label.`);
|
|
480
|
+
if (iconUrl !== void 0) checkIconUrl(id, iconUrl);
|
|
481
|
+
const credentials = {};
|
|
482
|
+
for (const [slot, declared] of Object.entries(input.credentials ?? {})) {
|
|
483
|
+
if (!SLOT_NAME.test(slot)) throw new KnowledgeImporterDefinitionError(`Importer "${id}" credential slot "${slot}" must be letters, digits and "_", starting with a letter.`);
|
|
484
|
+
if (!declared || typeof declared.description !== "string" || !declared.description.trim()) throw new KnowledgeImporterDefinitionError(`Importer "${id}" credential slot "${slot}" needs a description.`);
|
|
485
|
+
credentials[slot] = Object.freeze({
|
|
486
|
+
description: declared.description,
|
|
487
|
+
secret: declared.secret ?? true
|
|
488
|
+
});
|
|
489
|
+
}
|
|
490
|
+
Object.freeze(credentials);
|
|
491
|
+
let settingsSchema;
|
|
492
|
+
let settingsJsonSchema = EMPTY_KNOWLEDGE_IMPORTER_SETTINGS_SCHEMA;
|
|
493
|
+
if (input.settings !== void 0) {
|
|
494
|
+
try {
|
|
495
|
+
settingsSchema = (0, _mastra_schema_compat_schema.toStandardSchema)(input.settings);
|
|
496
|
+
settingsJsonSchema = (0, _mastra_schema_compat_schema.standardSchemaToJSONSchema)(settingsSchema, {
|
|
497
|
+
io: "input",
|
|
498
|
+
target: "draft-07"
|
|
499
|
+
});
|
|
500
|
+
} catch (error) {
|
|
501
|
+
throw new KnowledgeImporterDefinitionError(`Importer "${id}" settings schema can't be turned into JSON Schema: ${error instanceof Error ? error.message : String(error)}`);
|
|
502
|
+
}
|
|
503
|
+
const outside = jsonSchemaRefs(settingsJsonSchema).find((ref) => !ref.startsWith("#"));
|
|
504
|
+
if (outside) throw new KnowledgeImporterDefinitionError(`Importer "${id}" settings schema refers outside itself ($ref "${outside}").`);
|
|
505
|
+
}
|
|
506
|
+
const manifest = {
|
|
507
|
+
id,
|
|
508
|
+
label,
|
|
509
|
+
...description !== void 0 && { description },
|
|
510
|
+
...iconUrl !== void 0 && { iconUrl },
|
|
511
|
+
settingsSchema: settingsJsonSchema,
|
|
512
|
+
credentials: Object.fromEntries(Object.entries(credentials).map(([slot, declared]) => [slot, { ...declared }]))
|
|
513
|
+
};
|
|
514
|
+
return Object.freeze({
|
|
515
|
+
id,
|
|
516
|
+
label,
|
|
517
|
+
description,
|
|
518
|
+
iconUrl,
|
|
519
|
+
credentials,
|
|
520
|
+
async parseSettings(value) {
|
|
521
|
+
if (!settingsSchema) {
|
|
522
|
+
if (!(value === void 0 || isPlainObject(value) && Object.keys(value).length === 0)) throw new KnowledgeImporterSettingsError(`Importer "${id}" takes no settings.`, [{
|
|
523
|
+
path: [],
|
|
524
|
+
message: "Importer takes no settings"
|
|
525
|
+
}]);
|
|
526
|
+
return {};
|
|
527
|
+
}
|
|
528
|
+
const result = await settingsSchema["~standard"].validate(value);
|
|
529
|
+
if (result.issues) {
|
|
530
|
+
const issues = require_tool.createStandardSchemaIssuesError(result.issues);
|
|
531
|
+
throw new KnowledgeImporterSettingsError(`Settings for importer "${id}" are invalid:\n${issues.message}`, issues.errors);
|
|
532
|
+
}
|
|
533
|
+
return result.value;
|
|
534
|
+
},
|
|
535
|
+
checkCredentials(values) {
|
|
536
|
+
const supplied = values ?? {};
|
|
537
|
+
const unknown = Object.keys(supplied).filter((slot) => !Object.hasOwn(credentials, slot));
|
|
538
|
+
if (unknown.length) throw new KnowledgeImporterCredentialsError(`Importer "${id}" has no credential slot ${unknown.map((slot) => `"${slot}"`).join(", ")}.`);
|
|
539
|
+
const missing = Object.keys(credentials).filter((slot) => {
|
|
540
|
+
const value = supplied[slot];
|
|
541
|
+
return typeof value !== "string" || value.length === 0;
|
|
542
|
+
});
|
|
543
|
+
if (missing.length) throw new KnowledgeImporterCredentialsError(`Importer "${id}" is missing credential ${missing.map((slot) => `"${slot}"`).join(", ")}.`);
|
|
544
|
+
return Object.freeze({ ...supplied });
|
|
545
|
+
},
|
|
546
|
+
toManifest: () => structuredClone(manifest)
|
|
547
|
+
});
|
|
548
|
+
}
|
|
549
|
+
function isPlainObject(value) {
|
|
550
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
551
|
+
}
|
|
552
|
+
/**
|
|
553
|
+
* Indexes importer classes by id, refusing two different classes with the same id. A host uses it
|
|
554
|
+
* to construct the instance a stored binding names.
|
|
555
|
+
*
|
|
556
|
+
* @experimental
|
|
557
|
+
*/
|
|
558
|
+
function knowledgeImporterRegistry(importers) {
|
|
559
|
+
const registry = /* @__PURE__ */ new Map();
|
|
560
|
+
for (const importer of importers) {
|
|
561
|
+
const known = registry.get(importer.id);
|
|
562
|
+
if (known && known !== importer) throw new KnowledgeImporterDefinitionError(`Two importer classes have the id "${importer.id}".`);
|
|
563
|
+
registry.set(importer.id, importer);
|
|
564
|
+
}
|
|
565
|
+
return registry;
|
|
566
|
+
}
|
|
567
|
+
// src/knowledge/importers/runner.ts
|
|
568
|
+
/** Waits `ms`, or until `cut` settles; the timer is cleared either way. */
|
|
569
|
+
async function sleep(ms, cut) {
|
|
570
|
+
let timer;
|
|
571
|
+
try {
|
|
572
|
+
await Promise.race([new Promise((resolve) => timer = setTimeout(resolve, ms)), ...cut ? [cut] : []]);
|
|
573
|
+
} finally {
|
|
574
|
+
clearTimeout(timer);
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
/** `promise`, or `onTimeout()` thrown after `ms`. */
|
|
578
|
+
async function within(promise, ms, onTimeout) {
|
|
579
|
+
let timer;
|
|
580
|
+
try {
|
|
581
|
+
return await Promise.race([promise, new Promise((_, reject) => timer = setTimeout(() => reject(onTimeout()), ms))]);
|
|
582
|
+
} finally {
|
|
583
|
+
clearTimeout(timer);
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
/** Refusals kept on a run receipt. */
|
|
587
|
+
const MAX_RECEIPT_REFUSALS = 100;
|
|
588
|
+
const isRetryable = (error) => error instanceof KnowledgeImporterHostError && (error.status === void 0 || error.status >= 500);
|
|
589
|
+
/** The run ended for a reason that decides its outcome; buffered ops after it are dropped. */
|
|
590
|
+
var RunStop = class extends Error {
|
|
591
|
+
reason;
|
|
592
|
+
constructor(reason) {
|
|
593
|
+
super(`importer run ${reason}`);
|
|
594
|
+
this.reason = reason;
|
|
595
|
+
}
|
|
596
|
+
};
|
|
597
|
+
function sourceError(error) {
|
|
598
|
+
const { status } = error;
|
|
599
|
+
const httpStatus = Number.isInteger(status) && status >= 100 && status <= 599 ? status : void 0;
|
|
600
|
+
if (status === 401 || status === 403) return {
|
|
601
|
+
code: "source_auth_failed",
|
|
602
|
+
retryable: false,
|
|
603
|
+
httpStatus
|
|
604
|
+
};
|
|
605
|
+
if (status === 404) return {
|
|
606
|
+
code: "source_not_found",
|
|
607
|
+
retryable: false,
|
|
608
|
+
httpStatus
|
|
609
|
+
};
|
|
610
|
+
if (status === 429) return {
|
|
611
|
+
code: "source_rate_limited",
|
|
612
|
+
retryable: true,
|
|
613
|
+
httpStatus
|
|
614
|
+
};
|
|
615
|
+
if (status >= 500) return {
|
|
616
|
+
code: "source_unreachable",
|
|
617
|
+
retryable: true,
|
|
618
|
+
httpStatus
|
|
619
|
+
};
|
|
620
|
+
return {
|
|
621
|
+
code: "source_bad_response",
|
|
622
|
+
retryable: false,
|
|
623
|
+
httpStatus
|
|
624
|
+
};
|
|
625
|
+
}
|
|
626
|
+
/**
|
|
627
|
+
* Runs one import: starts a run on the host, calls the importer's `import` in passes, sends its items
|
|
628
|
+
* in numbered flushes, and records how the run ended. Every write goes through `host`; the runner
|
|
629
|
+
* never touches storage. Failures end the run with a fixed code; no exception text leaves the app.
|
|
630
|
+
*
|
|
631
|
+
* @experimental
|
|
632
|
+
*/
|
|
633
|
+
async function runKnowledgeImport(options) {
|
|
634
|
+
const { host, budgetMs = 15e5, graceMs = 18e4, maxPasses = 200, bufferSize = 200, heartbeatMs = 3e4, maxRetries = 8, hostCallTimeoutMs = 6e4, retryDelayMs = (attempt) => Math.min(250 * 2 ** attempt, 1e4) } = options;
|
|
635
|
+
const started = await within(host.startRun(options.bindingId, options.start), hostCallTimeoutMs, () => new KnowledgeImporterHostError("host call timed out"));
|
|
636
|
+
if (started.status === "skipped") return started;
|
|
637
|
+
const { runId, generation } = started;
|
|
638
|
+
const startedAt = Date.now();
|
|
639
|
+
let lastSeq = started.lastSeq;
|
|
640
|
+
/** A flush sent but never acknowledged: it may have committed. */
|
|
641
|
+
let unsettledSeq;
|
|
642
|
+
let state = { ...started.state };
|
|
643
|
+
let buffer = [];
|
|
644
|
+
let stop;
|
|
645
|
+
let hostFailure;
|
|
646
|
+
const controller = new AbortController();
|
|
647
|
+
let deadlineHit;
|
|
648
|
+
/** Settles at the hard deadline; never otherwise. */
|
|
649
|
+
const deadlinePassed = new Promise((resolve) => deadlineHit = resolve);
|
|
650
|
+
let wake;
|
|
651
|
+
/** Settles when the run stops for any reason, so nothing waits on an import or a backoff past it. */
|
|
652
|
+
const stopped = new Promise((resolve) => wake = resolve);
|
|
653
|
+
const halt = (reason) => {
|
|
654
|
+
if (reason === "stopped") deadlineHit();
|
|
655
|
+
stop ??= new RunStop(reason);
|
|
656
|
+
controller.abort(stop);
|
|
657
|
+
wake();
|
|
658
|
+
};
|
|
659
|
+
/**
|
|
660
|
+
* Sends with resends after a retryable failure. A call that takes longer than `hostCallTimeoutMs`
|
|
661
|
+
* counts as a lost ack. Once the run has stopped, a mutation (a flush) is not resent: its
|
|
662
|
+
* outcome stays unknown and the finish settles it. The finish itself is still resent.
|
|
663
|
+
*/
|
|
664
|
+
async function withRetries(send, kind) {
|
|
665
|
+
for (let attempt = 0;; attempt++) try {
|
|
666
|
+
return await within(send(), hostCallTimeoutMs, () => new KnowledgeImporterHostError("host call timed out"));
|
|
667
|
+
} catch (error) {
|
|
668
|
+
if (!isRetryable(error) || attempt >= maxRetries) throw error;
|
|
669
|
+
if (kind === "mutation" && stop) throw error;
|
|
670
|
+
await sleep(retryDelayMs(attempt), kind === "mutation" ? stopped : void 0);
|
|
671
|
+
if (kind === "mutation" && stop) throw error;
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
/**
|
|
675
|
+
* The last receipt said the host has settle work left. Unknown until a receipt arrives: settle
|
|
676
|
+
* work can be left from an earlier run, so a run that flushes nothing still sends one empty flush.
|
|
677
|
+
*/
|
|
678
|
+
let pending;
|
|
679
|
+
const refused = [];
|
|
680
|
+
let flushing = Promise.resolve();
|
|
681
|
+
/** `settle` sends an empty flush, which only runs the host's next settle slice. */
|
|
682
|
+
function flush(staged, settle = false) {
|
|
683
|
+
const ops = buffer;
|
|
684
|
+
buffer = [];
|
|
685
|
+
const next = flushing.then(async () => {
|
|
686
|
+
if (stop) throw stop;
|
|
687
|
+
if (ops.length === 0 && !staged && !settle) return;
|
|
688
|
+
const body = {
|
|
689
|
+
ops,
|
|
690
|
+
...staged ? { state: staged } : {}
|
|
691
|
+
};
|
|
692
|
+
const seq = lastSeq + 1;
|
|
693
|
+
const digest = await knowledgeImporterFlushDigest(body);
|
|
694
|
+
if (stop) throw stop;
|
|
695
|
+
const request = {
|
|
696
|
+
runId,
|
|
697
|
+
generation,
|
|
698
|
+
seq,
|
|
699
|
+
digest,
|
|
700
|
+
...body
|
|
701
|
+
};
|
|
702
|
+
unsettledSeq = seq;
|
|
703
|
+
try {
|
|
704
|
+
const receipt = await withRetries(() => host.flush(request), "mutation");
|
|
705
|
+
pending = receipt.pending === true;
|
|
706
|
+
refused.push(...receipt.refused.slice(0, MAX_RECEIPT_REFUSALS - refused.length));
|
|
707
|
+
} catch (error) {
|
|
708
|
+
if (!isRetryable(error)) unsettledSeq = void 0;
|
|
709
|
+
hostFailure = {
|
|
710
|
+
code: "importer_error",
|
|
711
|
+
retryable: isRetryable(error)
|
|
712
|
+
};
|
|
713
|
+
halt("host");
|
|
714
|
+
throw stop;
|
|
715
|
+
}
|
|
716
|
+
unsettledSeq = void 0;
|
|
717
|
+
lastSeq = seq;
|
|
718
|
+
if (staged) state = {
|
|
719
|
+
...state,
|
|
720
|
+
...staged
|
|
721
|
+
};
|
|
722
|
+
});
|
|
723
|
+
flushing = next.catch(() => {});
|
|
724
|
+
return next;
|
|
725
|
+
}
|
|
726
|
+
const push = async (op) => {
|
|
727
|
+
if (stop) throw stop;
|
|
728
|
+
buffer.push(op);
|
|
729
|
+
if (buffer.length >= bufferSize) await flush();
|
|
730
|
+
};
|
|
731
|
+
const finish = async (request) => {
|
|
732
|
+
const result = await finishRun(host, {
|
|
733
|
+
runId,
|
|
734
|
+
generation,
|
|
735
|
+
...request
|
|
736
|
+
}, lastSeq, unsettledSeq, (send) => withRetries(send, "finish"));
|
|
737
|
+
return "outcome" in result ? {
|
|
738
|
+
...result,
|
|
739
|
+
refused
|
|
740
|
+
} : result;
|
|
741
|
+
};
|
|
742
|
+
const binding = started.binding;
|
|
743
|
+
const configured = binding && options.importers.find((entry) => entry instanceof KnowledgeImporterBase && entry.binding.id === binding.id && entry.binding.importer === binding.importer);
|
|
744
|
+
const importerClass = binding && (configured ? configured.constructor : options.importers.find((entry) => typeof entry === "function" && entry.id === binding.importer));
|
|
745
|
+
if (!binding || !importerClass) return finish({
|
|
746
|
+
outcome: "failed",
|
|
747
|
+
backlog: false,
|
|
748
|
+
error: { code: "importer_missing_from_deploy" }
|
|
749
|
+
});
|
|
750
|
+
let importer;
|
|
751
|
+
let settings;
|
|
752
|
+
let credentials;
|
|
753
|
+
try {
|
|
754
|
+
importer = configured ?? new importerClass(binding);
|
|
755
|
+
settings = await importerClass.definition.parseSettings(binding.settings ?? {});
|
|
756
|
+
credentials = importerClass.definition.checkCredentials(binding.credentials ?? {});
|
|
757
|
+
} catch (error) {
|
|
758
|
+
if (error instanceof KnowledgeImporterSettingsError) return finish({
|
|
759
|
+
outcome: "failed",
|
|
760
|
+
backlog: false,
|
|
761
|
+
error: { code: "settings_invalid" }
|
|
762
|
+
});
|
|
763
|
+
if (error instanceof KnowledgeImporterCredentialsError) return finish({
|
|
764
|
+
outcome: "failed",
|
|
765
|
+
backlog: false,
|
|
766
|
+
error: { code: "credential_missing" }
|
|
767
|
+
});
|
|
768
|
+
await finish({
|
|
769
|
+
outcome: "failed",
|
|
770
|
+
backlog: false,
|
|
771
|
+
error: { code: "importer_error" }
|
|
772
|
+
}).catch(() => {});
|
|
773
|
+
throw error;
|
|
774
|
+
}
|
|
775
|
+
let backlog = false;
|
|
776
|
+
const fetchImpl = options.fetch ?? globalThis.fetch;
|
|
777
|
+
const ctx = {
|
|
778
|
+
signal: controller.signal,
|
|
779
|
+
binding: {
|
|
780
|
+
id: binding.id,
|
|
781
|
+
target: binding.target
|
|
782
|
+
},
|
|
783
|
+
settings,
|
|
784
|
+
credentials,
|
|
785
|
+
fetch: (input, init) => fetchImpl(input, {
|
|
786
|
+
...init,
|
|
787
|
+
signal: init?.signal ? AbortSignal.any([controller.signal, init.signal]) : controller.signal
|
|
788
|
+
}),
|
|
789
|
+
state: {
|
|
790
|
+
get: async (key) => state[key],
|
|
791
|
+
set: async (key, value) => {
|
|
792
|
+
if (stop) throw stop;
|
|
793
|
+
await flush({ [key]: value });
|
|
794
|
+
}
|
|
795
|
+
},
|
|
796
|
+
items: {
|
|
797
|
+
upsert: (item) => push({
|
|
798
|
+
op: "upsert",
|
|
799
|
+
item
|
|
800
|
+
}),
|
|
801
|
+
declare: (item) => push({
|
|
802
|
+
op: "declare",
|
|
803
|
+
item
|
|
804
|
+
}),
|
|
805
|
+
remove: (sourceId) => push({
|
|
806
|
+
op: "remove",
|
|
807
|
+
sourceId
|
|
808
|
+
})
|
|
809
|
+
},
|
|
810
|
+
reportBacklog: () => {
|
|
811
|
+
backlog = true;
|
|
812
|
+
}
|
|
813
|
+
};
|
|
814
|
+
let beating = false;
|
|
815
|
+
const heartbeat = setInterval(() => {
|
|
816
|
+
if (beating) return;
|
|
817
|
+
beating = true;
|
|
818
|
+
host.heartbeat(runId, generation).then(({ cancel }) => cancel && halt("canceled"), () => {}).finally(() => beating = false);
|
|
819
|
+
}, heartbeatMs);
|
|
820
|
+
const hardStop = setTimeout(() => halt("stopped"), budgetMs + graceMs);
|
|
821
|
+
let failure;
|
|
822
|
+
try {
|
|
823
|
+
for (let pass = 0; pass < maxPasses; pass++) {
|
|
824
|
+
backlog = false;
|
|
825
|
+
try {
|
|
826
|
+
await Promise.race([importer.import(ctx), stopped]);
|
|
827
|
+
if (!stop) await Promise.race([flush(), stopped]);
|
|
828
|
+
} catch (error) {
|
|
829
|
+
if (stop) break;
|
|
830
|
+
if (error instanceof KnowledgeImporterSourceError) failure = sourceError(error);
|
|
831
|
+
else if (error instanceof KnowledgeImporterHostError) failure = {
|
|
832
|
+
code: "importer_error",
|
|
833
|
+
retryable: true
|
|
834
|
+
};
|
|
835
|
+
else failure = { code: "importer_error" };
|
|
836
|
+
break;
|
|
837
|
+
}
|
|
838
|
+
if (stop || !backlog || Date.now() - startedAt >= budgetMs) break;
|
|
839
|
+
}
|
|
840
|
+
while (!stop && !failure && pending !== false && Date.now() - startedAt < budgetMs) try {
|
|
841
|
+
await Promise.race([flush(void 0, true), stopped]);
|
|
842
|
+
} catch {
|
|
843
|
+
break;
|
|
844
|
+
}
|
|
845
|
+
} finally {
|
|
846
|
+
clearInterval(heartbeat);
|
|
847
|
+
}
|
|
848
|
+
if (!stop || stop.reason !== "stopped") await Promise.race([flushing, deadlinePassed]);
|
|
849
|
+
clearTimeout(hardStop);
|
|
850
|
+
if (stop?.reason === "canceled") return finish({
|
|
851
|
+
outcome: "canceled",
|
|
852
|
+
backlog: false
|
|
853
|
+
});
|
|
854
|
+
if (stop?.reason === "stopped") return finish({
|
|
855
|
+
outcome: "failed",
|
|
856
|
+
backlog: false,
|
|
857
|
+
error: { code: "stopped" }
|
|
858
|
+
});
|
|
859
|
+
const error = stop?.reason === "host" ? hostFailure : failure;
|
|
860
|
+
if (error) return finish({
|
|
861
|
+
outcome: "failed",
|
|
862
|
+
backlog: false,
|
|
863
|
+
error
|
|
864
|
+
});
|
|
865
|
+
return finish({
|
|
866
|
+
outcome: "succeeded",
|
|
867
|
+
backlog
|
|
868
|
+
});
|
|
869
|
+
}
|
|
870
|
+
/**
|
|
871
|
+
* Records the end. A flush whose ack was lost may have committed, so the finish names the seq the
|
|
872
|
+
* host says it holds: the known seq, or the unsettled one when the host refuses the known one. The
|
|
873
|
+
* same request is resent after a lost ack; a host that stays unreachable leaves the run open for
|
|
874
|
+
* its liveness check, and the runner returns `unfinished`.
|
|
875
|
+
*/
|
|
876
|
+
async function finishRun(host, request, lastSeq, unsettledSeq, withRetries) {
|
|
877
|
+
const candidates = unsettledSeq === void 0 ? [lastSeq] : [lastSeq, unsettledSeq];
|
|
878
|
+
for (const seq of candidates) try {
|
|
879
|
+
return await withRetries(() => host.finishRun({
|
|
880
|
+
...request,
|
|
881
|
+
lastSeq: seq
|
|
882
|
+
}));
|
|
883
|
+
} catch (error) {
|
|
884
|
+
if (error instanceof KnowledgeImporterHostConflictError && error.code === "seq_mismatch") continue;
|
|
885
|
+
if (isRetryable(error)) return {
|
|
886
|
+
status: "unfinished",
|
|
887
|
+
runId: request.runId,
|
|
888
|
+
lastSeq: seq
|
|
889
|
+
};
|
|
890
|
+
throw error;
|
|
891
|
+
}
|
|
892
|
+
return {
|
|
893
|
+
status: "unfinished",
|
|
894
|
+
runId: request.runId,
|
|
895
|
+
lastSeq
|
|
896
|
+
};
|
|
897
|
+
}
|
|
898
|
+
// src/knowledge/importers/sink.ts
|
|
899
|
+
/**
|
|
900
|
+
* Applies one flush's ops to pages and the node map, on a transaction view. Pages are found by id
|
|
901
|
+
* through the node map: the binding tracks its anchor (the folder at its target) and the pages its
|
|
902
|
+
* nodes point at. A page already at a new item's path is taken over by that item's node, whoever
|
|
903
|
+
* wrote it, and kept as a stub rather than deleted when the item is removed.
|
|
904
|
+
*
|
|
905
|
+
* @internal
|
|
906
|
+
*/
|
|
907
|
+
/** The body a page keeps when its item is gone at the source but pages are still nested under it. */
|
|
908
|
+
const REMOVED_PARENT_BODY = "Removed from the source. Kept because pages are still nested under it.";
|
|
909
|
+
const REMOVED_BODIES = /* @__PURE__ */ new Set([
|
|
910
|
+
REMOVED_PARENT_BODY,
|
|
911
|
+
"Removed from the source. Kept because another importer writes under it.",
|
|
912
|
+
"Removed from the source. Kept because the page was here before the import."
|
|
913
|
+
]);
|
|
914
|
+
/** Heads the note that keeps the body a page had before an importer took it over. */
|
|
915
|
+
const ORIGINAL_BODY_NOTE = "The body this page had before an importer took it over:\n\n";
|
|
916
|
+
/** Every heading a kept-body note has been written with, newest first; removal recognizes them all. */
|
|
917
|
+
const ORIGINAL_BODY_NOTE_HEADINGS = [ORIGINAL_BODY_NOTE, "Written by hand before an importer took over this page:\n\n"];
|
|
918
|
+
/**
|
|
919
|
+
* Kept-body notes on a page have ids starting with this. Each takeover writes a new one and removes
|
|
920
|
+
* the earlier, so removal finds the body from the latest takeover. Notes written before takeovers
|
|
921
|
+
* had their own id used the prefix alone.
|
|
922
|
+
*/
|
|
923
|
+
const originalBodyNotePrefix = (pageId) => `knowledge-import-original:${pageId}`;
|
|
924
|
+
/**
|
|
925
|
+
* Host state key another binding's flush sets, to a fresh value, when it queues link repairs on
|
|
926
|
+
* this binding's pages. Those pages may sort before this binding's saved settle cursor, so its next
|
|
927
|
+
* slice starts the pass over when the value differs from {@link KNOWLEDGE_IMPORT_SETTLE_SEEN_KEY}.
|
|
928
|
+
* The binding's own flushes never write this key, so a flush that read the state earlier can't undo it.
|
|
929
|
+
*/
|
|
930
|
+
const KNOWLEDGE_IMPORT_SETTLE_RESTART_KEY = "mastra:settle:restart";
|
|
931
|
+
/** The {@link KNOWLEDGE_IMPORT_SETTLE_RESTART_KEY} value the binding's settling last started over for. */
|
|
932
|
+
const KNOWLEDGE_IMPORT_SETTLE_SEEN_KEY = "mastra:settle:seen";
|
|
933
|
+
/** An unresolved link as the node map lists it, with its label. */
|
|
934
|
+
const encodeLink = (link) => JSON.stringify([link.sourceId, link.rel]);
|
|
935
|
+
const LINKS_HEADING = "Links:";
|
|
936
|
+
/**
|
|
937
|
+
* The links section for these lines, or null for none. Lines are sorted, so a body written in one
|
|
938
|
+
* flush and one completed by a later settle match.
|
|
939
|
+
*/
|
|
940
|
+
const linkSection = (lines) => {
|
|
941
|
+
const sorted = [...new Set(lines)].sort();
|
|
942
|
+
return sorted.length ? `${LINKS_HEADING}\n${sorted.join("\n")}` : null;
|
|
943
|
+
};
|
|
944
|
+
const withSection = (text, section) => section === null ? text : text ? `${text}\n\n${section}` : section;
|
|
945
|
+
/**
|
|
946
|
+
* The source's own text in a body the sink wrote with `section` at its end, byte for byte; null when
|
|
947
|
+
* the body no longer ends with that section, because someone edited the page since.
|
|
948
|
+
*/
|
|
949
|
+
const ownText = (body, section) => {
|
|
950
|
+
if (section === null) return body;
|
|
951
|
+
if (body === section) return "";
|
|
952
|
+
return body.endsWith(`\n\n${section}`) ? body.slice(0, body.length - section.length - 2) : null;
|
|
953
|
+
};
|
|
954
|
+
/** A per-item refusal: its savepoint rolls back and the flush goes on. */
|
|
955
|
+
var KnowledgeImportRefusalError = class extends Error {
|
|
956
|
+
reason;
|
|
957
|
+
constructor(reason) {
|
|
958
|
+
super(`Knowledge import op refused: ${reason}`);
|
|
959
|
+
this.reason = reason;
|
|
960
|
+
this.name = "KnowledgeImportRefusalError";
|
|
961
|
+
}
|
|
962
|
+
};
|
|
963
|
+
/** Splits `<scope>#<path>`; throws on a target the sink can't own. */
|
|
964
|
+
function parseKnowledgeImportTarget(target) {
|
|
965
|
+
const hash = target.indexOf("#");
|
|
966
|
+
const scope = hash < 0 ? "" : target.slice(0, hash);
|
|
967
|
+
const path = hash < 0 ? [] : target.slice(hash + 1).split("/");
|
|
968
|
+
if (!scope || path.length === 0 || path.some((key) => !key || /[#%]/.test(key))) throw new TypeError(`Importer target "${target}" must be <scope>#<path> with non-empty keys.`);
|
|
969
|
+
return {
|
|
970
|
+
scope,
|
|
971
|
+
path
|
|
972
|
+
};
|
|
973
|
+
}
|
|
974
|
+
/**
|
|
975
|
+
* A reversible page key for a source ID: `/`, `#`, `%`, `:` and `~` become `~` and two hex digits,
|
|
976
|
+
* and an empty ID is `~`. As Platform's sink, so imported paths match.
|
|
977
|
+
*/
|
|
978
|
+
function knowledgeImportKey(sourceId) {
|
|
979
|
+
if (!sourceId) return "~";
|
|
980
|
+
return sourceId.replace(/[/#%:~]/g, (char) => `~${char.charCodeAt(0).toString(16).toUpperCase()}`);
|
|
981
|
+
}
|
|
982
|
+
const live = (page) => !!page && !page.deletedAt && !page.mergedInto;
|
|
983
|
+
/** Core errors that mean "this op can't land here", by name: an adapter may carry its own core copy. */
|
|
984
|
+
function refusalFor(error) {
|
|
985
|
+
if (error instanceof KnowledgeImportRefusalError) return error.reason;
|
|
986
|
+
switch (error?.name) {
|
|
987
|
+
case "KnowledgePageKeyConflictError": return "occupied";
|
|
988
|
+
case "KnowledgeMoveTooLargeError":
|
|
989
|
+
case "KnowledgeConflictError":
|
|
990
|
+
case "KnowledgeNotFoundError":
|
|
991
|
+
case "KnowledgePageHasChildrenError": return "conflict";
|
|
992
|
+
case "KnowledgePageDepthError": return "invalid";
|
|
993
|
+
default: return;
|
|
994
|
+
}
|
|
995
|
+
}
|
|
996
|
+
/**
|
|
997
|
+
* Link-index work for a page the flush just wrote. Unlike host writes, a failure isn't logged and
|
|
998
|
+
* skipped: it rolls the whole flush back (no pages, nodes or receipt), and the runner resends it.
|
|
999
|
+
* Only a store without a link index, and a refresh that landed but stopped at its cap (more than 100
|
|
1000
|
+
* linking pages, or more than 99 pages sharing a name), are let through: resending would stop at
|
|
1001
|
+
* the same cap every time.
|
|
1002
|
+
*/
|
|
1003
|
+
async function syncLinks(work) {
|
|
1004
|
+
try {
|
|
1005
|
+
await work();
|
|
1006
|
+
} catch (error) {
|
|
1007
|
+
if (error instanceof require_run_registry.KnowledgeUnsupportedCapabilityError || error instanceof require_run_registry.KnowledgeLinkRefreshIncompleteError) return;
|
|
1008
|
+
throw error;
|
|
1009
|
+
}
|
|
1010
|
+
}
|
|
1011
|
+
/** The ops as the sink applies them: the last op per sourceId, upserts parent-first, then removes. */
|
|
1012
|
+
function order(ops) {
|
|
1013
|
+
const last = /* @__PURE__ */ new Map();
|
|
1014
|
+
for (const op of ops) {
|
|
1015
|
+
const id = op.op === "remove" ? op.sourceId : op.item.sourceId;
|
|
1016
|
+
const before = last.get(id);
|
|
1017
|
+
if (op.op === "declare" && before?.op === "upsert") {
|
|
1018
|
+
last.delete(id);
|
|
1019
|
+
last.set(id, {
|
|
1020
|
+
op: "upsert",
|
|
1021
|
+
item: {
|
|
1022
|
+
...before.item,
|
|
1023
|
+
...op.item
|
|
1024
|
+
}
|
|
1025
|
+
});
|
|
1026
|
+
continue;
|
|
1027
|
+
}
|
|
1028
|
+
last.delete(id);
|
|
1029
|
+
last.set(id, op);
|
|
1030
|
+
}
|
|
1031
|
+
const writes = [...last.values()].filter((op) => op.op !== "remove");
|
|
1032
|
+
const removes = [...last.values()].filter((op) => op.op === "remove");
|
|
1033
|
+
const pending = new Map(writes.map((op) => [op.item.sourceId, op]));
|
|
1034
|
+
const sorted = [];
|
|
1035
|
+
const visit = (op, seen) => {
|
|
1036
|
+
if (!pending.has(op.item.sourceId) || seen.has(op.item.sourceId)) return;
|
|
1037
|
+
seen.add(op.item.sourceId);
|
|
1038
|
+
for (const dep of [op.item.parent, op.item.fallbackParent]) {
|
|
1039
|
+
const parent = dep ? pending.get(dep) : void 0;
|
|
1040
|
+
if (parent) visit(parent, seen);
|
|
1041
|
+
}
|
|
1042
|
+
pending.delete(op.item.sourceId);
|
|
1043
|
+
sorted.push(op);
|
|
1044
|
+
};
|
|
1045
|
+
for (const op of writes) visit(op, /* @__PURE__ */ new Set());
|
|
1046
|
+
return [...sorted, ...removes];
|
|
1047
|
+
}
|
|
1048
|
+
async function applyKnowledgeImportFlush(input) {
|
|
1049
|
+
const { storage, importers, binding, scope, provenance } = input;
|
|
1050
|
+
const target = parseKnowledgeImportTarget(binding.target);
|
|
1051
|
+
const result = {
|
|
1052
|
+
counts: {
|
|
1053
|
+
created: 0,
|
|
1054
|
+
updated: 0,
|
|
1055
|
+
unchanged: 0,
|
|
1056
|
+
moved: 0,
|
|
1057
|
+
removed: 0,
|
|
1058
|
+
stubbed: 0
|
|
1059
|
+
},
|
|
1060
|
+
refused: [],
|
|
1061
|
+
changes: [],
|
|
1062
|
+
embeds: [],
|
|
1063
|
+
applied: false
|
|
1064
|
+
};
|
|
1065
|
+
const ops = order(input.ops);
|
|
1066
|
+
if (ops.length === 0 && !(input.settle && binding.anchorPageId)) {
|
|
1067
|
+
if (input.settle) result.settle = {
|
|
1068
|
+
pending: false,
|
|
1069
|
+
cursor: null,
|
|
1070
|
+
settled: 0,
|
|
1071
|
+
fromStart: false
|
|
1072
|
+
};
|
|
1073
|
+
return result;
|
|
1074
|
+
}
|
|
1075
|
+
const keyPath = async (page) => {
|
|
1076
|
+
const keys = [];
|
|
1077
|
+
const ids = [];
|
|
1078
|
+
let at = page;
|
|
1079
|
+
while (at && !at.isScope) {
|
|
1080
|
+
if (!live(at) || at.key === void 0) return null;
|
|
1081
|
+
keys.unshift(at.key);
|
|
1082
|
+
ids.unshift(at.id);
|
|
1083
|
+
at = at.parentId ? await storage.getPage({
|
|
1084
|
+
id: at.parentId,
|
|
1085
|
+
read: "all"
|
|
1086
|
+
}) : null;
|
|
1087
|
+
}
|
|
1088
|
+
return at?.id === scope.id ? {
|
|
1089
|
+
keys,
|
|
1090
|
+
ids
|
|
1091
|
+
} : null;
|
|
1092
|
+
};
|
|
1093
|
+
const sameKeys = (a, b) => a.length === b.length && a.every((key, i) => key === b[i]);
|
|
1094
|
+
/**
|
|
1095
|
+
* Marks another binding's pages that link to `targets` for repair, and has its next settle slice
|
|
1096
|
+
* start the pass over: they may sort before its saved cursor.
|
|
1097
|
+
*/
|
|
1098
|
+
const queueRepairs = async (bindingId, targets) => {
|
|
1099
|
+
await importers.markLinkingNodesUnsettled(bindingId, targets);
|
|
1100
|
+
if (bindingId !== binding.id) await importers.setState(bindingId, { [KNOWLEDGE_IMPORT_SETTLE_RESTART_KEY]: (0, crypto.randomUUID)() });
|
|
1101
|
+
};
|
|
1102
|
+
/**
|
|
1103
|
+
* Stops another binding tracking a page as its item, so this one can take it over: its node is
|
|
1104
|
+
* dropped and that binding's links to it are marked for repair. Says whether it was an item. A
|
|
1105
|
+
* page that is another binding's folder stays its folder: folders are shared, so taking one over
|
|
1106
|
+
* never stops that binding writing or removing under it.
|
|
1107
|
+
*/
|
|
1108
|
+
const release = async (pageId) => {
|
|
1109
|
+
const node = await importers.getNodeByPage(pageId);
|
|
1110
|
+
if (!node) return false;
|
|
1111
|
+
await queueRepairs(node.bindingId, [node.sourceId]);
|
|
1112
|
+
await importers.deleteNode(node.bindingId, node.sourceId);
|
|
1113
|
+
return true;
|
|
1114
|
+
};
|
|
1115
|
+
const anchor = await (async () => {
|
|
1116
|
+
if (binding.anchorPageId) {
|
|
1117
|
+
const page = await storage.getPage({
|
|
1118
|
+
id: binding.anchorPageId,
|
|
1119
|
+
read: "all"
|
|
1120
|
+
});
|
|
1121
|
+
const path = live(page) ? await keyPath(page) : null;
|
|
1122
|
+
if (page && path) {
|
|
1123
|
+
await storage.lockPages(path.ids);
|
|
1124
|
+
const fresh = await storage.getPage({
|
|
1125
|
+
id: page.id,
|
|
1126
|
+
read: "all"
|
|
1127
|
+
});
|
|
1128
|
+
const freshPath = live(fresh) ? await keyPath(fresh) : null;
|
|
1129
|
+
if (fresh && freshPath) return {
|
|
1130
|
+
page: fresh,
|
|
1131
|
+
keys: freshPath.keys
|
|
1132
|
+
};
|
|
1133
|
+
}
|
|
1134
|
+
if (!await importers.setBindingAnchor({
|
|
1135
|
+
bindingId: binding.id,
|
|
1136
|
+
expected: binding.anchorPageId,
|
|
1137
|
+
pageId: null
|
|
1138
|
+
})) throw new KnowledgeImportRefusalError("conflict");
|
|
1139
|
+
}
|
|
1140
|
+
if (ops.every((op) => op.op === "remove")) return null;
|
|
1141
|
+
return storage.transaction(async (tx) => {
|
|
1142
|
+
const chain = async () => {
|
|
1143
|
+
const pages = [];
|
|
1144
|
+
for (let depth = 1; depth <= target.path.length; depth++) {
|
|
1145
|
+
const page = await tx.getPageByPath({
|
|
1146
|
+
scopeId: scope.id,
|
|
1147
|
+
path: target.path.slice(0, depth),
|
|
1148
|
+
read: "all"
|
|
1149
|
+
});
|
|
1150
|
+
if (!page) break;
|
|
1151
|
+
pages.push(page);
|
|
1152
|
+
}
|
|
1153
|
+
return pages;
|
|
1154
|
+
};
|
|
1155
|
+
for (let round = 0; round < 3; round++) {
|
|
1156
|
+
const before = await chain();
|
|
1157
|
+
await tx.lockPages([scope.id, ...before.map((page) => page.id)]);
|
|
1158
|
+
const locked = await chain();
|
|
1159
|
+
if (locked.length !== before.length || locked.some((page, i) => page.id !== before[i].id)) continue;
|
|
1160
|
+
let parent = locked.at(-1) ?? scope;
|
|
1161
|
+
if (locked.length === target.path.length) {
|
|
1162
|
+
const own = await importers.getNodeByPage(parent.id);
|
|
1163
|
+
if (own?.bindingId === binding.id) await importers.deleteNode(binding.id, own.sourceId);
|
|
1164
|
+
}
|
|
1165
|
+
for (let depth = locked.length + 1; depth <= target.path.length; depth++) {
|
|
1166
|
+
const key = target.path[depth - 1];
|
|
1167
|
+
parent = await tx.createPage({
|
|
1168
|
+
parentId: parent.id,
|
|
1169
|
+
key,
|
|
1170
|
+
name: key,
|
|
1171
|
+
provenance
|
|
1172
|
+
});
|
|
1173
|
+
result.embeds.push({
|
|
1174
|
+
kind: "index",
|
|
1175
|
+
pageId: parent.id
|
|
1176
|
+
});
|
|
1177
|
+
}
|
|
1178
|
+
if (!await importers.setBindingAnchor({
|
|
1179
|
+
bindingId: binding.id,
|
|
1180
|
+
expected: null,
|
|
1181
|
+
pageId: parent.id
|
|
1182
|
+
})) throw new KnowledgeImportRefusalError("conflict");
|
|
1183
|
+
result.applied = true;
|
|
1184
|
+
return {
|
|
1185
|
+
page: parent,
|
|
1186
|
+
keys: target.path
|
|
1187
|
+
};
|
|
1188
|
+
}
|
|
1189
|
+
throw new KnowledgeImportRefusalError("conflict");
|
|
1190
|
+
});
|
|
1191
|
+
})().catch((error) => {
|
|
1192
|
+
const reason = refusalFor(error);
|
|
1193
|
+
if (!reason) throw error;
|
|
1194
|
+
return reason;
|
|
1195
|
+
});
|
|
1196
|
+
if (typeof anchor === "string") {
|
|
1197
|
+
for (const op of ops) result.refused.push({
|
|
1198
|
+
sourceId: op.op === "remove" ? op.sourceId : op.item.sourceId,
|
|
1199
|
+
reason: anchor
|
|
1200
|
+
});
|
|
1201
|
+
return result;
|
|
1202
|
+
}
|
|
1203
|
+
const anchorPath = anchor?.keys ?? [];
|
|
1204
|
+
/**
|
|
1205
|
+
* A page this binding owns, checked after locking: live, in the target's scope, mapped back to the
|
|
1206
|
+
* node. A person may have moved it out of the anchor, under anyone's pages: it is still the
|
|
1207
|
+
* binding's and is updated where they put it (`outside`).
|
|
1208
|
+
*/
|
|
1209
|
+
const owned = async (pageId, sourceId) => {
|
|
1210
|
+
const read = async () => {
|
|
1211
|
+
const page = await storage.getPage({
|
|
1212
|
+
id: pageId,
|
|
1213
|
+
read: "all"
|
|
1214
|
+
});
|
|
1215
|
+
const path = live(page) ? await keyPath(page) : null;
|
|
1216
|
+
return page && path ? {
|
|
1217
|
+
page,
|
|
1218
|
+
path
|
|
1219
|
+
} : null;
|
|
1220
|
+
};
|
|
1221
|
+
const before = await read();
|
|
1222
|
+
if (!before) throw new KnowledgeImportRefusalError("conflict");
|
|
1223
|
+
await storage.lockPages(before.path.ids);
|
|
1224
|
+
const after = await read();
|
|
1225
|
+
if (!after) throw new KnowledgeImportRefusalError("conflict");
|
|
1226
|
+
const outside = !anchor || !(sameKeys(after.path.keys.slice(0, anchorPath.length), anchorPath) && after.path.ids.includes(anchor.page.id));
|
|
1227
|
+
if (after.page.id !== anchor?.page.id) {
|
|
1228
|
+
const node = await importers.getNodeByPage(after.page.id);
|
|
1229
|
+
if (!node || node.bindingId !== binding.id || sourceId !== void 0 && node.sourceId !== sourceId) throw new KnowledgeImportRefusalError("conflict");
|
|
1230
|
+
}
|
|
1231
|
+
return {
|
|
1232
|
+
page: after.page,
|
|
1233
|
+
keys: after.path.keys,
|
|
1234
|
+
outside
|
|
1235
|
+
};
|
|
1236
|
+
};
|
|
1237
|
+
const nodeOf = async (sourceId) => sourceId ? importers.getNode(binding.id, sourceId) : null;
|
|
1238
|
+
const gone = async (node) => {
|
|
1239
|
+
const page = await storage.getPage({
|
|
1240
|
+
id: node.pageId,
|
|
1241
|
+
read: "all"
|
|
1242
|
+
});
|
|
1243
|
+
return !page || !!page.deletedAt && !page.mergedInto || live(page) && page.scopeId !== scope.id;
|
|
1244
|
+
};
|
|
1245
|
+
/**
|
|
1246
|
+
* Drops the node of a page that is gone, so its item is written again as new. Pages that linked to
|
|
1247
|
+
* it still name its old path: this binding's linking items are marked unsettled so a settle slice
|
|
1248
|
+
* renders their links section from wherever the item lands, and Knowledge's own link index is
|
|
1249
|
+
* refreshed for the old page's refs. Keep that refresh: the sink's own removal does the same, and
|
|
1250
|
+
* a page deleted without going through `removePage` would otherwise leave stale index rows.
|
|
1251
|
+
*/
|
|
1252
|
+
/** A page's live kept-body notes, oldest first. */
|
|
1253
|
+
const keptBodyNotes = async (pageId) => {
|
|
1254
|
+
const prefix = originalBodyNotePrefix(pageId);
|
|
1255
|
+
const kept = [];
|
|
1256
|
+
let cursor;
|
|
1257
|
+
do {
|
|
1258
|
+
const out = await storage.listNotes({
|
|
1259
|
+
pageId,
|
|
1260
|
+
read: "all",
|
|
1261
|
+
...cursor ? { cursor } : {}
|
|
1262
|
+
});
|
|
1263
|
+
kept.push(...out.notes.filter((note) => note.id === prefix || note.id.startsWith(`${prefix}:`)));
|
|
1264
|
+
cursor = out.nextCursor;
|
|
1265
|
+
} while (cursor);
|
|
1266
|
+
return kept;
|
|
1267
|
+
};
|
|
1268
|
+
/**
|
|
1269
|
+
* Saves the body a page has as it is taken over, in place of any earlier takeover's. An empty body
|
|
1270
|
+
* keeps no note, so a removal stubs the page rather than bringing back a body a person cleared.
|
|
1271
|
+
*/
|
|
1272
|
+
const keepBody = async (pageId, body) => {
|
|
1273
|
+
for (const earlier of await keptBodyNotes(pageId)) await storage.removeNote({
|
|
1274
|
+
id: earlier.id,
|
|
1275
|
+
deletedBy: provenance.author,
|
|
1276
|
+
provenance
|
|
1277
|
+
});
|
|
1278
|
+
if (!body) return;
|
|
1279
|
+
await storage.addNote({
|
|
1280
|
+
id: `${originalBodyNotePrefix(pageId)}:${(0, crypto.randomUUID)()}`,
|
|
1281
|
+
pageId,
|
|
1282
|
+
text: ORIGINAL_BODY_NOTE + body,
|
|
1283
|
+
stampScopeIds: [scope.id],
|
|
1284
|
+
mentions: [],
|
|
1285
|
+
provenance
|
|
1286
|
+
});
|
|
1287
|
+
};
|
|
1288
|
+
const forget = async (node) => {
|
|
1289
|
+
const old = await storage.getPage({
|
|
1290
|
+
id: node.pageId,
|
|
1291
|
+
read: "all"
|
|
1292
|
+
});
|
|
1293
|
+
await importers.markLinkingNodesUnsettled(binding.id, [node.sourceId]);
|
|
1294
|
+
await importers.deleteNode(binding.id, node.sourceId);
|
|
1295
|
+
if (old) await syncLinks(() => require_run_registry.refreshKnowledgeLinksTo(storage, [old]));
|
|
1296
|
+
};
|
|
1297
|
+
const liveNodeOf = async (sourceId) => {
|
|
1298
|
+
const node = await nodeOf(sourceId);
|
|
1299
|
+
return node && !await gone(node) ? node : null;
|
|
1300
|
+
};
|
|
1301
|
+
const ref = (keys) => `${target.scope}#${keys.join("/")}`;
|
|
1302
|
+
const linkLine = async (link) => {
|
|
1303
|
+
const node = await importers.getNode(binding.id, link.sourceId);
|
|
1304
|
+
const page = node ? await storage.getPage({
|
|
1305
|
+
id: node.pageId,
|
|
1306
|
+
read: "all"
|
|
1307
|
+
}) : null;
|
|
1308
|
+
const path = live(page) ? await keyPath(page) : null;
|
|
1309
|
+
return path ? `- ${link.rel ? `${link.rel}: ` : ""}[[${ref(path.keys)}]]` : null;
|
|
1310
|
+
};
|
|
1311
|
+
const renderLinks = async (links) => {
|
|
1312
|
+
const lines = [];
|
|
1313
|
+
const unresolved = [];
|
|
1314
|
+
for (const link of links) {
|
|
1315
|
+
const line = await linkLine(link);
|
|
1316
|
+
if (line) lines.push(line);
|
|
1317
|
+
else unresolved.push(encodeLink(link));
|
|
1318
|
+
}
|
|
1319
|
+
return {
|
|
1320
|
+
section: linkSection(lines),
|
|
1321
|
+
unresolved
|
|
1322
|
+
};
|
|
1323
|
+
};
|
|
1324
|
+
const renderBody = async (item) => {
|
|
1325
|
+
const links = (item.links ?? []).map((link) => ({
|
|
1326
|
+
sourceId: link.sourceId,
|
|
1327
|
+
rel: link.rel ?? null
|
|
1328
|
+
}));
|
|
1329
|
+
const { section, unresolved } = await renderLinks(links);
|
|
1330
|
+
return {
|
|
1331
|
+
body: withSection(item.body.trim(), section),
|
|
1332
|
+
links,
|
|
1333
|
+
section,
|
|
1334
|
+
unresolved
|
|
1335
|
+
};
|
|
1336
|
+
};
|
|
1337
|
+
/**
|
|
1338
|
+
* Writes a node's links section again from where its targets are now. Only the section the sink
|
|
1339
|
+
* wrote is replaced; the source's text before it stays byte for byte. A page edited past that
|
|
1340
|
+
* section is left as it is, with nothing left waiting, until the source sends it again.
|
|
1341
|
+
*/
|
|
1342
|
+
const relink = async (node, current) => {
|
|
1343
|
+
const text = ownText(current.body ?? "", node.linkSection);
|
|
1344
|
+
if (text === null) return {
|
|
1345
|
+
page: current,
|
|
1346
|
+
changed: false,
|
|
1347
|
+
section: node.linkSection,
|
|
1348
|
+
unresolved: []
|
|
1349
|
+
};
|
|
1350
|
+
const { section, unresolved } = await renderLinks(node.links);
|
|
1351
|
+
const body = withSection(text, section);
|
|
1352
|
+
if (body === (current.body ?? "")) return {
|
|
1353
|
+
page: current,
|
|
1354
|
+
changed: false,
|
|
1355
|
+
section,
|
|
1356
|
+
unresolved
|
|
1357
|
+
};
|
|
1358
|
+
const page = await storage.updatePage({
|
|
1359
|
+
id: current.id,
|
|
1360
|
+
expectedVersion: current.version,
|
|
1361
|
+
body,
|
|
1362
|
+
provenance
|
|
1363
|
+
});
|
|
1364
|
+
await syncLinks(() => require_run_registry.syncKnowledgePageBodyLinks(storage, page));
|
|
1365
|
+
return {
|
|
1366
|
+
page,
|
|
1367
|
+
changed: true,
|
|
1368
|
+
section,
|
|
1369
|
+
unresolved
|
|
1370
|
+
};
|
|
1371
|
+
};
|
|
1372
|
+
const misplacedAt = async (node, page, outside) => {
|
|
1373
|
+
if (!node.parentSourceId || outside) return false;
|
|
1374
|
+
const parent = await nodeOf(node.parentSourceId);
|
|
1375
|
+
return !parent || page.parentId !== parent.pageId;
|
|
1376
|
+
};
|
|
1377
|
+
/**
|
|
1378
|
+
* Moves an owned page, `self`'s, under `parentId`, then rewrites the links sections of this
|
|
1379
|
+
* binding's pages that link to it or to an imported page in its subtree. Generated links are
|
|
1380
|
+
* paths, so without this a linking page that isn't sent again would keep pointing at where they
|
|
1381
|
+
* were. Other bindings' pages can move with the subtree too: their linking pages are marked
|
|
1382
|
+
* unsettled, one statement per binding, and each binding's next settle slice rewrites them. Of
|
|
1383
|
+
* this binding's, all are marked unsettled in one statement; up to
|
|
1384
|
+
* {@link MAX_KNOWLEDGE_LINK_REFRESH_SOURCES} are rewritten here and the rest by the settle slices
|
|
1385
|
+
* that follow. `self` is left to the caller, which writes its body anyway. Returns the moved page
|
|
1386
|
+
* and the pages it rewrote; the caller counts them once its op lands.
|
|
1387
|
+
*/
|
|
1388
|
+
let deferredLinkers = false;
|
|
1389
|
+
const moveOwned = async (self, page, parent) => {
|
|
1390
|
+
const targets = [];
|
|
1391
|
+
const othersTargets = /* @__PURE__ */ new Map();
|
|
1392
|
+
await storage.lockSubtree(page.id);
|
|
1393
|
+
for (const p of await require_run_registry.knowledgeSubtree(storage, page)) {
|
|
1394
|
+
const node = await importers.getNodeByPage(p.id);
|
|
1395
|
+
if (!node) continue;
|
|
1396
|
+
if (node.bindingId === binding.id) targets.push(node.sourceId);
|
|
1397
|
+
else othersTargets.set(node.bindingId, [...othersTargets.get(node.bindingId) ?? [], node.sourceId]);
|
|
1398
|
+
}
|
|
1399
|
+
const moved = await storage.movePage({
|
|
1400
|
+
id: page.id,
|
|
1401
|
+
expectedVersion: page.version,
|
|
1402
|
+
parentId: parent.page.id,
|
|
1403
|
+
provenance
|
|
1404
|
+
});
|
|
1405
|
+
const keys = [...parent.keys, moved.key];
|
|
1406
|
+
const relinked = [];
|
|
1407
|
+
for (const [other, theirs] of othersTargets) await queueRepairs(other, theirs);
|
|
1408
|
+
await importers.markLinkingNodesUnsettled(binding.id, targets);
|
|
1409
|
+
const linking = await importers.listLinkingNodes(binding.id, targets, { limit: 101 });
|
|
1410
|
+
if (linking.next || linking.items.filter((id) => id !== self).length > 100) deferredLinkers = true;
|
|
1411
|
+
for (const sourceId of linking.items.filter((id) => id !== self).slice(0, 100)) {
|
|
1412
|
+
const node = await importers.getNode(binding.id, sourceId);
|
|
1413
|
+
if (!node) continue;
|
|
1414
|
+
let current;
|
|
1415
|
+
try {
|
|
1416
|
+
current = await owned(node.pageId, sourceId);
|
|
1417
|
+
} catch (error) {
|
|
1418
|
+
if (!refusalFor(error)) throw error;
|
|
1419
|
+
deferredLinkers = true;
|
|
1420
|
+
continue;
|
|
1421
|
+
}
|
|
1422
|
+
const out = await relink(node, current.page);
|
|
1423
|
+
await importers.saveNode({
|
|
1424
|
+
...node,
|
|
1425
|
+
linkSection: out.section,
|
|
1426
|
+
unresolvedLinks: out.unresolved,
|
|
1427
|
+
unsettled: await misplacedAt(node, out.page, current.outside) || out.unresolved.length > 0
|
|
1428
|
+
});
|
|
1429
|
+
if (out.changed) relinked.push({
|
|
1430
|
+
sourceId,
|
|
1431
|
+
page: out.page,
|
|
1432
|
+
keys: current.keys
|
|
1433
|
+
});
|
|
1434
|
+
}
|
|
1435
|
+
return {
|
|
1436
|
+
page: moved,
|
|
1437
|
+
keys,
|
|
1438
|
+
relinked
|
|
1439
|
+
};
|
|
1440
|
+
};
|
|
1441
|
+
const recordRelinked = (relinked, embeds) => {
|
|
1442
|
+
for (const { sourceId, page, keys } of relinked) {
|
|
1443
|
+
result.applied = true;
|
|
1444
|
+
result.counts.updated++;
|
|
1445
|
+
embeds.push({
|
|
1446
|
+
kind: "index",
|
|
1447
|
+
pageId: page.id
|
|
1448
|
+
});
|
|
1449
|
+
result.changes.push({
|
|
1450
|
+
sourceId,
|
|
1451
|
+
pageId: page.id,
|
|
1452
|
+
change: "updated",
|
|
1453
|
+
title: page.name,
|
|
1454
|
+
path: ref(keys)
|
|
1455
|
+
});
|
|
1456
|
+
}
|
|
1457
|
+
};
|
|
1458
|
+
const write = async (item, hasBody) => {
|
|
1459
|
+
let existing = await importers.getNode(binding.id, item.sourceId);
|
|
1460
|
+
if (existing && await gone(existing)) {
|
|
1461
|
+
await forget(existing);
|
|
1462
|
+
existing = null;
|
|
1463
|
+
}
|
|
1464
|
+
const sourceParent = await liveNodeOf(item.parent);
|
|
1465
|
+
const misplaced = !!item.parent && !sourceParent;
|
|
1466
|
+
const parentNode = sourceParent ?? await liveNodeOf(item.fallbackParent);
|
|
1467
|
+
const destination = parentNode ? await owned(parentNode.pageId, parentNode.sourceId) : anchor;
|
|
1468
|
+
if (existing && destination.page.id === existing.pageId) throw new KnowledgeImportRefusalError("invalid");
|
|
1469
|
+
let rendered = hasBody ? await renderBody(item) : void 0;
|
|
1470
|
+
let fields = {
|
|
1471
|
+
name: item.title,
|
|
1472
|
+
...item.description !== void 0 ? { description: item.description } : {},
|
|
1473
|
+
...rendered ? { body: rendered.body } : {}
|
|
1474
|
+
};
|
|
1475
|
+
const key = knowledgeImportKey(item.sourceId);
|
|
1476
|
+
let page;
|
|
1477
|
+
let change;
|
|
1478
|
+
let moved = false;
|
|
1479
|
+
let renamed = false;
|
|
1480
|
+
let relinked = [];
|
|
1481
|
+
let rewrote = false;
|
|
1482
|
+
let adopted = existing?.adopted ?? false;
|
|
1483
|
+
const held = existing ? null : await storage.getPageByPath({
|
|
1484
|
+
scopeId: scope.id,
|
|
1485
|
+
path: [...destination.keys, key],
|
|
1486
|
+
read: "all"
|
|
1487
|
+
});
|
|
1488
|
+
if (held) {
|
|
1489
|
+
await storage.lockPages([held.id]);
|
|
1490
|
+
const fresh = await storage.getPage({
|
|
1491
|
+
id: held.id,
|
|
1492
|
+
read: "all"
|
|
1493
|
+
});
|
|
1494
|
+
if (!live(fresh) || fresh.parentId !== destination.page.id || fresh.key !== key) throw new KnowledgeImportRefusalError("occupied");
|
|
1495
|
+
const imported = await release(fresh.id);
|
|
1496
|
+
renamed = fields.name !== fresh.name;
|
|
1497
|
+
if (!imported) await keepBody(fresh.id, fresh.body ?? "");
|
|
1498
|
+
page = await storage.updatePage({
|
|
1499
|
+
id: fresh.id,
|
|
1500
|
+
expectedVersion: fresh.version,
|
|
1501
|
+
...fields,
|
|
1502
|
+
provenance
|
|
1503
|
+
});
|
|
1504
|
+
change = "updated";
|
|
1505
|
+
adopted = true;
|
|
1506
|
+
} else if (!existing) {
|
|
1507
|
+
page = await storage.createPage({
|
|
1508
|
+
parentId: destination.page.id,
|
|
1509
|
+
key,
|
|
1510
|
+
...fields,
|
|
1511
|
+
body: fields.body ?? "",
|
|
1512
|
+
provenance
|
|
1513
|
+
});
|
|
1514
|
+
change = "created";
|
|
1515
|
+
} else {
|
|
1516
|
+
const current = await owned(existing.pageId, item.sourceId);
|
|
1517
|
+
page = current.page;
|
|
1518
|
+
if (existing.stub && existing.adopted && !REMOVED_BODIES.has(page.body ?? "")) await keepBody(page.id, page.body ?? "");
|
|
1519
|
+
if (!current.outside && page.parentId !== destination.page.id) {
|
|
1520
|
+
if (destination.keys.length > current.keys.length && sameKeys(destination.keys.slice(0, current.keys.length), current.keys)) throw new KnowledgeImportRefusalError("invalid");
|
|
1521
|
+
({page, relinked} = await moveOwned(item.sourceId, page, destination));
|
|
1522
|
+
moved = true;
|
|
1523
|
+
if (hasBody) {
|
|
1524
|
+
rendered = await renderBody(item);
|
|
1525
|
+
fields = {
|
|
1526
|
+
...fields,
|
|
1527
|
+
body: rendered.body
|
|
1528
|
+
};
|
|
1529
|
+
}
|
|
1530
|
+
}
|
|
1531
|
+
if (!hasBody) {
|
|
1532
|
+
const out = await relink(existing, page);
|
|
1533
|
+
page = out.page;
|
|
1534
|
+
rewrote = out.changed;
|
|
1535
|
+
rendered = {
|
|
1536
|
+
links: existing.links,
|
|
1537
|
+
section: out.section,
|
|
1538
|
+
unresolved: out.unresolved
|
|
1539
|
+
};
|
|
1540
|
+
}
|
|
1541
|
+
const same = fields.name === page.name && (fields.description === void 0 || fields.description === (page.description ?? "")) && (fields.body === void 0 || fields.body === (page.body ?? ""));
|
|
1542
|
+
if (!same) {
|
|
1543
|
+
renamed = fields.name !== page.name;
|
|
1544
|
+
page = await storage.updatePage({
|
|
1545
|
+
id: page.id,
|
|
1546
|
+
expectedVersion: page.version,
|
|
1547
|
+
...fields,
|
|
1548
|
+
provenance
|
|
1549
|
+
});
|
|
1550
|
+
}
|
|
1551
|
+
change = !same || rewrote ? "updated" : moved ? "moved" : "unchanged";
|
|
1552
|
+
}
|
|
1553
|
+
await importers.saveNode({
|
|
1554
|
+
bindingId: binding.id,
|
|
1555
|
+
sourceId: item.sourceId,
|
|
1556
|
+
pageId: page.id,
|
|
1557
|
+
kind: item.kind ?? existing?.kind ?? null,
|
|
1558
|
+
parentSourceId: item.parent ?? null,
|
|
1559
|
+
aliases: item.aliases ?? existing?.aliases ?? [],
|
|
1560
|
+
unresolvedLinks: rendered ? rendered.unresolved : existing?.unresolvedLinks ?? [],
|
|
1561
|
+
links: rendered ? rendered.links : existing?.links ?? [],
|
|
1562
|
+
linkSection: rendered ? rendered.section : existing?.linkSection ?? null,
|
|
1563
|
+
stub: false,
|
|
1564
|
+
adopted,
|
|
1565
|
+
unsettled: misplaced || (rendered ? rendered.unresolved : existing?.unresolvedLinks ?? []).length > 0
|
|
1566
|
+
});
|
|
1567
|
+
if (change !== "unchanged" || existing?.stub) await syncLinks(async () => {
|
|
1568
|
+
await require_run_registry.syncKnowledgePageBodyLinks(storage, page);
|
|
1569
|
+
if (change === "created" || renamed || moved) await require_run_registry.refreshKnowledgeLinksTo(storage, [page], { withDescendants: moved });
|
|
1570
|
+
});
|
|
1571
|
+
return {
|
|
1572
|
+
page,
|
|
1573
|
+
change,
|
|
1574
|
+
moved,
|
|
1575
|
+
relinked
|
|
1576
|
+
};
|
|
1577
|
+
};
|
|
1578
|
+
const depth = /* @__PURE__ */ new Map();
|
|
1579
|
+
for (const op of ops) {
|
|
1580
|
+
if (op.op !== "remove") continue;
|
|
1581
|
+
const node = await importers.getNode(binding.id, op.sourceId);
|
|
1582
|
+
const page = node ? await storage.getPage({
|
|
1583
|
+
id: node.pageId,
|
|
1584
|
+
read: "all"
|
|
1585
|
+
}) : null;
|
|
1586
|
+
const path = live(page) ? await keyPath(page) : null;
|
|
1587
|
+
depth.set(op.sourceId, path?.keys.length ?? 0);
|
|
1588
|
+
}
|
|
1589
|
+
const writes = ops.filter((op) => op.op !== "remove");
|
|
1590
|
+
const removes = ops.filter((op) => op.op === "remove").sort((a, b) => depth.get(b.sourceId) - depth.get(a.sourceId));
|
|
1591
|
+
for (const op of [...writes, ...removes]) {
|
|
1592
|
+
const sourceId = op.op === "remove" ? op.sourceId : op.item.sourceId;
|
|
1593
|
+
const embeds = [];
|
|
1594
|
+
try {
|
|
1595
|
+
await storage.transaction(async () => {
|
|
1596
|
+
if (op.op === "remove") {
|
|
1597
|
+
const node = await importers.getNode(binding.id, sourceId);
|
|
1598
|
+
if (!node) return;
|
|
1599
|
+
if (await gone(node)) {
|
|
1600
|
+
await forget(node);
|
|
1601
|
+
result.applied = true;
|
|
1602
|
+
return;
|
|
1603
|
+
}
|
|
1604
|
+
const current = await owned(node.pageId, sourceId);
|
|
1605
|
+
await storage.lockSubtree(current.page.id);
|
|
1606
|
+
const children = (await storage.countChildPages({
|
|
1607
|
+
parentIds: [current.page.id],
|
|
1608
|
+
read: "all"
|
|
1609
|
+
}))[current.page.id] ?? 0;
|
|
1610
|
+
const folder = (await importers.listBindings()).some((other) => other.id !== binding.id && other.anchorPageId === current.page.id);
|
|
1611
|
+
if (children > 0 || node.adopted || folder) {
|
|
1612
|
+
if (node.stub) return;
|
|
1613
|
+
const note = node.adopted ? (await keptBodyNotes(current.page.id)).at(-1) : void 0;
|
|
1614
|
+
const heading = ORIGINAL_BODY_NOTE_HEADINGS.find((h) => note?.text.startsWith(h));
|
|
1615
|
+
const original = heading ? note.text.slice(heading.length) : note?.text;
|
|
1616
|
+
const page = await storage.updatePage({
|
|
1617
|
+
id: current.page.id,
|
|
1618
|
+
expectedVersion: current.page.version,
|
|
1619
|
+
body: original || (children > 0 ? "Removed from the source. Kept because pages are still nested under it." : folder ? "Removed from the source. Kept because another importer writes under it." : "Removed from the source. Kept because the page was here before the import."),
|
|
1620
|
+
provenance
|
|
1621
|
+
});
|
|
1622
|
+
await importers.saveNode({
|
|
1623
|
+
...node,
|
|
1624
|
+
stub: true
|
|
1625
|
+
});
|
|
1626
|
+
await syncLinks(() => require_run_registry.syncKnowledgePageBodyLinks(storage, page));
|
|
1627
|
+
embeds.push({
|
|
1628
|
+
kind: "index",
|
|
1629
|
+
pageId: page.id
|
|
1630
|
+
});
|
|
1631
|
+
result.counts.stubbed++;
|
|
1632
|
+
result.changes.push({
|
|
1633
|
+
sourceId,
|
|
1634
|
+
pageId: page.id,
|
|
1635
|
+
change: "stubbed",
|
|
1636
|
+
title: page.name,
|
|
1637
|
+
path: ref(current.keys)
|
|
1638
|
+
});
|
|
1639
|
+
} else {
|
|
1640
|
+
const deleted = await storage.deletePage({
|
|
1641
|
+
id: current.page.id,
|
|
1642
|
+
expectedVersion: current.page.version,
|
|
1643
|
+
deletedBy: provenance.author
|
|
1644
|
+
});
|
|
1645
|
+
await importers.deleteNode(binding.id, sourceId);
|
|
1646
|
+
if ((await importers.listLinkingNodes(binding.id, [sourceId], { limit: 1 })).items.length > 0) {
|
|
1647
|
+
await importers.markLinkingNodesUnsettled(binding.id, [sourceId]);
|
|
1648
|
+
await importers.setState(binding.id, { [KNOWLEDGE_IMPORT_SETTLE_RESTART_KEY]: (0, crypto.randomUUID)() });
|
|
1649
|
+
deferredLinkers = true;
|
|
1650
|
+
}
|
|
1651
|
+
await syncLinks(async () => {
|
|
1652
|
+
await require_run_registry.syncKnowledgePageBodyLinks(storage, deleted);
|
|
1653
|
+
await require_run_registry.refreshKnowledgeLinksTo(storage, [deleted]);
|
|
1654
|
+
});
|
|
1655
|
+
embeds.push({
|
|
1656
|
+
kind: "remove",
|
|
1657
|
+
pageId: deleted.id
|
|
1658
|
+
});
|
|
1659
|
+
result.counts.removed++;
|
|
1660
|
+
result.changes.push({
|
|
1661
|
+
sourceId,
|
|
1662
|
+
pageId: null,
|
|
1663
|
+
change: "removed",
|
|
1664
|
+
title: deleted.name,
|
|
1665
|
+
path: ref(current.keys)
|
|
1666
|
+
});
|
|
1667
|
+
}
|
|
1668
|
+
result.applied = true;
|
|
1669
|
+
return;
|
|
1670
|
+
}
|
|
1671
|
+
const { page, change, moved, relinked } = await write(op.item, op.op === "upsert");
|
|
1672
|
+
recordRelinked(relinked, embeds);
|
|
1673
|
+
if (change === "unchanged") {
|
|
1674
|
+
result.counts.unchanged++;
|
|
1675
|
+
return;
|
|
1676
|
+
}
|
|
1677
|
+
result.applied = true;
|
|
1678
|
+
if (change !== "moved") embeds.push({
|
|
1679
|
+
kind: "index",
|
|
1680
|
+
pageId: page.id
|
|
1681
|
+
});
|
|
1682
|
+
if (change === "created") result.counts.created++;
|
|
1683
|
+
else if (change === "updated") result.counts.updated++;
|
|
1684
|
+
if (moved) result.counts.moved++;
|
|
1685
|
+
const path = await keyPath(page);
|
|
1686
|
+
result.changes.push({
|
|
1687
|
+
sourceId,
|
|
1688
|
+
pageId: page.id,
|
|
1689
|
+
change,
|
|
1690
|
+
title: page.name,
|
|
1691
|
+
path: path ? ref(path.keys) : ""
|
|
1692
|
+
});
|
|
1693
|
+
});
|
|
1694
|
+
result.embeds.push(...embeds);
|
|
1695
|
+
} catch (error) {
|
|
1696
|
+
const reason = refusalFor(error);
|
|
1697
|
+
if (!reason) throw error;
|
|
1698
|
+
result.refused.push({
|
|
1699
|
+
sourceId,
|
|
1700
|
+
reason
|
|
1701
|
+
});
|
|
1702
|
+
}
|
|
1703
|
+
}
|
|
1704
|
+
if (input.settle) {
|
|
1705
|
+
if (anchor) {
|
|
1706
|
+
input.settle.onStart?.();
|
|
1707
|
+
result.settle = await settle(input.settle);
|
|
1708
|
+
} else result.settle = {
|
|
1709
|
+
pending: false,
|
|
1710
|
+
cursor: null,
|
|
1711
|
+
settled: 0,
|
|
1712
|
+
fromStart: false
|
|
1713
|
+
};
|
|
1714
|
+
}
|
|
1715
|
+
return result;
|
|
1716
|
+
/**
|
|
1717
|
+
* One settle slice (O3 §C, §C′): visits the binding's unsettled nodes after `budget.after`, each
|
|
1718
|
+
* in its own savepoint, moving a page under a source parent that has arrived since and writing
|
|
1719
|
+
* links whose targets now resolve. Stops at the candidate, move or time cap and leaves the rest
|
|
1720
|
+
* for the next slice. A node it can't settle (refused, or still waiting) is skipped and stays
|
|
1721
|
+
* unsettled; the pass ends when it reaches the last unsettled node.
|
|
1722
|
+
*/
|
|
1723
|
+
async function settle(budget) {
|
|
1724
|
+
let after = budget.after ?? void 0;
|
|
1725
|
+
const fromStart = after === void 0;
|
|
1726
|
+
let examined = 0;
|
|
1727
|
+
let moves = 0;
|
|
1728
|
+
let settled = 0;
|
|
1729
|
+
for (;;) {
|
|
1730
|
+
const page = await importers.listNodes(binding.id, {
|
|
1731
|
+
unsettled: true,
|
|
1732
|
+
...after !== void 0 ? { after } : {},
|
|
1733
|
+
limit: Math.max(1, budget.candidates - examined)
|
|
1734
|
+
});
|
|
1735
|
+
for (const node of page.items) {
|
|
1736
|
+
if (examined >= budget.candidates || moves >= budget.moves || Date.now() >= budget.until) return {
|
|
1737
|
+
pending: true,
|
|
1738
|
+
cursor: resumeAt(),
|
|
1739
|
+
settled,
|
|
1740
|
+
fromStart
|
|
1741
|
+
};
|
|
1742
|
+
examined++;
|
|
1743
|
+
after = node.sourceId;
|
|
1744
|
+
const embeds = [];
|
|
1745
|
+
try {
|
|
1746
|
+
const outcome = await storage.transaction(() => settleNode(node.sourceId, embeds, moves < budget.moves));
|
|
1747
|
+
if (outcome.moved) moves++;
|
|
1748
|
+
if (outcome.moved || outcome.relinked) settled++;
|
|
1749
|
+
result.embeds.push(...embeds);
|
|
1750
|
+
} catch (error) {
|
|
1751
|
+
if (!refusalFor(error)) throw error;
|
|
1752
|
+
}
|
|
1753
|
+
}
|
|
1754
|
+
if (!page.next) {
|
|
1755
|
+
if (deferredLinkers) {
|
|
1756
|
+
if ((await importers.listNodes(binding.id, {
|
|
1757
|
+
unsettled: true,
|
|
1758
|
+
limit: 1
|
|
1759
|
+
})).items.length > 0) return {
|
|
1760
|
+
pending: true,
|
|
1761
|
+
cursor: null,
|
|
1762
|
+
settled,
|
|
1763
|
+
fromStart
|
|
1764
|
+
};
|
|
1765
|
+
}
|
|
1766
|
+
return {
|
|
1767
|
+
pending: false,
|
|
1768
|
+
cursor: null,
|
|
1769
|
+
settled,
|
|
1770
|
+
fromStart
|
|
1771
|
+
};
|
|
1772
|
+
}
|
|
1773
|
+
if (examined >= budget.candidates) return {
|
|
1774
|
+
pending: true,
|
|
1775
|
+
cursor: resumeAt(),
|
|
1776
|
+
settled,
|
|
1777
|
+
fromStart
|
|
1778
|
+
};
|
|
1779
|
+
}
|
|
1780
|
+
function resumeAt() {
|
|
1781
|
+
return deferredLinkers ? null : after ?? null;
|
|
1782
|
+
}
|
|
1783
|
+
}
|
|
1784
|
+
async function settleNode(sourceId, embeds, canMove) {
|
|
1785
|
+
const node = await importers.getNode(binding.id, sourceId);
|
|
1786
|
+
if (!node?.unsettled) return {
|
|
1787
|
+
moved: false,
|
|
1788
|
+
relinked: false
|
|
1789
|
+
};
|
|
1790
|
+
const current = await owned(node.pageId, sourceId);
|
|
1791
|
+
let { page, keys } = current;
|
|
1792
|
+
let moved = false;
|
|
1793
|
+
let relinked = false;
|
|
1794
|
+
const parent = current.outside ? null : await nodeOf(node.parentSourceId);
|
|
1795
|
+
let misplaced = !current.outside && !!node.parentSourceId && !parent;
|
|
1796
|
+
if (parent && canMove) {
|
|
1797
|
+
const destination = await owned(parent.pageId, parent.sourceId);
|
|
1798
|
+
if (page.parentId !== destination.page.id) {
|
|
1799
|
+
if (destination.keys.length > keys.length && sameKeys(destination.keys.slice(0, keys.length), keys)) throw new KnowledgeImportRefusalError("invalid");
|
|
1800
|
+
let rewrote;
|
|
1801
|
+
({page, keys, relinked: rewrote} = await moveOwned(sourceId, page, destination));
|
|
1802
|
+
recordRelinked(rewrote, embeds);
|
|
1803
|
+
moved = true;
|
|
1804
|
+
await syncLinks(() => require_run_registry.refreshKnowledgeLinksTo(storage, [page], { withDescendants: true }));
|
|
1805
|
+
}
|
|
1806
|
+
} else if (parent) misplaced = true;
|
|
1807
|
+
const out = await relink(node, page);
|
|
1808
|
+
page = out.page;
|
|
1809
|
+
if (out.changed) {
|
|
1810
|
+
relinked = true;
|
|
1811
|
+
embeds.push({
|
|
1812
|
+
kind: "index",
|
|
1813
|
+
pageId: page.id
|
|
1814
|
+
});
|
|
1815
|
+
}
|
|
1816
|
+
await importers.saveNode({
|
|
1817
|
+
...node,
|
|
1818
|
+
linkSection: out.section,
|
|
1819
|
+
unresolvedLinks: out.unresolved,
|
|
1820
|
+
unsettled: misplaced || out.unresolved.length > 0
|
|
1821
|
+
});
|
|
1822
|
+
if (moved || relinked) {
|
|
1823
|
+
result.applied = true;
|
|
1824
|
+
if (moved) result.counts.moved++;
|
|
1825
|
+
if (relinked) result.counts.updated++;
|
|
1826
|
+
result.changes.push({
|
|
1827
|
+
sourceId,
|
|
1828
|
+
pageId: page.id,
|
|
1829
|
+
change: relinked ? "updated" : "moved",
|
|
1830
|
+
title: page.name,
|
|
1831
|
+
path: ref(keys)
|
|
1832
|
+
});
|
|
1833
|
+
}
|
|
1834
|
+
return {
|
|
1835
|
+
moved,
|
|
1836
|
+
relinked
|
|
1837
|
+
};
|
|
1838
|
+
}
|
|
1839
|
+
}
|
|
1840
|
+
// src/knowledge/importers/conformance.ts
|
|
1841
|
+
/**
|
|
1842
|
+
* The protocol every {@link KnowledgeImporterHost} keeps, as framework-free cases: run each one as a
|
|
1843
|
+
* test (`for (const c of importerHostConformance(factory)) it(c.name, c.run)`). A case throws when
|
|
1844
|
+
* the host breaks the protocol. It checks only what the runner relies on (sequencing, digests,
|
|
1845
|
+
* replay, generations, finish, heartbeat, state), not where pages land.
|
|
1846
|
+
* @experimental
|
|
1847
|
+
*/
|
|
1848
|
+
function importerHostConformance(factory) {
|
|
1849
|
+
return [
|
|
1850
|
+
["starts a run at seq 0 with empty state, and skips a second start while it runs", async (t) => {
|
|
1851
|
+
const run = await t.start();
|
|
1852
|
+
check(run.lastSeq === 0, `a first run starts at lastSeq 0, got ${run.lastSeq}`);
|
|
1853
|
+
check(Object.keys(run.state).length === 0, "a first run starts with empty state");
|
|
1854
|
+
const second = await t.host.startRun(t.bindingId);
|
|
1855
|
+
check(second.status === "skipped", `a second start while a run is going is skipped, got ${second.status}`);
|
|
1856
|
+
}],
|
|
1857
|
+
["applies flushes in seq order and returns a receipt for each", async (t) => {
|
|
1858
|
+
const run = await t.start();
|
|
1859
|
+
const first = await t.flush(run, 1, [upsert("a")]);
|
|
1860
|
+
check(first.seq === 1, `the receipt names its seq, got ${first.seq}`);
|
|
1861
|
+
check(first.created === 1, `one new item is one created page, got ${first.created}`);
|
|
1862
|
+
check((await t.flush(run, 2, [])).seq === 2, "an empty flush is a valid next seq");
|
|
1863
|
+
}],
|
|
1864
|
+
["replays a committed seq to the same receipt and refuses other content for it", async (t) => {
|
|
1865
|
+
const run = await t.start();
|
|
1866
|
+
const ops = [upsert("a")];
|
|
1867
|
+
const first = await t.flush(run, 1, ops);
|
|
1868
|
+
check(same(first, await t.flush(run, 1, ops)), "resending a committed flush returns its stored receipt");
|
|
1869
|
+
await refused(() => t.flush(run, 1, [upsert("b")]), 409, "digest_mismatch");
|
|
1870
|
+
const digest = await knowledgeImporterFlushDigest({ ops });
|
|
1871
|
+
await refused(() => t.host.flush({
|
|
1872
|
+
runId: run.runId,
|
|
1873
|
+
generation: run.generation,
|
|
1874
|
+
seq: 1,
|
|
1875
|
+
digest,
|
|
1876
|
+
ops: [upsert("b")]
|
|
1877
|
+
}), 409, "digest_mismatch");
|
|
1878
|
+
check(same(first, await t.flush(run, 1, ops)), "an exact replay still returns the stored receipt");
|
|
1879
|
+
check((await t.flush(run, 2, [])).seq === 2, "the replay did not advance the seq");
|
|
1880
|
+
}],
|
|
1881
|
+
["refuses a seq gap", async (t) => {
|
|
1882
|
+
const run = await t.start();
|
|
1883
|
+
await refused(() => t.flush(run, 2, [upsert("a")]), 409, "seq_mismatch");
|
|
1884
|
+
await t.flush(run, 1, [upsert("a")]);
|
|
1885
|
+
}],
|
|
1886
|
+
["recomputes the digest and refuses one that does not match the content", async (t) => {
|
|
1887
|
+
const run = await t.start();
|
|
1888
|
+
const digest = await knowledgeImporterFlushDigest({ ops: [upsert("a")] });
|
|
1889
|
+
await refused(() => t.host.flush({
|
|
1890
|
+
runId: run.runId,
|
|
1891
|
+
generation: run.generation,
|
|
1892
|
+
seq: 1,
|
|
1893
|
+
digest,
|
|
1894
|
+
ops: [upsert("b")]
|
|
1895
|
+
}), 409, "digest_mismatch");
|
|
1896
|
+
}],
|
|
1897
|
+
["refuses a flush or finish from another generation", async (t) => {
|
|
1898
|
+
const run = await t.start();
|
|
1899
|
+
const stale = {
|
|
1900
|
+
...run,
|
|
1901
|
+
generation: run.generation + 1
|
|
1902
|
+
};
|
|
1903
|
+
await refused(() => t.flush(stale, 1, [upsert("a")]), 409, "stale_generation");
|
|
1904
|
+
await refused(() => t.finish(stale, { lastSeq: 0 }), 409, "stale_generation");
|
|
1905
|
+
await toldToStop(() => t.host.heartbeat(run.runId, run.generation + 1), "stale_generation");
|
|
1906
|
+
}],
|
|
1907
|
+
["refuses a malformed flush without applying it", async (t) => {
|
|
1908
|
+
const run = await t.start();
|
|
1909
|
+
const ops = [{
|
|
1910
|
+
op: "upsert",
|
|
1911
|
+
item: { sourceId: "a" }
|
|
1912
|
+
}];
|
|
1913
|
+
await refused(() => t.host.flush({
|
|
1914
|
+
runId: run.runId,
|
|
1915
|
+
generation: run.generation,
|
|
1916
|
+
seq: 1,
|
|
1917
|
+
digest: "0".repeat(64),
|
|
1918
|
+
ops
|
|
1919
|
+
}), 400);
|
|
1920
|
+
await t.flush(run, 1, [upsert("a")]);
|
|
1921
|
+
}],
|
|
1922
|
+
["keeps a running run alive on heartbeat", async (t) => {
|
|
1923
|
+
const run = await t.start();
|
|
1924
|
+
check((await t.host.heartbeat(run.runId, run.generation)).cancel === false, "a live run is not told to cancel");
|
|
1925
|
+
}],
|
|
1926
|
+
["finishes at the committed seq, sums counts from receipts, and replays the finish exactly", async (t) => {
|
|
1927
|
+
const run = await t.start();
|
|
1928
|
+
await t.flush(run, 1, [upsert("a"), upsert("b")]);
|
|
1929
|
+
await refused(() => t.finish(run, { lastSeq: 2 }), 409, "seq_mismatch");
|
|
1930
|
+
const receipt = await t.finish(run, { lastSeq: 1 });
|
|
1931
|
+
check(receipt.outcome === "succeeded" && receipt.lastSeq === 1, "the receipt records the finish");
|
|
1932
|
+
check(receipt.counts.created === 2, `counts come from flush receipts, got ${receipt.counts.created}`);
|
|
1933
|
+
check(receipt.chain === false, "a run with no backlog and no settle work does not chain");
|
|
1934
|
+
check(same(receipt, await t.finish(run, { lastSeq: 1 })), "an identical finish replays its receipt");
|
|
1935
|
+
await refused(() => t.finish(run, {
|
|
1936
|
+
lastSeq: 1,
|
|
1937
|
+
backlog: true
|
|
1938
|
+
}), 409, "finish_mismatch");
|
|
1939
|
+
await refused(() => t.finish(run, {
|
|
1940
|
+
lastSeq: 1,
|
|
1941
|
+
outcome: "canceled"
|
|
1942
|
+
}), 409, "finish_mismatch");
|
|
1943
|
+
}],
|
|
1944
|
+
["chains a succeeded run that reports backlog", async (t) => {
|
|
1945
|
+
const run = await t.start();
|
|
1946
|
+
const receipt = await t.finish(run, {
|
|
1947
|
+
lastSeq: 0,
|
|
1948
|
+
backlog: true
|
|
1949
|
+
});
|
|
1950
|
+
check(receipt.backlog === true && receipt.chain === true, "backlog is chained");
|
|
1951
|
+
}],
|
|
1952
|
+
["records a failed run with its fixed error code", async (t) => {
|
|
1953
|
+
const run = await t.start();
|
|
1954
|
+
const receipt = await t.finish(run, {
|
|
1955
|
+
lastSeq: 0,
|
|
1956
|
+
outcome: "failed",
|
|
1957
|
+
error: {
|
|
1958
|
+
code: "source_unreachable",
|
|
1959
|
+
retryable: true,
|
|
1960
|
+
httpStatus: 503
|
|
1961
|
+
}
|
|
1962
|
+
});
|
|
1963
|
+
check(receipt.outcome === "failed", "the outcome is recorded");
|
|
1964
|
+
check(receipt.error?.code === "source_unreachable" && receipt.error.httpStatus === 503, "the error code and status are recorded");
|
|
1965
|
+
check(receipt.chain === false, "a failed run does not chain");
|
|
1966
|
+
}],
|
|
1967
|
+
["after a finish, refuses new flushes and still replays committed ones", async (t) => {
|
|
1968
|
+
const run = await t.start();
|
|
1969
|
+
const ops = [upsert("a")];
|
|
1970
|
+
const first = await t.flush(run, 1, ops);
|
|
1971
|
+
await t.finish(run, { lastSeq: 1 });
|
|
1972
|
+
check(same(first, await t.flush(run, 1, ops)), "a committed flush still replays after the finish");
|
|
1973
|
+
await refused(() => t.flush(run, 2, []), 409, "run_not_active");
|
|
1974
|
+
await toldToStop(() => t.host.heartbeat(run.runId, run.generation), "run_not_active");
|
|
1975
|
+
}],
|
|
1976
|
+
["hands the next run the state the last committed flush saved, and lets it start", async (t) => {
|
|
1977
|
+
const run = await t.start();
|
|
1978
|
+
await t.flush(run, 1, [upsert("a")], { cursor: "1" });
|
|
1979
|
+
await t.flush(run, 2, [], {
|
|
1980
|
+
cursor: "2",
|
|
1981
|
+
page: "x"
|
|
1982
|
+
});
|
|
1983
|
+
await t.finish(run, { lastSeq: 2 });
|
|
1984
|
+
const next = await t.start();
|
|
1985
|
+
check(next.runId !== run.runId, "the next run has its own id");
|
|
1986
|
+
check(next.lastSeq === 0, "seq starts over for each run");
|
|
1987
|
+
check(next.state.cursor === "2" && next.state.page === "x", "state is what the last flush saved");
|
|
1988
|
+
}],
|
|
1989
|
+
["saves no state from a refused flush", async (t) => {
|
|
1990
|
+
const run = await t.start();
|
|
1991
|
+
await t.flush(run, 1, [], { cursor: "1" });
|
|
1992
|
+
await refused(() => t.flush(run, 3, [], { cursor: "3" }), 409, "seq_mismatch");
|
|
1993
|
+
await t.finish(run, { lastSeq: 1 });
|
|
1994
|
+
const next = await t.start();
|
|
1995
|
+
check(next.state.cursor === "1", `a refused flush saves nothing, got cursor ${next.state.cursor}`);
|
|
1996
|
+
}]
|
|
1997
|
+
].map(([name, body]) => ({
|
|
1998
|
+
name,
|
|
1999
|
+
run: async () => {
|
|
2000
|
+
const fixture = await factory();
|
|
2001
|
+
try {
|
|
2002
|
+
await body(session(fixture));
|
|
2003
|
+
} finally {
|
|
2004
|
+
await fixture.cleanup?.();
|
|
2005
|
+
}
|
|
2006
|
+
}
|
|
2007
|
+
}));
|
|
2008
|
+
}
|
|
2009
|
+
function session({ host, bindingId }) {
|
|
2010
|
+
return {
|
|
2011
|
+
host,
|
|
2012
|
+
bindingId,
|
|
2013
|
+
async start() {
|
|
2014
|
+
const started = await host.startRun(bindingId);
|
|
2015
|
+
check(started.status === "started", `the binding's run starts, got ${started.status}`);
|
|
2016
|
+
return started;
|
|
2017
|
+
},
|
|
2018
|
+
async flush(run, seq, ops, state) {
|
|
2019
|
+
const digest = await knowledgeImporterFlushDigest(state ? {
|
|
2020
|
+
ops,
|
|
2021
|
+
state
|
|
2022
|
+
} : { ops });
|
|
2023
|
+
return host.flush({
|
|
2024
|
+
runId: run.runId,
|
|
2025
|
+
generation: run.generation,
|
|
2026
|
+
seq,
|
|
2027
|
+
digest,
|
|
2028
|
+
ops,
|
|
2029
|
+
...state ? { state } : {}
|
|
2030
|
+
});
|
|
2031
|
+
},
|
|
2032
|
+
finish(run, request) {
|
|
2033
|
+
return host.finishRun({
|
|
2034
|
+
runId: run.runId,
|
|
2035
|
+
generation: run.generation,
|
|
2036
|
+
outcome: "succeeded",
|
|
2037
|
+
backlog: false,
|
|
2038
|
+
...request
|
|
2039
|
+
});
|
|
2040
|
+
}
|
|
2041
|
+
};
|
|
2042
|
+
}
|
|
2043
|
+
const upsert = (sourceId) => ({
|
|
2044
|
+
op: "upsert",
|
|
2045
|
+
item: {
|
|
2046
|
+
sourceId,
|
|
2047
|
+
title: sourceId.toUpperCase(),
|
|
2048
|
+
body: `body of ${sourceId}`
|
|
2049
|
+
}
|
|
2050
|
+
});
|
|
2051
|
+
function check(condition, message) {
|
|
2052
|
+
if (!condition) throw new Error(`Importer host conformance: ${message}`);
|
|
2053
|
+
}
|
|
2054
|
+
/** Equal as JSON, key order aside: a host may store receipts in a store that reorders keys. */
|
|
2055
|
+
function same(a, b) {
|
|
2056
|
+
return canonicalJson(JSON.parse(JSON.stringify(a))) === canonicalJson(JSON.parse(JSON.stringify(b)));
|
|
2057
|
+
}
|
|
2058
|
+
/**
|
|
2059
|
+
* A heartbeat for a run the host no longer holds must not keep it going: it answers
|
|
2060
|
+
* `{ cancel: true }`, or (a host that enforces a lease) refuses with a 409 and `code`. The runner
|
|
2061
|
+
* ignores a refused heartbeat; its next flush or finish gets the same refusal.
|
|
2062
|
+
*/
|
|
2063
|
+
async function toldToStop(beat, code) {
|
|
2064
|
+
let answer;
|
|
2065
|
+
let error;
|
|
2066
|
+
try {
|
|
2067
|
+
answer = await beat();
|
|
2068
|
+
} catch (e) {
|
|
2069
|
+
error = e;
|
|
2070
|
+
}
|
|
2071
|
+
check(answer ? answer.cancel === true : error?.status === 409 && error.code === code, answer ? "a heartbeat for a run the host no longer holds is told to cancel" : `a refused heartbeat is a 409 ${code}, got ${String(error?.status)} ${String(error?.code)}: ${String(error)}`);
|
|
2072
|
+
}
|
|
2073
|
+
async function refused(call, status, code) {
|
|
2074
|
+
let error;
|
|
2075
|
+
try {
|
|
2076
|
+
await call();
|
|
2077
|
+
} catch (e) {
|
|
2078
|
+
error = e;
|
|
2079
|
+
}
|
|
2080
|
+
check(error, `expected a ${status}${code ? ` ${code}` : ""} refusal, but the call succeeded`);
|
|
2081
|
+
check(error.status === status && (code === void 0 || error.code === code), `expected a ${status}${code ? ` ${code}` : ""} refusal, got ${String(error.status)} ${String(error.code)}: ${String(error)}`);
|
|
2082
|
+
}
|
|
2083
|
+
// src/knowledge/importers/local-host.ts
|
|
2084
|
+
const DEFAULT_FLUSH_BUDGET_MS = 45e3;
|
|
2085
|
+
const DEFAULT_STALE_RUN_AFTER_MS = 3e5;
|
|
2086
|
+
const DEFAULT_SETTLE_BUDGET_MS = 1e4;
|
|
2087
|
+
const SETTLE_CANDIDATES = 200;
|
|
2088
|
+
const SETTLE_MOVES = 50;
|
|
2089
|
+
/** Settle flushes in a row that may time out before a run stops settling (O3 §C″). */
|
|
2090
|
+
const SETTLE_MAX_TIMEOUTS = 3;
|
|
2091
|
+
/**
|
|
2092
|
+
* Host bookkeeping kept beside the importer's own state, under a prefix the importer can't write:
|
|
2093
|
+
* where the settle pass stopped, `<runId>:<n>` settle timeouts in a row for the current run, and
|
|
2094
|
+
* the restart request another binding's flush left (see {@link KNOWLEDGE_IMPORT_SETTLE_RESTART_KEY}).
|
|
2095
|
+
*/
|
|
2096
|
+
const RESERVED_STATE_PREFIX = "mastra:";
|
|
2097
|
+
const SETTLE_CURSOR_KEY = "mastra:settle:cursor";
|
|
2098
|
+
const SETTLE_TIMEOUTS_KEY = "mastra:settle:timeouts";
|
|
2099
|
+
const settleTimeouts = (state, runId) => {
|
|
2100
|
+
const value = state[SETTLE_TIMEOUTS_KEY] ?? "";
|
|
2101
|
+
const at = value.lastIndexOf(":");
|
|
2102
|
+
return at > 0 && value.slice(0, at) === runId ? Number(value.slice(at + 1)) || 0 : 0;
|
|
2103
|
+
};
|
|
2104
|
+
const SETTLE_TIMEOUT_RECORD_MS = 5e3;
|
|
2105
|
+
const timedOut = (error) => {
|
|
2106
|
+
const e = error;
|
|
2107
|
+
if (!e) return false;
|
|
2108
|
+
if (e.name === "KnowledgeTransactionDeadlineError" || e.name === "TransactionDeadlineError") return true;
|
|
2109
|
+
if (e.code === "57014" || e.code === "55P03") return true;
|
|
2110
|
+
return e.cause !== void 0 && e.cause !== error && timedOut(e.cause);
|
|
2111
|
+
};
|
|
2112
|
+
/** Re-index rounds after a page changed under its embed; a page rewritten faster than this is left to its own writes' jobs. */
|
|
2113
|
+
const MAX_REINDEX_ROUNDS = 3;
|
|
2114
|
+
/** Unwinds a claimed start's transaction when another run of the binding is going (r352 S4). */
|
|
2115
|
+
var SkippedClaim = class extends Error {
|
|
2116
|
+
runId;
|
|
2117
|
+
constructor(runId) {
|
|
2118
|
+
super("Another run of the binding is going.");
|
|
2119
|
+
this.runId = runId;
|
|
2120
|
+
}
|
|
2121
|
+
};
|
|
2122
|
+
/**
|
|
2123
|
+
* Unwinds a transaction that holds the writer guard shared but found `firstWriteAt` unset where it
|
|
2124
|
+
* must mark it: marking under a shared lock can deadlock against another holder, so the work is
|
|
2125
|
+
* redone holding it exclusively (O2 lock preselection).
|
|
2126
|
+
*/
|
|
2127
|
+
var NeedsExclusiveGuard = class extends Error {
|
|
2128
|
+
constructor() {
|
|
2129
|
+
super("The first write must be marked under the exclusive writer guard.");
|
|
2130
|
+
}
|
|
2131
|
+
};
|
|
2132
|
+
/**
|
|
2133
|
+
* Unwinds a flush whose transaction deadline runs past where its run stops being live (r352 S1):
|
|
2134
|
+
* it is redone with `cutoff` as its deadline.
|
|
2135
|
+
*/
|
|
2136
|
+
var LeaseCutoff = class extends Error {
|
|
2137
|
+
cutoff;
|
|
2138
|
+
constructor(cutoff) {
|
|
2139
|
+
super("The flush transaction outlives its run lease.");
|
|
2140
|
+
this.cutoff = cutoff;
|
|
2141
|
+
}
|
|
2142
|
+
};
|
|
2143
|
+
/** Attempts to bound a flush by its run's lease before it is refused as retryable. */
|
|
2144
|
+
const MAX_LEASE_BOUND_ATTEMPTS = 3;
|
|
2145
|
+
/**
|
|
2146
|
+
* Taken off a redone flush's cutoff, so that a slower read of the store's clock on the next
|
|
2147
|
+
* attempt, which maps it earlier, doesn't unwind it again.
|
|
2148
|
+
*/
|
|
2149
|
+
const LEASE_CUTOFF_MARGIN_MS = 250;
|
|
2150
|
+
/**
|
|
2151
|
+
* The local time (epoch ms) by which the store's clock reaches `end`. The local clock is read
|
|
2152
|
+
* before the store's, so the round trip only moves the result earlier, never later.
|
|
2153
|
+
*/
|
|
2154
|
+
async function localTimeOf(importers, end) {
|
|
2155
|
+
return Date.now() + (end - (await importers.now()).getTime());
|
|
2156
|
+
}
|
|
2157
|
+
/** Carries `admit`'s own error out of the start transaction it rolled back. */
|
|
2158
|
+
var AdmitRefusal = class extends Error {
|
|
2159
|
+
refusal;
|
|
2160
|
+
constructor(refusal) {
|
|
2161
|
+
super("The claim was refused.");
|
|
2162
|
+
this.refusal = refusal;
|
|
2163
|
+
}
|
|
2164
|
+
};
|
|
2165
|
+
const conflict = (code, message) => new KnowledgeImporterHostConflictError(code, message);
|
|
2166
|
+
/** O2 run-state refusals as the host contract names them. */
|
|
2167
|
+
function runStateConflict(error) {
|
|
2168
|
+
switch (error.reason) {
|
|
2169
|
+
case "seq": return conflict("seq_mismatch", "The flush seq is not the committed seq + 1.");
|
|
2170
|
+
case "generation":
|
|
2171
|
+
case "stale_guard": return conflict("stale_generation", "The run belongs to an older writer generation.");
|
|
2172
|
+
default: return conflict("run_not_active", "The run is not running.");
|
|
2173
|
+
}
|
|
2174
|
+
}
|
|
2175
|
+
/** Failures a resend can get past: lock and serialization aborts, deadlines, lost connections. */
|
|
2176
|
+
function transient(error) {
|
|
2177
|
+
const e = error;
|
|
2178
|
+
return e?.name === "KnowledgeTransactionDeadlineError" || e?.name === "TransactionRolledBackError" || [
|
|
2179
|
+
"40001",
|
|
2180
|
+
"40P01",
|
|
2181
|
+
"55P03",
|
|
2182
|
+
"57014",
|
|
2183
|
+
"08006",
|
|
2184
|
+
"08003",
|
|
2185
|
+
"SQLITE_BUSY",
|
|
2186
|
+
"ECONNRESET"
|
|
2187
|
+
].includes(e?.code ?? "");
|
|
2188
|
+
}
|
|
2189
|
+
function hostError(error) {
|
|
2190
|
+
if (error instanceof KnowledgeImporterHostConflictError || error instanceof KnowledgeImporterHostError) return error;
|
|
2191
|
+
if (error instanceof require_run_registry.KnowledgeImporterRunStateError) return runStateConflict(error);
|
|
2192
|
+
const failure = new KnowledgeImporterHostError("The importer host could not apply the request; nothing was applied.", transient(error) ? 503 : 422);
|
|
2193
|
+
failure.cause = error;
|
|
2194
|
+
return failure;
|
|
2195
|
+
}
|
|
2196
|
+
const receiptCounts = (counts) => ({
|
|
2197
|
+
created: counts.created ?? 0,
|
|
2198
|
+
updated: counts.updated ?? 0,
|
|
2199
|
+
unchanged: counts.unchanged ?? 0,
|
|
2200
|
+
moved: counts.moved ?? 0,
|
|
2201
|
+
removed: counts.removed ?? 0,
|
|
2202
|
+
stubbed: counts.stubbed ?? 0,
|
|
2203
|
+
refused: counts.refused ?? 0
|
|
2204
|
+
});
|
|
2205
|
+
const runReceipt = (run) => {
|
|
2206
|
+
const { chain, by: _by, canceled, ...finish } = run.finish;
|
|
2207
|
+
const reported = canceled ? {
|
|
2208
|
+
outcome: "canceled",
|
|
2209
|
+
backlog: false,
|
|
2210
|
+
error: null
|
|
2211
|
+
} : {};
|
|
2212
|
+
return {
|
|
2213
|
+
runId: run.id,
|
|
2214
|
+
...finish,
|
|
2215
|
+
...reported,
|
|
2216
|
+
counts: receiptCounts(run.counts),
|
|
2217
|
+
chain: chain ?? false
|
|
2218
|
+
};
|
|
2219
|
+
};
|
|
2220
|
+
/** The app's normalized request a stored finish replays against. */
|
|
2221
|
+
const replayIdentity = (finish) => {
|
|
2222
|
+
const { chain: _chain, by: _by, canceled: _canceled, ...rest } = finish;
|
|
2223
|
+
return rest;
|
|
2224
|
+
};
|
|
2225
|
+
/** The finish a host records for a run it ended (r352 S2/S3). */
|
|
2226
|
+
const hostFinish = (run, code) => {
|
|
2227
|
+
const canceled = run.cancelRequestedAt !== null;
|
|
2228
|
+
return {
|
|
2229
|
+
...normalizeKnowledgeImporterFinish({
|
|
2230
|
+
runId: run.id,
|
|
2231
|
+
generation: run.generation,
|
|
2232
|
+
outcome: canceled ? "canceled" : "failed",
|
|
2233
|
+
backlog: false,
|
|
2234
|
+
lastSeq: run.lastSeq,
|
|
2235
|
+
...canceled ? {} : { error: {
|
|
2236
|
+
code,
|
|
2237
|
+
retryable: true
|
|
2238
|
+
} }
|
|
2239
|
+
}),
|
|
2240
|
+
chain: false,
|
|
2241
|
+
by: "host"
|
|
2242
|
+
};
|
|
2243
|
+
};
|
|
2244
|
+
/**
|
|
2245
|
+
* A {@link KnowledgeImporterHost} over the app's own Knowledge storage: each flush is one storage
|
|
2246
|
+
* transaction holding its page writes, node map, state, run changes and receipt. Embeds run after
|
|
2247
|
+
* commit; a failed embed is a warning and never fails the flush.
|
|
2248
|
+
*
|
|
2249
|
+
* @internal Reached through `Knowledge`; the writer is Knowledge's own.
|
|
2250
|
+
*/
|
|
2251
|
+
function createLocalKnowledgeImporterHost(writer, options) {
|
|
2252
|
+
const author = options.author ?? ((binding) => `importer:${binding.id}`);
|
|
2253
|
+
const leaseMs = options.leaseMs;
|
|
2254
|
+
/** The clock leases are judged by: the store's under `leaseMs`, else this process's. */
|
|
2255
|
+
const clock = async (importers) => leaseMs !== void 0 ? importers.now() : /* @__PURE__ */ new Date();
|
|
2256
|
+
/** Why a running run is no longer live at `now`, or null while it is. */
|
|
2257
|
+
const lapsed = (run, now, after = leaseMs) => {
|
|
2258
|
+
if (run.deadlineAt && run.deadlineAt.getTime() <= now.getTime()) return "deadline_exceeded";
|
|
2259
|
+
if (after !== void 0 && now.getTime() >= (run.heartbeatAt ?? run.startedAt).getTime() + after) return "lease_expired";
|
|
2260
|
+
return null;
|
|
2261
|
+
};
|
|
2262
|
+
/** Store time (epoch ms) at which a running run stops being live under `leaseMs`. */
|
|
2263
|
+
const liveUntil = (run) => Math.min((run.heartbeatAt ?? run.startedAt).getTime() + (leaseMs ?? Infinity), run.deadlineAt?.getTime() ?? Infinity);
|
|
2264
|
+
const listBindings = async () => typeof options.bindings === "function" ? await options.bindings() : options.bindings;
|
|
2265
|
+
const storageAndImporters = async () => {
|
|
2266
|
+
const storage = await writer.getStorage();
|
|
2267
|
+
const importers = storage.importers;
|
|
2268
|
+
if (!importers || !storage.getCapabilities().supportsTransactions) throw new KnowledgeImporterHostError("This Knowledge storage adapter does not support importers.", 501);
|
|
2269
|
+
return {
|
|
2270
|
+
storage,
|
|
2271
|
+
importers
|
|
2272
|
+
};
|
|
2273
|
+
};
|
|
2274
|
+
const bindingFor = async (bindingId) => {
|
|
2275
|
+
const binding = (await listBindings()).find((b) => b.id === bindingId);
|
|
2276
|
+
if (!binding) throw new KnowledgeImporterHostError(`No importer binding "${bindingId}".`, 404);
|
|
2277
|
+
return binding;
|
|
2278
|
+
};
|
|
2279
|
+
const runEmbeds = async (storage, jobs) => {
|
|
2280
|
+
const semantic = writer.semantic;
|
|
2281
|
+
if (!semantic) return;
|
|
2282
|
+
for (const job of jobs) try {
|
|
2283
|
+
if (job.kind === "remove") {
|
|
2284
|
+
await semantic.removePage(job.pageId);
|
|
2285
|
+
continue;
|
|
2286
|
+
}
|
|
2287
|
+
let indexed = 0;
|
|
2288
|
+
for (let round = 0; round < MAX_REINDEX_ROUNDS; round++) {
|
|
2289
|
+
const page = await storage.getPage({
|
|
2290
|
+
id: job.pageId,
|
|
2291
|
+
read: "all"
|
|
2292
|
+
});
|
|
2293
|
+
if (!page || page.deletedAt || page.version <= indexed) break;
|
|
2294
|
+
await semantic.indexPage(page);
|
|
2295
|
+
indexed = page.version;
|
|
2296
|
+
}
|
|
2297
|
+
} catch (error) {
|
|
2298
|
+
writer.warn(`Knowledge importer: indexing page ${job.pageId} failed after commit: ${String(error)}`);
|
|
2299
|
+
}
|
|
2300
|
+
};
|
|
2301
|
+
/**
|
|
2302
|
+
* Ends the binding's running run when its runner is gone (O3 §D): past its deadline, or no
|
|
2303
|
+
* heartbeat within `staleRunAfterMs`. Called under the writer guard and registration lock; the run row is
|
|
2304
|
+
* locked and rechecked so a heartbeat that commits first keeps it alive. Its runner's later
|
|
2305
|
+
* flushes and finish are refused as `run_not_active`; exact replays still return receipts.
|
|
2306
|
+
*/
|
|
2307
|
+
const staleAfter = leaseMs ?? options.staleRunAfterMs ?? DEFAULT_STALE_RUN_AFTER_MS;
|
|
2308
|
+
/** Ends `run` if it isn't live; the caller holds the guard and the run's lock. */
|
|
2309
|
+
const expireLocked = async (importers, run) => {
|
|
2310
|
+
const why = lapsed(run, await clock(importers), staleAfter);
|
|
2311
|
+
if (!why) return false;
|
|
2312
|
+
const finish = hostFinish(run, leaseMs !== void 0 ? why : "stopped");
|
|
2313
|
+
await importers.abandonRun({
|
|
2314
|
+
runId: run.id,
|
|
2315
|
+
finish,
|
|
2316
|
+
status: finish.outcome === "canceled" ? "canceled" : "failed"
|
|
2317
|
+
});
|
|
2318
|
+
return true;
|
|
2319
|
+
};
|
|
2320
|
+
const reclaimStaleRuns = async (importers, bindingId) => {
|
|
2321
|
+
for (const candidate of await importers.listRuns(bindingId)) {
|
|
2322
|
+
if (candidate.status !== "running") continue;
|
|
2323
|
+
const run = await importers.lockRun(candidate.id);
|
|
2324
|
+
if (!run || run.status !== "running") continue;
|
|
2325
|
+
await expireLocked(importers, run);
|
|
2326
|
+
}
|
|
2327
|
+
};
|
|
2328
|
+
/**
|
|
2329
|
+
* Counts a settle flush that timed out, outside its rolled-back transaction. Best effort, and
|
|
2330
|
+
* only for a run still live by the same checks a flush passes: same generation, not canceled, not
|
|
2331
|
+
* past its lease or deadline. Under a lease the write is also bounded by where the locked run
|
|
2332
|
+
* stops being live, so a timeout caused by the lease ending never writes after it.
|
|
2333
|
+
*/
|
|
2334
|
+
const countSettleTimeout = async (runId, generation) => {
|
|
2335
|
+
try {
|
|
2336
|
+
const { storage } = await storageAndImporters();
|
|
2337
|
+
const fenced = leaseMs !== void 0 && storage.getCapabilities().enforcesTransactionDeadline === true;
|
|
2338
|
+
let deadlineAt = Date.now() + SETTLE_TIMEOUT_RECORD_MS;
|
|
2339
|
+
for (let attempt = 1; attempt <= MAX_LEASE_BOUND_ATTEMPTS; attempt++) try {
|
|
2340
|
+
await storage.transaction(async (tx) => {
|
|
2341
|
+
const importers = tx.importers;
|
|
2342
|
+
const guard = await importers.lockWriterGuard("share");
|
|
2343
|
+
const run = await importers.lockRun(runId);
|
|
2344
|
+
if (!run || run.status !== "running" || run.cancelRequestedAt) return;
|
|
2345
|
+
if (run.generation !== generation || guard.generation !== generation) return;
|
|
2346
|
+
if (lapsed(run, await clock(importers))) return;
|
|
2347
|
+
if (fenced) {
|
|
2348
|
+
const cutoff = await localTimeOf(importers, liveUntil(run));
|
|
2349
|
+
if (cutoff < deadlineAt) throw new LeaseCutoff(cutoff);
|
|
2350
|
+
}
|
|
2351
|
+
const n = settleTimeouts(await importers.getState(run.bindingId), runId) + 1;
|
|
2352
|
+
await importers.setState(run.bindingId, { [SETTLE_TIMEOUTS_KEY]: `${runId}:${n}` });
|
|
2353
|
+
}, { deadlineAt });
|
|
2354
|
+
return;
|
|
2355
|
+
} catch (error) {
|
|
2356
|
+
if (!(error instanceof LeaseCutoff)) throw error;
|
|
2357
|
+
deadlineAt = error.cutoff - LEASE_CUTOFF_MARGIN_MS;
|
|
2358
|
+
if (deadlineAt <= Date.now()) return;
|
|
2359
|
+
}
|
|
2360
|
+
} catch (error) {
|
|
2361
|
+
writer.warn(`Knowledge importer: recording a settle timeout for run ${runId} failed: ${String(error)}`);
|
|
2362
|
+
}
|
|
2363
|
+
};
|
|
2364
|
+
return {
|
|
2365
|
+
async startRun(bindingId, start) {
|
|
2366
|
+
const binding = await bindingFor(bindingId);
|
|
2367
|
+
const runId = start?.runId ?? (0, crypto.randomUUID)();
|
|
2368
|
+
const claimed = start?.admit !== void 0 || start?.generation !== void 0;
|
|
2369
|
+
try {
|
|
2370
|
+
const { scope } = parseKnowledgeImportTarget(binding.target);
|
|
2371
|
+
const { storage, importers: rootImporters } = await storageAndImporters();
|
|
2372
|
+
let exclusive = !(await rootImporters.readWriterGuard()).firstWriteAt;
|
|
2373
|
+
await writer.runtime.resolve();
|
|
2374
|
+
const attempt = () => storage.transaction(async (tx) => {
|
|
2375
|
+
const importers = tx.importers;
|
|
2376
|
+
const guard = await importers.lockWriterGuard(exclusive ? "update" : "share");
|
|
2377
|
+
if (claimed && (guard.activePath !== "new" || start?.generation !== void 0 && guard.generation !== start.generation)) throw conflict("stale_generation", "The claim belongs to another writer generation or write path.");
|
|
2378
|
+
await importers.registerBinding({
|
|
2379
|
+
id: binding.id,
|
|
2380
|
+
importer: binding.importer,
|
|
2381
|
+
target: binding.target
|
|
2382
|
+
});
|
|
2383
|
+
await reclaimStaleRuns(importers, binding.id);
|
|
2384
|
+
if (start?.admit) try {
|
|
2385
|
+
await start.admit(tx);
|
|
2386
|
+
} catch (error) {
|
|
2387
|
+
throw new AdmitRefusal(error);
|
|
2388
|
+
}
|
|
2389
|
+
const { wrote } = await writer.runtime.materializeScopeIn(tx, scope, { author: author(binding) });
|
|
2390
|
+
if (wrote && !guard.firstWriteAt) {
|
|
2391
|
+
if (!exclusive) throw new NeedsExclusiveGuard();
|
|
2392
|
+
await importers.markFirstWrite();
|
|
2393
|
+
}
|
|
2394
|
+
const run = await importers.startRun({
|
|
2395
|
+
bindingId: binding.id,
|
|
2396
|
+
runId,
|
|
2397
|
+
generation: guard.generation,
|
|
2398
|
+
...start?.fireKey !== void 0 ? { fireKey: start.fireKey } : {},
|
|
2399
|
+
...start?.deadline !== void 0 ? { deadlineAt: new Date(start.deadline) } : {}
|
|
2400
|
+
});
|
|
2401
|
+
if (run.status !== "started" && start?.admit) throw new SkippedClaim(run.run.id);
|
|
2402
|
+
const saved = run.status === "started" ? await importers.getState(binding.id) : {};
|
|
2403
|
+
return {
|
|
2404
|
+
run,
|
|
2405
|
+
state: Object.fromEntries(Object.entries(saved).filter(([key]) => !key.startsWith(RESERVED_STATE_PREFIX)))
|
|
2406
|
+
};
|
|
2407
|
+
});
|
|
2408
|
+
let result;
|
|
2409
|
+
try {
|
|
2410
|
+
result = await attempt();
|
|
2411
|
+
} catch (error) {
|
|
2412
|
+
if (!(error instanceof NeedsExclusiveGuard)) throw error;
|
|
2413
|
+
exclusive = true;
|
|
2414
|
+
result = await attempt();
|
|
2415
|
+
}
|
|
2416
|
+
if (result.run.status !== "started") return {
|
|
2417
|
+
status: "skipped",
|
|
2418
|
+
runId: result.run.run.id
|
|
2419
|
+
};
|
|
2420
|
+
return {
|
|
2421
|
+
status: "started",
|
|
2422
|
+
runId: result.run.run.id,
|
|
2423
|
+
generation: result.run.run.generation,
|
|
2424
|
+
state: result.state,
|
|
2425
|
+
lastSeq: result.run.run.lastSeq,
|
|
2426
|
+
binding
|
|
2427
|
+
};
|
|
2428
|
+
} catch (error) {
|
|
2429
|
+
if (error instanceof SkippedClaim) return {
|
|
2430
|
+
status: "skipped",
|
|
2431
|
+
runId: error.runId
|
|
2432
|
+
};
|
|
2433
|
+
if (error?.name === "KnowledgeImporterBindingConflictError") throw new KnowledgeImporterHostError(`Importer binding "${binding.id}" was recorded with another importer or target.`, 409);
|
|
2434
|
+
if (error instanceof TypeError) throw new KnowledgeImporterHostError(error.message, 400);
|
|
2435
|
+
if (error instanceof AdmitRefusal) throw error.refusal;
|
|
2436
|
+
throw hostError(error);
|
|
2437
|
+
}
|
|
2438
|
+
},
|
|
2439
|
+
async flush(flush) {
|
|
2440
|
+
let body;
|
|
2441
|
+
try {
|
|
2442
|
+
body = parseKnowledgeImporterFlushBody(flush);
|
|
2443
|
+
} catch (error) {
|
|
2444
|
+
throw new KnowledgeImporterHostError(`Malformed flush: ${error.message}`, 400);
|
|
2445
|
+
}
|
|
2446
|
+
const reserved = Object.keys(body.state ?? {}).find((key) => key.startsWith(RESERVED_STATE_PREFIX));
|
|
2447
|
+
if (reserved !== void 0) throw new KnowledgeImporterHostError(`Malformed flush: state key "${reserved}" is reserved for the host.`, 400);
|
|
2448
|
+
const digest = await knowledgeImporterFlushDigest(body);
|
|
2449
|
+
if (digest !== flush.digest) throw conflict("digest_mismatch", "The digest does not match the flush content.");
|
|
2450
|
+
const { storage, importers: rootImporters } = await storageAndImporters();
|
|
2451
|
+
const budgetAt = Date.now() + (options.flushBudgetMs ?? DEFAULT_FLUSH_BUDGET_MS);
|
|
2452
|
+
const replayed = await storage.transaction((tx) => tx.importers.getFlush(flush.runId, flush.generation, flush.seq), { deadlineAt: budgetAt }).catch((error) => {
|
|
2453
|
+
throw hostError(error);
|
|
2454
|
+
});
|
|
2455
|
+
if (replayed) {
|
|
2456
|
+
if (replayed.digest !== digest) throw conflict("digest_mismatch", "This seq was committed with other content.");
|
|
2457
|
+
return replayed.receipt;
|
|
2458
|
+
}
|
|
2459
|
+
const [peek, peekRun] = await Promise.all([rootImporters.readWriterGuard(), rootImporters.getRun(flush.runId)]).catch((error) => {
|
|
2460
|
+
throw hostError(error);
|
|
2461
|
+
});
|
|
2462
|
+
if (leaseMs === void 0 && peekRun?.deadlineAt && peekRun.deadlineAt.getTime() <= Date.now()) throw conflict("run_not_active", "The run is past its deadline.");
|
|
2463
|
+
const resolvedAuthor = peekRun ? await bindingFor(peekRun.bindingId).then((binding) => ({ author: author(binding) })).catch((error) => ({ error })) : { error: conflict("run_not_active", "The run is not running.") };
|
|
2464
|
+
let deadlineAt = Math.min(budgetAt, peekRun?.deadlineAt?.getTime() ?? Infinity);
|
|
2465
|
+
const fenced = leaseMs !== void 0 && storage.getCapabilities().enforcesTransactionDeadline === true;
|
|
2466
|
+
if (fenced && peekRun) {
|
|
2467
|
+
const cutoff = await localTimeOf(rootImporters, liveUntil(peekRun)).catch((error) => {
|
|
2468
|
+
throw hostError(error);
|
|
2469
|
+
});
|
|
2470
|
+
if (cutoff > Date.now()) deadlineAt = Math.min(deadlineAt, cutoff);
|
|
2471
|
+
}
|
|
2472
|
+
let embeds = [];
|
|
2473
|
+
let settling = false;
|
|
2474
|
+
try {
|
|
2475
|
+
const write = (deadlineAt) => storage.transaction(async (tx) => {
|
|
2476
|
+
const importers = tx.importers;
|
|
2477
|
+
const guard = await importers.lockWriterGuard(peek.firstWriteAt ? "share" : "update");
|
|
2478
|
+
const run = await importers.lockRun(flush.runId);
|
|
2479
|
+
const stored = await importers.getFlush(flush.runId, flush.generation, flush.seq);
|
|
2480
|
+
if (stored) {
|
|
2481
|
+
if (stored.digest !== digest) throw conflict("digest_mismatch", "This seq was committed with other content.");
|
|
2482
|
+
return stored.receipt;
|
|
2483
|
+
}
|
|
2484
|
+
if (!run || run.status !== "running") throw conflict("run_not_active", "The run is not running.");
|
|
2485
|
+
if (run.generation !== flush.generation || guard.generation !== flush.generation) throw conflict("stale_generation", "The run belongs to an older writer generation.");
|
|
2486
|
+
if (run.cancelRequestedAt) throw conflict("run_not_active", "The run was canceled.");
|
|
2487
|
+
if (lapsed(run, await clock(importers))) throw conflict("run_not_active", "The run is past its lease or deadline.");
|
|
2488
|
+
if (fenced) {
|
|
2489
|
+
const cutoff = await localTimeOf(importers, liveUntil(run));
|
|
2490
|
+
if (cutoff < deadlineAt) throw new LeaseCutoff(cutoff);
|
|
2491
|
+
}
|
|
2492
|
+
if (flush.seq !== run.lastSeq + 1) throw conflict("seq_mismatch", "The flush seq is not the committed seq + 1.");
|
|
2493
|
+
if ("error" in resolvedAuthor) throw resolvedAuthor.error;
|
|
2494
|
+
const binding = await importers.getBinding(run.bindingId);
|
|
2495
|
+
if (!binding) throw conflict("run_not_active", "The run has no binding.");
|
|
2496
|
+
const [scope] = await tx.getScopesByAddress([parseKnowledgeImportTarget(binding.target).scope]);
|
|
2497
|
+
if (!scope) throw new KnowledgeImporterHostError("The binding target scope does not exist.", 503);
|
|
2498
|
+
const hostState = await importers.getState(binding.id);
|
|
2499
|
+
const timeouts = settleTimeouts(hostState, run.id);
|
|
2500
|
+
const restart = hostState["mastra:settle:restart"] ?? "";
|
|
2501
|
+
const restarting = restart !== (hostState["mastra:settle:seen"] ?? "");
|
|
2502
|
+
const applied = await applyKnowledgeImportFlush({
|
|
2503
|
+
storage: tx,
|
|
2504
|
+
importers,
|
|
2505
|
+
binding,
|
|
2506
|
+
scope,
|
|
2507
|
+
runId: run.id,
|
|
2508
|
+
ops: body.ops,
|
|
2509
|
+
provenance: { author: resolvedAuthor.author },
|
|
2510
|
+
...timeouts < SETTLE_MAX_TIMEOUTS ? { settle: {
|
|
2511
|
+
after: restarting ? null : hostState[SETTLE_CURSOR_KEY] || null,
|
|
2512
|
+
candidates: Math.max(1, SETTLE_CANDIDATES >> timeouts),
|
|
2513
|
+
moves: SETTLE_MOVES,
|
|
2514
|
+
until: Math.min(Date.now() + (options.settleBudgetMs ?? DEFAULT_SETTLE_BUDGET_MS), deadlineAt),
|
|
2515
|
+
onStart: () => {
|
|
2516
|
+
settling = true;
|
|
2517
|
+
}
|
|
2518
|
+
} } : {}
|
|
2519
|
+
});
|
|
2520
|
+
const settled = applied.settle;
|
|
2521
|
+
const hostUpdates = {};
|
|
2522
|
+
if (settled && (settled.cursor ?? "") !== (hostState[SETTLE_CURSOR_KEY] ?? "")) hostUpdates[SETTLE_CURSOR_KEY] = settled.cursor ?? "";
|
|
2523
|
+
if (timeouts > 0 && timeouts < SETTLE_MAX_TIMEOUTS) hostUpdates[SETTLE_TIMEOUTS_KEY] = "";
|
|
2524
|
+
if (restarting && settled?.fromStart) hostUpdates[KNOWLEDGE_IMPORT_SETTLE_SEEN_KEY] = restart;
|
|
2525
|
+
const state = {
|
|
2526
|
+
...body.state,
|
|
2527
|
+
...hostUpdates
|
|
2528
|
+
};
|
|
2529
|
+
if (Object.keys(state).length) await importers.setState(binding.id, state);
|
|
2530
|
+
for (const change of applied.changes) await importers.recordRunChange({
|
|
2531
|
+
runId: run.id,
|
|
2532
|
+
...change
|
|
2533
|
+
});
|
|
2534
|
+
const receipt = {
|
|
2535
|
+
seq: flush.seq,
|
|
2536
|
+
...applied.counts,
|
|
2537
|
+
refused: applied.refused,
|
|
2538
|
+
pending: settled?.pending ?? false
|
|
2539
|
+
};
|
|
2540
|
+
await importers.recordFlush({
|
|
2541
|
+
runId: run.id,
|
|
2542
|
+
generation: flush.generation,
|
|
2543
|
+
seq: flush.seq,
|
|
2544
|
+
digest,
|
|
2545
|
+
receipt,
|
|
2546
|
+
counts: {
|
|
2547
|
+
...applied.counts,
|
|
2548
|
+
refused: applied.refused.length,
|
|
2549
|
+
settled: settled?.settled ?? 0
|
|
2550
|
+
}
|
|
2551
|
+
});
|
|
2552
|
+
if (applied.applied && !guard.firstWriteAt) await importers.markFirstWrite();
|
|
2553
|
+
embeds = applied.embeds;
|
|
2554
|
+
return receipt;
|
|
2555
|
+
}, { deadlineAt });
|
|
2556
|
+
let receipt;
|
|
2557
|
+
for (let attempt = 1; receipt === void 0; attempt++) try {
|
|
2558
|
+
receipt = await write(deadlineAt);
|
|
2559
|
+
} catch (error) {
|
|
2560
|
+
if (!(error instanceof LeaseCutoff)) throw error;
|
|
2561
|
+
if (attempt >= MAX_LEASE_BOUND_ATTEMPTS) throw new KnowledgeImporterHostError("The flush could not be bounded by its run lease; resend it.", 503);
|
|
2562
|
+
deadlineAt = Math.min(budgetAt, error.cutoff - LEASE_CUTOFF_MARGIN_MS);
|
|
2563
|
+
}
|
|
2564
|
+
await runEmbeds(storage, embeds);
|
|
2565
|
+
return receipt;
|
|
2566
|
+
} catch (error) {
|
|
2567
|
+
if (settling && timedOut(error)) await countSettleTimeout(flush.runId, flush.generation);
|
|
2568
|
+
throw hostError(error);
|
|
2569
|
+
}
|
|
2570
|
+
},
|
|
2571
|
+
async heartbeat(runId, generation) {
|
|
2572
|
+
try {
|
|
2573
|
+
const { storage, importers } = await storageAndImporters();
|
|
2574
|
+
if (leaseMs === void 0) {
|
|
2575
|
+
const run = await importers.heartbeat(runId);
|
|
2576
|
+
return { cancel: !run || run.generation !== generation || run.cancelRequestedAt !== null };
|
|
2577
|
+
}
|
|
2578
|
+
return await storage.transaction(async (tx) => {
|
|
2579
|
+
const locked = tx.importers;
|
|
2580
|
+
const guard = await locked.lockWriterGuard("share");
|
|
2581
|
+
const run = await locked.lockRun(runId);
|
|
2582
|
+
if (!run || run.status !== "running") throw conflict("run_not_active", "The run is not running.");
|
|
2583
|
+
if (run.generation !== generation || guard.generation !== generation) throw conflict("stale_generation", "The run belongs to an older writer generation.");
|
|
2584
|
+
if (lapsed(run, await clock(locked))) throw conflict("run_not_active", "The run is past its lease or deadline.");
|
|
2585
|
+
if (run.cancelRequestedAt) return { cancel: true };
|
|
2586
|
+
await locked.heartbeat(runId);
|
|
2587
|
+
return { cancel: false };
|
|
2588
|
+
});
|
|
2589
|
+
} catch (error) {
|
|
2590
|
+
throw hostError(error);
|
|
2591
|
+
}
|
|
2592
|
+
},
|
|
2593
|
+
async requestCancel(runId) {
|
|
2594
|
+
const { storage } = await storageAndImporters();
|
|
2595
|
+
try {
|
|
2596
|
+
return await storage.transaction(async (tx) => {
|
|
2597
|
+
const importers = tx.importers;
|
|
2598
|
+
await importers.lockWriterGuard("share");
|
|
2599
|
+
const run = await importers.lockRun(runId);
|
|
2600
|
+
if (!run) return null;
|
|
2601
|
+
if (run.status !== "running") return { status: run.status };
|
|
2602
|
+
await importers.requestCancel(runId);
|
|
2603
|
+
return { status: run.status };
|
|
2604
|
+
});
|
|
2605
|
+
} catch (error) {
|
|
2606
|
+
throw hostError(error);
|
|
2607
|
+
}
|
|
2608
|
+
},
|
|
2609
|
+
async retireBinding(bindingId) {
|
|
2610
|
+
const { storage } = await storageAndImporters();
|
|
2611
|
+
try {
|
|
2612
|
+
await storage.transaction(async (tx) => {
|
|
2613
|
+
await tx.importers.lockWriterGuard("share");
|
|
2614
|
+
await tx.importers.retireBinding(bindingId);
|
|
2615
|
+
});
|
|
2616
|
+
} catch (error) {
|
|
2617
|
+
throw hostError(error);
|
|
2618
|
+
}
|
|
2619
|
+
},
|
|
2620
|
+
async expireRuns() {
|
|
2621
|
+
const { storage, importers: root } = await storageAndImporters();
|
|
2622
|
+
const expired = [];
|
|
2623
|
+
try {
|
|
2624
|
+
const candidates = [];
|
|
2625
|
+
for (const stored of await root.listBindings()) for (const run of await root.listRuns(stored.id)) if (run.status === "running") candidates.push(run.id);
|
|
2626
|
+
for (const runId of candidates) if (await storage.transaction(async (tx) => {
|
|
2627
|
+
const importers = tx.importers;
|
|
2628
|
+
await importers.lockWriterGuard("share");
|
|
2629
|
+
const run = await importers.lockRun(runId);
|
|
2630
|
+
return !!run && run.status === "running" && await expireLocked(importers, run);
|
|
2631
|
+
})) expired.push(runId);
|
|
2632
|
+
return { expired };
|
|
2633
|
+
} catch (error) {
|
|
2634
|
+
throw hostError(error);
|
|
2635
|
+
}
|
|
2636
|
+
},
|
|
2637
|
+
async readRun(runId) {
|
|
2638
|
+
const { importers } = await storageAndImporters();
|
|
2639
|
+
const run = await importers.getRun(runId);
|
|
2640
|
+
if (!run) return null;
|
|
2641
|
+
return {
|
|
2642
|
+
status: run.status,
|
|
2643
|
+
receipt: run.status === "running" || !run.finish ? null : runReceipt(run)
|
|
2644
|
+
};
|
|
2645
|
+
},
|
|
2646
|
+
async finishRun(request) {
|
|
2647
|
+
let normalized;
|
|
2648
|
+
try {
|
|
2649
|
+
normalized = normalizeKnowledgeImporterFinish(request);
|
|
2650
|
+
} catch (error) {
|
|
2651
|
+
throw new KnowledgeImporterHostError(`Malformed finish: ${error.message}`, 400);
|
|
2652
|
+
}
|
|
2653
|
+
const { storage } = await storageAndImporters();
|
|
2654
|
+
try {
|
|
2655
|
+
return await storage.transaction(async (tx) => {
|
|
2656
|
+
const importers = tx.importers;
|
|
2657
|
+
const guard = await importers.lockWriterGuard("share");
|
|
2658
|
+
const run = await importers.lockRun(request.runId);
|
|
2659
|
+
if (!run) throw conflict("run_not_active", "No such run.");
|
|
2660
|
+
if (run.finish !== null) {
|
|
2661
|
+
if (run.finish.by === "host") throw conflict("run_not_active", "The host ended the run.");
|
|
2662
|
+
if (run.generation === request.generation && canonicalJson(replayIdentity(run.finish)) === canonicalJson(normalized)) return runReceipt(run);
|
|
2663
|
+
throw conflict("finish_mismatch", "The run already finished differently.");
|
|
2664
|
+
}
|
|
2665
|
+
if (run.status !== "running") throw conflict("run_not_active", "The run is not running.");
|
|
2666
|
+
if (run.generation !== request.generation || guard.generation !== request.generation) throw conflict("stale_generation", "The run belongs to an older writer generation.");
|
|
2667
|
+
if (leaseMs !== void 0 && lapsed(run, await clock(importers))) throw conflict("run_not_active", "The run is past its lease or deadline.");
|
|
2668
|
+
if (run.lastSeq !== request.lastSeq) throw conflict("seq_mismatch", "lastSeq is not the committed seq.");
|
|
2669
|
+
if (run.cancelRequestedAt) {
|
|
2670
|
+
const canceled = await importers.finishRun({
|
|
2671
|
+
runId: run.id,
|
|
2672
|
+
generation: request.generation,
|
|
2673
|
+
lastSeq: request.lastSeq,
|
|
2674
|
+
status: "canceled",
|
|
2675
|
+
finish: {
|
|
2676
|
+
...normalized,
|
|
2677
|
+
chain: false,
|
|
2678
|
+
canceled: true
|
|
2679
|
+
}
|
|
2680
|
+
});
|
|
2681
|
+
return runReceipt(canceled);
|
|
2682
|
+
}
|
|
2683
|
+
const pending = ((run.lastSeq > 0 ? await importers.getFlush(run.id, run.generation, run.lastSeq) : null)?.receipt)?.pending === true;
|
|
2684
|
+
const binding = await importers.getBinding(run.bindingId);
|
|
2685
|
+
const gaveUp = !!binding && settleTimeouts(await importers.getState(binding.id), run.id) >= SETTLE_MAX_TIMEOUTS;
|
|
2686
|
+
const chain = normalized.backlog || normalized.outcome === "succeeded" && pending && !gaveUp && (run.counts.settled ?? 0) > 0;
|
|
2687
|
+
const finished = await importers.finishRun({
|
|
2688
|
+
runId: run.id,
|
|
2689
|
+
generation: request.generation,
|
|
2690
|
+
lastSeq: request.lastSeq,
|
|
2691
|
+
status: normalized.outcome,
|
|
2692
|
+
finish: {
|
|
2693
|
+
...normalized,
|
|
2694
|
+
chain
|
|
2695
|
+
}
|
|
2696
|
+
});
|
|
2697
|
+
return runReceipt(finished);
|
|
2698
|
+
});
|
|
2699
|
+
} catch (error) {
|
|
2700
|
+
throw hostError(error);
|
|
2701
|
+
}
|
|
2702
|
+
}
|
|
2703
|
+
};
|
|
2704
|
+
}
|
|
114
2705
|
// src/knowledge/reembed.ts
|
|
115
2706
|
const DEFAULT_LIMIT = 50;
|
|
116
2707
|
const MAX_LIMIT = 500;
|
|
@@ -624,6 +3215,23 @@ var KnowledgeScopeRuntime = class {
|
|
|
624
3215
|
return this.#materialize(address, principals, provenance, [], { held: this.#held(principals) });
|
|
625
3216
|
}
|
|
626
3217
|
/**
|
|
3218
|
+
* {@link materializeScope} through `storage`, a transaction view, so the scope's rows commit or
|
|
3219
|
+
* roll back with the caller's transaction. Declarations must already be resolved
|
|
3220
|
+
* ({@link resolve}): nothing here reads the runtime's own storage, so a one-connection pool
|
|
3221
|
+
* can't deadlock against the open transaction. `wrote` is false only when no row can have changed.
|
|
3222
|
+
*/
|
|
3223
|
+
async materializeScopeIn(storage, address, provenance) {
|
|
3224
|
+
const run = {
|
|
3225
|
+
held: this.#held([]),
|
|
3226
|
+
storage,
|
|
3227
|
+
wrote: false
|
|
3228
|
+
};
|
|
3229
|
+
return {
|
|
3230
|
+
scope: await this.#materialize(address, [], provenance, [], run),
|
|
3231
|
+
wrote: run.wrote === true
|
|
3232
|
+
};
|
|
3233
|
+
}
|
|
3234
|
+
/**
|
|
627
3235
|
* {@link materializeScope} for each address in turn (a write-run start's principals), reading
|
|
628
3236
|
* scopes from one lookup. `#materialize` skips the store call for a scope that exists, needs no new
|
|
629
3237
|
* `belongsTo` link, has its child scopes and declares no template pages; warnings fire as before.
|
|
@@ -677,7 +3285,7 @@ var KnowledgeScopeRuntime = class {
|
|
|
677
3285
|
const match = this.compiled.match(address);
|
|
678
3286
|
if (!match) throw new require_run_registry.KnowledgeDeclarationError(`Knowledge scope "${address}" does not match a declared scope type.`);
|
|
679
3287
|
if (ancestors.includes(address)) throw new require_run_registry.KnowledgeDeclarationError(`Knowledge scope placement cycle at "${address}".`);
|
|
680
|
-
const storage = await this.getStorage();
|
|
3288
|
+
const storage = run.storage ?? await this.getStorage();
|
|
681
3289
|
const known = run.known;
|
|
682
3290
|
const lookUp = async (scope) => known?.looked.has(scope) || known?.byAddress.has(scope) ? known.byAddress.get(scope) : (await storage.getScopesByAddress([scope]))[0];
|
|
683
3291
|
if (match.compiled.child) {
|
|
@@ -710,6 +3318,7 @@ var KnowledgeScopeRuntime = class {
|
|
|
710
3318
|
}
|
|
711
3319
|
const declaration = match.compiled.declaration;
|
|
712
3320
|
if (known && existing && parentId === existing.parentId && !declaration.pages?.length && match.compiled.children.every((child) => known.byAddress.has(`${address}/${child.child.name}`))) return existing;
|
|
3321
|
+
const templateCount = declaration.pages?.length ?? 0;
|
|
713
3322
|
const result = await storage.materializeScope({
|
|
714
3323
|
address,
|
|
715
3324
|
declaration: match.declaration,
|
|
@@ -726,6 +3335,7 @@ var KnowledgeScopeRuntime = class {
|
|
|
726
3335
|
provenance
|
|
727
3336
|
});
|
|
728
3337
|
this.#assertCurrent(result.scope);
|
|
3338
|
+
if (!existing || result.created || templateCount > 0 || match.compiled.children.length > 0 || result.scope.parentId !== existing.parentId) run.wrote = true;
|
|
729
3339
|
if (result.created) await require_run_registry.updateKnowledgeLinks(this.warn, () => require_run_registry.refreshKnowledgeLinksTo(storage, [result.scope], { withDescendants: true }));
|
|
730
3340
|
if (result.parentConflict) this.warn(`Knowledge scope "${address}" was already linked by another run; keeping its persisted parent.`);
|
|
731
3341
|
if (run.known) {
|
|
@@ -1285,6 +3895,8 @@ async function readKnowledgePageLinks(store, input) {
|
|
|
1285
3895
|
};
|
|
1286
3896
|
}
|
|
1287
3897
|
// src/knowledge/index.ts
|
|
3898
|
+
/** Reads a Knowledge's host writer for {@link createKnowledgeImporterHost}; set in the class's static block. */
|
|
3899
|
+
let hostWriterOf;
|
|
1288
3900
|
function resolvePins(pins) {
|
|
1289
3901
|
if (!pins) return false;
|
|
1290
3902
|
const options = pins === true ? {} : pins;
|
|
@@ -1307,6 +3919,7 @@ var Knowledge = class extends require_base.MastraBase {
|
|
|
1307
3919
|
#tools;
|
|
1308
3920
|
#pins;
|
|
1309
3921
|
#instructions;
|
|
3922
|
+
#importers;
|
|
1310
3923
|
#semantic;
|
|
1311
3924
|
#listeners = /* @__PURE__ */ new Set();
|
|
1312
3925
|
/** Config pins are never dropped, so a scope with more of them than the budget holds is a setup mistake. */
|
|
@@ -1340,6 +3953,15 @@ var Knowledge = class extends require_base.MastraBase {
|
|
|
1340
3953
|
if (maxTokens !== void 0 && (!Number.isInteger(maxTokens) || maxTokens < 100)) throw new Error(`Knowledge \`tools.read.maxTokens\` must be a whole number of at least 100; got ${maxTokens}.`);
|
|
1341
3954
|
this.#pins = resolvePins(config.pinnedContext);
|
|
1342
3955
|
this.#instructions = config.instructions;
|
|
3956
|
+
if (config.importers) {
|
|
3957
|
+
knowledgeImporterRegistry(config.importers.map((importer) => importer.constructor));
|
|
3958
|
+
const ids = /* @__PURE__ */ new Set();
|
|
3959
|
+
for (const importer of config.importers) {
|
|
3960
|
+
if (ids.has(importer.binding.id)) throw new KnowledgeImporterDefinitionError(`Two importers have the binding id "${importer.binding.id}".`);
|
|
3961
|
+
ids.add(importer.binding.id);
|
|
3962
|
+
}
|
|
3963
|
+
}
|
|
3964
|
+
this.#importers = config.importers;
|
|
1343
3965
|
if (Boolean(config.vector) !== Boolean(config.embedder)) throw new Error("Knowledge semantic search needs both `vector` and `embedder`; pass both or neither.");
|
|
1344
3966
|
if (config.vector && config.embedder) this.#semantic = new require_run_registry.KnowledgeSemanticIndex(config.vector, config.embedder, config.embedderOptions);
|
|
1345
3967
|
this.#runtime = new KnowledgeScopeRuntime(config.scopes, () => this.getStorage(), (message) => this.logger.warn(message));
|
|
@@ -1374,10 +3996,22 @@ var Knowledge = class extends require_base.MastraBase {
|
|
|
1374
3996
|
return this.#runtime.explainAccess(runScopes, target);
|
|
1375
3997
|
}
|
|
1376
3998
|
/**
|
|
3999
|
+
* Reads the store's scope declarations into the ones {@link scopeGrants}, {@link scopeDeclaration}
|
|
4000
|
+
* and {@link scopeLabel} use, reusing a read from the last 30 seconds. Call it before those when
|
|
4001
|
+
* nothing else async ran first, e.g. at the start of a browsing request. Checks nothing and grants
|
|
4002
|
+
* nothing.
|
|
4003
|
+
*
|
|
4004
|
+
* @experimental
|
|
4005
|
+
*/
|
|
4006
|
+
async resolveScopeDeclarations() {
|
|
4007
|
+
await this.#runtime.resolve();
|
|
4008
|
+
}
|
|
4009
|
+
/**
|
|
1377
4010
|
* Who the declared rules give a role on one scope: each principal scope address (bound for this
|
|
1378
4011
|
* scope's params) with its strongest role, `self` rules left out. `parentAddress` is the
|
|
1379
4012
|
* address of the scope page's tree parent, needed for rules that bind through `belongsTo`. Reads the
|
|
1380
|
-
* declarations as last resolved, not storage
|
|
4013
|
+
* declarations as last resolved, not storage (see {@link Knowledge.resolveScopeDeclarations}). For
|
|
4014
|
+
* browsing UIs that draw access between scopes.
|
|
1381
4015
|
*
|
|
1382
4016
|
* @experimental
|
|
1383
4017
|
*/
|
|
@@ -1449,7 +4083,8 @@ var Knowledge = class extends require_base.MastraBase {
|
|
|
1449
4083
|
* Deletes the page at `scope#path`; `null` when there is none. Refuses a page with child pages
|
|
1450
4084
|
* and a page declared in config. Host-only, like {@link Knowledge.upsertPage}. Not retried: a
|
|
1451
4085
|
* concurrent write to the same page between the read and the delete throws, so remove from one
|
|
1452
|
-
* sync worker or retry the call.
|
|
4086
|
+
* sync worker or retry the call. Pass `expected` to delete only the page you read, at the version
|
|
4087
|
+
* you read: anything else at the path throws `KnowledgeConflictError` and nothing is deleted.
|
|
1453
4088
|
*
|
|
1454
4089
|
* @experimental
|
|
1455
4090
|
*/
|
|
@@ -1498,6 +4133,30 @@ var Knowledge = class extends require_base.MastraBase {
|
|
|
1498
4133
|
removeNote(input) {
|
|
1499
4134
|
return require_run_registry.removeKnowledgeNote(this.#hostWriter(), input);
|
|
1500
4135
|
}
|
|
4136
|
+
/**
|
|
4137
|
+
* The app's importers: `host` applies flushes to this Knowledge's storage, and `run` runs one
|
|
4138
|
+
* binding's importer through it. Undefined without `importers` in the config. Host-only, like
|
|
4139
|
+
* {@link Knowledge.upsertPage}: never expose `run` without admin-level auth.
|
|
4140
|
+
*
|
|
4141
|
+
* @experimental
|
|
4142
|
+
*/
|
|
4143
|
+
get importers() {
|
|
4144
|
+
const importers = this.#importers;
|
|
4145
|
+
if (!importers) return void 0;
|
|
4146
|
+
const host = createKnowledgeImporterHost(this, { bindings: importers.map((importer) => importer.binding) });
|
|
4147
|
+
return {
|
|
4148
|
+
host,
|
|
4149
|
+
run: (bindingId, options) => runKnowledgeImport({
|
|
4150
|
+
...options,
|
|
4151
|
+
importers,
|
|
4152
|
+
host,
|
|
4153
|
+
bindingId
|
|
4154
|
+
})
|
|
4155
|
+
};
|
|
4156
|
+
}
|
|
4157
|
+
static {
|
|
4158
|
+
hostWriterOf = (knowledge) => knowledge.#hostWriter();
|
|
4159
|
+
}
|
|
1501
4160
|
#hostWriter() {
|
|
1502
4161
|
return {
|
|
1503
4162
|
runtime: this.#runtime,
|
|
@@ -1540,6 +4199,14 @@ var Knowledge = class extends require_base.MastraBase {
|
|
|
1540
4199
|
get pinnedContextEnabled() {
|
|
1541
4200
|
return this.#pins !== false;
|
|
1542
4201
|
}
|
|
4202
|
+
/** Which tool groups `createTools()` and `getInstructions()` include by default. @internal */
|
|
4203
|
+
get __toolGroups() {
|
|
4204
|
+
const { read, write } = this.#groups();
|
|
4205
|
+
return {
|
|
4206
|
+
read,
|
|
4207
|
+
write
|
|
4208
|
+
};
|
|
4209
|
+
}
|
|
1543
4210
|
/** The run's principals as a stable key; throws when the run has none or holds an undeclared scope. @internal */
|
|
1544
4211
|
__principalsKey(context) {
|
|
1545
4212
|
return require_run_registry.knowledgeRunPrincipals(this.#runtime, context).sort().join("\n");
|
|
@@ -1547,14 +4214,15 @@ var Knowledge = class extends require_base.MastraBase {
|
|
|
1547
4214
|
/**
|
|
1548
4215
|
* The pinned pages a host-run caller with these principals receives, rendered as an agent run
|
|
1549
4216
|
* receives them: only pages they can read, within this instance's pin budget. For hosts that serve
|
|
1550
|
-
* Knowledge outside an agent run, alongside {@link Knowledge.createTools} with `principals`.
|
|
4217
|
+
* Knowledge outside an agent run, alongside {@link Knowledge.createTools} with `principals`. Pass the
|
|
4218
|
+
* same `read` as that `createTools` call, so entries name read tools only when the caller has them.
|
|
1551
4219
|
*/
|
|
1552
4220
|
async getPinnedContext(options) {
|
|
1553
4221
|
const principals = this.#hostPrincipals(options.principals);
|
|
1554
4222
|
const budget = this.#pins || resolvePins(true);
|
|
1555
4223
|
if (!budget) return [];
|
|
1556
4224
|
const run = await require_run_registry.KnowledgeRun.start(this.#runtime, await this.getStorage(), void 0, { principals });
|
|
1557
|
-
return require_run_registry.knowledgeDeliveredPins(run, budget);
|
|
4225
|
+
return require_run_registry.knowledgeDeliveredPins(run, budget, this.#groups({ read: options.read }).read);
|
|
1558
4226
|
}
|
|
1559
4227
|
#hostPrincipals(principals) {
|
|
1560
4228
|
const unique = [...new Set(principals)];
|
|
@@ -1566,7 +4234,7 @@ var Knowledge = class extends require_base.MastraBase {
|
|
|
1566
4234
|
const budget = this.#pins || resolvePins(true);
|
|
1567
4235
|
if (!budget) return [];
|
|
1568
4236
|
const run = await require_run_registry.KnowledgeRun.start(this.#runtime, await this.getStorage(), context);
|
|
1569
|
-
return require_run_registry.knowledgeDeliveredPins(run, budget);
|
|
4237
|
+
return require_run_registry.knowledgeDeliveredPins(run, budget, this.#groups().read);
|
|
1570
4238
|
}
|
|
1571
4239
|
/** @internal */
|
|
1572
4240
|
__registerMastra(_mastra) {}
|
|
@@ -1637,7 +4305,8 @@ var Knowledge = class extends require_base.MastraBase {
|
|
|
1637
4305
|
/**
|
|
1638
4306
|
* The declaration a scope page was created from, by its `declaration` key (template children
|
|
1639
4307
|
* included, e.g. `account:$orgId:$accountId/internal`), for display. Access rules are left out;
|
|
1640
|
-
* use `explainAccess` for those. `undefined` for an unknown key.
|
|
4308
|
+
* use `explainAccess` for those. `undefined` for an unknown key. Reads the declarations as last
|
|
4309
|
+
* resolved, not storage; see {@link Knowledge.resolveScopeDeclarations}.
|
|
1641
4310
|
*/
|
|
1642
4311
|
scopeDeclaration(key) {
|
|
1643
4312
|
const compiled = this.#runtime.compiled.declarations.get(key);
|
|
@@ -1661,6 +4330,7 @@ var Knowledge = class extends require_base.MastraBase {
|
|
|
1661
4330
|
* declaration's `$params` filled in from the address's decoded values: `'$orgId policy'` on
|
|
1662
4331
|
* `policy:$orgId` gives `'acme policy'` for `policy:acme`. A concrete address's own `displayLabel`
|
|
1663
4332
|
* wins over its pattern's. `undefined` when the address matches no declaration or has no label.
|
|
4333
|
+
* Reads the declarations as last resolved, like {@link Knowledge.scopeDeclaration}.
|
|
1664
4334
|
*/
|
|
1665
4335
|
scopeLabel(address) {
|
|
1666
4336
|
const match = this.#runtime.compiled.match(address);
|
|
@@ -1669,13 +4339,40 @@ var Knowledge = class extends require_base.MastraBase {
|
|
|
1669
4339
|
return label.replace(/\$([A-Za-z_][A-Za-z0-9_]*)/g, (token, name) => Object.hasOwn(match.params, name) ? match.params[name] : token);
|
|
1670
4340
|
}
|
|
1671
4341
|
};
|
|
4342
|
+
/**
|
|
4343
|
+
* An importer host over this Knowledge's storage, for a host that applies flushes for bindings it
|
|
4344
|
+
* keeps itself and runs no importer code (a service that importers in other processes flush to).
|
|
4345
|
+
* Pass `bindings` as a function to read them at each run start. An app that runs its own importers
|
|
4346
|
+
* uses `new Knowledge({ importers: [...] })` and `knowledge.importers` instead.
|
|
4347
|
+
*
|
|
4348
|
+
* Host-only, like {@link Knowledge.upsertPage}: never expose it without admin-level auth.
|
|
4349
|
+
*
|
|
4350
|
+
* @experimental
|
|
4351
|
+
*/
|
|
4352
|
+
function createKnowledgeImporterHost(knowledge, options) {
|
|
4353
|
+
return createLocalKnowledgeImporterHost(hostWriterOf(knowledge), options);
|
|
4354
|
+
}
|
|
1672
4355
|
exports.DEFAULT_KNOWLEDGE_PAGE_GRAPH_LIMITS = DEFAULT_KNOWLEDGE_PAGE_GRAPH_LIMITS;
|
|
1673
4356
|
exports.InMemoryKnowledgeStorage = require_run_registry.InMemoryKnowledgeStorage;
|
|
4357
|
+
exports.KNOWLEDGE_IMPORTER_ERROR_CODES = KNOWLEDGE_IMPORTER_ERROR_CODES;
|
|
4358
|
+
exports.KNOWLEDGE_IMPORT_REMOVED_PARENT_BODY = REMOVED_PARENT_BODY;
|
|
1674
4359
|
exports.KNOWLEDGE_STORAGE_CONTRACT_VERSION = require_run_registry.KNOWLEDGE_STORAGE_CONTRACT_VERSION;
|
|
1675
4360
|
exports.KNOWLEDGE_STORAGE_SCHEMA_VERSION = require_run_registry.KNOWLEDGE_STORAGE_SCHEMA_VERSION;
|
|
1676
4361
|
exports.Knowledge = Knowledge;
|
|
1677
4362
|
exports.KnowledgeConflictError = require_run_registry.KnowledgeConflictError;
|
|
1678
4363
|
exports.KnowledgeDeclarationError = require_run_registry.KnowledgeDeclarationError;
|
|
4364
|
+
exports.KnowledgeImporter = KnowledgeImporter;
|
|
4365
|
+
exports.KnowledgeImporterBase = KnowledgeImporterBase;
|
|
4366
|
+
exports.KnowledgeImporterBindingConflictError = require_run_registry.KnowledgeImporterBindingConflictError;
|
|
4367
|
+
exports.KnowledgeImporterCredentialsError = KnowledgeImporterCredentialsError;
|
|
4368
|
+
exports.KnowledgeImporterDefinitionError = KnowledgeImporterDefinitionError;
|
|
4369
|
+
exports.KnowledgeImporterHostConflictError = KnowledgeImporterHostConflictError;
|
|
4370
|
+
exports.KnowledgeImporterHostError = KnowledgeImporterHostError;
|
|
4371
|
+
exports.KnowledgeImporterRunStateError = require_run_registry.KnowledgeImporterRunStateError;
|
|
4372
|
+
exports.KnowledgeImporterSettingsError = KnowledgeImporterSettingsError;
|
|
4373
|
+
exports.KnowledgeImporterSourceError = KnowledgeImporterSourceError;
|
|
4374
|
+
exports.KnowledgeImportersStorage = require_run_registry.KnowledgeImportersStorage;
|
|
4375
|
+
exports.KnowledgeInvalidCursorError = require_run_registry.KnowledgeInvalidCursorError;
|
|
1679
4376
|
exports.KnowledgeMoveTooLargeError = require_run_registry.KnowledgeMoveTooLargeError;
|
|
1680
4377
|
exports.KnowledgeNotFoundError = require_run_registry.KnowledgeNotFoundError;
|
|
1681
4378
|
exports.KnowledgePageDepthError = require_run_registry.KnowledgePageDepthError;
|
|
@@ -1683,6 +4380,7 @@ exports.KnowledgePageHasChildrenError = require_run_registry.KnowledgePageHasChi
|
|
|
1683
4380
|
exports.KnowledgePageKeyConflictError = require_run_registry.KnowledgePageKeyConflictError;
|
|
1684
4381
|
exports.KnowledgeSchemaResetRequiredError = require_run_registry.KnowledgeSchemaResetRequiredError;
|
|
1685
4382
|
exports.KnowledgeStorage = require_run_registry.KnowledgeStorage;
|
|
4383
|
+
exports.KnowledgeTransactionDeadlineError = require_run_registry.KnowledgeTransactionDeadlineError;
|
|
1686
4384
|
exports.KnowledgeUnsupportedCapabilityError = require_run_registry.KnowledgeUnsupportedCapabilityError;
|
|
1687
4385
|
exports.MAX_KNOWLEDGE_EXPLORER_PAGE_LINKS = MAX_KNOWLEDGE_EXPLORER_PAGE_LINKS;
|
|
1688
4386
|
exports.MAX_KNOWLEDGE_LINK_COUNT_PAGES = MAX_KNOWLEDGE_LINK_COUNT_PAGES;
|
|
@@ -1705,15 +4403,21 @@ exports.assertKnowledgePageDescriptionWithinBound = require_run_registry.assertK
|
|
|
1705
4403
|
exports.assertKnowledgeRecordTextWithinBound = require_run_registry.assertKnowledgeRecordTextWithinBound;
|
|
1706
4404
|
exports.assertKnowledgeSchemaCompatible = require_run_registry.assertKnowledgeSchemaCompatible;
|
|
1707
4405
|
exports.assertKnowledgeScopeWithinCeiling = require_run_registry.assertKnowledgeScopeWithinCeiling;
|
|
4406
|
+
exports.canonicalJson = canonicalJson;
|
|
1708
4407
|
exports.canonicalKnowledgeName = require_run_registry.canonicalKnowledgeName;
|
|
1709
4408
|
exports.canonicalizeKnowledgeScope = require_run_registry.canonicalizeKnowledgeScope;
|
|
4409
|
+
exports.createKnowledgeImporterHost = createKnowledgeImporterHost;
|
|
1710
4410
|
exports.createKnowledgeNodeCursor = require_run_registry.createKnowledgeNodeCursor;
|
|
1711
4411
|
exports.createKnowledgeUlid = require_run_registry.createKnowledgeUlid;
|
|
1712
4412
|
exports.decodeKnowledgeScopeId = require_run_registry.decodeKnowledgeScopeId;
|
|
1713
4413
|
exports.encodeKnowledgeScopeId = require_run_registry.encodeKnowledgeScopeId;
|
|
1714
4414
|
exports.expandKnowledgeScope = require_run_registry.expandKnowledgeScope;
|
|
4415
|
+
exports.importerHostConformance = importerHostConformance;
|
|
1715
4416
|
exports.inspectKnowledgeSchema = require_run_registry.inspectKnowledgeSchema;
|
|
1716
4417
|
exports.isKnowledgeScopeVisible = require_run_registry.isKnowledgeScopeVisible;
|
|
4418
|
+
exports.knowledgeImportKey = knowledgeImportKey;
|
|
4419
|
+
exports.knowledgeImporterFlushDigest = knowledgeImporterFlushDigest;
|
|
4420
|
+
exports.knowledgeImporterRegistry = knowledgeImporterRegistry;
|
|
1717
4421
|
exports.knowledgeLinkRefKey = require_run_registry.knowledgeLinkRefKey;
|
|
1718
4422
|
exports.knowledgeMemoryScopes = require_run_registry.knowledgeMemoryScopes;
|
|
1719
4423
|
exports.knowledgePagePath = require_run_registry.knowledgePagePath;
|
|
@@ -1726,6 +4430,8 @@ exports.knowledgeSemanticDocumentId = require_run_registry.knowledgeSemanticDocu
|
|
|
1726
4430
|
exports.knowledgeSemanticIdempotencyKey = require_run_registry.knowledgeSemanticIdempotencyKey;
|
|
1727
4431
|
exports.knowledgeVisibleScopeKeys = require_run_registry.knowledgeVisibleScopeKeys;
|
|
1728
4432
|
exports.listKnowledgeTreeChildren = listKnowledgeTreeChildren;
|
|
4433
|
+
exports.normalizeKnowledgeImporterFinish = normalizeKnowledgeImporterFinish;
|
|
4434
|
+
exports.parseKnowledgeImporterFlushBody = parseKnowledgeImporterFlushBody;
|
|
1729
4435
|
exports.parseKnowledgeNodeCursor = require_run_registry.parseKnowledgeNodeCursor;
|
|
1730
4436
|
exports.parseKnowledgePageRef = require_run_registry.parseKnowledgePageRef;
|
|
1731
4437
|
exports.parseKnowledgeWikilinks = require_run_registry.parseKnowledgeWikilinks;
|
|
@@ -1735,4 +4441,5 @@ exports.readKnowledgePageGraph = readKnowledgePageGraph;
|
|
|
1735
4441
|
exports.readKnowledgePageLinkCounts = readKnowledgePageLinkCounts;
|
|
1736
4442
|
exports.readKnowledgePageLinks = readKnowledgePageLinks;
|
|
1737
4443
|
exports.readKnowledgeScopeGrants = readKnowledgeScopeGrants;
|
|
4444
|
+
exports.runKnowledgeImport = runKnowledgeImport;
|
|
1738
4445
|
exports.searchKnowledgeExplorerPages = searchKnowledgeExplorerPages;
|