UNPKG

@mastra/core

Version:
1,649 lines • 63.9 kB
import { t as MastraBase } from "../base-CKLWBhDo.js";
import { $s as assertKnowledgeRecordTextWithinBound, Ac as knowledgePositionBetween, As as updateKnowledgeNote, Bc as assertKnowledgeSchemaCompatible, Bs as KnowledgeDeclarationError, Cc as MAX_KNOWLEDGE_PIN_LIST_DEPTH, Dc as knowledgeLinkRefKey, Ds as moveKnowledgePage, Ec as canonicalKnowledgeName, Es as addKnowledgeNote, Fc as KnowledgeConflictError, Fs as reindexKnowledgeLinks, Gs as strongerKnowledgeRole, Gt as getStorageSource, Hc as inspectKnowledgeSchema, Hs as knowledgeMemoryScopes, Ic as KnowledgeNotFoundError, Is as updateKnowledgeLinks, Js as MAX_KNOWLEDGE_NODE_DESCRIPTION_LENGTH, Ks as decodeKnowledgeScopeId, Lc as KnowledgeSchemaResetRequiredError, Ls as knowledgeAccessGrants, Mc as parseKnowledgePageRef, Ms as KnowledgeSemanticIndex, Nc as KNOWLEDGE_STORAGE_CONTRACT_VERSION, Oc as knowledgePagePath, Os as removeKnowledgeNote, Pc as KNOWLEDGE_STORAGE_SCHEMA_VERSION, Ps as refreshKnowledgeLinksTo, Qs as assertKnowledgeDescriptionWithinBound, Rc as KnowledgeStorage, Rs as knowledgeReadScopeFor, Sc as MAX_KNOWLEDGE_PAGE_LIST_LIMIT, Tc as assertKnowledgePageDescriptionWithinBound, Uc as parseKnowledgeWikilinks, Us as knowledgeRunScopes, Vc as createKnowledgeUlid, Vs as compileKnowledgeScopes, Wc as buildKnowledgeInstructions, Ws as knowledgeScopeAddress, Wt as augmentWithInit, Xs as MAX_KNOWLEDGE_SCOPE_TAGS, Ys as MAX_KNOWLEDGE_RECORD_TEXT_LENGTH, Zs as assertKnowledgeCeilingRaised, _c as MAX_KNOWLEDGE_PAGE_BODY_LINKS, _s as PINNED_READ_MEMO_KEY, ac as knowledgeScopeKey, bc as MAX_KNOWLEDGE_PAGE_LINKS, bs as KnowledgeRun, cc as knowledgeVisibleScopeKeys, dc as KnowledgeMoveTooLargeError, ec as assertKnowledgeScopeWithinCeiling, fc as KnowledgePageDepthError, gc as MAX_KNOWLEDGE_NOTE_TOKENS, hc as MAX_KNOWLEDGE_MOVE_PAGES, ic as isKnowledgeScopeVisible, jc as knowledgeScopeReadable, js as upsertKnowledgePage, kc as knowledgePinDepth, ks as removeKnowledgePage, lc as parseKnowledgeNodeCursor, mc as KnowledgePageKeyConflictError, nc as createKnowledgeNodeCursor, oc as knowledgeSemanticDocumentId, pc as KnowledgePageHasChildrenError, qs as encodeKnowledgeScopeId, rc as expandKnowledgeScope, sc as knowledgeSemanticIdempotencyKey, tc as canonicalizeKnowledgeScope, uc as InMemoryKnowledgeStorage, vc as MAX_KNOWLEDGE_PAGE_DEPTH, vs as knowledgeDeliveredPins, wc as assertKnowledgeNoteTextWithinBound, xc as MAX_KNOWLEDGE_PAGE_LINK_REF_LENGTH, xs as knowledgeRunPrincipals, yc as MAX_KNOWLEDGE_PAGE_DESCRIPTION_TOKENS, ys as buildKnowledgePageTools, zc as KnowledgeUnsupportedCapabilityError, zs as knowledgeRoleOn } from "../run-registry-Ca8idv6o.js";
import { randomUUID } from "crypto";
// src/knowledge/changes.ts
const page = (op) => (result) => {
	const { id, scopeId } = result;
	return {
		kind: "page",
		op,
		pageId: id,
		scopeId
	};
};
const note = (op) => (result) => {
	const { id, pageId } = result;
	return {
		kind: "note",
		op,
		pageId,
		noteId: id
	};
};
/** The page-store writes that emit, and the event each one's result maps to. */
const WRITES = {
	materializeScope: (result) => {
		const { scope, created } = result;
		return created ? {
			kind: "scope",
			op: "create",
			pageId: scope.id,
			scopeId: scope.id
		} : null;
	},
	createPage: page("create"),
	updatePage: page("update"),
	movePage: (result, _input, fromScopeId) => {
		const { id, scopeId } = result;
		return {
			kind: "page",
			op: "move",
			pageId: id,
			scopeId,
			fromScopeId
		};
	},
	deletePage: page("delete"),
	mergePages: (result, input, fromScopeId) => {
		const { id, scopeId } = result;
		return {
			kind: "page",
			op: "merge",
			pageId: id,
			scopeId,
			sourceId: input.sourceId,
			fromScopeId
		};
	},
	addNote: note("add"),
	restampNote: note("restamp"),
	removeNote: note("remove"),
	restoreNote: note("restore"),
	addPinAudience: (result) => ({
		kind: "pin",
		op: "add",
		pageId: result.pageId
	}),
	removePinAudience: (result, input) => ({
		kind: "pin",
		op: "remove",
		pageId: input.pageId
	})
};
/** Writes whose event says where the page was before; the page id is read from the input. */
const MOVED_PAGE = {
	movePage: (input) => input.id,
	mergePages: (input) => input.sourceId
};
/**
* Wraps `storage` so each page-store write in {@link WRITES} calls `emit` after it resolves. Every
* other member passes through, bound to the real store so adapters' private fields keep working.
* Nothing extra happens while `listening()` is false. Describing or emitting an event never fails a
* write that committed: errors go to `onError`.
*/
function emitKnowledgeChanges(storage, emit, listening, onError) {
	return new Proxy(storage, { get(target, property) {
		const value = Reflect.get(target, property, target);
		if (typeof value !== "function") return value;
		const describe = typeof property === "string" ? WRITES[property] : void 0;
		if (!describe) return value.bind(target);
		const moved = typeof property === "string" ? MOVED_PAGE[property] : void 0;
		return async (input, ...rest) => {
			let fromScopeId;
			if (moved && listening()) try {
				fromScopeId = (await target.getPage({
					id: moved(input),
					read: "all"
				}))?.scopeId;
			} catch (error) {
				onError(error);
			}
			const result = await value.call(target, input, ...rest);
			if (!listening()) return result;
			try {
				const change = describe(result, input, fromScopeId);
				if (change) emit(change);
			} catch (error) {
				onError(error);
			}
			return result;
		};
	} });
}
// src/knowledge/reembed.ts
const DEFAULT_LIMIT = 50;
const MAX_LIMIT = 500;
const NOTE_PAGE = 100;
function encode(position) {
	return Buffer.from(JSON.stringify({
		v: 2,
		...position
	})).toString("base64url");
}
function decode(cursor, scope) {
	let position;
	try {
		position = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));
	} catch {
		position = void 0;
	}
	if (!position || position.v !== 2 || ![
		"scope-notes",
		"pages",
		"scopes"
	].includes(position.phase)) throw new Error("Knowledge reembed: the cursor is not one reembed() returned.");
	if (position.scope !== scope) throw new Error("Knowledge reembed: the cursor was returned for a different scope.");
	return position;
}
/** A 429 from the embedder, whether thrown directly or as the last try of a retry error. */
function isRateLimit(error) {
	const e = error;
	return e?.statusCode === 429 || e?.lastError?.statusCode === 429;
}
function message(error) {
	return error instanceof Error ? error.message : String(error);
}
var RateLimited = class extends Error {};
/**
* Embeds existing pages and notes in batches, without changing them. Each call handles up to
* `limit` pages with their notes and returns a cursor to go on from, so a run over a large store
* can stop and resume. Vector ids are fixed per page chunk and note, so handling a page again
* overwrites its vectors.
* @internal
*/
async function reembedKnowledge(storage, index, options = {}) {
	const limit = options.limit ?? DEFAULT_LIMIT;
	if (!Number.isInteger(limit) || limit < 1 || limit > MAX_LIMIT) throw new Error(`Knowledge reembed: limit must be an integer from 1 to ${MAX_LIMIT}.`);
	let scopeId;
	if (options.scope !== void 0) {
		const [scope] = await storage.getScopesByAddress([options.scope]);
		if (!scope) throw new Error(`Knowledge reembed: no scope "${options.scope}".`);
		scopeId = scope.id;
	}
	const { item: resumeItem, ...start } = options.cursor ? decode(options.cursor, options.scope) : options.scope ? {
		scope: options.scope,
		phase: "scope-notes"
	} : {
		phase: "pages",
		skip: 0
	};
	let position = start;
	const result = {
		embedded: {
			pages: 0,
			notes: 0
		},
		failed: [],
		overChunkCap: []
	};
	let handled = 0;
	let item = resumeItem ?? {
		body: false,
		ns: 0
	};
	/** Notes on one page, from where `item` says the last call stopped. */
	const notesOn = async (pageId) => {
		do {
			const page = await storage.listNotes({
				pageId,
				read: "all",
				cursor: item.nc,
				limit: NOTE_PAGE
			});
			for (const note of page.notes.slice(item.ns)) {
				try {
					await index.indexNote(note);
					result.embedded.notes++;
				} catch (error) {
					if (isRateLimit(error)) throw new RateLimited();
					result.failed.push({
						kind: "note",
						id: note.id,
						error: message(error)
					});
				}
				item = {
					...item,
					ns: item.ns + 1
				};
			}
			if (!page.nextCursor) break;
			item = {
				...item,
				nc: page.nextCursor,
				ns: 0
			};
		} while (true);
	};
	/** One ordinary page with its notes. */
	const handlePage = async (page) => {
		if (!item.body) {
			try {
				const chunks = await index.indexPage(page, item.bc ?? 0);
				result.embedded.pages++;
				if (chunks > 100) result.overChunkCap.push({
					pageId: page.id,
					chunks
				});
			} catch (error) {
				if (isRateLimit(error)) {
					const stored = error.knowledgeStoredChunks;
					if (stored) item = {
						...item,
						bc: stored
					};
					throw new RateLimited();
				}
				result.failed.push({
					kind: "page",
					id: page.id,
					error: message(error)
				});
			}
			item = {
				...item,
				body: true,
				bc: void 0
			};
		}
		await notesOn(page.id);
	};
	/** Notes on a scope page (scope pages themselves aren't embedded). */
	const handleScope = (scopePageId) => notesOn(scopePageId);
	const done = () => {
		item = {
			body: false,
			ns: 0
		};
	};
	try {
		while (position && handled < limit) {
			if (position.phase === "scope-notes") {
				await handleScope(scopeId);
				done();
				position = {
					scope: options.scope,
					phase: "pages",
					skip: 0
				};
				continue;
			}
			if (position.phase === "pages") {
				const listing = await storage.listPages({
					read: "all",
					scopeId,
					cursor: position.c,
					limit: position.skip + (limit - handled)
				});
				const pages = listing.pages.slice(position.skip);
				for (const page of pages) {
					if (handled >= limit) break;
					await handlePage(page);
					done();
					handled++;
					position = {
						...position,
						skip: position.skip + 1
					};
				}
				if (position.skip >= listing.pages.length) position = listing.nextCursor ? {
					...position,
					c: listing.nextCursor,
					skip: 0
				} : options.scope ? void 0 : {
					phase: "scopes",
					path: [{ p: null }]
				};
				continue;
			}
			const path = position.path;
			const { p, c } = path[path.length - 1];
			const listing = await storage.listChildScopes({
				parentId: p,
				cursor: c,
				limit: 1
			});
			const child = listing.pages[0];
			const rest = path.slice(0, -1);
			if (child) {
				await handleScope(child.id);
				done();
				const next = listing.nextCursor ? [{
					p,
					c: listing.nextCursor
				}] : [];
				position = {
					phase: "scopes",
					path: [
						...rest,
						...next,
						{ p: child.id }
					]
				};
			} else position = rest.length ? {
				phase: "scopes",
				path: rest
			} : void 0;
			handled++;
		}
	} catch (error) {
		if (!(error instanceof RateLimited)) throw error;
		result.rateLimited = true;
		if (position && (item.body || item.bc || item.ns > 0 || item.nc)) position = {
			...position,
			item
		};
	}
	if (position) result.nextCursor = encode(position);
	return result;
}
/** Declaration-backed access and lazy scope creation shared by the Knowledge lifecycle and tools. @internal */
var KnowledgeScopeRuntime = class {
	getStorage;
	warn;
	#config;
	#configCompiled;
	/** The last resolved declarations, keyed by what the store supplied. */
	#resolved;
	#declarationsChecked;
	/** The store's declarations as last read, shared by concurrent calls until they expire. */
	#stored;
	constructor(declarations, getStorage, warn) {
		this.getStorage = getStorage;
		this.warn = warn;
		this.#config = structuredClone(declarations);
		this.#configCompiled = compileKnowledgeScopes(structuredClone(declarations));
		this.#resolved = {
			stored: "{}",
			compiled: this.#configCompiled,
			skipped: /* @__PURE__ */ new Map()
		};
	}
	/** The declarations as last resolved: the config's, plus the store's from the latest {@link resolve}. */
	get compiled() {
		return this.#resolved.compiled;
	}
	/**
	* Reads the store's scope declarations and merges them under the config's: a key the config
	* declares keeps the config's declaration. Called once at the start of every call. The store's
	* answer is reused for {@link KNOWLEDGE_STORE_DECLARATIONS_TTL_MS}, so a declaration the store adds
	* or changes applies within that window, and right away after {@link invalidate}. A store
	* declaration that doesn't compile next to the others is skipped with a warning. Recompiles only
	* when the store's answer changes.
	*/
	async resolve() {
		const entry = this.#readStored();
		const stored = await entry.declarations;
		if (this.#stored !== entry) return this.resolve();
		const key = JSON.stringify(stored);
		if (key === this.#resolved.stored) return this.#resolved.compiled;
		let merged = this.#config;
		let compiled = this.#configCompiled;
		let pending = Object.entries(stored).filter(([name]) => !Object.hasOwn(this.#config, name));
		const failures = /* @__PURE__ */ new Map();
		const skippedReasons = /* @__PURE__ */ new Map();
		const add = (entries, failed) => {
			const next = {
				...merged,
				...Object.fromEntries(entries)
			};
			try {
				compiled = compileKnowledgeScopes(structuredClone(next));
				merged = next;
				return true;
			} catch (error) {
				if (failed) failures.set(failed, error);
				return false;
			}
		};
		if (!add(pending)) while (pending.length) {
			const skipped = pending.filter((entry) => !add([entry], entry[0]));
			if (skipped.length < pending.length) {
				pending = skipped;
				continue;
			}
			const left = skipped.findIndex((_, i) => skipped.length > 1 && add(skipped.filter((__, j) => j !== i)));
			if (left !== -1) {
				pending = [skipped[left]];
				continue;
			}
			for (const [name] of skipped) {
				const error = failures.get(name);
				const reason = error instanceof Error ? error.message : String(error);
				skippedReasons.set(name, reason);
				this.warn(`Knowledge skipped the store's scope declaration "${name}": ${reason}`);
			}
			break;
		}
		this.#resolved = {
			stored: key,
			compiled,
			skipped: skippedReasons
		};
		this.#declarationsChecked = void 0;
		return compiled;
	}
	/** Makes the next {@link resolve} read the store's declarations again. */
	invalidate() {
		this.#stored = void 0;
	}
	#readStored() {
		const now = Date.now();
		if (this.#stored && now >= this.#stored.readAt && now - this.#stored.readAt < 3e4) return this.#stored;
		const entry = {
			readAt: now,
			declarations: this.getStorage().then((storage) => storage.getScopeDeclarations())
		};
		this.#stored = entry;
		entry.declarations.catch(() => {
			if (this.#stored === entry) this.#stored = void 0;
		});
		return entry;
	}
	validatePrincipals(principals) {
		for (const principal of principals) if (!this.compiled.match(principal)) throw new KnowledgeDeclarationError(`Knowledge run scope "${principal}" does not match a declared scope type.`);
	}
	/**
	* Fails when stored scope pages carry declaration keys neither the config nor the store declares: a
	* renamed or removed key would otherwise silently cut those scopes off from prefix and `belongsTo`
	* reach. Checked once per set of resolved declarations; only a pass is remembered, so a store error
	* is retried next time.
	*/
	checkDeclarations() {
		if (!this.#declarationsChecked) {
			const check = this.#checkDeclarations();
			this.#declarationsChecked = check;
			check.catch(() => {
				if (this.#declarationsChecked === check) this.#declarationsChecked = void 0;
			});
		}
		return this.#declarationsChecked;
	}
	async #checkDeclarations() {
		const orphans = (await (await this.getStorage()).listScopeDeclarations()).filter(({ declaration }) => !this.compiled.declarations.has(declaration));
		if (orphans.length === 0) return;
		const list = (entries) => entries.map(({ declaration, scopes }) => `"${declaration}" (${scopes} scope${scopes === 1 ? "" : "s"})`).join(", ");
		const skippedKey = (declaration) => {
			const key = declaration.split("/")[0];
			return this.#resolved.skipped.has(key) ? key : void 0;
		};
		const undeclared = orphans.filter(({ declaration }) => !skippedKey(declaration));
		const messages = [];
		if (undeclared.length) messages.push(`Knowledge storage has scopes created from declarations this config doesn't declare: ${list(undeclared)}. Restore each key in scopes, rename it with knowledge.renameScopeDeclaration(from, to), or keep the key with no access rules to retire it.`);
		for (const key of new Set(orphans.map(({ declaration }) => skippedKey(declaration)).filter((k) => k !== void 0))) {
			const stranded = orphans.filter(({ declaration }) => skippedKey(declaration) === key);
			messages.push(`Knowledge skipped the store's scope declaration "${key}", so its stored scopes have none: ${list(stranded)}. ${this.#resolved.skipped.get(key)} Fix that declaration in the store, or declare the key, with its children, in scopes to override it.`);
		}
		throw new KnowledgeDeclarationError(messages.join(" "));
	}
	/** Re-keys stored scopes from declaration `from` to `to`. See {@link Knowledge.renameScopeDeclaration}. */
	async renameScopeDeclaration(from, to) {
		if (this.compiled.declarations.has(from)) throw new KnowledgeDeclarationError(`Can't rename scope declaration "${from}": it is still declared. Remove it from scopes first.`);
		if (!this.compiled.declarations.has(to)) throw new KnowledgeDeclarationError(`Can't rename scope declaration to "${to}": it isn't declared in scopes.`);
		const renamed = await (await this.getStorage()).renameScopeDeclaration({
			from,
			to,
			check: (scopes) => {
				const mismatched = scopes.filter((scope) => this.compiled.match(scope.address)?.declaration !== scope.to);
				if (mismatched.length === 0) return;
				throw new KnowledgeDeclarationError(`Can't rename scope declaration "${from}" to "${to}": ` + mismatched.slice(0, 5).map((scope) => `"${scope.address}" doesn't match "${scope.to}"`).join(", ") + (mismatched.length > 5 ? `, and ${mismatched.length - 5} more` : "") + ". Nothing was renamed.");
			}
		});
		this.#declarationsChecked = void 0;
		this.invalidate();
		return renamed;
	}
	/**
	* Whether a stored scope row belongs to the declaration its address matches today. Rows written
	* before scope params matched exactly one segment can carry another (`org:acme:viewer` stored
	* under `org:$orgId`); they must not pick up the rules of the declaration that now matches them.
	*/
	#isCurrent(scope) {
		return !scope.declaration || this.compiled.match(scope.address)?.declaration === scope.declaration;
	}
	#assertCurrent(scope) {
		if (this.#isCurrent(scope)) return;
		throw new KnowledgeDeclarationError(`Knowledge scope "${scope.address}" was created from "${scope.declaration}", which no longer matches it (scope params match one segment; encode colons in ids as %3A). It can't be used as a scope of "${this.compiled.match(scope.address)?.declaration}".`);
	}
	async readScopeFor(principals) {
		this.validatePrincipals(principals);
		await this.checkDeclarations();
		const storage = await this.getStorage();
		const read = await knowledgeReadScopeFor(this.compiled, principals, async (addresses) => (await storage.getScopesByAddress(addresses)).filter((scope) => this.#isCurrent(scope)));
		if (read.addresses.length === 0) return read;
		const stale = new Set((await storage.getScopesByAddress(read.addresses)).filter((scope) => !this.#isCurrent(scope)).map((scope) => scope.address));
		return stale.size ? {
			...read,
			addresses: read.addresses.filter((address) => !stale.has(address))
		} : read;
	}
	async roleOn(principals, scope) {
		this.validatePrincipals(principals);
		if (!scope.isScope || !scope.address) throw new Error("Knowledge roles require a scope page.");
		if (!this.#isCurrent(scope)) return null;
		const storage = await this.getStorage();
		return knowledgeRoleOn(this.compiled, principals, {
			address: scope.address,
			parentAddress: await this.#currentParentAddress(storage, scope)
		});
	}
	async #currentParentAddress(storage, scope) {
		if (!scope.parentId) return void 0;
		const parent = await storage.getPage({
			id: scope.parentId,
			read: "all"
		});
		return parent && this.#isCurrent(parent) ? parent.address ?? void 0 : void 0;
	}
	async explainAccess(runScopes, target) {
		const principals = knowledgeRunScopes(this.compiled, runScopes);
		this.validatePrincipals(principals);
		const storage = await this.getStorage();
		let scope;
		let page = null;
		if ("scope" in target) {
			if (!this.compiled.match(target.scope)) throw new KnowledgeDeclarationError(`Knowledge scope "${target.scope}" does not match a declared scope type.`);
			[scope] = await storage.getScopesByAddress([target.scope]);
		} else {
			if (target.page.indexOf("#") > 0) {
				const parsed = parseKnowledgePageRef(target.page);
				if (parsed) [scope] = await storage.getScopesByAddress([parsed.scope]);
				page = parsed && scope ? await storage.getPageByPath({
					scopeId: scope.id,
					path: parsed.path,
					read: "all"
				}) : null;
			} else {
				page = await storage.getPage({
					id: target.page,
					read: "all"
				});
				if (page?.deletedAt) page = null;
				scope = page ? page.isScope ? page : await storage.getPage({
					id: page.scopeId,
					read: "all"
				}) ?? void 0 : void 0;
			}
			if (!page || !scope?.address) return {
				role: null,
				reasons: [],
				reason: "missing"
			};
		}
		const address = scope?.address ?? target.scope;
		const reasons = scope && !this.#isCurrent(scope) ? [] : knowledgeAccessGrants(this.compiled, principals, {
			address,
			parentAddress: scope ? await this.#currentParentAddress(storage, scope) : void 0
		});
		let role = null;
		for (const reason of reasons) role = strongerKnowledgeRole(role, reason.role);
		return {
			role,
			reasons,
			...page ? { page: {
				id: page.id,
				scope: address
			} } : {},
			...role ? {} : { reason: page ? "hidden" : "no-rule" }
		};
	}
	/**
	* The `<scope>#<key path>` of a page its scope's declaration lists in `pages`, or undefined for an
	* ordinary page. Template pages belong to config: tools can't move them or merge them away.
	*/
	async templatePageRef(page) {
		if (page.isScope || !page.key) return void 0;
		const storage = await this.getStorage();
		const path = [];
		let current = page;
		while (current && !current.isScope) {
			if (!current.key) return void 0;
			path.unshift(current.key);
			current = current.parentId ? await storage.getPage({
				id: current.parentId,
				read: "all"
			}) : null;
		}
		if (!current?.address) return void 0;
		let templates = this.compiled.match(current.address)?.compiled.declaration.pages;
		for (const key of path) {
			const template = templates?.find((entry) => entry.key === key);
			if (!template) return void 0;
			templates = template.pages;
		}
		return `${current.address}#${path.join("/")}`;
	}
	async materializeScope(address, principals, provenance) {
		this.validatePrincipals(principals);
		await this.checkDeclarations();
		return this.#materialize(address, principals, provenance, [], { held: this.#held(principals) });
	}
	/**
	* {@link materializeScope} for each address in turn (a write-run start's principals), reading
	* scopes from one lookup. `#materialize` skips the store call for a scope that exists, needs no new
	* `belongsTo` link, has its child scopes and declares no template pages; warnings fire as before.
	*/
	async materializeScopes(addresses, principals, provenance) {
		this.validatePrincipals(principals);
		await this.checkDeclarations();
		const storage = await this.getStorage();
		const wanted = /* @__PURE__ */ new Set();
		for (const address of addresses) {
			wanted.add(address);
			const match = this.compiled.match(address);
			if (match?.compiled.child) wanted.add(address.slice(0, address.lastIndexOf("/")));
			else for (const child of match?.compiled.children ?? []) wanted.add(`${address}/${child.child.name}`);
		}
		const known = {
			looked: wanted,
			byAddress: /* @__PURE__ */ new Map(),
			byId: /* @__PURE__ */ new Map()
		};
		for (const row of await storage.getScopesByAddress([...wanted])) {
			known.byAddress.set(row.address, row);
			known.byId.set(row.id, row);
		}
		const run = {
			held: this.#held(principals),
			known
		};
		for (const address of addresses) await this.#materialize(address, principals, provenance, [], run);
	}
	/** The run's distinct principals grouped by declaration key, matched once. */
	#held(principals) {
		const held = /* @__PURE__ */ new Map();
		for (const principal of new Set(principals)) {
			const match = this.compiled.match(principal);
			if (!match) continue;
			const group = held.get(match.compiled.key) ?? [];
			group.push({
				principal,
				params: match.params
			});
			held.set(match.compiled.key, group);
		}
		return held;
	}
	#belongsToCandidates(match, held) {
		const belongsTo = match.compiled.belongsTo;
		return (held.get(belongsTo.key) ?? []).filter((candidate) => belongsTo.params.every((param) => match.params[param] === void 0 || candidate.params[param] === match.params[param])).map((candidate) => candidate.principal);
	}
	async #materialize(address, principals, provenance, ancestors, run) {
		const match = this.compiled.match(address);
		if (!match) throw new KnowledgeDeclarationError(`Knowledge scope "${address}" does not match a declared scope type.`);
		if (ancestors.includes(address)) throw new KnowledgeDeclarationError(`Knowledge scope placement cycle at "${address}".`);
		const storage = await this.getStorage();
		const known = run.known;
		const lookUp = async (scope) => known?.looked.has(scope) || known?.byAddress.has(scope) ? known.byAddress.get(scope) : (await storage.getScopesByAddress([scope]))[0];
		if (match.compiled.child) {
			const parentAddress = address.slice(0, address.lastIndexOf("/"));
			await this.#materialize(parentAddress, principals, provenance, [...ancestors, address], run);
			const child = known?.byAddress.get(address) ?? (await storage.getScopesByAddress([address]))[0];
			if (!child) throw new Error(`Knowledge template child "${address}" was not materialized.`);
			return child;
		}
		const existing = await lookUp(address);
		if (existing) this.#assertCurrent(existing);
		let parentId = existing?.parentId;
		if (match.compiled.belongsTo) {
			const candidates = this.#belongsToCandidates(match, run.held);
			if (candidates.length > 1) this.warn(`Knowledge scope "${address}" has ambiguous belongsTo placement: ${candidates.join(", ")}. Keeping its existing placement.`);
			else if (candidates[0]) {
				if (existing?.parentId) {
					let parent = known?.byId.get(existing.parentId) ?? null;
					if (!parent) {
						parent = await storage.getPage({
							id: existing.parentId,
							read: "all"
						});
						if (parent) known?.byId.set(parent.id, parent);
					}
					if (parent?.address !== candidates[0]) this.warn(`Knowledge scope "${address}" already belongs to "${parent?.address}"; ignoring requested parent "${candidates[0]}".`);
				} else if (!ancestors.includes(candidates[0]) && candidates[0] !== address) parentId = (await this.#materialize(candidates[0], principals, provenance, [...ancestors, address], run)).id;
				else this.warn(`Knowledge scope "${address}" cannot be placed under "${candidates[0]}" because that would form a cycle.`);
			}
		}
		const declaration = match.compiled.declaration;
		if (known && existing && parentId === existing.parentId && !declaration.pages?.length && match.compiled.children.every((child) => known.byAddress.has(`${address}/${child.child.name}`))) return existing;
		const result = await storage.materializeScope({
			address,
			declaration: match.declaration,
			name: address,
			description: match.concrete?.description ?? declaration.description,
			parentId,
			children: match.compiled.children.map((child) => ({
				address: `${address}/${child.child.name}`,
				declaration: child.key,
				name: child.child.name,
				description: child.declaration.description
			})),
			pages: declaration.pages,
			provenance
		});
		this.#assertCurrent(result.scope);
		if (result.created) await updateKnowledgeLinks(this.warn, () => refreshKnowledgeLinksTo(storage, [result.scope], { withDescendants: true }));
		if (result.parentConflict) this.warn(`Knowledge scope "${address}" was already linked by another run; keeping its persisted parent.`);
		if (run.known) {
			run.known.byAddress.set(address, result.scope);
			run.known.byId.set(result.scope.id, result.scope);
		}
		return result.scope;
	}
};
// src/knowledge/explorer-pages.ts
/**
* Read-only views over the schema-4 page store for browsing UIs (Mastra Studio, Factory).
*
* Every reader takes the caller's `read` scope and passes it to each store call, so a page or note the
* caller can't read behaves like a missing id. `'all'` is for host surfaces behind their own auth.
* Scope pages are structure the store lists without a read filter; these readers only return the
* scope pages `read` allows, and hoist readable scopes found below an unreadable one so a bound
* viewer still reaches them. These functions never write.
*
* @experimental Knowledge APIs are experimental and may change without notice.
*/
/** Most scope pages one tree or ancestor walk looks at before it stops and reports truncation. */
const MAX_KNOWLEDGE_EXPLORER_SCOPE_SCAN = 1e3;
function scopeVisible(page, read) {
	return page.isScope && knowledgeScopeReadable(page, read);
}
async function allChildScopes(store, parentId, budget) {
	const scopes = [];
	let cursor;
	do {
		if (budget.remaining <= 0) return {
			scopes,
			truncated: true
		};
		const limit = Math.min(100, budget.remaining);
		const result = await store.listChildScopes({
			parentId,
			cursor,
			limit
		});
		budget.remaining -= result.pages.length;
		scopes.push(...result.pages);
		cursor = result.nextCursor;
	} while (cursor);
	return {
		scopes,
		truncated: false
	};
}
/**
* Child scopes of `parentId` that `read` allows. An unreadable child scope is not returned, but its
* own readable descendant scopes are, in its place.
*/
async function visibleChildScopes(store, parentId, read, budget) {
	const direct = await allChildScopes(store, parentId, budget);
	let truncated = direct.truncated;
	const scopes = [];
	for (const scope of direct.scopes) {
		if (scopeVisible(scope, read)) {
			scopes.push(scope);
			continue;
		}
		if (read === "all") continue;
		const hoisted = await visibleChildScopes(store, scope.id, read, budget);
		scopes.push(...hoisted.scopes);
		truncated ||= hoisted.truncated;
	}
	return {
		scopes,
		truncated
	};
}
/**
* One level of the page tree. `parentId: null` lists the root scopes `read` reaches. Child scopes come
* first (they're structure), then the parent's ordinary child pages, paged with `cursor`/`limit`.
*/
async function listKnowledgeTreeChildren(store, input) {
	const { parentId, read, cursor, limit } = input;
	if (parentId !== null && !await store.getPage({
		id: parentId,
		read
	})) return {
		pages: [],
		truncated: false
	};
	const scopes = cursor === void 0 ? await visibleChildScopes(store, parentId, read, { remaining: MAX_KNOWLEDGE_EXPLORER_SCOPE_SCAN }) : {
		scopes: [],
		truncated: false
	};
	if (parentId === null) {
		const counted = await withChildCounts(store, scopes.scopes, read);
		return {
			pages: counted.pages,
			truncated: scopes.truncated || counted.truncated
		};
	}
	const children = await store.listChildPages({
		parentId,
		read,
		cursor,
		limit
	});
	const counted = await withChildCounts(store, [...scopes.scopes, ...children.pages], read);
	return {
		pages: counted.pages,
		...children.nextCursor ? { nextCursor: children.nextCursor } : {},
		truncated: scopes.truncated || counted.truncated
	};
}
/** Child counts for one level: one `countChildPages` call, plus a child-scope walk per scope page. */
async function withChildCounts(store, pages, read) {
	if (pages.length === 0 || typeof store.countChildPages !== "function") return {
		pages,
		truncated: false
	};
	let counts;
	try {
		counts = await store.countChildPages({
			parentIds: pages.map((page) => page.id),
			read
		});
	} catch (error) {
		if (error instanceof KnowledgeUnsupportedCapabilityError) return {
			pages,
			truncated: false
		};
		throw error;
	}
	const budget = { remaining: MAX_KNOWLEDGE_EXPLORER_SCOPE_SCAN };
	let truncated = false;
	const counted = [];
	for (const page of pages) {
		let childCount = Object.hasOwn(counts, page.id) ? counts[page.id] ?? 0 : 0;
		let capped = false;
		if (page.isScope) {
			const childScopes = await visibleChildScopes(store, page.id, read, budget);
			childCount += childScopes.scopes.length;
			capped = childScopes.truncated;
			truncated ||= capped;
		}
		counted.push(capped ? {
			...page,
			childCount,
			childCountCapped: true
		} : {
			...page,
			childCount
		});
	}
	return {
		pages: counted,
		truncated
	};
}
/**
* Readable ancestors of a readable page, root first, so a UI can open the tree down to it. Unreadable
* ancestors are skipped, matching how {@link listKnowledgeTreeChildren} hoists readable scopes.
*/
async function readableAncestors(store, page, read) {
	const path = [];
	const seen = /* @__PURE__ */ new Set([page.id]);
	let parentId = page.parentId;
	while (parentId && !seen.has(parentId) && seen.size <= 1e3) {
		seen.add(parentId);
		const parent = await store.getPage({
			id: parentId,
			read: "all"
		});
		if (!parent) break;
		if (parent.isScope ? scopeVisible(parent, read) : !!await store.getPage({
			id: parent.id,
			read
		})) path.unshift(parent);
		parentId = parent.parentId;
	}
	return path;
}
/**
* A page by id, or by the reference a tool result names it with: a scope address (`site:mastra`) or
* `<scope>#<key>[/<key>…]`. Read-gated like the id lookup: an unreadable scope or page is not found.
* Scope addresses and refs always hold a `:`, which page ids never do, so an id never takes the ref path.
*/
async function pageByIdOrRef(store, ref, read) {
	const byId = await store.getPage({
		id: ref,
		read
	});
	if (byId || !ref.includes(":")) return byId;
	const parsed = ref.includes("#") ? parseKnowledgePageRef(ref) : {
		scope: ref,
		path: []
	};
	if (!parsed) return null;
	const [scope] = await store.getScopesByAddress([parsed.scope]);
	if (!scope || !knowledgeScopeReadable(scope, read)) return null;
	if (parsed.path.length === 0) return store.getPage({
		id: scope.id,
		read
	});
	return store.getPageByPath({
		scopeId: scope.id,
		path: parsed.path,
		read
	});
}
/** One page with its notes, pin and the pages they reference. Null when `read` can't see the page. */
async function readKnowledgePage(store, input) {
	const { read } = input;
	const page = await pageByIdOrRef(store, input.pageId, read);
	if (!page) return null;
	const pageId = page.id;
	const [notes, pins, mentionedBy, ancestors] = await Promise.all([
		store.listNotes({
			pageId,
			read,
			cursor: input.noteCursor,
			limit: input.noteLimit ?? 50
		}),
		store.listPins({
			audience: "all",
			read,
			kind: "page",
			pageIds: [pageId],
			limit: 1
		}),
		store.listNotesMentioning({
			pageId,
			read,
			limit: 50
		}),
		readableAncestors(store, page, read)
	]);
	const known = /* @__PURE__ */ new Set([page.id, ...ancestors.map((ancestor) => ancestor.id)]);
	const wanted = /* @__PURE__ */ new Set();
	for (const note of [...notes.notes, ...mentionedBy.notes]) for (const id of [
		...note.mentions,
		...note.stampScopeIds,
		note.pageId
	]) if (!known.has(id)) wanted.add(id);
	if (!known.has(page.scopeId)) wanted.add(page.scopeId);
	const related = (await Promise.all([...wanted].map((id) => store.getPage({
		id,
		read
	})))).filter((candidate) => candidate !== null);
	return {
		page,
		ancestors,
		notes: notes.notes,
		...notes.nextCursor ? { notesNextCursor: notes.nextCursor } : {},
		pin: pins.pins[0] ?? null,
		related,
		mentionedBy: mentionedBy.notes.filter((note) => note.pageId !== pageId)
	};
}
const NOTE_BATCH = 100;
const DEFAULT_KNOWLEDGE_PAGE_GRAPH_LIMITS = {
	maxPages: 200,
	maxNotes: 5e3,
	maxOutsidePages: 50
};
/** Runs a per-id count over `pages` in list-limit batches; null when the store can't count. */
async function countInBatches(pages, count) {
	const counts = {};
	try {
		for (let start = 0; start < pages.length; start += 100) Object.assign(counts, await count(pages.slice(start, start + 100).map((page) => page.id)));
	} catch (error) {
		if (error instanceof KnowledgeUnsupportedCapabilityError) return null;
		throw error;
	}
	return counts;
}
/**
* Children of every parent in one graph level, in the tree's order: readable child scopes of scope
* parents (scope pages only sit under scopes), then child pages, listed only for parents the level's
* one count says have some. `null` lists the root scopes.
*/
async function graphLevelChildren(store, level, read, byId) {
	let truncated = false;
	const pageCounts = await countInBatches(level.flatMap((id) => id === null ? [] : [byId.get(id)]), (ids) => store.countChildPages({
		parentIds: ids,
		read
	}));
	const byParent = [];
	for (const parentId of level) {
		const parent = parentId === null ? null : byId.get(parentId);
		const children = [];
		if (!parent || parent.isScope) {
			const scopes = await visibleChildScopes(store, parentId, read, { remaining: MAX_KNOWLEDGE_EXPLORER_SCOPE_SCAN });
			truncated ||= scopes.truncated;
			children.push(...scopes.scopes);
		}
		if (parent && (!pageCounts || pageCounts[parent.id])) {
			let cursor;
			do {
				const result = await store.listChildPages({
					parentId: parent.id,
					read,
					cursor
				});
				children.push(...result.pages);
				cursor = result.nextCursor;
			} while (cursor);
		}
		byParent.push(children);
	}
	return {
		byParent,
		truncated
	};
}
/**
* A bounded graph: pages breadth-first under `rootId` (or every root scope `read` reaches), parent
* edges between them, and mention edges from their readable notes. A hidden note never contributes
* an edge, so the graph shows only links the caller could read.
*/
async function readKnowledgePageGraph(store, input) {
	const { read } = input;
	const limits = {
		...DEFAULT_KNOWLEDGE_PAGE_GRAPH_LIMITS,
		...input.limits
	};
	const rootId = input.rootId ?? null;
	const pages = [];
	const byId = /* @__PURE__ */ new Map();
	const add = (page) => {
		if (byId.has(page.id)) return;
		byId.set(page.id, page);
		pages.push(page);
	};
	let truncated = false;
	let queue;
	if (rootId === null) queue = [null];
	else {
		const root = await store.getPage({
			id: rootId,
			read
		});
		if (!root) return null;
		add(root);
		queue = [root.id];
	}
	const treeParent = /* @__PURE__ */ new Map();
	walk: while (queue.length) {
		const level = queue;
		queue = [];
		const children = await graphLevelChildren(store, level, read, byId);
		truncated ||= children.truncated;
		for (const [i, parentId] of level.entries()) for (const child of children.byParent[i]) {
			if (byId.has(child.id)) continue;
			if (pages.length >= limits.maxPages) {
				truncated = true;
				break walk;
			}
			add(child);
			if (parentId !== null) treeParent.set(child.id, parentId);
			queue.push(child.id);
		}
	}
	const edges = [];
	for (const [child, parent] of treeParent) edges.push({
		source: parent,
		target: child,
		kind: "parent"
	});
	const walked = [...pages];
	const noteCounts = await countInBatches(walked, (ids) => store.countNotes({
		pageIds: ids,
		read
	}));
	const mentionCounts = /* @__PURE__ */ new Map();
	const outsideWanted = /* @__PURE__ */ new Set();
	let notesLeft = limits.maxNotes;
	notes: for (const page of walked) {
		if (noteCounts && !noteCounts[page.id]) continue;
		let cursor;
		do {
			if (notesLeft <= 0) {
				truncated = true;
				break notes;
			}
			const batch = await store.listNotes({
				pageId: page.id,
				read,
				cursor,
				limit: Math.min(NOTE_BATCH, notesLeft)
			});
			notesLeft -= batch.notes.length;
			for (const note of batch.notes) for (const target of new Set(note.mentions)) {
				if (target === page.id) continue;
				let counts = mentionCounts.get(page.id);
				if (!counts) mentionCounts.set(page.id, counts = /* @__PURE__ */ new Map());
				counts.set(target, (counts.get(target) ?? 0) + 1);
				if (!byId.has(target)) outsideWanted.add(target);
			}
			cursor = batch.nextCursor;
		} while (cursor);
	}
	const outsideIds = [];
	const wanted = [...outsideWanted];
	outside: for (let start = 0; start < wanted.length; start += 100) {
		const ids = wanted.slice(start, start + 100);
		const found = new Map((await store.getPages({
			ids,
			read
		})).map((page) => [page.id, page]));
		for (const id of ids) {
			const page = found.get(id);
			if (!page || page.deletedAt || page.mergedInto) continue;
			if (outsideIds.length >= limits.maxOutsidePages) {
				truncated = true;
				break outside;
			}
			add(page);
			outsideIds.push(page.id);
		}
	}
	for (const [source, counts] of mentionCounts) for (const [target, count] of counts) if (byId.has(target)) edges.push({
		source,
		target,
		kind: "mention",
		count
	});
	const pinnedIds = [];
	const ids = pages.map((page) => page.id);
	for (let start = 0; start < ids.length; start += 100) {
		let cursor;
		do {
			const result = await store.listPins({
				audience: "all",
				read,
				kind: "page",
				pageIds: ids.slice(start, start + 100),
				cursor
			});
			pinnedIds.push(...result.pins.map((pin) => pin.pageId));
			cursor = result.nextCursor;
		} while (cursor);
	}
	return {
		pages,
		outsideIds,
		edges,
		pinnedIds,
		truncated
	};
}
/** Pages (name, synopsis, body) and notes matching `query` that `read` allows, optionally within scopes. */
function searchKnowledgeExplorerPages(store, input) {
	return store.searchPages({
		...input,
		limit: input.limit ?? 20
	});
}
/** Activity newest first, filtered by what `read` can see now. */
function readKnowledgePageActivity(store, input) {
	return store.listPageActivity({
		...input,
		limit: input.limit ?? 25
	});
}
/**
* The declared grants onto the scope pages in `pages`, for drawing who can reach what. `grantsFor` is
* `knowledge.scopeGrants`. A principal is kept only when `read` can read its scope page; with `'all'`,
* a declared principal with no scope page yet comes back without `principalId`.
*/
async function readKnowledgeScopeGrants(store, input) {
	const { pages, read } = input;
	const byId = new Map(pages.map((page) => [page.id, page]));
	const wanted = [];
	for (const page of pages) {
		if (!page.isScope || !page.address || page.deletedAt || page.mergedInto) continue;
		const parentAddress = page.parentId ? byId.get(page.parentId)?.address ?? null : null;
		for (const grant of input.grantsFor({
			address: page.address,
			parentAddress
		})) if (grant.principal !== page.address) wanted.push({
			...grant,
			target: page.id
		});
	}
	if (!wanted.length) return [];
	const principals = [...new Set(wanted.map((grant) => grant.principal))];
	const scopes = /* @__PURE__ */ new Map();
	for (let start = 0; start < principals.length; start += 100) for (const scope of await store.getScopesByAddress(principals.slice(start, start + 100))) if (scope.address) scopes.set(scope.address, scope);
	const grants = [];
	for (const grant of wanted) {
		const scope = scopes.get(grant.principal);
		if (scope) {
			if (knowledgeScopeReadable(scope, read)) grants.push({
				...grant,
				principalId: scope.id
			});
		} else if (read === "all") grants.push(grant);
	}
	return grants;
}
/** Most pages one {@link readKnowledgePageLinkCounts} call counts. */
const MAX_KNOWLEDGE_LINK_COUNT_PAGES = 200;
/** Most links one {@link readKnowledgePageLinks} call returns. */
const MAX_KNOWLEDGE_EXPLORER_PAGE_LINKS = 200;
/**
* How many distinct other pages link to each page (`in`) and are linked from it (`out`), by body `[[ref]]`
* or note mention, counted by the store over every page it holds rather than only the ones a UI has
* loaded. Pages `read` can't reach count as zero, the same as pages that don't exist. Returns `null`
* when the store has no link index.
*/
async function readKnowledgePageLinkCounts(store, input) {
	const pageIds = [...new Set(input.pageIds)].slice(0, 200);
	if (pageIds.length === 0) return {};
	try {
		return await store.countPageLinks({
			pageIds,
			read: input.read
		});
	} catch (error) {
		if (error instanceof KnowledgeUnsupportedCapabilityError) return null;
		throw error;
	}
}
/**
* The links into and out of one readable page, by body `[[ref]]` or note mention. A page `read` can't
* reach has none. Returns `null` when the store has no link index.
*/
async function readKnowledgePageLinks(store, input) {
	if (!await store.getPage({
		id: input.pageId,
		read: input.read
	})) return {
		edges: [],
		pages: [],
		truncated: false
	};
	let listed;
	try {
		listed = await store.listPageLinks({
			pageIds: [input.pageId],
			read: input.read,
			direction: input.direction ?? "both",
			limit: 201
		});
	} catch (error) {
		if (error instanceof KnowledgeUnsupportedCapabilityError) return null;
		throw error;
	}
	const truncated = listed.length > 200;
	const edges = listed.slice(0, 200);
	const others = [...new Set(edges.flatMap((edge) => [edge.fromPageId, edge.toPageId]).filter((id) => id !== input.pageId))];
	const pages = [];
	for (let start = 0; start < others.length; start += 100) pages.push(...await store.getPages({
		ids: others.slice(start, start + 100),
		read: input.read
	}));
	return {
		edges,
		pages,
		truncated
	};
}
// src/knowledge/index.ts
function resolvePins(pins) {
	if (!pins) return false;
	const options = pins === true ? {} : pins;
	return {
		maxPins: options.maxPins ?? 20,
		maxTokens: options.maxTokens ?? 500
	};
}
/** Below this share of the pin budget each, config pins are too cut down to be useful. */
const MIN_TOKENS_PER_CONFIG_PIN = 50;
/** @experimental Knowledge APIs are experimental and may change without notice. */
var Knowledge = class extends MastraBase {
	id;
	hasOwnStorage;
	description;
	#storage;
	#storageSource;
	#storagePromise;
	#runtime;
	#tools;
	#pins;
	#instructions;
	#semantic;
	#listeners = /* @__PURE__ */ new Set();
	/** Config pins are never dropped, so a scope with more of them than the budget holds is a setup mistake. */
	#warnOnPinOvercommit(budget) {
		const { declarations, concrete } = this.#runtime.compiled;
		const entries = [...[...declarations.values()].map((compiled) => [compiled.key, compiled.declaration.pinnedContext]), ...[...concrete].map(([address, entry]) => [address, entry.declaration.pinnedContext])];
		for (const [key, pins] of entries) {
			const count = pins?.length ?? 0;
			if (count === 0) continue;
			if (count > budget.maxPins || budget.maxTokens / count < MIN_TOKENS_PER_CONFIG_PIN) this.logger.warn(`Knowledge scope "${key}" has ${count} pinnedContext pages for a budget of ${budget.maxPins} pins / ${budget.maxTokens} tokens; pinnedContext pages are never dropped, so each will be cut to about ${Math.floor(budget.maxTokens / count)} tokens and stored pins won't fit. Pin fewer pages or raise pinnedContext.maxTokens.`);
		}
	}
	constructor(config) {
		super({
			component: "STORAGE",
			name: config?.name ?? config?.id ?? "Knowledge"
		});
		if (!config?.scopes || typeof config.scopes !== "object") throw new KnowledgeDeclarationError("Knowledge needs `scopes`: declare the scopes its runs hold, e.g. `scopes: { ...knowledgeMemoryScopes() }`, or `{}` for none.");
		this.id = config.id ?? randomUUID();
		this.description = config.description;
		const tools = config.tools;
		this.#tools = typeof tools === "object" ? {
			read: Boolean(tools.read),
			write: Boolean(tools.write),
			maxTokens: typeof tools.read === "object" ? tools.read.maxTokens : void 0
		} : {
			read: Boolean(tools),
			write: Boolean(tools)
		};
		const maxTokens = this.#tools.maxTokens;
		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}.`);
		this.#pins = resolvePins(config.pinnedContext);
		this.#instructions = config.instructions;
		if (Boolean(config.vector) !== Boolean(config.embedder)) throw new Error("Knowledge semantic search needs both `vector` and `embedder`; pass both or neither.");
		if (config.vector && config.embedder) this.#semantic = new KnowledgeSemanticIndex(config.vector, config.embedder, config.embedderOptions);
		this.#runtime = new KnowledgeScopeRuntime(config.scopes, () => this.getStorage(), (message) => this.logger.warn(message));
		if (this.#pins) this.#warnOnPinOvercommit(this.#pins);
		this.hasOwnStorage = config.storage !== void 0;
		if (config.storage) {
			this.#storageSource = getStorageSource(config.storage);
			this.#storage = augmentWithInit(config.storage);
		}
	}
	/**
	* What a holder of `principals` reads: the principals themselves plus every scope their declared
	* rules reach in one hop. Undeclared principals throw; an empty list reads nothing. Never `'all'`.
	* Pass the result as `read` to the store's read methods.
	*/
	async readScopeFor(principals) {
		await this.#runtime.resolve();
		return this.#runtime.readScopeFor(principals);
	}
	/**
	* Why a run holding `runScopes` can or can't reach a scope or page: its role there and the rules
	* that give it. `runScopes` are canonical run scopes, as passed to an agent run; undeclared ones throw
	* like they do at run start. `target` is a scope address, or a page id or `<scope>#<key>[/<key>…]`.
	*
	* **Host-only.** It tells a missing page from a hidden one, which runs must never learn. Never
	* expose it through an agent tool, or through a server route without admin-level auth.
	*
	* @experimental
	*/
	async explainAccess(runScopes, target) {
		await this.#runtime.resolve();
		return this.#runtime.explainAccess(runScopes, target);
	}
	/**
	* Who the declared rules give a role on one scope: each principal scope address (bound for this
	* scope's params) with its strongest role, `self` rules left out. `parentAddress` is the
	* address of the scope page's tree parent, needed for rules that bind through `belongsTo`. Reads the
	* declarations as last resolved, not storage. For browsing UIs that draw access between scopes.
	*
	* @experimental
	*/
	scopeGrants(scope) {
		const strongest = /* @__PURE__ */ new Map();
		for (const grant of knowledgeAccessGrants(this.#runtime.compiled, "any", scope)) {
			if (grant.via === "self") continue;
			strongest.set(grant.principal, strongerKnowledgeRole(strongest.get(grant.principal) ?? null, grant.role));
		}
		return [...strongest].map(([principal, role]) => ({
			principal,
			role
		}));
	}
	/**
	* After renaming a scope declaration key in `scopes`, moves the scopes stored under the old key
	* (and its template children, `from/<name>`) to the new one, in one atomic step. Until then this
	* instance refuses to run: stored scopes under an undeclared key would otherwise silently lose
	* prefix and `belongsTo` reach. Refuses when `from` is still declared, `to` isn't, or any stored
	* address doesn't match the `to` pattern; nothing changes then. Returns how many scopes moved.
	*
	* In a rolling deploy, instances with the new config fail until the rename runs, and instances
	* still on the old config lose reach to those scopes after it; deploy, then rename right away.
	*
	* @experimental
	*/
	async renameScopeDeclaration(from, to) {
		await this.#runtime.resolve();
		return this.#runtime.renameScopeDeclaration(from, to);
	}
	#groups(override) {
		const pinnedContext = override?.pinnedContext;
		return {
			read: override?.read ?? this.#tools.read,
			write: override?.write ?? this.#tools.write,
			pins: pinnedContext ?? this.#pins !== false
		};
	}
	/** Tools for explicit wiring; defaults to the groups configured on this Knowledge. */
	createTools(options) {
		return buildKnowledgePageTools({
			runtime: this.#runtime,
			getStorage: () => this.getStorage(),
			semantic: this.#semantic,
			warn: (message) => this.logger.warn(message),
			maxTokens: this.#tools.maxTokens
		}, this.#groups(options), (context) => context?.requestContext?.delete?.(PINNED_READ_MEMO_KEY));
	}
	/**
	* Creates or updates the page at `scope#path`, for apps that sync content in from outside an agent
	* run (a docs site, a CMS). The path is the page's identity, so running a sync again updates the
	* same pages; an unchanged page is not written. Notes on the page are kept. The page is embedded
	* when Knowledge has `vector` and `embedder`, and change listeners are told.
	*
	* **Host-only.** No run scopes and no access rules are checked; who reads the page is decided by
	* the scope's access rules as usual (`explainAccess` explains run access, not host writes). Never
	* expose it through an agent tool, or through a server route without admin-level auth. A scope
	* first created here gets its `belongsTo` parent when a run holding that parent first uses it.
	*
	* @experimental
	*/
	upsertPage(input) {
		return upsertKnowledgePage(this.#hostWriter(), input);
	}
	/**
	* Deletes the page at `scope#path`; `null` when there is none. Refuses a page with child pages
	* and a page declared in config. Host-only, like {@link Knowledge.upsertPage}. Not retried: a
	* concurrent write to the same page between the read and the delete throws, so remove from one
	* sync worker or retry the call.
	*
	* @experimental
	*/
	removePage(input) {
		return removeKnowledgePage(this.#hostWriter(), input);
	}
	/**
	* Moves the page at `scope#path`, with its subtree, under the page at `parent` (a key path; left
	* out, the top of the scope), in `toScope` when given. The page keeps its id, notes, pins and
	* vectors; paths below it change, and links by path are re-resolved. Throws
	* `KnowledgeNotFoundError` for a missing page or parent, and refuses a page declared in config, a
	* move into its own subtree, a key the new parent already has, and a move past the depth limit.
	* Host-only, like {@link Knowledge.upsertPage}. Not retried: a concurrent write to the page
	* between the read and the move throws.
	*
	* @experimental
	*/
	movePage(input) {
		return moveKnowledgePage(this.#hostWriter(), input);
	}
	/**
	* Adds a note to the page at `scope#path`; throws when there is no page there. Readers of the
	* `stamps` scopes (default: the page's scope) see it. Keep the returned id to edit or remove it.
	* Host-only, like {@link Knowledge.upsertPage}.
	*
	* @experimental
	*/
	addNote(input) {
		return addKnowledgeNote(this.#hostWriter(), input);
	}
	/**
	* Replaces a note's text. Notes are immutable, so this adds the new note and then removes the old
	* one: the result has a **new id**. If removing the old note fails after the add, both exist;
	* call `removeNote` with the old id. Host-only, like {@link Knowledge.upsertPage}.
	*
	* @experimental
	*/
	updateNote(input) {
		return updateKnowledgeNote(this.#hostWriter(), input);
	}
	/**
	* Removes a note; `null` when it is already gone. Host-only, like {@link Knowledge.upsertPage}.
	*
	* @experimental
	*/
	removeNote(input) {
		return removeKnowledgeNote(this.#hostWriter(), input);
	}
	#hostWriter() {
		return {
			runtime: this.#runtime,
			getStorage: () => this.getStorage(),
			semantic: this.#semantic,
			warn: (message) => this.logger.warn(message)
		};
	}
	/**
	* Rebuilds the page link index from every page body, for pages written before the index existed
	* or straight to the store. Needs no vector store. Returns how many pages were indexed.
	*
	* @experimental
	*/
	async reindexLinks() {
		return reindexKnowledgeLinks(await this.getStorage());
	}
	/**
	* Embeds pages and notes that already exist, without changing them: content written before a
	* `vector` and `embedder` were configured, or before switching embedders. Each call handles up to
	* `limit` pages (default 50, at most 500) with their notes and returns `nextCursor`; pass it to the
	* next call until it's absent. Handling a page again overwrites its vectors, so a run can stop and
	* resume. Failures are listed, not thrown; if the embedder keeps rate limiting, the call stops
	* early with `rateLimited: true` and a cursor that resumes where it stopped, mid-page if need be; wait before resuming. The
	* cursor is not a snapshot: pages added or removed during a run can be missed or handled twice, and
	* a page read before a concurrent edit can overwrite the vectors that edit wrote, so rerun after
	* concurrent writes finish. Throws without `vector` and `embedder`.
	*
	* @experimental
	*/
	async reembed(options) {
		if (!this.#semantic) throw new Error("Knowledge has no `vector` and `embedder` to embed into.");
		return reembedKnowledge(await this.getStorage(), this.#semantic, options);
	}
	/** The usage block that goes with `createTools(options)`. */
	getInstructions(options) {
		return buildKnowledgeInstructions(this.#groups(options), this.#instructions);
	}
	/** Whether attached agents get pinned context delivered every turn. */
	get pinnedContextEnabled() {
		return this.#pins !== false;
	}
	/** The run's principals as a stable key; throws when the run has none or holds an undeclared scope. @internal */
	__principalsKey(context) {
		return knowledgeRunPrincipals(this.#runtime, context).sort().join("\n");
	}
	/** The pinned pages a run receives this turn. @internal */
	async __deliveredPins(context) {
		const budget = this.#pins || resolvePins(true);
		if (!budget) return [];
		const run = await KnowledgeRun.start(this.#runtime, await this.getStorage(), context);
		return knowledgeDeliveredPins(run, budget);
	}
	/** @internal */
	__registerMastra(_mastra) {}
	/** @internal */
	__sharesStorageWith(other) {
		if (!this.#storageSource || !other.#storageSource) return false;
		if (this.#storageSource === other.#storageSource) return true;
		const domain = this.#storageSource.stores?.knowledge;
		const otherDomain = other.#storageSource.stores?.knowledge;
		return domain !== void 0 && otherDomain !== void 0 && domain.getStorageIsolationKey() === otherDomain.getStorageIsolationKey();
	}
	/** @internal */
	__usesStorage(storage) {
		const source = getStorageSource(storage);
		if (this.#storageSource === source) return true;
		const domain = this.#storageSource?.stores?.knowledge;
		const sourceDomain = source.stores?.knowledge;
		return domain !== void 0 && sourceDomain !== void 0 && domain.getStorageIsolationKey() === sourceDomain.getStorageIsolationKey();
	}
	/** @internal */
	setStorage(storage, source = storage) {
		if (this.hasOwnStorage) return;
		this.#storageSource = getStorageSource(source);
		this.#storage = augmentWithInit(storage);
		this.#storagePromise = void 0;
	}
	async getStorage() {
		if (!this.#storagePromise) {
			const promise = this.#resolveStorage().catch((error) => {
				if (this.#storagePromise === promise) this.#storagePromise = void 0;
				throw error;
			});
			this.#storagePromise = promise;
		}
		return this.#storagePromise;
	}
	async #resolveStorage() {
		if (!this.#storage) throw new Error("Knowledge requires a storage provider. Configure storage on the Knowledge instance or on the owning Mastra instance.");
		const storage = await this.#storage.getStore("knowledge");
		if (!storage) throw new Error("The configured storage provider does not provide a Knowledge storage domain.");
		return emitKnowledgeChanges(storage, (change) => this.#emit(change), () => this.#listeners.size > 0, (error) => this.logger.error("Knowledge change event failed after a committed write", { error }));
	}
	#emit(change) {
		if (this.#listeners.size === 0) return;
		const event = {
			...change,
			knowledgeId: this.id,
			at: /* @__PURE__ */ new Date()
		};
		for (const listener of this.#listeners) try {
			listener(event);
		} catch (error) {
			this.logger.error("Knowledge change listener threw", { error });
		}
	}
	/**
	* Calls `listener` after each committed write made through this instance's store
	* (`getStorage()`): tool writes, host writes and scope creation. Writes made on a store obtained
	* some other way aren't seen. Events carry ids, not content and not access: anything that relays
	* them to people must re-read each page under that person's read scope. Returns an unsubscribe.
	*/
	onChange(listener) {
		this.#listeners.add(listener);
		return () => {
			this.#listeners.delete(listener);
		};
	}
	/**
	* The declaration a scope page was created from, by its `declaration` key (template children
	* included, e.g. `account:$orgId:$accountId/internal`), for display. Access rules are left out;
	* use `explainAccess` for those. `undefined` for an unknown key.
	*/
	scopeDeclaration(key) {
		const compiled = this.#runtime.compiled.declarations.get(key);
		if (!compiled) return void 0;
		const { description, displayLabel, belongsTo } = compiled.declaration;
		return {
			key,
			...description !== void 0 && { description },
			...displayLabel !== void 0 && { displayLabel },
			...belongsTo !== void 0 && { belongsTo },
			children: compiled.children.map((child) => ({
				key: child.key,
				name: child.child.name,
				...child.declaration.description !== void 0 && { description: child.declaration.description },
				...child.declaration.displayLabel !== void 0 && { displayLabel: child.declaration.displayLabel }
			}))
		};
	}
	/**
	* The display label for a canonical scope address (template children included), with the
	* declaration's `$params` filled in from the address's decoded values: `'$orgId policy'` on
	* `policy:$orgId` gives `'acme policy'` for `policy:acme`. A concrete address's own `displayLabel`
	* wins over its pattern's. `undefined` when the address matches no declaration or has no label.
	*/
	scopeLabel(address) {
		const match = this.#runtime.compiled.match(address);
		const label = match?.concrete?.displayLabel ?? match?.compiled.declaration.displayLabel;
		if (label === void 0) return void 0;
		return label.replace(/\$([A-Za-z_][A-Za-z0-9_]*)/g, (token, name) => Object.hasOwn(match.params, name) ? match.params[name] : token);
	}
};
export { DEFAULT_KNOWLEDGE_PAGE_GRAPH_LIMITS, InMemoryKnowledgeStorage, KNOWLEDGE_STORAGE_CONTRACT_VERSION, KNOWLEDGE_STORAGE_SCHEMA_VERSION, Knowledge, KnowledgeConflictError, KnowledgeDeclarationError, KnowledgeMoveTooLargeError, KnowledgeNotFoundError, KnowledgePageDepthError, KnowledgePageHasChildrenError, KnowledgePageKeyConflictError, KnowledgeSchemaResetRequiredError, KnowledgeStorage, KnowledgeUnsupportedCapabilityError, MAX_KNOWLEDGE_EXPLORER_PAGE_LINKS, MAX_KNOWLEDGE_LINK_COUNT_PAGES, MAX_KNOWLEDGE_MOVE_PAGES, MAX_KNOWLEDGE_NODE_DESCRIPTION_LENGTH, MAX_KNOWLEDGE_NOTE_TOKENS, MAX_KNOWLEDGE_PAGE_BODY_LINKS, MAX_KNOWLEDGE_PAGE_DEPTH, MAX_KNOWLEDGE_PAGE_DESCRIPTION_TOKENS, MAX_KNOWLEDGE_PAGE_LINKS, MAX_KNOWLEDGE_PAGE_LINK_REF_LENGTH, MAX_KNOWLEDGE_PAGE_LIST_LIMIT, MAX_KNOWLEDGE_PIN_LIST_DEPTH, MAX_KNOWLEDGE_RECORD_TEXT_LENGTH, MAX_KNOWLEDGE_SCOPE_TAGS, assertKnowledgeCeilingRaised, assertKnowledgeDescriptionWithinBound, assertKnowledgeNoteTextWithinBound, assertKnowledgePageDescriptionWithinBound, assertKnowledgeRecordTextWithinBound, assertKnowledgeSchemaCompatible, assertKnowledgeScopeWithinCeiling, canonicalKnowledgeName, canonicalizeKnowledgeScope, createKnowledgeNodeCursor, createKnowledgeUlid, decodeKnowledgeScopeId, encodeKnowledgeScopeId, expandKnowledgeScope, inspectKnowledgeSchema, isKnowledgeScopeVisible, knowledgeLinkRefKey, knowledgeMemoryScopes, knowledgePagePath, knowledgePinDepth, knowledgePositionBetween, knowledgeScopeAddress, knowledgeScopeKey, knowledgeScopeReadable, knowledgeSemanticDocumentId, knowledgeSemanticIdempotencyKey, knowledgeVisibleScopeKeys, listKnowledgeTreeChildren, parseKnowledgeNodeCursor, parseKnowledgePageRef, parseKnowledgeWikilinks, readKnowledgePage, readKnowledgePageActivity, readKnowledgePageGraph, readKnowledgePageLinkCounts, readKnowledgePageLinks, readKnowledgeScopeGrants, searchKnowledgeExplorerPages };

//# sourceMappingURL=index.js.map