@tangle-network/agent-app 0.60.91 → 0.60.92

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 (33) hide show
  1. package/dist/agent-profiles/d1.js +2 -1
  2. package/dist/agent-profiles/d1.js.map +1 -1
  3. package/dist/agent-profiles/index.d.ts +2 -6
  4. package/dist/agent-profiles/index.js +5 -3
  5. package/dist/agent-profiles/switch.d.ts +11 -0
  6. package/dist/agent-profiles/switch.js +9 -0
  7. package/dist/agent-profiles/switch.js.map +1 -0
  8. package/dist/assistant/index.js +5 -5
  9. package/dist/chat-routes/index.js +10 -10
  10. package/dist/chat-store/index.js +3 -3
  11. package/dist/{chunk-JBEFTXDO.js → chunk-2YLSWZ5W.js} +4 -4
  12. package/dist/{chunk-A2TCZVW4.js → chunk-736V4L2S.js} +6 -6
  13. package/dist/chunk-I6BZVIRH.js +16 -0
  14. package/dist/chunk-I6BZVIRH.js.map +1 -0
  15. package/dist/{chunk-NRG2YHGY.js → chunk-IMTU5LCF.js} +1 -1
  16. package/dist/{chunk-QE2NXMDZ.js → chunk-JWZ32ZGD.js} +2 -2
  17. package/dist/{chunk-ABUF7A4T.js → chunk-ORCY6XGW.js} +5 -12
  18. package/dist/chunk-ORCY6XGW.js.map +1 -0
  19. package/dist/{chunk-XNKLQG26.js → chunk-ZGUXI5SI.js} +5 -5
  20. package/dist/design-canvas-react/index.js +1 -1
  21. package/dist/design-canvas-react/lazy.js +1 -1
  22. package/dist/public-consultation/index.js +5 -5
  23. package/dist/stream/index.js +2 -2
  24. package/dist/web-react/index.js +5 -5
  25. package/dist/workspace-export/index.js +6 -1
  26. package/dist/workspace-export/index.js.map +1 -1
  27. package/package.json +6 -1
  28. package/dist/chunk-ABUF7A4T.js.map +0 -1
  29. /package/dist/{chunk-JBEFTXDO.js.map → chunk-2YLSWZ5W.js.map} +0 -0
  30. /package/dist/{chunk-A2TCZVW4.js.map → chunk-736V4L2S.js.map} +0 -0
  31. /package/dist/{chunk-NRG2YHGY.js.map → chunk-IMTU5LCF.js.map} +0 -0
  32. /package/dist/{chunk-QE2NXMDZ.js.map → chunk-JWZ32ZGD.js.map} +0 -0
  33. /package/dist/{chunk-XNKLQG26.js.map → chunk-ZGUXI5SI.js.map} +0 -0
@@ -2,7 +2,8 @@ import {
2
2
  ProfileConflictError,
3
3
  parseProfileRevisionDiff,
4
4
  serializeProfileRevisionDiff
5
- } from "../chunk-ABUF7A4T.js";
5
+ } from "../chunk-ORCY6XGW.js";
6
+ import "../chunk-I6BZVIRH.js";
6
7
  import "../chunk-BMZTYGKE.js";
7
8
  import "../chunk-UGWQLQDS.js";
