@tangle-network/agent-app 0.63.60 → 0.63.62

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 (105) hide show
  1. package/dist/{DesignCanvas-Q65UV4D5.js → DesignCanvas-566V5KVC.js} +3 -2
  2. package/dist/{DesignCanvasEditor-THEFESEX.js → DesignCanvasEditor-6XNHSREG.js} +5 -4
  3. package/dist/agent-profiles/d1.js +3 -3
  4. package/dist/agent-profiles/index.js +3 -3
  5. package/dist/app-auth/index.js +2 -1
  6. package/dist/app-auth/index.js.map +1 -1
  7. package/dist/assistant/index.js +6 -5
  8. package/dist/assistant/index.js.map +1 -1
  9. package/dist/chat-react/index.js +3 -3
  10. package/dist/chat-routes/agent-producers.d.ts +39 -0
  11. package/dist/chat-routes/dispatch-parts.d.ts +24 -2
  12. package/dist/chat-routes/hybrid-producer.d.ts +6 -2
  13. package/dist/chat-routes/index.d.ts +1 -0
  14. package/dist/chat-routes/index.js +31 -12
  15. package/dist/chat-routes/index.js.map +1 -1
  16. package/dist/chat-routes/turn-admission.d.ts +3 -3
  17. package/dist/chat-routes/turn-route-contracts.d.ts +39 -1
  18. package/dist/chat-routes/wire.d.ts +35 -4
  19. package/dist/chat-store/index.js +4 -2
  20. package/dist/chat-store/index.js.map +1 -1
  21. package/dist/chat-store/parts.d.ts +19 -3
  22. package/dist/{chunk-6XSQCP6W.js → chunk-43CV4JIT.js} +2 -2
  23. package/dist/{chunk-SFZELD6V.js → chunk-4JTEPK2G.js} +2 -2
  24. package/dist/{chunk-RILVJYXJ.js → chunk-5ERXADSW.js} +2 -2
  25. package/dist/{chunk-LAZCUQFZ.js → chunk-73AVOSH6.js} +179 -86
  26. package/dist/chunk-73AVOSH6.js.map +1 -0
  27. package/dist/{chunk-HHPQMFKP.js → chunk-7O62NYGT.js} +2 -2
  28. package/dist/{chunk-GGJYAV7R.js → chunk-AHBVQRJA.js} +2 -2
  29. package/dist/{chunk-GGJYAV7R.js.map → chunk-AHBVQRJA.js.map} +1 -1
  30. package/dist/{chunk-UTF7H6BK.js → chunk-EUQ46YWK.js} +15 -15
  31. package/dist/chunk-EUQ46YWK.js.map +1 -0
  32. package/dist/{chunk-PIGW5LRM.js → chunk-FJRQCF43.js} +3 -3
  33. package/dist/{chunk-AICYKYYF.js → chunk-GAYWV565.js} +17 -4
  34. package/dist/chunk-GAYWV565.js.map +1 -0
  35. package/dist/{chunk-5C3RXQQ7.js → chunk-H3DAXUKV.js} +2 -2
  36. package/dist/{chunk-SRA7VAVK.js → chunk-HJYEK4SU.js} +2 -2
  37. package/dist/{chunk-P7UB7ZVP.js → chunk-IAK227OO.js} +2 -2
  38. package/dist/{chunk-QGJOT6R6.js → chunk-K2JPSXKI.js} +54 -9
  39. package/dist/{chunk-QGJOT6R6.js.map → chunk-K2JPSXKI.js.map} +1 -1
  40. package/dist/{chunk-QFIVY6WA.js → chunk-NJW4JCSF.js} +2 -2
  41. package/dist/{chunk-IDQ7N36R.js → chunk-Q55WW6DO.js} +15 -15
  42. package/dist/{chunk-H6BRJU5M.js → chunk-RKNNMC6T.js} +1 -1
  43. package/dist/{chunk-KFO5R4SN.js → chunk-RYKANV3P.js} +945 -801
  44. package/dist/chunk-RYKANV3P.js.map +1 -0
  45. package/dist/{chunk-4E2MUVGL.js → chunk-VQIH5NAB.js} +3 -3
  46. package/dist/chunk-XBBXPZJI.js +47 -0
  47. package/dist/chunk-XBBXPZJI.js.map +1 -0
  48. package/dist/{chunk-DCGATWZ5.js → chunk-XPB2UYHU.js} +5 -5
  49. package/dist/{chunk-DCGATWZ5.js.map → chunk-XPB2UYHU.js.map} +1 -1
  50. package/dist/design-canvas/index.js +2 -1
  51. package/dist/design-canvas/index.js.map +1 -1
  52. package/dist/design-canvas-react/engine.js +2 -1
  53. package/dist/design-canvas-react/index.js +5 -4
  54. package/dist/design-canvas-react/index.js.map +1 -1
  55. package/dist/design-canvas-react/lazy.js +1 -1
  56. package/dist/operator/index.js +2 -2
  57. package/dist/platform/index.js +2 -1
  58. package/dist/platform/index.js.map +1 -1
  59. package/dist/preset-cloudflare/index.js +6 -6
  60. package/dist/public-consultation/index.d.ts +2 -2
  61. package/dist/public-consultation/index.js +11 -10
  62. package/dist/public-consultation/index.js.map +1 -1
  63. package/dist/sandbox/index.js +6 -6
  64. package/dist/sequences/index.js +2 -1
  65. package/dist/sequences/index.js.map +1 -1
  66. package/dist/stories/chat/fixtures.d.ts +4 -0
  67. package/dist/theme/brand.generated.d.ts +15 -15
  68. package/dist/theme/dom.js +2 -2
  69. package/dist/theme/index.js +1 -1
  70. package/dist/theme/tokens.css +210 -356
  71. package/dist/tools/index.js +4 -4
  72. package/dist/web/index.d.ts +1 -0
  73. package/dist/web/index.js +7 -1
  74. package/dist/web/speakers.d.ts +30 -0
  75. package/dist/web-react/chat-messages.d.ts +1 -1
  76. package/dist/web-react/chat-stream.d.ts +7 -0
  77. package/dist/web-react/document.js +2 -2
  78. package/dist/web-react/entry-composer.d.ts +2 -2
  79. package/dist/web-react/index.d.ts +3 -0
  80. package/dist/web-react/index.js +18 -5
  81. package/dist/web-react/message-projection.d.ts +19 -0
  82. package/dist/web-react/use-file-mentions.d.ts +23 -4
  83. package/dist/work-product/index.js +2 -2
  84. package/dist/workspace-react/index.d.ts +29 -1
  85. package/dist/workspace-react/index.js +34 -0
  86. package/dist/workspace-react/index.js.map +1 -1
  87. package/package.json +4 -4
  88. package/dist/chunk-AICYKYYF.js.map +0 -1
  89. package/dist/chunk-KFO5R4SN.js.map +0 -1
  90. package/dist/chunk-LAZCUQFZ.js.map +0 -1
  91. package/dist/chunk-UTF7H6BK.js.map +0 -1
  92. /package/dist/{DesignCanvas-Q65UV4D5.js.map → DesignCanvas-566V5KVC.js.map} +0 -0
  93. /package/dist/{DesignCanvasEditor-THEFESEX.js.map → DesignCanvasEditor-6XNHSREG.js.map} +0 -0
  94. /package/dist/{chunk-6XSQCP6W.js.map → chunk-43CV4JIT.js.map} +0 -0
  95. /package/dist/{chunk-SFZELD6V.js.map → chunk-4JTEPK2G.js.map} +0 -0
  96. /package/dist/{chunk-RILVJYXJ.js.map → chunk-5ERXADSW.js.map} +0 -0
  97. /package/dist/{chunk-HHPQMFKP.js.map → chunk-7O62NYGT.js.map} +0 -0
  98. /package/dist/{chunk-PIGW5LRM.js.map → chunk-FJRQCF43.js.map} +0 -0
  99. /package/dist/{chunk-5C3RXQQ7.js.map → chunk-H3DAXUKV.js.map} +0 -0
  100. /package/dist/{chunk-SRA7VAVK.js.map → chunk-HJYEK4SU.js.map} +0 -0
  101. /package/dist/{chunk-P7UB7ZVP.js.map → chunk-IAK227OO.js.map} +0 -0
  102. /package/dist/{chunk-QFIVY6WA.js.map → chunk-NJW4JCSF.js.map} +0 -0
  103. /package/dist/{chunk-IDQ7N36R.js.map → chunk-Q55WW6DO.js.map} +0 -0
  104. /package/dist/{chunk-H6BRJU5M.js.map → chunk-RKNNMC6T.js.map} +0 -0
  105. /package/dist/{chunk-4E2MUVGL.js.map → chunk-VQIH5NAB.js.map} +0 -0
@@ -2,7 +2,7 @@
2
2
  import { type ChatMessagePart } from '../chat-store/parts';
3
3
  import type { TurnTrace } from '../turn-trace/recorder';
4
4
  import type { ChatTurnAuthorization, CreateChatTurnRoutesOptions } from './turn-route-contracts';
5
- import { ChatTurnInputError, type ChatTurnFilePartInput, type ChatTurnRequestPayload, type FileMention } from './wire';
5
+ import { ChatTurnInputError, type ChatTurnFilePartInput, type ChatTurnRequestPayload, type ChatMention } from './wire';
6
6
  /** A turn whose body parsed and whose caller `authorize` admitted. */
