@tangle-network/agent-app 3.0.33 → 3.0.35

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.
@@ -1,8 +1,9 @@
1
1
  import {
2
+ PROFILE_PROMPT_HISTORY_MAX,
2
3
  ProfileConflictError,
3
4
  parseProfileRevisionDiff,
4
5
  serializeProfileRevisionDiff
5
- } from "../chunk-GP2BEEBJ.js";
6
+ } from "../chunk-KYF6YK3C.js";
6
7
  import "../chunk-3CI35I4X.js";
7
8
  import "../chunk-GD4ONMKJ.js";
8
9
  import "../chunk-UGWQLQDS.js";
@@ -235,6 +236,29 @@ function createD1ProfileRevisionStore(db, options = {}) {
235
236
  getBinding,
236
237
  getSwitchReceipt,
237
238
  getTurnPin,
239
+ async readPromptHistory(workspaceId, profileId, revisionId) {
240
+ const prompt = (alias) => `json_extract(${alias}.profile_json, '$.prompt.systemPrompt')`;
241
+ const rows = await db.prepare(`WITH RECURSIVE history(revision_id, parent_id, depth) AS (
242
+ SELECT revision_id, parent_id, 0 FROM agent_profile_revision
243
+ WHERE workspace_id = ? AND profile_id = ? AND revision_id = ?
244
+ UNION ALL
245
+ SELECT r.revision_id, r.parent_id, h.depth + 1
246
+ FROM history h JOIN agent_profile_revision r ON r.revision_id = h.parent_id AND r.workspace_id = ? AND r.profile_id = ?
247
+ WHERE h.depth < ${PROFILE_PROMPT_HISTORY_MAX - 1})
248
+ SELECT r.revision_id, r.parent_id, r.author_kind, r.author_id,
249
+ ${prompt("r")} IS (SELECT ${prompt("n")} FROM agent_profile_revision n WHERE n.revision_id = ?) AS same_as_newest,
250
+ CASE WHEN p.revision_id IS NULL THEN NULL ELSE ${prompt("r")} IS ${prompt("p")} END AS same_as_parent
251
+ FROM history h JOIN agent_profile_revision r ON r.revision_id = h.revision_id
252
+ LEFT JOIN agent_profile_revision p ON p.revision_id = h.parent_id AND p.workspace_id = ? AND p.profile_id = ?
253
+ ORDER BY h.depth LIMIT ${PROFILE_PROMPT_HISTORY_MAX}`).bind(workspaceId, profileId, revisionId, workspaceId, profileId, revisionId, workspaceId, profileId).all();
254
+ return rows.results.map((row) => ({
255
+ id: row.revision_id,
256
+ parentId: row.parent_id,
257
+ author: { kind: row.author_kind, id: row.author_id },
258
+ sameAsNewest: row.same_as_newest === 1,
259
+ sameAsParent: row.same_as_parent === null ? null : row.same_as_parent === 1
260
+ }));
261
+ },
238
262
  async listKnowledgeEvents(workspaceId, profileId) {
239
263
  const rows = await db.prepare(`SELECT * FROM agent_profile_knowledge_event
240
264
  WHERE workspace_id = ? AND profile_id = ? ORDER BY created_at, event_id`).bind(workspaceId, profileId).all();
@@ -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/profile-snapshot'\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 }; results?: unknown[] }[]>\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 NULLs the receipt's required message; D1's batch rolls both writes back.\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 // The rolled-back batch above surfaces a stale expectedVersion as a constraint failure.\n if (/constraint failed/i.test(String(error))) throw new ProfileConflictError('Profile binding changed during switch')\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; its immutable receipt is still the answer.\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, options) {\n const key = pin\n // admitProfileTurn has already read this message's pin; a second read here was one more serial round trip.\n if (!options?.priorChecked) {\n const prior = await getTurnPin(key, pin.messageId, pin.inputHash)\n if (prior) return prior\n }\n const insert = 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)\n const readBack = db.prepare(`SELECT * FROM agent_profile_turn_pin WHERE workspace_id = ?\n AND member_id = ? AND channel = ? AND message_id = ?`).bind(...keyValues(key), pin.messageId)\n // The compare-and-set insert and its read-back travel as one batch: one round trip instead of two.\n const [inserted, read] = await db.batch([insert, readBack])\n const row = (read?.results?.[0] ?? null) as TurnRow | null\n if (row && row.input_hash !== pin.inputHash) throw new ProfileConflictError('Message id was reused with different input')\n const saved = row ? turnFromRow(row) : null\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,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,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;AACtD,YAAM,WAAW,GAAG,QAAQ;AAAA,6DAC2B,EAAE,KAAK,GAAG,UAAU,GAAG,GAAG,IAAI,SAAS;AAE9F,YAAM,CAAC,UAAU,IAAI,IAAI,MAAM,GAAG,MAAM,CAAC,QAAQ,QAAQ,CAAC;AAC1D,YAAM,MAAO,MAAM,UAAU,CAAC,KAAK;AACnC,UAAI,OAAO,IAAI,eAAe,IAAI,UAAW,OAAM,IAAI,qBAAqB,4CAA4C;AACxH,YAAM,QAAQ,MAAM,YAAY,GAAG,IAAI;AACvC,UAAI,CAAC,SAAU,SAAU,KAAK,YAAY,KAAK,MAAM,eAAe,IAAI,YAAa;AACnF,cAAM,IAAI,qBAAqB,+CAA+C;AAAA,MAChF;AACA,aAAO;AAAA,IACT;AAAA,EACF;AACF;","names":["options"]}
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/profile-snapshot'\nimport {\n parseProfileRevisionDiff,\n PROFILE_PROMPT_HISTORY_MAX,\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 }; results?: unknown[] }[]>\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 readPromptHistory(workspaceId, profileId, revisionId) {\n // One round trip that returns flags, not prompts. The recursion carries ids only; prompts are compared once per\n // row in the final select. The depth bound keeps a corrupt parent cycle finite; a cut history reads as incomplete.\n const prompt = (alias: string) => `json_extract(${alias}.profile_json, '$.prompt.systemPrompt')`\n const rows = await db.prepare(`WITH RECURSIVE history(revision_id, parent_id, depth) AS (\n SELECT revision_id, parent_id, 0 FROM agent_profile_revision\n WHERE workspace_id = ? AND profile_id = ? AND revision_id = ?\n UNION ALL\n SELECT r.revision_id, r.parent_id, h.depth + 1\n FROM history h JOIN agent_profile_revision r ON r.revision_id = h.parent_id AND r.workspace_id = ? AND r.profile_id = ?\n WHERE h.depth < ${PROFILE_PROMPT_HISTORY_MAX - 1})\n SELECT r.revision_id, r.parent_id, r.author_kind, r.author_id,\n ${prompt('r')} IS (SELECT ${prompt('n')} FROM agent_profile_revision n WHERE n.revision_id = ?) AS same_as_newest,\n CASE WHEN p.revision_id IS NULL THEN NULL ELSE ${prompt('r')} IS ${prompt('p')} END AS same_as_parent\n FROM history h JOIN agent_profile_revision r ON r.revision_id = h.revision_id\n LEFT JOIN agent_profile_revision p ON p.revision_id = h.parent_id AND p.workspace_id = ? AND p.profile_id = ?\n ORDER BY h.depth LIMIT ${PROFILE_PROMPT_HISTORY_MAX}`)\n .bind(workspaceId, profileId, revisionId, workspaceId, profileId, revisionId, workspaceId, profileId)\n .all<Pick<RevisionRow, 'revision_id' | 'parent_id' | 'author_kind' | 'author_id'> &\n { same_as_newest: number; same_as_parent: number | null }>()\n return rows.results.map(row => ({ id: row.revision_id, parentId: row.parent_id,\n author: { kind: row.author_kind, id: row.author_id }, sameAsNewest: row.same_as_newest === 1,\n sameAsParent: row.same_as_parent === null ? null : row.same_as_parent === 1 }))\n },\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 NULLs the receipt's required message; D1's batch rolls both writes back.\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 // The rolled-back batch above surfaces a stale expectedVersion as a constraint failure.\n if (/constraint failed/i.test(String(error))) throw new ProfileConflictError('Profile binding changed during switch')\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; its immutable receipt is still the answer.\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, options) {\n const key = pin\n // admitProfileTurn has already read this message's pin; a second read here was one more serial round trip.\n if (!options?.priorChecked) {\n const prior = await getTurnPin(key, pin.messageId, pin.inputHash)\n if (prior) return prior\n }\n const insert = 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)\n const readBack = db.prepare(`SELECT * FROM agent_profile_turn_pin WHERE workspace_id = ?\n AND member_id = ? AND channel = ? AND message_id = ?`).bind(...keyValues(key), pin.messageId)\n // The compare-and-set insert and its read-back travel as one batch: one round trip instead of two.\n const [inserted, read] = await db.batch([insert, readBack])\n const row = (read?.results?.[0] ?? null) as TurnRow | null\n if (row && row.input_hash !== pin.inputHash) throw new ProfileConflictError('Message id was reused with different input')\n const saved = row ? turnFromRow(row) : null\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;AAsC9B,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;A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AAC1D,YAAM,MAAO,MAAM,UAAU,CAAC,KAAK;AACnC,UAAI,OAAO,IAAI,eAAe,IAAI,UAAW,OAAM,IAAI,qBAAqB,4CAA4C;AACxH,YAAM,QAAQ,MAAM,YAAY,GAAG,IAAI;AACvC,UAAI,CAAC,SAAU,SAAU,KAAK,YAAY,KAAK,MAAM,eAAe,IAAI,YAAa;AACnF,cAAM,IAAI,qBAAqB,+CAA+C;AAAA,MAChF;AACA,aAAO;AAAA,IACT;AAAA,EACF;AACF;","names":["options"]}
@@ -98,6 +98,20 @@ export interface ProfileRevisionStore {
98
98
  getTurnPin(key: ProfileBindingKey, messageId: string, inputHash: string): Promise<ProfileTurnPin | null>;
99
99
  listKnowledgeEvents(workspaceId: string, profileId: string): Promise<ProfileKnowledgeEvent[]>;
100
100
  appendKnowledgeEvent(event: ProfileKnowledgeEvent): Promise<void>;
101
+ /** A revision and its ancestors, newest first, in one read; it ends early at a missing ancestor.
102
+ * Without it, `followProductRelease` reads the history one `getRevision` at a time. */
103
+ readPromptHistory?(workspaceId: string, profileId: string, revisionId: string): Promise<ProfilePromptHistoryEntry[]>;
104
+ }
105
+ /** One revision of a profile's history, reduced to what decides whether the newest one's system prompt is product
106
+ * text. Prompts are compared where they are stored, so the history carries no prompt text. */
107
+ export interface ProfilePromptHistoryEntry {
108
+ id: string;
109
+ parentId: string | null;
110
+ author: ProfileRevision['author'];
111
+ /** Its system prompt equals the newest entry's. */
112
+ sameAsNewest: boolean;
113
+ /** Its system prompt equals its parent's; `null` when it has no parent row. */
114
+ sameAsParent: boolean | null;
101
115
  }
