@mastra/code-sdk 1.12.0-alpha.3 → 1.12.0-alpha.4

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.
Files changed (51) hide show
  1. package/dist/acp/agent.d.ts.map +1 -1
  2. package/dist/acp/agent.js +0 -6
  3. package/dist/acp/agent.js.map +1 -1
  4. package/dist/acp/runtime.js +1 -1
  5. package/dist/agents/mastracode-gateway.d.ts.map +1 -1
  6. package/dist/agents/mastracode-gateway.js +9 -5
  7. package/dist/agents/mastracode-gateway.js.map +1 -1
  8. package/dist/agents/memory.d.ts +2 -1
  9. package/dist/agents/memory.d.ts.map +1 -1
  10. package/dist/agents/memory.js +92 -34
  11. package/dist/agents/memory.js.map +1 -1
  12. package/dist/agents/model.d.ts +33 -2
  13. package/dist/agents/model.d.ts.map +1 -1
  14. package/dist/agents/model.js +32 -4
  15. package/dist/agents/model.js.map +1 -1
  16. package/dist/index.d.ts +17 -4
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js +80 -22
  19. package/dist/index.js.map +1 -1
  20. package/dist/knowledge-inspector.d.ts +4 -0
  21. package/dist/knowledge-inspector.d.ts.map +1 -1
  22. package/dist/knowledge-inspector.js +10 -1
  23. package/dist/knowledge-inspector.js.map +1 -1
  24. package/dist/onboarding/om-settings.d.ts +29 -8
  25. package/dist/onboarding/om-settings.d.ts.map +1 -1
  26. package/dist/onboarding/om-settings.js +42 -15
  27. package/dist/onboarding/om-settings.js.map +1 -1
  28. package/dist/onboarding/packs.d.ts +12 -3
  29. package/dist/onboarding/packs.d.ts.map +1 -1
  30. package/dist/onboarding/packs.js +20 -2
  31. package/dist/onboarding/packs.js.map +1 -1
  32. package/dist/onboarding/settings.d.ts +5 -0
  33. package/dist/onboarding/settings.d.ts.map +1 -1
  34. package/dist/onboarding/settings.js +7 -2
  35. package/dist/onboarding/settings.js.map +1 -1
  36. package/dist/providers/claude-max.js +1 -1
  37. package/dist/providers/deepseek-thinking.d.ts +4 -0
  38. package/dist/providers/deepseek-thinking.d.ts.map +1 -0
  39. package/dist/providers/deepseek-thinking.js +16 -0
  40. package/dist/providers/deepseek-thinking.js.map +1 -0
  41. package/dist/providers/openai-codex.js +1 -1
  42. package/dist/providers/provider-thinking.d.ts +18 -0
  43. package/dist/providers/provider-thinking.d.ts.map +1 -0
  44. package/dist/providers/provider-thinking.js +34 -0
  45. package/dist/providers/provider-thinking.js.map +1 -0
  46. package/dist/schema.d.ts +199 -6
  47. package/dist/schema.d.ts.map +1 -1
  48. package/dist/schema.js +10 -4
  49. package/dist/schema.js.map +1 -1
  50. package/dist/thinking.js +1 -1
  51. package/package.json +8 -8
@@ -1,4 +1,6 @@
1
1
  import type { Session } from '@mastra/core/agent-controller';
2
+ import type { Knowledge } from '@mastra/core/knowledge';
3
+ import type { Mastra } from '@mastra/core/mastra';
2
4
  import type { KnowledgeActivityEvent, MastraCompositeStore } from '@mastra/core/storage';
3
5
  import type { MastraCodeState } from './schema.js';
4
6
  export type KnowledgeInspectorScopeLevel = 'org' | 'resource' | 'thread';
@@ -114,6 +116,8 @@ export declare class KnowledgeInspectorError extends Error {
114
116
  }
115
117
  export declare function createKnowledgeInspector(input: {
116
118
  storage: MastraCompositeStore;
119
+ knowledge?: Knowledge | string;
120
+ mastra?: Pick<Mastra, 'getKnowledge'>;
117
121
  session: Session<MastraCodeState>;
118
122
  }): Promise<KnowledgeInspector | undefined>;
