@mastra/code-sdk 1.6.1-alpha.1 → 1.7.0-alpha.3
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/agents/instructions.d.ts +4 -2
- package/dist/agents/instructions.d.ts.map +1 -1
- package/dist/agents/instructions.js +8 -4
- package/dist/agents/instructions.js.map +1 -1
- package/dist/agents/memory.d.ts +2 -6
- package/dist/agents/memory.d.ts.map +1 -1
- package/dist/agents/memory.js +9 -15
- package/dist/agents/memory.js.map +1 -1
- package/dist/agents/prompts/index.d.ts +1 -0
- package/dist/agents/prompts/index.d.ts.map +1 -1
- package/dist/agents/prompts/index.js +6 -0
- package/dist/agents/prompts/index.js.map +1 -1
- package/dist/index.d.ts +5 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +9 -2
- package/dist/index.js.map +1 -1
- package/dist/knowledge-inspector.d.ts.map +1 -1
- package/dist/knowledge-inspector.js +16 -9
- package/dist/knowledge-inspector.js.map +1 -1
- package/dist/knowledge-scope.d.ts +35 -0
- package/dist/knowledge-scope.d.ts.map +1 -0
- package/dist/knowledge-scope.js +47 -0
- package/dist/knowledge-scope.js.map +1 -0
- package/package.json +9 -9
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"knowledge-inspector.js","names":["#knowledge","#session","#handles","#cursors","#invalidateIdnode","#binding","#scope","#consumeCursor","#recordSummary","#sampledRelationshipCounts","#assertStable","#mintCursor","#rankedNodeSnapshot","#readHandle","#assertVisible","#outgoingTargets","#incomingParents","#activityRecord","#fingerprint","#identityKey","#mintHandle","#outgoingNodeRecords","#incomingParentRecords","#pruneOpaqueEntries"],"sources":["../src/knowledge-inspector.ts"],"sourcesContent":["import { randomBytes } from 'node:crypto';\n\nimport type { Session } from '@mastra/core/agent-controller';\nimport { createKnowledgeNodeCursor, isKnowledgeScopeVisible, parseKnowledgeWikilinks } from '@mastra/core/storage';\nimport type {\n KnowledgeActivityEvent,\n KnowledgeRecord,\n KnowledgeNode,\n KnowledgeScope,\n KnowledgeStorage,\n MastraCompositeStore,\n} from '@mastra/core/storage';\n\nimport type { MastraCodeState } from './schema.js';\n\nexport type KnowledgeInspectorScopeLevel = 'org' | 'resource' | 'thread';\nexport type KnowledgeInspectorRecordType = 'node';\nexport type KnowledgeInspectorNodeSort = 'relevant' | 'recent' | 'connected';\n\nexport interface KnowledgeInspectorScopeRoot {\n level: KnowledgeInspectorScopeLevel;\n id?: string;\n available: boolean;\n reason?: string;\n}\n\nexport interface KnowledgeInspectorScopeTree {\n identityKey: string;\n defaultLevel: 'resource';\n roots: KnowledgeInspectorScopeRoot[];\n}\n\nexport interface KnowledgeInspectorScopeBadge {\n level: KnowledgeInspectorScopeLevel;\n id: string;\n}\n\nexport interface KnowledgeInspectorRelationshipCounts {\n records: number;\n outgoing: number;\n incoming: number;\n sampled: boolean;\n}\n\nexport interface KnowledgeInspectorNodeSummary {\n handle: string;\n type: KnowledgeInspectorRecordType;\n name: string;\n kind?: string;\n scope: KnowledgeInspectorScopeBadge;\n version: number;\n updatedAt: string;\n relationshipCounts?: KnowledgeInspectorRelationshipCounts;\n}\n\nexport interface KnowledgeInspectorRecordSummary {\n text: string;\n scope: KnowledgeInspectorScopeBadge;\n sourceThreadId: string;\n capturedAt: string;\n when?: string;\n}\n\nexport interface KnowledgeInspectorNodeList {\n identityKey: string;\n scopeLevel: KnowledgeInspectorScopeLevel;\n nodes: KnowledgeInspectorNodeSummary[];\n nextCursor?: string;\n sort?: KnowledgeInspectorNodeSort;\n coverage?: 'exact' | 'recent-window';\n}\n\nexport interface KnowledgeInspectorRelationshipPreview {\n nodes: KnowledgeInspectorNodeSummary[];\n partial: boolean;\n}\n\nexport interface KnowledgeInspectorNodeDetail {\n identityKey: string;\n scopeLevel: KnowledgeInspectorScopeLevel;\n node: KnowledgeInspectorNodeSummary;\n records: KnowledgeInspectorRecordSummary[];\n recordsNextCursor?: string;\n mentioningRecords: KnowledgeInspectorRecordSummary[];\n mentioningRecordsNextCursor?: string;\n outgoingTargets: KnowledgeInspectorRelationshipPreview;\n incomingParents: KnowledgeInspectorRelationshipPreview;\n relationshipCounts: KnowledgeInspectorRelationshipCounts;\n content?: string;\n contentTruncated: boolean;\n links: Array<{ label: string; node?: KnowledgeInspectorNodeSummary }>;\n}\n\nexport interface KnowledgeInspectorActivityEvent {\n action: KnowledgeActivityEvent['action'];\n recordType: KnowledgeActivityEvent['recordType'];\n scope: KnowledgeInspectorScopeBadge;\n sourceThreadId?: string;\n createdAt: string;\n record?: KnowledgeInspectorNodeSummary;\n}\n\nexport interface KnowledgeInspectorActivityList {\n identityKey: string;\n scopeLevel: KnowledgeInspectorScopeLevel;\n events: KnowledgeInspectorActivityEvent[];\n nextCursor?: string;\n}\n\nexport interface KnowledgeInspector {\n getScopeTree(): Promise<KnowledgeInspectorScopeTree>;\n listNodes(input: {\n level: KnowledgeInspectorScopeLevel;\n namePrefix?: string;\n kind?: string;\n sort?: KnowledgeInspectorNodeSort;\n cursor?: string;\n limit?: number;\n }): Promise<KnowledgeInspectorNodeList>;\n getNode(input: {\n handle: string;\n recordsCursor?: string;\n mentioningRecordsCursor?: string;\n recordLimit?: number;\n }): Promise<KnowledgeInspectorNodeDetail>;\n listActivity(input: {\n level: KnowledgeInspectorScopeLevel;\n cursor?: string;\n limit?: number;\n }): Promise<KnowledgeInspectorActivityList>;\n}\n\nexport class KnowledgeInspectorError extends Error {\n constructor(\n readonly code: 'unavailable' | 'invalid-handle' | 'stale-handle' | 'invalid-cursor' | 'not-visible',\n message: string,\n ) {\n super(message);\n this.name = 'KnowledgeInspectorError';\n }\n}\n\ninterface Binding {\n ownerId: string;\n resourceId: string;\n threadId?: string;\n fingerprint: string;\n identityKey: string;\n}\n\ninterface HandleEntry {\n identityKey: string;\n level: KnowledgeInspectorScopeLevel;\n type: KnowledgeInspectorRecordType;\n recordId: string;\n expiresAt: number;\n}\n\ninterface CursorEntry {\n identityKey: string;\n level: KnowledgeInspectorScopeLevel;\n kind: 'node' | 'ranked-node' | 'records' | 'mentioning-records' | 'activity';\n value: string;\n filters?: { namePrefix?: string; kind?: string; sort?: KnowledgeInspectorNodeSort };\n expiresAt: number;\n}\n\ninterface RankedNodeSnapshot {\n offset: number;\n entries: { id: string; degree: number; counts: KnowledgeInspectorRelationshipCounts }[];\n}\n\ninterface RelationshipRecords {\n nodes: KnowledgeNode[];\n truncated: boolean;\n}\n\nconst HANDLE_TTL_MS = 5 * 60_000;\nconst MAX_OPAQUE_ENTRIES = 1_000;\nconst DEFAULT_RECORD_LIMIT = 50;\nconst MAX_RECORD_LIMIT = 50;\nconst DEFAULT_FACT_LIMIT = 25;\nconst MAX_FACT_LIMIT = 100;\nconst DEFAULT_ACTIVITY_LIMIT = 20;\nconst MAX_ACTIVITY_LIMIT = 100;\nconst MAX_RELATED_RECORDS = 25;\nconst MAX_RANK_CANDIDATES = 50;\nconst MAX_RANK_FACTS = 100;\nconst RRF_K = 60;\nconst MAX_NODE_CONTENT_BYTES = 32 * 1024;\n\nfunction opaqueToken(): string {\n return randomBytes(24).toString('base64url');\n}\n\nfunction boundedLimit(value: number | undefined, fallback: number, maximum: number): number {\n if (value === undefined) return fallback;\n if (!Number.isInteger(value) || value < 1) return fallback;\n return Math.min(value, maximum);\n}\n\nfunction scopeBadge(scope: KnowledgeScope): KnowledgeInspectorScopeBadge {\n const entry = scope.at(-1);\n if (!entry) throw new KnowledgeInspectorError('unavailable', 'Knowledge record has no scope.');\n const separator = entry.indexOf(':');\n return {\n level: entry.slice(0, separator) as KnowledgeInspectorScopeLevel,\n id: entry.slice(separator + 1),\n };\n}\n\nfunction knowledgeSummary(record: KnowledgeRecord): KnowledgeInspectorRecordSummary {\n return {\n text: record.text,\n scope: scopeBadge(record.scope),\n sourceThreadId: record.sourceThreadId,\n capturedAt: record.capturedAt.toISOString(),\n when: record.when?.toISOString(),\n };\n}\n\nfunction truncateUtf8(value: string, maxBytes: number): { value: string; truncated: boolean } {\n const encoded = Buffer.from(value);\n if (encoded.byteLength <= maxBytes) return { value, truncated: false };\n let end = maxBytes;\n let truncated = encoded.subarray(0, end).toString('utf8');\n while (Buffer.byteLength(truncated) > maxBytes) {\n truncated = encoded.subarray(0, --end).toString('utf8');\n }\n return { value: truncated, truncated: true };\n}\n\nclass ScopedKnowledgeInspector implements KnowledgeInspector {\n readonly #knowledge: KnowledgeStorage;\n readonly #session: Session<MastraCodeState>;\n readonly #handles = new Map<string, HandleEntry>();\n readonly #cursors = new Map<string, CursorEntry>();\n #fingerprint?: string;\n #identityKey = opaqueToken();\n\n constructor(input: { knowledge: KnowledgeStorage; session: Session<MastraCodeState> }) {\n this.#knowledge = input.knowledge;\n this.#session = input.session;\n this.#session.subscribe(event => {\n if (event.type === 'thread_changed' || event.type === 'thread_created' || event.type === 'thread_deleted') {\n this.#invalidateIdnode();\n }\n });\n }\n\n async getScopeTree(): Promise<KnowledgeInspectorScopeTree> {\n const binding = await this.#binding();\n return {\n identityKey: binding.identityKey,\n defaultLevel: 'resource',\n roots: [\n { level: 'org', id: binding.ownerId, available: true },\n { level: 'resource', id: binding.resourceId, available: true },\n binding.threadId\n ? { level: 'thread', id: binding.threadId, available: true }\n : { level: 'thread', available: false, reason: 'No active thread belongs to this project.' },\n ],\n };\n }\n\n async listNodes(input: {\n level: KnowledgeInspectorScopeLevel;\n namePrefix?: string;\n kind?: string;\n sort?: KnowledgeInspectorNodeSort;\n cursor?: string;\n limit?: number;\n }): Promise<KnowledgeInspectorNodeList> {\n const binding = await this.#binding();\n const scope = this.#scope(binding, input.level);\n const limit = boundedLimit(input.limit, DEFAULT_RECORD_LIMIT, MAX_RECORD_LIMIT);\n const sort = input.sort ?? 'relevant';\n if (sort === 'recent') {\n const cursor = this.#consumeCursor(input.cursor, binding, input.level, 'node', {\n namePrefix: input.namePrefix,\n kind: input.kind,\n sort,\n });\n const records = await this.#knowledge.listNodes({\n scope,\n namePrefix: input.namePrefix,\n kind: input.kind,\n cursor,\n limit,\n });\n const nodes: KnowledgeInspectorNodeSummary[] = await Promise.all(\n records.map(async record => ({\n ...this.#recordSummary(record, binding, input.level),\n relationshipCounts: (await this.#sampledRelationshipCounts(record, scope)).counts,\n })),\n );\n await this.#assertStable(binding);\n return {\n identityKey: binding.identityKey,\n scopeLevel: input.level,\n nodes,\n nextCursor:\n records.length === limit\n ? this.#mintCursor(\n binding,\n input.level,\n 'node',\n createKnowledgeNodeCursor(records.at(-1)!, {\n namePrefix: input.namePrefix,\n kind: input.kind,\n }),\n {\n namePrefix: input.namePrefix,\n kind: input.kind,\n sort,\n },\n )\n : undefined,\n sort,\n coverage: 'exact',\n };\n }\n\n const filters = { namePrefix: input.namePrefix, kind: input.kind, sort };\n const encodedSnapshot = this.#consumeCursor(input.cursor, binding, input.level, 'ranked-node', filters);\n const snapshot = encodedSnapshot\n ? (JSON.parse(encodedSnapshot) as RankedNodeSnapshot)\n : await this.#rankedNodeSnapshot(scope, input.namePrefix, input.kind, sort);\n const page = snapshot.entries.slice(snapshot.offset, snapshot.offset + limit);\n const nodes: KnowledgeInspectorNodeSummary[] = [];\n for (const entry of page) {\n const node = await this.#knowledge.getNode(entry.id);\n if (!node || !isKnowledgeScopeVisible(node.scope, scope)) continue;\n nodes.push({ ...this.#recordSummary(node, binding, input.level), relationshipCounts: entry.counts });\n }\n const nextOffset = snapshot.offset + limit;\n await this.#assertStable(binding);\n return {\n identityKey: binding.identityKey,\n scopeLevel: input.level,\n nodes,\n nextCursor:\n nextOffset < snapshot.entries.length\n ? this.#mintCursor(\n binding,\n input.level,\n 'ranked-node',\n JSON.stringify({ ...snapshot, offset: nextOffset } satisfies RankedNodeSnapshot),\n filters,\n )\n : undefined,\n sort,\n coverage: 'recent-window',\n };\n }\n\n async getNode(input: {\n handle: string;\n recordsCursor?: string;\n mentioningRecordsCursor?: string;\n recordLimit?: number;\n }): Promise<KnowledgeInspectorNodeDetail> {\n const binding = await this.#binding();\n const handle = this.#readHandle(input.handle, binding, 'node');\n const scope = this.#scope(binding, handle.level);\n const node = await this.#knowledge.getNode(handle.recordId);\n this.#assertVisible(node, scope);\n const limit = boundedLimit(input.recordLimit, DEFAULT_FACT_LIMIT, MAX_FACT_LIMIT);\n const recordsAfter = this.#consumeCursor(input.recordsCursor, binding, handle.level, 'records');\n const mentioningAfter = this.#consumeCursor(\n input.mentioningRecordsCursor,\n binding,\n handle.level,\n 'mentioning-records',\n );\n const [recordsResult, mentioningResult] = await Promise.all([\n this.#knowledge.listKnowledgeAbout({ node: node.id, scope, after: recordsAfter, limit }),\n this.#knowledge.listKnowledgeMentioning({ node: node.id, scope, after: mentioningAfter, limit }),\n ]);\n const mentioningRecords = mentioningResult.records.filter(record => record.node !== node.id);\n const content = truncateUtf8(node.content ?? '', MAX_NODE_CONTENT_BYTES);\n const [outgoingTargets, incomingParents, relationship] = await Promise.all([\n this.#outgoingTargets(node, recordsResult.records, scope, binding, handle.level),\n this.#incomingParents(node, mentioningRecords, scope, binding, handle.level),\n this.#sampledRelationshipCounts(node, scope),\n ]);\n const links = await Promise.all(\n parseKnowledgeWikilinks(content.value)\n .slice(0, MAX_RELATED_RECORDS)\n .map(async label => {\n const target = await this.#knowledge.resolveNode({ name: label, scope });\n return {\n label,\n node: target ? this.#recordSummary(target, binding, handle.level) : undefined,\n };\n }),\n );\n await this.#assertStable(binding);\n return {\n identityKey: binding.identityKey,\n scopeLevel: handle.level,\n node: { ...this.#recordSummary(node, binding, handle.level), relationshipCounts: relationship.counts },\n records: recordsResult.records.map(knowledgeSummary),\n recordsNextCursor: recordsResult.nextCursor\n ? this.#mintCursor(binding, handle.level, 'records', recordsResult.nextCursor)\n : undefined,\n mentioningRecords: mentioningRecords.map(knowledgeSummary),\n mentioningRecordsNextCursor: mentioningResult.nextCursor\n ? this.#mintCursor(binding, handle.level, 'mentioning-records', mentioningResult.nextCursor)\n : undefined,\n outgoingTargets: {\n nodes: outgoingTargets.nodes,\n partial: outgoingTargets.partial || Boolean(recordsResult.nextCursor),\n },\n incomingParents: {\n nodes: incomingParents.nodes,\n partial: incomingParents.partial || Boolean(mentioningResult.nextCursor),\n },\n relationshipCounts: relationship.counts,\n content: node.content === undefined ? undefined : content.value,\n contentTruncated: content.truncated,\n links,\n };\n }\n\n async listActivity(input: {\n level: KnowledgeInspectorScopeLevel;\n cursor?: string;\n limit?: number;\n }): Promise<KnowledgeInspectorActivityList> {\n const binding = await this.#binding();\n const scope = this.#scope(binding, input.level);\n const limit = boundedLimit(input.limit, DEFAULT_ACTIVITY_LIMIT, MAX_ACTIVITY_LIMIT);\n const after = this.#consumeCursor(input.cursor, binding, input.level, 'activity');\n const events = await this.#knowledge.listActivity({ scope, after, limit });\n const activityEvents: KnowledgeInspectorActivityEvent[] = [];\n for (const event of events) {\n const record = await this.#activityRecord(event, scope, binding, input.level);\n activityEvents.push({\n action: event.action,\n recordType: event.recordType,\n scope: scopeBadge(event.scope),\n sourceThreadId: record ? event.sourceThreadId : undefined,\n createdAt: event.createdAt.toISOString(),\n record,\n });\n }\n await this.#assertStable(binding);\n return {\n identityKey: binding.identityKey,\n scopeLevel: input.level,\n events: activityEvents,\n nextCursor:\n events.length === limit ? this.#mintCursor(binding, input.level, 'activity', events.at(-1)!.id) : undefined,\n };\n }\n\n async #binding(): Promise<Binding> {\n const ownerId = this.#session.identity.getOwnerId();\n const resourceId = this.#session.identity.getResourceId();\n if (!ownerId || !resourceId) {\n throw new KnowledgeInspectorError('unavailable', 'Knowledge inspection requires an active owner and project.');\n }\n const activeThreadId = this.#session.thread.getId() ?? undefined;\n const thread = activeThreadId ? await this.#session.thread.getById({ threadId: activeThreadId }) : null;\n const threadId = thread?.resourceId === resourceId ? thread.id : undefined;\n const fingerprint = `${ownerId}\\0${resourceId}\\0${threadId ?? ''}`;\n if (this.#fingerprint !== fingerprint) {\n this.#fingerprint = fingerprint;\n this.#identityKey = opaqueToken();\n this.#handles.clear();\n this.#cursors.clear();\n }\n return { ownerId, resourceId, threadId, fingerprint, identityKey: this.#identityKey };\n }\n\n #scope(binding: Binding, level: KnowledgeInspectorScopeLevel): KnowledgeScope {\n if (level === 'org') return [`org:${binding.ownerId}`];\n const scope = [`org:${binding.ownerId}`, `resource:${binding.resourceId}`];\n if (level === 'resource') return scope;\n if (!binding.threadId) {\n throw new KnowledgeInspectorError('unavailable', 'The active thread does not belong to this project.');\n }\n return [...scope, `thread:${binding.threadId}`];\n }\n\n async #assertStable(binding: Binding): Promise<void> {\n const current = await this.#binding();\n if (current.identityKey !== binding.identityKey || current.fingerprint !== binding.fingerprint) {\n throw new KnowledgeInspectorError('stale-handle', 'Knowledge scope changed while the request was running.');\n }\n }\n\n #assertVisible<T extends KnowledgeNode>(record: T | null, scope: KnowledgeScope): asserts record is T {\n if (!record || !isKnowledgeScopeVisible(record.scope, scope)) {\n throw new KnowledgeInspectorError('not-visible', 'Knowledge record is not visible in the selected scope.');\n }\n }\n\n #recordSummary(\n record: KnowledgeNode,\n binding: Binding,\n level: KnowledgeInspectorScopeLevel,\n ): KnowledgeInspectorNodeSummary {\n const type: KnowledgeInspectorRecordType = 'node';\n return {\n handle: this.#mintHandle(binding, level, type, record.id),\n type,\n name: record.name,\n kind: record.kind,\n scope: scopeBadge(record.scope),\n version: record.version,\n updatedAt: record.updatedAt.toISOString(),\n };\n }\n\n async #rankedNodeSnapshot(\n scope: KnowledgeScope,\n namePrefix: string | undefined,\n kind: string | undefined,\n sort: Exclude<KnowledgeInspectorNodeSort, 'recent'>,\n ): Promise<RankedNodeSnapshot> {\n const records = await this.#knowledge.listNodes({\n scope,\n namePrefix,\n kind,\n limit: MAX_RANK_CANDIDATES,\n });\n const ranked = await Promise.all(\n records.map(async (node, recencyRank) => ({\n node,\n recencyRank,\n ...(await this.#sampledRelationshipCounts(node, scope)),\n })),\n );\n const connected = [...ranked].sort(\n (a, b) => b.degree - a.degree || a.recencyRank - b.recencyRank || a.node.id.localeCompare(b.node.id),\n );\n const connectedRank = new Map(connected.map((entry, index) => [entry.node.id, index]));\n const ordered =\n sort === 'connected'\n ? connected\n : [...ranked].sort((a, b) => {\n const aScore = 1 / (RRF_K + a.recencyRank + 1) + 1 / (RRF_K + connectedRank.get(a.node.id)! + 1);\n const bScore = 1 / (RRF_K + b.recencyRank + 1) + 1 / (RRF_K + connectedRank.get(b.node.id)! + 1);\n return bScore - aScore || a.recencyRank - b.recencyRank || a.node.id.localeCompare(b.node.id);\n });\n return {\n offset: 0,\n entries: ordered.map(entry => ({ id: entry.node.id, degree: entry.degree, counts: entry.counts })),\n };\n }\n\n async #sampledRelationshipCounts(\n node: KnowledgeNode,\n scope: KnowledgeScope,\n ): Promise<{ degree: number; counts: KnowledgeInspectorRelationshipCounts }> {\n const [aboutResult, mentioningResult] = await Promise.all([\n this.#knowledge.listKnowledgeAbout({ node: node.id, scope, limit: MAX_RANK_FACTS }),\n this.#knowledge.listKnowledgeMentioning({ node: node.id, scope, limit: MAX_RANK_FACTS }),\n ]);\n const [outgoing, incoming] = await Promise.all([\n this.#outgoingNodeRecords(node, aboutResult.records, scope),\n this.#incomingParentRecords(node, mentioningResult.records, scope),\n ]);\n const mentioningRecords = mentioningResult.records.filter(record => record.node !== node.id);\n const degree = new Set([...outgoing.nodes, ...incoming.nodes].map(record => record.id)).size;\n return {\n degree,\n counts: {\n records: aboutResult.records.length + mentioningRecords.length,\n outgoing: outgoing.nodes.length,\n incoming: incoming.nodes.length,\n sampled: Boolean(\n aboutResult.nextCursor || mentioningResult.nextCursor || outgoing.truncated || incoming.truncated,\n ),\n },\n };\n }\n\n async #outgoingNodeRecords(\n current: KnowledgeNode,\n records: KnowledgeRecord[],\n scope: KnowledgeScope,\n ): Promise<RelationshipRecords> {\n const related = new Map<string, KnowledgeNode>();\n let truncated = false;\n const sources = [current.content ?? '', ...records.map(record => record.text)];\n for (const source of sources) {\n for (const name of parseKnowledgeWikilinks(source)) {\n if (related.size >= MAX_RELATED_RECORDS) {\n truncated = true;\n break;\n }\n const node = await this.#knowledge.resolveNode({ name, scope });\n if (node && node.id !== current.id && isKnowledgeScopeVisible(node.scope, scope)) {\n related.set(node.id, node);\n }\n }\n if (truncated) break;\n }\n return { nodes: [...related.values()], truncated };\n }\n\n async #incomingParentRecords(\n current: KnowledgeNode,\n records: KnowledgeRecord[],\n scope: KnowledgeScope,\n ): Promise<RelationshipRecords> {\n const related = new Map<string, KnowledgeNode>();\n let truncated = false;\n for (const record of records) {\n if (record.node === current.id || related.has(record.node)) continue;\n if (related.size >= MAX_RELATED_RECORDS) {\n truncated = true;\n break;\n }\n const node = await this.#knowledge.getNode(record.node);\n if (node && isKnowledgeScopeVisible(node.scope, scope)) related.set(node.id, node);\n }\n return { nodes: [...related.values()], truncated };\n }\n\n async #outgoingTargets(\n current: KnowledgeNode,\n records: KnowledgeRecord[],\n scope: KnowledgeScope,\n binding: Binding,\n level: KnowledgeInspectorScopeLevel,\n ): Promise<KnowledgeInspectorRelationshipPreview> {\n const related = await this.#outgoingNodeRecords(current, records, scope);\n return {\n nodes: related.nodes.map(node => this.#recordSummary(node, binding, level)),\n partial: related.truncated,\n };\n }\n\n async #incomingParents(\n current: KnowledgeNode,\n records: KnowledgeRecord[],\n scope: KnowledgeScope,\n binding: Binding,\n level: KnowledgeInspectorScopeLevel,\n ): Promise<KnowledgeInspectorRelationshipPreview> {\n const related = await this.#incomingParentRecords(current, records, scope);\n return {\n nodes: related.nodes.map(node => this.#recordSummary(node, binding, level)),\n partial: related.truncated,\n };\n }\n\n async #activityRecord(\n event: KnowledgeActivityEvent,\n scope: KnowledgeScope,\n binding: Binding,\n level: KnowledgeInspectorScopeLevel,\n ): Promise<KnowledgeInspectorNodeSummary | undefined> {\n if (event.recordType === 'node') {\n const node = await this.#knowledge.getNode(event.recordId);\n return node && isKnowledgeScopeVisible(node.scope, scope) ? this.#recordSummary(node, binding, level) : undefined;\n }\n const record = await this.#knowledge.getKnowledge({ id: event.recordId, includeDeleted: true });\n if (!record || !isKnowledgeScopeVisible(record.scope, scope)) return undefined;\n const node = await this.#knowledge.getNode(record.node);\n return node && isKnowledgeScopeVisible(node.scope, scope) ? this.#recordSummary(node, binding, level) : undefined;\n }\n\n #mintHandle(\n binding: Binding,\n level: KnowledgeInspectorScopeLevel,\n type: KnowledgeInspectorRecordType,\n recordId: string,\n ): string {\n this.#pruneOpaqueEntries();\n const token = opaqueToken();\n this.#handles.set(token, {\n identityKey: binding.identityKey,\n level,\n type,\n recordId,\n expiresAt: Date.now() + HANDLE_TTL_MS,\n });\n return token;\n }\n\n #readHandle(handle: string, binding: Binding, expectedType: KnowledgeInspectorRecordType): HandleEntry {\n const entry = this.#handles.get(handle);\n if (!entry || entry.expiresAt < Date.now() || entry.type !== expectedType) {\n throw new KnowledgeInspectorError('invalid-handle', 'Knowledge record handle is invalid or expired.');\n }\n if (entry.identityKey !== binding.identityKey) {\n throw new KnowledgeInspectorError('stale-handle', 'Knowledge record handle belongs to a previous scope.');\n }\n return entry;\n }\n\n #mintCursor(\n binding: Binding,\n level: KnowledgeInspectorScopeLevel,\n kind: CursorEntry['kind'],\n value: string,\n filters?: CursorEntry['filters'],\n ): string {\n this.#pruneOpaqueEntries();\n const token = opaqueToken();\n this.#cursors.set(token, {\n identityKey: binding.identityKey,\n level,\n kind,\n value,\n filters,\n expiresAt: Date.now() + HANDLE_TTL_MS,\n });\n return token;\n }\n\n #consumeCursor(\n cursor: string | undefined,\n binding: Binding,\n level: KnowledgeInspectorScopeLevel,\n kind: CursorEntry['kind'],\n filters?: CursorEntry['filters'],\n ): string | undefined {\n if (!cursor) return undefined;\n const entry = this.#cursors.get(cursor);\n if (\n !entry ||\n entry.expiresAt < Date.now() ||\n entry.identityKey !== binding.identityKey ||\n entry.level !== level ||\n entry.kind !== kind ||\n entry.filters?.namePrefix !== filters?.namePrefix ||\n entry.filters?.kind !== filters?.kind ||\n entry.filters?.sort !== filters?.sort\n ) {\n throw new KnowledgeInspectorError(\n 'invalid-cursor',\n 'Knowledge cursor does not match the active scope and filters.',\n );\n }\n return entry.value;\n }\n\n #pruneOpaqueEntries(): void {\n const now = Date.now();\n for (const [token, entry] of this.#handles) {\n if (entry.expiresAt < now) this.#handles.delete(token);\n }\n for (const [token, entry] of this.#cursors) {\n if (entry.expiresAt < now) this.#cursors.delete(token);\n }\n while (this.#handles.size + this.#cursors.size >= MAX_OPAQUE_ENTRIES) {\n const handle = this.#handles.keys().next().value;\n if (handle) this.#handles.delete(handle);\n else {\n const cursor = this.#cursors.keys().next().value;\n if (cursor) this.#cursors.delete(cursor);\n else break;\n }\n }\n }\n\n #invalidateIdnode(): void {\n this.#fingerprint = undefined;\n this.#identityKey = opaqueToken();\n this.#handles.clear();\n this.#cursors.clear();\n }\n}\n\nexport async function createKnowledgeInspector(input: {\n storage: MastraCompositeStore;\n session: Session<MastraCodeState>;\n}): Promise<KnowledgeInspector | undefined> {\n const knowledge = await input.storage.getStore('knowledge');\n return knowledge ? new ScopedKnowledgeInspector({ knowledge, session: input.session }) : undefined;\n}\n"],"mappings":";;;AAoIA,IAAa,0BAAb,cAA6C,MAAM;CAEtC;CADX,YACE,MACA,SACA;EACA,MAAM,OAAO;EAHJ,KAAA,OAAA;EAIT,KAAK,OAAO;CACd;AACF;AAqCA,MAAM,gBAAgB,IAAI;AAC1B,MAAM,qBAAqB;AAC3B,MAAM,uBAAuB;AAC7B,MAAM,mBAAmB;AACzB,MAAM,qBAAqB;AAC3B,MAAM,iBAAiB;AACvB,MAAM,yBAAyB;AAC/B,MAAM,qBAAqB;AAC3B,MAAM,sBAAsB;AAC5B,MAAM,sBAAsB;AAC5B,MAAM,iBAAiB;AACvB,MAAM,QAAQ;AACd,MAAM,yBAAyB,KAAK;AAEpC,SAAS,cAAsB;CAC7B,OAAO,YAAY,EAAE,CAAC,CAAC,SAAS,WAAW;AAC7C;AAEA,SAAS,aAAa,OAA2B,UAAkB,SAAyB;CAC1F,IAAI,UAAU,KAAA,GAAW,OAAO;CAChC,IAAI,CAAC,OAAO,UAAU,KAAK,KAAK,QAAQ,GAAG,OAAO;CAClD,OAAO,KAAK,IAAI,OAAO,OAAO;AAChC;AAEA,SAAS,WAAW,OAAqD;CAC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3,"file":"knowledge-inspector.js","names":["#knowledge","#session","#handles","#cursors","#invalidateIdnode","#binding","#scope","#consumeCursor","#recordSummary","#sampledRelationshipCounts","#assertStable","#mintCursor","#rankedNodeSnapshot","#readHandle","#assertVisible","#outgoingTargets","#incomingParents","#activityRecord","#fingerprint","#identityKey","#mintHandle","#outgoingNodeRecords","#incomingParentRecords","#pruneOpaqueEntries"],"sources":["../src/knowledge-inspector.ts"],"sourcesContent":["import { randomBytes } from 'node:crypto';\n\nimport type { Session } from '@mastra/core/agent-controller';\nimport { createKnowledgeNodeCursor, isKnowledgeScopeVisible, parseKnowledgeWikilinks } from '@mastra/core/storage';\nimport type {\n KnowledgeActivityEvent,\n KnowledgeRecord,\n KnowledgeNode,\n KnowledgeScope,\n KnowledgeStorage,\n MastraCompositeStore,\n} from '@mastra/core/storage';\n\nimport { resolveKnowledgeScopeIdentity } from './knowledge-scope.js';\nimport type { MastraCodeState } from './schema.js';\n\nexport type KnowledgeInspectorScopeLevel = 'org' | 'resource' | 'thread';\nexport type KnowledgeInspectorRecordType = 'node';\nexport type KnowledgeInspectorNodeSort = 'relevant' | 'recent' | 'connected';\n\nexport interface KnowledgeInspectorScopeRoot {\n level: KnowledgeInspectorScopeLevel;\n id?: string;\n available: boolean;\n reason?: string;\n}\n\nexport interface KnowledgeInspectorScopeTree {\n identityKey: string;\n defaultLevel: 'resource';\n roots: KnowledgeInspectorScopeRoot[];\n}\n\nexport interface KnowledgeInspectorScopeBadge {\n level: KnowledgeInspectorScopeLevel;\n id: string;\n}\n\nexport interface KnowledgeInspectorRelationshipCounts {\n records: number;\n outgoing: number;\n incoming: number;\n sampled: boolean;\n}\n\nexport interface KnowledgeInspectorNodeSummary {\n handle: string;\n type: KnowledgeInspectorRecordType;\n name: string;\n kind?: string;\n scope: KnowledgeInspectorScopeBadge;\n version: number;\n updatedAt: string;\n relationshipCounts?: KnowledgeInspectorRelationshipCounts;\n}\n\nexport interface KnowledgeInspectorRecordSummary {\n text: string;\n scope: KnowledgeInspectorScopeBadge;\n sourceThreadId: string;\n capturedAt: string;\n when?: string;\n}\n\nexport interface KnowledgeInspectorNodeList {\n identityKey: string;\n scopeLevel: KnowledgeInspectorScopeLevel;\n nodes: KnowledgeInspectorNodeSummary[];\n nextCursor?: string;\n sort?: KnowledgeInspectorNodeSort;\n coverage?: 'exact' | 'recent-window';\n}\n\nexport interface KnowledgeInspectorRelationshipPreview {\n nodes: KnowledgeInspectorNodeSummary[];\n partial: boolean;\n}\n\nexport interface KnowledgeInspectorNodeDetail {\n identityKey: string;\n scopeLevel: KnowledgeInspectorScopeLevel;\n node: KnowledgeInspectorNodeSummary;\n records: KnowledgeInspectorRecordSummary[];\n recordsNextCursor?: string;\n mentioningRecords: KnowledgeInspectorRecordSummary[];\n mentioningRecordsNextCursor?: string;\n outgoingTargets: KnowledgeInspectorRelationshipPreview;\n incomingParents: KnowledgeInspectorRelationshipPreview;\n relationshipCounts: KnowledgeInspectorRelationshipCounts;\n content?: string;\n contentTruncated: boolean;\n links: Array<{ label: string; node?: KnowledgeInspectorNodeSummary }>;\n}\n\nexport interface KnowledgeInspectorActivityEvent {\n action: KnowledgeActivityEvent['action'];\n recordType: KnowledgeActivityEvent['recordType'];\n scope: KnowledgeInspectorScopeBadge;\n sourceThreadId?: string;\n createdAt: string;\n record?: KnowledgeInspectorNodeSummary;\n}\n\nexport interface KnowledgeInspectorActivityList {\n identityKey: string;\n scopeLevel: KnowledgeInspectorScopeLevel;\n events: KnowledgeInspectorActivityEvent[];\n nextCursor?: string;\n}\n\nexport interface KnowledgeInspector {\n getScopeTree(): Promise<KnowledgeInspectorScopeTree>;\n listNodes(input: {\n level: KnowledgeInspectorScopeLevel;\n namePrefix?: string;\n kind?: string;\n sort?: KnowledgeInspectorNodeSort;\n cursor?: string;\n limit?: number;\n }): Promise<KnowledgeInspectorNodeList>;\n getNode(input: {\n handle: string;\n recordsCursor?: string;\n mentioningRecordsCursor?: string;\n recordLimit?: number;\n }): Promise<KnowledgeInspectorNodeDetail>;\n listActivity(input: {\n level: KnowledgeInspectorScopeLevel;\n cursor?: string;\n limit?: number;\n }): Promise<KnowledgeInspectorActivityList>;\n}\n\nexport class KnowledgeInspectorError extends Error {\n constructor(\n readonly code: 'unavailable' | 'invalid-handle' | 'stale-handle' | 'invalid-cursor' | 'not-visible',\n message: string,\n ) {\n super(message);\n this.name = 'KnowledgeInspectorError';\n }\n}\n\ninterface Binding {\n /** Org rung shared with the subconscious writers (see knowledge-scope.ts). */\n organizationId: string;\n /** Resource rung of the knowledge scope: the Factory project id, else the session resource. */\n resourceId: string;\n threadId?: string;\n fingerprint: string;\n identityKey: string;\n}\n\ninterface HandleEntry {\n identityKey: string;\n level: KnowledgeInspectorScopeLevel;\n type: KnowledgeInspectorRecordType;\n recordId: string;\n expiresAt: number;\n}\n\ninterface CursorEntry {\n identityKey: string;\n level: KnowledgeInspectorScopeLevel;\n kind: 'node' | 'ranked-node' | 'records' | 'mentioning-records' | 'activity';\n value: string;\n filters?: { namePrefix?: string; kind?: string; sort?: KnowledgeInspectorNodeSort };\n expiresAt: number;\n}\n\ninterface RankedNodeSnapshot {\n offset: number;\n entries: { id: string; degree: number; counts: KnowledgeInspectorRelationshipCounts }[];\n}\n\ninterface RelationshipRecords {\n nodes: KnowledgeNode[];\n truncated: boolean;\n}\n\nconst HANDLE_TTL_MS = 5 * 60_000;\nconst MAX_OPAQUE_ENTRIES = 1_000;\nconst DEFAULT_RECORD_LIMIT = 50;\nconst MAX_RECORD_LIMIT = 50;\nconst DEFAULT_FACT_LIMIT = 25;\nconst MAX_FACT_LIMIT = 100;\nconst DEFAULT_ACTIVITY_LIMIT = 20;\nconst MAX_ACTIVITY_LIMIT = 100;\nconst MAX_RELATED_RECORDS = 25;\nconst MAX_RANK_CANDIDATES = 50;\nconst MAX_RANK_FACTS = 100;\nconst RRF_K = 60;\nconst MAX_NODE_CONTENT_BYTES = 32 * 1024;\n\nfunction opaqueToken(): string {\n return randomBytes(24).toString('base64url');\n}\n\nfunction boundedLimit(value: number | undefined, fallback: number, maximum: number): number {\n if (value === undefined) return fallback;\n if (!Number.isInteger(value) || value < 1) return fallback;\n return Math.min(value, maximum);\n}\n\nfunction scopeBadge(scope: KnowledgeScope): KnowledgeInspectorScopeBadge {\n const entry = scope.at(-1);\n if (!entry) throw new KnowledgeInspectorError('unavailable', 'Knowledge record has no scope.');\n const separator = entry.indexOf(':');\n return {\n level: entry.slice(0, separator) as KnowledgeInspectorScopeLevel,\n id: entry.slice(separator + 1),\n };\n}\n\nfunction knowledgeSummary(record: KnowledgeRecord): KnowledgeInspectorRecordSummary {\n return {\n text: record.text,\n scope: scopeBadge(record.scope),\n sourceThreadId: record.sourceThreadId,\n capturedAt: record.capturedAt.toISOString(),\n when: record.when?.toISOString(),\n };\n}\n\nfunction truncateUtf8(value: string, maxBytes: number): { value: string; truncated: boolean } {\n const encoded = Buffer.from(value);\n if (encoded.byteLength <= maxBytes) return { value, truncated: false };\n let end = maxBytes;\n let truncated = encoded.subarray(0, end).toString('utf8');\n while (Buffer.byteLength(truncated) > maxBytes) {\n truncated = encoded.subarray(0, --end).toString('utf8');\n }\n return { value: truncated, truncated: true };\n}\n\nclass ScopedKnowledgeInspector implements KnowledgeInspector {\n readonly #knowledge: KnowledgeStorage;\n readonly #session: Session<MastraCodeState>;\n readonly #handles = new Map<string, HandleEntry>();\n readonly #cursors = new Map<string, CursorEntry>();\n #fingerprint?: string;\n #identityKey = opaqueToken();\n\n constructor(input: { knowledge: KnowledgeStorage; session: Session<MastraCodeState> }) {\n this.#knowledge = input.knowledge;\n this.#session = input.session;\n this.#session.subscribe(event => {\n if (event.type === 'thread_changed' || event.type === 'thread_created' || event.type === 'thread_deleted') {\n this.#invalidateIdnode();\n }\n });\n }\n\n async getScopeTree(): Promise<KnowledgeInspectorScopeTree> {\n const binding = await this.#binding();\n return {\n identityKey: binding.identityKey,\n defaultLevel: 'resource',\n roots: [\n { level: 'org', id: binding.organizationId, available: true },\n { level: 'resource', id: binding.resourceId, available: true },\n binding.threadId\n ? { level: 'thread', id: binding.threadId, available: true }\n : { level: 'thread', available: false, reason: 'No active thread belongs to this project.' },\n ],\n };\n }\n\n async listNodes(input: {\n level: KnowledgeInspectorScopeLevel;\n namePrefix?: string;\n kind?: string;\n sort?: KnowledgeInspectorNodeSort;\n cursor?: string;\n limit?: number;\n }): Promise<KnowledgeInspectorNodeList> {\n const binding = await this.#binding();\n const scope = this.#scope(binding, input.level);\n const limit = boundedLimit(input.limit, DEFAULT_RECORD_LIMIT, MAX_RECORD_LIMIT);\n const sort = input.sort ?? 'relevant';\n if (sort === 'recent') {\n const cursor = this.#consumeCursor(input.cursor, binding, input.level, 'node', {\n namePrefix: input.namePrefix,\n kind: input.kind,\n sort,\n });\n const records = await this.#knowledge.listNodes({\n scope,\n namePrefix: input.namePrefix,\n kind: input.kind,\n cursor,\n limit,\n });\n const nodes: KnowledgeInspectorNodeSummary[] = await Promise.all(\n records.map(async record => ({\n ...this.#recordSummary(record, binding, input.level),\n relationshipCounts: (await this.#sampledRelationshipCounts(record, scope)).counts,\n })),\n );\n await this.#assertStable(binding);\n return {\n identityKey: binding.identityKey,\n scopeLevel: input.level,\n nodes,\n nextCursor:\n records.length === limit\n ? this.#mintCursor(\n binding,\n input.level,\n 'node',\n createKnowledgeNodeCursor(records.at(-1)!, {\n namePrefix: input.namePrefix,\n kind: input.kind,\n }),\n {\n namePrefix: input.namePrefix,\n kind: input.kind,\n sort,\n },\n )\n : undefined,\n sort,\n coverage: 'exact',\n };\n }\n\n const filters = { namePrefix: input.namePrefix, kind: input.kind, sort };\n const encodedSnapshot = this.#consumeCursor(input.cursor, binding, input.level, 'ranked-node', filters);\n const snapshot = encodedSnapshot\n ? (JSON.parse(encodedSnapshot) as RankedNodeSnapshot)\n : await this.#rankedNodeSnapshot(scope, input.namePrefix, input.kind, sort);\n const page = snapshot.entries.slice(snapshot.offset, snapshot.offset + limit);\n const nodes: KnowledgeInspectorNodeSummary[] = [];\n for (const entry of page) {\n const node = await this.#knowledge.getNode(entry.id);\n if (!node || !isKnowledgeScopeVisible(node.scope, scope)) continue;\n nodes.push({ ...this.#recordSummary(node, binding, input.level), relationshipCounts: entry.counts });\n }\n const nextOffset = snapshot.offset + limit;\n await this.#assertStable(binding);\n return {\n identityKey: binding.identityKey,\n scopeLevel: input.level,\n nodes,\n nextCursor:\n nextOffset < snapshot.entries.length\n ? this.#mintCursor(\n binding,\n input.level,\n 'ranked-node',\n JSON.stringify({ ...snapshot, offset: nextOffset } satisfies RankedNodeSnapshot),\n filters,\n )\n : undefined,\n sort,\n coverage: 'recent-window',\n };\n }\n\n async getNode(input: {\n handle: string;\n recordsCursor?: string;\n mentioningRecordsCursor?: string;\n recordLimit?: number;\n }): Promise<KnowledgeInspectorNodeDetail> {\n const binding = await this.#binding();\n const handle = this.#readHandle(input.handle, binding, 'node');\n const scope = this.#scope(binding, handle.level);\n const node = await this.#knowledge.getNode(handle.recordId);\n this.#assertVisible(node, scope);\n const limit = boundedLimit(input.recordLimit, DEFAULT_FACT_LIMIT, MAX_FACT_LIMIT);\n const recordsAfter = this.#consumeCursor(input.recordsCursor, binding, handle.level, 'records');\n const mentioningAfter = this.#consumeCursor(\n input.mentioningRecordsCursor,\n binding,\n handle.level,\n 'mentioning-records',\n );\n const [recordsResult, mentioningResult] = await Promise.all([\n this.#knowledge.listKnowledgeAbout({ node: node.id, scope, after: recordsAfter, limit }),\n this.#knowledge.listKnowledgeMentioning({ node: node.id, scope, after: mentioningAfter, limit }),\n ]);\n const mentioningRecords = mentioningResult.records.filter(record => record.node !== node.id);\n const content = truncateUtf8(node.content ?? '', MAX_NODE_CONTENT_BYTES);\n const [outgoingTargets, incomingParents, relationship] = await Promise.all([\n this.#outgoingTargets(node, recordsResult.records, scope, binding, handle.level),\n this.#incomingParents(node, mentioningRecords, scope, binding, handle.level),\n this.#sampledRelationshipCounts(node, scope),\n ]);\n const links = await Promise.all(\n parseKnowledgeWikilinks(content.value)\n .slice(0, MAX_RELATED_RECORDS)\n .map(async label => {\n const target = await this.#knowledge.resolveNode({ name: label, scope });\n return {\n label,\n node: target ? this.#recordSummary(target, binding, handle.level) : undefined,\n };\n }),\n );\n await this.#assertStable(binding);\n return {\n identityKey: binding.identityKey,\n scopeLevel: handle.level,\n node: { ...this.#recordSummary(node, binding, handle.level), relationshipCounts: relationship.counts },\n records: recordsResult.records.map(knowledgeSummary),\n recordsNextCursor: recordsResult.nextCursor\n ? this.#mintCursor(binding, handle.level, 'records', recordsResult.nextCursor)\n : undefined,\n mentioningRecords: mentioningRecords.map(knowledgeSummary),\n mentioningRecordsNextCursor: mentioningResult.nextCursor\n ? this.#mintCursor(binding, handle.level, 'mentioning-records', mentioningResult.nextCursor)\n : undefined,\n outgoingTargets: {\n nodes: outgoingTargets.nodes,\n partial: outgoingTargets.partial || Boolean(recordsResult.nextCursor),\n },\n incomingParents: {\n nodes: incomingParents.nodes,\n partial: incomingParents.partial || Boolean(mentioningResult.nextCursor),\n },\n relationshipCounts: relationship.counts,\n content: node.content === undefined ? undefined : content.value,\n contentTruncated: content.truncated,\n links,\n };\n }\n\n async listActivity(input: {\n level: KnowledgeInspectorScopeLevel;\n cursor?: string;\n limit?: number;\n }): Promise<KnowledgeInspectorActivityList> {\n const binding = await this.#binding();\n const scope = this.#scope(binding, input.level);\n const limit = boundedLimit(input.limit, DEFAULT_ACTIVITY_LIMIT, MAX_ACTIVITY_LIMIT);\n const after = this.#consumeCursor(input.cursor, binding, input.level, 'activity');\n const events = await this.#knowledge.listActivity({ scope, after, limit });\n const activityEvents: KnowledgeInspectorActivityEvent[] = [];\n for (const event of events) {\n const record = await this.#activityRecord(event, scope, binding, input.level);\n activityEvents.push({\n action: event.action,\n recordType: event.recordType,\n scope: scopeBadge(event.scope),\n sourceThreadId: record ? event.sourceThreadId : undefined,\n createdAt: event.createdAt.toISOString(),\n record,\n });\n }\n await this.#assertStable(binding);\n return {\n identityKey: binding.identityKey,\n scopeLevel: input.level,\n events: activityEvents,\n nextCursor:\n events.length === limit ? this.#mintCursor(binding, input.level, 'activity', events.at(-1)!.id) : undefined,\n };\n }\n\n async #binding(): Promise<Binding> {\n // Scope rungs come from the same resolver the subconscious writes under; an\n // owner id is a USER id and never names a knowledge org.\n const identity = resolveKnowledgeScopeIdentity(this.#session.state.get());\n const sessionResourceId = this.#session.identity.getResourceId();\n if (!identity.resolved) {\n // An unresolved org is its own identity: handles minted under the\n // previous scope must not survive into whatever resolves next.\n this.#invalidateIdnode();\n throw new KnowledgeInspectorError(\n 'unavailable',\n identity.reason\n ? `Knowledge inspection unavailable: ${identity.reason}`\n : 'Knowledge inspection requires a resolved organization for this session.',\n );\n }\n if (!sessionResourceId) {\n throw new KnowledgeInspectorError('unavailable', 'Knowledge inspection requires an active project.');\n }\n const organizationId = identity.organizationId;\n const resourceId = identity.knowledgeResourceId ?? sessionResourceId;\n const activeThreadId = this.#session.thread.getId() ?? undefined;\n const thread = activeThreadId ? await this.#session.thread.getById({ threadId: activeThreadId }) : null;\n const threadId = thread?.resourceId === sessionResourceId ? thread.id : undefined;\n const fingerprint = `${organizationId}\\0${resourceId}\\0${threadId ?? ''}`;\n if (this.#fingerprint !== fingerprint) {\n this.#fingerprint = fingerprint;\n this.#identityKey = opaqueToken();\n this.#handles.clear();\n this.#cursors.clear();\n }\n return { organizationId, resourceId, threadId, fingerprint, identityKey: this.#identityKey };\n }\n\n #scope(binding: Binding, level: KnowledgeInspectorScopeLevel): KnowledgeScope {\n if (level === 'org') return [`org:${binding.organizationId}`];\n const scope = [`org:${binding.organizationId}`, `resource:${binding.resourceId}`];\n if (level === 'resource') return scope;\n if (!binding.threadId) {\n throw new KnowledgeInspectorError('unavailable', 'The active thread does not belong to this project.');\n }\n return [...scope, `thread:${binding.threadId}`];\n }\n\n async #assertStable(binding: Binding): Promise<void> {\n const current = await this.#binding();\n if (current.identityKey !== binding.identityKey || current.fingerprint !== binding.fingerprint) {\n throw new KnowledgeInspectorError('stale-handle', 'Knowledge scope changed while the request was running.');\n }\n }\n\n #assertVisible<T extends KnowledgeNode>(record: T | null, scope: KnowledgeScope): asserts record is T {\n if (!record || !isKnowledgeScopeVisible(record.scope, scope)) {\n throw new KnowledgeInspectorError('not-visible', 'Knowledge record is not visible in the selected scope.');\n }\n }\n\n #recordSummary(\n record: KnowledgeNode,\n binding: Binding,\n level: KnowledgeInspectorScopeLevel,\n ): KnowledgeInspectorNodeSummary {\n const type: KnowledgeInspectorRecordType = 'node';\n return {\n handle: this.#mintHandle(binding, level, type, record.id),\n type,\n name: record.name,\n kind: record.kind,\n scope: scopeBadge(record.scope),\n version: record.version,\n updatedAt: record.updatedAt.toISOString(),\n };\n }\n\n async #rankedNodeSnapshot(\n scope: KnowledgeScope,\n namePrefix: string | undefined,\n kind: string | undefined,\n sort: Exclude<KnowledgeInspectorNodeSort, 'recent'>,\n ): Promise<RankedNodeSnapshot> {\n const records = await this.#knowledge.listNodes({\n scope,\n namePrefix,\n kind,\n limit: MAX_RANK_CANDIDATES,\n });\n const ranked = await Promise.all(\n records.map(async (node, recencyRank) => ({\n node,\n recencyRank,\n ...(await this.#sampledRelationshipCounts(node, scope)),\n })),\n );\n const connected = [...ranked].sort(\n (a, b) => b.degree - a.degree || a.recencyRank - b.recencyRank || a.node.id.localeCompare(b.node.id),\n );\n const connectedRank = new Map(connected.map((entry, index) => [entry.node.id, index]));\n const ordered =\n sort === 'connected'\n ? connected\n : [...ranked].sort((a, b) => {\n const aScore = 1 / (RRF_K + a.recencyRank + 1) + 1 / (RRF_K + connectedRank.get(a.node.id)! + 1);\n const bScore = 1 / (RRF_K + b.recencyRank + 1) + 1 / (RRF_K + connectedRank.get(b.node.id)! + 1);\n return bScore - aScore || a.recencyRank - b.recencyRank || a.node.id.localeCompare(b.node.id);\n });\n return {\n offset: 0,\n entries: ordered.map(entry => ({ id: entry.node.id, degree: entry.degree, counts: entry.counts })),\n };\n }\n\n async #sampledRelationshipCounts(\n node: KnowledgeNode,\n scope: KnowledgeScope,\n ): Promise<{ degree: number; counts: KnowledgeInspectorRelationshipCounts }> {\n const [aboutResult, mentioningResult] = await Promise.all([\n this.#knowledge.listKnowledgeAbout({ node: node.id, scope, limit: MAX_RANK_FACTS }),\n this.#knowledge.listKnowledgeMentioning({ node: node.id, scope, limit: MAX_RANK_FACTS }),\n ]);\n const [outgoing, incoming] = await Promise.all([\n this.#outgoingNodeRecords(node, aboutResult.records, scope),\n this.#incomingParentRecords(node, mentioningResult.records, scope),\n ]);\n const mentioningRecords = mentioningResult.records.filter(record => record.node !== node.id);\n const degree = new Set([...outgoing.nodes, ...incoming.nodes].map(record => record.id)).size;\n return {\n degree,\n counts: {\n records: aboutResult.records.length + mentioningRecords.length,\n outgoing: outgoing.nodes.length,\n incoming: incoming.nodes.length,\n sampled: Boolean(\n aboutResult.nextCursor || mentioningResult.nextCursor || outgoing.truncated || incoming.truncated,\n ),\n },\n };\n }\n\n async #outgoingNodeRecords(\n current: KnowledgeNode,\n records: KnowledgeRecord[],\n scope: KnowledgeScope,\n ): Promise<RelationshipRecords> {\n const related = new Map<string, KnowledgeNode>();\n let truncated = false;\n const sources = [current.content ?? '', ...records.map(record => record.text)];\n for (const source of sources) {\n for (const name of parseKnowledgeWikilinks(source)) {\n if (related.size >= MAX_RELATED_RECORDS) {\n truncated = true;\n break;\n }\n const node = await this.#knowledge.resolveNode({ name, scope });\n if (node && node.id !== current.id && isKnowledgeScopeVisible(node.scope, scope)) {\n related.set(node.id, node);\n }\n }\n if (truncated) break;\n }\n return { nodes: [...related.values()], truncated };\n }\n\n async #incomingParentRecords(\n current: KnowledgeNode,\n records: KnowledgeRecord[],\n scope: KnowledgeScope,\n ): Promise<RelationshipRecords> {\n const related = new Map<string, KnowledgeNode>();\n let truncated = false;\n for (const record of records) {\n if (record.node === current.id || related.has(record.node)) continue;\n if (related.size >= MAX_RELATED_RECORDS) {\n truncated = true;\n break;\n }\n const node = await this.#knowledge.getNode(record.node);\n if (node && isKnowledgeScopeVisible(node.scope, scope)) related.set(node.id, node);\n }\n return { nodes: [...related.values()], truncated };\n }\n\n async #outgoingTargets(\n current: KnowledgeNode,\n records: KnowledgeRecord[],\n scope: KnowledgeScope,\n binding: Binding,\n level: KnowledgeInspectorScopeLevel,\n ): Promise<KnowledgeInspectorRelationshipPreview> {\n const related = await this.#outgoingNodeRecords(current, records, scope);\n return {\n nodes: related.nodes.map(node => this.#recordSummary(node, binding, level)),\n partial: related.truncated,\n };\n }\n\n async #incomingParents(\n current: KnowledgeNode,\n records: KnowledgeRecord[],\n scope: KnowledgeScope,\n binding: Binding,\n level: KnowledgeInspectorScopeLevel,\n ): Promise<KnowledgeInspectorRelationshipPreview> {\n const related = await this.#incomingParentRecords(current, records, scope);\n return {\n nodes: related.nodes.map(node => this.#recordSummary(node, binding, level)),\n partial: related.truncated,\n };\n }\n\n async #activityRecord(\n event: KnowledgeActivityEvent,\n scope: KnowledgeScope,\n binding: Binding,\n level: KnowledgeInspectorScopeLevel,\n ): Promise<KnowledgeInspectorNodeSummary | undefined> {\n if (event.recordType === 'node') {\n const node = await this.#knowledge.getNode(event.recordId);\n return node && isKnowledgeScopeVisible(node.scope, scope) ? this.#recordSummary(node, binding, level) : undefined;\n }\n const record = await this.#knowledge.getKnowledge({ id: event.recordId, includeDeleted: true });\n if (!record || !isKnowledgeScopeVisible(record.scope, scope)) return undefined;\n const node = await this.#knowledge.getNode(record.node);\n return node && isKnowledgeScopeVisible(node.scope, scope) ? this.#recordSummary(node, binding, level) : undefined;\n }\n\n #mintHandle(\n binding: Binding,\n level: KnowledgeInspectorScopeLevel,\n type: KnowledgeInspectorRecordType,\n recordId: string,\n ): string {\n this.#pruneOpaqueEntries();\n const token = opaqueToken();\n this.#handles.set(token, {\n identityKey: binding.identityKey,\n level,\n type,\n recordId,\n expiresAt: Date.now() + HANDLE_TTL_MS,\n });\n return token;\n }\n\n #readHandle(handle: string, binding: Binding, expectedType: KnowledgeInspectorRecordType): HandleEntry {\n const entry = this.#handles.get(handle);\n if (!entry || entry.expiresAt < Date.now() || entry.type !== expectedType) {\n throw new KnowledgeInspectorError('invalid-handle', 'Knowledge record handle is invalid or expired.');\n }\n if (entry.identityKey !== binding.identityKey) {\n throw new KnowledgeInspectorError('stale-handle', 'Knowledge record handle belongs to a previous scope.');\n }\n return entry;\n }\n\n #mintCursor(\n binding: Binding,\n level: KnowledgeInspectorScopeLevel,\n kind: CursorEntry['kind'],\n value: string,\n filters?: CursorEntry['filters'],\n ): string {\n this.#pruneOpaqueEntries();\n const token = opaqueToken();\n this.#cursors.set(token, {\n identityKey: binding.identityKey,\n level,\n kind,\n value,\n filters,\n expiresAt: Date.now() + HANDLE_TTL_MS,\n });\n return token;\n }\n\n #consumeCursor(\n cursor: string | undefined,\n binding: Binding,\n level: KnowledgeInspectorScopeLevel,\n kind: CursorEntry['kind'],\n filters?: CursorEntry['filters'],\n ): string | undefined {\n if (!cursor) return undefined;\n const entry = this.#cursors.get(cursor);\n if (\n !entry ||\n entry.expiresAt < Date.now() ||\n entry.identityKey !== binding.identityKey ||\n entry.level !== level ||\n entry.kind !== kind ||\n entry.filters?.namePrefix !== filters?.namePrefix ||\n entry.filters?.kind !== filters?.kind ||\n entry.filters?.sort !== filters?.sort\n ) {\n throw new KnowledgeInspectorError(\n 'invalid-cursor',\n 'Knowledge cursor does not match the active scope and filters.',\n );\n }\n return entry.value;\n }\n\n #pruneOpaqueEntries(): void {\n const now = Date.now();\n for (const [token, entry] of this.#handles) {\n if (entry.expiresAt < now) this.#handles.delete(token);\n }\n for (const [token, entry] of this.#cursors) {\n if (entry.expiresAt < now) this.#cursors.delete(token);\n }\n while (this.#handles.size + this.#cursors.size >= MAX_OPAQUE_ENTRIES) {\n const handle = this.#handles.keys().next().value;\n if (handle) this.#handles.delete(handle);\n else {\n const cursor = this.#cursors.keys().next().value;\n if (cursor) this.#cursors.delete(cursor);\n else break;\n }\n }\n }\n\n #invalidateIdnode(): void {\n this.#fingerprint = undefined;\n this.#identityKey = opaqueToken();\n this.#handles.clear();\n this.#cursors.clear();\n }\n}\n\nexport async function createKnowledgeInspector(input: {\n storage: MastraCompositeStore;\n session: Session<MastraCodeState>;\n}): Promise<KnowledgeInspector | undefined> {\n const knowledge = await input.storage.getStore('knowledge');\n return knowledge ? new ScopedKnowledgeInspector({ knowledge, session: input.session }) : undefined;\n}\n"],"mappings":";;;;AAqIA,IAAa,0BAAb,cAA6C,MAAM;CAEtC;CADX,YACE,MACA,SACA;EACA,MAAM,OAAO;EAHJ,KAAA,OAAA;EAIT,KAAK,OAAO;CACd;AACF;AAuCA,MAAM,gBAAgB,IAAI;AAC1B,MAAM,qBAAqB;AAC3B,MAAM,uBAAuB;AAC7B,MAAM,mBAAmB;AACzB,MAAM,qBAAqB;AAC3B,MAAM,iBAAiB;AACvB,MAAM,yBAAyB;AAC/B,MAAM,qBAAqB;AAC3B,MAAM,sBAAsB;AAC5B,MAAM,sBAAsB;AAC5B,MAAM,iBAAiB;AACvB,MAAM,QAAQ;AACd,MAAM,yBAAyB,KAAK;AAEpC,SAAS,cAAsB;CAC7B,OAAO,YAAY,EAAE,CAAC,CAAC,SAAS,WAAW;AAC7C;AAEA,SAAS,aAAa,OAA2B,UAAkB,SAAyB;CAC1F,IAAI,UAAU,KAAA,GAAW,OAAO;CAChC,IAAI,CAAC,OAAO,UAAU,KAAK,KAAK,QAAQ,GAAG,OAAO;CAClD,OAAO,KAAK,IAAI,OAAO,OAAO;AAChC;AAEA,SAAS,WAAW,OAAqD;CACvE,MAAM,QAAQ,MAAM,GAAG,EAAE;CACzB,IAAI,CAAC,OAAO,MAAM,IAAI,wBAAwB,eAAe,gCAAgC;CAC7F,MAAM,YAAY,MAAM,QAAQ,GAAG;CACnC,OAAO;EACL,OAAO,MAAM,MAAM,GAAG,SAAS;EAC/B,IAAI,MAAM,MAAM,YAAY,CAAC;CAC/B;AACF;AAEA,SAAS,iBAAiB,QAA0D;CAClF,OAAO;EACL,MAAM,OAAO;EACb,OAAO,WAAW,OAAO,KAAK;EAC9B,gBAAgB,OAAO;EACvB,YAAY,OAAO,WAA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,gBAAgB,QAAQ,eAC9B,MAAM,UAAU,SAChB,MAAM,SAAS,QACf,MAAM,SAAS,eAAe,SAAS,cACvC,MAAM,SAAS,SAAS,SAAS,QACjC,MAAM,SAAS,SAAS,SAAS,MAEjC,MAAM,IAAI,wBACR,kBACA,+DACF;EAEF,OAAO,MAAM;CACf;CAEA,sBAA4B;EAC1B,MAAM,MAAM,KAAK,IAAI;EACrB,KAAK,MAAM,CAAC,OAAO,UAAU,KAAKD,UAChC,IAAI,MAAM,YAAY,KAAK,KAAKA,SAAS,OAAO,KAAK;EAEvD,KAAK,MAAM,CAAC,OAAO,UAAU,KAAKC,UAChC,IAAI,MAAM,YAAY,KAAK,KAAKA,SAAS,OAAO,KAAK;EAEvD,OAAO,KAAKD,SAAS,OAAO,KAAKC,SAAS,QAAQ,oBAAoB;GACpE,MAAM,SAAS,KAAKD,SAAS,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC;GAC3C,IAAI,QAAQ,KAAKA,SAAS,OAAO,MAAM;QAClC;IACH,MAAM,SAAS,KAAKC,SAAS,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC;IAC3C,IAAI,QAAQ,KAAKA,SAAS,OAAO,MAAM;SAClC;GACP;EACF;CACF;CAEA,oBAA0B;EACxB,KAAKe,eAAe,KAAA;EACpB,KAAKC,eAAe,YAAY;EAChC,KAAKjB,SAAS,MAAM;EACpB,KAAKC,SAAS,MAAM;CACtB;AACF;AAEA,eAAsB,yBAAyB,OAGH;CAC1C,MAAM,YAAY,MAAM,MAAM,QAAQ,SAAS,WAAW;CAC1D,OAAO,YAAY,IAAI,yBAAyB;EAAE;EAAW,SAAS,MAAM;CAAQ,CAAC,IAAI,KAAA;AAC3F"}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { MastraCodeState } from './schema.js';
|
|
2
|
+
/**
|
|
3
|
+
* The organization rung local (TUI/studio) knowledge is curated under. A fixed
|
|
4
|
+
* literal on purpose: deriving it from a hostname, machine id, or path would
|
|
5
|
+
* fragment local knowledge per machine or checkout, and a user running several
|
|
6
|
+
* machines against one shared store could never share knowledge between them.
|
|
7
|
+
* Resolving a real org id (settings, /knowledge, login) is future work; when it
|
|
8
|
+
* lands, it replaces this default here.
|
|
9
|
+
*/
|
|
10
|
+
export declare const LOCAL_KNOWLEDGE_ORG_ID = "local";
|
|
11
|
+
export type KnowledgeScopeIdentity = {
|
|
12
|
+
resolved: true;
|
|
13
|
+
organizationId: string;
|
|
14
|
+
/** Set when the resource rung is anchored on something other than the session resource. */
|
|
15
|
+
knowledgeResourceId?: string;
|
|
16
|
+
} | {
|
|
17
|
+
resolved: false;
|
|
18
|
+
knowledgeResourceId?: string;
|
|
19
|
+
reason?: string;
|
|
20
|
+
};
|
|
21
|
+
/**
|
|
22
|
+
* The single source of truth for which org/resource rungs a session's knowledge
|
|
23
|
+
* lives under. Every reader and writer of the knowledge store (the subconscious
|
|
24
|
+
* memory factory, the /knowledge inspector) must derive its scope from here so
|
|
25
|
+
* that what curation writes is what the browser reads.
|
|
26
|
+
*
|
|
27
|
+
* - Factory seeds the authoritative org id into session state. There is no
|
|
28
|
+
* fallback: a session owner is a USER id, never an organization, so a
|
|
29
|
+
* Factory-owned session without an org resolves to nothing (fail closed).
|
|
30
|
+
* - Factory runs share one knowledge graph per project, so the resource rung is
|
|
31
|
+
* anchored on the project id.
|
|
32
|
+
* - TUI/studio sessions use {@link LOCAL_KNOWLEDGE_ORG_ID}.
|
|
33
|
+
*/
|
|
34
|
+
export declare function resolveKnowledgeScopeIdentity(state: MastraCodeState | undefined): KnowledgeScopeIdentity;
|
|
35
|
+
//# sourceMappingURL=knowledge-scope.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"knowledge-scope.d.ts","sourceRoot":"","sources":["../src/knowledge-scope.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAEnD;;;;;;;GAOG;AACH,eAAO,MAAM,sBAAsB,UAAU,CAAC;AAE9C,MAAM,MAAM,sBAAsB,GAC9B;IACE,QAAQ,EAAE,IAAI,CAAC;IACf,cAAc,EAAE,MAAM,CAAC;IACvB,2FAA2F;IAC3F,mBAAmB,CAAC,EAAE,MAAM,CAAC;CAC9B,GACD;IAAE,QAAQ,EAAE,KAAK,CAAC;IAAC,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC;AAEvE;;;;;;;;;;;;GAYG;AACH,wBAAgB,6BAA6B,CAAC,KAAK,EAAE,eAAe,GAAG,SAAS,GAAG,sBAAsB,CAoBxG"}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
//#region src/knowledge-scope.ts
|
|
2
|
+
/**
|
|
3
|
+
* The organization rung local (TUI/studio) knowledge is curated under. A fixed
|
|
4
|
+
* literal on purpose: deriving it from a hostname, machine id, or path would
|
|
5
|
+
* fragment local knowledge per machine or checkout, and a user running several
|
|
6
|
+
* machines against one shared store could never share knowledge between them.
|
|
7
|
+
* Resolving a real org id (settings, /knowledge, login) is future work; when it
|
|
8
|
+
* lands, it replaces this default here.
|
|
9
|
+
*/
|
|
10
|
+
const LOCAL_KNOWLEDGE_ORG_ID = "local";
|
|
11
|
+
/**
|
|
12
|
+
* The single source of truth for which org/resource rungs a session's knowledge
|
|
13
|
+
* lives under. Every reader and writer of the knowledge store (the subconscious
|
|
14
|
+
* memory factory, the /knowledge inspector) must derive its scope from here so
|
|
15
|
+
* that what curation writes is what the browser reads.
|
|
16
|
+
*
|
|
17
|
+
* - Factory seeds the authoritative org id into session state. There is no
|
|
18
|
+
* fallback: a session owner is a USER id, never an organization, so a
|
|
19
|
+
* Factory-owned session without an org resolves to nothing (fail closed).
|
|
20
|
+
* - Factory runs share one knowledge graph per project, so the resource rung is
|
|
21
|
+
* anchored on the project id.
|
|
22
|
+
* - TUI/studio sessions use {@link LOCAL_KNOWLEDGE_ORG_ID}.
|
|
23
|
+
*/
|
|
24
|
+
function resolveKnowledgeScopeIdentity(state) {
|
|
25
|
+
const factoryProjectId = state?.factoryProjectId;
|
|
26
|
+
const isFactory = typeof factoryProjectId === "string" && factoryProjectId.trim().length > 0;
|
|
27
|
+
const factoryOrgId = state?.factoryOrgId;
|
|
28
|
+
const factoryOwned = isFactory || state?.factoryOrgUnresolved === true;
|
|
29
|
+
const organizationId = typeof factoryOrgId === "string" ? factoryOrgId.trim() : "";
|
|
30
|
+
if (organizationId) return {
|
|
31
|
+
resolved: true,
|
|
32
|
+
organizationId,
|
|
33
|
+
knowledgeResourceId: isFactory ? factoryProjectId : void 0
|
|
34
|
+
};
|
|
35
|
+
if (factoryOwned) return {
|
|
36
|
+
resolved: false,
|
|
37
|
+
knowledgeResourceId: isFactory ? factoryProjectId : void 0
|
|
38
|
+
};
|
|
39
|
+
return {
|
|
40
|
+
resolved: true,
|
|
41
|
+
organizationId: LOCAL_KNOWLEDGE_ORG_ID
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
//#endregion
|
|
45
|
+
export { LOCAL_KNOWLEDGE_ORG_ID, resolveKnowledgeScopeIdentity };
|
|
46
|
+
|
|
47
|
+
//# sourceMappingURL=knowledge-scope.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"knowledge-scope.js","names":[],"sources":["../src/knowledge-scope.ts"],"sourcesContent":["import type { MastraCodeState } from './schema.js';\n\n/**\n * The organization rung local (TUI/studio) knowledge is curated under. A fixed\n * literal on purpose: deriving it from a hostname, machine id, or path would\n * fragment local knowledge per machine or checkout, and a user running several\n * machines against one shared store could never share knowledge between them.\n * Resolving a real org id (settings, /knowledge, login) is future work; when it\n * lands, it replaces this default here.\n */\nexport const LOCAL_KNOWLEDGE_ORG_ID = 'local';\n\nexport type KnowledgeScopeIdentity =\n | {\n resolved: true;\n organizationId: string;\n /** Set when the resource rung is anchored on something other than the session resource. */\n knowledgeResourceId?: string;\n }\n | { resolved: false; knowledgeResourceId?: string; reason?: string };\n\n/**\n * The single source of truth for which org/resource rungs a session's knowledge\n * lives under. Every reader and writer of the knowledge store (the subconscious\n * memory factory, the /knowledge inspector) must derive its scope from here so\n * that what curation writes is what the browser reads.\n *\n * - Factory seeds the authoritative org id into session state. There is no\n * fallback: a session owner is a USER id, never an organization, so a\n * Factory-owned session without an org resolves to nothing (fail closed).\n * - Factory runs share one knowledge graph per project, so the resource rung is\n * anchored on the project id.\n * - TUI/studio sessions use {@link LOCAL_KNOWLEDGE_ORG_ID}.\n */\nexport function resolveKnowledgeScopeIdentity(state: MastraCodeState | undefined): KnowledgeScopeIdentity {\n const factoryProjectId = state?.factoryProjectId;\n const isFactory = typeof factoryProjectId === 'string' && factoryProjectId.trim().length > 0;\n const factoryOrgId = state?.factoryOrgId;\n const factoryOwned = isFactory || state?.factoryOrgUnresolved === true;\n\n // Trimmed to match what the Factory org seeder stores; not every seam routes\n // its seed through it.\n const organizationId = typeof factoryOrgId === 'string' ? factoryOrgId.trim() : '';\n if (organizationId) {\n return {\n resolved: true,\n organizationId,\n knowledgeResourceId: isFactory ? factoryProjectId : undefined,\n };\n }\n if (factoryOwned) {\n return { resolved: false, knowledgeResourceId: isFactory ? factoryProjectId : undefined };\n }\n return { resolved: true, organizationId: LOCAL_KNOWLEDGE_ORG_ID };\n}\n"],"mappings":";;;;;;;;;AAUA,MAAa,yBAAyB;;;;;;;;;;;;;;AAwBtC,SAAgB,8BAA8B,OAA4D;CACxG,MAAM,mBAAmB,OAAO;CAChC,MAAM,YAAY,OAAO,qBAAqB,YAAY,iBAAiB,KAAK,CAAC,CAAC,SAAS;CAC3F,MAAM,eAAe,OAAO;CAC5B,MAAM,eAAe,aAAa,OAAO,yBAAyB;CAIlE,MAAM,iBAAiB,OAAO,iBAAiB,WAAW,aAAa,KAAK,IAAI;CAChF,IAAI,gBACF,OAAO;EACL,UAAU;EACV;EACA,qBAAqB,YAAY,mBAAmB,KAAA;CACtD;CAEF,IAAI,cACF,OAAO;EAAE,UAAU;EAAO,qBAAqB,YAAY,mBAAmB,KAAA;CAAU;CAE1F,OAAO;EAAE,UAAU;EAAM,gBAAgB;CAAuB;AAClE"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mastra/code-sdk",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.7.0-alpha.3",
|
|
4
4
|
"description": "Mastra Code SDK: the agent core behind Mastra Code (everything except the TUI) — build your own UIs and surfaces on top of it",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"publishConfig": {
|
|
@@ -56,20 +56,20 @@
|
|
|
56
56
|
"vscode-languageserver-protocol": "^3.17.5",
|
|
57
57
|
"yaml": "^2.7.1",
|
|
58
58
|
"zod": "^4.3.6",
|
|
59
|
-
"@mastra/fastembed": "1.3.1",
|
|
60
|
-
"@mastra/core": "1.65.0-alpha.1",
|
|
61
|
-
"@mastra/duckdb": "1.6.4",
|
|
62
59
|
"@mastra/agent-browser": "0.5.2",
|
|
60
|
+
"@mastra/core": "1.65.0-alpha.2",
|
|
61
|
+
"@mastra/duckdb": "1.7.0-alpha.0",
|
|
63
62
|
"@mastra/github-signals": "0.4.0",
|
|
63
|
+
"@mastra/fastembed": "1.3.1",
|
|
64
64
|
"@mastra/libsql": "1.22.3",
|
|
65
65
|
"@mastra/mcp": "1.17.3",
|
|
66
|
-
"@mastra/memory": "1.28.3-alpha.0",
|
|
67
66
|
"@mastra/parallel": "0.1.1",
|
|
68
|
-
"@mastra/pg": "1.22.3",
|
|
69
|
-
"@mastra/schema-compat": "1.3.8",
|
|
70
67
|
"@mastra/observability": "1.17.6-alpha.0",
|
|
71
|
-
"@mastra/
|
|
72
|
-
"@mastra/
|
|
68
|
+
"@mastra/memory": "1.28.3-alpha.1",
|
|
69
|
+
"@mastra/pg": "1.23.0-alpha.0",
|
|
70
|
+
"@mastra/schema-compat": "1.3.8",
|
|
71
|
+
"@mastra/tavily": "1.1.2",
|
|
72
|
+
"@mastra/stagehand": "0.3.4"
|
|
73
73
|
},
|
|
74
74
|
"devDependencies": {
|
|
75
75
|
"@libsql/client": "^0.17.4",
|