@tangle-network/agent-app 0.60.6 → 0.60.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/dist/{DesignCanvas-OWE67ZX3.js → DesignCanvas-TW45DTK7.js} +3 -2
  2. package/dist/{DesignCanvasEditor-4FPLJ3YJ.js → DesignCanvasEditor-3DL3PF6P.js} +3 -2
  3. package/dist/agent-surfaces/cli.d.ts +2 -0
  4. package/dist/agent-surfaces/cli.js +49 -0
  5. package/dist/agent-surfaces/cli.js.map +1 -0
  6. package/dist/agent-surfaces/generate.d.ts +1 -0
  7. package/dist/agent-surfaces/index.d.ts +139 -0
  8. package/dist/agent-surfaces/index.js +27 -0
  9. package/dist/agent-surfaces/index.js.map +1 -0
  10. package/dist/app-auth/index.js +2 -1
  11. package/dist/app-auth/index.js.map +1 -1
  12. package/dist/assistant/index.js +4 -4
  13. package/dist/chat-routes/index.js +2 -1
  14. package/dist/chat-routes/index.js.map +1 -1
  15. package/dist/{chunk-DWUSVC3U.js → chunk-AKC5ZC4R.js} +3 -3
  16. package/dist/chunk-C5RHSYUA.js +376 -0
  17. package/dist/chunk-C5RHSYUA.js.map +1 -0
  18. package/dist/chunk-MLDKEEFQ.js +48 -0
  19. package/dist/chunk-MLDKEEFQ.js.map +1 -0
  20. package/dist/{chunk-GJRGCVDV.js → chunk-MUZQUS6X.js} +236 -187
  21. package/dist/chunk-MUZQUS6X.js.map +1 -0
  22. package/dist/chunk-RN4WPTBH.js +62 -0
  23. package/dist/chunk-RN4WPTBH.js.map +1 -0
  24. package/dist/{chunk-YNSPVKMS.js → chunk-UTAIRVOK.js} +1 -60
  25. package/dist/chunk-UTAIRVOK.js.map +1 -0
  26. package/dist/design-canvas/index.js +2 -1
  27. package/dist/design-canvas/index.js.map +1 -1
  28. package/dist/design-canvas-react/engine.js +2 -1
  29. package/dist/design-canvas-react/index.js +6 -5
  30. package/dist/design-canvas-react/index.js.map +1 -1
  31. package/dist/design-canvas-react/lazy.js +1 -1
  32. package/dist/operator/client.d.ts +76 -0
  33. package/dist/operator/contract.d.ts +255 -0
  34. package/dist/operator/index.d.ts +8 -0
  35. package/dist/operator/index.js +533 -0
  36. package/dist/operator/index.js.map +1 -0
  37. package/dist/operator/server.d.ts +101 -0
  38. package/dist/platform/index.js +5 -45
  39. package/dist/platform/index.js.map +1 -1
  40. package/dist/public-consultation/index.d.ts +1 -1
  41. package/dist/public-consultation/index.js +2 -1
  42. package/dist/public-consultation/index.js.map +1 -1
  43. package/dist/sequences/index.js +2 -1
  44. package/dist/sequences/index.js.map +1 -1
  45. package/dist/web/index.js +4 -2
  46. package/dist/web-react/agent-setup-block.d.ts +16 -0
  47. package/dist/web-react/index.d.ts +1 -0
  48. package/dist/web-react/index.js +12 -10
  49. package/package.json +12 -1
  50. package/dist/chunk-GJRGCVDV.js.map +0 -1
  51. package/dist/chunk-YNSPVKMS.js.map +0 -1
  52. /package/dist/{DesignCanvas-OWE67ZX3.js.map → DesignCanvas-TW45DTK7.js.map} +0 -0
  53. /package/dist/{DesignCanvasEditor-4FPLJ3YJ.js.map → DesignCanvasEditor-3DL3PF6P.js.map} +0 -0
  54. /package/dist/{chunk-DWUSVC3U.js.map → chunk-AKC5ZC4R.js.map} +0 -0
@@ -3,10 +3,11 @@ import {
3
3
  } from "./chunk-DKHM4B4A.js";
4
4
  import "./chunk-6NYVAURR.js";
5
5
  import "./chunk-OHWQUKBP.js";
6
- import "./chunk-YNSPVKMS.js";
6
+ import "./chunk-UTAIRVOK.js";
7
+ import "./chunk-RN4WPTBH.js";
7
8
  import "./chunk-3NCPXNBZ.js";