7
7
  export type AdmittedTurn<TContext> = {
8
8
  parsed: ParsedTurnBody;
@@ -21,7 +21,7 @@ export interface ParsedTurnBody {
21
21
  payload: ChatTurnRequestPayload;
22
22
  content: string;
23
23
  fileParts: ChatTurnFilePartInput[];
24
- mentions: FileMention[];
24
+ mentions: ChatMention[];
25
25
  turnId: string | undefined;
26
26
  }
27
27
  /**
@@ -45,4 +45,4 @@ export declare function validateTurnBody(body: Record<string, unknown>): ParsedT
45
45
  * text stays the product's job — only the product knows how to resolve a
46
46
  * workspace-relative path to an in-box one (`fileMentionsToParts`'
47
47
  * `resolvePath` seam), so the route never dispatches them itself. */
48
- export declare function userPartsWithFiles(userParts: Array<Record<string, unknown>>, fileParts: ChatTurnFilePartInput[], mentions: FileMention[]): ChatMessagePart[];
48
+ export declare function userPartsWithFiles(userParts: Array<Record<string, unknown>>, fileParts: ChatTurnFilePartInput[], mentions: ChatMention[]): ChatMessagePart[];
@@ -12,7 +12,8 @@ import type { ModelPolicy } from '../policy-filters/index';
12
12
  import type { PersistedChatMessageForTurn, TurnEventStore } from '../stream/index';
13
13
  import type { TurnSpan, TurnSpanAttrs, TurnTrace, TurnTraceSink, TurnTraceSummary } from '../turn-trace/recorder';
14
14
  import type { TurnRoutePhase } from './turn-progress';
15
- import type { ChatTurnPartInput, ChatTurnRequestPayload } from './wire';
15
+ import type { AgentProfile } from '@tangle-network/agent-interface';
16
+ import type { AgentMention, ChatTurnPartInput, ChatTurnRequestPayload } from './wire';
16
17
  import type { RouterTurnProducerOptions } from './router-producer';
17
18
  import type { HybridTurnProducerOptions } from './hybrid-producer';
18
19
  import type { SandboxChatProducerOptions } from './sandbox-producer';
@@ -232,8 +233,40 @@ export interface ChatTurnRequestContext {
232
233
  /** Limits already authenticated by the server adapter. */
233
234
  executionLimits?: ChatTurnExecutionLimits;
234
235
  }
236
+ /** A workspace agent a turn is addressed to, resolved by the product from an
237
+ * `@` mention. `id` is the stable profile id the mention carried. */
238
+ export interface ChatTurnAgentTarget {
239
+ id: string;
240
+ handle: string;
241
+ name: string;
242
+ /** The profile this responder runs as. A product's `produce` reads it from
243
+ * `args.agent` and runs the turn as that agent instead of the thread's
244
+ * bound one; the binding itself does not move. */
245
+ profile?: AgentProfile;
246
+ }
247
+ /** How a route turns `@agent` mentions into responders. */
248
+ export interface ChatTurnAgentsOptions<TContext> {
249
+ /** Resolve the mentioned agents to the targets this caller may address.
250
+ * Return only the ids you recognise for this workspace: a mention whose id
251
+ * is missing from the result is refused as `unknown_agent` before anything
252
+ * runs. Order is ignored; responders answer in mention order. */
253
+ resolve(args: {
254
+ identity: ChatTurnIdentity;
255
+ context: TContext;
256
+ mentions: AgentMention[];
257
+ }): Promise<ChatTurnAgentTarget[]>;
258
+ }
235
259
  /** Define the arguments required to produce a chat turn with context and messaging details */
236
260
  export interface ChatTurnProduceArgs<TContext, TResource = unknown> {
261
+ /** The agent this producer answers as, when the turn was addressed to one
262
+ * or more agents by mention. The route calls `produce` once per responder,
263
+ * all at once, each with the same thread history and none seeing another's
264
+ * answer, and persists their answers as one assistant row with a speaker
265
+ * part before each, in mention order. Absent → the thread's own agent
266
+ * answers, as before. */
267
+ agent?: ChatTurnAgentTarget;
268
+ /** Every responder of this turn, in mention order. */
269
+ agents?: ChatTurnAgentTarget[];
237
270
  request: Request;
238
271
  /** The opaque resource afterAuthorize started; the route disposes it at this turn's end. */
239
272
  earlyResource?: Promise<TResource>;
@@ -539,6 +572,11 @@ export interface CreateChatTurnRoutesOptions<TContext = void, TResource = unknow
539
572
  * product-supplied access step: session auth, thread/workspace access,
540
573
  * seat/balance gates, rate limits all live here. */
541
574
  authorize(args: ChatTurnAuthorizeArgs): Promise<ChatTurnAuthorization<TContext>>;
575
+ /** Let a turn address workspace agents by `@` mention: the composer's
576
+ * `useFileMentions({ agents })` sends them, this resolves them to the
577
+ * profiles they run as, and `produce` answers once per responder. Omit →
578
+ * a turn carrying an agent mention is refused as `agents_unsupported`. */
579
+ agents?: ChatTurnAgentsOptions<TContext>;
542
580
  /** Resolve the exact authenticated stop target. Without this capability,
543
581
  * cancel returns 405 before parsing or authorization. */
544
582
  cancel?: ChatTurnCancelOptions<TContext>;
@@ -146,7 +146,7 @@ export interface ChatTurnRequestPayload {
146
146
  * persist as their own `ChatMentionPart`s so a retry rebuilds them. The
147
147
  * route validates this field with {@link parseFileMentions} and replaces it
148
148
  * on the payload with the validated, deduped list. */
149
- mentions?: FileMention[];
149
+ mentions?: ChatMention[];
150
150
  /** Files uploaded to the product's store ahead of the turn — path
151
151
  * references, NOT inline bytes (those ride `parts`). Validated and
152
152
  * size-re-derived by {@link resolveChatAttachments} into persistable
@@ -225,13 +225,40 @@ export interface FileMention {
225
225
  name: string;
226
226
  size?: number;
227
227
  }
228
+ /** An agent mention from the composer's `@`-picker: a workspace agent the
229
+ * turn is addressed to. `handle` is the `@`-token identity (the pill's
230
+ * `MentionItem.id`, what the message text carries as `@<handle>`);
231
+ * `agentId` is the stable profile id, so a renamed agent still resolves from
232
+ * an old message. A file mention has no `kind`; this one always does. */
233
+ export interface AgentMention {
234
+ kind: 'agent';
235
+ agentId: string;
236
+ handle: string;
237
+ name: string;
238
+ }
239
+ /** Everything the composer can `@`: a file in the box or an agent in the workspace. */
240
+ export type ChatMention = FileMention | AgentMention;
241
+ export declare function isAgentMention(mention: ChatMention): mention is AgentMention;
242
+ /** The file mentions of a validated list, for the seams that read the box. */
243
+ export declare function fileMentionsOf(mentions: readonly ChatMention[]): FileMention[];
244
+ /** The agent mentions of a validated list, in mention order: the turn's responders. */
245
+ export declare function agentMentionsOf(mentions: readonly ChatMention[]): AgentMention[];
246
+ /** A handle is what a person types after `@`: lowercase letters, digits and
247
+ * hyphens, as `normalizeProfileName` in `/agent-profiles` spells a name. */
248
+ export declare const AGENT_HANDLE_PATTERN: RegExp;
249
+ /** The handle a profile name gets: lowercase, runs of anything else become one
250
+ * hyphen, no leading or trailing hyphen, at most 63 characters. "Research
251
+ * Lead" is `research-lead`. One spelling for the composer, the route and the
252
+ * rail, so a product never derives its own. An empty result (a name with no
253
+ * letters or digits) is `agent`. */
254
+ export declare function agentHandle(name: string): string;
228
255
  /** The `image/*` mime for a mention path by extension, or `undefined` for
229
256
  * anything not in the known image set (dispatched as `type: 'file'`). */
230
257
  export declare function mediaTypeForMentionPath(path: string): string | undefined;
231
258
  /** The image/file split a mention is rendered and persisted under — the
232
259
  * composer pill's icon, the dispatched part's `type`, and
233
260
  * `ChatMentionPart.mentionKind` are all this one value. */
234
- export type ChatMentionKind = 'image' | 'file';
261
+ export type ChatMentionKind = 'image' | 'file' | 'agent';
235
262
  /** `image` when the path's extension is in the known image set (the same table
236
263
  * {@link mediaTypeForMentionPath} reads), `file` otherwise. Exported so a
237
264
  * client that needs only the discriminant — a pill icon, a persisted part's
@@ -249,13 +276,13 @@ export interface FileMentionsToPartsOptions {
249
276
  * `image` vs `file` by extension, and always a `path`, never a `url` (the
250
277
  * url/path XOR invariant: a mention is a sandbox path reference, never
251
278
  * inline bytes). */
252
- export declare function fileMentionsToParts(mentions: readonly FileMention[], opts?: FileMentionsToPartsOptions): ChatTurnFilePartInput[];
279
+ export declare function fileMentionsToParts(mentions: readonly ChatMention[], opts?: FileMentionsToPartsOptions): ChatTurnFilePartInput[];
253
280
  /** The agent-facing pointer block appended to the dispatched prompt — never
254
281
  * persisted in message `content`. Empty array → `''` so callers can append
255
282
  * unconditionally. This is the sole producer of that text: the current
256
283
  * turn's dispatch and any history projection built from the same mention
257
284
  * list both route through here, so the two can't drift apart. */
258
- export declare function buildMentionPromptBlock(mentions: readonly Pick<FileMention, 'name' | 'path'>[]): string;
285
+ export declare function buildMentionPromptBlock(mentions: readonly (Pick<FileMention, 'name' | 'path'> | AgentMention)[]): string;
259
286
  /** Hard cap on mentions per turn. Bounds the prompt pointer block, the
260
287
  * persisted parts, and whatever media budget a dispatch draws from them. */
261
288
  export declare const MENTION_MAX_COUNT = 16;
@@ -287,6 +314,10 @@ export declare function validateSandboxMentionPath(path: unknown): SandboxMentio
287
314
  * than rejected: mentioning the same file twice is plausible user input, not
288
315
  * an attack.
289
316
  */
317
+ /** The validated, deduped mention list off the wire: files by path, agents
318
+ * by id, in the order typed. One cap covers both kinds. */
319
+ export declare function parseMentions(raw: unknown): ChatMention[];
320
+ /** The file mentions of the wire list; agent mentions are validated and set aside. */
290
321
  export declare function parseFileMentions(raw: unknown): FileMention[];
291
322
  /** Validates the untyped `parts` array off the wire. Returns the typed parts
292
323
  * or throws `ChatTurnInputError` (400) naming the offending entry. */
@@ -12,16 +12,17 @@ import {
12
12
  isChatAttachmentPart,
13
13
  isChatInteractionPart,
14
14
  isChatMentionPart,
15
+ isChatSpeakerPart,
15
16
  mentionInputToPart,
16
17
  mentionPartsFromMessageParts,
17
18
  toChatMessageParts
18
- } from "../chunk-AICYKYYF.js";
19
+ } from "../chunk-GAYWV565.js";
19
20
  import "../chunk-ZVEEWGDK.js";
20
21
  import {
21
22
  attachmentPartKey
22
23
  } from "../chunk-U4F6NHAA.js";
23
24
  import "../chunk-TB6KNPFI.js";
24
- import "../chunk-QGJOT6R6.js";
25
+ import "../chunk-K2JPSXKI.js";
25
26
  import "../chunk-4PIN6QYQ.js";
26
27
  import "../chunk-TXD5HXLE.js";
27
28
 
@@ -344,6 +345,7 @@ export {
344
345
  isChatAttachmentPart,
345
346
  isChatInteractionPart,
346
347
  isChatMentionPart,
348
+ isChatSpeakerPart,
347
349
  mentionInputToPart,
348
350
  mentionPartsFromMessageParts,
349
351
  threadTitleFromMessage,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/chat-store/core.ts","../../src/chat-store/schema.ts","../../src/chat-store/store.ts"],"sourcesContent":["/**\n * Pure (drizzle-free) pieces of the chat store: thread-title derivation, the\n * bulk-delete bound, message-write contract, and typed input error. Split from\n * `./schema`/`./store`\n * so the root barrel can re-export them without dragging the optional\n * drizzle-orm peer into every root-entry consumer.\n */\n\nimport type { ChatMessagePart } from './parts'\n\n/** Bounds a single bulk-delete request's write set; product surfaces cap\n * thread lists at far fewer, so a larger batch is a malformed or hostile\n * request. (Lifted from legal's api.threads.bulk-delete route.) */\nexport const BULK_DELETE_MAX_THREADS = 200\n\n/** Invalid caller input (missing/oversized ids, empty title). Products map it\n * to a 400; anything else out of the store is a real failure. */\nexport class ChatStoreInputError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'ChatStoreInputError'\n }\n}\n\n/** Thread titles come from the first message — keep the list scannable by\n * storing only its first non-empty line, capped at 80 chars, never the whole\n * multi-page prompt. (Lifted verbatim from legal's chat.new route.) */\nexport function threadTitleFromMessage(message: string): string {\n const firstLine = message.split('\\n').find((l) => l.trim().length > 0)?.trim() ?? ''\n if (!firstLine) return 'New Thread'\n return firstLine.length > 80 ? `${firstLine.slice(0, 79)}…` : firstLine\n}\n\n/** Stored message body, model attribution and usage shared by append and patch adapters. */\nexport type ChatMessageValues = {\n content: string\n parts?: ChatMessagePart[]\n model?: string | null\n requestedModel?: string | null\n servedModel?: string | null\n servedProvider?: string | null\n servedSource?: string | null\n inputTokens?: number | null\n outputTokens?: number | null\n reasoningTokens?: number | null\n cacheReadTokens?: number | null\n cacheWriteTokens?: number | null\n costUsd?: number | null\n}\n","/**\n * Drizzle schema factory for the chat thread/message tables — the same\n * injection pattern as `createTeamTables`: the product owns the workspace\n * table; the factory wires the thread FK into it so the whole graph lives in\n * one drizzle schema with real cascade semantics. Column names, types,\n * defaults, enums, and indexes mirror legal's and gtm's hand-rolled `thread`/\n * `message` tables so a product with those tables adopts the factory without\n * rewriting rows; `tablePrefix` covers products that namespace (tax's\n * `chat_messages` style).\n *\n * The core is the superset the three products agree on. Divergences dropped,\n * and why:\n * - `thread.status` ('active'|'archived', legal+gtm) — archive semantics\n * diverge (tax uses `archivedAt`); product-domain lifecycle → extra column.\n * - `thread.scopeKind`/`scopeKey`/`harness` (gtm) — artifact anchoring and\n * harness pinning are product-domain → extra columns.\n * - tax's `tax_sessions` session columns (`taxYear`, `projectRef`,\n * `agentSessionId`, `agentRuntime`, `agentHarness`, `profile`, `error`,\n * `userId`) — sandbox-session state, not chat state → extra columns.\n * - `message.toolInput`/`toolOutput` (legal+gtm) — duplicate of the tool\n * part's `state.input`/`state.output` inside `parts` (the shape `/stream`'s\n * `normalizePersistedPart` owns); keeping both invites drift.\n * - `message.vaultFiles` (legal+gtm) — vault is product-domain → extra column.\n * - tax's re-declared `turn_events`/`turn_status` DDL — deliberately NOT here;\n * `/stream`'s turn-buffer owns that DDL (`TURN_BUFFER_D1_SCHEMA_SQL`).\n *\n * Kept beyond the intersection: tax's per-message `model`/`inputTokens`/\n * `outputTokens`, extended to the full usage receipt the harness actually\n * reports in `step-finish` parts (`tokens {input, output, reasoning,\n * cache{read, write}}` + `cost`) — see `./parts`.\n *\n * `threadExtraColumns`/`messageExtraColumns` merge product columns into the\n * table definitions (the `/missions` opaque-extras pattern: the store writes\n * `extras` values verbatim in the SAME insert statement and never infers their\n * meaning). A product declaring a `metadata` column may use the store\n * metadata merge-patch operation; its fields remain opaque product data.\n *\n * SERVER-side module (D1/libsql/better-sqlite3 behind a worker or server\n * route) — but free of `node:` builtins on purpose: D1 workers have none.\n */\n\nimport { sql } from 'drizzle-orm'\nimport { index, integer, real, sqliteTable, text, uniqueIndex } from 'drizzle-orm/sqlite-core'\nimport type {\n AnySQLiteColumn,\n AnySQLiteTable,\n SQLiteColumnBuilderBase,\n SQLiteTableExtraConfigValue,\n} from 'drizzle-orm/sqlite-core'\nimport type { ChatMessagePart } from './parts'\n\n/** A product table referenced by FK — only the `id` column is touched. */\nexport type ChatParentTable = AnySQLiteTable & { id: AnySQLiteColumn }\n\n/** Define options to customize chat thread and message table creation including workspace and naming prefixes */\nexport interface CreateChatTablesOptions<\n TThreadExtras extends Record<string, SQLiteColumnBuilderBase> = {},\n TMessageExtras extends Record<string, SQLiteColumnBuilderBase> = {},\n> {\n /** The product's workspace table — threads reference `workspaceTable.id`\n * with cascade. Omitted: `workspace_id` stays a plain indexed text column\n * (products whose tenant table lives in another database). */\n workspaceTable?: ChatParentTable\n /** Prefixes table AND index names (`'chat_'` → `chat_thread`,\n * `idx_chat_thread_workspace`) for products that namespace chat tables in a\n * shared database. Default: unprefixed `thread`/`message` (legal/gtm row\n * compatibility). */\n tablePrefix?: string\n /** Product columns merged into the thread table (the `/missions` extras\n * pattern) — e.g. a `status` lifecycle enum or gtm's scope columns. */\n threadExtraColumns?: TThreadExtras\n /** Product columns merged into the message table — e.g. legal's\n * `vault_files`. */\n messageExtraColumns?: TMessageExtras\n /**\n * Product indexes appended to the thread table's own, given the built\n * columns (extras included) so a product can index what it added.\n *\n * Names are used VERBATIM — `tablePrefix` is not applied — because these\n * have to byte-match indexes the product's migrations already created.\n *\n * Without this a product with one extra index cannot adopt the factory at\n * all: it keeps a hand-rolled duplicate of the same physical table, and the\n * two drift on the next factory change.\n */\n threadExtraIndexes?: ChatExtraIndexes\n /** Product indexes appended to the message table's own. Same rules as\n * `threadExtraIndexes`. */\n messageExtraIndexes?: ChatExtraIndexes\n}\n\n/**\n * Builds product indexes from a table's columns.\n *\n * The column map is passed untyped because its shape depends on the product's\n * own extras; the RETURN is drizzle's own extra-config type, so the spread\n * below stays inside the union `sqliteTable` expects and the built table keeps\n * its inferred column types. Returning `unknown[]` here would force a cast on\n * the config array, which widens every column to the cross-dialect union and\n * breaks `db.select()` at every call site.\n */\nexport type ChatExtraIndexes = (\n columns: Record<string, AnySQLiteColumn>,\n) => SQLiteTableExtraConfigValue[]\n\nconst hexId = () => text('id').primaryKey().default(sql`(lower(hex(randomblob(16))))`)\n\nconst createdAt = () => integer('created_at', { mode: 'timestamp' }).notNull().default(sql`(unixepoch())`)\n\nconst updatedAt = () => integer('updated_at', { mode: 'timestamp' }).notNull().default(sql`(unixepoch())`)\n\n/** Build chat-related SQLite tables with customizable thread and message columns */\nexport function createChatTables<\n TThreadExtras extends Record<string, SQLiteColumnBuilderBase> = {},\n TMessageExtras extends Record<string, SQLiteColumnBuilderBase> = {},\n>(options: CreateChatTablesOptions<TThreadExtras, TMessageExtras> = {}) {\n const { workspaceTable, tablePrefix = '' } = options\n const threadExtras = options.threadExtraColumns ?? ({} as TThreadExtras)\n const messageExtras = options.messageExtraColumns ?? ({} as TMessageExtras)\n const extraIndexes = (\n build: ChatExtraIndexes | undefined,\n table: Record<string, AnySQLiteColumn>,\n ): SQLiteTableExtraConfigValue[] => build?.(table) ?? []\n\n const threads = sqliteTable(`${tablePrefix}thread`, {\n id: hexId(),\n workspaceId: workspaceTable\n ? text('workspace_id').notNull().references(() => workspaceTable.id, { onDelete: 'cascade' })\n : text('workspace_id').notNull(),\n title: text('title').notNull(),\n category: text('category'),\n isPinned: integer('is_pinned', { mode: 'boolean' }).notNull().default(false),\n createdAt: createdAt(),\n updatedAt: updatedAt(),\n ...threadExtras,\n }, (table) => [\n index(`idx_${tablePrefix}thread_workspace`).on(table.workspaceId),\n // Supports the store's list ordering (updatedAt desc within a workspace).\n index(`idx_${tablePrefix}thread_workspace_updated`).on(table.workspaceId, table.updatedAt),\n ...extraIndexes(options.threadExtraIndexes, table as unknown as Record<string, AnySQLiteColumn>),\n ])\n\n const messages = sqliteTable(`${tablePrefix}message`, {\n id: hexId(),\n threadId: text('thread_id').notNull().references(() => threads.id, { onDelete: 'cascade' }),\n role: text('role', { enum: ['user', 'assistant', 'system', 'tool'] }).notNull(),\n content: text('content').notNull(),\n parts: text('parts', { mode: 'json' }).$type<ChatMessagePart[]>().default([]),\n toolName: text('tool_name'),\n model: text('model'),\n requestedModel: text('requested_model'),\n servedModel: text('served_model'),\n servedProvider: text('served_provider'),\n servedSource: text('served_model_source'),\n // Usage receipt, flattened from the harness's `step-finish` shape\n // (`tokens {input, output, reasoning, cache{read, write}}` + `cost`).\n inputTokens: integer('input_tokens'),\n outputTokens: integer('output_tokens'),\n reasoningTokens: integer('reasoning_tokens'),\n cacheReadTokens: integer('cache_read_tokens'),\n cacheWriteTokens: integer('cache_write_tokens'),\n costUsd: real('cost_usd'),\n createdAt: createdAt(),\n ...messageExtras,\n }, (table) => [\n index(`idx_${tablePrefix}message_thread`).on(table.threadId),\n index(`idx_${tablePrefix}message_thread_created`).on(table.threadId, table.createdAt),\n ...extraIndexes(options.messageExtraIndexes, table as unknown as Record<string, AnySQLiteColumn>),\n ])\n\n return { threads, messages }\n}\n\n/**\n * Build the `thread_artifact_link` table: artifacts a thread mentioned or\n * touched beyond its own scope, inserted once on first reference. It powers a\n * thread's \"also discussed\" chips and the reverse \"which threads touched this\n * file\" lookup. `kinds` is the product's artifact-kind enum.\n */\nexport function createThreadArtifactLinksTable<const Kind extends string>(\n threadTable: ChatParentTable,\n kinds: readonly [Kind, ...Kind[]],\n) {\n return sqliteTable('thread_artifact_link', {\n id: hexId(),\n threadId: text('thread_id').notNull().references(() => threadTable.id, { onDelete: 'cascade' }),\n artifactKind: text('artifact_kind', { enum: kinds }).notNull(),\n artifactKey: text('artifact_key').notNull(),\n firstReferencedAt: integer('first_referenced_at', { mode: 'timestamp' }).notNull().default(sql`(unixepoch())`),\n }, (table) => [\n index('idx_thread_artifact_link_thread').on(table.threadId),\n uniqueIndex('idx_thread_artifact_link_unique').on(table.threadId, table.artifactKind, table.artifactKey),\n index('idx_thread_artifact_link_reverse').on(table.artifactKind, table.artifactKey),\n ])\n}\n\n/**\n * Build the `agent_run` table: one row per agent run in a workspace, with the\n * product's run telemetry as JSON `metadata`. `idx_agent_run_workspace` covers\n * `(workspace_id, agent_id)`, or `workspace_id` alone with `indexAgentId: false`\n * for products whose migration created it that way.\n */\nexport function createAgentRunsTable<Metadata = Record<string, unknown>>(\n workspaceTable: ChatParentTable,\n options: { indexAgentId?: boolean } = {},\n) {\n return sqliteTable('agent_run', {\n id: hexId(),\n workspaceId: text('workspace_id').notNull().references(() => workspaceTable.id, { onDelete: 'cascade' }),\n agentId: text('agent_id').notNull(),\n status: text('status', { enum: ['running', 'completed', 'failed'] }).notNull().default('running'),\n success: integer('success', { mode: 'boolean' }).notNull().default(true),\n resultSummary: text('result_summary'),\n metadata: text('metadata', { mode: 'json' }).$type<Metadata>(),\n startedAt: integer('started_at', { mode: 'timestamp' }).notNull().default(sql`(unixepoch())`),\n completedAt: integer('completed_at', { mode: 'timestamp' }),\n }, (table) => [\n options.indexAgentId === false\n ? index('idx_agent_run_workspace').on(table.workspaceId)\n : index('idx_agent_run_workspace').on(table.workspaceId, table.agentId),\n ])\n}\n\n/**\n * The base (no-extras) table pair, pinned via an instantiation expression:\n * `ReturnType<typeof createChatTables>` on the bare generic substitutes the\n * extras params with their CONSTRAINT (`Record<string,\n * SQLiteColumnBuilderBase>`), stamping an index signature into the column map\n * that widens every concrete column to `unknown`/`notNull: false` — concrete\n * factory results then fail `extends ChatTables`. (`teams`' `createTeamTables`\n * is non-generic, so its plain `ReturnType` never hits this.)\n */\nexport type ChatTables = ReturnType<typeof createChatTables<{}, {}>>\n\n/** Resolve the selected fields of a chat thread row from the chat threads table */\nexport type ChatThreadRow = ChatTables['threads']['$inferSelect']\n/** Resolve the selected structure of a chat message row from the messages table */\nexport type ChatMessageRow = ChatTables['messages']['$inferSelect']\n/** Resolve the type for inserting a new chat thread row into the threads table */\nexport type NewChatThreadRow = ChatTables['threads']['$inferInsert']\n/** Resolve the type for inserting a new chat message row into the messages table */\nexport type NewChatMessageRow = ChatTables['messages']['$inferInsert']\n","/**\n * Typed CRUD over the tables from `createChatTables`. Works against any\n * SQLite drizzle driver (D1, libsql, better-sqlite3) — builders are awaited,\n * never `.run()`/`.all()`, so sync and async drivers behave identically.\n *\n * Access control is an injected seam, never an import: single-thread routes\n * check workspace access themselves (they know the thread), while\n * `bulkDeleteThreads` REQUIRES an `assertAccess` callback because one request\n * can span workspaces — it is called once per distinct workspace and any\n * throw rejects the whole request before a single delete runs (fail-closed;\n * legal's bulk-delete semantics).\n *\n * Deletes run messages-first in ONE `db.batch` round trip when the driver has\n * one (D1, libsql), so a partial failure never leaves orphaned rows behind a\n * deleted thread; drivers without `batch` (better-sqlite3) fall back to\n * sequential awaits in the same order.\n */\n\nimport { and, asc, desc, eq, getTableColumns, gte, inArray, lt, sql, type SQL } from 'drizzle-orm'\nimport type { AnySQLiteColumn, BaseSQLiteDatabase } from 'drizzle-orm/sqlite-core'\nimport {\n runSqliteStatements,\n type SqliteBatchDatabase,\n} from '../store'\nimport { type ChatMessageValues, BULK_DELETE_MAX_THREADS, ChatStoreInputError, threadTitleFromMessage } from './core'\nimport type { ChatMessageRow, ChatTables, ChatThreadRow, NewChatMessageRow, NewChatThreadRow } from './schema'\n\n/** Any SQLite drizzle database — `any` erases the driver-specific run-result\n * and schema generics so better-sqlite3, D1, and libsql handles all fit.\n * `batch` is structural: present on D1/libsql drizzle instances. */\nexport type ChatDatabase = BaseSQLiteDatabase<'sync' | 'async', any, any> &\n SqliteBatchDatabase\n\n/** Product-injected access check. Throw to deny; the store never interprets\n * users or roles itself. */\nexport type WorkspaceAccessCheck = (workspaceId: string) => void | Promise<void>\n\n/** Define input parameters for listing threads within a workspace with pagination options */\nexport interface ListThreadsInput {\n workspaceId: string\n /** Clamped to 1..200; default 50 (legal's list route semantics). */\n limit?: number\n /** Clamped to >= 0; default 0. */\n offset?: number\n}\n\n/** Represent a paginated collection of chat threads with total count and pagination details */\nexport interface ListThreadsResult<TThread = ChatThreadRow> {\n threads: TThread[]\n total: number\n limit: number\n offset: number\n}\n\n/** Define input parameters required to create a new thread in a workspace */\nexport interface CreateThreadInput {\n /** Caller-assigned primary key. The agent gateway uses its validated\n * conversation id so API and browser turns share one durable thread. */\n id?: string\n workspaceId: string\n /** Title source when `title` is absent: first non-empty line, 80-char cap\n * (`threadTitleFromMessage`). */\n firstMessage?: string\n /** Explicit title; still normalized through `threadTitleFromMessage` so a\n * multi-page paste never becomes a sidebar entry. */\n title?: string\n category?: string | null\n isPinned?: boolean\n /** Opaque product-column values written verbatim in the SAME insert (the\n * `/missions` extras pattern). Never read, validated, or defaulted here. */\n extras?: Record<string, unknown>\n}\n\n/** Define input parameters for appending a message to a chat thread with optional metadata */\nexport interface AppendMessageInput extends ChatMessageValues {\n /** Caller-assigned primary key. Omitted, the column default assigns a random\n * hex id (today's behavior). Incremental assistant persistence passes a\n * DETERMINISTIC id derived from the turn's own identity, so a re-entered\n * turn (crashed worker, durable-driver retry) finds and updates the row a\n * previous attempt started instead of inserting a second one. */\n id?: string\n threadId: string\n role: 'user' | 'assistant' | 'system' | 'tool'\n toolName?: string | null\n /** Opaque product-column values written verbatim in the SAME insert. */\n extras?: Record<string, unknown>\n}\n\n/** Fields an existing message row may be patched with. Every field is\n * optional and only DEFINED fields are written, so a partial patch never\n * clears a column it does not mention. `threadId` and `role` are absent on\n * purpose: a message never moves thread or changes speaker.\n *\n * Exists for incremental assistant persistence — the streaming turn writes\n * the row once and then patches it as content accumulates, so the durable\n * transcript is at most one cadence interval behind the live stream. */\nexport interface UpdateMessageInput extends Partial<ChatMessageValues> {\n toolName?: string | null\n /** Opaque product-column values written verbatim in the SAME update. */\n extras?: Record<string, unknown>\n}\n\n/** Define options to configure message listing with optional limit and offset parameters */\nexport interface ListMessagesOptions {\n limit?: number\n offset?: number\n}\n\n/** Define input for bulk deleting threads with access checks per workspace */\nexport interface BulkDeleteThreadsInput {\n ids: string[]\n /** Optional single-workspace fence for products whose route already resolved\n * one active workspace. Omitted preserves the multi-workspace legal route. */\n workspaceId?: string\n /** Called once per distinct workspace the ids touch, before ANY delete. */\n assertAccess: WorkspaceAccessCheck\n}\n\n/** Delete threads selected by their last activity time within one workspace.\n *\n * Products can add a lifecycle predicate such as `status = 'active'` through\n * `where`; the store still owns workspace scope, access ordering, and message\n * cleanup for every consumer. */\nexport interface BulkDeleteThreadsByUpdatedAtInput {\n workspaceId: string\n /** Exclusive upper bound: rows older than this instant. */\n updatedBefore?: Date\n /** Inclusive lower bound: rows updated at or after this instant. */\n updatedAfter?: Date\n where?: SQL\n /** Called before any delete for the requested workspace. */\n assertAccess: WorkspaceAccessCheck\n}\n\n/** Manage chat threads and messages with operations for listing, creating, updating, and deleting data */\nexport interface ChatStore<TThread = ChatThreadRow, TMessage = ChatMessageRow> {\n listThreads(input: ListThreadsInput): Promise<ListThreadsResult<TThread>>\n getThread(threadId: string): Promise<TThread | null>\n createThread(input: CreateThreadInput): Promise<TThread>\n renameThread(threadId: string, title: string): Promise<TThread | null>\n pinThread(threadId: string, isPinned: boolean): Promise<TThread | null>\n /** Messages + thread in one batch. Resolves false when the thread does not\n * exist. `assertAccess` (optional) receives the thread's workspaceId before\n * the delete — single-thread callers usually check access themselves. */\n deleteThread(threadId: string, options?: { assertAccess?: WorkspaceAccessCheck }): Promise<boolean>\n bulkDeleteThreads(input: BulkDeleteThreadsInput): Promise<{ deleted: number }>\n bulkDeleteThreadsByUpdatedAt(input: BulkDeleteThreadsByUpdatedAtInput): Promise<{ deleted: number }>\n /** Ordered oldest-first: `created_at`, then rowid (insertion order within a\n * same-second burst — a user+assistant pair lands in one epoch second). */\n listMessages(threadId: string, options?: ListMessagesOptions): Promise<TMessage[]>\n getMessage(id: string): Promise<TMessage | null>\n /** Atomic JSON Merge Patch for a product-declared metadata column. Null removes keys;\n * expected top-level fields fence the update against another attempt. Opaque values stay product-owned. */\n patchMessageMetadata(id: string, mergePatch: Record<string, unknown>, expected?: { fields: Record<string, unknown> } | { snapshot: Record<string, unknown> }): Promise<TMessage | null>\n /** Inserts the message and bumps the thread's `updatedAt` in one batch so\n * workspace recency sorts stay truthful. */\n appendMessage(input: AppendMessageInput): Promise<TMessage>\n /** Patches an existing message and bumps its thread's `updatedAt` in the\n * same batch. Resolves `null` when the id does not exist. Only defined\n * patch fields are written. */\n updateMessage(id: string, patch: UpdateMessageInput): Promise<TMessage | null>\n /** Removes one message. Resolves false when the id does not exist. Used by\n * incremental persistence to retract a draft row for a turn that ended\n * producing nothing, so an empty assistant row is never left behind. */\n deleteMessage(id: string): Promise<boolean>\n}\n\nfunction clampLimit(limit: number | undefined, fallback: number, max: number): number {\n const value = Number.isFinite(limit) ? Math.trunc(limit as number) : fallback\n return Math.min(Math.max(value, 1), max)\n}\n\nfunction clampOffset(offset: number | undefined): number {\n const value = Number.isFinite(offset) ? Math.trunc(offset as number) : 0\n return Math.max(value, 0)\n}\n\n/** Create a chat store managing threads and messages based on the provided database and tables */\nexport function createChatStore<TTables extends ChatTables>(\n db: ChatDatabase,\n tables: TTables,\n): ChatStore<TTables['threads']['$inferSelect'], TTables['messages']['$inferSelect']> {\n type TThread = TTables['threads']['$inferSelect']\n type TMessage = TTables['messages']['$inferSelect']\n const threads = tables.threads as ChatTables['threads']\n const messages = tables.messages as ChatTables['messages']\n\n return {\n async listThreads(input) {\n const limit = clampLimit(input.limit, 50, 200)\n const offset = clampOffset(input.offset)\n const scope = eq(threads.workspaceId, input.workspaceId)\n const [list, [countRow]] = await Promise.all([\n db.select().from(threads).where(scope)\n // `id` tiebreak keeps pagination stable across same-second updates.\n .orderBy(desc(threads.updatedAt), asc(threads.id))\n .limit(limit)\n .offset(offset),\n db.select({ total: sql<number>`count(*)` }).from(threads).where(scope),\n ])\n return { threads: list as TThread[], total: countRow?.total ?? 0, limit, offset }\n },\n\n async getThread(threadId) {\n const [row] = await db.select().from(threads).where(eq(threads.id, threadId)).limit(1)\n return (row as TThread | undefined) ?? null\n },\n\n async createThread(input) {\n const title = threadTitleFromMessage(input.title ?? input.firstMessage ?? '')\n const values = {\n ...(input.id !== undefined ? { id: input.id } : {}),\n workspaceId: input.workspaceId,\n title,\n ...(input.category !== undefined ? { category: input.category } : {}),\n ...(input.isPinned !== undefined ? { isPinned: input.isPinned } : {}),\n ...(input.extras ?? {}),\n } as NewChatThreadRow\n const [row] = await db.insert(threads).values(values).returning()\n if (!row) throw new Error('thread insert returned no row')\n return row as TThread\n },\n\n async renameThread(threadId, title) {\n const trimmed = title.trim()\n if (!trimmed) throw new ChatStoreInputError('Missing title')\n const [row] = await db.update(threads)\n .set({ title: trimmed, updatedAt: new Date() })\n .where(eq(threads.id, threadId))\n .returning()\n return (row as TThread | undefined) ?? null\n },\n\n async pinThread(threadId, isPinned) {\n const [row] = await db.update(threads)\n .set({ isPinned, updatedAt: new Date() })\n .where(eq(threads.id, threadId))\n .returning()\n return (row as TThread | undefined) ?? null\n },\n\n async deleteThread(threadId, options) {\n const [existing] = await db.select({ id: threads.id, workspaceId: threads.workspaceId })\n .from(threads)\n .where(eq(threads.id, threadId))\n .limit(1)\n if (!existing) return false\n if (options?.assertAccess) await options.assertAccess(existing.workspaceId)\n // Messages first so a partial failure never leaves orphaned rows behind\n // a deleted thread.\n await runSqliteStatements(db, [\n db.delete(messages).where(eq(messages.threadId, threadId)),\n db.delete(threads).where(eq(threads.id, threadId)),\n ])\n return true\n },\n\n async bulkDeleteThreads(input) {\n const { ids, workspaceId, assertAccess } = input\n if (typeof assertAccess !== 'function') throw new ChatStoreInputError('Missing assertAccess')\n if (!Array.isArray(ids) || ids.length === 0 || !ids.every((id) => typeof id === 'string' && id.length > 0)) {\n throw new ChatStoreInputError('Missing ids')\n }\n if (ids.length > BULK_DELETE_MAX_THREADS) {\n throw new ChatStoreInputError(`Too many ids (max ${BULK_DELETE_MAX_THREADS})`)\n }\n if (workspaceId !== undefined && !workspaceId.trim()) {\n throw new ChatStoreInputError('Invalid workspaceId')\n }\n\n const scope = workspaceId\n ? and(inArray(threads.id, ids), eq(threads.workspaceId, workspaceId))\n : inArray(threads.id, ids)\n const rows = await db.select({ id: threads.id, workspaceId: threads.workspaceId })\n .from(threads)\n .where(scope)\n if (rows.length === 0) return { deleted: 0 }\n\n // Access is verified once per workspace the ids touch. Fail-closed: one\n // inaccessible workspace rejects the whole request before any delete.\n // Sorted so the check order (and therefore which denial surfaces) is\n // deterministic — row order follows random hex ids and varies per run.\n const workspaceIds = [...new Set(rows.map((row) => row.workspaceId))].sort()\n for (const workspaceId of workspaceIds) {\n await assertAccess(workspaceId)\n }\n\n const foundIds = rows.map((row) => row.id)\n await runSqliteStatements(db, [\n db.delete(messages).where(inArray(messages.threadId, foundIds)),\n db.delete(threads).where(inArray(threads.id, foundIds)),\n ])\n return { deleted: foundIds.length }\n },\n\n async bulkDeleteThreadsByUpdatedAt(input) {\n const { workspaceId, updatedBefore, updatedAfter, where, assertAccess } = input\n if (typeof assertAccess !== 'function') throw new ChatStoreInputError('Missing assertAccess')\n if (!workspaceId.trim()) throw new ChatStoreInputError('Missing workspaceId')\n if (updatedBefore === undefined && updatedAfter === undefined) {\n throw new ChatStoreInputError('Missing updatedAt boundary')\n }\n for (const boundary of [updatedBefore, updatedAfter]) {\n if (boundary !== undefined && Number.isNaN(boundary.getTime())) {\n throw new ChatStoreInputError('Invalid updatedAt boundary')\n }\n }\n\n const conditions = [eq(threads.workspaceId, workspaceId)]\n if (updatedBefore) conditions.push(lt(threads.updatedAt, updatedBefore))\n if (updatedAfter) conditions.push(gte(threads.updatedAt, updatedAfter))\n if (where) conditions.push(where)\n const scope = and(...conditions)\n const [countRow] = await db.select({ total: sql<number>`count(*)` })\n .from(threads)\n .where(scope)\n const deleted = Number(countRow?.total ?? 0)\n if (deleted === 0) return { deleted: 0 }\n\n await assertAccess(workspaceId)\n // Keep the age path unbounded without constructing a giant host-parameter\n // list; the subquery lets SQLite/D1 stream the matching thread ids.\n const matchingThreads = db.select({ id: threads.id }).from(threads).where(scope)\n await runSqliteStatements(db, [\n db.delete(messages).where(inArray(messages.threadId, matchingThreads)),\n db.delete(threads).where(scope),\n ])\n return { deleted }\n },\n\n async listMessages(threadId, options) {\n const query = db.select().from(messages)\n .where(eq(messages.threadId, threadId))\n .orderBy(asc(messages.createdAt), sql`rowid`)\n .$dynamic()\n if (options?.limit !== undefined) query.limit(clampLimit(options.limit, 1, 1000))\n if (options?.offset !== undefined) query.offset(clampOffset(options.offset))\n return await query as TMessage[]\n },\n\n async getMessage(id) {\n const [row] = await db.select().from(messages).where(eq(messages.id, id)).limit(1)\n return (row as TMessage | undefined) ?? null\n },\n\n async patchMessageMetadata(id, mergePatch, expected) {\n const metadata = (getTableColumns(tables.messages) as Record<string, AnySQLiteColumn>).metadata\n if (!metadata) throw new Error('Chat metadata requires a product-declared metadata column')\n const guards = Object.entries(expected && 'fields' in expected ? expected.fields : {}).map(([field, value]) => {\n const encoded = JSON.stringify(value)\n if (encoded === undefined) throw new Error('Expected chat metadata must be JSON')\n return sql`json_extract(${metadata}, ${`$.${JSON.stringify(field)}`}) IS json_extract(${encoded}, '$')`\n })\n if (expected && 'snapshot' in expected) guards.push(sql`coalesce(${metadata}, '{}') = ${JSON.stringify(expected.snapshot)}`)\n const [row] = await db.update(messages).set({\n metadata: sql`json_patch(coalesce(${metadata}, '{}'), ${JSON.stringify(mergePatch)})`,\n } as Partial<NewChatMessageRow>).where(and(eq(messages.id, id), ...guards)).returning()\n return (row as TMessage | undefined) ?? null\n },\n\n async appendMessage(input) {\n const values = {\n ...(input.id !== undefined ? { id: input.id } : {}),\n threadId: input.threadId,\n role: input.role,\n content: input.content,\n ...(input.parts !== undefined ? { parts: input.parts } : {}),\n ...(input.toolName !== undefined ? { toolName: input.toolName } : {}),\n ...(input.model !== undefined ? { model: input.model } : {}),\n ...(input.requestedModel !== undefined ? { requestedModel: input.requestedModel } : {}),\n ...(input.servedModel !== undefined ? { servedModel: input.servedModel } : {}),\n ...(input.servedProvider !== undefined ? { servedProvider: input.servedProvider } : {}),\n ...(input.servedSource !== undefined ? { servedSource: input.servedSource } : {}),\n ...(input.inputTokens !== undefined ? { inputTokens: input.inputTokens } : {}),\n ...(input.outputTokens !== undefined ? { outputTokens: input.outputTokens } : {}),\n ...(input.reasoningTokens !== undefined ? { reasoningTokens: input.reasoningTokens } : {}),\n ...(input.cacheReadTokens !== undefined ? { cacheReadTokens: input.cacheReadTokens } : {}),\n ...(input.cacheWriteTokens !== undefined ? { cacheWriteTokens: input.cacheWriteTokens } : {}),\n ...(input.costUsd !== undefined ? { costUsd: input.costUsd } : {}),\n ...(input.extras ?? {}),\n } as NewChatMessageRow\n const [insertResult] = await runSqliteStatements(db, [\n db.insert(messages).values(values).returning(),\n db.update(threads).set({ updatedAt: new Date() }).where(eq(threads.id, input.threadId)),\n ])\n const row = (insertResult as TMessage[] | undefined)?.[0]\n if (!row) throw new Error('message insert returned no row')\n return row\n },\n\n async updateMessage(id, patch) {\n const values = {\n ...(patch.content !== undefined ? { content: patch.content } : {}),\n ...(patch.parts !== undefined ? { parts: patch.parts } : {}),\n ...(patch.toolName !== undefined ? { toolName: patch.toolName } : {}),\n ...(patch.model !== undefined ? { model: patch.model } : {}),\n ...(patch.requestedModel !== undefined ? { requestedModel: patch.requestedModel } : {}),\n ...(patch.servedModel !== undefined ? { servedModel: patch.servedModel } : {}),\n ...(patch.servedProvider !== undefined ? { servedProvider: patch.servedProvider } : {}),\n ...(patch.servedSource !== undefined ? { servedSource: patch.servedSource } : {}),\n ...(patch.inputTokens !== undefined ? { inputTokens: patch.inputTokens } : {}),\n ...(patch.outputTokens !== undefined ? { outputTokens: patch.outputTokens } : {}),\n ...(patch.reasoningTokens !== undefined ? { reasoningTokens: patch.reasoningTokens } : {}),\n ...(patch.cacheReadTokens !== undefined ? { cacheReadTokens: patch.cacheReadTokens } : {}),\n ...(patch.cacheWriteTokens !== undefined ? { cacheWriteTokens: patch.cacheWriteTokens } : {}),\n ...(patch.costUsd !== undefined ? { costUsd: patch.costUsd } : {}),\n ...(patch.extras ?? {}),\n }\n if (Object.keys(values).length === 0) {\n const [current] = await db.select().from(messages).where(eq(messages.id, id))\n return (current as TMessage | undefined) ?? null\n }\n // The thread bump reads the row's own `thread_id` rather than trusting a\n // caller-supplied one: a message never moves thread, so the subquery is\n // the authoritative source and one fewer parameter to get wrong.\n const [updateResult] = await runSqliteStatements(db, [\n db.update(messages).set(values).where(eq(messages.id, id)).returning(),\n db.update(threads).set({ updatedAt: new Date() })\n .where(eq(threads.id, sql`(select ${messages.threadId} from ${messages} where ${messages.id} = ${id})`)),\n ])\n return (updateResult as TMessage[] | undefined)?.[0] ?? null\n },\n\n async deleteMessage(id) {\n const deleted = await db.delete(messages).where(eq(messages.id, id)).returning()\n return (deleted as unknown[]).length > 0\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAaO,IAAM,0BAA0B;AAIhC,IAAM,sBAAN,cAAkC,MAAM;AAAA,EAC7C,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAKO,SAAS,uBAAuB,SAAyB;AAC9D,QAAM,YAAY,QAAQ,MAAM,IAAI,EAAE,KAAK,CAAC,MAAM,EAAE,KAAK,EAAE,SAAS,CAAC,GAAG,KAAK,KAAK;AAClF,MAAI,CAAC,UAAW,QAAO;AAC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,cAAM,CAAC,OAAO,IAAI,MAAM,GAAG,OAAO,EAAE,KAAK,QAAQ,EAAE,MAAM,GAAG,SAAS,IAAI,EAAE,CAAC;AAC5E,eAAQ,WAAoC;AAAA,MAC9C;AAIA,YAAM,CAAC,YAAY,IAAI,MAAM,oBAAoB,IAAI;AAAA,QACnD,GAAG,OAAO,QAAQ,EAAE,IAAI,MAAM,EAAE,MAAM,GAAG,SAAS,IAAI,EAAE,CAAC,EAAE,UAAU;AAAA,QACrE,GAAG,OAAO,OAAO,EAAE,IAAI,EAAE,WAAW,oBAAI,KAAK,EAAE,CAAC,EAC7C,MAAM,GAAG,QAAQ,IAAIA,eAAc,SAAS,QAAQ,SAAS,QAAQ,UAAU,SAAS,EAAE,MAAM,EAAE,GAAG,CAAC;AAAA,MAC3G,CAAC;AACD,aAAQ,eAA0C,CAAC,KAAK;AAAA,IAC1D;AAAA,IAEA,MAAM,cAAc,IAAI;AACtB,YAAM,UAAU,MAAM,GAAG,OAAO,QAAQ,EAAE,MAAM,GAAG,SAAS,IAAI,EAAE,CAAC,EAAE,UAAU;AAC/E,aAAQ,QAAsB,SAAS;AAAA,IACzC;AAAA,EACF;AACF;","names":["sql","sql","workspaceId"]}
1
+ {"version":3,"sources":["../../src/chat-store/core.ts","../../src/chat-store/schema.ts","../../src/chat-store/store.ts"],"sourcesContent":["/**\n * Pure (drizzle-free) pieces of the chat store: thread-title derivation, the\n * bulk-delete bound, message-write contract, and typed input error. Split from\n * `./schema`/`./store`\n * so the root barrel can re-export them without dragging the optional\n * drizzle-orm peer into every root-entry consumer.\n */\n\nimport type { ChatMessagePart } from './parts'\n\n/** Bounds a single bulk-delete request's write set; product surfaces cap\n * thread lists at far fewer, so a larger batch is a malformed or hostile\n * request. (Lifted from legal's api.threads.bulk-delete route.) */\nexport const BULK_DELETE_MAX_THREADS = 200\n\n/** Invalid caller input (missing/oversized ids, empty title). Products map it\n * to a 400; anything else out of the store is a real failure. */\nexport class ChatStoreInputError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'ChatStoreInputError'\n }\n}\n\n/** Thread titles come from the first message — keep the list scannable by\n * storing only its first non-empty line, capped at 80 chars, never the whole\n * multi-page prompt. (Lifted verbatim from legal's chat.new route.) */\nexport function threadTitleFromMessage(message: string): string {\n const firstLine = message.split('\\n').find((l) => l.trim().length > 0)?.trim() ?? ''\n if (!firstLine) return 'New Thread'\n return firstLine.length > 80 ? `${firstLine.slice(0, 79)}…` : firstLine\n}\n\n/** Stored message body, model attribution and usage shared by append and patch adapters. */\nexport type ChatMessageValues = {\n content: string\n parts?: ChatMessagePart[]\n model?: string | null\n requestedModel?: string | null\n servedModel?: string | null\n servedProvider?: string | null\n servedSource?: string | null\n inputTokens?: number | null\n outputTokens?: number | null\n reasoningTokens?: number | null\n cacheReadTokens?: number | null\n cacheWriteTokens?: number | null\n costUsd?: number | null\n}\n","/**\n * Drizzle schema factory for the chat thread/message tables — the same\n * injection pattern as `createTeamTables`: the product owns the workspace\n * table; the factory wires the thread FK into it so the whole graph lives in\n * one drizzle schema with real cascade semantics. Column names, types,\n * defaults, enums, and indexes mirror legal's and gtm's hand-rolled `thread`/\n * `message` tables so a product with those tables adopts the factory without\n * rewriting rows; `tablePrefix` covers products that namespace (tax's\n * `chat_messages` style).\n *\n * The core is the superset the three products agree on. Divergences dropped,\n * and why:\n * - `thread.status` ('active'|'archived', legal+gtm) — archive semantics\n * diverge (tax uses `archivedAt`); product-domain lifecycle → extra column.\n * - `thread.scopeKind`/`scopeKey`/`harness` (gtm) — artifact anchoring and\n * harness pinning are product-domain → extra columns.\n * - tax's `tax_sessions` session columns (`taxYear`, `projectRef`,\n * `agentSessionId`, `agentRuntime`, `agentHarness`, `profile`, `error`,\n * `userId`) — sandbox-session state, not chat state → extra columns.\n * - `message.toolInput`/`toolOutput` (legal+gtm) — duplicate of the tool\n * part's `state.input`/`state.output` inside `parts` (the shape `/stream`'s\n * `normalizePersistedPart` owns); keeping both invites drift.\n * - `message.vaultFiles` (legal+gtm) — vault is product-domain → extra column.\n * - tax's re-declared `turn_events`/`turn_status` DDL — deliberately NOT here;\n * `/stream`'s turn-buffer owns that DDL (`TURN_BUFFER_D1_SCHEMA_SQL`).\n *\n * Kept beyond the intersection: tax's per-message `model`/`inputTokens`/\n * `outputTokens`, extended to the full usage receipt the harness actually\n * reports in `step-finish` parts (`tokens {input, output, reasoning,\n * cache{read, write}}` + `cost`) — see `./parts`.\n *\n * `threadExtraColumns`/`messageExtraColumns` merge product columns into the\n * table definitions (the `/missions` opaque-extras pattern: the store writes\n * `extras` values verbatim in the SAME insert statement and never infers their\n * meaning). A product declaring a `metadata` column may use the store\n * metadata merge-patch operation; its fields remain opaque product data.\n *\n * SERVER-side module (D1/libsql/better-sqlite3 behind a worker or server\n * route) — but free of `node:` builtins on purpose: D1 workers have none.\n */\n\nimport { sql } from 'drizzle-orm'\nimport { index, integer, real, sqliteTable, text, uniqueIndex } from 'drizzle-orm/sqlite-core'\nimport type {\n AnySQLiteColumn,\n AnySQLiteTable,\n SQLiteColumnBuilderBase,\n SQLiteTableExtraConfigValue,\n} from 'drizzle-orm/sqlite-core'\nimport type { ChatMessagePart } from './parts'\n\n/** A product table referenced by FK — only the `id` column is touched. */\nexport type ChatParentTable = AnySQLiteTable & { id: AnySQLiteColumn }\n\n/** Define options to customize chat thread and message table creation including workspace and naming prefixes */\nexport interface CreateChatTablesOptions<\n TThreadExtras extends Record<string, SQLiteColumnBuilderBase> = {},\n TMessageExtras extends Record<string, SQLiteColumnBuilderBase> = {},\n> {\n /** The product's workspace table — threads reference `workspaceTable.id`\n * with cascade. Omitted: `workspace_id` stays a plain indexed text column\n * (products whose tenant table lives in another database). */\n workspaceTable?: ChatParentTable\n /** Prefixes table AND index names (`'chat_'` → `chat_thread`,\n * `idx_chat_thread_workspace`) for products that namespace chat tables in a\n * shared database. Default: unprefixed `thread`/`message` (legal/gtm row\n * compatibility). */\n tablePrefix?: string\n /** Product columns merged into the thread table (the `/missions` extras\n * pattern) — e.g. a `status` lifecycle enum or gtm's scope columns. */\n threadExtraColumns?: TThreadExtras\n /** Product columns merged into the message table — e.g. legal's\n * `vault_files`. */\n messageExtraColumns?: TMessageExtras\n /**\n * Product indexes appended to the thread table's own, given the built\n * columns (extras included) so a product can index what it added.\n *\n * Names are used VERBATIM — `tablePrefix` is not applied — because these\n * have to byte-match indexes the product's migrations already created.\n *\n * Without this a product with one extra index cannot adopt the factory at\n * all: it keeps a hand-rolled duplicate of the same physical table, and the\n * two drift on the next factory change.\n */\n threadExtraIndexes?: ChatExtraIndexes\n /** Product indexes appended to the message table's own. Same rules as\n * `threadExtraIndexes`. */\n messageExtraIndexes?: ChatExtraIndexes\n}\n\n/**\n * Builds product indexes from a table's columns.\n *\n * The column map is passed untyped because its shape depends on the product's\n * own extras; the RETURN is drizzle's own extra-config type, so the spread\n * below stays inside the union `sqliteTable` expects and the built table keeps\n * its inferred column types. Returning `unknown[]` here would force a cast on\n * the config array, which widens every column to the cross-dialect union and\n * breaks `db.select()` at every call site.\n */\nexport type ChatExtraIndexes = (\n columns: Record<string, AnySQLiteColumn>,\n) => SQLiteTableExtraConfigValue[]\n\nconst hexId = () => text('id').primaryKey().default(sql`(lower(hex(randomblob(16))))`)\n\nconst createdAt = () => integer('created_at', { mode: 'timestamp' }).notNull().default(sql`(unixepoch())`)\n\nconst updatedAt = () => integer('updated_at', { mode: 'timestamp' }).notNull().default(sql`(unixepoch())`)\n\n/** Build chat-related SQLite tables with customizable thread and message columns */\nexport function createChatTables<\n TThreadExtras extends Record<string, SQLiteColumnBuilderBase> = {},\n TMessageExtras extends Record<string, SQLiteColumnBuilderBase> = {},\n>(options: CreateChatTablesOptions<TThreadExtras, TMessageExtras> = {}) {\n const { workspaceTable, tablePrefix = '' } = options\n const threadExtras = options.threadExtraColumns ?? ({} as TThreadExtras)\n const messageExtras = options.messageExtraColumns ?? ({} as TMessageExtras)\n const extraIndexes = (\n build: ChatExtraIndexes | undefined,\n table: Record<string, AnySQLiteColumn>,\n ): SQLiteTableExtraConfigValue[] => build?.(table) ?? []\n\n const threads = sqliteTable(`${tablePrefix}thread`, {\n id: hexId(),\n workspaceId: workspaceTable\n ? text('workspace_id').notNull().references(() => workspaceTable.id, { onDelete: 'cascade' })\n : text('workspace_id').notNull(),\n title: text('title').notNull(),\n category: text('category'),\n isPinned: integer('is_pinned', { mode: 'boolean' }).notNull().default(false),\n createdAt: createdAt(),\n updatedAt: updatedAt(),\n ...threadExtras,\n }, (table) => [\n index(`idx_${tablePrefix}thread_workspace`).on(table.workspaceId),\n // Supports the store's list ordering (updatedAt desc within a workspace).\n index(`idx_${tablePrefix}thread_workspace_updated`).on(table.workspaceId, table.updatedAt),\n ...extraIndexes(options.threadExtraIndexes, table as unknown as Record<string, AnySQLiteColumn>),\n ])\n\n const messages = sqliteTable(`${tablePrefix}message`, {\n id: hexId(),\n threadId: text('thread_id').notNull().references(() => threads.id, { onDelete: 'cascade' }),\n role: text('role', { enum: ['user', 'assistant', 'system', 'tool'] }).notNull(),\n content: text('content').notNull(),\n parts: text('parts', { mode: 'json' }).$type<ChatMessagePart[]>().default([]),\n toolName: text('tool_name'),\n model: text('model'),\n requestedModel: text('requested_model'),\n servedModel: text('served_model'),\n servedProvider: text('served_provider'),\n servedSource: text('served_model_source'),\n // Usage receipt, flattened from the harness's `step-finish` shape\n // (`tokens {input, output, reasoning, cache{read, write}}` + `cost`).\n inputTokens: integer('input_tokens'),\n outputTokens: integer('output_tokens'),\n reasoningTokens: integer('reasoning_tokens'),\n cacheReadTokens: integer('cache_read_tokens'),\n cacheWriteTokens: integer('cache_write_tokens'),\n costUsd: real('cost_usd'),\n createdAt: createdAt(),\n ...messageExtras,\n }, (table) => [\n index(`idx_${tablePrefix}message_thread`).on(table.threadId),\n index(`idx_${tablePrefix}message_thread_created`).on(table.threadId, table.createdAt),\n ...extraIndexes(options.messageExtraIndexes, table as unknown as Record<string, AnySQLiteColumn>),\n ])\n\n return { threads, messages }\n}\n\n/**\n * Build the `thread_artifact_link` table: artifacts a thread mentioned or\n * touched beyond its own scope, inserted once on first reference. It powers a\n * thread's \"also discussed\" chips and the reverse \"which threads touched this\n * file\" lookup. `kinds` is the product's artifact-kind enum.\n */\nexport function createThreadArtifactLinksTable<const Kind extends string>(\n threadTable: ChatParentTable,\n kinds: readonly [Kind, ...Kind[]],\n) {\n return sqliteTable('thread_artifact_link', {\n id: hexId(),\n threadId: text('thread_id').notNull().references(() => threadTable.id, { onDelete: 'cascade' }),\n artifactKind: text('artifact_kind', { enum: kinds }).notNull(),\n artifactKey: text('artifact_key').notNull(),\n firstReferencedAt: integer('first_referenced_at', { mode: 'timestamp' }).notNull().default(sql`(unixepoch())`),\n }, (table) => [\n index('idx_thread_artifact_link_thread').on(table.threadId),\n uniqueIndex('idx_thread_artifact_link_unique').on(table.threadId, table.artifactKind, table.artifactKey),\n index('idx_thread_artifact_link_reverse').on(table.artifactKind, table.artifactKey),\n ])\n}\n\n/**\n * Build the `agent_run` table: one row per agent run in a workspace, with the\n * product's run telemetry as JSON `metadata`. `idx_agent_run_workspace` covers\n * `(workspace_id, agent_id)`, or `workspace_id` alone with `indexAgentId: false`\n * for products whose migration created it that way.\n */\nexport function createAgentRunsTable<Metadata = Record<string, unknown>>(\n workspaceTable: ChatParentTable,\n options: { indexAgentId?: boolean } = {},\n) {\n return sqliteTable('agent_run', {\n id: hexId(),\n workspaceId: text('workspace_id').notNull().references(() => workspaceTable.id, { onDelete: 'cascade' }),\n agentId: text('agent_id').notNull(),\n status: text('status', { enum: ['running', 'completed', 'failed'] }).notNull().default('running'),\n success: integer('success', { mode: 'boolean' }).notNull().default(true),\n resultSummary: text('result_summary'),\n metadata: text('metadata', { mode: 'json' }).$type<Metadata>(),\n startedAt: integer('started_at', { mode: 'timestamp' }).notNull().default(sql`(unixepoch())`),\n completedAt: integer('completed_at', { mode: 'timestamp' }),\n }, (table) => [\n options.indexAgentId === false\n ? index('idx_agent_run_workspace').on(table.workspaceId)\n : index('idx_agent_run_workspace').on(table.workspaceId, table.agentId),\n ])\n}\n\n/**\n * The base (no-extras) table pair, pinned via an instantiation expression:\n * `ReturnType<typeof createChatTables>` on the bare generic substitutes the\n * extras params with their CONSTRAINT (`Record<string,\n * SQLiteColumnBuilderBase>`), stamping an index signature into the column map\n * that widens every concrete column to `unknown`/`notNull: false` — concrete\n * factory results then fail `extends ChatTables`. (`teams`' `createTeamTables`\n * is non-generic, so its plain `ReturnType` never hits this.)\n */\nexport type ChatTables = ReturnType<typeof createChatTables<{}, {}>>\n\n/** Resolve the selected fields of a chat thread row from the chat threads table */\nexport type ChatThreadRow = ChatTables['threads']['$inferSelect']\n/** Resolve the selected structure of a chat message row from the messages table */\nexport type ChatMessageRow = ChatTables['messages']['$inferSelect']\n/** Resolve the type for inserting a new chat thread row into the threads table */\nexport type NewChatThreadRow = ChatTables['threads']['$inferInsert']\n/** Resolve the type for inserting a new chat message row into the messages table */\nexport type NewChatMessageRow = ChatTables['messages']['$inferInsert']\n","/**\n * Typed CRUD over the tables from `createChatTables`. Works against any\n * SQLite drizzle driver (D1, libsql, better-sqlite3) — builders are awaited,\n * never `.run()`/`.all()`, so sync and async drivers behave identically.\n *\n * Access control is an injected seam, never an import: single-thread routes\n * check workspace access themselves (they know the thread), while\n * `bulkDeleteThreads` REQUIRES an `assertAccess` callback because one request\n * can span workspaces — it is called once per distinct workspace and any\n * throw rejects the whole request before a single delete runs (fail-closed;\n * legal's bulk-delete semantics).\n *\n * Deletes run messages-first in ONE `db.batch` round trip when the driver has\n * one (D1, libsql), so a partial failure never leaves orphaned rows behind a\n * deleted thread; drivers without `batch` (better-sqlite3) fall back to\n * sequential awaits in the same order.\n */\n\nimport { and, asc, desc, eq, getTableColumns, gte, inArray, lt, sql, type SQL } from 'drizzle-orm'\nimport type { AnySQLiteColumn, BaseSQLiteDatabase } from 'drizzle-orm/sqlite-core'\nimport {\n runSqliteStatements,\n type SqliteBatchDatabase,\n} from '../store'\nimport { type ChatMessageValues, BULK_DELETE_MAX_THREADS, ChatStoreInputError, threadTitleFromMessage } from './core'\nimport type { ChatMessageRow, ChatTables, ChatThreadRow, NewChatMessageRow, NewChatThreadRow } from './schema'\n\n/** Any SQLite drizzle database — `any` erases the driver-specific run-result\n * and schema generics so better-sqlite3, D1, and libsql handles all fit.\n * `batch` is structural: present on D1/libsql drizzle instances. */\nexport type ChatDatabase = BaseSQLiteDatabase<'sync' | 'async', any, any> &\n SqliteBatchDatabase\n\n/** Product-injected access check. Throw to deny; the store never interprets\n * users or roles itself. */\nexport type WorkspaceAccessCheck = (workspaceId: string) => void | Promise<void>\n\n/** Define input parameters for listing threads within a workspace with pagination options */\nexport interface ListThreadsInput {\n workspaceId: string\n /** Clamped to 1..200; default 50 (legal's list route semantics). */\n limit?: number\n /** Clamped to >= 0; default 0. */\n offset?: number\n}\n\n/** Represent a paginated collection of chat threads with total count and pagination details */\nexport interface ListThreadsResult<TThread = ChatThreadRow> {\n threads: TThread[]\n total: number\n limit: number\n offset: number\n}\n\n/** Define input parameters required to create a new thread in a workspace */\nexport interface CreateThreadInput {\n /** Caller-assigned primary key. The agent gateway uses its validated\n * conversation id so API and browser turns share one durable thread. */\n id?: string\n workspaceId: string\n /** Title source when `title` is absent: first non-empty line, 80-char cap\n * (`threadTitleFromMessage`). */\n firstMessage?: string\n /** Explicit title; still normalized through `threadTitleFromMessage` so a\n * multi-page paste never becomes a sidebar entry. */\n title?: string\n category?: string | null\n isPinned?: boolean\n /** Opaque product-column values written verbatim in the SAME insert (the\n * `/missions` extras pattern). Never read, validated, or defaulted here. */\n extras?: Record<string, unknown>\n}\n\n/** Define input parameters for appending a message to a chat thread with optional metadata */\nexport interface AppendMessageInput extends ChatMessageValues {\n /** Caller-assigned primary key. Omitted, the column default assigns a random\n * hex id (today's behavior). Incremental assistant persistence passes a\n * DETERMINISTIC id derived from the turn's own identity, so a re-entered\n * turn (crashed worker, durable-driver retry) finds and updates the row a\n * previous attempt started instead of inserting a second one. */\n id?: string\n threadId: string\n role: 'user' | 'assistant' | 'system' | 'tool'\n toolName?: string | null\n /** Opaque product-column values written verbatim in the SAME insert. */\n extras?: Record<string, unknown>\n}\n\n/** Fields an existing message row may be patched with. Every field is\n * optional and only DEFINED fields are written, so a partial patch never\n * clears a column it does not mention. `threadId` and `role` are absent on\n * purpose: a message never moves thread or changes speaker.\n *\n * Exists for incremental assistant persistence — the streaming turn writes\n * the row once and then patches it as content accumulates, so the durable\n * transcript is at most one cadence interval behind the live stream. */\nexport interface UpdateMessageInput extends Partial<ChatMessageValues> {\n toolName?: string | null\n /** Opaque product-column values written verbatim in the SAME update. */\n extras?: Record<string, unknown>\n}\n\n/** Define options to configure message listing with optional limit and offset parameters */\nexport interface ListMessagesOptions {\n limit?: number\n offset?: number\n}\n\n/** Define input for bulk deleting threads with access checks per workspace */\nexport interface BulkDeleteThreadsInput {\n ids: string[]\n /** Optional single-workspace fence for products whose route already resolved\n * one active workspace. Omitted preserves the multi-workspace legal route. */\n workspaceId?: string\n /** Called once per distinct workspace the ids touch, before ANY delete. */\n assertAccess: WorkspaceAccessCheck\n}\n\n/** Delete threads selected by their last activity time within one workspace.\n *\n * Products can add a lifecycle predicate such as `status = 'active'` through\n * `where`; the store still owns workspace scope, access ordering, and message\n * cleanup for every consumer. */\nexport interface BulkDeleteThreadsByUpdatedAtInput {\n workspaceId: string\n /** Exclusive upper bound: rows older than this instant. */\n updatedBefore?: Date\n /** Inclusive lower bound: rows updated at or after this instant. */\n updatedAfter?: Date\n where?: SQL\n /** Called before any delete for the requested workspace. */\n assertAccess: WorkspaceAccessCheck\n}\n\n/** Manage chat threads and messages with operations for listing, creating, updating, and deleting data */\nexport interface ChatStore<TThread = ChatThreadRow, TMessage = ChatMessageRow> {\n listThreads(input: ListThreadsInput): Promise<ListThreadsResult<TThread>>\n getThread(threadId: string): Promise<TThread | null>\n createThread(input: CreateThreadInput): Promise<TThread>\n renameThread(threadId: string, title: string): Promise<TThread | null>\n pinThread(threadId: string, isPinned: boolean): Promise<TThread | null>\n /** Messages + thread in one batch. Resolves false when the thread does not\n * exist. `assertAccess` (optional) receives the thread's workspaceId before\n * the delete — single-thread callers usually check access themselves. */\n deleteThread(threadId: string, options?: { assertAccess?: WorkspaceAccessCheck }): Promise<boolean>\n bulkDeleteThreads(input: BulkDeleteThreadsInput): Promise<{ deleted: number }>\n bulkDeleteThreadsByUpdatedAt(input: BulkDeleteThreadsByUpdatedAtInput): Promise<{ deleted: number }>\n /** Ordered oldest-first: `created_at`, then rowid (insertion order within a\n * same-second burst — a user+assistant pair lands in one epoch second). */\n listMessages(threadId: string, options?: ListMessagesOptions): Promise<TMessage[]>\n getMessage(id: string): Promise<TMessage | null>\n /** Atomic JSON Merge Patch for a product-declared metadata column. Null removes keys;\n * expected top-level fields fence the update against another attempt. Opaque values stay product-owned. */\n patchMessageMetadata(id: string, mergePatch: Record<string, unknown>, expected?: { fields: Record<string, unknown> } | { snapshot: Record<string, unknown> }): Promise<TMessage | null>\n /** Inserts the message and bumps the thread's `updatedAt` in one batch so\n * workspace recency sorts stay truthful. */\n appendMessage(input: AppendMessageInput): Promise<TMessage>\n /** Patches an existing message and bumps its thread's `updatedAt` in the\n * same batch. Resolves `null` when the id does not exist. Only defined\n * patch fields are written. */\n updateMessage(id: string, patch: UpdateMessageInput): Promise<TMessage | null>\n /** Removes one message. Resolves false when the id does not exist. Used by\n * incremental persistence to retract a draft row for a turn that ended\n * producing nothing, so an empty assistant row is never left behind. */\n deleteMessage(id: string): Promise<boolean>\n}\n\nfunction clampLimit(limit: number | undefined, fallback: number, max: number): number {\n const value = Number.isFinite(limit) ? Math.trunc(limit as number) : fallback\n return Math.min(Math.max(value, 1), max)\n}\n\nfunction clampOffset(offset: number | undefined): number {\n const value = Number.isFinite(offset) ? Math.trunc(offset as number) : 0\n return Math.max(value, 0)\n}\n\n/** Create a chat store managing threads and messages based on the provided database and tables */\nexport function createChatStore<TTables extends ChatTables>(\n db: ChatDatabase,\n tables: TTables,\n): ChatStore<TTables['threads']['$inferSelect'], TTables['messages']['$inferSelect']> {\n type TThread = TTables['threads']['$inferSelect']\n type TMessage = TTables['messages']['$inferSelect']\n const threads = tables.threads as ChatTables['threads']\n const messages = tables.messages as ChatTables['messages']\n\n return {\n async listThreads(input) {\n const limit = clampLimit(input.limit, 50, 200)\n const offset = clampOffset(input.offset)\n const scope = eq(threads.workspaceId, input.workspaceId)\n const [list, [countRow]] = await Promise.all([\n db.select().from(threads).where(scope)\n // `id` tiebreak keeps pagination stable across same-second updates.\n .orderBy(desc(threads.updatedAt), asc(threads.id))\n .limit(limit)\n .offset(offset),\n db.select({ total: sql<number>`count(*)` }).from(threads).where(scope),\n ])\n return { threads: list as TThread[], total: countRow?.total ?? 0, limit, offset }\n },\n\n async getThread(threadId) {\n const [row] = await db.select().from(threads).where(eq(threads.id, threadId)).limit(1)\n return (row as TThread | undefined) ?? null\n },\n\n async createThread(input) {\n const title = threadTitleFromMessage(input.title ?? input.firstMessage ?? '')\n const values = {\n ...(input.id !== undefined ? { id: input.id } : {}),\n workspaceId: input.workspaceId,\n title,\n ...(input.category !== undefined ? { category: input.category } : {}),\n ...(input.isPinned !== undefined ? { isPinned: input.isPinned } : {}),\n ...(input.extras ?? {}),\n } as NewChatThreadRow\n const [row] = await db.insert(threads).values(values).returning()\n if (!row) throw new Error('thread insert returned no row')\n return row as TThread\n },\n\n async renameThread(threadId, title) {\n const trimmed = title.trim()\n if (!trimmed) throw new ChatStoreInputError('Missing title')\n const [row] = await db.update(threads)\n .set({ title: trimmed, updatedAt: new Date() })\n .where(eq(threads.id, threadId))\n .returning()\n return (row as TThread | undefined) ?? null\n },\n\n async pinThread(threadId, isPinned) {\n const [row] = await db.update(threads)\n .set({ isPinned, updatedAt: new Date() })\n .where(eq(threads.id, threadId))\n .returning()\n return (row as TThread | undefined) ?? null\n },\n\n async deleteThread(threadId, options) {\n const [existing] = await db.select({ id: threads.id, workspaceId: threads.workspaceId })\n .from(threads)\n .where(eq(threads.id, threadId))\n .limit(1)\n if (!existing) return false\n if (options?.assertAccess) await options.assertAccess(existing.workspaceId)\n // Messages first so a partial failure never leaves orphaned rows behind\n // a deleted thread.\n await runSqliteStatements(db, [\n db.delete(messages).where(eq(messages.threadId, threadId)),\n db.delete(threads).where(eq(threads.id, threadId)),\n ])\n return true\n },\n\n async bulkDeleteThreads(input) {\n const { ids, workspaceId, assertAccess } = input\n if (typeof assertAccess !== 'function') throw new ChatStoreInputError('Missing assertAccess')\n if (!Array.isArray(ids) || ids.length === 0 || !ids.every((id) => typeof id === 'string' && id.length > 0)) {\n throw new ChatStoreInputError('Missing ids')\n }\n if (ids.length > BULK_DELETE_MAX_THREADS) {\n throw new ChatStoreInputError(`Too many ids (max ${BULK_DELETE_MAX_THREADS})`)\n }\n if (workspaceId !== undefined && !workspaceId.trim()) {\n throw new ChatStoreInputError('Invalid workspaceId')\n }\n\n const scope = workspaceId\n ? and(inArray(threads.id, ids), eq(threads.workspaceId, workspaceId))\n : inArray(threads.id, ids)\n const rows = await db.select({ id: threads.id, workspaceId: threads.workspaceId })\n .from(threads)\n .where(scope)\n if (rows.length === 0) return { deleted: 0 }\n\n // Access is verified once per workspace the ids touch. Fail-closed: one\n // inaccessible workspace rejects the whole request before any delete.\n // Sorted so the check order (and therefore which denial surfaces) is\n // deterministic — row order follows random hex ids and varies per run.\n const workspaceIds = [...new Set(rows.map((row) => row.workspaceId))].sort()\n for (const workspaceId of workspaceIds) {\n await assertAccess(workspaceId)\n }\n\n const foundIds = rows.map((row) => row.id)\n await runSqliteStatements(db, [\n db.delete(messages).where(inArray(messages.threadId, foundIds)),\n db.delete(threads).where(inArray(threads.id, foundIds)),\n ])\n return { deleted: foundIds.length }\n },\n\n async bulkDeleteThreadsByUpdatedAt(input) {\n const { workspaceId, updatedBefore, updatedAfter, where, assertAccess } = input\n if (typeof assertAccess !== 'function') throw new ChatStoreInputError('Missing assertAccess')\n if (!workspaceId.trim()) throw new ChatStoreInputError('Missing workspaceId')\n if (updatedBefore === undefined && updatedAfter === undefined) {\n throw new ChatStoreInputError('Missing updatedAt boundary')\n }\n for (const boundary of [updatedBefore, updatedAfter]) {\n if (boundary !== undefined && Number.isNaN(boundary.getTime())) {\n throw new ChatStoreInputError('Invalid updatedAt boundary')\n }\n }\n\n const conditions = [eq(threads.workspaceId, workspaceId)]\n if (updatedBefore) conditions.push(lt(threads.updatedAt, updatedBefore))\n if (updatedAfter) conditions.push(gte(threads.updatedAt, updatedAfter))\n if (where) conditions.push(where)\n const scope = and(...conditions)\n const [countRow] = await db.select({ total: sql<number>`count(*)` })\n .from(threads)\n .where(scope)\n const deleted = Number(countRow?.total ?? 0)\n if (deleted === 0) return { deleted: 0 }\n\n await assertAccess(workspaceId)\n // Keep the age path unbounded without constructing a giant host-parameter\n // list; the subquery lets SQLite/D1 stream the matching thread ids.\n const matchingThreads = db.select({ id: threads.id }).from(threads).where(scope)\n await runSqliteStatements(db, [\n db.delete(messages).where(inArray(messages.threadId, matchingThreads)),\n db.delete(threads).where(scope),\n ])\n return { deleted }\n },\n\n async listMessages(threadId, options) {\n const query = db.select().from(messages)\n .where(eq(messages.threadId, threadId))\n .orderBy(asc(messages.createdAt), sql`rowid`)\n .$dynamic()\n if (options?.limit !== undefined) query.limit(clampLimit(options.limit, 1, 1000))\n if (options?.offset !== undefined) query.offset(clampOffset(options.offset))\n return await query as TMessage[]\n },\n\n async getMessage(id) {\n const [row] = await db.select().from(messages).where(eq(messages.id, id)).limit(1)\n return (row as TMessage | undefined) ?? null\n },\n\n async patchMessageMetadata(id, mergePatch, expected) {\n const metadata = (getTableColumns(tables.messages) as Record<string, AnySQLiteColumn>).metadata\n if (!metadata) throw new Error('Chat metadata requires a product-declared metadata column')\n const guards = Object.entries(expected && 'fields' in expected ? expected.fields : {}).map(([field, value]) => {\n const encoded = JSON.stringify(value)\n if (encoded === undefined) throw new Error('Expected chat metadata must be JSON')\n return sql`json_extract(${metadata}, ${`$.${JSON.stringify(field)}`}) IS json_extract(${encoded}, '$')`\n })\n if (expected && 'snapshot' in expected) guards.push(sql`coalesce(${metadata}, '{}') = ${JSON.stringify(expected.snapshot)}`)\n const [row] = await db.update(messages).set({\n metadata: sql`json_patch(coalesce(${metadata}, '{}'), ${JSON.stringify(mergePatch)})`,\n } as Partial<NewChatMessageRow>).where(and(eq(messages.id, id), ...guards)).returning()\n return (row as TMessage | undefined) ?? null\n },\n\n async appendMessage(input) {\n const values = {\n ...(input.id !== undefined ? { id: input.id } : {}),\n threadId: input.threadId,\n role: input.role,\n content: input.content,\n ...(input.parts !== undefined ? { parts: input.parts } : {}),\n ...(input.toolName !== undefined ? { toolName: input.toolName } : {}),\n ...(input.model !== undefined ? { model: input.model } : {}),\n ...(input.requestedModel !== undefined ? { requestedModel: input.requestedModel } : {}),\n ...(input.servedModel !== undefined ? { servedModel: input.servedModel } : {}),\n ...(input.servedProvider !== undefined ? { servedProvider: input.servedProvider } : {}),\n ...(input.servedSource !== undefined ? { servedSource: input.servedSource } : {}),\n ...(input.inputTokens !== undefined ? { inputTokens: input.inputTokens } : {}),\n ...(input.outputTokens !== undefined ? { outputTokens: input.outputTokens } : {}),\n ...(input.reasoningTokens !== undefined ? { reasoningTokens: input.reasoningTokens } : {}),\n ...(input.cacheReadTokens !== undefined ? { cacheReadTokens: input.cacheReadTokens } : {}),\n ...(input.cacheWriteTokens !== undefined ? { cacheWriteTokens: input.cacheWriteTokens } : {}),\n ...(input.costUsd !== undefined ? { costUsd: input.costUsd } : {}),\n ...(input.extras ?? {}),\n } as NewChatMessageRow\n const [insertResult] = await runSqliteStatements(db, [\n db.insert(messages).values(values).returning(),\n db.update(threads).set({ updatedAt: new Date() }).where(eq(threads.id, input.threadId)),\n ])\n const row = (insertResult as TMessage[] | undefined)?.[0]\n if (!row) throw new Error('message insert returned no row')\n return row\n },\n\n async updateMessage(id, patch) {\n const values = {\n ...(patch.content !== undefined ? { content: patch.content } : {}),\n ...(patch.parts !== undefined ? { parts: patch.parts } : {}),\n ...(patch.toolName !== undefined ? { toolName: patch.toolName } : {}),\n ...(patch.model !== undefined ? { model: patch.model } : {}),\n ...(patch.requestedModel !== undefined ? { requestedModel: patch.requestedModel } : {}),\n ...(patch.servedModel !== undefined ? { servedModel: patch.servedModel } : {}),\n ...(patch.servedProvider !== undefined ? { servedProvider: patch.servedProvider } : {}),\n ...(patch.servedSource !== undefined ? { servedSource: patch.servedSource } : {}),\n ...(patch.inputTokens !== undefined ? { inputTokens: patch.inputTokens } : {}),\n ...(patch.outputTokens !== undefined ? { outputTokens: patch.outputTokens } : {}),\n ...(patch.reasoningTokens !== undefined ? { reasoningTokens: patch.reasoningTokens } : {}),\n ...(patch.cacheReadTokens !== undefined ? { cacheReadTokens: patch.cacheReadTokens } : {}),\n ...(patch.cacheWriteTokens !== undefined ? { cacheWriteTokens: patch.cacheWriteTokens } : {}),\n ...(patch.costUsd !== undefined ? { costUsd: patch.costUsd } : {}),\n ...(patch.extras ?? {}),\n }\n if (Object.keys(values).length === 0) {\n const [current] = await db.select().from(messages).where(eq(messages.id, id))\n return (current as TMessage | undefined) ?? null\n }\n // The thread bump reads the row's own `thread_id` rather than trusting a\n // caller-supplied one: a message never moves thread, so the subquery is\n // the authoritative source and one fewer parameter to get wrong.\n const [updateResult] = await runSqliteStatements(db, [\n db.update(messages).set(values).where(eq(messages.id, id)).returning(),\n db.update(threads).set({ updatedAt: new Date() })\n .where(eq(threads.id, sql`(select ${messages.threadId} from ${messages} where ${messages.id} = ${id})`)),\n ])\n return (updateResult as TMessage[] | undefined)?.[0] ?? null\n },\n\n async deleteMessage(id) {\n const deleted = await db.delete(messages).where(eq(messages.id, id)).returning()\n return (deleted as unknown[]).length > 0\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAaO,IAAM,0BAA0B;AAIhC,IAAM,sBAAN,cAAkC,MAAM;AAAA,EAC7C,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAKO,SAAS,uBAAuB,SAAyB;AAC9D,QAAM,YAAY,QAAQ,MAAM,IAAI,EA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C;AAAA,QAChE,GAAI,MAAM,UAAU,CAAC;AAAA,MACvB;AACA,UAAI,OAAO,KAAK,MAAM,EAAE,WAAW,GAAG;AACpC,cAAM,CAAC,OAAO,IAAI,MAAM,GAAG,OAAO,EAAE,KAAK,QAAQ,EAAE,MAAM,GAAG,SAAS,IAAI,EAAE,CAAC;AAC5E,eAAQ,WAAoC;AAAA,MAC9C;AAIA,YAAM,CAAC,YAAY,IAAI,MAAM,oBAAoB,IAAI;AAAA,QACnD,GAAG,OAAO,QAAQ,EAAE,IAAI,MAAM,EAAE,MAAM,GAAG,SAAS,IAAI,EAAE,CAAC,EAAE,UAAU;AAAA,QACrE,GAAG,OAAO,OAAO,EAAE,IAAI,EAAE,WAAW,oBAAI,KAAK,EAAE,CAAC,EAC7C,MAAM,GAAG,QAAQ,IAAIA,eAAc,SAAS,QAAQ,SAAS,QAAQ,UAAU,SAAS,EAAE,MAAM,EAAE,GAAG,CAAC;AAAA,MAC3G,CAAC;AACD,aAAQ,eAA0C,CAAC,KAAK;AAAA,IAC1D;AAAA,IAEA,MAAM,cAAc,IAAI;AACtB,YAAM,UAAU,MAAM,GAAG,OAAO,QAAQ,EAAE,MAAM,GAAG,SAAS,IAAI,EAAE,CAAC,EAAE,UAAU;AAC/E,aAAQ,QAAsB,SAAS;AAAA,IACzC;AAAA,EACF;AACF;","names":["sql","sql","workspaceId"]}
@@ -56,7 +56,7 @@ import type { Part as HarnessWirePart } from '@tangle-network/agent-interface';
56
56
  import type { ChatInteractionField, ChatInteractionStatus, InteractionAnswers, NoticeKind } from '../web-react/chat-interactions';
57
57
  import { type WorkProductPersistedPart } from '../work-product/types';
58
58
  import { type ChatPlanPersistedPart } from '../plans/index';
59
- import { type ChatAttachmentInput, type ChatAttachmentKind, type ChatMentionKind, type FileMention } from '../chat-routes/wire';
59
+ import { type ChatAttachmentInput, type ChatAttachmentKind, type ChatMention, type ChatMentionKind } from '../chat-routes/wire';
60
60
  export type { ChatMentionKind, ChatAttachmentKind };
61
61
  /** Start/end wall-clock millis, as normalized by `/stream`'s `normalizeTime`. */
62
62
  export interface ChatPartTime {
@@ -205,13 +205,28 @@ export interface ChatNoticePart {
205
205
  export interface ChatMentionPart {
206
206
  type: 'mention';
207
207
  mentionKind: ChatMentionKind;
208
+ /** The `@`-token identity the message text carries: a workspace-relative
209
+ * path for a file, the handle for an agent. */
208
210
  path: string;
209
211
  name: string;
210
212
  size?: number;
211
213
  turnId?: string;
214
+ /** The stable profile id behind an `agent` mention, so a rename never
215
+ * breaks an old message. Absent on file mentions. */
216
+ agentId?: string;
217
+ }
218
+ /** Who wrote the parts that follow, when one assistant row holds more than one
219
+ * responder: a turn addressed to `@a @b` is one row whose parts read
220
+ * speaker a, a's text, speaker b, b's text. A renderer splits the row at
221
+ * these (`expandSpeakerRows` in `/web`); a row with none is one speaker. */
222
+ export interface ChatSpeakerPart {
223
+ type: 'speaker';
224
+ id: string;
225
+ name: string;
226
+ handle?: string;
212
227
  }
213
228
  /** Represent parts of a chat message including text, reasoning, tools, files, images, subtasks, steps, interactions, notices, plans, and mentions */
214
- export type ChatMessagePart = ChatTextPart | ChatReasoningPart | ChatToolPart | ChatFilePart | ChatImagePart | ChatSubtaskPart | ChatStepStartPart | ChatStepFinishPart | ChatInteractionPart | ChatNoticePart | ChatPlanPart | ChatWorkProductPart | ChatMentionPart;
229
+ export type ChatMessagePart = ChatTextPart | ChatReasoningPart | ChatToolPart | ChatFilePart | ChatImagePart | ChatSubtaskPart | ChatStepStartPart | ChatStepFinishPart | ChatInteractionPart | ChatNoticePart | ChatPlanPart | ChatWorkProductPart | ChatMentionPart | ChatSpeakerPart;
215
230
  /** Every canonical harness wire-part kind must be storable — compile-time
216
231
  * guarantee that a new agent-interface part kind cannot silently fall out of
217
232
  * the persisted vocabulary. */
@@ -242,6 +257,7 @@ export declare function isChatInteractionPart(part: ChatMessagePart): part is Ch
242
257
  * them, `mentionInputToPart` trusts its input, and a read guard stricter than
243
258
  * what the writer can emit would drop rows it produced itself. */
244
259
  export declare function isChatMentionPart(part: unknown): part is ChatMentionPart;
260
+ export declare function isChatSpeakerPart(part: unknown): part is ChatSpeakerPart;
245
261
  /** Every mention part on one message, in stored order. The projection a
246
262
  * transcript renderer runs before deciding which mentions the message text
247
263
  * already shows inline (see `segmentMentionContent` in `/web-react`). */
@@ -250,7 +266,7 @@ export declare function mentionPartsFromMessageParts(parts: ReadonlyArray<Record
250
266
  * part the turn route persists. An absent/non-finite `size` is DROPPED rather
251
267
  * than stored as `undefined`, so a stored row never carries a key that means
252
268
  * nothing. */
253
- export declare function mentionInputToPart(input: FileMention): ChatMentionPart;
269
+ export declare function mentionInputToPart(mention: ChatMention): ChatMentionPart;
254
270
  /** `image` for any `image/*` mime, `file` for everything else (including an
255
271
  * absent/empty mime) — the same split the composer and the persisted-part
256
272
  * discriminant both key on. */
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  validateOpenUIJsonNode
3
- } from "./chunk-DCGATWZ5.js";
3
+ } from "./chunk-XPB2UYHU.js";
4
4
  import {
5
5
  ToolInputError
6
6
  } from "./chunk-F4XBNR5L.js";
@@ -27,4 +27,4 @@ function parseRenderUiSchema(value) {
27
27
  export {
28
28
  parseRenderUiSchema
29
29
  };
30
- //# sourceMappingURL=chunk-6XSQCP6W.js.map
30
+ //# sourceMappingURL=chunk-43CV4JIT.js.map
@@ -2,7 +2,7 @@ import {
2
2
  darkTheme,
3
3
  lightTheme,
4
4
  themeColor
5
- } from "./chunk-UTF7H6BK.js";
5
+ } from "./chunk-EUQ46YWK.js";
6
6
 
7
7
  // src/theme/dom.ts
8
8
  var LIGHT_THEME_COLOR = themeColor(lightTheme.background);
@@ -49,4 +49,4 @@ export {
49
49
  syncThemePreference,
50
50
  THEME_BOOTSTRAP_SCRIPT
51
51
  };
52
- //# sourceMappingURL=chunk-SFZELD6V.js.map
52
+ //# sourceMappingURL=chunk-4JTEPK2G.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  addStepFinishUsage
3
- } from "./chunk-HHPQMFKP.js";
3
+ } from "./chunk-7O62NYGT.js";
4
4
  import {
5
5
  asRecord,
6
6
  asString,
@@ -480,4 +480,4 @@ export {
480
480
  TOOL_ABORTED_ERROR,
481
481
  observeNativeCompletion
482
482
  };
483
- //# sourceMappingURL=chunk-RILVJYXJ.js.map
483
+ //# sourceMappingURL=chunk-5ERXADSW.js.map