@tangle-network/agent-app 0.58.14 → 0.58.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent-profiles/d1.js +4 -1
- package/dist/agent-profiles/d1.js.map +1 -1
- package/dist/agent-profiles/index.d.ts +1 -1
- package/dist/agent-profiles/index.js +10 -1
- package/dist/agent-profiles/self-management.d.ts +77 -0
- package/dist/assistant/index.js +7 -7
- package/dist/chat-react/index.js +3 -3
- package/dist/chat-routes/index.js +3 -3
- package/dist/{chunk-W5VBZTNN.js → chunk-4ZMZDE24.js} +9 -9
- package/dist/{chunk-FZCXV4NH.js → chunk-57TTYY6T.js} +2 -2
- package/dist/{chunk-52PYOFI6.js → chunk-EXBAVMMK.js} +5 -5
- package/dist/{chunk-52PYOFI6.js.map → chunk-EXBAVMMK.js.map} +1 -1
- package/dist/{chunk-LLHHZHQC.js → chunk-GIBNG64C.js} +2 -2
- package/dist/{chunk-YEBSFADG.js → chunk-IBTM5SAZ.js} +121 -1
- package/dist/chunk-IBTM5SAZ.js.map +1 -0
- package/dist/{chunk-Y2TP52AB.js → chunk-MLG7YSTS.js} +3 -3
- package/dist/{chunk-KU3XTB7O.js → chunk-POE5UUUT.js} +3 -3
- package/dist/{chunk-SPLPFIWT.js → chunk-T5U7LDQW.js} +3 -3
- package/dist/chunk-T5U7LDQW.js.map +1 -0
- package/dist/{chunk-WN24GJ7A.js → chunk-TUNRLEDH.js} +2 -2
- package/dist/{mention-editor-BPDSMGJI.js → mention-editor-W2GG2NZ7.js} +2 -2
- package/dist/sandbox/index.js +3 -3
- package/dist/studio-react/index.js +3 -3
- package/dist/tools/index.js +3 -3
- package/dist/web-react/controls.d.ts +2 -3
- package/dist/web-react/index.js +7 -7
- package/dist/workspace-react/index.js +4 -4
- package/package.json +1 -1
- package/dist/chunk-SPLPFIWT.js.map +0 -1
- package/dist/chunk-YEBSFADG.js.map +0 -1
- /package/dist/{chunk-W5VBZTNN.js.map → chunk-4ZMZDE24.js.map} +0 -0
- /package/dist/{chunk-FZCXV4NH.js.map → chunk-57TTYY6T.js.map} +0 -0
- /package/dist/{chunk-LLHHZHQC.js.map → chunk-GIBNG64C.js.map} +0 -0
- /package/dist/{chunk-Y2TP52AB.js.map → chunk-MLG7YSTS.js.map} +0 -0
- /package/dist/{chunk-KU3XTB7O.js.map → chunk-POE5UUUT.js.map} +0 -0
- /package/dist/{chunk-WN24GJ7A.js.map → chunk-TUNRLEDH.js.map} +0 -0
- /package/dist/{mention-editor-BPDSMGJI.js.map → mention-editor-W2GG2NZ7.js.map} +0 -0
|
@@ -2,7 +2,10 @@ import {
|
|
|
2
2
|
ProfileConflictError,
|
|
3
3
|
parseProfileRevisionDiff,
|
|
4
4
|
serializeProfileRevisionDiff
|
|
5
|
-
} from "../chunk-
|
|
5
|
+
} from "../chunk-IBTM5SAZ.js";
|
|
6
|
+
import "../chunk-4CBU7QIL.js";
|
|
7
|
+
import "../chunk-UGWQLQDS.js";
|
|
8
|
+
import "../chunk-NZNXHCVU.js";
|
|
6
9
|
|
|
7
10
|
// src/agent-profiles/d1.ts
|
|
8
11
|
import { snapshotAgentProfile } from "@tangle-network/agent-interface";
|
|
@@ -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,aAA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AAI;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
|
+
{"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":";;;;;;;;;;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;AAAA,MACF;AACA,YAAM,QAAQ,MAAM,iBAAiB,KAAK,QAAQ,WAAW,QAAQ,SAAS;AAC9E,UAAI,CAAC,MAAO,OAAM,IAAI,qBAAqB,uCAAuC;AAClF,aAAO;AAAA,IACT;AAAA,IACA,MAAM,QAAQ,KAAK,wBAAwB;AACzC,YAAM,MAAM;AACZ,YAAM,QAAQ,MAAM,WAAW,KAAK,IAAI,WAAW,IAAI,SAAS;AAChE,UAAI,MAAO,QAAO;AAClB,YAAM,WAAW,MAAM,GAAG,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":[]}
|
|
@@ -307,4 +307,4 @@ export interface ProfileToolContext<TTurn extends ProfileToolTurn = ProfileToolT
|
|
|
307
307
|
}
|
|
308
308
|
/** Shared self-edit tools; only the authenticated active turn can name the profile. */
|
|
309
309
|
export declare function profileTools<TTurn extends ProfileToolTurn>(context: ProfileToolContext<TTurn>): McpToolDefinition<Record<string, never>>[];
|
|
310
|
-
export
|
|
310
|
+
export * from './self-management';
|
|
@@ -1,10 +1,13 @@
|
|
|
1
1
|
import {
|
|
2
|
+
PERMITTED_SELF_MOUNT_DIMENSIONS,
|
|
2
3
|
PROFILE_CHANGE_POLICY,
|
|
3
4
|
ProfileAccessError,
|
|
4
5
|
ProfileConflictError,
|
|
5
6
|
addProfileKnowledgeDocument,
|
|
6
7
|
admitProfileTurn,
|
|
7
8
|
bindProfileText,
|
|
9
|
+
createInMemorySelfMountStorage,
|
|
10
|
+
createMountProfileChangeTool,
|
|
8
11
|
createTextProfile,
|
|
9
12
|
handleProfileSwitchText,
|
|
10
13
|
normalizeProfileName,
|
|
@@ -23,14 +26,20 @@ import {
|
|
|
23
26
|
rollbackProfileBinding,
|
|
24
27
|
serializeProfileRevisionDiff,
|
|
25
28
|
switchProfile
|
|
26
|
-
} from "../chunk-
|
|
29
|
+
} from "../chunk-IBTM5SAZ.js";
|
|
30
|
+
import "../chunk-4CBU7QIL.js";
|
|
31
|
+
import "../chunk-UGWQLQDS.js";
|
|
32
|
+
import "../chunk-NZNXHCVU.js";
|
|
27
33
|
export {
|
|
34
|
+
PERMITTED_SELF_MOUNT_DIMENSIONS,
|
|
28
35
|
PROFILE_CHANGE_POLICY,
|
|
29
36
|
ProfileAccessError,
|
|
30
37
|
ProfileConflictError,
|
|
31
38
|
addProfileKnowledgeDocument,
|
|
32
39
|
admitProfileTurn,
|
|
33
40
|
bindProfileText,
|
|
41
|
+
createInMemorySelfMountStorage,
|
|
42
|
+
createMountProfileChangeTool,
|
|
34
43
|
createTextProfile,
|
|
35
44
|
handleProfileSwitchText,
|
|
36
45
|
normalizeProfileName,
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Live profile self-mounting — the safe, immediate subset of agent
|
|
3
|
+
* self-improvement.
|
|
4
|
+
*
|
|
5
|
+
* The revision system ({@link ProfileRevision}, `PROFILE_CHANGE_POLICY`) owns
|
|
6
|
+
* durable profile evolution: authority edits need editor consent, optimizer
|
|
7
|
+
* revisions promote through eval. Self-mounting is the complementary
|
|
8
|
+
* LIVE dimension — the sandboxed agent adjusts its own mounted context
|
|
9
|
+
* (skills today) within a permitted, idempotent, catalog-validated delta.
|
|
10
|
+
* Nothing here touches authority: model, permissions, tools denials and
|
|
11
|
+
* billing identity are not agent-changeable dimensions, and every refusal
|
|
12
|
+
* names the permitted set.
|
|
13
|
+
*
|
|
14
|
+
* One audited verb, not a family: `mount_profile_change` applies a validated
|
|
15
|
+
* delta against a permitted-dimensions allowlist; re-applying the same delta
|
|
16
|
+
* is a no-op; the baseline skill cannot be removed; the mount count is capped
|
|
17
|
+
* because context is a budget.
|
|
18
|
+
*
|
|
19
|
+
* Products wire their own catalog and persistence:
|
|
20
|
+
*
|
|
21
|
+
* ```ts
|
|
22
|
+
* import { createMountProfileChangeTool, createInMemorySelfMountStorage } from '@tangle-network/agent-app/agent-profiles'
|
|
23
|
+
*
|
|
24
|
+
* const mountProfileChange = createMountProfileChangeTool({
|
|
25
|
+
* skills: mySkillRegistry, // { id, description }[]
|
|
26
|
+
* storage: createD1SelfMountStorage(env.DB), // or any { get, set }
|
|
27
|
+
* scopeKey: (ctx) => ctx.threadId ?? ctx.userId, // product's persistence scope
|
|
28
|
+
* baseline: 'cad',
|
|
29
|
+
* })
|
|
30
|
+
* ```
|
|
31
|
+
*/
|
|
32
|
+
import { type AppToolDefinition } from '../tools/registry';
|
|
33
|
+
import type { AppToolContext } from '../tools/types';
|
|
34
|
+
/** The only profile dimensions an agent may change on its own mounted state.
|
|
35
|
+
* Anything else in a delta is refused with this list — the boundary is the
|
|
36
|
+
* schema, not the verb count. */
|
|
37
|
+
export declare const PERMITTED_SELF_MOUNT_DIMENSIONS: readonly ['skills'];
|
|
38
|
+
export interface SelfMountSkillEntry {
|
|
39
|
+
/** Registry-unique skill id. */
|
|
40
|
+
id: string;
|
|
41
|
+
/** One-line description, surfaced in the tool's catalog. */
|
|
42
|
+
description: string;
|
|
43
|
+
}
|
|
44
|
+
/** Durable mounted-skill state, keyed by the product's scope. */
|
|
45
|
+
export interface SelfMountStorage {
|
|
46
|
+
get(scope: string): Promise<readonly string[]>;
|
|
47
|
+
set(scope: string, ids: readonly string[]): Promise<void>;
|
|
48
|
+
}
|
|
49
|
+
/** Non-durable default for tests and single-instance products. */
|
|
50
|
+
export declare function createInMemorySelfMountStorage(): SelfMountStorage;
|
|
51
|
+
export interface MountProfileChangeDeps {
|
|
52
|
+
/** The product's skill catalog — the only mountable ids. */
|
|
53
|
+
skills: readonly SelfMountSkillEntry[];
|
|
54
|
+
/** Where mounted ids persist, keyed by the product's scope. */
|
|
55
|
+
storage: SelfMountStorage;
|
|
56
|
+
/** The persistence scope for a call (project id, thread id, …). */
|
|
57
|
+
scopeKey: (ctx: AppToolContext) => string;
|
|
58
|
+
/** Always-mounted skill id that cannot be removed. Default: none. */
|
|
59
|
+
baseline?: string;
|
|
60
|
+
/** Upper bound on total mounted skills. Default 12; context is a budget. */
|
|
61
|
+
maxMounted?: number;
|
|
62
|
+
/** Tool name override when a product needs a distinct verb. */
|
|
63
|
+
name?: string;
|
|
64
|
+
}
|
|
65
|
+
export interface MountProfileChangeResult {
|
|
66
|
+
ok: true;
|
|
67
|
+
mounted: string[];
|
|
68
|
+
removed: string[];
|
|
69
|
+
effective: string[];
|
|
70
|
+
note: string;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* The permitted, idempotent self-mount verb as an app tool. Register it with
|
|
74
|
+
* the product's tool set; the sandboxed agent calls it through the per-turn
|
|
75
|
+
* MCP surface like any other app tool.
|
|
76
|
+
*/
|
|
77
|
+
export declare function createMountProfileChangeTool(deps: MountProfileChangeDeps): AppToolDefinition<Record<string, unknown>>;
|
package/dist/assistant/index.js
CHANGED
|
@@ -1,20 +1,20 @@
|
|
|
1
1
|
import {
|
|
2
2
|
chatToolCallPart
|
|
3
|
-
} from "../chunk-
|
|
4
|
-
import "../chunk-
|
|
3
|
+
} from "../chunk-GIBNG64C.js";
|
|
4
|
+
import "../chunk-POE5UUUT.js";
|
|
5
5
|
import "../chunk-3HUFJ5LO.js";
|
|
6
6
|
import "../chunk-FBVLEGEG.js";
|
|
7
7
|
import "../chunk-Y6PRDUFJ.js";
|
|
8
8
|
import {
|
|
9
9
|
ChatComposer
|
|
10
|
-
} from "../chunk-
|
|
10
|
+
} from "../chunk-EXBAVMMK.js";
|
|
11
11
|
import "../chunk-L7MB2LLM.js";
|
|
12
|
-
import "../chunk-
|
|
13
|
-
import "../chunk-
|
|
14
|
-
import "../chunk-
|
|
12
|
+
import "../chunk-MLG7YSTS.js";
|
|
13
|
+
import "../chunk-TUNRLEDH.js";
|
|
14
|
+
import "../chunk-57TTYY6T.js";
|
|
15
15
|
import {
|
|
16
16
|
ModelPicker
|
|
17
|
-
} from "../chunk-
|
|
17
|
+
} from "../chunk-T5U7LDQW.js";
|
|
18
18
|
import "../chunk-E4AY62T2.js";
|
|
19
19
|
import "../chunk-SJWIZT7B.js";
|
|
20
20
|
import "../chunk-GEYACSFW.js";
|
package/dist/chat-react/index.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import {
|
|
2
2
|
ComposerModeControls,
|
|
3
3
|
EntryComposer
|
|
4
|
-
} from "../chunk-
|
|
4
|
+
} from "../chunk-EXBAVMMK.js";
|
|
5
5
|
import "../chunk-L7MB2LLM.js";
|
|
6
|
-
import "../chunk-
|
|
7
|
-
import "../chunk-
|
|
6
|
+
import "../chunk-57TTYY6T.js";
|
|
7
|
+
import "../chunk-T5U7LDQW.js";
|
|
8
8
|
import "../chunk-SJWIZT7B.js";
|
|
9
9
|
import "../chunk-MLG6XKPV.js";
|
|
10
10
|
import "../chunk-NJA6X7JI.js";
|
|
@@ -45,13 +45,13 @@ import {
|
|
|
45
45
|
} from "../chunk-CJW24QMJ.js";
|
|
46
46
|
import "../chunk-MCYJON3F.js";
|
|
47
47
|
import "../chunk-LWSJK546.js";
|
|
48
|
-
import "../chunk-
|
|
48
|
+
import "../chunk-4ZMZDE24.js";
|
|
49
49
|
import "../chunk-6A7MYOUI.js";
|
|
50
|
+
import "../chunk-4YHE7PGO.js";
|
|
51
|
+
import "../chunk-S5SRJJQG.js";
|
|
50
52
|
import "../chunk-4CBU7QIL.js";
|
|
51
53
|
import "../chunk-UGWQLQDS.js";
|
|
52
|
-
import "../chunk-4YHE7PGO.js";
|
|
53
54
|
import "../chunk-NZNXHCVU.js";
|
|
54
|
-
import "../chunk-S5SRJJQG.js";
|
|
55
55
|
import {
|
|
56
56
|
ProtectedModelSettlementError
|
|
57
57
|
} from "../chunk-RN2N75EI.js";
|
|
@@ -2,23 +2,23 @@ import {
|
|
|
2
2
|
authenticateToolRequest,
|
|
3
3
|
createMcpToolHandler
|
|
4
4
|
} from "./chunk-6A7MYOUI.js";
|
|
5
|
-
import {
|
|
6
|
-
buildAppToolOpenAITools,
|
|
7
|
-
findCustomTool,
|
|
8
|
-
isAppToolName
|
|
9
|
-
} from "./chunk-4CBU7QIL.js";
|
|
10
5
|
import {
|
|
11
6
|
assertRenderUiSchema
|
|
12
7
|
} from "./chunk-4YHE7PGO.js";
|
|
13
|
-
import {
|
|
14
|
-
ToolInputError
|
|
15
|
-
} from "./chunk-NZNXHCVU.js";
|
|
16
8
|
import {
|
|
17
9
|
base64UrlDecodeText,
|
|
18
10
|
base64UrlEncodeText,
|
|
19
11
|
constantTimeEqual,
|
|
20
12
|
hmacSha256Base64Url
|
|
21
13
|
} from "./chunk-S5SRJJQG.js";
|
|
14
|
+
import {
|
|
15
|
+
buildAppToolOpenAITools,
|
|
16
|
+
findCustomTool,
|
|
17
|
+
isAppToolName
|
|
18
|
+
} from "./chunk-4CBU7QIL.js";
|
|
19
|
+
import {
|
|
20
|
+
ToolInputError
|
|
21
|
+
} from "./chunk-NZNXHCVU.js";
|
|
22
22
|
|
|
23
23
|
// src/tools/capability.ts
|
|
24
24
|
async function createCapabilityToken(userId, opts) {
|
|
@@ -270,4 +270,4 @@ export {
|
|
|
270
270
|
createAppToolRuntimeExecutor,
|
|
271
271
|
handleAppToolRequest
|
|
272
272
|
};
|
|
273
|
-
//# sourceMappingURL=chunk-
|
|
273
|
+
//# sourceMappingURL=chunk-4ZMZDE24.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
usePopover
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-T5U7LDQW.js";
|
|
4
4
|
|
|
5
5
|
// src/web-react/popover-dialog.ts
|
|
6
6
|
import { useEffect, useId } from "react";
|
|
@@ -45,4 +45,4 @@ function usePopoverDialog(open, onOpenChange) {
|
|
|
45
45
|
export {
|
|
46
46
|
usePopoverDialog
|
|
47
47
|
};
|
|
48
|
-
//# sourceMappingURL=chunk-
|
|
48
|
+
//# sourceMappingURL=chunk-57TTYY6T.js.map
|
|
@@ -3,7 +3,7 @@ import {
|
|
|
3
3
|
} from "./chunk-L7MB2LLM.js";
|
|
4
4
|
import {
|
|
5
5
|
usePopoverDialog
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-57TTYY6T.js";
|
|
7
7
|
import {
|
|
8
8
|
CheckGlyph,
|
|
9
9
|
EffortPicker,
|
|
@@ -14,7 +14,7 @@ import {
|
|
|
14
14
|
pickerRootClass,
|
|
15
15
|
quietPickerTriggerClass,
|
|
16
16
|
usePopover
|
|
17
|
-
} from "./chunk-
|
|
17
|
+
} from "./chunk-T5U7LDQW.js";
|
|
18
18
|
import {
|
|
19
19
|
filterCommandPaletteItems
|
|
20
20
|
} from "./chunk-SJWIZT7B.js";
|
|
@@ -338,7 +338,7 @@ import {
|
|
|
338
338
|
} from "react";
|
|
339
339
|
import { Fragment, jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
|
|
340
340
|
function createLazyMentionEditor() {
|
|
341
|
-
return lazy(() => import("./mention-editor-
|
|
341
|
+
return lazy(() => import("./mention-editor-W2GG2NZ7.js").then((m) => m.loadMentionEditor()));
|
|
342
342
|
}
|
|
343
343
|
var IS_APPLE_PLATFORM = typeof navigator !== "undefined" && /Mac|iPhone|iPad|iPod/i.test(navigator.platform);
|
|
344
344
|
function SendGlyph({ className }) {
|
|
@@ -1924,7 +1924,7 @@ function ComposerModeControls({ planMode }) {
|
|
|
1924
1924
|
// Inset ring: this chip sits in a composer row that clips its overflow,
|
|
1925
1925
|
// so an outward ring loses three of its four sides. Only the offset is
|
|
1926
1926
|
// overridden — width and colour stay with the tokens.
|
|
1927
|
-
"inline-flex h-
|
|
1927
|
+
"inline-flex h-[var(--control-height-sm,2rem)] items-center gap-1 rounded-full border px-2.5 text-sm transition-colors focus-visible:[outline-offset:-2px]",
|
|
1928
1928
|
planMode.enabled ? "border-primary/50 bg-primary/10 text-primary" : "border-border bg-transparent text-muted-foreground hover:text-foreground",
|
|
1929
1929
|
planMode.saving && "opacity-60"
|
|
1930
1930
|
),
|
|
@@ -2045,4 +2045,4 @@ export {
|
|
|
2045
2045
|
ComposerModeControls,
|
|
2046
2046
|
EntryComposer
|
|
2047
2047
|
};
|
|
2048
|
-
//# sourceMappingURL=chunk-
|
|
2048
|
+
//# sourceMappingURL=chunk-EXBAVMMK.js.map
|