8
9
  import "./chunk-TXD5HXLE.js";
9
10
  export {
10
11
  DesignCanvas
11
12
  };
12
- //# sourceMappingURL=DesignCanvas-OWE67ZX3.js.map
13
+ //# sourceMappingURL=DesignCanvas-TW45DTK7.js.map
@@ -6,10 +6,11 @@ import "./chunk-VUXCM5ZO.js";
6
6
  import "./chunk-CFGA7PXM.js";
7
7
  import "./chunk-6NYVAURR.js";
8
8
  import "./chunk-OHWQUKBP.js";
9
- import "./chunk-YNSPVKMS.js";
9
+ import "./chunk-UTAIRVOK.js";
10
+ import "./chunk-RN4WPTBH.js";
10
11
  import "./chunk-3NCPXNBZ.js";
11
12
  import "./chunk-TXD5HXLE.js";
12
13
  export {
13
14
  DesignCanvasEditor
14
15
  };
15
- //# sourceMappingURL=DesignCanvasEditor-4FPLJ3YJ.js.map
16
+ //# sourceMappingURL=DesignCanvasEditor-3DL3PF6P.js.map
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,49 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ agentSurfaceFiles
4
+ } from "../chunk-C5RHSYUA.js";
5
+
6
+ // src/agent-surfaces/generate.ts
7
+ import { mkdirSync, readFileSync, writeFileSync } from "fs";
8
+ import { dirname, join, resolve } from "path";
9
+ function readExisting(path) {
10
+ try {
11
+ return readFileSync(path, "utf8");
12
+ } catch {
13
+ return void 0;
14
+ }
15
+ }
16
+ function runAgentSurfacesCli(argv) {
17
+ const [configPath, ...rest] = argv;
18
+ const outIndex = rest.indexOf("--out");
19
+ const outDir = outIndex >= 0 ? rest[outIndex + 1] : void 0;
20
+ const check = rest.includes("--check");
21
+ if (!configPath || !outDir) {
22
+ console.error("Usage: agent-app-agent-surfaces <config.json> --out <dir> [--check]");
23
+ return 2;
24
+ }
25
+ const config = JSON.parse(readFileSync(resolve(configPath), "utf8"));
26
+ const stale = [];
27
+ for (const file of agentSurfaceFiles(config)) {
28
+ const target = join(resolve(outDir), file.path);
29
+ if (readExisting(target) === file.body) continue;
30
+ if (check) {
31
+ stale.push(file.path);
32
+ continue;
33
+ }
34
+ mkdirSync(dirname(target), { recursive: true });
35
+ writeFileSync(target, file.body);
36
+ console.log(`wrote ${file.path}`);
37
+ }
38
+ if (stale.length > 0) {
39
+ console.error(
40
+ `Agent surfaces are stale: ${stale.join(", ")}. Regenerate with: agent-app-agent-surfaces ${configPath} --out ${outDir}`
41
+ );
42
+ return 1;
43
+ }
44
+ return 0;
45
+ }
46
+
47
+ // src/agent-surfaces/cli.ts
48
+ process.exit(runAgentSurfacesCli(process.argv.slice(2)));
49
+ //# sourceMappingURL=cli.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/agent-surfaces/generate.ts","../../src/agent-surfaces/cli.ts"],"sourcesContent":["/**\n * Writes or checks a product's agent surfaces as static files. Node-only; the\n * `agent-app-agent-surfaces` bin wraps it.\n */\nimport { mkdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { dirname, join, resolve } from 'node:path'\nimport { type AgentSurfaceConfig, agentSurfaceFiles } from './index'\n\nfunction readExisting(path: string): string | undefined {\n try {\n return readFileSync(path, 'utf8')\n } catch {\n return undefined\n }\n}\n\nexport function runAgentSurfacesCli(argv: readonly string[]): number {\n const [configPath, ...rest] = argv\n const outIndex = rest.indexOf('--out')\n const outDir = outIndex >= 0 ? rest[outIndex + 1] : undefined\n const check = rest.includes('--check')\n if (!configPath || !outDir) {\n console.error('Usage: agent-app-agent-surfaces <config.json> --out <dir> [--check]')\n return 2\n }\n const config = JSON.parse(readFileSync(resolve(configPath), 'utf8')) as AgentSurfaceConfig\n const stale: string[] = []\n for (const file of agentSurfaceFiles(config)) {\n const target = join(resolve(outDir), file.path)\n if (readExisting(target) === file.body) continue\n if (check) {\n stale.push(file.path)\n continue\n }\n mkdirSync(dirname(target), { recursive: true })\n writeFileSync(target, file.body)\n console.log(`wrote ${file.path}`)\n }\n if (stale.length > 0) {\n console.error(\n `Agent surfaces are stale: ${stale.join(', ')}. Regenerate with: agent-app-agent-surfaces ${configPath} --out ${outDir}`,\n )\n return 1\n }\n return 0\n}\n\n","#!/usr/bin/env node\n/**\n * `agent-app-agent-surfaces <config.json> --out <dir> [--check]`\n *\n * Writes a product's agent surfaces as static files, for products that serve\n * them as assets. `--check` writes nothing and exits 1 when a committed file\n * differs from what the config generates, so product docs cannot drift from\n * the shared source. Exit 2 is a usage error.\n */\nimport { runAgentSurfacesCli } from './generate'\n\nprocess.exit(runAgentSurfacesCli(process.argv.slice(2)))\n"],"mappings":";;;;;;AAIA,SAAS,WAAW,cAAc,qBAAqB;AACvD,SAAS,SAAS,MAAM,eAAe;AAGvC,SAAS,aAAa,MAAkC;AACtD,MAAI;AACF,WAAO,aAAa,MAAM,MAAM;AAAA,EAClC,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEO,SAAS,oBAAoB,MAAiC;AACnE,QAAM,CAAC,YAAY,GAAG,IAAI,IAAI;AAC9B,QAAM,WAAW,KAAK,QAAQ,OAAO;AACrC,QAAM,SAAS,YAAY,IAAI,KAAK,WAAW,CAAC,IAAI;AACpD,QAAM,QAAQ,KAAK,SAAS,SAAS;AACrC,MAAI,CAAC,cAAc,CAAC,QAAQ;AAC1B,YAAQ,MAAM,qEAAqE;AACnF,WAAO;AAAA,EACT;AACA,QAAM,SAAS,KAAK,MAAM,aAAa,QAAQ,UAAU,GAAG,MAAM,CAAC;AACnE,QAAM,QAAkB,CAAC;AACzB,aAAW,QAAQ,kBAAkB,MAAM,GAAG;AAC5C,UAAM,SAAS,KAAK,QAAQ,MAAM,GAAG,KAAK,IAAI;AAC9C,QAAI,aAAa,MAAM,MAAM,KAAK,KAAM;AACxC,QAAI,OAAO;AACT,YAAM,KAAK,KAAK,IAAI;AACpB;AAAA,IACF;AACA,cAAU,QAAQ,MAAM,GAAG,EAAE,WAAW,KAAK,CAAC;AAC9C,kBAAc,QAAQ,KAAK,IAAI;AAC/B,YAAQ,IAAI,SAAS,KAAK,IAAI,EAAE;AAAA,EAClC;AACA,MAAI,MAAM,SAAS,GAAG;AACpB,YAAQ;AAAA,MACN,6BAA6B,MAAM,KAAK,IAAI,CAAC,+CAA+C,UAAU,UAAU,MAAM;AAAA,IACxH;AACA,WAAO;AAAA,EACT;AACA,SAAO;AACT;;;AClCA,QAAQ,KAAK,oBAAoB,QAAQ,KAAK,MAAM,CAAC,CAAC,CAAC;","names":[]}
@@ -0,0 +1 @@
1
+ export declare function runAgentSurfacesCli(argv: readonly string[]): number;
@@ -0,0 +1,139 @@
1
+ /**
2
+ * Machine-readable surfaces for a Tangle product, generated from one config.
3
+ *
4
+ * Every product publishes the same four things an AI agent needs to become a
5
+ * customer without a human doing the setup:
6
+ *
7
+ * - `/agent-setup.md`: a SKILL.md (Claude Code and Codex skill format) that
8
+ * doubles as a copy-paste prompt. It takes a fresh agent from nothing to a
9
+ * verified first call: one owner approval, a scoped key, install, call.
10
+ * - `/llms.txt`: the llms.txt index, pointing at the setup skill first.
11
+ * - `/.well-known/tangle-agent.json`: the Tangle agent manifest.
12
+ * - Markdown for `Accept: text/markdown` on the product's pages, with
13
+ * `Vary: Accept` on both representations so caches keep them apart.
14
+ *
15
+ * The signup section is rendered here, not in product config, so every
16
+ * product describes Platform's agent signup identically and cannot drift.
17
+ *
18
+ * Web-standard `Request`/`Response` only: safe in Workers, Node and browsers.
19
+ */
20
+ /** Manifest schema this module emits. Additive over the 2026-06-16 shape. */
21
+ export declare const AGENT_MANIFEST_SCHEMA_VERSION = "2026-10-09";
22
+ export declare const TANGLE_PLATFORM_ORIGIN = "https://id.tangle.tools";
23
+ export interface AgentSurfaceStep {
24
+ title: string;
25
+ /** Fence language for the code block. */
26
+ language: 'bash' | 'js' | 'ts' | 'python' | 'json';
27
+ code: string;
28
+ /** What a successful run prints or returns. */
29
+ expect: string;
30
+ }
31
+ export interface AgentSurfaceError {
32
+ symptom: string;
33
+ cause: string;
34
+ fix: string;
35
+ }
36
+ export interface AgentSurfaceLink {
37
+ label: string;
38
+ url: string;
39
+ }
40
+ /**
41
+ * How an agent obtains a key. `device` uses Platform's agent signup: the owner
42
+ * approves once and the agent receives its own capped, revocable key.
43
+ */
44
+ export type AgentSignup = {
45
+ kind: 'device';
46
+ /** Platform trusted-app id the key is minted for (`sandbox`, `router`). */
47
+ app: string;
48
+ /** Default lifetime spend cap the skill asks for, in USD. */
49
+ budgetUsd?: number;
50
+ } | {
51
+ kind: 'manual';
52
+ /** Numbered steps the owner performs; each one is a human input. */
53
+ steps: string[];
54
+ };
55
+ export interface AgentSurfaceConfig {
56
+ /** Short id used in the skill name: `tangle-<id>-setup`. */
57
+ id: string;
58
+ name: string;
59
+ /** Public HTTPS origin, no trailing slash. */
60
+ origin: string;
61
+ /** What the product is for, in one to three plain sentences. */
62
+ summary: string;
63
+ useWhen: string[];
64
+ signup: AgentSignup;
65
+ /** Environment variable the key is exported as. */
66
+ apiKeyEnv: string;
67
+ /** Runtime prerequisites a fresh machine needs, e.g. `Node.js 20 or newer`. */
68
+ prerequisites: string[];
69
+ install: AgentSurfaceStep[];
70
+ firstCall: AgentSurfaceStep[];
71
+ verify: AgentSurfaceStep[];
72
+ errors: AgentSurfaceError[];
73
+ pricing: {
74
+ /** Plain statement of how usage is charged. */
75
+ summary: string;
76
+ /** Public, credential-free price data an agent can quote from. */
77
+ quoteUrl?: string;
78
+ url?: string;
79
+ };
80
+ next: AgentSurfaceLink[];
81
+ docs?: string;
82
+ openapi?: string;
83
+ mcp?: {
84
+ url: string;
85
+ auth: string;
86
+ };
87
+ related?: Array<{
88
+ name: string;
89
+ manifest?: string;
90
+ url?: string;
91
+ }>;
92
+ /** Extra manifest fields a product already publishes (kept verbatim). */
93
+ manifest?: Record<string, unknown>;
94
+ }
95
+ export interface AgentSurfaceFile {
96
+ path: string;
97
+ contentType: string;
98
+ body: string;
99
+ }
100
+ /**
101
+ * The signup script the skill tells an agent to save and run. Node 18+ only,
102
+ * no dependencies. It never prints the key; it writes `.tangle/api-key` with
103
+ * mode 0600 and reports whether the owner's account can pay yet.
104
+ */
105
+ export declare function agentSignupScript(platformOrigin?: string): string;
106
+ /** The agent setup skill: valid SKILL.md and a plain copy-paste prompt. */
107
+ export declare function renderAgentSetupSkill(config: AgentSurfaceConfig): string;
108
+ /** llms.txt index for the product. The setup skill is the first link. */
109
+ export declare function renderLlmsTxt(config: AgentSurfaceConfig): string;
110
+ /** Markdown for the product's home page, served for `Accept: text/markdown`. */
111
+ export declare function renderHomeMarkdown(config: AgentSurfaceConfig): string;
112
+ /** The `/.well-known/tangle-agent.json` document. */
113
+ export declare function renderAgentManifest(config: AgentSurfaceConfig): Record<string, unknown>;
114
+ /** Every static surface as files, for products that ship them as assets. */
115
+ export declare function agentSurfaceFiles(config: AgentSurfaceConfig): AgentSurfaceFile[];
116
+ /**
117
+ * True when `Accept` ranks `text/markdown` strictly above `text/html` and
118
+ * gives it a nonzero weight. A browser's default header never does.
119
+ */
120
+ export declare function prefersMarkdown(accept: string | null | undefined): boolean;
121
+ /** A copy of `response` whose `Vary` includes `Accept`. */
122
+ export declare function withVaryAccept(response: Response): Response;
123
+ export interface AgentSurfaceHandler {
124
+ /**
125
+ * Answers a surface request (`/agent-setup.md`, `/llms.txt`, the manifest,
126
+ * or a negotiated markdown page), or `null` to let the app answer it.
127
+ */
128
+ handle(request: Request): Response | null;
129
+ /** Adds `Vary: Accept` when the path has a markdown representation. */
130
+ finalize(request: Request, response: Response): Response;
131
+ }
132
+ /**
133
+ * Request handler over {@link agentSurfaceFiles}. `markdownPages` maps extra
134
+ * HTML paths to markdown served on negotiation; `/` always maps to the home
135
+ * markdown.
136
+ */
137
+ export declare function createAgentSurfaceHandler(config: AgentSurfaceConfig, options?: {
138
+ markdownPages?: Record<string, string>;
139
+ }): AgentSurfaceHandler;
@@ -0,0 +1,27 @@
1
+ import {
2
+ AGENT_MANIFEST_SCHEMA_VERSION,
3
+ TANGLE_PLATFORM_ORIGIN,
4
+ agentSignupScript,
5
+ agentSurfaceFiles,
6
+ createAgentSurfaceHandler,
7
+ prefersMarkdown,
8
+ renderAgentManifest,
9
+ renderAgentSetupSkill,
10
+ renderHomeMarkdown,
11
+ renderLlmsTxt,
12
+ withVaryAccept
13
+ } from "../chunk-C5RHSYUA.js";
14
+ export {
15
+ AGENT_MANIFEST_SCHEMA_VERSION,
16
+ TANGLE_PLATFORM_ORIGIN,
17
+ agentSignupScript,
18
+ agentSurfaceFiles,
19
+ createAgentSurfaceHandler,
20
+ prefersMarkdown,
21
+ renderAgentManifest,
22
+ renderAgentSetupSkill,
23
+ renderHomeMarkdown,
24
+ renderLlmsTxt,
25
+ withVaryAccept
26
+ };
27
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -7,7 +7,8 @@ import {
7
7
  noticeEmail
8
8
  } from "../chunk-OYN2UY3K.js";