119
123
  //# sourceMappingURL=knowledge-inspector.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"knowledge-inspector.d.ts","sourceRoot":"","sources":["../src/knowledge-inspector.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,+BAA+B,CAAC;AAE7D,OAAO,KAAK,EACV,sBAAsB,EAKtB,oBAAoB,EACrB,MAAM,sBAAsB,CAAC;AAG9B,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAEnD,MAAM,MAAM,4BAA4B,G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ChB,KAAK,CAAC,EAAE,MAAM,CAAC;KAChB,GAAG,OAAO,CAAC,8BAA8B,CAAC,CAAC;CAC7C;AAED,qBAAa,uBAAwB,SAAQ,KAAK;IAE9C,QAAQ,CAAC,IAAI,EAAE,aAAa,GAAG,gBAAgB,GAAG,cAAc,GAAG,gBAAgB,GAAG,aAAa;gBAA1F,IAAI,EAAE,aAAa,GAAG,gBAAgB,GAAG,cAAc,GAAG,gBAAgB,GAAG,aAAa,EACnG,OAAO,EAAE,MAAM;CAKlB;AAuoBD,wBAAsB,wBAAwB,CAAC,KAAK,EAAE;IACpD,OAAO,EAAE,oBAAoB,CAAC;IAC9B,SAAS,CAAC,EAAE,SAAS,GAAG,MAAM,CAAC;IAC/B,MAAM,CAAC,EAAE,IAAI,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC;IACtC,OAAO,EAAE,OAAO,CAAC,eAAe,CAAC,CAAC;CACnC,GAAG,OAAO,CAAC,kBAAkB,GAAG,SAAS,CAAC,CAgB1C"}
@@ -495,7 +495,16 @@ var ScopedKnowledgeInspector = class {
495
495
  }
496
496
  };