8
9
  import "../chunk-TMOYOMSW.js";
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/agent-profiles/d1.ts"],"sourcesContent":["/** Atomic D1 adapter for `/agent-profiles`. Products apply the SQL in their own migration. */\nimport { snapshotAgentProfile } from '@tangle-network/agent-interface'\nimport {\n parseProfileRevisionDiff,\n ProfileConflictError,\n serializeProfileRevisionDiff,\n type ProfileBinding,\n type ProfileBindingKey,\n type ProfileKnowledgeEvent,\n type ProfileRevision,\n type ProfileRevisionStore,\n type ProfileSwitchReceipt,\n type ProfileTurnPin,\n} from './index'\n\n/** Structural subset of Cloudflare D1; keeps the optional driver out of other subpaths. */\nexport interface ProfileD1Statement {\n bind(...values: (string | number | null)[]): ProfileD1Statement\n first<T>(): Promise<T | null>\n all<T>(): Promise<{ results: T[] }>\n run(): Promise<{ meta: { changes: number } }>\n}\n\nexport interface ProfileD1Database {\n prepare(sql: string): ProfileD1Statement\n batch(statements: ProfileD1Statement[]): Promise<{ meta: { changes: number } }[]>\n}\n\n/** Trusted product SQL checked in the same D1 transaction as an agent-authored save. */\nexport interface ProfileD1RevisionWriteGuard {\n /** A boolean SQLite expression with bound values; never build it from model input. */\n sql: string\n values: (string | number | null)[]\n}\n\n/** Trusted product predicate evaluated when a binding event commits. */\nexport type ProfileD1BindingWriteGuard = (receipt: ProfileSwitchReceipt) => ProfileD1RevisionWriteGuard\n\nexport const AGENT_PROFILE_D1_SCHEMA_SQL = `\nCREATE TABLE agent_profile_revision (\n revision_id TEXT PRIMARY KEY,\n workspace_id TEXT NOT NULL,\n profile_id TEXT NOT NULL,\n parent_id TEXT,\n profile_json TEXT NOT NULL,\n knowledge_text TEXT NOT NULL,\n author_kind TEXT NOT NULL CHECK (author_kind IN ('person', 'agent', 'optimizer')),\n author_id TEXT NOT NULL,\n reason TEXT NOT NULL,\n diff_json TEXT NOT NULL,\n authority_digest TEXT NOT NULL,\n plan_digest TEXT NOT NULL,\n state TEXT NOT NULL CHECK (state IN ('active', 'candidate', 'pending-consent')),\n created_at INTEGER NOT NULL\n);\nCREATE INDEX agent_profile_revision_history ON agent_profile_revision(workspace_id, profile_id, created_at DESC);\nCREATE TRIGGER agent_profile_revision_immutable_update BEFORE UPDATE ON agent_profile_revision\nBEGIN SELECT RAISE(ABORT, 'Profile revisions are immutable'); END;\nCREATE TRIGGER agent_profile_revision_immutable_delete BEFORE DELETE ON agent_profile_revision\nBEGIN SELECT RAISE(ABORT, 'Profile revisions are immutable'); END;\nCREATE TABLE agent_profile_activation_event (\n event_id TEXT PRIMARY KEY,\n workspace_id TEXT NOT NULL,\n profile_id TEXT NOT NULL,\n version INTEGER NOT NULL CHECK (version >= 1),\n revision_id TEXT NOT NULL,\n created_at INTEGER NOT NULL,\n UNIQUE (workspace_id, profile_id, version),\n FOREIGN KEY (revision_id) REFERENCES agent_profile_revision(revision_id)\n);\nCREATE TABLE agent_profile_binding_event (\n event_id TEXT PRIMARY KEY,\n workspace_id TEXT NOT NULL,\n member_id TEXT NOT NULL,\n channel TEXT NOT NULL,\n profile_id TEXT NOT NULL,\n pinned_revision_id TEXT,\n authority_digest TEXT NOT NULL,\n plan_digest TEXT NOT NULL,\n version INTEGER NOT NULL CHECK (version >= 1),\n source_message_id TEXT NOT NULL,\n created_at INTEGER NOT NULL,\n UNIQUE (workspace_id, member_id, channel, version),\n UNIQUE (workspace_id, member_id, channel, source_message_id)\n);\nCREATE TABLE agent_profile_switch_receipt (\n workspace_id TEXT NOT NULL,\n member_id TEXT NOT NULL,\n channel TEXT NOT NULL,\n message_id TEXT NOT NULL,\n input_hash TEXT NOT NULL,\n conversation_id TEXT,\n created_at INTEGER NOT NULL,\n profile_id TEXT,\n revision_id TEXT,\n pinned_revision_id TEXT,\n authority_digest TEXT,\n plan_digest TEXT,\n outcome TEXT NOT NULL CHECK (outcome IN ('switched', 'refused')),\n message TEXT NOT NULL,\n conflicts_json TEXT NOT NULL,\n PRIMARY KEY (workspace_id, member_id, channel, message_id)\n);\nCREATE INDEX agent_profile_switch_conversation ON agent_profile_switch_receipt(workspace_id, conversation_id, created_at);\nCREATE TABLE agent_profile_turn_pin (\n workspace_id TEXT NOT NULL,\n member_id TEXT NOT NULL,\n channel TEXT NOT NULL,\n message_id TEXT NOT NULL,\n input_hash TEXT NOT NULL,\n profile_id TEXT NOT NULL,\n revision_id TEXT NOT NULL,\n authority_digest TEXT NOT NULL,\n plan_digest TEXT NOT NULL,\n PRIMARY KEY (workspace_id, member_id, channel, message_id)\n);\nCREATE TABLE agent_profile_knowledge_event (\n event_id TEXT PRIMARY KEY,\n workspace_id TEXT NOT NULL,\n profile_id TEXT NOT NULL,\n document_id TEXT NOT NULL,\n kind TEXT NOT NULL CHECK (kind IN ('add', 'remove')),\n content TEXT,\n observed_add_ids_json TEXT NOT NULL,\n created_at INTEGER NOT NULL,\n CHECK ((kind = 'add' AND content IS NOT NULL) OR (kind = 'remove' AND content IS NULL))\n);\nCREATE INDEX agent_profile_knowledge_history ON agent_profile_knowledge_event(workspace_id, profile_id, document_id, created_at);\nCREATE TRIGGER agent_profile_activation_immutable_update BEFORE UPDATE ON agent_profile_activation_event\nBEGIN SELECT RAISE(ABORT, 'Profile activation events are immutable'); END;\nCREATE TRIGGER agent_profile_activation_immutable_delete BEFORE DELETE ON agent_profile_activation_event\nBEGIN SELECT RAISE(ABORT, 'Profile activation events are immutable'); END;\nCREATE TRIGGER agent_profile_binding_immutable_update BEFORE UPDATE ON agent_profile_binding_event\nBEGIN SELECT RAISE(ABORT, 'Profile binding events are immutable'); END;\nCREATE TRIGGER agent_profile_binding_immutable_delete BEFORE DELETE ON agent_profile_binding_event\nBEGIN SELECT RAISE(ABORT, 'Profile binding events are immutable'); END;\nCREATE TRIGGER agent_profile_switch_immutable_update BEFORE UPDATE ON agent_profile_switch_receipt\nBEGIN SELECT RAISE(ABORT, 'Profile switch receipts are immutable'); END;\nCREATE TRIGGER agent_profile_switch_immutable_delete BEFORE DELETE ON agent_profile_switch_receipt\nBEGIN SELECT RAISE(ABORT, 'Profile switch receipts are immutable'); END;\nCREATE TRIGGER agent_profile_turn_immutable_update BEFORE UPDATE ON agent_profile_turn_pin\nBEGIN SELECT RAISE(ABORT, 'Profile turn pins are immutable'); END;\nCREATE TRIGGER agent_profile_turn_immutable_delete BEFORE DELETE ON agent_profile_turn_pin\nBEGIN SELECT RAISE(ABORT, 'Profile turn pins are immutable'); END;\nCREATE TRIGGER agent_profile_knowledge_immutable_update BEFORE UPDATE ON agent_profile_knowledge_event\nBEGIN SELECT RAISE(ABORT, 'Profile knowledge events are immutable'); END;\nCREATE TRIGGER agent_profile_knowledge_immutable_delete BEFORE DELETE ON agent_profile_knowledge_event\nBEGIN SELECT RAISE(ABORT, 'Profile knowledge events are immutable'); END;`\n\ninterface RevisionRow {\n revision_id: string\n workspace_id: string\n profile_id: string\n parent_id: string | null\n profile_json: string\n knowledge_text: string\n author_kind: ProfileRevision['author']['kind']\n author_id: string\n reason: string\n diff_json: string\n authority_digest: string\n plan_digest: string\n state: ProfileRevision['state']\n created_at: number\n}\n\ninterface BindingRow {\n workspace_id: string\n member_id: string\n channel: string\n profile_id: string\n pinned_revision_id: string | null\n authority_digest: string\n plan_digest: string\n version: number\n}\n\ninterface SwitchRow {\n workspace_id: string\n member_id: string\n channel: string\n message_id: string\n input_hash: string\n conversation_id: string | null\n created_at: number\n profile_id: string | null\n revision_id: string | null\n pinned_revision_id: string | null\n authority_digest: string | null\n plan_digest: string | null\n outcome: ProfileSwitchReceipt['outcome']\n message: string\n conflicts_json: string\n}\n\ninterface TurnRow {\n workspace_id: string\n member_id: string\n channel: string\n message_id: string\n input_hash: string\n profile_id: string\n revision_id: string\n authority_digest: string\n plan_digest: string\n}\n\ninterface KnowledgeRow {\n event_id: string\n workspace_id: string\n profile_id: string\n document_id: string\n kind: ProfileKnowledgeEvent['kind']\n content: string | null\n observed_add_ids_json: string\n created_at: number\n}\n\nconst keyValues = (key: ProfileBindingKey) => [key.workspaceId, key.memberId, key.channel] as const\n\nfunction revisionFromRow(row: RevisionRow): ProfileRevision {\n return { id: row.revision_id, workspaceId: row.workspace_id, profileId: row.profile_id,\n parentId: row.parent_id, profile: snapshotAgentProfile(JSON.parse(row.profile_json)),\n knowledgeText: row.knowledge_text, author: { kind: row.author_kind, id: row.author_id },\n reason: row.reason, ...parseProfileRevisionDiff(row.diff_json),\n authorityDigest: row.authority_digest, planDigest: row.plan_digest,\n state: row.state, createdAt: row.created_at }\n}\n\nfunction receiptFromRow(row: SwitchRow): ProfileSwitchReceipt {\n return { key: { workspaceId: row.workspace_id, memberId: row.member_id, channel: row.channel },\n messageId: row.message_id, inputHash: row.input_hash, profileId: row.profile_id,\n conversationId: row.conversation_id, createdAt: row.created_at,\n revisionId: row.revision_id, pinnedRevisionId: row.pinned_revision_id,\n authorityDigest: row.authority_digest, planDigest: row.plan_digest,\n outcome: row.outcome, message: row.message,\n conflicts: JSON.parse(row.conflicts_json) as string[] }\n}\n\n/** Product auth and profile visibility stay outside this workspace-scoped catalog read. */\nexport async function listD1ActiveProfileRevisions(\n db: ProfileD1Database,\n workspaceId: string,\n): Promise<ProfileRevision[]> {\n const rows = await db.prepare(`SELECT r.* FROM agent_profile_activation_event h\n JOIN agent_profile_revision r ON r.revision_id = h.revision_id\n WHERE h.workspace_id = ? AND h.version = (\n SELECT MAX(latest.version) FROM agent_profile_activation_event latest\n WHERE latest.workspace_id = h.workspace_id AND latest.profile_id = h.profile_id\n ) ORDER BY h.profile_id`).bind(workspaceId).all<RevisionRow>()\n return rows.results.map(revisionFromRow)\n}\n\n/** Product auth stays outside this read. The receipt itself is the durable chat marker. */\nexport async function listD1ProfileSwitchReceipts(\n db: ProfileD1Database,\n workspaceId: string,\n conversationId: string,\n): Promise<ProfileSwitchReceipt[]> {\n const rows = await db.prepare(`SELECT * FROM agent_profile_switch_receipt\n WHERE workspace_id = ? AND conversation_id = ? AND outcome = 'switched'\n ORDER BY created_at, message_id`).bind(workspaceId, conversationId).all<SwitchRow>()\n return rows.results.map(receiptFromRow)\n}\n\nfunction turnFromRow(row: TurnRow): ProfileTurnPin {\n return { workspaceId: row.workspace_id, memberId: row.member_id, channel: row.channel,\n messageId: row.message_id, inputHash: row.input_hash, profileId: row.profile_id,\n revisionId: row.revision_id, authorityDigest: row.authority_digest, planDigest: row.plan_digest }\n}\n\nexport function createD1ProfileRevisionStore(db: ProfileD1Database,\n options: { revisionWriteGuard?: ProfileD1RevisionWriteGuard;\n bindingWriteGuard?: ProfileD1BindingWriteGuard } = {}): ProfileRevisionStore {\n const writeGuard = options.revisionWriteGuard\n if (writeGuard && (!writeGuard.sql.trim() || /;|--|\\/\\*/.test(writeGuard.sql))) {\n throw new TypeError('Revision write guard must be a single trusted SQL expression')\n }\n const currentActivation = `(SELECT revision_id FROM agent_profile_activation_event\n WHERE workspace_id = ? AND profile_id = ? ORDER BY version DESC LIMIT 1)`\n const bindingVersion = `(SELECT COALESCE(MAX(version), 0) FROM agent_profile_binding_event\n WHERE workspace_id = ? AND member_id = ? AND channel = ?)`\n\n async function getRevision(workspaceId: string, profileId: string, revisionId: string) {\n const row = await db.prepare(`SELECT * FROM agent_profile_revision WHERE workspace_id = ? AND profile_id = ? AND revision_id = ?`)\n .bind(workspaceId, profileId, revisionId).first<RevisionRow>()\n return row ? revisionFromRow(row) : null\n }\n\n async function getActiveRevision(workspaceId: string, profileId: string) {\n const row = await db.prepare(`SELECT r.* FROM agent_profile_activation_event h JOIN agent_profile_revision r\n ON r.revision_id = h.revision_id WHERE h.workspace_id = ? AND h.profile_id = ?\n ORDER BY h.version DESC LIMIT 1`)\n .bind(workspaceId, profileId).first<RevisionRow>()\n return row ? revisionFromRow(row) : null\n }\n\n async function getBinding(key: ProfileBindingKey): Promise<ProfileBinding | null> {\n const row = await db.prepare(`SELECT * FROM agent_profile_binding_event\n WHERE workspace_id = ? AND member_id = ? AND channel = ? ORDER BY version DESC LIMIT 1`)\n .bind(...keyValues(key)).first<BindingRow>()\n return row ? { workspaceId: row.workspace_id, memberId: row.member_id, channel: row.channel,\n profileId: row.profile_id, pinnedRevisionId: row.pinned_revision_id,\n authorityDigest: row.authority_digest, planDigest: row.plan_digest, version: row.version } : null\n }\n\n async function getSwitchReceipt(key: ProfileBindingKey, messageId: string, inputHash: string) {\n const row = await db.prepare(`SELECT * FROM agent_profile_switch_receipt WHERE workspace_id = ?\n AND member_id = ? AND channel = ? AND message_id = ?`)\n .bind(...keyValues(key), messageId).first<SwitchRow>()\n if (row && row.input_hash !== inputHash) throw new ProfileConflictError('Message id was reused with different input')\n return row ? receiptFromRow(row) : null\n }\n\n async function getTurnPin(key: ProfileBindingKey, messageId: string, inputHash: string) {\n const row = await db.prepare(`SELECT * FROM agent_profile_turn_pin WHERE workspace_id = ?\n AND member_id = ? AND channel = ? AND message_id = ?`)\n .bind(...keyValues(key), messageId).first<TurnRow>()\n if (row && row.input_hash !== inputHash) throw new ProfileConflictError('Message id was reused with different input')\n return row ? turnFromRow(row) : null\n }\n\n return {\n getRevision,\n getActiveRevision,\n getBinding,\n getSwitchReceipt,\n getTurnPin,\n async listKnowledgeEvents(workspaceId, profileId) {\n const rows = await db.prepare(`SELECT * FROM agent_profile_knowledge_event\n WHERE workspace_id = ? AND profile_id = ? ORDER BY created_at, event_id`)\n .bind(workspaceId, profileId).all<KnowledgeRow>()\n return rows.results.map(row => ({ id: row.event_id, workspaceId: row.workspace_id,\n profileId: row.profile_id, documentId: row.document_id, kind: row.kind,\n content: row.content, observedAddIds: JSON.parse(row.observed_add_ids_json) as string[],\n createdAt: row.created_at }))\n },\n async appendKnowledgeEvent(event) {\n await db.prepare(`INSERT INTO agent_profile_knowledge_event\n (event_id, workspace_id, profile_id, document_id, kind, content, observed_add_ids_json, created_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).bind(event.id, event.workspaceId, event.profileId,\n event.documentId, event.kind, event.content, JSON.stringify(event.observedAddIds), event.createdAt).run()\n },\n async appendRevision(revision, expectedActiveId, activate) {\n const rowValues = [revision.id, revision.workspaceId, revision.profileId, revision.parentId,\n JSON.stringify(revision.profile), revision.knowledgeText, revision.author.kind, revision.author.id,\n revision.reason, serializeProfileRevisionDiff(revision), revision.authorityDigest, revision.planDigest,\n revision.state, revision.createdAt]\n const insert = db.prepare(`INSERT INTO agent_profile_revision\n (revision_id, workspace_id, profile_id, parent_id, profile_json, knowledge_text,\n author_kind, author_id, reason, diff_json, authority_digest, plan_digest, state, created_at)\n SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? WHERE ${expectedActiveId === null\n ? `${currentActivation} IS NULL`\n : `${currentActivation} = ?`}${writeGuard ? ` AND (${writeGuard.sql})` : ''}`)\n .bind(...rowValues, revision.workspaceId, revision.profileId,\n ...(expectedActiveId === null ? [] : [expectedActiveId]), ...(writeGuard?.values ?? []))\n if (!activate) return (await insert.run()).meta.changes === 1\n const activateEvent = db.prepare(`INSERT INTO agent_profile_activation_event\n (event_id, workspace_id, profile_id, version, revision_id, created_at)\n SELECT ?, ?, ?, COALESCE((SELECT MAX(version) FROM agent_profile_activation_event\n WHERE workspace_id = ? AND profile_id = ?), 0) + 1, ?, ?\n WHERE EXISTS (SELECT 1 FROM agent_profile_revision WHERE revision_id = ?\n AND workspace_id = ? AND profile_id = ?)\n AND ${expectedActiveId === null ? `${currentActivation} IS NULL` : `${currentActivation} = ?`}\n ${writeGuard ? `AND (${writeGuard.sql})` : ''}`)\n .bind(crypto.randomUUID(), revision.workspaceId, revision.profileId,\n revision.workspaceId, revision.profileId, revision.id, Date.now(),\n revision.id, revision.workspaceId, revision.profileId,\n revision.workspaceId, revision.profileId, ...(expectedActiveId === null ? [] : [expectedActiveId]),\n ...(writeGuard?.values ?? []))\n const [inserted, activated] = await db.batch([insert, activateEvent])\n return inserted?.meta.changes === 1 && activated?.meta.changes === 1\n },\n async promoteRevision(workspaceId, profileId, revisionId, expectedActiveId) {\n const query = db.prepare(`INSERT INTO agent_profile_activation_event\n (event_id, workspace_id, profile_id, version, revision_id, created_at)\n SELECT ?, ?, ?, COALESCE((SELECT MAX(version) FROM agent_profile_activation_event\n WHERE workspace_id = ? AND profile_id = ?), 0) + 1, ?, ?\n WHERE EXISTS (SELECT 1 FROM agent_profile_revision WHERE workspace_id = ?\n AND profile_id = ? AND revision_id = ? AND parent_id IS ?)\n AND ${expectedActiveId === null ? `${currentActivation} IS NULL` : `${currentActivation} = ?`}`)\n .bind(crypto.randomUUID(), workspaceId, profileId, workspaceId, profileId,\n revisionId, Date.now(), workspaceId, profileId, revisionId, expectedActiveId,\n workspaceId, profileId, ...(expectedActiveId === null ? [] : [expectedActiveId]))\n return (await query.run()).meta.changes === 1\n },\n async recordSwitch(receipt, expectedVersion) {\n const key = receipt.key\n const versionGuard = `${bindingVersion} = ?`\n const bindingGuard = receipt.outcome === 'switched' ? options.bindingWriteGuard?.(receipt) : undefined\n if (bindingGuard && (!bindingGuard.sql.trim() || /;|--|\\/\\*/.test(bindingGuard.sql))) {\n throw new TypeError('Binding write guard must be a single trusted SQL expression')\n }\n const insertReceipt = (requireEventId?: string) => db.prepare(`INSERT INTO agent_profile_switch_receipt\n (workspace_id, member_id, channel, message_id, input_hash, conversation_id, created_at, profile_id, revision_id,\n pinned_revision_id, authority_digest, plan_digest, outcome, message, conflicts_json)\n SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,\n ${requireEventId ? `(SELECT ? WHERE EXISTS (SELECT 1 FROM agent_profile_binding_event WHERE event_id = ?))` : '?'}, ?\n WHERE ${versionGuard} ${requireEventId ? '' : 'ON CONFLICT DO NOTHING'}`)\n .bind(...keyValues(key), receipt.messageId, receipt.inputHash,\n receipt.conversationId ?? null, receipt.createdAt ?? Date.now(),\n receipt.profileId, receipt.revisionId, receipt.pinnedRevisionId,\n receipt.authorityDigest, receipt.planDigest, receipt.outcome,\n receipt.message, ...(requireEventId ? [requireEventId] : []),\n JSON.stringify(receipt.conflicts), ...keyValues(key),\n requireEventId ? expectedVersion + 1 : expectedVersion)\n if (receipt.outcome === 'refused') {\n await insertReceipt().run()\n } else {\n const eventId = crypto.randomUUID()\n const move = db.prepare(`INSERT INTO agent_profile_binding_event\n (event_id, workspace_id, member_id, channel, profile_id, pinned_revision_id,\n authority_digest, plan_digest, version, source_message_id, created_at)\n SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?\n WHERE ${versionGuard}\n AND EXISTS (SELECT 1 FROM agent_profile_revision r WHERE r.workspace_id = ?\n AND r.profile_id = ? AND r.revision_id = ? AND r.authority_digest = ?)\n AND (? IS NOT NULL OR ${currentActivation} = ?)\n ${bindingGuard ? `AND (${bindingGuard.sql})` : ''}\n ON CONFLICT DO NOTHING`)\n .bind(eventId, ...keyValues(key), receipt.profileId, receipt.pinnedRevisionId,\n receipt.authorityDigest, receipt.planDigest, expectedVersion + 1,\n receipt.messageId, Date.now(), ...keyValues(key), expectedVersion,\n key.workspaceId, receipt.profileId, receipt.revisionId, receipt.authorityDigest,\n receipt.pinnedRevisionId, key.workspaceId, receipt.profileId, receipt.revisionId,\n ...(bindingGuard?.values ?? []))\n // A failed event makes the receipt's required message NULL. D1's batch\n // rolls back both writes instead of leaving a success receipt without a binding.\n let outcome: { meta: { changes: number } }[]\n try {\n outcome = await db.batch([move, insertReceipt(eventId)])\n } catch (error) {\n const prior = await getSwitchReceipt(key, receipt.messageId, receipt.inputHash)\n if (prior) return prior\n throw error\n }\n if (outcome[0]?.meta.changes !== 1 || outcome[1]?.meta.changes !== 1) {\n // Another copy of this message may have won before a later switch.\n // Its immutable receipt is still the answer for this message.\n const prior = await getSwitchReceipt(key, receipt.messageId, receipt.inputHash)\n if (prior) return prior\n throw new ProfileConflictError('Profile binding changed during switch')\n }\n }\n const saved = await getSwitchReceipt(key, receipt.messageId, receipt.inputHash)\n if (!saved) throw new ProfileConflictError('Profile binding changed during switch')\n return saved\n },\n async pinTurn(pin, expectedBindingVersion) {\n const key = pin\n const prior = await getTurnPin(key, pin.messageId, pin.inputHash)\n if (prior) return prior\n const inserted = await db.prepare(`INSERT INTO agent_profile_turn_pin\n (workspace_id, member_id, channel, message_id, input_hash, profile_id, revision_id,\n authority_digest, plan_digest)\n SELECT ?, ?, ?, ?, ?, ?, ?, ?, ? WHERE EXISTS (\n SELECT 1 FROM agent_profile_binding_event b WHERE b.workspace_id = ? AND b.member_id = ?\n AND b.channel = ? AND b.version = ? AND b.profile_id = ?\n AND b.version = (SELECT MAX(version) FROM agent_profile_binding_event\n WHERE workspace_id = b.workspace_id AND member_id = b.member_id AND channel = b.channel)\n AND b.authority_digest = ?\n AND (b.pinned_revision_id = ? OR (b.pinned_revision_id IS NULL AND EXISTS (\n SELECT 1 FROM agent_profile_activation_event h WHERE h.workspace_id = b.workspace_id\n AND h.profile_id = b.profile_id AND h.revision_id = ?\n AND h.version = (SELECT MAX(version) FROM agent_profile_activation_event\n WHERE workspace_id = b.workspace_id AND profile_id = b.profile_id))))\n ) AND EXISTS (SELECT 1 FROM agent_profile_revision r WHERE r.workspace_id = ?\n AND r.profile_id = ? AND r.revision_id = ? AND r.authority_digest = ?)\n ON CONFLICT DO NOTHING`)\n .bind(...keyValues(key), pin.messageId, pin.inputHash, pin.profileId, pin.revisionId,\n pin.authorityDigest, pin.planDigest, ...keyValues(key), expectedBindingVersion,\n pin.profileId, pin.authorityDigest,\n pin.revisionId, pin.revisionId, key.workspaceId,\n pin.profileId, pin.revisionId, pin.authorityDigest).run()\n const saved = await getTurnPin(key, pin.messageId, pin.inputHash)\n if (!saved || (inserted.meta.changes === 0 && saved.revisionId !== pin.revisionId)) {\n throw new ProfileConflictError('Profile binding changed during turn admission')\n }\n return saved\n },\n }\n}\n"],"mappings":";;;;;;;;;;AACA,SAAS,4BAA4B;AAqC9B,IAAM,8BAA8B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAoL3C,IAAM,YAAY,CAAC,QAA2B,CAAC,IAAI,aAAa,IAAI,UAAU,IAAI,OAAO;AAEzF,SAAS,gBAAgB,KAAmC;AAC1D,SAAO;AAAA,IAAE,IAAI,IAAI;AAAA,IAAa,aAAa,IAAI;AAAA,IAAc,WAAW,IAAI;AAAA,IAC1E,UAAU,IAAI;AAAA,IAAW,SAAS,qBAAqB,KAAK,MAAM,IAAI,YAAY,CAAC;AAAA,IACnF,eAAe,IAAI;AAAA,IAAgB,QAAQ,EAAE,MAAM,IAAI,aAAa,IAAI,IAAI,UAAU;AAAA,I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ourcesContent":["/** Atomic D1 adapter for `/agent-profiles`. Products apply the SQL in their own migration. */\nimport { snapshotAgentProfile } from '@tangle-network/agent-interface'\nimport {\n parseProfileRevisionDiff,\n ProfileConflictError,\n serializeProfileRevisionDiff,\n type ProfileBinding,\n type ProfileBindingKey,\n type ProfileKnowledgeEvent,\n type ProfileRevision,\n type ProfileRevisionStore,\n type ProfileSwitchReceipt,\n type ProfileTurnPin,\n} from './index'\n\n/** Structural subset of Cloudflare D1; keeps the optional driver out of other subpaths. */\nexport interface ProfileD1Statement {\n bind(...values: (string | number | null)[]): ProfileD1Statement\n first<T>(): Promise<T | null>\n all<T>(): Promise<{ results: T[] }>\n run(): Promise<{ meta: { changes: number } }>\n}\n\nexport interface ProfileD1Database {\n prepare(sql: string): ProfileD1Statement\n batch(statements: ProfileD1Statement[]): Promise<{ meta: { changes: number } }[]>\n}\n\n/** Trusted product SQL checked in the same D1 transaction as an agent-authored save. */\nexport interface ProfileD1RevisionWriteGuard {\n /** A boolean SQLite expression with bound values; never build it from model input. */\n sql: string\n values: (string | number | null)[]\n}\n\n/** Trusted product predicate evaluated when a binding event commits. */\nexport type ProfileD1BindingWriteGuard = (receipt: ProfileSwitchReceipt) => ProfileD1RevisionWriteGuard\n\nexport const AGENT_PROFILE_D1_SCHEMA_SQL = `\nCREATE TABLE agent_profile_revision (\n revision_id TEXT PRIMARY KEY,\n workspace_id TEXT NOT NULL,\n profile_id TEXT NOT NULL,\n parent_id TEXT,\n profile_json TEXT NOT NULL,\n knowledge_text TEXT NOT NULL,\n author_kind TEXT NOT NULL CHECK (author_kind IN ('person', 'agent', 'optimizer')),\n author_id TEXT NOT NULL,\n reason TEXT NOT NULL,\n diff_json TEXT NOT NULL,\n authority_digest TEXT NOT NULL,\n plan_digest TEXT NOT NULL,\n state TEXT NOT NULL CHECK (state IN ('active', 'candidate', 'pending-consent')),\n created_at INTEGER NOT NULL\n);\nCREATE INDEX agent_profile_revision_history ON agent_profile_revision(workspace_id, profile_id, created_at DESC);\nCREATE TRIGGER agent_profile_revision_immutable_update BEFORE UPDATE ON agent_profile_revision\nBEGIN SELECT RAISE(ABORT, 'Profile revisions are immutable'); END;\nCREATE TRIGGER agent_profile_revision_immutable_delete BEFORE DELETE ON agent_profile_revision\nBEGIN SELECT RAISE(ABORT, 'Profile revisions are immutable'); END;\nCREATE TABLE agent_profile_activation_event (\n event_id TEXT PRIMARY KEY,\n workspace_id TEXT NOT NULL,\n profile_id TEXT NOT NULL,\n version INTEGER NOT NULL CHECK (version >= 1),\n revision_id TEXT NOT NULL,\n created_at INTEGER NOT NULL,\n UNIQUE (workspace_id, profile_id, version),\n FOREIGN KEY (revision_id) REFERENCES agent_profile_revision(revision_id)\n);\nCREATE TABLE agent_profile_binding_event (\n event_id TEXT PRIMARY KEY,\n workspace_id TEXT NOT NULL,\n member_id TEXT NOT NULL,\n channel TEXT NOT NULL,\n profile_id TEXT NOT NULL,\n pinned_revision_id TEXT,\n authority_digest TEXT NOT NULL,\n plan_digest TEXT NOT NULL,\n version INTEGER NOT NULL CHECK (version >= 1),\n source_message_id TEXT NOT NULL,\n created_at INTEGER NOT NULL,\n UNIQUE (workspace_id, member_id, channel, version),\n UNIQUE (workspace_id, member_id, channel, source_message_id)\n);\nCREATE TABLE agent_profile_switch_receipt (\n workspace_id TEXT NOT NULL,\n member_id TEXT NOT NULL,\n channel TEXT NOT NULL,\n message_id TEXT NOT NULL,\n input_hash TEXT NOT NULL,\n conversation_id TEXT,\n created_at INTEGER NOT NULL,\n profile_id TEXT,\n revision_id TEXT,\n pinned_revision_id TEXT,\n authority_digest TEXT,\n plan_digest TEXT,\n outcome TEXT NOT NULL CHECK (outcome IN ('switched', 'refused')),\n message TEXT NOT NULL,\n conflicts_json TEXT NOT NULL,\n PRIMARY KEY (workspace_id, member_id, channel, message_id)\n);\nCREATE INDEX agent_profile_switch_conversation ON agent_profile_switch_receipt(workspace_id, conversation_id, created_at);\nCREATE TABLE agent_profile_turn_pin (\n workspace_id TEXT NOT NULL,\n member_id TEXT NOT NULL,\n channel TEXT NOT NULL,\n message_id TEXT NOT NULL,\n input_hash TEXT NOT NULL,\n profile_id TEXT NOT NULL,\n revision_id TEXT NOT NULL,\n authority_digest TEXT NOT NULL,\n plan_digest TEXT NOT NULL,\n PRIMARY KEY (workspace_id, member_id, channel, message_id)\n);\nCREATE TABLE agent_profile_knowledge_event (\n event_id TEXT PRIMARY KEY,\n workspace_id TEXT NOT NULL,\n profile_id TEXT NOT NULL,\n document_id TEXT NOT NULL,\n kind TEXT NOT NULL CHECK (kind IN ('add', 'remove')),\n content TEXT,\n observed_add_ids_json TEXT NOT NULL,\n created_at INTEGER NOT NULL,\n CHECK ((kind = 'add' AND content IS NOT NULL) OR (kind = 'remove' AND content IS NULL))\n);\nCREATE INDEX agent_profile_knowledge_history ON agent_profile_knowledge_event(workspace_id, profile_id, document_id, created_at);\nCREATE TRIGGER agent_profile_activation_immutable_update BEFORE UPDATE ON agent_profile_activation_event\nBEGIN SELECT RAISE(ABORT, 'Profile activation events are immutable'); END;\nCREATE TRIGGER agent_profile_activation_immutable_delete BEFORE DELETE ON agent_profile_activation_event\nBEGIN SELECT RAISE(ABORT, 'Profile activation events are immutable'); END;\nCREATE TRIGGER agent_profile_binding_immutable_update BEFORE UPDATE ON agent_profile_binding_event\nBEGIN SELECT RAISE(ABORT, 'Profile binding events are immutable'); END;\nCREATE TRIGGER agent_profile_binding_immutable_delete BEFORE DELETE ON agent_profile_binding_event\nBEGIN SELECT RAISE(ABORT, 'Profile binding events are immutable'); END;\nCREATE TRIGGER agent_profile_switch_immutable_update BEFORE UPDATE ON agent_profile_switch_receipt\nBEGIN SELECT RAISE(ABORT, 'Profile switch receipts are immutable'); END;\nCREATE TRIGGER agent_profile_switch_immutable_delete BEFORE DELETE ON agent_profile_switch_receipt\nBEGIN SELECT RAISE(ABORT, 'Profile switch receipts are immutable'); END;\nCREATE TRIGGER agent_profile_turn_immutable_update BEFORE UPDATE ON agent_profile_turn_pin\nBEGIN SELECT RAISE(ABORT, 'Profile turn pins are immutable'); END;\nCREATE TRIGGER agent_profile_turn_immutable_delete BEFORE DELETE ON agent_profile_turn_pin\nBEGIN SELECT RAISE(ABORT, 'Profile turn pins are immutable'); END;\nCREATE TRIGGER agent_profile_knowledge_immutable_update BEFORE UPDATE ON agent_profile_knowledge_event\nBEGIN SELECT RAISE(ABORT, 'Profile knowledge events are immutable'); END;\nCREATE TRIGGER agent_profile_knowledge_immutable_delete BEFORE DELETE ON agent_profile_knowledge_event\nBEGIN SELECT RAISE(ABORT, 'Profile knowledge events are immutable'); END;`\n\ninterface RevisionRow {\n revision_id: string\n workspace_id: string\n profile_id: string\n parent_id: string | null\n profile_json: string\n knowledge_text: string\n author_kind: ProfileRevision['author']['kind']\n author_id: string\n reason: string\n diff_json: string\n authority_digest: string\n plan_digest: string\n state: ProfileRevision['state']\n created_at: number\n}\n\ninterface BindingRow {\n workspace_id: string\n member_id: string\n channel: string\n profile_id: string\n pinned_revision_id: string | null\n authority_digest: string\n plan_digest: string\n version: number\n}\n\ninterface SwitchRow {\n workspace_id: string\n member_id: string\n channel: string\n message_id: string\n input_hash: string\n conversation_id: string | null\n created_at: number\n profile_id: string | null\n revision_id: string | null\n pinned_revision_id: string | null\n authority_digest: string | null\n plan_digest: string | null\n outcome: ProfileSwitchReceipt['outcome']\n message: string\n conflicts_json: string\n}\n\ninterface TurnRow {\n workspace_id: string\n member_id: string\n channel: string\n message_id: string\n input_hash: string\n profile_id: string\n revision_id: string\n authority_digest: string\n plan_digest: string\n}\n\ninterface KnowledgeRow {\n event_id: string\n workspace_id: string\n profile_id: string\n document_id: string\n kind: ProfileKnowledgeEvent['kind']\n content: string | null\n observed_add_ids_json: string\n created_at: number\n}\n\nconst keyValues = (key: ProfileBindingKey) => [key.workspaceId, key.memberId, key.channel] as const\n\nfunction revisionFromRow(row: RevisionRow): ProfileRevision {\n return { id: row.revision_id, workspaceId: row.workspace_id, profileId: row.profile_id,\n parentId: row.parent_id, profile: snapshotAgentProfile(JSON.parse(row.profile_json)),\n knowledgeText: row.knowledge_text, author: { kind: row.author_kind, id: row.author_id },\n reason: row.reason, ...parseProfileRevisionDiff(row.diff_json),\n authorityDigest: row.authority_digest, planDigest: row.plan_digest,\n state: row.state, createdAt: row.created_at }\n}\n\nfunction receiptFromRow(row: SwitchRow): ProfileSwitchReceipt {\n return { key: { workspaceId: row.workspace_id, memberId: row.member_id, channel: row.channel },\n messageId: row.message_id, inputHash: row.input_hash, profileId: row.profile_id,\n conversationId: row.conversation_id, createdAt: row.created_at,\n revisionId: row.revision_id, pinnedRevisionId: row.pinned_revision_id,\n authorityDigest: row.authority_digest, planDigest: row.plan_digest,\n outcome: row.outcome, message: row.message,\n conflicts: JSON.parse(row.conflicts_json) as string[] }\n}\n\n/** Product auth and profile visibility stay outside this workspace-scoped catalog read. */\nexport async function listD1ActiveProfileRevisions(\n db: ProfileD1Database,\n workspaceId: string,\n): Promise<ProfileRevision[]> {\n const rows = await db.prepare(`SELECT r.* FROM agent_profile_activation_event h\n JOIN agent_profile_revision r ON r.revision_id = h.revision_id\n WHERE h.workspace_id = ? AND h.version = (\n SELECT MAX(latest.version) FROM agent_profile_activation_event latest\n WHERE latest.workspace_id = h.workspace_id AND latest.profile_id = h.profile_id\n ) ORDER BY h.profile_id`).bind(workspaceId).all<RevisionRow>()\n return rows.results.map(revisionFromRow)\n}\n\n/** Product auth stays outside this read. The receipt itself is the durable chat marker. */\nexport async function listD1ProfileSwitchReceipts(\n db: ProfileD1Database,\n workspaceId: string,\n conversationId: string,\n): Promise<ProfileSwitchReceipt[]> {\n const rows = await db.prepare(`SELECT * FROM agent_profile_switch_receipt\n WHERE workspace_id = ? AND conversation_id = ? AND outcome = 'switched'\n ORDER BY created_at, message_id`).bind(workspaceId, conversationId).all<SwitchRow>()\n return rows.results.map(receiptFromRow)\n}\n\nfunction turnFromRow(row: TurnRow): ProfileTurnPin {\n return { workspaceId: row.workspace_id, memberId: row.member_id, channel: row.channel,\n messageId: row.message_id, inputHash: row.input_hash, profileId: row.profile_id,\n revisionId: row.revision_id, authorityDigest: row.authority_digest, planDigest: row.plan_digest }\n}\n\nexport function createD1ProfileRevisionStore(db: ProfileD1Database,\n options: { revisionWriteGuard?: ProfileD1RevisionWriteGuard;\n bindingWriteGuard?: ProfileD1BindingWriteGuard } = {}): ProfileRevisionStore {\n const writeGuard = options.revisionWriteGuard\n if (writeGuard && (!writeGuard.sql.trim() || /;|--|\\/\\*/.test(writeGuard.sql))) {\n throw new TypeError('Revision write guard must be a single trusted SQL expression')\n }\n const currentActivation = `(SELECT revision_id FROM agent_profile_activation_event\n WHERE workspace_id = ? AND profile_id = ? ORDER BY version DESC LIMIT 1)`\n const bindingVersion = `(SELECT COALESCE(MAX(version), 0) FROM agent_profile_binding_event\n WHERE workspace_id = ? AND member_id = ? AND channel = ?)`\n\n async function getRevision(workspaceId: string, profileId: string, revisionId: string) {\n const row = await db.prepare(`SELECT * FROM agent_profile_revision WHERE workspace_id = ? AND profile_id = ? AND revision_id = ?`)\n .bind(workspaceId, profileId, revisionId).first<RevisionRow>()\n return row ? revisionFromRow(row) : null\n }\n\n async function getActiveRevision(workspaceId: string, profileId: string) {\n const row = await db.prepare(`SELECT r.* FROM agent_profile_activation_event h JOIN agent_profile_revision r\n ON r.revision_id = h.revision_id WHERE h.workspace_id = ? AND h.profile_id = ?\n ORDER BY h.version DESC LIMIT 1`)\n .bind(workspaceId, profileId).first<RevisionRow>()\n return row ? revisionFromRow(row) : null\n }\n\n async function getBinding(key: ProfileBindingKey): Promise<ProfileBinding | null> {\n const row = await db.prepare(`SELECT * FROM agent_profile_binding_event\n WHERE workspace_id = ? AND member_id = ? AND channel = ? ORDER BY version DESC LIMIT 1`)\n .bind(...keyValues(key)).first<BindingRow>()\n return row ? { workspaceId: row.workspace_id, memberId: row.member_id, channel: row.channel,\n profileId: row.profile_id, pinnedRevisionId: row.pinned_revision_id,\n authorityDigest: row.authority_digest, planDigest: row.plan_digest, version: row.version } : null\n }\n\n async function getSwitchReceipt(key: ProfileBindingKey, messageId: string, inputHash: string) {\n const row = await db.prepare(`SELECT * FROM agent_profile_switch_receipt WHERE workspace_id = ?\n AND member_id = ? AND channel = ? AND message_id = ?`)\n .bind(...keyValues(key), messageId).first<SwitchRow>()\n if (row && row.input_hash !== inputHash) throw new ProfileConflictError('Message id was reused with different input')\n return row ? receiptFromRow(row) : null\n }\n\n async function getTurnPin(key: ProfileBindingKey, messageId: string, inputHash: string) {\n const row = await db.prepare(`SELECT * FROM agent_profile_turn_pin WHERE workspace_id = ?\n AND member_id = ? AND channel = ? AND message_id = ?`)\n .bind(...keyValues(key), messageId).first<TurnRow>()\n if (row && row.input_hash !== inputHash) throw new ProfileConflictError('Message id was reused with different input')\n return row ? turnFromRow(row) : null\n }\n\n return {\n getRevision,\n getActiveRevision,\n getBinding,\n getSwitchReceipt,\n getTurnPin,\n async listKnowledgeEvents(workspaceId, profileId) {\n const rows = await db.prepare(`SELECT * FROM agent_profile_knowledge_event\n WHERE workspace_id = ? AND profile_id = ? ORDER BY created_at, event_id`)\n .bind(workspaceId, profileId).all<KnowledgeRow>()\n return rows.results.map(row => ({ id: row.event_id, workspaceId: row.workspace_id,\n profileId: row.profile_id, documentId: row.document_id, kind: row.kind,\n content: row.content, observedAddIds: JSON.parse(row.observed_add_ids_json) as string[],\n createdAt: row.created_at }))\n },\n async appendKnowledgeEvent(event) {\n await db.prepare(`INSERT INTO agent_profile_knowledge_event\n (event_id, workspace_id, profile_id, document_id, kind, content, observed_add_ids_json, created_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).bind(event.id, event.workspaceId, event.profileId,\n event.documentId, event.kind, event.content, JSON.stringify(event.observedAddIds), event.createdAt).run()\n },\n async appendRevision(revision, expectedActiveId, activate) {\n const rowValues = [revision.id, revision.workspaceId, revision.profileId, revision.parentId,\n JSON.stringify(revision.profile), revision.knowledgeText, revision.author.kind, revision.author.id,\n revision.reason, serializeProfileRevisionDiff(revision), revision.authorityDigest, revision.planDigest,\n revision.state, revision.createdAt]\n const insert = db.prepare(`INSERT INTO agent_profile_revision\n (revision_id, workspace_id, profile_id, parent_id, profile_json, knowledge_text,\n author_kind, author_id, reason, diff_json, authority_digest, plan_digest, state, created_at)\n SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? WHERE ${expectedActiveId === null\n ? `${currentActivation} IS NULL`\n : `${currentActivation} = ?`}${writeGuard ? ` AND (${writeGuard.sql})` : ''}`)\n .bind(...rowValues, revision.workspaceId, revision.profileId,\n ...(expectedActiveId === null ? [] : [expectedActiveId]), ...(writeGuard?.values ?? []))\n if (!activate) return (await insert.run()).meta.changes === 1\n const activateEvent = db.prepare(`INSERT INTO agent_profile_activation_event\n (event_id, workspace_id, profile_id, version, revision_id, created_at)\n SELECT ?, ?, ?, COALESCE((SELECT MAX(version) FROM agent_profile_activation_event\n WHERE workspace_id = ? AND profile_id = ?), 0) + 1, ?, ?\n WHERE EXISTS (SELECT 1 FROM agent_profile_revision WHERE revision_id = ?\n AND workspace_id = ? AND profile_id = ?)\n AND ${expectedActiveId === null ? `${currentActivation} IS NULL` : `${currentActivation} = ?`}\n ${writeGuard ? `AND (${writeGuard.sql})` : ''}`)\n .bind(crypto.randomUUID(), revision.workspaceId, revision.profileId,\n revision.workspaceId, revision.profileId, revision.id, Date.now(),\n revision.id, revision.workspaceId, revision.profileId,\n revision.workspaceId, revision.profileId, ...(expectedActiveId === null ? [] : [expectedActiveId]),\n ...(writeGuard?.values ?? []))\n const [inserted, activated] = await db.batch([insert, activateEvent])\n return inserted?.meta.changes === 1 && activated?.meta.changes === 1\n },\n async promoteRevision(workspaceId, profileId, revisionId, expectedActiveId) {\n const query = db.prepare(`INSERT INTO agent_profile_activation_event\n (event_id, workspace_id, profile_id, version, revision_id, created_at)\n SELECT ?, ?, ?, COALESCE((SELECT MAX(version) FROM agent_profile_activation_event\n WHERE workspace_id = ? AND profile_id = ?), 0) + 1, ?, ?\n WHERE EXISTS (SELECT 1 FROM agent_profile_revision WHERE workspace_id = ?\n AND profile_id = ? AND revision_id = ? AND parent_id IS ?)\n AND ${expectedActiveId === null ? `${currentActivation} IS NULL` : `${currentActivation} = ?`}`)\n .bind(crypto.randomUUID(), workspaceId, profileId, workspaceId, profileId,\n revisionId, Date.now(), workspaceId, profileId, revisionId, expectedActiveId,\n workspaceId, profileId, ...(expectedActiveId === null ? [] : [expectedActiveId]))\n return (await query.run()).meta.changes === 1\n },\n async recordSwitch(receipt, expectedVersion) {\n const key = receipt.key\n const versionGuard = `${bindingVersion} = ?`\n const bindingGuard = receipt.outcome === 'switched' ? options.bindingWriteGuard?.(receipt) : undefined\n if (bindingGuard && (!bindingGuard.sql.trim() || /;|--|\\/\\*/.test(bindingGuard.sql))) {\n throw new TypeError('Binding write guard must be a single trusted SQL expression')\n }\n const insertReceipt = (requireEventId?: string) => db.prepare(`INSERT INTO agent_profile_switch_receipt\n (workspace_id, member_id, channel, message_id, input_hash, conversation_id, created_at, profile_id, revision_id,\n pinned_revision_id, authority_digest, plan_digest, outcome, message, conflicts_json)\n SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,\n ${requireEventId ? `(SELECT ? WHERE EXISTS (SELECT 1 FROM agent_profile_binding_event WHERE event_id = ?))` : '?'}, ?\n WHERE ${versionGuard} ${requireEventId ? '' : 'ON CONFLICT DO NOTHING'}`)\n .bind(...keyValues(key), receipt.messageId, receipt.inputHash,\n receipt.conversationId ?? null, receipt.createdAt ?? Date.now(),\n receipt.profileId, receipt.revisionId, receipt.pinnedRevisionId,\n receipt.authorityDigest, receipt.planDigest, receipt.outcome,\n receipt.message, ...(requireEventId ? [requireEventId] : []),\n JSON.stringify(receipt.conflicts), ...keyValues(key),\n requireEventId ? expectedVersion + 1 : expectedVersion)\n if (receipt.outcome === 'refused') {\n await insertReceipt().run()\n } else {\n const eventId = crypto.randomUUID()\n const move = db.prepare(`INSERT INTO agent_profile_binding_event\n (event_id, workspace_id, member_id, channel, profile_id, pinned_revision_id,\n authority_digest, plan_digest, version, source_message_id, created_at)\n SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?\n WHERE ${versionGuard}\n AND EXISTS (SELECT 1 FROM agent_profile_revision r WHERE r.workspace_id = ?\n AND r.profile_id = ? AND r.revision_id = ? AND r.authority_digest = ?)\n AND (? IS NOT NULL OR ${currentActivation} = ?)\n ${bindingGuard ? `AND (${bindingGuard.sql})` : ''}\n ON CONFLICT DO NOTHING`)\n .bind(eventId, ...keyValues(key), receipt.profileId, receipt.pinnedRevisionId,\n receipt.authorityDigest, receipt.planDigest, expectedVersion + 1,\n receipt.messageId, Date.now(), ...keyValues(key), expectedVersion,\n key.workspaceId, receipt.profileId, receipt.revisionId, receipt.authorityDigest,\n receipt.pinnedRevisionId, key.workspaceId, receipt.profileId, receipt.revisionId,\n ...(bindingGuard?.values ?? []))\n // A failed event makes the receipt's required message NULL. D1's batch\n // rolls back both writes instead of leaving a success receipt without a binding.\n let outcome: { meta: { changes: number } }[]\n try {\n outcome = await db.batch([move, insertReceipt(eventId)])\n } catch (error) {\n const prior = await getSwitchReceipt(key, receipt.messageId, receipt.inputHash)\n if (prior) return prior\n throw error\n }\n if (outcome[0]?.meta.changes !== 1 || outcome[1]?.meta.changes !== 1) {\n // Another copy of this message may have won before a later switch.\n // Its immutable receipt is still the answer for this message.\n const prior = await getSwitchReceipt(key, receipt.messageId, receipt.inputHash)\n if (prior) return prior\n throw new ProfileConflictError('Profile binding changed during switch')\n }\n }\n const saved = await getSwitchReceipt(key, receipt.messageId, receipt.inputHash)\n if (!saved) throw new ProfileConflictError('Profile binding changed during switch')\n return saved\n },\n async pinTurn(pin, expectedBindingVersion) {\n const key = pin\n const prior = await getTurnPin(key, pin.messageId, pin.inputHash)\n if (prior) return prior\n const inserted = await db.prepare(`INSERT INTO agent_profile_turn_pin\n (workspace_id, member_id, channel, message_id, input_hash, profile_id, revision_id,\n authority_digest, plan_digest)\n SELECT ?, ?, ?, ?, ?, ?, ?, ?, ? WHERE EXISTS (\n SELECT 1 FROM agent_profile_binding_event b WHERE b.workspace_id = ? AND b.member_id = ?\n AND b.channel = ? AND b.version = ? AND b.profile_id = ?\n AND b.version = (SELECT MAX(version) FROM agent_profile_binding_event\n WHERE workspace_id = b.workspace_id AND member_id = b.member_id AND channel = b.channel)\n AND b.authority_digest = ?\n AND (b.pinned_revision_id = ? OR (b.pinned_revision_id IS NULL AND EXISTS (\n SELECT 1 FROM agent_profile_activation_event h WHERE h.workspace_id = b.workspace_id\n AND h.profile_id = b.profile_id AND h.revision_id = ?\n AND h.version = (SELECT MAX(version) FROM agent_profile_activation_event\n WHERE workspace_id = b.workspace_id AND profile_id = b.profile_id))))\n ) AND EXISTS (SELECT 1 FROM agent_profile_revision r WHERE r.workspace_id = ?\n AND r.profile_id = ? AND r.revision_id = ? AND r.authority_digest = ?)\n ON CONFLICT DO NOTHING`)\n .bind(...keyValues(key), pin.messageId, pin.inputHash, pin.profileId, pin.revisionId,\n pin.authorityDigest, pin.planDigest, ...keyValues(key), expectedBindingVersion,\n pin.profileId, pin.authorityDigest,\n pin.revisionId, pin.revisionId, key.workspaceId,\n pin.profileId, pin.revisionId, pin.authorityDigest).run()\n const saved = await getTurnPin(key, pin.messageId, pin.inputHash)\n if (!saved || (inserted.meta.changes === 0 && saved.revisionId !== pin.revisionId)) {\n throw new ProfileConflictError('Profile binding changed during turn admission')\n }\n return saved\n },\n }\n}\n"],"mappings":";;;;;;;;;;;AACA,SAAS,4BAA4B;AAqC9B,IAAM,8BAA8B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAA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AG,QAAQ;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,+BAgBT,EACtB;AAAA,QAAK,GAAG,UAAU,GAAG;AAAA,QAAG,IAAI;AAAA,QAAW,IAAI;AAAA,QAAW,IAAI;AAAA,QAAW,IAAI;AAAA,QACxE,IAAI;AAAA,QAAiB,IAAI;AAAA,QAAY,GAAG,UAAU,GAAG;AAAA,QAAG;AAAA,QACxD,IAAI;AAAA,QAAW,IAAI;AAAA,QACnB,IAAI;AAAA,QAAY,IAAI;AAAA,QAAY,IAAI;AAAA,QACpC,IAAI;AAAA,QAAW,IAAI;AAAA,QAAY,IAAI;AAAA,MAAe,EAAE,IAAI;AAC5D,YAAM,QAAQ,MAAM,WAAW,KAAK,IAAI,WAAW,IAAI,SAAS;AAChE,UAAI,CAAC,SAAU,SAAS,KAAK,YAAY,KAAK,MAAM,eAAe,IAAI,YAAa;AAClF,cAAM,IAAI,qBAAqB,+CAA+C;AAAA,MAChF;AACA,aAAO;AAAA,IACT;AAAA,EACF;AACF;","names":[]}
@@ -1,6 +1,8 @@
1
1
  /** Chat-owned profile revisions and member/channel bindings. Execution stays in the substrate. */
2
2
  import { type AgentProfile, type AgentProfileDiff } from '@tangle-network/agent-interface';
3
3
  import { z } from 'zod';
4
+ import { normalizeProfileName, parseProfileSwitch } from './switch';
5
+ export { normalizeProfileName, parseProfileSwitch };
4
6
  import type { McpToolDefinition } from '../tools';
5
7
  export type ProfileAuthorKind = 'person' | 'agent' | 'optimizer';
6
8
  export type ProfileRevisionState = 'active' | 'candidate' | 'pending-consent';
@@ -217,12 +219,6 @@ export declare function promoteRevision(input: {
217
219
  /** Verified by the product's consent route; required when authority changes. */
218
220
  verifyConsent?: (revision: ProfileRevision) => Promise<boolean>;
219
221
  }): Promise<ProfileRevision>;
220
- export declare function parseProfileSwitch(text: string): {
221
- name: string;
222
- } | {
223
- invalid: true;
224
- } | null;
225
- export declare function normalizeProfileName(name: string): string;
226
222
  /** A source identity joins the command hash without entering the receipt row. */
227
223
  export declare function profileSwitchInputHashFromContentHash(contentHash: string, identityContext?: string): string;
228
224
  export declare function profileSwitchInputHash(content: string, identityContext?: string): string;
@@ -10,9 +10,7 @@ import {
10
10
  createMountProfileChangeTool,
11
11
  createTextProfile,
12
12
  handleProfileSwitchText,
13
- normalizeProfileName,
14
13
  parseProfileRevisionDiff,
15
- parseProfileSwitch,
16
14
  profileAuthority,
17
15
  profileAuthorityDigest,
18
16
  profileSwitchInputHash,
@@ -26,7 +24,11 @@ import {
26
24
  rollbackProfileBinding,
27
25
  serializeProfileRevisionDiff,
28
26
  switchProfile
29
- } from "../chunk-ABUF7A4T.js";
27
+ } from "../chunk-ORCY6XGW.js";
28
+ import {
29
+ normalizeProfileName,
30
+ parseProfileSwitch
31
+ } from "../chunk-I6BZVIRH.js";
30
32
  import "../chunk-BMZTYGKE.js";
31
33
  import "../chunk-UGWQLQDS.js";
32
34
  import "../chunk-TMOYOMSW.js";
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Chat profile-switch parsing with no dependencies, so browser code can import it without the
3
+ * profile schemas: through the agent-profiles barrel it pulled zod and the schemas into
4
+ * Hospitality's first page (254 KB of its 1,396 KB initial JavaScript, 2026-10-11).
5
+ */
6
+ export declare function parseProfileSwitch(text: string): {
7
+ name: string;
8
+ } | {
9
+ invalid: true;
10
+ } | null;
11
+ export declare function normalizeProfileName(name: string): string;
@@ -0,0 +1,9 @@
1
+ import {
2
+ normalizeProfileName,
3
+ parseProfileSwitch
4
+ } from "../chunk-I6BZVIRH.js";
5
+ export {
6
+ normalizeProfileName,
7
+ parseProfileSwitch
8
+ };
9
+ //# sourceMappingURL=switch.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -1,12 +1,12 @@
1
1
  import {
2
2
  chatToolCallPart
3
- } from "../chunk-A2TCZVW4.js";
3
+ } from "../chunk-736V4L2S.js";
4
4
  import "../chunk-2FLSODOX.js";
5
5
  import "../chunk-3HUFJ5LO.js";
6
+ import "../chunk-FBVLEGEG.js";
6
7
  import "../chunk-KHCJKVQN.js";
7
8
  import "../chunk-XEURJVS5.js";
8
9
  import "../chunk-E4AY62T2.js";
9
- import "../chunk-FBVLEGEG.js";
10
10
  import "../chunk-Y6PRDUFJ.js";
11
11
  import "../chunk-GEYACSFW.js";
12
12
  import {
@@ -28,13 +28,13 @@ import "../chunk-MCYJON3F.js";
28
28
  import "../chunk-B7CL7ENS.js";
29
29
  import "../chunk-PV33JZKV.js";
30
30
  import "../chunk-7YA4QNTU.js";
31
- import "../chunk-JBEFTXDO.js";
31
+ import "../chunk-2YLSWZ5W.js";
32
32
  import "../chunk-ZVEEWGDK.js";
33
33
  import "../chunk-6E7LKHYV.js";
34
34
  import "../chunk-TXD5HXLE.js";
35
- import "../chunk-XNKLQG26.js";
36
- import "../chunk-LQYIBL3G.js";
35
+ import "../chunk-ZGUXI5SI.js";
37
36
  import "../chunk-6VQCFJWP.js";
37
+ import "../chunk-LQYIBL3G.js";
38
38
 
39
39
  // src/assistant/sse.ts
40
40
  var SSEChunkParser = class {
@@ -65,16 +65,16 @@ import {
65
65
  rowIdOf,
66
66
  storeSupportsDraftPersistence,
67
67
  streamChatRouteAsSandboxEvents
68
- } from "../chunk-QE2NXMDZ.js";
68
+ } from "../chunk-JWZ32ZGD.js";
69
+ import "../chunk-Q7WEEN7P.js";
69
70
  import "../chunk-UTAIRVOK.js";
70
71
  import "../chunk-RN4WPTBH.js";
71
- import "../chunk-Q7WEEN7P.js";
72
72
  import "../chunk-3NCPXNBZ.js";
73
73
  import {
74
74
  attachmentInputToPart,
75
75
  attachmentKindForMime,
76
76
  toChatMessageParts
77
- } from "../chunk-JBEFTXDO.js";
77
+ } from "../chunk-2YLSWZ5W.js";
78
78
  import "../chunk-ZVEEWGDK.js";
79
79
  import {
80
80
  ChatTurnInputError,
@@ -124,13 +124,7 @@ import {
124
124
  normalizePersistedPart,
125
125
  normalizeToolEvent,
126
126
  terminalizeDanglingAssistantToolUpdates
127
- } from "../chunk-XNKLQG26.js";
128
- import {
129
- parsePlanSubmittedEvent,
130
- persistedPartToPlan,
131
- planFollowUpTurnId,
132
- planToPersistedPart
133
- } from "../chunk-LQYIBL3G.js";
127
+ } from "../chunk-ZGUXI5SI.js";
134
128
  import {
135
129
  cancelStatusFor,
136
130
  interactionPartKey,
@@ -141,6 +135,12 @@ import {
141
135
  parseInteractionCancel,
142
136
  parseInteractionRequest
143
137
  } from "../chunk-6VQCFJWP.js";
138
+ import {
139
+ parsePlanSubmittedEvent,
140
+ persistedPartToPlan,
141
+ planFollowUpTurnId,
142
+ planToPersistedPart
143
+ } from "../chunk-LQYIBL3G.js";
144
144
  import {
145
145
  coalesceDeltas,
146
146
  createBufferedTurnTap
@@ -14,15 +14,15 @@ import {
14
14
  mentionInputToPart,
15
15
  mentionPartsFromMessageParts,
16
16
  toChatMessageParts
17
- } from "../chunk-JBEFTXDO.js";
17
+ } from "../chunk-2YLSWZ5W.js";
18
18
  import "../chunk-ZVEEWGDK.js";
19
19
  import "../chunk-6E7LKHYV.js";
20
20
  import "../chunk-TXD5HXLE.js";
21
21
  import {
22
22
  attachmentPartKey
23
- } from "../chunk-XNKLQG26.js";
24
- import "../chunk-LQYIBL3G.js";
23
+ } from "../chunk-ZGUXI5SI.js";
25
24
  import "../chunk-6VQCFJWP.js";
25
+ import "../chunk-LQYIBL3G.js";
26
26
 
27
27
  // src/chat-store/core.ts
28
28
  var BULK_DELETE_MAX_THREADS = 200;
@@ -4,13 +4,13 @@ import {
4
4
  import {
5
5
  mentionKindForPath
6
6
  } from "./chunk-6E7LKHYV.js";
7
+ import {
8
+ persistedPartToInteraction
9
+ } from "./chunk-6VQCFJWP.js";
7
10
  import {
8
11
  persistedPartToPlan,
9
12
  planToPersistedPart
10
13
  } from "./chunk-LQYIBL3G.js";
11
- import {
12
- persistedPartToInteraction
13
- } from "./chunk-6VQCFJWP.js";
14
14
 
15
15
  // src/chat-store/parts.ts
16
16
  function toChatMessageParts(parts) {
@@ -135,4 +135,4 @@ export {
135
135
  buildAttachmentPromptBlock,
136
136
  historyContentWithAttachments
137
137
  };
138
- //# sourceMappingURL=chunk-JBEFTXDO.js.map
138
+ //# sourceMappingURL=chunk-2YLSWZ5W.js.map
@@ -50,16 +50,12 @@ import {
50
50
  } from "./chunk-B7CL7ENS.js";
51
51
  import {
52
52
  attachmentPartsFromMessageParts
53
- } from "./chunk-JBEFTXDO.js";
53
+ } from "./chunk-2YLSWZ5W.js";
54
54
  import {
55
55
  TURN_PHASE_EVENT,
56
56
  isTurnPhaseEvent,
57
57
  settleTurnResponse
58
58
  } from "./chunk-6E7LKHYV.js";
59
- import {
60
- parsePlanSubmittedEvent,
61
- persistedPartToPlan
62
- } from "./chunk-LQYIBL3G.js";
63
59
  import {
64
60
  cancelStatusFor,
65
61
  fieldAcceptsFreeText,
@@ -70,6 +66,10 @@ import {
70
66
  persistedPartToInteraction,
71
67
  questionInteractionContentSignature
72
68
  } from "./chunk-6VQCFJWP.js";
69
+ import {
70
+ parsePlanSubmittedEvent,
71
+ persistedPartToPlan
72
+ } from "./chunk-LQYIBL3G.js";
73
73
 
74
74
  // src/web-react/index.tsx
75
75
  import { useEffect as useEffect18, useMemo as useMemo10, useRef as useRef17, useState as useState26, memo } from "react";
@@ -8971,4 +8971,4 @@ export {
8971
8971
  useThinkingSeconds,
8972
8972
  ChatMessages
8973
8973
  };
8974
- //# sourceMappingURL=chunk-A2TCZVW4.js.map
8974
+ //# sourceMappingURL=chunk-736V4L2S.js.map
@@ -0,0 +1,16 @@
1
+ // src/agent-profiles/switch.ts
2
+ function parseProfileSwitch(text) {
3
+ const trimmed = text.trim();
4
+ if (!/^switch\s+to\b/i.test(trimmed)) return null;
5
+ const match = /^switch[ \t]+to[ \t]+([^\r\n]+)$/i.exec(trimmed);
6
+ return match?.[1]?.trim() ? { name: match[1].trim() } : { invalid: true };
7
+ }
8
+ function normalizeProfileName(name) {
9
+ return name.trim().replace(/\s+/g, " ").toLowerCase();
10
+ }
11
+
12
+ export {
13
+ parseProfileSwitch,
14
+ normalizeProfileName
15
+ };
16
+ //# sourceMappingURL=chunk-I6BZVIRH.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/agent-profiles/switch.ts"],"sourcesContent":["/**\n * Chat profile-switch parsing with no dependencies, so browser code can import it without the\n * profile schemas: through the agent-profiles barrel it pulled zod and the schemas into\n * Hospitality's first page (254 KB of its 1,396 KB initial JavaScript, 2026-10-11).\n */\nexport function parseProfileSwitch(text: string): { name: string } | { invalid: true } | null {\n const trimmed = text.trim()\n if (!/^switch\\s+to\\b/i.test(trimmed)) return null\n const match = /^switch[ \\t]+to[ \\t]+([^\\r\\n]+)$/i.exec(trimmed)\n return match?.[1]?.trim() ? { name: match[1].trim() } : { invalid: true }\n}\n\nexport function normalizeProfileName(name: string): string {\n return name.trim().replace(/\\s+/g, ' ').toLowerCase()\n}\n"],"mappings":";AAKO,SAAS,mBAAmB,MAA2D;AAC5F,QAAM,UAAU,KAAK,KAAK;AAC1B,MAAI,CAAC,kBAAkB,KAAK,OAAO,EAAG,QAAO;AAC7C,QAAM,QAAQ,oCAAoC,KAAK,OAAO;AAC9D,SAAO,QAAQ,CAAC,GAAG,KAAK,IAAI,EAAE,MAAM,MAAM,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,SAAS,KAAK;AAC1E;AAEO,SAAS,qBAAqB,MAAsB;AACzD,SAAO,KAAK,KAAK,EAAE,QAAQ,QAAQ,GAAG,EAAE,YAAY;AACtD;","names":[]}
@@ -11,4 +11,4 @@ export {
11
11
  DesignCanvasLazy,
12
12
  DesignCanvasChromeLazy
13
13
  };
14
- //# sourceMappingURL=chunk-NRG2YHGY.js.map
14
+ //# sourceMappingURL=chunk-IMTU5LCF.js.map
@@ -7,7 +7,7 @@ import {
7
7
  import {
8
8
  mentionInputToPart,
9
9
  toChatMessageParts
10
- } from "./chunk-JBEFTXDO.js";
10
+ } from "./chunk-2YLSWZ5W.js";
11
11
  import {
12
12
  ChatTurnInputError,
13
13
  TURN_PROGRESS_FIRST,
@@ -1186,4 +1186,4 @@ export {
1186
1186
  createChatTurnRoutes,
1187
1187
  streamChatRouteAsSandboxEvents
1188
1188
  };
1189
- //# sourceMappingURL=chunk-QE2NXMDZ.js.map
1189
+ //# sourceMappingURL=chunk-JWZ32ZGD.js.map
@@ -1,3 +1,7 @@
1
+ import {
2
+ normalizeProfileName,
3
+ parseProfileSwitch
4
+ } from "./chunk-I6BZVIRH.js";
1
5
  import {
2
6
  defineAppTool
3
7
  } from "./chunk-BMZTYGKE.js";
@@ -324,15 +328,6 @@ async function promoteRevision(input) {
324
328
  }
325
329
  return revision;
326
330
  }
327
- function parseProfileSwitch(text) {
328
- const trimmed = text.trim();
329
- if (!/^switch\s+to\b/i.test(trimmed)) return null;
330
- const match = /^switch[ \t]+to[ \t]+([^\r\n]+)$/i.exec(trimmed);
331
- return match?.[1]?.trim() ? { name: match[1].trim() } : { invalid: true };
332
- }
333
- function normalizeProfileName(name) {
334
- return name.trim().replace(/\s+/g, " ").toLowerCase();
335
- }
336
331
  function profileSwitchInputHashFromContentHash(contentHash, identityContext) {
337
332
  return identityContext === void 0 ? contentHash : sha256Utf8(JSON.stringify([identityContext, contentHash]));
338
333
  }
@@ -602,8 +597,6 @@ export {
602
597
  proposeRevision,
603
598
  createTextProfile,
604
599
  promoteRevision,
605
- parseProfileSwitch,
606
- normalizeProfileName,
607
600
  profileSwitchInputHashFromContentHash,
608
601
  profileSwitchInputHash,
609
602
  switchProfile,
@@ -613,4 +606,4 @@ export {
613
606
  profileTextChange,
614
607
  profileTools
615
608
  };
616
- //# sourceMappingURL=chunk-ABUF7A4T.js.map
609
+ //# sourceMappingURL=chunk-ORCY6XGW.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/agent-profiles/index.ts","../src/agent-profiles/self-management.ts"],"sourcesContent":["/** Chat-owned profile revisions and member/channel bindings. Execution stays in the substrate. */\nimport {\n canonicalAgentProfileDigest,\n diffAgentProfiles,\n snapshotAgentProfile,\n sha256Utf8,\n type AgentProfile,\n type AgentProfileDiff,\n} from '@tangle-network/agent-interface'\nimport { z } from 'zod'\nimport { normalizeProfileName, parseProfileSwitch } from './switch'\nexport { normalizeProfileName, parseProfileSwitch }\nimport type { McpToolDefinition } from '../tools'\n\nexport type ProfileAuthorKind = 'person' | 'agent' | 'optimizer'\nexport type ProfileRevisionState = 'active' | 'candidate' | 'pending-consent'\n\n/** The decision table used by every write path; products may narrow access, never widen it. */\nexport const PROFILE_CHANGE_POLICY = {\n textEdit: { admission: 'automatic', conversation: 'same', destructive: false },\n sameAuthoritySwitch: { admission: 'prepare-then-flip', conversation: 'same', destructive: false },\n differentAuthoritySwitch: { admission: 'prepare-then-flip', conversation: 'same', destructive: false },\n authorityEdit: { admission: 'editor-consent', conversation: 'same', destructive: false },\n optimizerRevision: { admission: 'eval-promotion', conversation: 'same', destructive: false },\n destructiveAction: { admission: 'reaper-only', conversation: 'none', destructive: true },\n} as const\n\nexport interface ProfileRevision {\n id: string\n workspaceId: string\n profileId: string\n parentId: string | null\n profile: AgentProfile\n knowledgeText: string\n author: { kind: ProfileAuthorKind; id: string }\n reason: string\n /** `null` means an older stored revision did not record the knowledge delta. */\n knowledgeTextChanged?: boolean | null\n diff: AgentProfileDiff[]\n authorityDigest: string\n /** ADC hash of the public profile plan, without per-turn product attachments. */\n planDigest: string\n state: ProfileRevisionState\n createdAt: number\n}\n\nexport interface ProfileBindingKey {\n workspaceId: string\n memberId: string\n /** `chat`, or a product-scoped phone line and sender key. */\n channel: string\n}\n\nexport interface ProfileBinding extends ProfileBindingKey {\n profileId: string\n pinnedRevisionId: string | null\n authorityDigest: string\n planDigest: string\n version: number\n}\n\nexport interface ProfileTurnPin {\n workspaceId: string\n memberId: string\n channel: string\n messageId: string\n inputHash: string\n profileId: string\n revisionId: string\n authorityDigest: string\n /** Effective ADC plan selected by the executor, including allowed turn attachments. */\n planDigest: string\n}\n\n/** Remove events name only adds they observed; a concurrent add survives. */\nexport interface ProfileKnowledgeEvent {\n id: string\n workspaceId: string\n profileId: string\n documentId: string\n kind: 'add' | 'remove'\n content: string | null\n observedAddIds: string[]\n createdAt: number\n}\n\nexport interface ProfileKnowledgeDocument {\n documentId: string\n content: string\n addEventId: string\n}\n\nexport interface ProfileSwitchReceipt {\n key: ProfileBindingKey\n messageId: string\n inputHash: string\n /** Visible conversation that should render this switch marker on reload. */\n conversationId?: string | null\n createdAt?: number\n profileId: string | null\n revisionId: string | null\n /** A rollback binds the previous immutable revision, not the current head. */\n pinnedRevisionId: string | null\n authorityDigest: string | null\n planDigest: string | null\n outcome: 'switched' | 'refused'\n message: string\n /** Workspace resource collisions retain the original and place the profile copy beside it. */\n conflicts: string[]\n}\n\nexport interface ProfileRevisionStore {\n getActiveRevision(workspaceId: string, profileId: string): Promise<ProfileRevision | null>\n getRevision(workspaceId: string, profileId: string, revisionId: string): Promise<ProfileRevision | null>\n /** Append the immutable row and optionally an activation event in one guarded transaction. */\n appendRevision(revision: ProfileRevision, expectedActiveId: string | null, activate: boolean): Promise<boolean>\n /** Promotion appends an activation event; the historical revision remains immutable. */\n promoteRevision(workspaceId: string, profileId: string, revisionId: string, expectedActiveId: string | null): Promise<boolean>\n getBinding(key: ProfileBindingKey): Promise<ProfileBinding | null>\n getSwitchReceipt(key: ProfileBindingKey, messageId: string, inputHash: string): Promise<ProfileSwitchReceipt | null>\n /** Receipt and binding event append atomically; a refusal leaves the binding untouched. */\n recordSwitch(receipt: ProfileSwitchReceipt, expectedVersion: number): Promise<ProfileSwitchReceipt>\n /** Persist one immutable pin under a message id; retries must return the same pin. */\n pinTurn(pin: ProfileTurnPin, expectedBindingVersion: number): Promise<ProfileTurnPin>\n getTurnPin(key: ProfileBindingKey, messageId: string, inputHash: string): Promise<ProfileTurnPin | null>\n listKnowledgeEvents(workspaceId: string, profileId: string): Promise<ProfileKnowledgeEvent[]>\n appendKnowledgeEvent(event: ProfileKnowledgeEvent): Promise<void>\n}\n\nexport class ProfileConflictError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'ProfileConflictError'\n }\n}\n\nexport class ProfileAccessError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'ProfileAccessError'\n }\n}\n\n/** Keep the existing diff column readable while adding the separate knowledge text axis. */\nexport function parseProfileRevisionDiff(value: string): {\n diff: AgentProfileDiff[]; knowledgeTextChanged: boolean | null\n} {\n const parsed: unknown = JSON.parse(value)\n if (Array.isArray(parsed)) return { diff: parsed as AgentProfileDiff[], knowledgeTextChanged: null }\n if (!parsed || typeof parsed !== 'object' || !('profile' in parsed) ||\n !Array.isArray(parsed.profile) || !('knowledgeTextChanged' in parsed) ||\n (parsed.knowledgeTextChanged !== null && typeof parsed.knowledgeTextChanged !== 'boolean')) {\n throw new TypeError('Stored profile revision diff is invalid')\n }\n return { diff: parsed.profile as AgentProfileDiff[],\n knowledgeTextChanged: parsed.knowledgeTextChanged }\n}\n\nexport function serializeProfileRevisionDiff(revision: Pick<ProfileRevision, 'diff' | 'knowledgeTextChanged'>): string {\n return JSON.stringify({ profile: revision.diff, knowledgeTextChanged: revision.knowledgeTextChanged ?? null })\n}\n\n/** Remove exactly the declared text axes. Unknown future fields remain authority. */\nexport function profileAuthority(profile: AgentProfile): AgentProfile {\n const { name: _name, description: _description, prompt, ...authority } = profile\n const { systemPrompt: _systemPrompt, instructions: _instructions, ...promptAuthority } = prompt ?? {}\n return { ...authority, ...(Object.keys(promptAuthority).length ? { prompt: promptAuthority } : {}) }\n}\n\nexport function profileAuthorityDigest(profile: AgentProfile): string {\n return canonicalAgentProfileDigest(profileAuthority(snapshotAgentProfile(profile)))\n}\n\nexport function projectKnowledgeDocuments(events: readonly ProfileKnowledgeEvent[]): ProfileKnowledgeDocument[] {\n const removed = new Set(events.filter(event => event.kind === 'remove').flatMap(event => event.observedAddIds))\n const visible = events.filter(event => event.kind === 'add' && !removed.has(event.id))\n const latest = new Map<string, ProfileKnowledgeEvent>()\n for (const event of visible) {\n const prior = latest.get(event.documentId)\n if (!prior || event.createdAt > prior.createdAt ||\n (event.createdAt === prior.createdAt && event.id > prior.id)) latest.set(event.documentId, event)\n }\n return [...latest.values()].sort((a, b) => a.documentId.localeCompare(b.documentId))\n .map(event => ({ documentId: event.documentId, content: event.content!, addEventId: event.id }))\n}\n\nexport async function addProfileKnowledgeDocument(input: {\n store: ProfileRevisionStore\n workspaceId: string\n profileId: string\n documentId: string\n content: string\n actorRole: 'owner' | 'manager' | 'member' | 'viewer'\n id?: string\n now?: number\n}): Promise<ProfileKnowledgeEvent> {\n if (input.actorRole !== 'owner' && input.actorRole !== 'manager') {\n throw new ProfileAccessError('Profile management is required')\n }\n if (!input.documentId || !input.content) throw new TypeError('A knowledge document needs an id and content')\n const event: ProfileKnowledgeEvent = { id: input.id ?? crypto.randomUUID(),\n workspaceId: input.workspaceId, profileId: input.profileId, documentId: input.documentId,\n kind: 'add', content: input.content, observedAddIds: [], createdAt: input.now ?? Date.now() }\n await input.store.appendKnowledgeEvent(event)\n return event\n}\n\nexport async function removeProfileKnowledgeDocument(input: {\n store: ProfileRevisionStore\n workspaceId: string\n profileId: string\n documentId: string\n actorRole: 'owner' | 'manager' | 'member' | 'viewer'\n id?: string\n now?: number\n}): Promise<ProfileKnowledgeEvent> {\n if (input.actorRole !== 'owner' && input.actorRole !== 'manager') {\n throw new ProfileAccessError('Profile management is required')\n }\n const events = await input.store.listKnowledgeEvents(input.workspaceId, input.profileId)\n const removed = new Set(events.filter(event => event.kind === 'remove').flatMap(event => event.observedAddIds))\n const observedAddIds = events.filter(event => event.kind === 'add' &&\n event.documentId === input.documentId && !removed.has(event.id)).map(event => event.id)\n const event: ProfileKnowledgeEvent = { id: input.id ?? crypto.randomUUID(),\n workspaceId: input.workspaceId, profileId: input.profileId, documentId: input.documentId,\n kind: 'remove', content: null, observedAddIds, createdAt: input.now ?? Date.now() }\n await input.store.appendKnowledgeEvent(event)\n return event\n}\n\n/** The per-turn text overlay is validated without admitting tools, model, MCP or resources. */\nexport function bindProfileText(consentedBaseline: AgentProfile, selected: AgentProfile): AgentProfile {\n if (profileAuthorityDigest(consentedBaseline) !== profileAuthorityDigest(selected)) {\n throw new ProfileAccessError('Profile authority differs; prepare its managed plan before the next turn')\n }\n // Profiles are digested as RFC 8785 JSON, which has no `undefined`: an\n // absent selected field removes the baseline's value instead of storing it.\n const result: AgentProfile = { ...consentedBaseline, name: selected.name }\n if (selected.description === undefined) delete result.description\n else result.description = selected.description\n const prompt: NonNullable<AgentProfile['prompt']> = { ...consentedBaseline.prompt }\n const { systemPrompt, instructions } = selected.prompt ?? {}\n if (systemPrompt === undefined) delete prompt.systemPrompt\n else prompt.systemPrompt = systemPrompt\n if (instructions === undefined) delete prompt.instructions\n else prompt.instructions = instructions\n if (Object.values(prompt).some(value => value !== undefined)) result.prompt = prompt\n else delete result.prompt\n return snapshotAgentProfile(result)\n}\n\nexport interface ProposeRevisionInput {\n store: ProfileRevisionStore\n workspaceId: string\n profileId: string\n expectedRevisionId: string | null\n profile: AgentProfile\n knowledgeText: string\n /** The exact ADC `hashWorkspacePlan` for this authored snapshot. */\n planDigest: string\n author: ProfileRevision['author']\n /** Trusted role from the authenticated session, never model arguments. */\n actorRole: 'owner' | 'manager' | 'member' | 'viewer'\n reason: string\n id?: string\n now?: number\n}\n\n/** All authors use one immutable write path. Optimizer and authority edits cannot self-activate. */\nexport async function proposeRevision(input: ProposeRevisionInput): Promise<ProfileRevision> {\n if (input.author.kind !== 'optimizer' && input.actorRole !== 'owner' && input.actorRole !== 'manager') {\n throw new ProfileAccessError('Only an owner or manager can change a profile')\n }\n if (!input.workspaceId || !input.profileId || !input.author.id || !input.reason.trim() ||\n !/^sha256:[a-f0-9]{64}$/.test(input.planDigest)) {\n throw new TypeError('A profile revision needs workspace, profile, author, reason and plan digest')\n }\n const previous = await input.store.getActiveRevision(input.workspaceId, input.profileId)\n if ((previous?.id ?? null) !== input.expectedRevisionId) {\n throw new ProfileConflictError('The profile changed; read its latest revision before saving')\n }\n const profile = snapshotAgentProfile(input.profile)\n const diff = previous ? diffAgentProfiles(previous.profile, profile) : []\n const authorityDigest = profileAuthorityDigest(profile)\n const authorityChanged = !!previous && previous.authorityDigest !== authorityDigest\n const admission = input.author.kind === 'optimizer'\n ? PROFILE_CHANGE_POLICY.optimizerRevision.admission\n : authorityChanged\n ? PROFILE_CHANGE_POLICY.authorityEdit.admission\n : PROFILE_CHANGE_POLICY.textEdit.admission\n const state: ProfileRevisionState = admission === 'eval-promotion' ? 'candidate'\n : admission === 'editor-consent' ? 'pending-consent' : 'active'\n const revision: ProfileRevision = {\n id: input.id ?? crypto.randomUUID(), workspaceId: input.workspaceId, profileId: input.profileId,\n parentId: previous?.id ?? null, profile, knowledgeText: input.knowledgeText,\n author: input.author, reason: input.reason.trim(), diff,\n knowledgeTextChanged: previous ? previous.knowledgeText !== input.knowledgeText : input.knowledgeText.length > 0,\n authorityDigest,\n planDigest: input.planDigest, state, createdAt: input.now ?? Date.now(),\n }\n if (!await input.store.appendRevision(revision, input.expectedRevisionId, state === 'active')) {\n throw new ProfileConflictError('The profile changed while saving')\n }\n return revision\n}\n\nexport interface CreateTextProfileInput {\n store: ProfileRevisionStore\n workspaceId: string\n /** An active profile whose authority the new profile inherits exactly. */\n baselineProfileId: string\n /** Include builtins and user profiles from the authenticated workspace catalog. */\n existingProfiles: readonly { name: string }[]\n name: string\n instructions: string\n authorId: string\n actorRole: 'owner' | 'manager' | 'member' | 'viewer'\n /** Product computes ADC's hashWorkspacePlan for the complete authored snapshot. */\n planDigest: (profile: AgentProfile) => string | Promise<string>\n now?: number\n}\n\n/** Create a distinct text persona without granting new model, tool, MCP or secret authority. */\nexport async function createTextProfile(input: CreateTextProfileInput): Promise<ProfileRevision> {\n if (input.actorRole !== 'owner' && input.actorRole !== 'manager') {\n throw new ProfileAccessError('Only an owner or manager can create a profile')\n }\n const name = input.name.trim().replace(/\\s+/g, ' ')\n const normalizedName = normalizeProfileName(name)\n if (!normalizedName) throw new TypeError('A profile needs a name')\n if (input.existingProfiles.some(profile => normalizeProfileName(profile.name) === normalizedName)) {\n throw new ProfileConflictError('A profile with that name already exists')\n }\n const baseline = await input.store.getActiveRevision(input.workspaceId, input.baselineProfileId)\n if (!baseline) throw new ProfileConflictError('The baseline profile is not active')\n // Equal names map to one id, so two concurrent creates cannot create an\n // ambiguous text command even when both read the catalog before either writes.\n const profileId = `custom-${sha256Utf8(`${input.workspaceId}\\0${normalizedName}`).slice(7, 39)}`\n const addedInstruction = input.instructions.trim()\n const profile = bindProfileText(baseline.profile, {\n ...baseline.profile, name,\n prompt: {\n ...baseline.profile.prompt,\n instructions: [...(baseline.profile.prompt?.instructions ?? []),\n ...(addedInstruction ? [addedInstruction] : [])],\n },\n })\n return proposeRevision({\n store: input.store, workspaceId: input.workspaceId, profileId,\n expectedRevisionId: null, profile, knowledgeText: '',\n planDigest: await input.planDigest(profile),\n author: { kind: 'person', id: input.authorId }, actorRole: input.actorRole,\n reason: 'Created a text profile from an approved baseline', now: input.now,\n })\n}\n\nexport async function promoteRevision(input: {\n store: ProfileRevisionStore\n workspaceId: string\n profileId: string\n revisionId: string\n actorRole: 'owner' | 'manager' | 'member' | 'viewer'\n /** Verified by the product's consent route; required when authority changes. */\n verifyConsent?: (revision: ProfileRevision) => Promise<boolean>\n}): Promise<ProfileRevision> {\n if (input.actorRole !== 'owner' && input.actorRole !== 'manager') {\n throw new ProfileAccessError('Only an owner or manager can promote a profile')\n }\n const [revision, head] = await Promise.all([\n input.store.getRevision(input.workspaceId, input.profileId, input.revisionId),\n input.store.getActiveRevision(input.workspaceId, input.profileId),\n ])\n if (!revision || revision.parentId !== (head?.id ?? null)) throw new ProfileConflictError('Profile parent changed')\n if (revision.authorityDigest !== head?.authorityDigest &&\n (input.actorRole !== 'owner' || !input.verifyConsent || !await input.verifyConsent(revision))) {\n throw new ProfileAccessError('Authority changes require owner consent')\n }\n if (!await input.store.promoteRevision(input.workspaceId, input.profileId, revision.id, head?.id ?? null)) {\n throw new ProfileConflictError('The profile changed while promoting')\n }\n return revision\n}\n\n/** A source identity joins the command hash without entering the receipt row. */\nexport function profileSwitchInputHashFromContentHash(contentHash: string,\n identityContext?: string): string {\n return identityContext === undefined ? contentHash\n : sha256Utf8(JSON.stringify([identityContext, contentHash]))\n}\n\nexport function profileSwitchInputHash(content: string, identityContext?: string): string {\n return profileSwitchInputHashFromContentHash(sha256Utf8(content), identityContext)\n}\n\nexport interface SwitchableProfile {\n id: string\n name: string\n status: 'active' | 'draft' | 'paused'\n}\n\nexport interface SwitchProfileInput {\n store: ProfileRevisionStore\n key: ProfileBindingKey\n messageId: string\n content: string\n /** Trusted source identity, such as a phone sender; replay must preserve it. */\n identityContext?: string\n conversationId?: string\n choice: { name: string } | { profileId: string }\n profiles: readonly SwitchableProfile[]\n /** Product's role/phone allowlist decision for the authenticated member. */\n canSelect: (profileId: string) => Promise<boolean>\n /** Stage a complete managed plan for the same conversation; never mutate live workspace files. */\n prepareAuthority: (revision: ProfileRevision, key: ProfileBindingKey) => Promise<{\n planDigest: string; healthy: true; conflicts: string[]\n }>\n /** Receives the reason preparation failed; the person sees only a generic refusal.\n * Defaults to one structured `console.error` line so the reason reaches the host's logs. */\n onPrepareFailure?: (error: unknown, profileId: string) => void\n}\n\n/** The picker and deterministic text command converge here. Models cannot call it. */\nfunction logPrepareFailure(error: unknown, profileId: string): void {\n console.error(JSON.stringify({ event: 'profile-switch-prepare-failed', profileId,\n error: error instanceof Error ? `${error.name}: ${error.message}` : String(error) }))\n}\n\nexport async function switchProfile(input: SwitchProfileInput): Promise<ProfileSwitchReceipt> {\n const inputHash = profileSwitchInputHash(input.content, input.identityContext)\n const previousReceipt = await input.store.getSwitchReceipt(input.key, input.messageId, inputHash)\n if (previousReceipt) return previousReceipt\n const binding = await input.store.getBinding(input.key)\n const choice = input.choice\n const matches = 'name' in choice\n ? input.profiles.filter(profile => normalizeProfileName(profile.name) === normalizeProfileName(choice.name))\n : input.profiles.filter(profile => profile.id === choice.profileId)\n const target = matches.length === 1 ? matches[0] : undefined\n let revision: ProfileRevision | null = null\n if (target?.status === 'active' && await input.canSelect(target.id)) {\n revision = await input.store.getActiveRevision(input.key.workspaceId, target.id)\n if (revision && 'name' in choice &&\n normalizeProfileName(revision.profile.name ?? '') !== normalizeProfileName(choice.name)) {\n revision = null\n }\n }\n let outcome: ProfileSwitchReceipt['outcome'] = 'refused'\n let message = matches.length > 1 ? 'That profile name is ambiguous.'\n : target?.status !== 'active' && target ? `${target.name} is not active.`\n : 'That profile is not available for this member.'\n let planDigest: string | null = null\n let conflicts: string[] = []\n if (revision && target) {\n try {\n const prepared = await input.prepareAuthority(revision, input.key)\n if (!prepared.healthy || prepared.planDigest !== revision.planDigest) {\n throw new ProfileConflictError('The managed plan was not prepared for this revision')\n }\n planDigest = prepared.planDigest\n conflicts = prepared.conflicts\n } catch (error) {\n revision = null\n message = `Could not prepare ${target.name}; your current agent is unchanged.`\n ;(input.onPrepareFailure ?? logPrepareFailure)(error, target.id)\n }\n if (revision && planDigest) {\n outcome = 'switched'\n message = `Now talking to ${target.name}`\n }\n }\n return input.store.recordSwitch({ key: input.key, messageId: input.messageId, inputHash,\n conversationId: input.conversationId,\n profileId: revision?.profileId ?? null, revisionId: revision?.id ?? null,\n pinnedRevisionId: null, authorityDigest: revision?.authorityDigest ?? null,\n planDigest, outcome, message, conflicts }, binding?.version ?? 0)\n}\n\n/** Call before dispatching a chat message; a recognized command is never sent to the model. */\nexport async function handleProfileSwitchText(\n input: Omit<SwitchProfileInput, 'choice'>,\n): Promise<ProfileSwitchReceipt | null> {\n const parsed = parseProfileSwitch(input.content)\n if (!parsed) return null\n if ('name' in parsed) return switchProfile({ ...input, choice: parsed })\n const inputHash = profileSwitchInputHash(input.content, input.identityContext)\n const previous = await input.store.getSwitchReceipt(input.key, input.messageId, inputHash)\n if (previous) return previous\n const binding = await input.store.getBinding(input.key)\n return input.store.recordSwitch({ key: input.key, messageId: input.messageId, inputHash,\n conversationId: input.conversationId,\n profileId: null, revisionId: null, pinnedRevisionId: null, outcome: 'refused',\n authorityDigest: null, planDigest: null, conflicts: [],\n message: 'Send only “Switch to [agent name]” to change agents.' },\n binding?.version ?? 0)\n}\n\n/** One-step rollback moves this member/channel to its previous immutable revision. */\nexport async function rollbackProfileBinding(input: {\n store: ProfileRevisionStore\n key: ProfileBindingKey\n messageId: string\n conversationId?: string\n actorRole: 'owner' | 'manager' | 'member' | 'viewer'\n canSelect: (profileId: string) => Promise<boolean>\n prepareAuthority: SwitchProfileInput['prepareAuthority']\n}): Promise<ProfileSwitchReceipt> {\n if (input.actorRole !== 'owner' && input.actorRole !== 'manager') {\n throw new ProfileAccessError('Only an owner or manager can roll back a profile')\n }\n const inputHash = sha256Utf8(`rollback:${input.messageId}`)\n const prior = await input.store.getSwitchReceipt(input.key, input.messageId, inputHash)\n if (prior) return prior\n const binding = await input.store.getBinding(input.key)\n if (!binding || !await input.canSelect(binding.profileId)) throw new ProfileAccessError('Profile is unavailable')\n const current = binding.pinnedRevisionId\n ? await input.store.getRevision(input.key.workspaceId, binding.profileId, binding.pinnedRevisionId)\n : await input.store.getActiveRevision(input.key.workspaceId, binding.profileId)\n if (!current?.parentId) throw new ProfileConflictError('The bound profile has no previous revision')\n const parent = await input.store.getRevision(input.key.workspaceId, binding.profileId, current.parentId)\n if (!parent) throw new ProfileConflictError('The previous revision is unavailable')\n let planDigest = binding.planDigest\n let conflicts: string[] = []\n if (binding.authorityDigest !== parent.authorityDigest || binding.planDigest !== parent.planDigest) {\n try {\n const prepared = await input.prepareAuthority(parent, input.key)\n if (!prepared.healthy || prepared.planDigest !== parent.planDigest) {\n throw new ProfileConflictError('The prior managed plan was not prepared')\n }\n planDigest = prepared.planDigest\n conflicts = prepared.conflicts\n } catch {\n return input.store.recordSwitch({ key: input.key, messageId: input.messageId, inputHash,\n conversationId: input.conversationId,\n profileId: null, revisionId: null, pinnedRevisionId: null, outcome: 'refused',\n authorityDigest: null, planDigest: null, conflicts: [],\n message: 'Could not prepare the previous profile; your current agent is unchanged.' },\n binding.version)\n }\n }\n return input.store.recordSwitch({ key: input.key, messageId: input.messageId, inputHash,\n conversationId: input.conversationId,\n profileId: parent.profileId, revisionId: parent.id, pinnedRevisionId: parent.id,\n authorityDigest: parent.authorityDigest, planDigest, outcome: 'switched', conflicts,\n message: `Now talking to ${parent.profile.name ?? 'this profile'}` }, binding.version)\n}\n\nexport async function admitProfileTurn(input: {\n store: ProfileRevisionStore\n key: ProfileBindingKey\n messageId: string\n content: string\n /** Effective ADC plan digest selected by the executor for this revision and turn. */\n observedManagedPlanDigest: string\n /** Required if trusted per-turn attachments change the public profile plan. */\n verifyEffectivePlan?: (revision: ProfileRevision, effectivePlanDigest: string,\n key: ProfileBindingKey) => Promise<boolean>\n}): Promise<ProfileTurnPin> {\n const inputHash = sha256Utf8(input.content)\n const prior = await input.store.getTurnPin(input.key, input.messageId, inputHash)\n if (prior) return prior\n const binding = await input.store.getBinding(input.key)\n if (!binding) throw new ProfileAccessError('Choose a profile before sending a message')\n const revision = binding.pinnedRevisionId\n ? await input.store.getRevision(input.key.workspaceId, binding.profileId, binding.pinnedRevisionId)\n : await input.store.getActiveRevision(input.key.workspaceId, binding.profileId)\n if (!revision) throw new ProfileConflictError('The bound profile revision is unavailable')\n if (revision.authorityDigest !== binding.authorityDigest ||\n !/^sha256:[a-f0-9]{64}$/.test(input.observedManagedPlanDigest)) {\n throw new ProfileAccessError('The selected managed plan is not active for this turn')\n }\n const planMatches = revision.planDigest === input.observedManagedPlanDigest ||\n (input.verifyEffectivePlan !== undefined &&\n await input.verifyEffectivePlan(revision, input.observedManagedPlanDigest, input.key))\n if (!planMatches) {\n throw new ProfileAccessError('The selected managed plan is not active for this turn')\n }\n return input.store.pinTurn({ ...input.key, messageId: input.messageId, inputHash,\n profileId: revision.profileId, revisionId: revision.id,\n authorityDigest: revision.authorityDigest, planDigest: input.observedManagedPlanDigest }, binding.version)\n}\n\nconst textChangeSchema = z.object({\n name: z.string().trim().min(1).max(160).optional(),\n description: z.string().max(2000).nullable().optional(),\n systemPrompt: z.string().max(32000).nullable().optional(),\n instructions: z.array(z.string().max(32000)).max(40).optional(),\n knowledgeText: z.string().max(32000).optional(),\n}).strict().refine(changes => Object.keys(changes).length > 0)\nconst updateToolSchema = z.object({ expectedRevisionId: z.string().min(1), changes: textChangeSchema }).strict()\n\nexport function profileTextChange(revision: ProfileRevision, changes: z.infer<typeof textChangeSchema>): {\n profile: AgentProfile; knowledgeText: string\n} {\n const profile = structuredClone(revision.profile)\n if (changes.name !== undefined) profile.name = changes.name\n if (changes.description !== undefined) profile.description = changes.description ?? undefined\n if (changes.systemPrompt !== undefined || changes.instructions !== undefined) {\n profile.prompt = { ...profile.prompt,\n ...(changes.systemPrompt !== undefined ? { systemPrompt: changes.systemPrompt ?? undefined } : {}),\n ...(changes.instructions !== undefined ? { instructions: changes.instructions } : {}) }\n }\n return { profile: snapshotAgentProfile(profile), knowledgeText: changes.knowledgeText ?? revision.knowledgeText }\n}\n\nexport interface ProfileToolTurn {\n workspaceId: string; profileId: string; revisionId: string\n memberId: string; role: 'owner' | 'manager' | 'member' | 'viewer'\n}\n\nexport interface ProfileToolContext<TTurn extends ProfileToolTurn = ProfileToolTurn> {\n /** Resolve the running turn from the trusted server session; never from tool arguments. */\n activeTurn(): Promise<TTurn>\n /** Product computes the plan with ADC, returning `hashWorkspacePlan(plan)`. */\n planDigest(profile: AgentProfile, knowledgeText: string): Promise<string>\n store: ProfileRevisionStore\n /** Return a store whose revision append atomically rechecks product turn authority. */\n storeForTurn?(turn: TTurn): ProfileRevisionStore\n}\n\n/** Shared self-edit tools; only the authenticated active turn can name the profile. */\nexport function profileTools<TTurn extends ProfileToolTurn>(\n context: ProfileToolContext<TTurn>): McpToolDefinition<Record<string, never>>[] {\n return [{\n name: 'profile.read',\n description: 'Read the active agent profile text and revision. Saved text applies on the next message.',\n inputSchema: z.toJSONSchema(z.object({}).strict(), { io: 'input' }) as Record<string, unknown>,\n async run(args) {\n z.object({}).strict().parse(args)\n const turn = await context.activeTurn()\n if (turn.role !== 'owner' && turn.role !== 'manager') throw new ProfileAccessError('Profile management is required')\n const revision = await context.store.getActiveRevision(turn.workspaceId, turn.profileId)\n if (!revision) throw new ProfileConflictError('Profile revision is unavailable')\n return { profileId: turn.profileId, revisionId: revision.id, currentTurnRevisionId: turn.revisionId,\n name: revision.profile.name, description: revision.profile.description ?? null,\n systemPrompt: revision.profile.prompt?.systemPrompt ?? null,\n instructions: revision.profile.prompt?.instructions ?? [], knowledgeText: revision.knowledgeText }\n },\n }, {\n name: 'profile.update',\n description: 'Save a requested owner or manager text change with the revision from profile.read. Applies on the next message.',\n inputSchema: z.toJSONSchema(updateToolSchema, { io: 'input' }) as Record<string, unknown>,\n async run(args) {\n const { expectedRevisionId, changes } = updateToolSchema.parse(args)\n const turn = await context.activeTurn()\n if (turn.role !== 'owner' && turn.role !== 'manager') throw new ProfileAccessError('Profile management is required')\n const current = await context.store.getActiveRevision(turn.workspaceId, turn.profileId)\n if (!current || current.id !== expectedRevisionId) throw new ProfileConflictError('The profile changed; read it again')\n const next = profileTextChange(current, changes)\n const revision = await proposeRevision({ store: context.storeForTurn?.(turn) ?? context.store,\n workspaceId: turn.workspaceId,\n profileId: turn.profileId, expectedRevisionId, ...next,\n planDigest: await context.planDigest(next.profile, next.knowledgeText),\n author: { kind: 'agent', id: turn.memberId }, actorRole: turn.role,\n reason: 'Owner or manager requested a text change during chat' })\n return { profileId: turn.profileId, revisionId: revision.id, state: revision.state,\n canonicalSaved: revision.state === 'active', appliesTo: 'next_message', currentTurn: 'unchanged' }\n },\n }]\n}\n\nexport * from './self-management'\n","/**\n * Live profile self-mounting — the safe, immediate subset of agent\n * self-improvement.\n *\n * The revision system ({@link ProfileRevision}, `PROFILE_CHANGE_POLICY`) owns\n * durable profile evolution: authority edits need editor consent, optimizer\n * revisions promote through eval. Self-mounting is the complementary\n * LIVE dimension — the sandboxed agent adjusts its own mounted context\n * (skills today) within a permitted, idempotent, catalog-validated delta.\n * Nothing here touches authority: model, permissions, tools denials and\n * billing identity are not agent-changeable dimensions, and every refusal\n * names the permitted set.\n *\n * One audited verb, not a family: `mount_profile_change` applies a validated\n * delta against a permitted-dimensions allowlist; re-applying the same delta\n * is a no-op; the baseline skill cannot be removed; the mount count is capped\n * because context is a budget.\n *\n * Products wire their own catalog and persistence:\n *\n * ```ts\n * import { createMountProfileChangeTool, createInMemorySelfMountStorage } from '@tangle-network/agent-app/agent-profiles'\n *\n * const mountProfileChange = createMountProfileChangeTool({\n * skills: mySkillRegistry, // { id, description }[]\n * storage: createD1SelfMountStorage(env.DB), // or any { get, set }\n * scopeKey: (ctx) => ctx.threadId ?? ctx.userId, // product's persistence scope\n * baseline: 'cad',\n * })\n * ```\n */\nimport { defineAppTool, type AppToolDefinition } from '../tools/registry'\nimport { ToolInputError } from '../tools/errors'\nimport type { AppToolContext } from '../tools/types'\n\n/** The only profile dimensions an agent may change on its own mounted state.\n * Anything else in a delta is refused with this list — the boundary is the\n * schema, not the verb count. */\nexport const PERMITTED_SELF_MOUNT_DIMENSIONS = ['skills'] as const\n\nexport interface SelfMountSkillEntry {\n /** Registry-unique skill id. */\n id: string\n /** One-line description, surfaced in the tool's catalog. */\n description: string\n}\n\n/** Durable mounted-skill state, keyed by the product's scope. */\nexport interface SelfMountStorage {\n get(scope: string): Promise<readonly string[]>\n set(scope: string, ids: readonly string[]): Promise<void>\n}\n\n/** Non-durable default for tests and single-instance products. */\nexport function createInMemorySelfMountStorage(): SelfMountStorage {\n const state = new Map<string, string[]>()\n return {\n async get(scope) {\n return state.get(scope) ?? []\n },\n async set(scope, ids) {\n state.set(scope, [...new Set(ids)].sort())\n },\n }\n}\n\nexport interface MountProfileChangeDeps {\n /** The product's skill catalog — the only mountable ids. */\n skills: readonly SelfMountSkillEntry[]\n /** Where mounted ids persist, keyed by the product's scope. */\n storage: SelfMountStorage\n /** The persistence scope for a call (project id, thread id, …). */\n scopeKey: (ctx: AppToolContext) => string\n /** Always-mounted skill id that cannot be removed. Default: none. */\n baseline?: string\n /** Upper bound on total mounted skills. Default 12; context is a budget. */\n maxMounted?: number\n /** Tool name override when a product needs a distinct verb. */\n name?: string\n}\n\ninterface SkillsDelta {\n add?: string[]\n remove?: string[]\n}\n\nexport interface MountProfileChangeResult {\n ok: true\n mounted: string[]\n removed: string[]\n effective: string[]\n note: string\n}\n\nfunction catalogLine(skills: readonly SelfMountSkillEntry[]): string {\n return skills.map((s) => `${s.id} (${s.description})`).join('; ')\n}\n\n/**\n * The permitted, idempotent self-mount verb as an app tool. Register it with\n * the product's tool set; the sandboxed agent calls it through the per-turn\n * MCP surface like any other app tool.\n */\nexport function createMountProfileChangeTool(deps: MountProfileChangeDeps): AppToolDefinition<Record<string, unknown>> {\n const { skills, storage, scopeKey } = deps\n const baseline = deps.baseline?.trim() || undefined\n const maxMounted = deps.maxMounted ?? 12\n const known = new Set(skills.map((s) => s.id))\n if (known.size !== skills.length) throw new Error('createMountProfileChangeTool: duplicate skill ids in the catalog')\n if (baseline && !known.has(baseline)) throw new Error(`createMountProfileChangeTool: baseline \"${baseline}\" is not in the catalog`)\n\n return defineAppTool({\n name: deps.name ?? 'mount_profile_change',\n description:\n `Apply a permitted, idempotent change to the mounted skills on this profile. ` +\n `Permitted dimension: skills ({ add: [ids], remove: [ids] }) — anything else is refused. ` +\n `Re-applying the same change is a no-op. Takes effect the next time the profile renders. ` +\n `Catalog: ${catalogLine(skills)}.`,\n parameters: {\n type: 'object',\n properties: {\n changes: {\n type: 'object',\n description: `The profile delta. Permitted dimensions: ${PERMITTED_SELF_MOUNT_DIMENSIONS.join(', ')}.`,\n properties: {\n skills: {\n type: 'object',\n description: 'Skill mounts: catalog ids to add or remove.',\n properties: {\n add: { type: 'array', items: { type: 'string' }, description: 'Catalog skill ids to mount.' },\n remove: { type: 'array', items: { type: 'string' }, description: 'Mounted skill ids to unmount.' },\n },\n additionalProperties: false,\n },\n },\n additionalProperties: false,\n },\n },\n required: ['changes'],\n additionalProperties: false,\n },\n async execute(args: unknown, ctx: AppToolContext): Promise<MountProfileChangeResult | { ok: false; error: string }> {\n const changes = (args as { changes?: Record<string, unknown> }).changes ?? {}\n const unknownDimensions = Object.keys(changes).filter(\n (d) => !(PERMITTED_SELF_MOUNT_DIMENSIONS as readonly string[]).includes(d),\n )\n if (unknownDimensions.length > 0) {\n throw new ToolInputError(\n 'mount_profile_change',\n `dimensions [${unknownDimensions.join(', ')}] are not agent-changeable. Permitted dimensions: ${PERMITTED_SELF_MOUNT_DIMENSIONS.join(', ')}.`,\n )\n }\n const delta = (changes.skills ?? {}) as SkillsDelta\n const add = [...new Set((delta.add ?? []).map((s) => s.trim()).filter(Boolean))]\n const remove = [...new Set((delta.remove ?? []).map((s) => s.trim()).filter(Boolean))]\n if (add.length === 0 && remove.length === 0) {\n throw new ToolInputError('mount_profile_change', 'empty delta: provide skills.add and/or skills.remove')\n }\n const invalid = [...add, ...remove].filter((id) => !known.has(id))\n if (invalid.length > 0) {\n throw new ToolInputError(\n 'mount_profile_change',\n `unknown skill ids: ${invalid.join(', ')}. Catalog: ${[...known].sort().join(', ')}.`)\n }\n if (baseline && remove.includes(baseline)) {\n throw new ToolInputError(\n 'mount_profile_change',\n `refused: \"${baseline}\" is the always-on baseline and cannot be removed`)\n }\n\n const scope = scopeKey(ctx)\n const stored = await storage.get(scope)\n const before = [...new Set([...stored, ...(baseline ? [baseline] : [])])].sort()\n const mounted = new Set(before)\n for (const id of add) mounted.add(id)\n for (const id of remove) mounted.delete(id)\n if (baseline) mounted.add(baseline)\n const effective = [...mounted].sort()\n if (effective.length > maxMounted) {\n throw new ToolInputError(\n 'mount_profile_change',\n `refused: ${effective.length} skills exceeds the ${maxMounted}-skill mount limit`)\n }\n if (JSON.stringify(before) === JSON.stringify(effective)) {\n return { ok: true, mounted: [], removed: [], effective, note: 'no change (already in that state) — idempotent no-op' }\n }\n await storage.set(scope, effective)\n return {\n ok: true,\n mounted: effective.filter((id) => !before.includes(id)),\n removed: before.filter((id) => !effective.includes(id)),\n effective,\n note: 'applied — takes effect the next time the profile renders',\n }\n },\n })\n}\n"],"mappings":";;;;;;;;;;;;AACA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AACP,SAAS,SAAS;;;AC6BX,IAAM,kCAAkC,CAAC,QAAQ;AAgBjD,SAAS,iCAAmD;AACjE,QAAM,QAAQ,oBAAI,IAAsB;AACxC,SAAO;AAAA,IACL,MAAM,IAAI,OAAO;AACf,aAAO,MAAM,IAAI,KAAK,KAAK,CAAC;AAAA,IAC9B;AAAA,IACA,MAAM,IAAI,OAAO,KAAK;AACpB,YAAM,IAAI,OAAO,CAAC,GAAG,IAAI,IAAI,GAAG,CAAC,EAAE,KAAK,CAAC;AAAA,IAC3C;AAAA,EACF;AACF;AA8BA,SAAS,YAAY,QAAgD;AACnE,SAAO,OAAO,IAAI,CAAC,MAAM,GAAG,EAAE,EAAE,KAAK,EAAE,WAAW,GAAG,EAAE,KAAK,IAAI;AAClE;AAOO,SAAS,6BAA6B,MAA0E;AACrH,QAAM,EAAE,QAAQ,SAAS,SAAS,IAAI;AACtC,QAAM,WAAW,KAAK,UAAU,KAAK,KAAK;AAC1C,QAAM,aAAa,KAAK,cAAc;AACtC,QAAM,QAAQ,IAAI,IAAI,OAAO,IAAI,CAAC,MAAM,EAAE,EAAE,CAAC;AAC7C,MAAI,MAAM,SAAS,OAAO,OAAQ,OAAM,IAAI,MAAM,kEAAkE;AACpH,MAAI,YAAY,CAAC,MAAM,IAAI,QAAQ,EAAG,OAAM,IAAI,MAAM,2CAA2C,QAAQ,yBAAyB;AAElI,SAAO,cAAc;AAAA,IACnB,MAAM,KAAK,QAAQ;AAAA,IACnB,aACE,6QAGY,YAAY,MAAM,CAAC;AAAA,IACjC,YAAY;AAAA,MACV,MAAM;AAAA,MACN,YAAY;AAAA,QACV,SAAS;AAAA,UACP,MAAM;AAAA,UACN,aAAa,4CAA4C,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