9
9
  import "../chunk-D6UJEOZQ.js";
10
- import "../chunk-YNSPVKMS.js";
10
+ import "../chunk-UTAIRVOK.js";
11
+ import "../chunk-RN4WPTBH.js";
11
12
  import "../chunk-3NCPXNBZ.js";
12
13
  import "../chunk-TXD5HXLE.js";
13
14
 
@@ -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/** 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 /** Reset/verification mail. Omit to disable password reset entirely. */\n email?: AppAuthEmailConfig\n social?: AppAuthSocialConfig\n /** Session cookie-cache TTL in seconds; `false` disables the cache.\n * Default 300. */\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 if (!email) return { enabled: true }\n const warn = email.warn ?? ((message: string) => console.warn(message))\n return {\n enabled: true,\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 ...(config.sessionCookieCacheSeconds === false\n ? {}\n : {\n session: {\n cookieCache: {\n enabled: true,\n maxAge: config.sessionCookieCacheSeconds ?? DEFAULT_SESSION_COOKIE_CACHE_SECONDS,\n },\n },\n }),\n advanced: { cookiePrefix, ...config.advanced },\n }\n\n const auth: AppAuthInstance = betterAuth(options)\n\n const getSession = 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\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;AAsKjD,SAAS,QAAQ,MAAsB;AACrC,SAAO,K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Aa,SACtC,EAAE,UAAU,QAAiB,MAAM,OAAO,IAAI,QAAQ,OAAO,OAAO,IAAI,OAAO,gBAAgB,OAAO,IAAI,eAAe,IACzH,OAAO,IAAI,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/** 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 /** Reset/verification mail. Omit to disable password reset entirely. */\n email?: AppAuthEmailConfig\n social?: AppAuthSocialConfig\n /** Session cookie-cache TTL in seconds; `false` disables the cache.\n * Default 300. */\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 if (!email) return { enabled: true }\n const warn = email.warn ?? ((message: string) => console.warn(message))\n return {\n enabled: true,\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 ...(config.sessionCookieCacheSeconds === false\n ? {}\n : {\n session: {\n cookieCache: {\n enabled: true,\n maxAge: config.sessionCookieCacheSeconds ?? DEFAULT_SESSION_COOKIE_CACHE_SECONDS,\n },\n },\n }),\n advanced: { cookiePrefix, ...config.advanced },\n }\n\n const auth: AppAuthInstance = betterAuth(options)\n\n const getSession = 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\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;AAsKjD,SAAS,QAAQ,MAAsB;AACrC,SAAO,KACJ,YAAY,EACZ,QAAQ,eAAe,GAAG,EAC1B,QAAQ,YAAY,EAAE;AAC3B;AAEA,SAAS,aAAa,QAAqC;AACzD,SAAO,EAAE,MAAM,OAAO,SAAS,KAAK,OAAO,QAAQ;AACrD;AAEA,SAAS,mBAAmB,OAAsD;AAChF,SAAO,OAAO,MAAM,WAAW,aAAa,MAAM,OAAO,IAAI,MAAM;AACrE;AAMA,SAAS,oBACP,IACA,QACmC;AACnC,SAAO,CAAC,YAAY;AAClB,QAAI;AACJ,UAAM,UAAU,MAAO,YAAY,eAAe,IAAI,MAAM,EAAE,OAAO;AAErE,WAAO;AAAA,MACL,IAAI;AAAA,MACJ,QAAQ,CAAC,SAAS,QAAQ,EAAE,OAAO,IAAI;AAAA,MACvC,SAAS,CAAC,SAAS,QAAQ,EAAE,QAAQ,IAAI;AAAA,MACzC,UAAU,CAAC,SAAS,QAAQ,EAAE,SAAS,IAAI;AAAA,MAC3C,OAAO,CAAC,SAAS,QAAQ,EAAE,MAAM,IAAI;AAAA,MACrC,QAAQ,CAAC,SAAS,QAAQ,EAAE,OAAO,IAAI;AAAA,MACvC,YAAY,CAAC,SAAS,QAAQ,EAAE,WAAW,IAAI;AAAA,MAC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BAAoB,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,23 +1,23 @@
1
1
  import {
2
2
  chatToolCallPart
3
- } from "../chunk-GJRGCVDV.js";
3
+ } from "../chunk-MUZQUS6X.js";
4
4
  import "../chunk-FAU5FIFD.js";