497
497
  async function createKnowledgeInspector(input) {
498
- const knowledge = await input.storage.getStore("knowledge");
498
+ let selected;
499
+ if (typeof input.knowledge === "string") {
500
+ try {
501
+ selected = input.mastra?.getKnowledge(input.knowledge);
502
+ } catch {
503
+ throw new KnowledgeInspectorError("unavailable", "The configured Knowledge runtime is unavailable.");
504
+ }
505
+ if (!selected) throw new KnowledgeInspectorError("unavailable", "The configured Knowledge runtime is unavailable.");
506
+ } else selected = input.knowledge;
507
+ const knowledge = selected ? await selected.getStorage() : await input.storage.getStore("knowledge");
499
508
  return knowledge ? new ScopedKnowledgeInspector({
500
509
  knowledge,
501
510
  session: input.session
@@ -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 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 Buffer.from(globalThis.crypto.getRandomValues(new Uint8Array(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 ScopedK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AS,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"}
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 type { Session } from '@mastra/core/agent-controller';\nimport type { Knowledge } from '@mastra/core/knowledge';\nimport type { Mastra } from '@mastra/core/mastra';\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 Buffer.from(globalThis.crypto.getRandomValues(new Uint8Array(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 knowledge?: Knowledge | string;\n mastra?: Pick<Mastra, 'getKnowledge'>;\n session: Session<MastraCodeState>;\n}): Promise<KnowledgeInspector | undefined> {\n let selected: Knowledge | undefined;\n if (typeof input.knowledge === 'string') {\n try {\n selected = input.mastra?.getKnowledge(input.knowledge);\n } catch {\n throw new KnowledgeInspectorError('unavailable', 'The configured Knowledge runtime is unavailable.');\n }\n if (!selected) {\n throw new KnowledgeInspectorError('unavailable', 'The configured Knowledge runtime is unavailable.');\n }\n } else {\n selected = input.knowledge;\n }\n const knowledge = selected ? await selected.getStorage() : 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,OAAO,KAAK,WAAW,OAAO,gCAAgB,IAAI,WAAW,EAAE,CAAC,CAAC,CAAC,CAAC,SAAS,WAAW;AAChG;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,IAA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DAAkD;EACrG;EACA,IAAI,CAAC,UACH,MAAM,IAAI,wBAAwB,eAAe,kDAAkD;CAEvG,OACE,WAAW,MAAM;CAEnB,MAAM,YAAY,WAAW,MAAM,SAAS,WAAW,IAAI,MAAM,MAAM,QAAQ,SAAS,WAAW;CACnG,OAAO,YAAY,IAAI,yBAAyB;EAAE;EAAW,SAAS,MAAM;CAAQ,CAAC,IAAI,KAAA;AAC3F"}
@@ -5,22 +5,43 @@
5
5
  */
6
6
  import type { OMPack } from './packs.js';
7
7
  import type { GlobalSettings } from './settings.js';
8
- /** Whether the user has already chosen any persisted OM model or pack. */
8
+ /**
9
+ * Whether the user has already chosen any persisted OM model or pack.
10
+ *
11
+ * No longer called inside this repo — auto selection replaced the "seed a pack
12
+ * at login" flow — but part of the documented `@mastra/code-sdk/onboarding/om-settings`
13
+ * surface since 1.1.0, so it stays for external callers.
14
+ *
15
+ * @deprecated Observer and Reflector default to Auto; there is no default left to seed.
16
+ */
9
17
  export declare function hasExplicitOMConfiguration(settings: GlobalSettings): boolean;
10
- /** Seed a built-in OM pack unless the user already chose one; true when settings changed. */
18
+ /**
19
+ * Seed a built-in OM pack unless the user already chose one; true when settings changed.
20
+ *
21
+ * The TUI stopped calling this when auto became the default; kept exported for
22
+ * external callers alongside {@link hasExplicitOMConfiguration}.
23
+ *
24
+ * @deprecated Seeding pins both roles to a fixed model. Leave them on Auto instead.
25
+ */
11
26
  export declare function applyOMDefaultIfUnconfigured(settings: GlobalSettings, pack: OMPack): boolean;
27
+ /**
28
+ * Seed the provider's built-in OM pack into saved settings unless the user already chose one.
29
+ *
30
+ * @deprecated Signing in no longer seeds memory models; seeding pins both roles instead of
31
+ * leaving them on Auto.
32
+ */
12
33
  export declare function seedProviderOMDefault(providerId: string): OMPack | undefined;
13
34
  /**
14
35
  * Apply a role-specific OM model override to an in-memory `GlobalSettings`.
15
36
  *
16
- * When switching `activeOmPackId` from a built-in pack to `'custom'` we also
17
- * snapshot the *other* role's currently-resolved model into its override
18
- * field. Without this, the other role would silently lose its model on next
19
- * startup because `resolveOmRoleModel` would no longer resolve it from the
20
- * (now-overridden) pack.
37
+ * Role intent outranks the pack in `resolveOmRoleModel`, so `activeOmPackId` is
38
+ * deliberately left alone: the other role keeps resolving from its built-in
39
+ * pack instead of being dragged along by this role's choice.
21
40
  *
22
41
  * Exported for unit testing; `persistOmRoleOverride` is the disk-backed wrapper.
23
42
  */
24
- export declare function applyOmRoleOverride(settings: GlobalSettings, role: 'observer' | 'reflector', modelId: string, otherRoleCurrentModelId: string | null): void;
43
+ export declare function applyOmRoleOverride(settings: GlobalSettings, role: 'observer' | 'reflector', modelId: string): void;
44
+ /** Reset one persisted OM role to dynamic auto selection without touching the other role. */
45
+ export declare function applyOmRoleAuto(settings: GlobalSettings, role: 'observer' | 'reflector'): void;
25
46
  export declare function persistOmObserveAttachments(value: 'auto' | boolean): void;
26
47
  //# sourceMappingURL=om-settings.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"om-settings.d.ts","sourceRoot":"","sources":["../../src/onboarding/om-settings.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,YAAY,CAAC;AAEzC,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAGpD,0EAA0E;AAC1E,wBAAgB,0BAA0B,CAAC,QAAQ,EAAE,cAAc,GAAG,OAAO,CAO5E;AAED,6FAA6F;AAC7F,wBAAgB,4BAA4B,CAAC,QAAQ,EAAE,cAAc,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAO5F;AAED,wBAAgB,qBAAqB,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAW5E;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,mBAAmB,CACjC,QAAQ,EAAE,cAAc,EACxB,IAAI,EAAE,UAAU,GAAG,WAAW,EAC9B,OAAO,EAAE,MAAM,EACf,uBAAuB,EAAE,MAAM,GAAG,IAAI,GACrC,IAAI,CAgBN;AAED,wBAAgB,2BAA2B,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,GAAG,IAAI,CAIzE"}
1
+ {"version":3,"file":"om-settings.d.ts","sourceRoot":"","sources":["../../src/onboarding/om-settings.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,YAAY,CAAC;AAEzC,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAGpD;;;;;;;;GAQG;AACH,wBAAgB,0BAA0B,CAAC,QAAQ,EAAE,cAAc,GAAG,OAAO,CAsB5E;AAED;;;;;;;GAOG;AACH,wBAAgB,4BAA4B,CAAC,QAAQ,EAAE,cAAc,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAO5F;AAED;;;;;GAKG;AACH,wBAAgB,qBAAqB,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAW5E;AAED;;;;;;;;GAQG;AACH,wBAAgB,mBAAmB,CAAC,QAAQ,EAAE,cAAc,EAAE,IAAI,EAAE,UAAU,GAAG,WAAW,EAAE,OAAO,EAAE,MAAM,GAAG,IAAI,CAQnH;AAED,6FAA6F;AAC7F,wBAAgB,eAAe,CAAC,QAAQ,EAAE,cAAc,EAAE,IAAI,EAAE,UAAU,GAAG,WAAW,GAAG,IAAI,CAQ9F;AAED,wBAAgB,2BAA2B,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,GAAG,IAAI,CAIzE"}
@@ -1,13 +1,28 @@
1
1
  import { resolveProviderOMDefault } from "./packs.js";
2
2
  import { loadSettings, saveSettings } from "./settings.js";
3
3
  //#region src/onboarding/om-settings.ts
4
- /** Whether the user has already chosen any persisted OM model or pack. */
4
+ /**
5
+ * Whether the user has already chosen any persisted OM model or pack.
6
+ *
7
+ * No longer called inside this repo — auto selection replaced the "seed a pack
8
+ * at login" flow — but part of the documented `@mastra/code-sdk/onboarding/om-settings`
9
+ * surface since 1.1.0, so it stays for external callers.
10
+ *
11
+ * @deprecated Observer and Reflector default to Auto; there is no default left to seed.
12
+ */
5
13
  function hasExplicitOMConfiguration(settings) {
6
- const { activeOmPackId, omModelOverride, observerModelOverride, reflectorModelOverride } = settings.models;
7
- if (omModelOverride || observerModelOverride || reflectorModelOverride) return true;
14
+ const { activeOmPackId, omModelOverride, observerModelOverride, observerModelSelection, reflectorModelOverride, reflectorModelSelection } = settings.models;
15
+ if (omModelOverride || observerModelOverride || observerModelSelection && observerModelSelection !== "auto" || reflectorModelOverride || reflectorModelSelection && reflectorModelSelection !== "auto") return true;
8
16
  return [settings.onboarding.omPackId, activeOmPackId].some((packId) => packId && packId !== "custom");
9
17
  }
10
- /** Seed a built-in OM pack unless the user already chose one; true when settings changed. */
18
+ /**
19
+ * Seed a built-in OM pack unless the user already chose one; true when settings changed.
20
+ *
21
+ * The TUI stopped calling this when auto became the default; kept exported for
22
+ * external callers alongside {@link hasExplicitOMConfiguration}.
23
+ *
24
+ * @deprecated Seeding pins both roles to a fixed model. Leave them on Auto instead.
25
+ */
11
26
  function applyOMDefaultIfUnconfigured(settings, pack) {
12
27
  if (hasExplicitOMConfiguration(settings)) return false;
13
28
  settings.onboarding.omPackId = pack.id;
@@ -15,6 +30,12 @@ function applyOMDefaultIfUnconfigured(settings, pack) {
15
30
  settings.models.omModelOverride = null;
16
31
  return true;
17
32
  }
33
+ /**
34
+ * Seed the provider's built-in OM pack into saved settings unless the user already chose one.
35
+ *
36
+ * @deprecated Signing in no longer seeds memory models; seeding pins both roles instead of
37
+ * leaving them on Auto.
38
+ */
18
39
  function seedProviderOMDefault(providerId) {
19
40
  const pack = resolveProviderOMDefault(providerId);
20
41
  if (pack.id === "custom") return void 0;
@@ -26,24 +47,30 @@ function seedProviderOMDefault(providerId) {
26
47
  /**
27
48
  * Apply a role-specific OM model override to an in-memory `GlobalSettings`.
28
49
  *
29
- * When switching `activeOmPackId` from a built-in pack to `'custom'` we also
30
- * snapshot the *other* role's currently-resolved model into its override
31
- * field. Without this, the other role would silently lose its model on next
32
- * startup because `resolveOmRoleModel` would no longer resolve it from the
33
- * (now-overridden) pack.
50
+ * Role intent outranks the pack in `resolveOmRoleModel`, so `activeOmPackId` is
51
+ * deliberately left alone: the other role keeps resolving from its built-in
52
+ * pack instead of being dragged along by this role's choice.
34
53
  *
35
54
  * Exported for unit testing; `persistOmRoleOverride` is the disk-backed wrapper.
36
55
  */
37
- function applyOmRoleOverride(settings, role, modelId, otherRoleCurrentModelId) {
38
- const wasBuiltinPack = settings.models.activeOmPackId !== null && settings.models.activeOmPackId !== "custom";
56
+ function applyOmRoleOverride(settings, role, modelId) {
39
57
  if (role === "observer") {
40
- if (wasBuiltinPack && otherRoleCurrentModelId && !settings.models.reflectorModelOverride) settings.models.reflectorModelOverride = otherRoleCurrentModelId;
41
58
  settings.models.observerModelOverride = modelId;
59
+ settings.models.observerModelSelection = modelId;
42
60
  } else {
43
- if (wasBuiltinPack && otherRoleCurrentModelId && !settings.models.observerModelOverride) settings.models.observerModelOverride = otherRoleCurrentModelId;
44
61
  settings.models.reflectorModelOverride = modelId;
62
+ settings.models.reflectorModelSelection = modelId;
63
+ }
64
+ }
65
+ /** Reset one persisted OM role to dynamic auto selection without touching the other role. */
66
+ function applyOmRoleAuto(settings, role) {
67
+ if (role === "observer") {
68
+ settings.models.observerModelOverride = null;
69
+ settings.models.observerModelSelection = "auto";
70
+ } else {
71
+ settings.models.reflectorModelOverride = null;
72
+ settings.models.reflectorModelSelection = "auto";
45
73
  }
46
- settings.models.activeOmPackId = "custom";
47
74
  }
48
75
  function persistOmObserveAttachments(value) {
49
76
  const settings = loadSettings();
@@ -51,6 +78,6 @@ function persistOmObserveAttachments(value) {
51
78
  saveSettings(settings);
52
79
  }
53
80
  //#endregion
54
- export { applyOMDefaultIfUnconfigured, applyOmRoleOverride, hasExplicitOMConfiguration, persistOmObserveAttachments, seedProviderOMDefault };
81
+ export { applyOMDefaultIfUnconfigured, applyOmRoleAuto, applyOmRoleOverride, hasExplicitOMConfiguration, persistOmObserveAttachments, seedProviderOMDefault };
55
82
 
56
83
  //# sourceMappingURL=om-settings.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"om-settings.js","names":[],"sources":["../../src/onboarding/om-settings.ts"],"sourcesContent":["/**\n * Pure `GlobalSettings` mutation helpers for observational-memory (OM)\n * configuration. Shared by the TUI `/om` command and the web settings\n * routes — no UI dependencies.\n */\nimport type { OMPack } from './packs.js';\nimport { resolveProviderOMDefault } from './packs.js';\nimport type { GlobalSettings } from './settings.js';\nimport { loadSettings, saveSettings } from './settings.js';\n\n/** Whether the user has already chosen any persisted OM model or pack. */\nexport function hasExplicitOMConfiguration(settings: GlobalSettings): boolean {\n const { activeOmPackId, omModelOverride, observerModelOverride, reflectorModelOverride } = settings.models;\n if (omModelOverride || observerModelOverride || reflectorModelOverride) return true;\n\n // 'custom' without a model is what onboarding persists when no provider was\n // reachable — a forced non-choice, not a preference worth preserving.\n return [settings.onboarding.omPackId, activeOmPackId].some(packId => packId && packId !== 'custom');\n}\n\n/** Seed a built-in OM pack unless the user already chose one; true when settings changed. */\nexport function applyOMDefaultIfUnconfigured(settings: GlobalSettings, pack: OMPack): boolean {\n if (hasExplicitOMConfiguration(settings)) return false;\n\n settings.onboarding.omPackId = pack.id;\n settings.models.activeOmPackId = pack.id;\n settings.models.omModelOverride = null;\n return true;\n}\n\nexport function seedProviderOMDefault(providerId: string): OMPack | undefined {\n const pack = resolveProviderOMDefault(providerId);\n // No cheap OM pack for this provider — leave OM open for a later login rather\n // than pinning observation and reflection to a full-size coding model.\n if (pack.id === 'custom') return undefined;\n\n const settings = loadSettings();\n if (!applyOMDefaultIfUnconfigured(settings, pack)) return undefined;\n\n saveSettings(settings);\n return pack;\n}\n\n/**\n * Apply a role-specific OM model override to an in-memory `GlobalSettings`.\n *\n * When switching `activeOmPackId` from a built-in pack to `'custom'` we also\n * snapshot the *other* role's currently-resolved model into its override\n * field. Without this, the other role would silently lose its model on next\n * startup because `resolveOmRoleModel` would no longer resolve it from the\n * (now-overridden) pack.\n *\n * Exported for unit testing; `persistOmRoleOverride` is the disk-backed wrapper.\n */\nexport function applyOmRoleOverride(\n settings: GlobalSettings,\n role: 'observer' | 'reflector',\n modelId: string,\n otherRoleCurrentModelId: string | null,\n): void {\n const wasBuiltinPack = settings.models.activeOmPackId !== null && settings.models.activeOmPackId !== 'custom';\n\n if (role === 'observer') {\n if (wasBuiltinPack && otherRoleCurrentModelId && !settings.models.reflectorModelOverride) {\n settings.models.reflectorModelOverride = otherRoleCurrentModelId;\n }\n settings.models.observerModelOverride = modelId;\n } else {\n if (wasBuiltinPack && otherRoleCurrentModelId && !settings.models.observerModelOverride) {\n settings.models.observerModelOverride = otherRoleCurrentModelId;\n }\n settings.models.reflectorModelOverride = modelId;\n }\n\n settings.models.activeOmPackId = 'custom';\n}\n\nexport function persistOmObserveAttachments(value: 'auto' | boolean): void {\n const settings = loadSettings();\n settings.models.omObserveAttachments = value;\n saveSettings(settings);\n}\n"],"mappings":";;;;AAWA,SAAgB,2BAA2B,UAAmC;CAC5E,MAAM,EAAE,gBAAgB,iBAAiB,uBAAuB,2BAA2B,SAAS;CACpG,IAAI,mBAAmB,yBAAyB,wBAAwB,OAAO;CAI/E,OAAO,CAAC,SAAS,WAAW,UAAU,cAAc,CAAC,CAAC,MAAK,WAAU,UAAU,WAAW,QAAQ;AACpG;;AAGA,SAAgB,6BAA6B,UAA0B,MAAuB;CAC5F,IAAI,2BAA2B,QAAQ,GAAG,OAAO;CAEjD,SAAS,WAAW,WAAW,KAAK;CACpC,SAAS,OAAO,iBAAiB,KAAK;CACtC,SAAS,OAAO,kBAAkB;CAClC,OAAO;AACT;AAEA,SAAgB,sBAAsB,YAAwC;CAC5E,MAAM,OAAO,yBAAyB,UAAU;CAGhD,IAAI,KAAK,OAAO,UAAU,OAAO,KAAA;CAEjC,MAAM,WAAW,aAAa;CAC9B,IAAI,CAAC,6BAA6B,UAAU,IAAI,GAAG,OAAO,KAAA;CAE1D,aAAa,QAAQ;CACrB,OAAO;AACT;;;;;;;;;;;;AAaA,SAAgB,oBACd,UACA,MACA,SACA,yBACM;CACN,MAAM,iBAAiB,SAAS,OAAO,mBAAmB,QAAQ,SAAS,OAAO,mBAAmB;CAErG,IAAI,SAAS,YAAY;EACvB,IAAI,kBAAkB,2BAA2B,CAAC,SAAS,OAAO,wBAChE,SAAS,OAAO,yBAAyB;EAE3C,SAAS,OAAO,wBAAwB;CAC1C,OAAO;EACL,IAAI,kBAAkB,2BAA2B,CAAC,SAAS,OAAO,uBAChE,SAAS,OAAO,wBAAwB;EAE1C,SAAS,OAAO,yBAAyB;CAC3C;CAEA,SAAS,OAAO,iBAAiB;AACnC;AAEA,SAAgB,4BAA4B,OAA+B;CACzE,MAAM,WAAW,aAAa;CAC9B,SAAS,OAAO,uBAAuB;CACvC,aAAa,QAAQ;AACvB"}
1
+ {"version":3,"file":"om-settings.js","names":[],"sources":["../../src/onboarding/om-settings.ts"],"sourcesContent":["/**\n * Pure `GlobalSettings` mutation helpers for observational-memory (OM)\n * configuration. Shared by the TUI `/om` command and the web settings\n * routes — no UI dependencies.\n */\nimport type { OMPack } from './packs.js';\nimport { resolveProviderOMDefault } from './packs.js';\nimport type { GlobalSettings } from './settings.js';\nimport { loadSettings, saveSettings } from './settings.js';\n\n/**\n * Whether the user has already chosen any persisted OM model or pack.\n *\n * No longer called inside this repo — auto selection replaced the \"seed a pack\n * at login\" flow — but part of the documented `@mastra/code-sdk/onboarding/om-settings`\n * surface since 1.1.0, so it stays for external callers.\n *\n * @deprecated Observer and Reflector default to Auto; there is no default left to seed.\n */\nexport function hasExplicitOMConfiguration(settings: GlobalSettings): boolean {\n const {\n activeOmPackId,\n omModelOverride,\n observerModelOverride,\n observerModelSelection,\n reflectorModelOverride,\n reflectorModelSelection,\n } = settings.models;\n if (\n omModelOverride ||\n observerModelOverride ||\n (observerModelSelection && observerModelSelection !== 'auto') ||\n reflectorModelOverride ||\n (reflectorModelSelection && reflectorModelSelection !== 'auto')\n ) {\n return true;\n }\n\n // 'custom' without a model is what onboarding persists when no provider was\n // reachable — a forced non-choice, not a preference worth preserving.\n return [settings.onboarding.omPackId, activeOmPackId].some(packId => packId && packId !== 'custom');\n}\n\n/**\n * Seed a built-in OM pack unless the user already chose one; true when settings changed.\n *\n * The TUI stopped calling this when auto became the default; kept exported for\n * external callers alongside {@link hasExplicitOMConfiguration}.\n *\n * @deprecated Seeding pins both roles to a fixed model. Leave them on Auto instead.\n */\nexport function applyOMDefaultIfUnconfigured(settings: GlobalSettings, pack: OMPack): boolean {\n if (hasExplicitOMConfiguration(settings)) return false;\n\n settings.onboarding.omPackId = pack.id;\n settings.models.activeOmPackId = pack.id;\n settings.models.omModelOverride = null;\n return true;\n}\n\n/**\n * Seed the provider's built-in OM pack into saved settings unless the user already chose one.\n *\n * @deprecated Signing in no longer seeds memory models; seeding pins both roles instead of\n * leaving them on Auto.\n */\nexport function seedProviderOMDefault(providerId: string): OMPack | undefined {\n const pack = resolveProviderOMDefault(providerId);\n // No cheap OM pack for this provider — leave OM open for a later login rather\n // than pinning observation and reflection to a full-size coding model.\n if (pack.id === 'custom') return undefined;\n\n const settings = loadSettings();\n if (!applyOMDefaultIfUnconfigured(settings, pack)) return undefined;\n\n saveSettings(settings);\n return pack;\n}\n\n/**\n * Apply a role-specific OM model override to an in-memory `GlobalSettings`.\n *\n * Role intent outranks the pack in `resolveOmRoleModel`, so `activeOmPackId` is\n * deliberately left alone: the other role keeps resolving from its built-in\n * pack instead of being dragged along by this role's choice.\n *\n * Exported for unit testing; `persistOmRoleOverride` is the disk-backed wrapper.\n */\nexport function applyOmRoleOverride(settings: GlobalSettings, role: 'observer' | 'reflector', modelId: string): void {\n if (role === 'observer') {\n settings.models.observerModelOverride = modelId;\n settings.models.observerModelSelection = modelId;\n } else {\n settings.models.reflectorModelOverride = modelId;\n settings.models.reflectorModelSelection = modelId;\n }\n}\n\n/** Reset one persisted OM role to dynamic auto selection without touching the other role. */\nexport function applyOmRoleAuto(settings: GlobalSettings, role: 'observer' | 'reflector'): void {\n if (role === 'observer') {\n settings.models.observerModelOverride = null;\n settings.models.observerModelSelection = 'auto';\n } else {\n settings.models.reflectorModelOverride = null;\n settings.models.reflectorModelSelection = 'auto';\n }\n}\n\nexport function persistOmObserveAttachments(value: 'auto' | boolean): void {\n const settings = loadSettings();\n settings.models.omObserveAttachments = value;\n saveSettings(settings);\n}\n"],"mappings":";;;;;;;;;;;;AAmBA,SAAgB,2BAA2B,UAAmC;CAC5E,MAAM,EACJ,gBACA,iBACA,uBACA,wBACA,wBACA,4BACE,SAAS;CACb,IACE,mBACA,yBACC,0BAA0B,2BAA2B,UACtD,0BACC,2BAA2B,4BAA4B,QAExD,OAAO;CAKT,OAAO,CAAC,SAAS,WAAW,UAAU,cAAc,CAAC,CAAC,MAAK,WAAU,UAAU,WAAW,QAAQ;AACpG;;;;;;;;;AAUA,SAAgB,6BAA6B,UAA0B,MAAuB;CAC5F,IAAI,2BAA2B,QAAQ,GAAG,OAAO;CAEjD,SAAS,WAAW,WAAW,KAAK;CACpC,SAAS,OAAO,iBAAiB,KAAK;CACtC,SAAS,OAAO,kBAAkB;CAClC,OAAO;AACT;;;;;;;AAQA,SAAgB,sBAAsB,YAAwC;CAC5E,MAAM,OAAO,yBAAyB,UAAU;CAGhD,IAAI,KAAK,OAAO,UAAU,OAAO,KAAA;CAEjC,MAAM,WAAW,aAAa;CAC9B,IAAI,CAAC,6BAA6B,UAAU,IAAI,GAAG,OAAO,KAAA;CAE1D,aAAa,QAAQ;CACrB,OAAO;AACT;;;;;;;;;;AAWA,SAAgB,oBAAoB,UAA0B,MAAgC,SAAuB;CACnH,IAAI,SAAS,YAAY;EACvB,SAAS,OAAO,wBAAwB;EACxC,SAAS,OAAO,yBAAyB;CAC3C,OAAO;EACL,SAAS,OAAO,yBAAyB;EACzC,SAAS,OAAO,0BAA0B;CAC5C;AACF;;AAGA,SAAgB,gBAAgB,UAA0B,MAAsC;CAC9F,IAAI,SAAS,YAAY;EACvB,SAAS,OAAO,wBAAwB;EACxC,SAAS,OAAO,yBAAyB;CAC3C,OAAO;EACL,SAAS,OAAO,yBAAyB;EACzC,SAAS,OAAO,0BAA0B;CAC5C;AACF;AAEA,SAAgB,4BAA4B,OAA+B;CACzE,MAAM,WAAW,aAAa;CAC9B,SAAS,OAAO,uBAAuB;CACvC,aAAa,QAAQ;AACvB"}
@@ -7,9 +7,9 @@ export interface ModePack {
7
7
  plan: string;
8
8
  fast: string;
9
9
  /**
10
- * Optional observational-memory model. When set, OM observer/reflector
11
- * resolve from the pack (and its fallback chain) instead of the standalone
12
- * OM settings, unless an explicit OM role override exists.
10
+ * Optional observational-memory model for both roles while the pack is
11
+ * active: a concrete model ID (with the pack fallback chain), `'auto'`, or
12
+ * unset to follow the per-role `/om` settings.
13
13
  */
14
14
  memory?: string;
15
15
  };
@@ -86,6 +86,15 @@ export declare function getAvailableModePacks(access: ProviderAccess, savedCusto
86
86
  }>): ModePack[];
87
87
  /** A provider's low-cost OM pack, or a custom pack on `fallbackModelId` when it has none. */
88
88
  export declare function resolveProviderOMDefault(providerId: string, fallbackModelId?: string): OMPack;
89
+ /**
90
+ * Mastra Code's overrides for `@mastra/memory`'s auto model table. Memory owns
91
+ * the auto policy; Mastra Code only keeps its newer Gemini Flash default.
92
+ */
93
+ export declare const MASTRACODE_AUTO_OM_MODELS: Readonly<Record<string, string>>;
94
+ /** The model ID Memory reports for a main-session model ID (without Mastra Code's custom-provider prefix). */
95
+ export declare function toMemoryModelId(modelId: string): string;
96
+ /** Preview the concrete model Memory's `'auto'` resolves to for a main-session model ID. */
97
+ export declare function resolveAutoOMModelId(currentModelId?: string): string;
89
98
  export declare function getAvailableOmPacks(access: ProviderAccess): OMPack[];
90
99
  /** Best reachable built-in OM pack: preferred provider, then OAuth, then built-in order. */
91
100
  export declare function selectPreferredOMPack(access: ProviderAccess, preferredProviderId?: string): OMPack | undefined;
@@ -1 +1 @@
1
- {"version":3,"file":"packs.d.ts","sourceRoot":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,CAAC,CAAA;CAAE,CAAM,GAC7E,QAAQ,EAAE,CAuCZ;AAyCD,6FAA6F;AAC7F,wBAAgB,wBAAwB,CAAC,UAAU,EAAE,MAAM,EAAE,eAAe,SAAsB,GAAG,MAAM,CAkB1G;AAED;;;GAGG;AACH,eAAO,MAAM,yBAAyB,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAmC,CAAC;AAI3G,8GAA8G;AAC9G,wBAAgB,eAAe,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAEvD;AAED,4FAA4F;AAC5F,wBAAgB,oBAAoB,CAAC,cAAc,CAAC,EAAE,MAAM,GAAG,MAAM,CAMpE;AAED,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,cAAc,GAAG,MAAM,EAAE,CAuBpE;AAED,4FAA4F;AAC5F,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,cAAc,EAAE,mBAAmB,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAc9G;AAMD,eAAO,MAAM,kBAAkB,IAAI,CAAC"}
@@ -1,4 +1,5 @@
1
1
  import { DEFAULT_OM_MODEL_ID } from "../constants.js";
2
+ import { resolveAutoModelId } from "@mastra/memory";
2
3
  //#region src/onboarding/packs.ts
3
4
  /**
4
5
  * Onboarding "packs" — predefined model configurations for each mode.
@@ -190,7 +191,7 @@ const BUILTIN_OM_PACKS = [
190
191
  id: "openai",
191
192
  providerId: "openai",
192
193
  name: "OpenAI Mini",
193
- modelId: "openai/gpt-5.4-mini",
194
+ modelId: "openai/gpt-6-luna",
194
195
  description: (access) => access === "oauth" ? "Via Codex subscription" : "Via OpenAI API key"
195
196
  },
196
197
  {
@@ -221,6 +222,23 @@ function resolveProviderOMDefault(providerId, fallbackModelId = DEFAULT_OM_MODEL
221
222
  modelId: fallbackModelId || DEFAULT_OM_MODEL_ID
222
223
  };
223
224
  }
225
+ /**
226
+ * Mastra Code's overrides for `@mastra/memory`'s auto model table. Memory owns
227
+ * the auto policy; Mastra Code only keeps its newer Gemini Flash default.
228
+ */
229
+ const MASTRACODE_AUTO_OM_MODELS = { google: DEFAULT_OM_MODEL_ID };
230
+ const CUSTOM_PROVIDER_PREFIX = "mastracode/";
231
+ /** The model ID Memory reports for a main-session model ID (without Mastra Code's custom-provider prefix). */
232
+ function toMemoryModelId(modelId) {
233
+ return modelId.startsWith(CUSTOM_PROVIDER_PREFIX) ? modelId.slice(11) : modelId;
234
+ }
235
+ /** Preview the concrete model Memory's `'auto'` resolves to for a main-session model ID. */
236
+ function resolveAutoOMModelId(currentModelId) {
237
+ if (!currentModelId) return resolveAutoModelId(void 0, { autoModels: MASTRACODE_AUTO_OM_MODELS }) ?? DEFAULT_OM_MODEL_ID;
238
+ const memoryModelId = toMemoryModelId(currentModelId);
239
+ const picked = resolveAutoModelId(memoryModelId, { autoModels: MASTRACODE_AUTO_OM_MODELS });
240
+ return !picked || picked === memoryModelId ? currentModelId : picked;
241
+ }
224
242
  function getAvailableOmPacks(access) {
225
243
  const packs = BUILTIN_OM_PACKS.flatMap((pack) => {
226
244
  const providerAccess = access[pack.providerId];
@@ -255,6 +273,6 @@ function selectPreferredOMPack(access, preferredProviderId) {
255
273
  }
256
274
  const ONBOARDING_VERSION = 1;
257
275
  //#endregion
258
- export { ONBOARDING_VERSION, getAvailableModePacks, getAvailableOmPacks, getBuiltinModePack, isKnownModePackId, listBuiltinModePacks, pruneUnknownModePackFallbacks, pruneUnknownPackAccountPreferences, resolveModePackFallbackChain, resolveProviderOMDefault, selectPreferredOMPack };
276
+ export { MASTRACODE_AUTO_OM_MODELS, ONBOARDING_VERSION, getAvailableModePacks, getAvailableOmPacks, getBuiltinModePack, isKnownModePackId, listBuiltinModePacks, pruneUnknownModePackFallbacks, pruneUnknownPackAccountPreferences, resolveAutoOMModelId, resolveModePackFallbackChain, resolveProviderOMDefault, selectPreferredOMPack, toMemoryModelId };
259
277
 
260
278
  //# sourceMappingURL=packs.js.map