@tangle-network/agent-app 0.63.30 → 0.63.32
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/{DesignCanvas-3DGZQOD7.js → DesignCanvas-VKZ7Y3JU.js} +2 -3
- package/dist/{DesignCanvasEditor-OG4QY5WJ.js → DesignCanvasEditor-3V53YLLZ.js} +2 -3
- package/dist/agent-profiles/d1.js +4 -3
- package/dist/agent-profiles/d1.js.map +1 -1
- package/dist/agent-profiles/index.js +4 -3
- package/dist/alerting/github.d.ts +33 -0
- package/dist/alerting/index.d.ts +1 -0
- package/dist/alerting/index.js +47 -0
- package/dist/alerting/index.js.map +1 -1
- package/dist/app-auth/index.js +1 -2
- package/dist/app-auth/index.js.map +1 -1
- package/dist/assistant/index.js +4 -4
- package/dist/billing/index.d.ts +15 -0
- package/dist/billing/index.js +5 -3
- package/dist/chat-routes/index.js +15 -14
- package/dist/chat-routes/index.js.map +1 -1
- package/dist/chat-store/index.js +34 -4
- package/dist/chat-store/index.js.map +1 -1
- package/dist/chat-store/schema.d.ts +286 -0
- package/dist/{chunk-6JEDSKFH.js → chunk-2SDX3OC4.js} +32 -24
- package/dist/{chunk-6JEDSKFH.js.map → chunk-2SDX3OC4.js.map} +1 -1
- package/dist/{chunk-QLZ6A73E.js → chunk-4CEIZZTH.js} +9 -9
- package/dist/{chunk-WL7PZK7Q.js → chunk-4PIN6QYQ.js} +43 -1
- package/dist/chunk-4PIN6QYQ.js.map +1 -0
- package/dist/{chunk-6UMIOEDR.js → chunk-AZRPDSRQ.js} +3 -3
- package/dist/{chunk-6LMM3OVX.js → chunk-BMCC2BUP.js} +3 -3
- package/dist/{chunk-36HSG7HU.js → chunk-CRZXEKCX.js} +2 -2
- package/dist/chunk-F4XBNR5L.js +16 -0
- package/dist/chunk-F4XBNR5L.js.map +1 -0
- package/dist/chunk-GY4IPYG4.js +40 -0
- package/dist/chunk-GY4IPYG4.js.map +1 -0
- package/dist/{chunk-6OG4244Y.js → chunk-MTKD2FN5.js} +2 -251
- package/dist/chunk-MTKD2FN5.js.map +1 -0
- package/dist/{chunk-5AUZR655.js → chunk-NDXQFEZQ.js} +51 -48
- package/dist/chunk-NDXQFEZQ.js.map +1 -0
- package/dist/chunk-NSWLZTJX.js +645 -0
- package/dist/chunk-NSWLZTJX.js.map +1 -0
- package/dist/chunk-PU6AWIRE.js +252 -0
- package/dist/chunk-PU6AWIRE.js.map +1 -0
- package/dist/{chunk-JKECSYDB.js → chunk-PV3GSLUY.js} +3 -3
- package/dist/{chunk-7Y7U7U7X.js → chunk-Q7RSHLEV.js} +5 -3
- package/dist/{chunk-7Y7U7U7X.js.map → chunk-Q7RSHLEV.js.map} +1 -1
- package/dist/{chunk-HRBF4B5L.js → chunk-TUJ4277Q.js} +1 -14
- package/dist/chunk-TUJ4277Q.js.map +1 -0
- package/dist/{chunk-57XPEL7X.js → chunk-V42C72V5.js} +25 -2
- package/dist/chunk-V42C72V5.js.map +1 -0
- package/dist/{chunk-FCYHDENJ.js → chunk-VOIVDEAV.js} +2 -2
- package/dist/{chunk-ACB7KOQ6.js → chunk-WSQSKYXP.js} +4 -4
- package/dist/{chunk-F6J5J4H6.js → chunk-WYQTPFPI.js} +26 -2
- package/dist/chunk-WYQTPFPI.js.map +1 -0
- package/dist/{chunk-PFTOGTHH.js → chunk-Z3IJ7XEW.js} +3 -3
- package/dist/{chunk-ZD2AUFIT.js → chunk-ZGGEYYEQ.js} +3 -3
- package/dist/{chunk-O5AUJQIA.js → chunk-ZNWJJRHP.js} +2 -2
- package/dist/design-canvas/index.js +1 -2
- package/dist/design-canvas/index.js.map +1 -1
- package/dist/design-canvas-react/engine.js +1 -2
- package/dist/design-canvas-react/index.js +2 -3
- package/dist/design-canvas-react/index.js.map +1 -1
- package/dist/design-canvas-react/lazy.js +1 -1
- package/dist/media/generate-request.d.ts +27 -1
- package/dist/media/index.js +36 -426
- package/dist/media/index.js.map +1 -1
- package/dist/media/router-generation.d.ts +7 -0
- package/dist/operator/gateway-keys.d.ts +44 -0
- package/dist/operator/index.d.ts +1 -0
- package/dist/operator/index.js +55 -1
- package/dist/operator/index.js.map +1 -1
- package/dist/plans/decision.d.ts +31 -0
- package/dist/plans/drizzle.js +1 -1
- package/dist/plans/index.js +5 -1
- package/dist/platform/billing.d.ts +3 -2
- package/dist/platform/deployment.d.ts +21 -0
- package/dist/platform/index.d.ts +1 -0
- package/dist/platform/index.js +30 -10
- package/dist/platform/index.js.map +1 -1
- package/dist/preset-cloudflare/index.js +9 -8
- package/dist/preset-cloudflare/index.js.map +1 -1
- package/dist/public-consultation/index.d.ts +1 -1
- package/dist/public-consultation/index.js +13 -12
- package/dist/public-consultation/index.js.map +1 -1
- package/dist/sandbox/computer-receipts.d.ts +1 -1
- package/dist/sandbox/index.d.ts +1 -0
- package/dist/sandbox/index.js +15 -8
- package/dist/sandbox/router-model-policy.d.ts +31 -0
- package/dist/sequences/index.js +1 -2
- package/dist/sequences/index.js.map +1 -1
- package/dist/spend/drizzle.d.ts +195 -0
- package/dist/spend/drizzle.js +22 -0
- package/dist/spend/drizzle.js.map +1 -1
- package/dist/stream/index.js +2 -2
- package/dist/studio/generated-media/flows.d.ts +240 -0
- package/dist/studio/generated-media/index.d.ts +3 -1
- package/dist/studio/generated-media/index.js +357 -138
- package/dist/studio/generated-media/index.js.map +1 -1
- package/dist/studio/index.js +18 -16
- package/dist/studio-react/index.js +28 -26
- package/dist/studio-react/index.js.map +1 -1
- package/dist/teams/index.d.ts +1 -0
- package/dist/teams/index.js +16 -0
- package/dist/teams/index.js.map +1 -1
- package/dist/teams/invitations-api.js +1 -1
- package/dist/teams/members-api.d.ts +5 -3
- package/dist/teams/members-api.js +1 -1
- package/dist/teams/thread-access.d.ts +22 -0
- package/dist/tools/index.js +5 -4
- package/dist/web/index.js +4 -6
- package/dist/web-react/index.js +4 -4
- package/dist/work-product/index.js +3 -2
- package/dist/work-product/index.js.map +1 -1
- package/dist/workspace-export/d1.d.ts +1 -1
- package/dist/workspace-export/index.js +9 -2
- package/dist/workspace-export/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-57XPEL7X.js.map +0 -1
- package/dist/chunk-5AUZR655.js.map +0 -1
- package/dist/chunk-6OG4244Y.js.map +0 -1
- package/dist/chunk-6Z7TZVKZ.js +0 -26
- package/dist/chunk-6Z7TZVKZ.js.map +0 -1
- package/dist/chunk-F6J5J4H6.js.map +0 -1
- package/dist/chunk-HRBF4B5L.js.map +0 -1
- package/dist/chunk-WL7PZK7Q.js.map +0 -1
- /package/dist/{DesignCanvas-3DGZQOD7.js.map → DesignCanvas-VKZ7Y3JU.js.map} +0 -0
- /package/dist/{DesignCanvasEditor-OG4QY5WJ.js.map → DesignCanvasEditor-3V53YLLZ.js.map} +0 -0
- /package/dist/{chunk-QLZ6A73E.js.map → chunk-4CEIZZTH.js.map} +0 -0
- /package/dist/{chunk-6UMIOEDR.js.map → chunk-AZRPDSRQ.js.map} +0 -0
- /package/dist/{chunk-6LMM3OVX.js.map → chunk-BMCC2BUP.js.map} +0 -0
- /package/dist/{chunk-36HSG7HU.js.map → chunk-CRZXEKCX.js.map} +0 -0
- /package/dist/{chunk-JKECSYDB.js.map → chunk-PV3GSLUY.js.map} +0 -0
- /package/dist/{chunk-FCYHDENJ.js.map → chunk-VOIVDEAV.js.map} +0 -0
- /package/dist/{chunk-ACB7KOQ6.js.map → chunk-WSQSKYXP.js.map} +0 -0
- /package/dist/{chunk-PFTOGTHH.js.map → chunk-Z3IJ7XEW.js.map} +0 -0
- /package/dist/{chunk-ZD2AUFIT.js.map → chunk-ZGGEYYEQ.js.map} +0 -0
- /package/dist/{chunk-O5AUJQIA.js.map → chunk-ZNWJJRHP.js.map} +0 -0
|
@@ -7,10 +7,9 @@ import "./chunk-VCG4DQC4.js";
|
|
|
7
7
|
import "./chunk-DPTNKH22.js";
|
|
8
8
|
import "./chunk-RN4WPTBH.js";
|
|
9
9
|
import "./chunk-ALIWB2P3.js";
|
|
10
|
+
import "./chunk-V42C72V5.js";
|
|
10
11
|
import "./chunk-TXD5HXLE.js";
|
|
11
|
-
import "./chunk-6Z7TZVKZ.js";
|
|
12
|
-
import "./chunk-57XPEL7X.js";
|
|
13
12
|
export {
|
|
14
13
|
DesignCanvas
|
|
15
14
|
};
|
|
16
|
-
//# sourceMappingURL=DesignCanvas-
|
|
15
|
+
//# sourceMappingURL=DesignCanvas-VKZ7Y3JU.js.map
|
|
@@ -9,11 +9,10 @@ import "./chunk-VCG4DQC4.js";
|
|
|
9
9
|
import "./chunk-DPTNKH22.js";
|
|
10
10
|
import "./chunk-RN4WPTBH.js";
|
|
11
11
|
import "./chunk-ALIWB2P3.js";
|
|
12
|
+
import "./chunk-V42C72V5.js";
|
|
12
13
|
import "./chunk-TXD5HXLE.js";
|
|
13
|
-
import "./chunk-6Z7TZVKZ.js";
|
|
14
|
-
import "./chunk-57XPEL7X.js";
|
|
15
14
|
import "./chunk-UTF7H6BK.js";
|
|
16
15
|
export {
|
|
17
16
|
DesignCanvasEditor
|
|
18
17
|
};
|
|
19
|
-
//# sourceMappingURL=DesignCanvasEditor-
|
|
18
|
+
//# sourceMappingURL=DesignCanvasEditor-3V53YLLZ.js.map
|
|
@@ -2,11 +2,12 @@ import {
|
|
|
2
2
|
ProfileConflictError,
|
|
3
3
|
parseProfileRevisionDiff,
|
|
4
4
|
serializeProfileRevisionDiff
|
|
5
|
-
} from "../chunk-
|
|
5
|
+
} from "../chunk-PV3GSLUY.js";
|
|
6
6
|
import "../chunk-3CI35I4X.js";
|
|
7
|
-
import "../chunk-
|
|
7
|
+
import "../chunk-VOIVDEAV.js";
|
|
8
8
|
import "../chunk-UGWQLQDS.js";
|
|
9
|
-
import "../chunk-
|
|
9
|
+
import "../chunk-TUJ4277Q.js";
|
|
10
|
+
import "../chunk-F4XBNR5L.js";
|
|
10
11
|
|
|
11
12
|
// src/agent-profiles/d1.ts
|
|
12
13
|
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 }; 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 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, 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 bin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,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'\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 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, 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,YAAY,CAAC,QAA2B,CAAC,IAAI,aAAa,IAAI,UAAU,IAAI,OAAO;AAEzF,SAAS,gBAAgB,KAAmC;AAC1D,SAAO;AAAA,IAAE,IAAI,IAAI;AAAA,IAAa,aAAa,IAAI;AAAA,IAAc,WAAW,IAAI;AAAA,IAC1E,UAAU,IAAI;AAAA,IAAW,SAAS,qBAAqB,KAAK,MAAM,IAAI,YAAY,CAAC;AAAA,IACnF,eAAe,IAAI;AAAA,IAAgB,QAAQ,EAAE,MAAM,IAAI,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,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"]}
|
|
@@ -21,14 +21,15 @@ import {
|
|
|
21
21
|
readProfileAdmission,
|
|
22
22
|
serializeProfileRevisionDiff,
|
|
23
23
|
switchProfile
|
|
24
|
-
} from "../chunk-
|
|
24
|
+
} from "../chunk-PV3GSLUY.js";
|
|
25
25
|
import {
|
|
26
26
|
normalizeProfileName,
|
|
27
27
|
parseProfileSwitch
|
|
28
28
|
} from "../chunk-3CI35I4X.js";
|
|
29
|
-
import "../chunk-
|
|
29
|
+
import "../chunk-VOIVDEAV.js";
|
|
30
30
|
import "../chunk-UGWQLQDS.js";
|
|
31
|
-
import "../chunk-
|
|
31
|
+
import "../chunk-TUJ4277Q.js";
|
|
32
|
+
import "../chunk-F4XBNR5L.js";
|
|
32
33
|
export {
|
|
33
34
|
PERMITTED_SELF_MOUNT_DIMENSIONS,
|
|
34
35
|
PROFILE_MEMORY_PREFIX,
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A rolling GitHub-issue alert channel: the first alert files an issue under a
|
|
3
|
+
* label, later alerts comment on the open one, so a persistent problem is one
|
|
4
|
+
* thread a human can follow instead of a hundred issues nobody reads.
|
|
5
|
+
*
|
|
6
|
+
* The token is a fine-grained PAT scoped to Issues:write on the one repository,
|
|
7
|
+
* read from the caller at each use so a Worker secret can rotate. Whether the
|
|
8
|
+
* channel is configured is a separate question from whether a write succeeded,
|
|
9
|
+
* so a caller can report "the alert token is missing" as its own state.
|
|
10
|
+
*/
|
|
11
|
+
export interface GithubIssueAlertOptions {
|
|
12
|
+
owner: string;
|
|
13
|
+
repo: string;
|
|
14
|
+
/** The label that marks the rolling issue. */
|
|
15
|
+
label: string;
|
|
16
|
+
/** The PAT, or undefined when the deployment has none. */
|
|
17
|
+
token: () => string | undefined;
|
|
18
|
+
/** The User-Agent GitHub requires on every call. */
|
|
19
|
+
userAgent: string;
|
|
20
|
+
/** The variable a missing token is reported under. */
|
|
21
|
+
tokenName?: string;
|
|
22
|
+
}
|
|
23
|
+
export interface GithubIssueAlertChannel {
|
|
24
|
+
/** Whether a token is configured, checked before an alert is composed. */
|
|
25
|
+
configured(): boolean;
|
|
26
|
+
/**
|
|
27
|
+
* Comment on the open labeled issue, or file one when none is open. Returns
|
|
28
|
+
* the issue URL so the caller can record that the channel fired; throws when
|
|
29
|
+
* the token is missing or GitHub refuses the write.
|
|
30
|
+
*/
|
|
31
|
+
file(title: string, body: string): Promise<string>;
|
|
32
|
+
}
|
|
33
|
+
export declare function createGithubIssueAlertChannel(options: GithubIssueAlertOptions): GithubIssueAlertChannel;
|
package/dist/alerting/index.d.ts
CHANGED
|
@@ -6,3 +6,4 @@
|
|
|
6
6
|
* alert are the caller's, this owns delivery and the honest verdict about it.
|
|
7
7
|
*/
|
|
8
8
|
export { postSlackAlert, type SlackAlertFailure, type SlackAlertOptions, type SlackAlertOutcome, type SlackFailureReason, } from './slack';
|
|
9
|
+
export { createGithubIssueAlertChannel, type GithubIssueAlertChannel, type GithubIssueAlertOptions, } from './github';
|
package/dist/alerting/index.js
CHANGED
|
@@ -1,7 +1,54 @@
|
|
|
1
1
|
import {
|
|
2
2
|
postSlackAlert
|
|
3
3
|
} from "../chunk-JRCZHDRG.js";
|
|
4
|
+
|
|
5
|
+
// src/alerting/github.ts
|
|
6
|
+
function createGithubIssueAlertChannel(options) {
|
|
7
|
+
const { owner, repo, label } = options;
|
|
8
|
+
const tokenName = options.tokenName ?? "GITHUB_ALERT_TOKEN";
|
|
9
|
+
async function request(path, init) {
|
|
10
|
+
const token = options.token();
|
|
11
|
+
if (!token) throw new Error(`${tokenName} is required to file a GitHub alert`);
|
|
12
|
+
const res = await fetch(`https://api.github.com${path}`, {
|
|
13
|
+
...init,
|
|
14
|
+
headers: {
|
|
15
|
+
Authorization: `Bearer ${token}`,
|
|
16
|
+
Accept: "application/vnd.github+json",
|
|
17
|
+
"X-GitHub-Api-Version": "2022-11-28",
|
|
18
|
+
"User-Agent": options.userAgent,
|
|
19
|
+
...init?.body ? { "Content-Type": "application/json" } : {},
|
|
20
|
+
...init?.headers ?? {}
|
|
21
|
+
}
|
|
22
|
+
});
|
|
23
|
+
if (!res.ok) {
|
|
24
|
+
const body = await res.text().catch(() => "");
|
|
25
|
+
throw new Error(`GitHub API ${init?.method ?? "GET"} ${path} failed (${res.status}): ${body.slice(0, 500)}`);
|
|
26
|
+
}
|
|
27
|
+
return await res.json();
|
|
28
|
+
}
|
|
29
|
+
return {
|
|
30
|
+
configured: () => Boolean(options.token()),
|
|
31
|
+
async file(title, body) {
|
|
32
|
+
const [existing] = await request(
|
|
33
|
+
`/repos/${owner}/${repo}/issues?state=open&labels=${encodeURIComponent(label)}&per_page=1`
|
|
34
|
+
);
|
|
35
|
+
if (existing) {
|
|
36
|
+
await request(`/repos/${owner}/${repo}/issues/${existing.number}/comments`, {
|
|
37
|
+
method: "POST",
|
|
38
|
+
body: JSON.stringify({ body })
|
|
39
|
+
});
|
|
40
|
+
return existing.html_url;
|
|
41
|
+
}
|
|
42
|
+
const created = await request(`/repos/${owner}/${repo}/issues`, {
|
|
43
|
+
method: "POST",
|
|
44
|
+
body: JSON.stringify({ title, body, labels: [label] })
|
|
45
|
+
});
|
|
46
|
+
return created.html_url;
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
}
|
|
4
50
|
export {
|
|
51
|
+
createGithubIssueAlertChannel,
|
|
5
52
|
postSlackAlert
|
|
6
53
|
};
|
|
7
54
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/alerting/github.ts"],"sourcesContent":["/**\n * A rolling GitHub-issue alert channel: the first alert files an issue under a\n * label, later alerts comment on the open one, so a persistent problem is one\n * thread a human can follow instead of a hundred issues nobody reads.\n *\n * The token is a fine-grained PAT scoped to Issues:write on the one repository,\n * read from the caller at each use so a Worker secret can rotate. Whether the\n * channel is configured is a separate question from whether a write succeeded,\n * so a caller can report \"the alert token is missing\" as its own state.\n */\n\nexport interface GithubIssueAlertOptions {\n owner: string\n repo: string\n /** The label that marks the rolling issue. */\n label: string\n /** The PAT, or undefined when the deployment has none. */\n token: () => string | undefined\n /** The User-Agent GitHub requires on every call. */\n userAgent: string\n /** The variable a missing token is reported under. */\n tokenName?: string\n}\n\nexport interface GithubIssueAlertChannel {\n /** Whether a token is configured, checked before an alert is composed. */\n configured(): boolean\n /**\n * Comment on the open labeled issue, or file one when none is open. Returns\n * the issue URL so the caller can record that the channel fired; throws when\n * the token is missing or GitHub refuses the write.\n */\n file(title: string, body: string): Promise<string>\n}\n\ninterface GithubIssue {\n readonly number: number\n readonly html_url: string\n}\n\nexport function createGithubIssueAlertChannel(options: GithubIssueAlertOptions): GithubIssueAlertChannel {\n const { owner, repo, label } = options\n const tokenName = options.tokenName ?? 'GITHUB_ALERT_TOKEN'\n\n async function request<T>(path: string, init?: RequestInit): Promise<T> {\n const token = options.token()\n if (!token) throw new Error(`${tokenName} is required to file a GitHub alert`)\n const res = await fetch(`https://api.github.com${path}`, {\n ...init,\n headers: {\n Authorization: `Bearer ${token}`,\n Accept: 'application/vnd.github+json',\n 'X-GitHub-Api-Version': '2022-11-28',\n 'User-Agent': options.userAgent,\n ...(init?.body ? { 'Content-Type': 'application/json' } : {}),\n ...(init?.headers ?? {}),\n },\n })\n if (!res.ok) {\n const body = await res.text().catch(() => '')\n throw new Error(`GitHub API ${init?.method ?? 'GET'} ${path} failed (${res.status}): ${body.slice(0, 500)}`)\n }\n return (await res.json()) as T\n }\n\n return {\n configured: () => Boolean(options.token()),\n async file(title, body) {\n const [existing] = await request<GithubIssue[]>(\n `/repos/${owner}/${repo}/issues?state=open&labels=${encodeURIComponent(label)}&per_page=1`,\n )\n if (existing) {\n await request(`/repos/${owner}/${repo}/issues/${existing.number}/comments`, {\n method: 'POST',\n body: JSON.stringify({ body }),\n })\n return existing.html_url\n }\n const created = await request<GithubIssue>(`/repos/${owner}/${repo}/issues`, {\n method: 'POST',\n body: JSON.stringify({ title, body, labels: [label] }),\n })\n return created.html_url\n },\n }\n}\n"],"mappings":";;;;;AAwCO,SAAS,8BAA8B,SAA2D;AACvG,QAAM,EAAE,OAAO,MAAM,MAAM,IAAI;AAC/B,QAAM,YAAY,QAAQ,aAAa;AAEvC,iBAAe,QAAW,MAAc,MAAgC;AACtE,UAAM,QAAQ,QAAQ,MAAM;AAC5B,QAAI,CAAC,MAAO,OAAM,IAAI,MAAM,GAAG,SAAS,qCAAqC;AAC7E,UAAM,MAAM,MAAM,MAAM,yBAAyB,IAAI,IAAI;AAAA,MACvD,GAAG;AAAA,MACH,SAAS;AAAA,QACP,eAAe,UAAU,KAAK;AAAA,QAC9B,QAAQ;AAAA,QACR,wBAAwB;AAAA,QACxB,cAAc,QAAQ;AAAA,QACtB,GAAI,MAAM,OAAO,EAAE,gBAAgB,mBAAmB,IAAI,CAAC;AAAA,QAC3D,GAAI,MAAM,WAAW,CAAC;AAAA,MACxB;AAAA,IACF,CAAC;AACD,QAAI,CAAC,IAAI,IAAI;AACX,YAAM,OAAO,MAAM,IAAI,KAAK,EAAE,MAAM,MAAM,EAAE;AAC5C,YAAM,IAAI,MAAM,cAAc,MAAM,UAAU,KAAK,IAAI,IAAI,YAAY,IAAI,MAAM,MAAM,KAAK,MAAM,GAAG,GAAG,CAAC,EAAE;AAAA,IAC7G;AACA,WAAQ,MAAM,IAAI,KAAK;AAAA,EACzB;AAEA,SAAO;AAAA,IACL,YAAY,MAAM,QAAQ,QAAQ,MAAM,CAAC;AAAA,IACzC,MAAM,KAAK,OAAO,MAAM;AACtB,YAAM,CAAC,QAAQ,IAAI,MAAM;AAAA,QACvB,UAAU,KAAK,IAAI,IAAI,6BAA6B,mBAAmB,KAAK,CAAC;AAAA,MAC/E;AACA,UAAI,UAAU;AACZ,cAAM,QAAQ,UAAU,KAAK,IAAI,IAAI,WAAW,SAAS,MAAM,aAAa;AAAA,UAC1E,QAAQ;AAAA,UACR,MAAM,KAAK,UAAU,EAAE,KAAK,CAAC;AAAA,QAC/B,CAAC;AACD,eAAO,SAAS;AAAA,MAClB;AACA,YAAM,UAAU,MAAM,QAAqB,UAAU,KAAK,IAAI,IAAI,WAAW;AAAA,QAC3E,QAAQ;AAAA,QACR,MAAM,KAAK,UAAU,EAAE,OAAO,MAAM,QAAQ,CAAC,KAAK,EAAE,CAAC;AAAA,MACvD,CAAC;AACD,aAAO,QAAQ;AAAA,IACjB;AAAA,EACF;AACF;","names":[]}
|
package/dist/app-auth/index.js
CHANGED
|
@@ -10,9 +10,8 @@ import "../chunk-DPTNKH22.js";
|
|
|
10
10
|
import "../chunk-RN4WPTBH.js";
|
|
11
11
|
import "../chunk-ALIWB2P3.js";
|
|
12
12
|
import "../chunk-D6UJEOZQ.js";
|
|
13
|
+
import "../chunk-V42C72V5.js";
|
|
13
14
|
import "../chunk-TXD5HXLE.js";
|
|
14
|
-
import "../chunk-6Z7TZVKZ.js";
|
|
15
|
-
import "../chunk-57XPEL7X.js";
|
|
16
15
|
|
|
17
16
|
// src/app-auth/index.ts
|
|
18
17
|
import { betterAuth } from "better-auth";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/app-auth/index.ts"],"sourcesContent":["/**\n * better-auth config factory for agent products (#188 Phase 1). Every product\n * hand-rolls the same ~70–150 line setup — drizzle adapter over the standard\n * users/sessions/accounts/verifications tables, email+password with branded\n * reset/verification mail (`./email`), env-gated GitHub/Google social providers, session\n * cookie cache, and a per-app cookie prefix — and tax additionally\n * re-implemented better-auth's cookie signing for its Tangle SSO callback.\n * `createAppAuth` owns that mechanism once and returns the configured\n * better-auth instance plus the request guards products actually use.\n *\n * Domain stays a parameter: the drizzle db + schema, email client, provider\n * credentials, and SSO store/client all come from the product. No product\n * import, no engine re-implementation — the SSO path composes the existing\n * `platform/sso` cookie minter (`createBetterAuthSessionCookieMinter`), which\n * is byte-compatible with better-auth's own `makeSignature` contract.\n *\n * better-auth is an OPTIONAL peer: only this subpath imports it, so it is\n * deliberately NOT re-exported from the root barrel.\n */\n\nimport { betterAuth, type Auth, type BetterAuthOptions, type Session, type User } from 'better-auth'\nimport { drizzleAdapter } from 'better-auth/adapters/drizzle'\nimport { noticeEmail, type EmailAttachment, type EmailMessage, type EmailProduct } from '../email'\nimport { createAuthGuard, type AuthGuard } from '../platform/guards'\nimport {\n createBetterAuthSessionCookieMinter,\n createTangleSsoHandlers,\n type TangleSsoAccountStore,\n type TangleSsoAuthClient,\n type TangleSsoHandlers,\n type TangleIdentitySsoAccountStore,\n type TangleIdentitySsoAuthClient,\n type TangleOidcSsoAccountStore,\n type TangleOidcSsoAuthClient,\n} from '../platform/sso'\n\nconst DEFAULT_STATE_COOKIE = 'tangle_sso_state'\nconst DEFAULT_SESSION_COOKIE_CACHE_SECONDS = 5 * 60\n\n/**\n * A full session read costs two serial database round trips (session, then\n * user), and a request often resolves it more than once. A resolved session is\n * reused within a request, and for at most SESSION_MEMO_MAX_MS across requests\n * in one isolate, keyed by the exact credentials sent. A reuse across requests\n * is never trusted on its own: every one re-reads the session row by its token\n * (one round trip instead of two), so a session revoked anywhere (sign-out,\n * revocation, a password change deleting the other sessions) is refused on the\n * next request in every isolate. Only when that row read fails is the\n * remembered session served, so a database error does not sign everyone out.\n * Any non-GET auth call in this isolate also clears the app's entries.\n */\nconst SESSION_MEMO_MAX_MS = 30_000\nconst SESSION_MEMO_LIMIT = 500\nconst requestSessions = new WeakMap<Request, Promise<AppAuthSession | null>>()\nconst isolateSessions = new Map<string, { until: number; session: AppAuthSession }>()\n// Bumped by forgetSessions, so a read that began before a sign-out cannot remember its result.\nconst scopeGenerations = new Map<string, number>()\n\n/** Whether a session row still exists and has not expired. Throws when the store cannot answer. */\ntype SessionRowCheck = (token: string) => Promise<boolean>\n\nfunction memoizedSession(scope: string, ttlMs: number, request: Request,\n read: (request: Request) => Promise<AppAuthSession | null>,\n isLive: SessionRowCheck,\n log: (message: string, meta: Record<string, unknown>) => void): Promise<AppAuthSession | null> {\n const known = requestSessions.get(request)\n if (known) return known\n const cookie = request.headers.get('cookie') ?? ''\n const authorization = request.headers.get('authorization') ?? ''\n if (!cookie && !authorization) return read(request)\n const key = `${scope}\\u0000${authorization}\\u0000${cookie}`\n const startedAt = Date.now()\n const hit = isolateSessions.get(key)\n if (hit && hit.until > startedAt) {\n const remembered = hit.session\n const checked = (async () => {\n const token = remembered.session.token\n if (!token) {\n // Nothing to check it against: never reuse it.\n if (isolateSessions.get(key) === hit) isolateSessions.delete(key)\n return read(request)\n }\n try {\n if (await isLive(token)) return remembered\n } catch (error) {\n // The store cannot answer: keep the session it verified moments ago.\n log('[app-auth] session row check failed; serving the remembered session', {\n error: error instanceof Error ? error.message : String(error),\n })\n return remembered\n }\n // Revoked or expired since it was remembered.\n if (isolateSessions.get(key) === hit) isolateSessions.delete(key)\n return null\n })()\n requestSessions.set(request, checked)\n return checked\n }\n // Only a resolved session is shared across requests, never a read in flight.\n // Workers ties a read's I/O to the request that started it: when that request\n // is cancelled (a navigation), the read never settles, and every other request\n // awaiting it hung until its client gave up (Hospitality production, 20.4-21.0 s).\n const generation = scopeGenerations.get(scope) ?? 0\n const session = read(request).then((value) => {\n const expiresAt = value ? new Date(value.session.expiresAt).getTime() : 0\n isolateSessions.delete(key)\n // Only a live session is reused; a miss or an expired session is read again next time.\n if (value && expiresAt > Date.now() && (scopeGenerations.get(scope) ?? 0) === generation) {\n isolateSessions.set(key, { until: Math.min(startedAt + ttlMs, expiresAt), session: value })\n if (isolateSessions.size > SESSION_MEMO_LIMIT) isolateSessions.delete(isolateSessions.keys().next().value!)\n }\n return value\n })\n requestSessions.set(request, session)\n return session\n}\n\nfunction forgetSessions(scope: string): void {\n scopeGenerations.set(scope, (scopeGenerations.get(scope) ?? 0) + 1)\n for (const key of isolateSessions.keys()) if (key.startsWith(`${scope}\\u0000`)) isolateSessions.delete(key)\n}\n\n/** Structural slice of a Resend-style client — no `resend` import. */\nexport interface AppAuthEmailClient {\n emails: {\n send(message: {\n from: string\n to: string\n subject: string\n html: string\n text?: string\n /** Inline images the HTML references by `cid:`, such as the Tangle mark. */\n attachments?: EmailAttachment[]\n }): Promise<unknown>\n }\n}\n\n/** Define email configuration for app authentication including client, sender, verification, and warning options */\nexport interface AppAuthEmailConfig {\n /** A Resend-style client, or a lazy getter returning null when the API key\n * is absent (the products' dev default — mail is skipped with a warning,\n * sign-up itself must not crash). */\n resend: AppAuthEmailClient | (() => AppAuthEmailClient | null)\n /** RFC 5322 From; build it with `emailSender` from `./email`, e.g. `Legal Agent · Tangle <noreply@tangle.tools>`. */\n from: string\n /** Send a verification email on sign-up and auto-sign-in after verifying\n * (the tax/gtm behavior). Default false (the legal behavior). */\n verifyOnSignUp?: boolean\n /** Receives the \"email client unavailable\" warning. Default console.warn. */\n warn?: (message: string) => void\n}\n\n/** Env-shaped: pass the env vars straight through; the provider is registered\n * only when BOTH values are non-empty, so unset env disables it. */\nexport interface AppAuthSocialProviderConfig {\n clientId?: string\n clientSecret?: string\n}\n\n/** Define social authentication configuration options for GitHub and Google providers */\nexport interface AppAuthSocialConfig {\n github?: AppAuthSocialProviderConfig\n google?: AppAuthSocialProviderConfig\n}\n\n/** Cross-site Tangle SSO wiring. The factory supplies the better-auth side —\n * `setSessionCookie` via `createBetterAuthSessionCookieMinter(auth)` (signed\n * `__Secure-`/prefixed cookie that `auth.api.getSession` accepts) — so the\n * product no longer touches `better-auth/crypto` itself. */\nexport interface AppAuthSsoConfig {\n protocol?: 'legacy'\n /** Platform wire client (authorizeUrl + exchange). */\n client: TangleSsoAuthClient\n /** Product persistence: user upsert, session row, platform link. */\n store: TangleSsoAccountStore\n /** Absolute callback URL registered with the platform. */\n callbackUrl: string\n /** Default 'tangle_sso_state'. */\n stateCookieName?: string\n /** HMAC secret for the CSRF state cookie. Default: the auth `secret`. */\n stateSecret?: string\n /** Default: `baseURL` is https. Must match better-auth's own\n * secure-cookie decision or the cookie name lookup diverges. */\n secureCookies?: boolean\n sessionTtlSeconds?: number\n stateTtlSeconds?: number\n /** Post-login redirect fallback. Default '/app'. */\n defaultRedirectPath?: string\n /** Default: the top-level `loginPath`. */\n loginPath?: string\n /** Failure log hook (e.g. console.error). Default no-op. */\n log?: (message: string, error?: unknown) => void\n}\n\n/** Registered OIDC client configuration. The caller supplies Runtime PKCE; login does not mint an API key. */\nexport interface AppAuthOidcSsoConfig extends Omit<AppAuthSsoConfig, 'protocol' | 'client' | 'store'> {\n protocol: 'oidc'\n client: TangleOidcSsoAuthClient\n store: TangleOidcSsoAccountStore\n /** Pass the Runtime's `createPkcePair` helper from the OIDC-only caller. */\n createPkcePair: () => Promise<{ verifier: string; challenge: string }>\n}\n\n/** First-party identity login; no Platform API key is issued or stored. */\nexport interface AppAuthIdentitySsoConfig extends Omit<AppAuthSsoConfig, 'protocol' | 'client' | 'store'> {\n protocol: 'identity'\n client: TangleIdentitySsoAuthClient\n store: TangleIdentitySsoAccountStore\n}\n\n/** Define the structure for application authentication data including users, sessions, accounts, and verifications */\nexport interface AppAuthSchema {\n users: unknown\n sessions: unknown\n accounts: unknown\n verifications: unknown\n}\n\n/** Define configuration settings for app authentication including app name, base URL, secrets, and trusted origins */\nexport interface AppAuthConfig {\n /** Product name — used in email subjects and as the cookie-prefix default. */\n appName: string\n /** Absolute origin better-auth serves from (`BETTER_AUTH_URL`). */\n baseURL: string\n /** better-auth HMAC secret. Optional only because better-auth falls back to\n * the BETTER_AUTH_SECRET env var; `sso` needs it explicitly (or\n * `sso.stateSecret`). */\n secret?: string\n trustedOrigins?: string[]\n /**\n * Session-cookie prefix. Default: slugified `appName`. A per-app prefix is\n * load-bearing, not cosmetic: the platform (id.tangle.tools) mints its own\n * better-auth cookie `Domain=.tangle.tools`-wide under the DEFAULT name, and\n * the platform's (older) cookie wins the Cookie-header order — an app on the\n * default prefix reads the platform's token, fails its own signature check,\n * and every fresh login lands back on /login.\n */\n cookiePrefix?: string\n /** Drizzle database instance; wired through better-auth's drizzle adapter\n * together with `schema`. */\n db?: unknown\n /** The product's users/sessions/accounts/verifications tables (mapped to\n * better-auth's user/session/account/verification models). */\n schema?: AppAuthSchema\n /** Drizzle dialect. Default 'sqlite' (D1). */\n provider?: 'sqlite' | 'pg' | 'mysql'\n /** Escape hatch: a pre-built better-auth database adapter (e.g.\n * `memoryAdapter` in tests). Wins over `db`/`schema`. */\n database?: BetterAuthOptions['database']\n /** Email+password sign-in. Default true (all current products enable it). */\n emailAndPassword?: boolean\n /** Revoke browser sessions when a password reset succeeds. Forwarded to Better Auth. */\n revokeSessionsOnPasswordReset?: boolean\n /** Reset/verification mail. Omit to disable password reset entirely. */\n email?: AppAuthEmailConfig\n social?: AppAuthSocialConfig\n /** How long, in seconds, one isolate reuses a verified session across\n * requests (capped at 30). Each reuse still re-reads the session row by its\n * token, so a revoked session is refused on the next request everywhere.\n * `false` reads the full session on every request. Default 300 (so 30). */\n sessionCookieCacheSeconds?: number | false\n /** Tangle cross-site SSO (start/callback handlers). */\n sso?: AppAuthSsoConfig | AppAuthOidcSsoConfig | AppAuthIdentitySsoConfig\n /** Where guards redirect unauthenticated page requests. Default '/login'. */\n loginPath?: string\n /** Merged over the factory's `advanced` block (cookiePrefix stays unless\n * overridden here). */\n advanced?: BetterAuthOptions['advanced']\n}\n\n/** The configured better-auth instance, typed at better-auth's base surface\n * (`handler`, `api`, `$context`, `$Infer`). */\nexport type AppAuthInstance = Auth\n\n/** What `getSession`/guards resolve: better-auth's base session + user rows. */\nexport interface AppAuthSession {\n session: Session\n user: User\n}\n\n/** Define authentication guard with session retrieval and optional SSO handlers for app requests */\nexport interface AppAuth extends AuthGuard<AppAuthSession> {\n auth: AppAuthInstance\n /** `auth.api.getSession` over a `Request` — the seam the guards consume. */\n getSession(request: Request): Promise<AppAuthSession | null>\n /** Tangle SSO start/callback handlers; null unless `sso` was configured. */\n sso: TangleSsoHandlers | null\n}\n\n/** Lowercased, non-alphanumerics collapsed to '-': `'Legal Agent'` → `'legal-agent'`. */\nfunction slugify(name: string): string {\n return name\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n}\n\nfunction emailProduct(config: AppAuthConfig): EmailProduct {\n return { name: config.appName, url: config.baseURL }\n}\n\nfunction resolveEmailClient(email: AppAuthEmailConfig): AppAuthEmailClient | null {\n return typeof email.resend === 'function' ? email.resend() : email.resend\n}\n\ntype DrizzleAuthAdapter = ReturnType<ReturnType<typeof drizzleAdapter>>\n\n/** Better Auth reads adapter identity during startup, before Workers inject D1.\n * Build the Drizzle adapter on its first database operation. */\nfunction deferDrizzleAdapter(\n db: Record<string, unknown>,\n config: Parameters<typeof drizzleAdapter>[1],\n): ReturnType<typeof drizzleAdapter> {\n return (options) => {\n let adapter: DrizzleAuthAdapter | undefined\n const resolve = () => (adapter ??= drizzleAdapter(db, config)(options))\n\n return {\n id: 'drizzle',\n create: (data) => resolve().create(data),\n findOne: (data) => resolve().findOne(data),\n findMany: (data) => resolve().findMany(data),\n count: (data) => resolve().count(data),\n update: (data) => resolve().update(data),\n updateMany: (data) => resolve().updateMany(data),\n delete: (data) => resolve().delete(data),\n deleteMany: (data) => resolve().deleteMany(data),\n consumeOne: (data) => resolve().consumeOne(data),\n incrementOne: (data) => resolve().incrementOne(data),\n transaction: (callback) => resolve().transaction(callback),\n }\n }\n}\n\n/** Resend reports failures in the resolved value, not by rejecting — surface\n * them loud so better-auth's flow (and the caller's logs) see the failure. */\nasync function sendEmail(client: AppAuthEmailClient, from: string, to: string, message: EmailMessage): Promise<void> {\n const { subject, html, text, attachments } = message\n const result = (await client.emails.send({ from, to, subject, html, text, attachments })) as\n | { error?: { message?: string } | null }\n | null\n | undefined\n if (result && typeof result === 'object' && result.error) {\n throw new Error(`[app-auth] email send failed: ${result.error.message ?? 'unknown error'}`)\n }\n}\n\nfunction resolveDatabase(config: AppAuthConfig): NonNullable<BetterAuthOptions['database']> {\n if (config.database) return config.database\n if (config.db && config.schema) {\n return deferDrizzleAdapter(config.db as Record<string, unknown>, {\n provider: config.provider ?? 'sqlite',\n schema: {\n user: config.schema.users,\n session: config.schema.sessions,\n account: config.schema.accounts,\n verification: config.schema.verifications,\n } as Record<string, unknown>,\n })\n }\n throw new Error(\n 'createAppAuth requires a database: pass `db` + `schema` (drizzle) or `database` (a better-auth adapter)',\n )\n}\n\nfunction resolveSocialProviders(social: AppAuthSocialConfig | undefined): BetterAuthOptions['socialProviders'] {\n const providers: NonNullable<BetterAuthOptions['socialProviders']> = {}\n if (social?.github?.clientId && social.github.clientSecret) {\n providers.github = { clientId: social.github.clientId, clientSecret: social.github.clientSecret }\n }\n if (social?.google?.clientId && social.google.clientSecret) {\n providers.google = { clientId: social.google.clientId, clientSecret: social.google.clientSecret }\n }\n return Object.keys(providers).length > 0 ? providers : undefined\n}\n\nfunction emailAndPasswordOptions(config: AppAuthConfig): BetterAuthOptions['emailAndPassword'] {\n const email = config.email\n const revocation = config.revokeSessionsOnPasswordReset === undefined\n ? {}\n : { revokeSessionsOnPasswordReset: config.revokeSessionsOnPasswordReset }\n if (!email) return { enabled: true, ...revocation }\n const warn = email.warn ?? ((message: string) => console.warn(message))\n return {\n enabled: true,\n ...revocation,\n sendResetPassword: async ({ user, url }) => {\n const client = resolveEmailClient(email)\n if (!client) {\n warn('[app-auth] email client unavailable — password reset email not sent')\n return\n }\n await sendEmail(client, email.from, user.email, noticeEmail(emailProduct(config), {\n subject: 'Reset your password',\n title: 'Reset your password',\n body: `Someone asked to reset the password for ${user.email}. If it was not you, ignore this email.`,\n action: { label: 'Reset password', url },\n showLink: true,\n note: 'This link expires in 1 hour.',\n footer: { reason: 'You received this because a password reset was requested for this address.' },\n }))\n },\n }\n}\n\nfunction emailVerificationOptions(config: AppAuthConfig): BetterAuthOptions['emailVerification'] {\n const email = config.email\n if (!email?.verifyOnSignUp) return undefined\n const warn = email.warn ?? ((message: string) => console.warn(message))\n return {\n sendOnSignUp: true,\n autoSignInAfterVerification: true,\n sendVerificationEmail: async ({ user, url }) => {\n const client = resolveEmailClient(email)\n if (!client) {\n warn('[app-auth] email client unavailable — verification email not sent')\n return\n }\n await sendEmail(client, email.from, user.email, noticeEmail(emailProduct(config), {\n subject: 'Verify your email',\n title: 'Verify your email',\n body: `Confirm ${user.email} to finish signing in to ${config.appName}.`,\n action: { label: 'Verify email', url },\n showLink: true,\n note: 'This link expires in 1 hour.',\n footer: { reason: `You received this because this address was used to sign in to ${config.appName}.` },\n }))\n },\n }\n}\n\n/**\n * Build the product's better-auth instance plus the request-boundary helpers:\n * `getSession` (Request → session|null), the `createAuthGuard` quartet\n * (`requireUser` 302, `requireApiUser` JSON 401, `requireSession`,\n * `getOptionalSession`), and — when `sso` is configured — the Tangle SSO\n * start/callback handlers with the session cookie minted through better-auth's\n * own name/attributes/signing (no `better-auth/crypto` in product code).\n */\nexport function createAppAuth(config: AppAuthConfig): AppAuth {\n if (!config.appName) throw new Error('createAppAuth: appName is required')\n if (!config.baseURL) throw new Error('createAppAuth: baseURL is required')\n\n const cookiePrefix = config.cookiePrefix ?? slugify(config.appName)\n if (!cookiePrefix) throw new Error('createAppAuth: cookiePrefix (or a slugifiable appName) is required')\n\n const socialProviders = resolveSocialProviders(config.social)\n const options: BetterAuthOptions = {\n appName: config.appName,\n baseURL: config.baseURL,\n ...(config.secret ? { secret: config.secret } : {}),\n ...(config.trustedOrigins ? { trustedOrigins: config.trustedOrigins } : {}),\n database: resolveDatabase(config),\n ...(config.emailAndPassword === false ? {} : { emailAndPassword: emailAndPasswordOptions(config) }),\n ...(config.email?.verifyOnSignUp ? { emailVerification: emailVerificationOptions(config) } : {}),\n ...(socialProviders ? { socialProviders } : {}),\n // better-auth's own session cookie cache answers from a signed cookie for\n // its whole maxAge, so a revoked session kept working for up to five\n // minutes on any client holding the cookie. It stays off; the per-isolate\n // reuse above re-checks the session row on every request instead.\n advanced: { cookiePrefix, ...config.advanced },\n }\n\n const auth: AppAuthInstance = betterAuth(options)\n // One indexed read of the session row by token: the revocation check for a\n // remembered session.\n const sessionRowIsLive: SessionRowCheck = async (token) => {\n const ctx = await (auth.$context as unknown as PromiseLike<{\n adapter: { findOne(args: { model: string; where: Array<{ field: string; value: unknown }> }): Promise<Record<string, unknown> | null> }\n }>)\n const row = await ctx.adapter.findOne({ model: 'session', where: [{ field: 'token', value: token }] })\n const expiresAt = row ? new Date(row.expiresAt as string | number | Date).getTime() : 0\n return expiresAt > Date.now()\n }\n\n const readSession = async (request: Request): Promise<AppAuthSession | null> => {\n const session = await auth.api.getSession({ headers: request.headers })\n return (session as AppAuthSession | null) ?? null\n }\n const memoMs = config.sessionCookieCacheSeconds === false ? 0\n : Math.min(SESSION_MEMO_MAX_MS, (config.sessionCookieCacheSeconds ?? DEFAULT_SESSION_COOKIE_CACHE_SECONDS) * 1000)\n const memoScope = `${config.baseURL}\\u0000${cookiePrefix}`\n const logSession = (message: string, meta: Record<string, unknown>) => console.warn(message, meta)\n const getSession = (request: Request): Promise<AppAuthSession | null> =>\n memoMs > 0 ? memoizedSession(memoScope, memoMs, request, readSession, sessionRowIsLive, logSession) : readSession(request)\n // Sign-out and session revocation drop this isolate's remembered sessions for the app.\n const handler = auth.handler\n auth.handler = async (request: Request) => {\n // In finally: a sign-out that fails after deleting the session must not leave it remembered.\n try { return await handler(request) }\n finally { if (request.method !== 'GET') forgetSessions(memoScope) }\n }\n\n const loginPath = config.loginPath ?? '/login'\n const guard = createAuthGuard<AppAuthSession>({ getSession, loginPath })\n\n let sso: TangleSsoHandlers | null = null\n if (config.sso) {\n const stateSecret = config.sso.stateSecret ?? config.secret\n if (!stateSecret) {\n throw new Error(\n 'createAppAuth: sso requires `secret` (or sso.stateSecret) — the signed-state CSRF cookie needs an HMAC secret',\n )\n }\n const transport = config.sso.protocol === 'oidc'\n ? { protocol: 'oidc' as const, auth: config.sso.client, store: config.sso.store, createPkcePair: config.sso.createPkcePair }\n : config.sso.protocol === 'identity'\n ? { protocol: 'identity' as const, auth: config.sso.client, store: config.sso.store }\n : { protocol: 'legacy' as const, auth: config.sso.client, store: config.sso.store }\n sso = createTangleSsoHandlers({\n ...transport,\n stateSecret,\n callbackUrl: config.sso.callbackUrl,\n stateCookieName: config.sso.stateCookieName ?? DEFAULT_STATE_COOKIE,\n setSessionCookie: createBetterAuthSessionCookieMinter(auth),\n secureCookies: config.sso.secureCookies ?? config.baseURL.startsWith('https:'),\n ...(config.sso.sessionTtlSeconds !== undefined ? { sessionTtlSeconds: config.sso.sessionTtlSeconds } : {}),\n ...(config.sso.stateTtlSeconds !== undefined ? { stateTtlSeconds: config.sso.stateTtlSeconds } : {}),\n ...(config.sso.defaultRedirectPath ? { defaultRedirectPath: config.sso.defaultRedirectPath } : {}),\n loginPath: config.sso.loginPath ?? loginPath,\n ...(config.sso.log ? { log: config.sso.log } : {}),\n })\n }\n\n return { auth, getSession, ...guard, sso }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAoBA,SAAS,kBAA8E;AACvF,SAAS,sBAAsB;AAe/B,IAAM,uBAAuB;AAC7B,IAAM,uCAAuC,IAAI;AAcjD,IAAM,sBAAsB;AAC5B,IAAM,qBAAqB;AAC3B,IAAM,kBAAkB,oBAAI,QAAiD;AAC7E,IAAM,kBAAkB,oBAAI,IAAwD;AAEpF,IAAM,mBAAmB,oBAAI,IAAoB;AAKjD,SAAS,gBAAgB,OAAe,OAAe,SACrD,MACA,QACA,KAA+F;AAC/F,QAAM,QAAQ,gBAAgB,IAAI,OAAO;AACzC,MAAI,MAAO,QAAO;AAClB,QAAM,SAAS,QAAQ,QAAQ,IAAI,QAAQ,KAAK;AAChD,QAAM,gBAAgB,QAAQ,QAAQ,I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AAI,aAAa,aACtB,EAAE,UAAU,YAAqB,MAAM,OAAO,IAAI,QAAQ,OAAO,OAAO,IAAI,MAAM,IACpF,EAAE,UAAU,UAAmB,MAAM,OAAO,IAAI,QAAQ,OAAO,OAAO,IAAI,MAAM;AACpF,UAAM,wBAAwB;AAAA,MAC5B,GAAG;AAAA,MACH;AAAA,MACA,aAAa,OAAO,IAAI;AAAA,MACxB,iBAAiB,OAAO,IAAI,mBAAmB;AAAA,MAC/C,kBAAkB,oCAAoC,IAAI;AAAA,MAC1D,eAAe,OAAO,IAAI,iBAAiB,OAAO,QAAQ,WAAW,QAAQ;AAAA,MAC7E,GAAI,OAAO,IAAI,sBAAsB,SAAY,EAAE,mBAAmB,OAAO,IAAI,kBAAkB,IAAI,CAAC;AAAA,MACxG,GAAI,OAAO,IAAI,oBAAoB,SAAY,EAAE,iBAAiB,OAAO,IAAI,gBAAgB,IAAI,CAAC;AAAA,MAClG,GAAI,OAAO,IAAI,sBAAsB,EAAE,qBAAqB,OAAO,IAAI,oBAAoB,IAAI,CAAC;AAAA,MAChG,WAAW,OAAO,IAAI,aAAa;AAAA,MACnC,GAAI,OAAO,IAAI,MAAM,EAAE,KAAK,OAAO,IAAI,IAAI,IAAI,CAAC;AAAA,IAClD,CAAC;AAAA,EACH;AAEA,SAAO,EAAE,MAAM,YAAY,GAAG,OAAO,IAAI;AAC3C;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/app-auth/index.ts"],"sourcesContent":["/**\n * better-auth config factory for agent products (#188 Phase 1). Every product\n * hand-rolls the same ~70–150 line setup — drizzle adapter over the standard\n * users/sessions/accounts/verifications tables, email+password with branded\n * reset/verification mail (`./email`), env-gated GitHub/Google social providers, session\n * cookie cache, and a per-app cookie prefix — and tax additionally\n * re-implemented better-auth's cookie signing for its Tangle SSO callback.\n * `createAppAuth` owns that mechanism once and returns the configured\n * better-auth instance plus the request guards products actually use.\n *\n * Domain stays a parameter: the drizzle db + schema, email client, provider\n * credentials, and SSO store/client all come from the product. No product\n * import, no engine re-implementation — the SSO path composes the existing\n * `platform/sso` cookie minter (`createBetterAuthSessionCookieMinter`), which\n * is byte-compatible with better-auth's own `makeSignature` contract.\n *\n * better-auth is an OPTIONAL peer: only this subpath imports it, so it is\n * deliberately NOT re-exported from the root barrel.\n */\n\nimport { betterAuth, type Auth, type BetterAuthOptions, type Session, type User } from 'better-auth'\nimport { drizzleAdapter } from 'better-auth/adapters/drizzle'\nimport { noticeEmail, type EmailAttachment, type EmailMessage, type EmailProduct } from '../email'\nimport { createAuthGuard, type AuthGuard } from '../platform/guards'\nimport {\n createBetterAuthSessionCookieMinter,\n createTangleSsoHandlers,\n type TangleSsoAccountStore,\n type TangleSsoAuthClient,\n type TangleSsoHandlers,\n type TangleIdentitySsoAccountStore,\n type TangleIdentitySsoAuthClient,\n type TangleOidcSsoAccountStore,\n type TangleOidcSsoAuthClient,\n} from '../platform/sso'\n\nconst DEFAULT_STATE_COOKIE = 'tangle_sso_state'\nconst DEFAULT_SESSION_COOKIE_CACHE_SECONDS = 5 * 60\n\n/**\n * A full session read costs two serial database round trips (session, then\n * user), and a request often resolves it more than once. A resolved session is\n * reused within a request, and for at most SESSION_MEMO_MAX_MS across requests\n * in one isolate, keyed by the exact credentials sent. A reuse across requests\n * is never trusted on its own: every one re-reads the session row by its token\n * (one round trip instead of two), so a session revoked anywhere (sign-out,\n * revocation, a password change deleting the other sessions) is refused on the\n * next request in every isolate. Only when that row read fails is the\n * remembered session served, so a database error does not sign everyone out.\n * Any non-GET auth call in this isolate also clears the app's entries.\n */\nconst SESSION_MEMO_MAX_MS = 30_000\nconst SESSION_MEMO_LIMIT = 500\nconst requestSessions = new WeakMap<Request, Promise<AppAuthSession | null>>()\nconst isolateSessions = new Map<string, { until: number; session: AppAuthSession }>()\n// Bumped by forgetSessions, so a read that began before a sign-out cannot remember its result.\nconst scopeGenerations = new Map<string, number>()\n\n/** Whether a session row still exists and has not expired. Throws when the store cannot answer. */\ntype SessionRowCheck = (token: string) => Promise<boolean>\n\nfunction memoizedSession(scope: string, ttlMs: number, request: Request,\n read: (request: Request) => Promise<AppAuthSession | null>,\n isLive: SessionRowCheck,\n log: (message: string, meta: Record<string, unknown>) => void): Promise<AppAuthSession | null> {\n const known = requestSessions.get(request)\n if (known) return known\n const cookie = request.headers.get('cookie') ?? ''\n const authorization = request.headers.get('authorization') ?? ''\n if (!cookie && !authorization) return read(request)\n const key = `${scope}\\u0000${authorization}\\u0000${cookie}`\n const startedAt = Date.now()\n const hit = isolateSessions.get(key)\n if (hit && hit.until > startedAt) {\n const remembered = hit.session\n const checked = (async () => {\n const token = remembered.session.token\n if (!token) {\n // Nothing to check it against: never reuse it.\n if (isolateSessions.get(key) === hit) isolateSessions.delete(key)\n return read(request)\n }\n try {\n if (await isLive(token)) return remembered\n } catch (error) {\n // The store cannot answer: keep the session it verified moments ago.\n log('[app-auth] session row check failed; serving the remembered session', {\n error: error instanceof Error ? error.message : String(error),\n })\n return remembered\n }\n // Revoked or expired since it was remembered.\n if (isolateSessions.get(key) === hit) isolateSessions.delete(key)\n return null\n })()\n requestSessions.set(request, checked)\n return checked\n }\n // Only a resolved session is shared across requests, never a read in flight.\n // Workers ties a read's I/O to the request that started it: when that request\n // is cancelled (a navigation), the read never settles, and every other request\n // awaiting it hung until its client gave up (Hospitality production, 20.4-21.0 s).\n const generation = scopeGenerations.get(scope) ?? 0\n const session = read(request).then((value) => {\n const expiresAt = value ? new Date(value.session.expiresAt).getTime() : 0\n isolateSessions.delete(key)\n // Only a live session is reused; a miss or an expired session is read again next time.\n if (value && expiresAt > Date.now() && (scopeGenerations.get(scope) ?? 0) === generation) {\n isolateSessions.set(key, { until: Math.min(startedAt + ttlMs, expiresAt), session: value })\n if (isolateSessions.size > SESSION_MEMO_LIMIT) isolateSessions.delete(isolateSessions.keys().next().value!)\n }\n return value\n })\n requestSessions.set(request, session)\n return session\n}\n\nfunction forgetSessions(scope: string): void {\n scopeGenerations.set(scope, (scopeGenerations.get(scope) ?? 0) + 1)\n for (const key of isolateSessions.keys()) if (key.startsWith(`${scope}\\u0000`)) isolateSessions.delete(key)\n}\n\n/** Structural slice of a Resend-style client — no `resend` import. */\nexport interface AppAuthEmailClient {\n emails: {\n send(message: {\n from: string\n to: string\n subject: string\n html: string\n text?: string\n /** Inline images the HTML references by `cid:`, such as the Tangle mark. */\n attachments?: EmailAttachment[]\n }): Promise<unknown>\n }\n}\n\n/** Define email configuration for app authentication including client, sender, verification, and warning options */\nexport interface AppAuthEmailConfig {\n /** A Resend-style client, or a lazy getter returning null when the API key\n * is absent (the products' dev default — mail is skipped with a warning,\n * sign-up itself must not crash). */\n resend: AppAuthEmailClient | (() => AppAuthEmailClient | null)\n /** RFC 5322 From; build it with `emailSender` from `./email`, e.g. `Legal Agent · Tangle <noreply@tangle.tools>`. */\n from: string\n /** Send a verification email on sign-up and auto-sign-in after verifying\n * (the tax/gtm behavior). Default false (the legal behavior). */\n verifyOnSignUp?: boolean\n /** Receives the \"email client unavailable\" warning. Default console.warn. */\n warn?: (message: string) => void\n}\n\n/** Env-shaped: pass the env vars straight through; the provider is registered\n * only when BOTH values are non-empty, so unset env disables it. */\nexport interface AppAuthSocialProviderConfig {\n clientId?: string\n clientSecret?: string\n}\n\n/** Define social authentication configuration options for GitHub and Google providers */\nexport interface AppAuthSocialConfig {\n github?: AppAuthSocialProviderConfig\n google?: AppAuthSocialProviderConfig\n}\n\n/** Cross-site Tangle SSO wiring. The factory supplies the better-auth side —\n * `setSessionCookie` via `createBetterAuthSessionCookieMinter(auth)` (signed\n * `__Secure-`/prefixed cookie that `auth.api.getSession` accepts) — so the\n * product no longer touches `better-auth/crypto` itself. */\nexport interface AppAuthSsoConfig {\n protocol?: 'legacy'\n /** Platform wire client (authorizeUrl + exchange). */\n client: TangleSsoAuthClient\n /** Product persistence: user upsert, session row, platform link. */\n store: TangleSsoAccountStore\n /** Absolute callback URL registered with the platform. */\n callbackUrl: string\n /** Default 'tangle_sso_state'. */\n stateCookieName?: string\n /** HMAC secret for the CSRF state cookie. Default: the auth `secret`. */\n stateSecret?: string\n /** Default: `baseURL` is https. Must match better-auth's own\n * secure-cookie decision or the cookie name lookup diverges. */\n secureCookies?: boolean\n sessionTtlSeconds?: number\n stateTtlSeconds?: number\n /** Post-login redirect fallback. Default '/app'. */\n defaultRedirectPath?: string\n /** Default: the top-level `loginPath`. */\n loginPath?: string\n /** Failure log hook (e.g. console.error). Default no-op. */\n log?: (message: string, error?: unknown) => void\n}\n\n/** Registered OIDC client configuration. The caller supplies Runtime PKCE; login does not mint an API key. */\nexport interface AppAuthOidcSsoConfig extends Omit<AppAuthSsoConfig, 'protocol' | 'client' | 'store'> {\n protocol: 'oidc'\n client: TangleOidcSsoAuthClient\n store: TangleOidcSsoAccountStore\n /** Pass the Runtime's `createPkcePair` helper from the OIDC-only caller. */\n createPkcePair: () => Promise<{ verifier: string; challenge: string }>\n}\n\n/** First-party identity login; no Platform API key is issued or stored. */\nexport interface AppAuthIdentitySsoConfig extends Omit<AppAuthSsoConfig, 'protocol' | 'client' | 'store'> {\n protocol: 'identity'\n client: TangleIdentitySsoAuthClient\n store: TangleIdentitySsoAccountStore\n}\n\n/** Define the structure for application authentication data including users, sessions, accounts, and verifications */\nexport interface AppAuthSchema {\n users: unknown\n sessions: unknown\n accounts: unknown\n verifications: unknown\n}\n\n/** Define configuration settings for app authentication including app name, base URL, secrets, and trusted origins */\nexport interface AppAuthConfig {\n /** Product name — used in email subjects and as the cookie-prefix default. */\n appName: string\n /** Absolute origin better-auth serves from (`BETTER_AUTH_URL`). */\n baseURL: string\n /** better-auth HMAC secret. Optional only because better-auth falls back to\n * the BETTER_AUTH_SECRET env var; `sso` needs it explicitly (or\n * `sso.stateSecret`). */\n secret?: string\n trustedOrigins?: string[]\n /**\n * Session-cookie prefix. Default: slugified `appName`. A per-app prefix is\n * load-bearing, not cosmetic: the platform (id.tangle.tools) mints its own\n * better-auth cookie `Domain=.tangle.tools`-wide under the DEFAULT name, and\n * the platform's (older) cookie wins the Cookie-header order — an app on the\n * default prefix reads the platform's token, fails its own signature check,\n * and every fresh login lands back on /login.\n */\n cookiePrefix?: string\n /** Drizzle database instance; wired through better-auth's drizzle adapter\n * together with `schema`. */\n db?: unknown\n /** The product's users/sessions/accounts/verifications tables (mapped to\n * better-auth's user/session/account/verification models). */\n schema?: AppAuthSchema\n /** Drizzle dialect. Default 'sqlite' (D1). */\n provider?: 'sqlite' | 'pg' | 'mysql'\n /** Escape hatch: a pre-built better-auth database adapter (e.g.\n * `memoryAdapter` in tests). Wins over `db`/`schema`. */\n database?: BetterAuthOptions['database']\n /** Email+password sign-in. Default true (all current products enable it). */\n emailAndPassword?: boolean\n /** Revoke browser sessions when a password reset succeeds. Forwarded to Better Auth. */\n revokeSessionsOnPasswordReset?: boolean\n /** Reset/verification mail. Omit to disable password reset entirely. */\n email?: AppAuthEmailConfig\n social?: AppAuthSocialConfig\n /** How long, in seconds, one isolate reuses a verified session across\n * requests (capped at 30). Each reuse still re-reads the session row by its\n * token, so a revoked session is refused on the next request everywhere.\n * `false` reads the full session on every request. Default 300 (so 30). */\n sessionCookieCacheSeconds?: number | false\n /** Tangle cross-site SSO (start/callback handlers). */\n sso?: AppAuthSsoConfig | AppAuthOidcSsoConfig | AppAuthIdentitySsoConfig\n /** Where guards redirect unauthenticated page requests. Default '/login'. */\n loginPath?: string\n /** Merged over the factory's `advanced` block (cookiePrefix stays unless\n * overridden here). */\n advanced?: BetterAuthOptions['advanced']\n}\n\n/** The configured better-auth instance, typed at better-auth's base surface\n * (`handler`, `api`, `$context`, `$Infer`). */\nexport type AppAuthInstance = Auth\n\n/** What `getSession`/guards resolve: better-auth's base session + user rows. */\nexport interface AppAuthSession {\n session: Session\n user: User\n}\n\n/** Define authentication guard with session retrieval and optional SSO handlers for app requests */\nexport interface AppAuth extends AuthGuard<AppAuthSession> {\n auth: AppAuthInstance\n /** `auth.api.getSession` over a `Request` — the seam the guards consume. */\n getSession(request: Request): Promise<AppAuthSession | null>\n /** Tangle SSO start/callback handlers; null unless `sso` was configured. */\n sso: TangleSsoHandlers | null\n}\n\n/** Lowercased, non-alphanumerics collapsed to '-': `'Legal Agent'` → `'legal-agent'`. */\nfunction slugify(name: string): string {\n return name\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n}\n\nfunction emailProduct(config: AppAuthConfig): EmailProduct {\n return { name: config.appName, url: config.baseURL }\n}\n\nfunction resolveEmailClient(email: AppAuthEmailConfig): AppAuthEmailClient | null {\n return typeof email.resend === 'function' ? email.resend() : email.resend\n}\n\ntype DrizzleAuthAdapter = ReturnType<ReturnType<typeof drizzleAdapter>>\n\n/** Better Auth reads adapter identity during startup, before Workers inject D1.\n * Build the Drizzle adapter on its first database operation. */\nfunction deferDrizzleAdapter(\n db: Record<string, unknown>,\n config: Parameters<typeof drizzleAdapter>[1],\n): ReturnType<typeof drizzleAdapter> {\n return (options) => {\n let adapter: DrizzleAuthAdapter | undefined\n const resolve = () => (adapter ??= drizzleAdapter(db, config)(options))\n\n return {\n id: 'drizzle',\n create: (data) => resolve().create(data),\n findOne: (data) => resolve().findOne(data),\n findMany: (data) => resolve().findMany(data),\n count: (data) => resolve().count(data),\n update: (data) => resolve().update(data),\n updateMany: (data) => resolve().updateMany(data),\n delete: (data) => resolve().delete(data),\n deleteMany: (data) => resolve().deleteMany(data),\n consumeOne: (data) => resolve().consumeOne(data),\n incrementOne: (data) => resolve().incrementOne(data),\n transaction: (callback) => resolve().transaction(callback),\n }\n }\n}\n\n/** Resend reports failures in the resolved value, not by rejecting — surface\n * them loud so better-auth's flow (and the caller's logs) see the failure. */\nasync function sendEmail(client: AppAuthEmailClient, from: string, to: string, message: EmailMessage): Promise<void> {\n const { subject, html, text, attachments } = message\n const result = (await client.emails.send({ from, to, subject, html, text, attachments })) as\n | { error?: { message?: string } | null }\n | null\n | undefined\n if (result && typeof result === 'object' && result.error) {\n throw new Error(`[app-auth] email send failed: ${result.error.message ?? 'unknown error'}`)\n }\n}\n\nfunction resolveDatabase(config: AppAuthConfig): NonNullable<BetterAuthOptions['database']> {\n if (config.database) return config.database\n if (config.db && config.schema) {\n return deferDrizzleAdapter(config.db as Record<string, unknown>, {\n provider: config.provider ?? 'sqlite',\n schema: {\n user: config.schema.users,\n session: config.schema.sessions,\n account: config.schema.accounts,\n verification: config.schema.verifications,\n } as Record<string, unknown>,\n })\n }\n throw new Error(\n 'createAppAuth requires a database: pass `db` + `schema` (drizzle) or `database` (a better-auth adapter)',\n )\n}\n\nfunction resolveSocialProviders(social: AppAuthSocialConfig | undefined): BetterAuthOptions['socialProviders'] {\n const providers: NonNullable<BetterAuthOptions['socialProviders']> = {}\n if (social?.github?.clientId && social.github.clientSecret) {\n providers.github = { clientId: social.github.clientId, clientSecret: social.github.clientSecret }\n }\n if (social?.google?.clientId && social.google.clientSecret) {\n providers.google = { clientId: social.google.clientId, clientSecret: social.google.clientSecret }\n }\n return Object.keys(providers).length > 0 ? providers : undefined\n}\n\nfunction emailAndPasswordOptions(config: AppAuthConfig): BetterAuthOptions['emailAndPassword'] {\n const email = config.email\n const revocation = config.revokeSessionsOnPasswordReset === undefined\n ? {}\n : { revokeSessionsOnPasswordReset: config.revokeSessionsOnPasswordReset }\n if (!email) return { enabled: true, ...revocation }\n const warn = email.warn ?? ((message: string) => console.warn(message))\n return {\n enabled: true,\n ...revocation,\n sendResetPassword: async ({ user, url }) => {\n const client = resolveEmailClient(email)\n if (!client) {\n warn('[app-auth] email client unavailable — password reset email not sent')\n return\n }\n await sendEmail(client, email.from, user.email, noticeEmail(emailProduct(config), {\n subject: 'Reset your password',\n title: 'Reset your password',\n body: `Someone asked to reset the password for ${user.email}. If it was not you, ignore this email.`,\n action: { label: 'Reset password', url },\n showLink: true,\n note: 'This link expires in 1 hour.',\n footer: { reason: 'You received this because a password reset was requested for this address.' },\n }))\n },\n }\n}\n\nfunction emailVerificationOptions(config: AppAuthConfig): BetterAuthOptions['emailVerification'] {\n const email = config.email\n if (!email?.verifyOnSignUp) return undefined\n const warn = email.warn ?? ((message: string) => console.warn(message))\n return {\n sendOnSignUp: true,\n autoSignInAfterVerification: true,\n sendVerificationEmail: async ({ user, url }) => {\n const client = resolveEmailClient(email)\n if (!client) {\n warn('[app-auth] email client unavailable — verification email not sent')\n return\n }\n await sendEmail(client, email.from, user.email, noticeEmail(emailProduct(config), {\n subject: 'Verify your email',\n title: 'Verify your email',\n body: `Confirm ${user.email} to finish signing in to ${config.appName}.`,\n action: { label: 'Verify email', url },\n showLink: true,\n note: 'This link expires in 1 hour.',\n footer: { reason: `You received this because this address was used to sign in to ${config.appName}.` },\n }))\n },\n }\n}\n\n/**\n * Build the product's better-auth instance plus the request-boundary helpers:\n * `getSession` (Request → session|null), the `createAuthGuard` quartet\n * (`requireUser` 302, `requireApiUser` JSON 401, `requireSession`,\n * `getOptionalSession`), and — when `sso` is configured — the Tangle SSO\n * start/callback handlers with the session cookie minted through better-auth's\n * own name/attributes/signing (no `better-auth/crypto` in product code).\n */\nexport function createAppAuth(config: AppAuthConfig): AppAuth {\n if (!config.appName) throw new Error('createAppAuth: appName is required')\n if (!config.baseURL) throw new Error('createAppAuth: baseURL is required')\n\n const cookiePrefix = config.cookiePrefix ?? slugify(config.appName)\n if (!cookiePrefix) throw new Error('createAppAuth: cookiePrefix (or a slugifiable appName) is required')\n\n const socialProviders = resolveSocialProviders(config.social)\n const options: BetterAuthOptions = {\n appName: config.appName,\n baseURL: config.baseURL,\n ...(config.secret ? { secret: config.secret } : {}),\n ...(config.trustedOrigins ? { trustedOrigins: config.trustedOrigins } : {}),\n database: resolveDatabase(config),\n ...(config.emailAndPassword === false ? {} : { emailAndPassword: emailAndPasswordOptions(config) }),\n ...(config.email?.verifyOnSignUp ? { emailVerification: emailVerificationOptions(config) } : {}),\n ...(socialProviders ? { socialProviders } : {}),\n // better-auth's own session cookie cache answers from a signed cookie for\n // its whole maxAge, so a revoked session kept working for up to five\n // minutes on any client holding the cookie. It stays off; the per-isolate\n // reuse above re-checks the session row on every request instead.\n advanced: { cookiePrefix, ...config.advanced },\n }\n\n const auth: AppAuthInstance = betterAuth(options)\n // One indexed read of the session row by token: the revocation check for a\n // remembered session.\n const sessionRowIsLive: SessionRowCheck = async (token) => {\n const ctx = await (auth.$context as unknown as PromiseLike<{\n adapter: { findOne(args: { model: string; where: Array<{ field: string; value: unknown }> }): Promise<Record<string, unknown> | null> }\n }>)\n const row = await ctx.adapter.findOne({ model: 'session', where: [{ field: 'token', value: token }] })\n const expiresAt = row ? new Date(row.expiresAt as string | number | Date).getTime() : 0\n return expiresAt > Date.now()\n }\n\n const readSession = async (request: Request): Promise<AppAuthSession | null> => {\n const session = await auth.api.getSession({ headers: request.headers })\n return (session as AppAuthSession | null) ?? null\n }\n const memoMs = config.sessionCookieCacheSeconds === false ? 0\n : Math.min(SESSION_MEMO_MAX_MS, (config.sessionCookieCacheSeconds ?? DEFAULT_SESSION_COOKIE_CACHE_SECONDS) * 1000)\n const memoScope = `${config.baseURL}\\u0000${cookiePrefix}`\n const logSession = (message: string, meta: Record<string, unknown>) => console.warn(message, meta)\n const getSession = (request: Request): Promise<AppAuthSession | null> =>\n memoMs > 0 ? memoizedSession(memoScope, memoMs, request, readSession, sessionRowIsLive, logSession) : readSession(request)\n // Sign-out and session revocation drop this isolate's remembered sessions for the app.\n const handler = auth.handler\n auth.handler = async (request: Request) => {\n // In finally: a sign-out that fails after deleting the session must not leave it remembered.\n try { return await handler(request) }\n finally { if (request.method !== 'GET') forgetSessions(memoScope) }\n }\n\n const loginPath = config.loginPath ?? '/login'\n const guard = createAuthGuard<AppAuthSession>({ getSession, loginPath })\n\n let sso: TangleSsoHandlers | null = null\n if (config.sso) {\n const stateSecret = config.sso.stateSecret ?? config.secret\n if (!stateSecret) {\n throw new Error(\n 'createAppAuth: sso requires `secret` (or sso.stateSecret) — the signed-state CSRF cookie needs an HMAC secret',\n )\n }\n const transport = config.sso.protocol === 'oidc'\n ? { protocol: 'oidc' as const, auth: config.sso.client, store: config.sso.store, createPkcePair: config.sso.createPkcePair }\n : config.sso.protocol === 'identity'\n ? { protocol: 'identity' as const, auth: config.sso.client, store: config.sso.store }\n : { protocol: 'legacy' as const, auth: config.sso.client, store: config.sso.store }\n sso = createTangleSsoHandlers({\n ...transport,\n stateSecret,\n callbackUrl: config.sso.callbackUrl,\n stateCookieName: config.sso.stateCookieName ?? DEFAULT_STATE_COOKIE,\n setSessionCookie: createBetterAuthSessionCookieMinter(auth),\n secureCookies: config.sso.secureCookies ?? config.baseURL.startsWith('https:'),\n ...(config.sso.sessionTtlSeconds !== undefined ? { sessionTtlSeconds: config.sso.sessionTtlSeconds } : {}),\n ...(config.sso.stateTtlSeconds !== undefined ? { stateTtlSeconds: config.sso.stateTtlSeconds } : {}),\n ...(config.sso.defaultRedirectPath ? { defaultRedirectPath: config.sso.defaultRedirectPath } : {}),\n loginPath: config.sso.loginPath ?? loginPath,\n ...(config.sso.log ? { log: config.sso.log } : {}),\n })\n }\n\n return { auth, getSession, ...guard, sso }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAoBA,SAAS,kBAA8E;AACvF,SAAS,sBAAsB;AAe/B,IAAM,uBAAuB;AAC7B,IAAM,uCAAuC,IAAI;AAcjD,IAAM,sBAAsB;AAC5B,IAAM,qBAAqB;AAC3B,IAAM,kBAAkB,oBAAI,QAAiD;AAC7E,IAAM,kBAAkB,oBAAI,IAAwD;AAEpF,IAAM,mBAAmB,oBAAI,IAAoB;AAKjD,SAAS,gBAAgB,OAAe,OAAe,SACrD,MACA,QACA,KAA+F;AAC/F,QAAM,QAAQ,gBAAgB,IAAI,OAAO;AACzC,MAAI,MAAO,QAAO;AAClB,QAAM,SAAS,QAAQ,QAAQ,IAAI,QAAQ,KAAK;AAChD,QAAM,gBAAgB,QAAQ,QAAQ,IAAI,eAAe,KAAK;AAC9D,MAAI,CAAC,UAAU,CAAC,cAAe,QAAO,KAAK,OAAO;AAClD,QAAM,MAAM,GAAG,KAAK,KAAS,aAAa,KAAS,MAAM;AACzD,QAA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OAAO,OAAO,IAAI,MAAM;AACpF,UAAM,wBAAwB;AAAA,MAC5B,GAAG;AAAA,MACH;AAAA,MACA,aAAa,OAAO,IAAI;AAAA,MACxB,iBAAiB,OAAO,IAAI,mBAAmB;AAAA,MAC/C,kBAAkB,oCAAoC,IAAI;AAAA,MAC1D,eAAe,OAAO,IAAI,iBAAiB,OAAO,QAAQ,WAAW,QAAQ;AAAA,MAC7E,GAAI,OAAO,IAAI,sBAAsB,SAAY,EAAE,mBAAmB,OAAO,IAAI,kBAAkB,IAAI,CAAC;AAAA,MACxG,GAAI,OAAO,IAAI,oBAAoB,SAAY,EAAE,iBAAiB,OAAO,IAAI,gBAAgB,IAAI,CAAC;AAAA,MAClG,GAAI,OAAO,IAAI,sBAAsB,EAAE,qBAAqB,OAAO,IAAI,oBAAoB,IAAI,CAAC;AAAA,MAChG,WAAW,OAAO,IAAI,aAAa;AAAA,MACnC,GAAI,OAAO,IAAI,MAAM,EAAE,KAAK,OAAO,IAAI,IAAI,IAAI,CAAC;AAAA,IAClD,CAAC;AAAA,EACH;AAEA,SAAO,EAAE,MAAM,YAAY,GAAG,OAAO,IAAI;AAC3C;","names":[]}
|
package/dist/assistant/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
ReasoningRow,
|
|
3
3
|
chatToolCallPart
|
|
4
|
-
} from "../chunk-
|
|
4
|
+
} from "../chunk-AZRPDSRQ.js";
|
|
5
5
|
import "../chunk-UHSUY6H6.js";
|
|
6
6
|
import "../chunk-3HUFJ5LO.js";
|
|
7
7
|
import "../chunk-7PULOECS.js";
|
|
@@ -32,16 +32,16 @@ import "../chunk-RASGKEAL.js";
|
|
|
32
32
|
import "../chunk-FQYAJYPW.js";
|
|
33
33
|
import "../chunk-P7UB7ZVP.js";
|
|
34
34
|
import "../chunk-B7CL7ENS.js";
|
|
35
|
-
import "../chunk-
|
|
35
|
+
import "../chunk-CRZXEKCX.js";
|
|
36
36
|
import "../chunk-ZVEEWGDK.js";
|
|
37
|
-
import "../chunk-
|
|
37
|
+
import "../chunk-ZNWJJRHP.js";
|
|
38
38
|
import "../chunk-SRZTL3Z5.js";
|
|
39
39
|
import "../chunk-QGJOT6R6.js";
|
|
40
40
|
import "../chunk-AMUXRAUO.js";
|
|
41
41
|
import "../chunk-PV33JZKV.js";
|
|
42
42
|
import "../chunk-ELX5YITO.js";
|
|
43
|
+
import "../chunk-4PIN6QYQ.js";
|
|
43
44
|
import "../chunk-TXD5HXLE.js";
|
|
44
|
-
import "../chunk-WL7PZK7Q.js";
|
|
45
45
|
|
|
46
46
|
// src/assistant/sse.ts
|
|
47
47
|
var SSEChunkParser = class {
|
package/dist/billing/index.d.ts
CHANGED
|
@@ -199,6 +199,21 @@ export interface SharedBillingState<Plan extends string> {
|
|
|
199
199
|
concurrency: number;
|
|
200
200
|
overageAllowed: boolean;
|
|
201
201
|
}
|
|
202
|
+
/** Reads one platform key's plan and balance for {@link readSharedBillingState}. */
|
|
203
|
+
export interface SharedBillingReads<Plan extends string> {
|
|
204
|
+
getPlan(apiKey: string): Promise<Plan>;
|
|
205
|
+
getBalance(apiKey: string): Promise<PlatformBalanceInfo>;
|
|
206
|
+
/** Plan → limits map (the product's pricing). */
|
|
207
|
+
planLimits: Record<Plan, PlanLimit>;
|
|
208
|
+
/** The plan a key-less user falls to. */
|
|
209
|
+
freePlan: Plan;
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* The plan, limits and balance behind one platform key. No key means the user
|
|
213
|
+
* is not linked: the free plan with zero balance, and no read is issued with
|
|
214
|
+
* an empty key.
|
|
215
|
+
*/
|
|
216
|
+
export declare function readSharedBillingState<Plan extends string>(apiKey: string | null | undefined, reads: SharedBillingReads<Plan>): Promise<Omit<SharedBillingState<Plan>, 'platformUserId'>>;
|
|
202
217
|
/** Define configuration options for managing platform balance based on billing plans */
|
|
203
218
|
export interface PlatformBalanceManagerOptions<Plan extends string> {
|
|
204
219
|
client: PlatformBillingClient<Plan>;
|
package/dist/billing/index.js
CHANGED
|
@@ -2,13 +2,15 @@ import {
|
|
|
2
2
|
createIdentityBoundWorkspaceKeyManager,
|
|
3
3
|
createPlatformBalanceManager,
|
|
4
4
|
createTcloudKeyProvisioner,
|
|
5
|
-
createWorkspaceKeyManager
|
|
6
|
-
|
|
5
|
+
createWorkspaceKeyManager,
|
|
6
|
+
readSharedBillingState
|
|
7
|
+
} from "../chunk-2SDX3OC4.js";
|
|
7
8
|
import "../chunk-VGS2NXLB.js";
|
|
8
9
|
export {
|
|
9
10
|
createIdentityBoundWorkspaceKeyManager,
|
|
10
11
|
createPlatformBalanceManager,
|
|
11
12
|
createTcloudKeyProvisioner,
|
|
12
|
-
createWorkspaceKeyManager
|
|
13
|
+
createWorkspaceKeyManager,
|
|
14
|
+
readSharedBillingState
|
|
13
15
|
};
|
|
14
16
|
//# sourceMappingURL=index.js.map
|