5
5
  import "../chunk-3HUFJ5LO.js";
6
6
  import "../chunk-FBVLEGEG.js";
7
+ import "../chunk-KHCJKVQN.js";
8
+ import "../chunk-XEURJVS5.js";
9
+ import "../chunk-E4AY62T2.js";
7
10
  import "../chunk-Y6PRDUFJ.js";
8
11
  import "../chunk-GEYACSFW.js";
9
12
  import {
10
13
  ChatComposer
11
14
  } from "../chunk-DECJLOS4.js";
12
15
  import "../chunk-L7MB2LLM.js";
13
- import "../chunk-KHCJKVQN.js";
14
- import "../chunk-XEURJVS5.js";
15
16
  import "../chunk-NJDQ2JCP.js";
16
17
  import {
17
18
  ModelPicker
18
19
  } from "../chunk-HG4OONJA.js";
19
20
  import "../chunk-SJWIZT7B.js";
20
- import "../chunk-E4AY62T2.js";
21
21
  import {
22
22
  AsyncView
23
23
  } from "../chunk-LSUELMHY.js";
@@ -66,7 +66,8 @@ import {
66
66
  streamChatRouteAsSandboxEvents
67
67
  } from "../chunk-FNRUXPXE.js";
68
68
  import "../chunk-6VRVRWYN.js";
69
- import "../chunk-YNSPVKMS.js";
69
+ import "../chunk-UTAIRVOK.js";
70
+ import "../chunk-RN4WPTBH.js";
70
71
  import "../chunk-3NCPXNBZ.js";
71
72
  import "../chunk-53K4S3K6.js";
72
73
  import {