102
116
  export declare class ProfileConflictError extends Error {
103
117
  readonly code?: 'profile_changed' | undefined;
@@ -291,3 +305,4 @@ export declare const PROFILE_MEMORY_PREFIX = "/memories/workspace/";
291
305
  /** Shared self-edit tools; only the authenticated active turn can name the profile. */
292
306
  export declare function profileTools<TTurn extends ProfileToolTurn>(context: ProfileToolContext<TTurn>): McpToolDefinition<Record<string, never>>[];
293
307
  export * from './self-management.js';
308
+ export * from './release.js';
@@ -1,6 +1,7 @@
1
1
  import {
2
2
  PERMITTED_SELF_MOUNT_DIMENSIONS,
3
3
  PROFILE_MEMORY_PREFIX,
4
+ PROFILE_PROMPT_HISTORY_MAX,
4
5
  ProfileAccessError,
5
6
  ProfileConflictError,
6
7
  admitProfileTurn,
@@ -9,7 +10,9 @@ import {
9
10
  createMountProfileChangeTool,
10
11
  createProductSelfMount,
11
12
  createTextProfile,
13
+ followProductRelease,
12
14
  handleProfileSwitchText,
15
+ overlayOnRelease,
13
16
  parseProfileRevisionDiff,
14
17
  profileAdmissionValues,
15
18
  profileAuthority,
@@ -17,11 +20,13 @@ import {
17
20
  profileSwitchInputHash,
18
21
  profileTools,
19
22
  promoteRevision,
23
+ promptShippedByProduct,
20
24
  proposeRevision,
21
25
  readProfileAdmission,
26
+ refreshBuiltinSkills,
22
27
  serializeProfileRevisionDiff,
23
28
  switchProfile
24
- } from "../chunk-GP2BEEBJ.js";
29
+ } from "../chunk-KYF6YK3C.js";
25
30
  import {
26
31
  normalizeProfileName,
27
32
  parseProfileSwitch
@@ -33,6 +38,7 @@ import "../chunk-F4XBNR5L.js";
33
38
  export {
34
39
  PERMITTED_SELF_MOUNT_DIMENSIONS,
35
40
  PROFILE_MEMORY_PREFIX,
41
+ PROFILE_PROMPT_HISTORY_MAX,
36
42
  ProfileAccessError,
37
43
  ProfileConflictError,
38
44
  admitProfileTurn,
@@ -41,8 +47,10 @@ export {
41
47
  createMountProfileChangeTool,
42
48
  createProductSelfMount,
43
49
  createTextProfile,
50
+ followProductRelease,
44
51
  handleProfileSwitchText,
45
52
  normalizeProfileName,
53
+ overlayOnRelease,
46
54
  parseProfileRevisionDiff,
47
55
  parseProfileSwitch,
48
56
  profileAdmissionValues,
@@ -51,8 +59,10 @@ export {
51
59
  profileSwitchInputHash,
52
60
  profileTools,
53
61
  promoteRevision,
62
+ promptShippedByProduct,
54
63
  proposeRevision,
55
64
  readProfileAdmission,
65
+ refreshBuiltinSkills,
56
66
  serializeProfileRevisionDiff,
57
67
  switchProfile
58
68
  };
@@ -0,0 +1,68 @@
1
+ /**
2
+ * A stored profile runs the current product release plus its own changes.
3
+ *
4
+ * Revisions are complete AgentProfile snapshots, so a workspace's import carries a copy of the product text current
5
+ * when it was made, and that copy goes stale with the next release. A turn resolves the stored profile over the
6
+ * release serving it: text equal to a version the product shipped (the release's own, or one in the workspace's
7
+ * history) is product text and runs as the release's; text that matches no shipped version is the workspace's own
8
+ * and stays. Nothing stored is rewritten.
9
+ *
10
+ * Only `prompt.systemPrompt` follows a release. No product profile ships `prompt.instructions` (2026-11-15: Creative,
11
+ * Legal, Hardware, Tax and GTM set only the system prompt there); instructions in a stored revision are a person's.
12
+ */
13
+ import { type AgentProfile } from '@tangle-network/agent-interface';
14
+ import type { ProfileRevision, ProfileRevisionStore } from './index.js';
15
+ type SkillRef = NonNullable<NonNullable<AgentProfile['resources']>['skills']>[number];
16
+ /** How a stored profile's text compares with the current release; `customized` text is the workspace's own and stays. */
17
+ export interface ProfileReleaseUpdates {
18
+ systemPrompt: 'current' | 'outdated' | 'customized';
19
+ specialists: {
20
+ updated: string[];
21
+ customized: string[];
22
+ };
23
+ skills: {
24
+ added: string[];
25
+ updated: string[];
26
+ removed: string[];
27
+ /** Built-in skills this workspace edited; they stay as they are. */
28
+ customized: string[];
29
+ };
30
+ }
31
+ /** The longest history read; a longer one reads as incomplete, so its prompt is kept. The D1 case in
32
+ * tests/agent-profiles-pin.integration.test.ts reads a history this long with 20 KB prompts. */
33
+ export declare const PROFILE_PROMPT_HISTORY_MAX = 1000;
34
+ /**
35
+ * The active profile's skills with built-ins brought to the release. A built-in counts as untouched while it
36
+ * matches a version the product shipped (`shipped`); edited built-ins and workspace skills are kept.
37
+ */
38
+ export declare function refreshBuiltinSkills(active: AgentProfile, shipped: readonly SkillRef[], release: AgentProfile): {
39
+ skills: SkillRef[];
40
+ updates: ProfileReleaseUpdates['skills'];
41
+ };
42
+ /**
43
+ * Resolve a stored profile over the release. `shipped` holds every complete profile the product delivered to this
44
+ * workspace (its import and each release refresh). The system prompt, specialists, built-in skills and every
45
+ * executable control come from the release; the workspace keeps the text it wrote.
46
+ */
47
+ export declare function overlayOnRelease(stored: AgentProfile, shipped: readonly AgentProfile[], release: AgentProfile): {
48
+ profile: AgentProfile;
49
+ updates: ProfileReleaseUpdates;
50
+ };
51
+ /**
52
+ * Whether a revision's system prompt is one the product shipped into its history: some revision by a product author
53
+ * has that prompt and differs from its parent's (an import, or a release refresh). A product revision that carries
54
+ * its parent's prompt forward ships nothing, so a person's text a release copied stays theirs. An incomplete history
55
+ * (a missing ancestor, or a longer one than `PROFILE_PROMPT_HISTORY_MAX`) shows nothing to be the product's.
56
+ */
57
+ export declare function promptShippedByProduct(store: ProfileRevisionStore, revision: ProfileRevision, productAuthorIds: readonly string[]): Promise<boolean>;
58
+ /**
59
+ * The profile a turn runs for `revision`: the stored profile with the release's system prompt where the stored prompt
60
+ * is one the product shipped into its history (`promptShippedByProduct`, revisions whose author id is in
61
+ * `productAuthorIds`) or absent; unchanged, and returned as is, where a person wrote it. Only the system prompt
62
+ * moves; authority, name, description and instructions stay. The history is read once per revision and isolate, in
63
+ * one round trip on the D1 store, and not at all when the stored prompt already is the release's. A plan digest
64
+ * computed from the result moves with each release, so a product's `verifyEffectivePlan` must compute it from this
65
+ * function's result too.
66
+ */
67
+ export declare function followProductRelease(store: ProfileRevisionStore, revision: ProfileRevision, release: AgentProfile, productAuthorIds: readonly string[]): Promise<AgentProfile>;
68
+ export {};
@@ -88,14 +88,14 @@ import {
88
88
  turnPromptText,
89
89
  valueRedactor,
90
90
  withProducerStream
91
- } from "../chunk-KNVFMTC2.js";
91
+ } from "../chunk-VG27P322.js";
92
92
  import "../chunk-SBHFMDR7.js";
93
93
  import "../chunk-H6BRJU5M.js";
94
94
  import "../chunk-4DBHC63F.js";
95
95
  import "../chunk-RN4WPTBH.js";
96
96
  import "../chunk-MM6RLOXF.js";
97
97
  import "../chunk-M4QITAQV.js";
98
- import "../chunk-3FKIGI3I.js";
98
+ import "../chunk-5DG2LO3T.js";
99
99
  import "../chunk-F4TUZYMX.js";
100
100
  import {
101
101
  redactErrorMessage
@@ -3491,14 +3491,43 @@ async function finalizeExistingBox(shell, client, box, stage, name, workspaceId,
3491
3491
  const renewed = await pushRuntimeEnv(finalBox, runtimeEnv, void 0, deadline);
3492
3492
  if (!renewed.succeeded) throw renewed.error;
3493
3493
  }
3494
- if (shell.bootstrap) {
3495
- const boot = await shell.bootstrap(finalBox, scope);
3496
- if (!boot.succeeded) {
3497
- throw new Error(`bootstrap failed on ${stage} box ${name}`, { cause: boot.error });
3498
- }
3499
- }
3494
+ await bootstrapBox(shell, finalBox, scope, harness, stage, name, false);
3500
3495
  return finalBox;
3501
3496
  }
3497
+ var BOOTSTRAP_MARKERS = '"$HOME/.agent-app/bootstrapped"';
3498
+ var BOOTSTRAP_MARKER_MAX_AGE_MINUTES = 24 * 60;
3499
+ async function bootstrapBox(shell, box, scope, harness, stage, name, fresh) {
3500
+ const bootstrap = shell.bootstrap;
3501
+ if (!bootstrap) return;
3502
+ const key = await bootstrapKey(shell, scope, harness);
3503
+ if (key !== void 0 && !fresh && await hasBootstrapMarker(box, key)) return;
3504
+ const boot = await bootstrap.call(shell, box, scope);
3505
+ if (!boot.succeeded) {
3506
+ throw new Error(`bootstrap failed on ${stage} box ${name}`, { cause: boot.error });
3507
+ }
3508
+ if (key !== void 0) await writeBootstrapMarker(box, key);
3509
+ }
3510
+ async function bootstrapKey(shell, scope, harness) {
3511
+ if (!shell.bootstrapDigest) return void 0;
3512
+ const build = await shell.bootstrapDigest(scope);
3513
+ if (!build) return void 0;
3514
+ const egress = shell.egressPolicy ? normalizedEgressPolicy(shell.egressPolicy) : null;
3515
+ return createHash2("sha256").update(JSON.stringify([build, harness, egress, scope.workspaceId, scope.userId ?? null]), "utf8").digest("hex");
3516
+ }
3517
+ async function hasBootstrapMarker(box, key) {
3518
+ try {
3519
+ const fresh = `find ${BOOTSTRAP_MARKERS} -maxdepth 1 -name ${key} -mmin -${BOOTSTRAP_MARKER_MAX_AGE_MINUTES} 2>/dev/null`;
3520
+ return (await box.exec(`test -n "$(${fresh})"`)).exitCode === 0;
3521
+ } catch {
3522
+ return false;
3523
+ }
3524
+ }
3525
+ async function writeBootstrapMarker(box, key) {
3526
+ try {
3527
+ await box.exec(`mkdir -p ${BOOTSTRAP_MARKERS} && : > ${BOOTSTRAP_MARKERS}/${key}`);
3528
+ } catch {
3529
+ }
3530
+ }
3502
3531
  function canonicalizeJson(value) {
3503
3532
  if (Array.isArray(value)) return value.map(canonicalizeJson);
3504
3533
  if (value === null || typeof value !== "object") return value;
@@ -3944,13 +3973,7 @@ async function provisionWorkspaceSandbox(shell, options, gate, reuseOnly) {
3944
3973
  throw deferredProfileWriteFailed("new", name, written.error);
3945
3974
  }
3946
3975
  }
3947
- if (shell.bootstrap) {
3948
- const bootstrap = shell.bootstrap.bind(shell);
3949
- const boot = await measure("bootstrap", () => bootstrap(box, scope));
3950
- if (!boot.succeeded) {
3951
- throw new Error(`bootstrap failed on new box ${name}`, { cause: boot.error });
3952
- }
3953
- }
3976
+ if (shell.bootstrap) await measure("bootstrap", () => bootstrapBox(shell, box, scope, harness, "new", name, true));
3954
3977
  return rememberRunningBox(name, box);
3955
3978
  }
3956
3979
  async function prepareWorkspacePayload(shell, workspaceId, userId, scope, harness, name, recoveryRestore, resources, billingOwnerId, signal) {
@@ -4334,4 +4357,4 @@ export {
4334
4357
  deleteSecret,
4335
4358
  mintSandboxScopedToken
4336
4359
  };
4337
- //# sourceMappingURL=chunk-3FKIGI3I.js.map
4360
+ //# sourceMappingURL=chunk-5DG2LO3T.js.map