@tangle-network/agent-app 0.54.1 → 0.55.0

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 (76) hide show
  1. package/dist/{DesignCanvas-BVBMDXBZ.js → DesignCanvas-OWE67ZX3.js} +4 -4
  2. package/dist/DesignCanvasEditor-VJ3R7RM2.js +15 -0
  3. package/dist/{TimelineEditor-52YEPDX5.js → TimelineEditor-7KBPJQLT.js} +3 -3
  4. package/dist/assets/index.js +1 -26
  5. package/dist/assets/index.js.map +1 -1
  6. package/dist/assets/schema.d.ts +0 -26
  7. package/dist/assistant/index.js +3 -3
  8. package/dist/chat-routes/index.js +2 -2
  9. package/dist/chat-store/index.js +1 -11
  10. package/dist/chat-store/index.js.map +1 -1
  11. package/dist/chat-store/parts.d.ts +0 -10
  12. package/dist/{chunk-JB2GFEOC.js → chunk-2N7PDPLC.js} +3 -3
  13. package/dist/{chunk-CUXCWQMW.js → chunk-47UDWWUN.js} +1 -5
  14. package/dist/chunk-47UDWWUN.js.map +1 -0
  15. package/dist/{chunk-XDB7IBYE.js → chunk-5FAKBTCK.js} +1 -22
  16. package/dist/chunk-5FAKBTCK.js.map +1 -0
  17. package/dist/{chunk-HQ7R6CGM.js → chunk-6NYVAURR.js} +2 -2
  18. package/dist/{chunk-TY2DALJG.js → chunk-7TYQ43TP.js} +1 -10
  19. package/dist/chunk-7TYQ43TP.js.map +1 -0
  20. package/dist/{chunk-RRWC77YY.js → chunk-CFGA7PXM.js} +2 -2
  21. package/dist/{chunk-YJYPXMDL.js → chunk-DKHM4B4A.js} +3 -3
  22. package/dist/{chunk-ZGY6QB4F.js → chunk-MEKOWH5E.js} +2 -2
  23. package/dist/{chunk-H6XQZFTT.js → chunk-OHWQUKBP.js} +1 -5
  24. package/dist/{chunk-H6XQZFTT.js.map → chunk-OHWQUKBP.js.map} +1 -1
  25. package/dist/{chunk-IJDPERPL.js → chunk-PFOJRQ3Q.js} +3 -3
  26. package/dist/{chunk-4XBRPVL3.js → chunk-RSTPXLC3.js} +2 -2
  27. package/dist/{chunk-BVKQKGRK.js → chunk-SISVELAA.js} +1 -9
  28. package/dist/chunk-SISVELAA.js.map +1 -0
  29. package/dist/{chunk-DVOJNI6T.js → chunk-V4JZ5OYC.js} +1 -21
  30. package/dist/chunk-V4JZ5OYC.js.map +1 -0
  31. package/dist/{chunk-LEECH4MY.js → chunk-YHR2P7FY.js} +5 -16
  32. package/dist/chunk-YHR2P7FY.js.map +1 -0
  33. package/dist/design-canvas/export-presets.d.ts +0 -2
  34. package/dist/design-canvas/index.js +1 -11
  35. package/dist/design-canvas/index.js.map +1 -1
  36. package/dist/design-canvas/mcp-tools.d.ts +0 -6
  37. package/dist/design-canvas-react/engine.js +3 -3
  38. package/dist/design-canvas-react/export.d.ts +0 -7
  39. package/dist/design-canvas-react/index.js +6 -8
  40. package/dist/design-canvas-react/index.js.map +1 -1
  41. package/dist/design-canvas-react/lazy.js +1 -1
  42. package/dist/preflight/cli.js +1 -2
  43. package/dist/preflight/cli.js.map +1 -1
  44. package/dist/preflight/index.d.ts +1 -34
  45. package/dist/preflight/index.js +3 -6
  46. package/dist/public-consultation/index.js +2 -2
  47. package/dist/sequences/drizzle.js +1 -1
  48. package/dist/sequences/index.js +1 -7
  49. package/dist/sequences/index.js.map +1 -1
  50. package/dist/sequences/mcp-tools.d.ts +0 -2
  51. package/dist/sequences/model.d.ts +0 -6
  52. package/dist/sequences-react/index.js +3 -3
  53. package/dist/studio/generation.d.ts +0 -5
  54. package/dist/studio/index.js +1 -3
  55. package/dist/studio-react/index.js +1 -1
  56. package/dist/web-react/index.js +3 -5
  57. package/dist/web-react/work-product.d.ts +0 -2
  58. package/dist/work-product-react/index.js +1 -1
  59. package/package.json +1 -1
  60. package/dist/DesignCanvasEditor-IBFHC25D.js +0 -15
  61. package/dist/chunk-BVKQKGRK.js.map +0 -1
  62. package/dist/chunk-CUXCWQMW.js.map +0 -1
  63. package/dist/chunk-DVOJNI6T.js.map +0 -1
  64. package/dist/chunk-LEECH4MY.js.map +0 -1
  65. package/dist/chunk-TY2DALJG.js.map +0 -1
  66. package/dist/chunk-XDB7IBYE.js.map +0 -1
  67. /package/dist/{DesignCanvas-BVBMDXBZ.js.map → DesignCanvas-OWE67ZX3.js.map} +0 -0
  68. /package/dist/{DesignCanvasEditor-IBFHC25D.js.map → DesignCanvasEditor-VJ3R7RM2.js.map} +0 -0
  69. /package/dist/{TimelineEditor-52YEPDX5.js.map → TimelineEditor-7KBPJQLT.js.map} +0 -0
  70. /package/dist/{chunk-JB2GFEOC.js.map → chunk-2N7PDPLC.js.map} +0 -0
  71. /package/dist/{chunk-HQ7R6CGM.js.map → chunk-6NYVAURR.js.map} +0 -0
  72. /package/dist/{chunk-RRWC77YY.js.map → chunk-CFGA7PXM.js.map} +0 -0
  73. /package/dist/{chunk-YJYPXMDL.js.map → chunk-DKHM4B4A.js.map} +0 -0
  74. /package/dist/{chunk-ZGY6QB4F.js.map → chunk-MEKOWH5E.js.map} +0 -0
  75. /package/dist/{chunk-IJDPERPL.js.map → chunk-PFOJRQ3Q.js.map} +0 -0
  76. /package/dist/{chunk-4XBRPVL3.js.map → chunk-RSTPXLC3.js.map} +0 -0
@@ -1,12 +1,12 @@
1
1
  import {
2
2
  DesignCanvas
3
- } from "./chunk-YJYPXMDL.js";
4
- import "./chunk-HQ7R6CGM.js";
5
- import "./chunk-H6XQZFTT.js";
3
+ } from "./chunk-DKHM4B4A.js";
4
+ import "./chunk-6NYVAURR.js";
5
+ import "./chunk-OHWQUKBP.js";
6
6
  import "./chunk-YNSPVKMS.js";
7
7
  import "./chunk-3NCPXNBZ.js";
8
8
  import "./chunk-TXD5HXLE.js";
9
9
  export {
10
10
  DesignCanvas
11
11
  };
12
- //# sourceMappingURL=DesignCanvas-BVBMDXBZ.js.map
12
+ //# sourceMappingURL=DesignCanvas-OWE67ZX3.js.map
@@ -0,0 +1,15 @@
1
+ import {
2
+ DesignCanvasEditor
3
+ } from "./chunk-YHR2P7FY.js";
4
+ import "./chunk-DKHM4B4A.js";
5
+ import "./chunk-TMKSWEVQ.js";
6
+ import "./chunk-CFGA7PXM.js";
7
+ import "./chunk-6NYVAURR.js";
8
+ import "./chunk-OHWQUKBP.js";
9
+ import "./chunk-YNSPVKMS.js";
10
+ import "./chunk-3NCPXNBZ.js";
11
+ import "./chunk-TXD5HXLE.js";
12
+ export {
13
+ DesignCanvasEditor
14
+ };
15
+ //# sourceMappingURL=DesignCanvasEditor-VJ3R7RM2.js.map
@@ -2,11 +2,11 @@ import {
2
2
  SEQUENCE_MEDIA_DRAG_TYPE,
3
3
  TimelineEditor,
4
4
  TimelineEditor_default
5
- } from "./chunk-ZGY6QB4F.js";
6
- import "./chunk-BVKQKGRK.js";
5
+ } from "./chunk-MEKOWH5E.js";
6
+ import "./chunk-SISVELAA.js";
7
7
  export {
8
8
  SEQUENCE_MEDIA_DRAG_TYPE,
9
9
  TimelineEditor,
10
10
  TimelineEditor_default as default
11
11
  };
12
- //# sourceMappingURL=TimelineEditor-52YEPDX5.js.map
12
+ //# sourceMappingURL=TimelineEditor-7KBPJQLT.js.map
@@ -160,21 +160,6 @@ var CopyContentSchema = z.object({
160
160
  platform: z.enum(["instagram", "tiktok", "x", "linkedin", "sms", "email-subject"]),
161
161
  characterCount: z.number().optional()
162
162
  });
163
- var ApprovalEventSchema = z.object({
164
- assetId: z.string(),
165
- variantId: z.string().optional(),
166
- action: z.enum(["approved", "rejected", "edited", "scheduled"]),
167
- editedFields: z.array(z.string()).optional(),
168
- userId: z.string(),
169
- timestamp: z.string()
170
- });
171
- var ConversionMetricsSchema = z.object({
172
- impressions: z.number().nonnegative(),
173
- clicks: z.number().nonnegative(),
174
- conversions: z.number().nonnegative(),
175
- ctr: z.number().nonnegative(),
176
- cvr: z.number().nonnegative()
177
- });
178
163
  var AssetFormatValues = [
179
164
  "email",
180
165
  "image:feed",
@@ -231,23 +216,13 @@ function parseAssetSpec(raw) {
231
216
  const content = contentSchema.parse(raw.content);
232
217
  return { ...base, content };
233
218
  }
234
- function safeParseAssetSpec(raw) {
235
- try {
236
- return parseAssetSpec(raw);
237
- } catch {
238
- return null;
239
- }
240
- }
241
219
  export {
242
- ApprovalEventSchema,
243
220
  BrandTokensSchema,
244
- ConversionMetricsSchema,
245
221
  CopyContentSchema,
246
222
  EmailContentSchema,
247
223
  ImageContentSchema,
248
224
  VideoContentSchema,
249
225
  assetCreateJsonSchema,
250
- parseAssetSpec,
251
- safeParseAssetSpec
226
+ parseAssetSpec
252
227
  };
253
228
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/assets/schema.ts"],"sourcesContent":["import { z } from 'zod'\nimport type { AssetSpec, AssetFormat } from './types'\n\n// --- Brand ---\n\n/** Validate brand token properties including colors, font, logo URL, business name, and voice */\nexport const BrandTokensSchema = z.object({\n primaryColor: z.string(),\n accentColor: z.string(),\n textColor: z.string(),\n fontFamily: z.string(),\n logoUrl: z.string().optional(),\n businessName: z.string(),\n voice: z.string(),\n})\n\n// --- Email ---\n\nconst EmailHeroSectionSchema = z.object({\n type: z.literal('hero'),\n headline: z.string(),\n subheadline: z.string().optional(),\n imageUrl: z.string().optional(),\n ctaLabel: z.string().optional(),\n ctaUrl: z.string().optional(),\n})\n\nconst EmailBodySectionSchema = z.object({\n type: z.literal('body'),\n text: z.string(),\n})\n\nconst EmailFeatureSectionSchema = z.object({\n type: z.literal('feature'),\n headline: z.string(),\n description: z.string(),\n imageUrl: z.string().optional(),\n})\n\nconst EmailTestimonialSectionSchema = z.object({\n type: z.literal('testimonial'),\n quote: z.string(),\n author: z.string(),\n role: z.string().optional(),\n avatarUrl: z.string().optional(),\n})\n\nconst EmailCtaSectionSchema = z.object({\n type: z.literal('cta'),\n label: z.string(),\n url: z.string(),\n subtext: z.string().optional(),\n})\n\nconst EmailDividerSectionSchema = z.object({\n type: z.literal('divider'),\n})\n\nconst EmailSectionSchema = z.discriminatedUnion('type', [\n EmailHeroSectionSchema,\n EmailBodySectionSchema,\n EmailFeatureSectionSchema,\n EmailTestimonialSectionSchema,\n EmailCtaSectionSchema,\n EmailDividerSectionSchema,\n])\n\n/** Validate and parse email content objects with subject, optional preheader, and sections */\nexport const EmailContentSchema = z.object({\n subject: z.string(),\n preheader: z.string().optional(),\n sections: z.array(EmailSectionSchema),\n})\n\n// --- Image ---\n\nconst ImageBackgroundSchema = z.discriminatedUnion('type', [\n z.object({ type: z.literal('color'), value: z.string() }),\n z.object({ type: z.literal('gradient'), from: z.string(), to: z.string(), direction: z.string().optional() }),\n z.object({ type: z.literal('image'), url: z.string(), overlay: z.string().optional(), overlayOpacity: z.number().optional() }),\n])\n\nconst ImageTextLayerSchema = z.object({\n type: z.literal('text'),\n text: z.string(),\n fontSize: z.number().optional(),\n fontWeight: z.enum(['normal', 'bold']).optional(),\n color: z.string().optional(),\n x: z.number(),\n y: z.number(),\n width: z.number().optional(),\n align: z.enum(['left', 'center', 'right']).optional(),\n})\n\nconst ImageImageLayerSchema = z.object({\n type: z.literal('image'),\n url: z.string(),\n x: z.number(),\n y: z.number(),\n width: z.number(),\n height: z.number(),\n opacity: z.number().optional(),\n})\n\nconst ImageShapeLayerSchema = z.object({\n type: z.literal('shape'),\n shape: z.enum(['rect', 'circle', 'rounded-rect']),\n x: z.number(),\n y: z.number(),\n width: z.number(),\n height: z.number(),\n fill: z.string().optional(),\n opacity: z.number().optional(),\n})\n\nconst ImageLogoLayerSchema = z.object({\n type: z.literal('logo'),\n x: z.number(),\n y: z.number(),\n width: z.number().optional(),\n})\n\nconst ImageLayerSchema = z.discriminatedUnion('type', [\n ImageTextLayerSchema,\n ImageImageLayerSchema,\n ImageShapeLayerSchema,\n ImageLogoLayerSchema,\n])\n\nconst ImageSlideSchema = z.object({\n background: ImageBackgroundSchema,\n layers: z.array(ImageLayerSchema),\n})\n\n/** Validate image content with an array of one or more slides containing background details */\nexport const ImageContentSchema = z.object({\n slides: z.array(ImageSlideSchema).min(1),\n})\n\n// --- Video ---\n\nconst VideoTextAnimationSceneSchema = z.object({\n type: z.literal('text-animation'),\n durationSeconds: z.number().positive(),\n headline: z.string(),\n subtext: z.string().optional(),\n animation: z.enum(['fade', 'slide-up', 'typewriter']).optional(),\n background: ImageBackgroundSchema.optional(),\n})\n\nconst VideoImageRevealSceneSchema = z.object({\n type: z.literal('image-reveal'),\n durationSeconds: z.number().positive(),\n imageUrl: z.string(),\n caption: z.string().optional(),\n})\n\nconst VideoSlideSceneSchema = z.object({\n type: z.literal('slide'),\n durationSeconds: z.number().positive(),\n slide: ImageSlideSchema,\n})\n\nconst VideoCountdownSceneSchema = z.object({\n type: z.literal('countdown'),\n durationSeconds: z.number().positive(),\n from: z.number().int().positive(),\n label: z.string().optional(),\n})\n\nconst VideoSceneSchema = z.discriminatedUnion('type', [\n VideoTextAnimationSceneSchema,\n VideoImageRevealSceneSchema,\n VideoSlideSceneSchema,\n VideoCountdownSceneSchema,\n])\n\nconst VideoCaptionSchema = z.object({\n startSeconds: z.number().nonnegative(),\n endSeconds: z.number().positive(),\n text: z.string(),\n})\n\n/** Define the schema for validating video content including duration, scenes, audio, captions, and rendered URL */\nexport const VideoContentSchema = z.object({\n durationSeconds: z.number().positive(),\n scenes: z.array(VideoSceneSchema).min(1),\n audioUrl: z.string().optional(),\n captions: z.array(VideoCaptionSchema).optional(),\n renderedUrl: z.string().optional(),\n})\n\n// --- Copy ---\n\n/** Validate and parse copy content with headline, body, optional hashtags, platform, and character count */\nexport const CopyContentSchema = z.object({\n headline: z.string(),\n body: z.string(),\n hashtags: z.array(z.string()).optional(),\n platform: z.enum(['instagram', 'tiktok', 'x', 'linkedin', 'sms', 'email-subject']),\n characterCount: z.number().optional(),\n})\n\n// --- Approval ---\n\n/** Validate approval event data including asset, action, user, timestamp, and optional fields */\nexport const ApprovalEventSchema = z.object({\n assetId: z.string(),\n variantId: z.string().optional(),\n action: z.enum(['approved', 'rejected', 'edited', 'scheduled']),\n editedFields: z.array(z.string()).optional(),\n userId: z.string(),\n timestamp: z.string(),\n})\n\n/** Validate conversion metrics with nonnegative impressions, clicks, conversions, CTR, and CVR fields */\nexport const ConversionMetricsSchema = z.object({\n impressions: z.number().nonnegative(),\n clicks: z.number().nonnegative(),\n conversions: z.number().nonnegative(),\n ctr: z.number().nonnegative(),\n cvr: z.number().nonnegative(),\n})\n\n// --- Content map for discriminated parse ---\n\nconst AssetFormatValues = [\n 'email',\n 'image:feed',\n 'image:story',\n 'image:carousel',\n 'video:reel',\n 'video:feed',\n 'copy:caption',\n 'copy:headline',\n 'copy:sms',\n] as const\n\nconst ContentSchemaByFormat = {\n email: EmailContentSchema,\n 'image:feed': ImageContentSchema,\n 'image:story': ImageContentSchema,\n 'image:carousel': ImageContentSchema,\n 'video:reel': VideoContentSchema,\n 'video:feed': VideoContentSchema,\n 'copy:caption': CopyContentSchema,\n 'copy:headline': CopyContentSchema,\n 'copy:sms': CopyContentSchema,\n} as const\n\n// Model-facing create payload. Keep this union derived from the same schemas\n// as parseAssetSpec so prompt and tool authors cannot invent a second shape.\nconst AssetCreatePayloadSchema = z.union([\n z.object({ format: z.literal('email'), campaignId: z.string().optional(), brand: BrandTokensSchema, content: EmailContentSchema }),\n z.object({ format: z.literal('image:feed'), campaignId: z.string().optional(), brand: BrandTokensSchema, content: ImageContentSchema }),\n z.object({ format: z.literal('image:story'), campaignId: z.string().optional(), brand: BrandTokensSchema, content: ImageContentSchema }),\n z.object({ format: z.literal('image:carousel'), campaignId: z.string().optional(), brand: BrandTokensSchema, content: ImageContentSchema }),\n z.object({ format: z.literal('video:reel'), campaignId: z.string().optional(), brand: BrandTokensSchema, content: VideoContentSchema }),\n z.object({ format: z.literal('video:feed'), campaignId: z.string().optional(), brand: BrandTokensSchema, content: VideoContentSchema }),\n z.object({ format: z.literal('copy:caption'), campaignId: z.string().optional(), brand: BrandTokensSchema, content: CopyContentSchema }),\n z.object({ format: z.literal('copy:headline'), campaignId: z.string().optional(), brand: BrandTokensSchema, content: CopyContentSchema }),\n z.object({ format: z.literal('copy:sms'), campaignId: z.string().optional(), brand: BrandTokensSchema, content: CopyContentSchema }),\n])\n\n/**\n * JSON Schema for the model-facing asset-create payload.\n *\n * `format`, `brand`, and `content` are required. `campaignId` is optional.\n * The host assigns `id`, `workspaceId`, `status`, and timestamps before it\n * calls {@link parseAssetSpec}; every content branch comes from its parser\n * schema, so this is the one reference products should mount in prompts.\n */\nexport const assetCreateJsonSchema = {\n ...z.toJSONSchema(AssetCreatePayloadSchema),\n $id: 'https://tangle.tools/schemas/asset-create.json',\n title: 'AssetCreate',\n description: 'A model-produced marketing asset payload before host metadata is assigned.',\n} as const\n\nconst AssetSpecBaseSchema = z.object({\n id: z.string(),\n workspaceId: z.string(),\n campaignId: z.string().optional(),\n format: z.enum(AssetFormatValues),\n brand: BrandTokensSchema,\n status: z.enum(['draft', 'pending_review', 'approved', 'rejected', 'scheduled', 'published']),\n scheduledAt: z.string().optional(),\n createdAt: z.string(),\n updatedAt: z.string(),\n})\n\n/**\n * Validates an unknown value as an AssetSpec, including format-specific\n * content validation. Throws ZodError on invalid input.\n */\nexport function parseAssetSpec(raw: unknown): AssetSpec {\n const base = AssetSpecBaseSchema.parse(raw)\n const contentSchema = ContentSchemaByFormat[base.format]\n const content = contentSchema.parse((raw as Record<string, unknown>).content)\n return { ...base, content } as AssetSpec\n}\n\n/**\n * Safe parse — returns null instead of throwing.\n */\nexport function safeParseAssetSpec(raw: unknown): AssetSpec | null {\n try {\n return parseAssetSpec(raw)\n } catch {\n return null\n }\n}\n"],"mappings":";AAAA,SAAS,SAAS;AAMX,IAAM,oBAAoB,EAAE,OAAO;AAAA,EACxC,cAAc,EAAE,OAAO;AAAA,EACvB,aAAa,EAAE,OAAO;AAAA,EACtB,WAAW,EAAE,OAAO;AAAA,EACpB,YAAY,EAAE,OAAO;AAAA,EACrB,SAAS,EAAE,OAAO,EAAE,SAAS;AAAA,EAC7B,cAAc,EAAE,OAAO;AAAA,EACvB,OAAO,EAAE,OAAO;AAClB,CAAC;AAID,IAA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;AAAA,EACtB,YAAY,EAAE,OAAO,EAAE,SAAS;AAAA,EAChC,QAAQ,EAAE,KAAK,iBAAiB;AAAA,EAChC,OAAO;AAAA,EACP,QAAQ,EAAE,KAAK,CAAC,SAAS,kBAAkB,YAAY,YAAY,aAAa,WAAW,CAAC;AAAA,EAC5F,aAAa,EAAE,OAAO,EAAE,SAAS;AAAA,EACjC,WAAW,EAAE,OAAO;AAAA,EACpB,WAAW,EAAE,OAAO;AACtB,CAAC;AAMM,SAAS,eAAe,KAAyB;AACtD,QAAM,OAAO,oBAAoB,MAAM,GAAG;AAC1C,QAAM,gBAAgB,sBAAsB,KAAK,MAAM;AACvD,QAAM,UAAU,cAAc,MAAO,IAAgC,OAAO;AAC5E,SAAO,EAAE,GAAG,MAAM,QAAQ;AAC5B;AAKO,SAAS,mBAAmB,KAAgC;AACjE,MAAI;AACF,WAAO,eAAe,GAAG;AAAA,EAC3B,QAAQ;AACN,WAAO;AAAA,EACT;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/assets/schema.ts"],"sourcesContent":["import { z } from 'zod'\nimport type { AssetSpec, AssetFormat } from './types'\n\n// --- Brand ---\n\n/** Validate brand token properties including colors, font, logo URL, business name, and voice */\nexport const BrandTokensSchema = z.object({\n primaryColor: z.string(),\n accentColor: z.string(),\n textColor: z.string(),\n fontFamily: z.string(),\n logoUrl: z.string().optional(),\n businessName: z.string(),\n voice: z.string(),\n})\n\n// --- Email ---\n\nconst EmailHeroSectionSchema = z.object({\n type: z.literal('hero'),\n headline: z.string(),\n subheadline: z.string().optional(),\n imageUrl: z.string().optional(),\n ctaLabel: z.string().optional(),\n ctaUrl: z.string().optional(),\n})\n\nconst EmailBodySectionSchema = z.object({\n type: z.literal('body'),\n text: z.string(),\n})\n\nconst EmailFeatureSectionSchema = z.object({\n type: z.literal('feature'),\n headline: z.string(),\n description: z.string(),\n imageUrl: z.string().optional(),\n})\n\nconst EmailTestimonialSectionSchema = z.object({\n type: z.literal('testimonial'),\n quote: z.string(),\n author: z.string(),\n role: z.string().optional(),\n avatarUrl: z.string().optional(),\n})\n\nconst EmailCtaSectionSchema = z.object({\n type: z.literal('cta'),\n label: z.string(),\n url: z.string(),\n subtext: z.string().optional(),\n})\n\nconst EmailDividerSectionSchema = z.object({\n type: z.literal('divider'),\n})\n\nconst EmailSectionSchema = z.discriminatedUnion('type', [\n EmailHeroSectionSchema,\n EmailBodySectionSchema,\n EmailFeatureSectionSchema,\n EmailTestimonialSectionSchema,\n EmailCtaSectionSchema,\n EmailDividerSectionSchema,\n])\n\n/** Validate and parse email content objects with subject, optional preheader, and sections */\nexport const EmailContentSchema = z.object({\n subject: z.string(),\n preheader: z.string().optional(),\n sections: z.array(EmailSectionSchema),\n})\n\n// --- Image ---\n\nconst ImageBackgroundSchema = z.discriminatedUnion('type', [\n z.object({ type: z.literal('color'), value: z.string() }),\n z.object({ type: z.literal('gradient'), from: z.string(), to: z.string(), direction: z.string().optional() }),\n z.object({ type: z.literal('image'), url: z.string(), overlay: z.string().optional(), overlayOpacity: z.number().optional() }),\n])\n\nconst ImageTextLayerSchema = z.object({\n type: z.literal('text'),\n text: z.string(),\n fontSize: z.number().optional(),\n fontWeight: z.enum(['normal', 'bold']).optional(),\n color: z.string().optional(),\n x: z.number(),\n y: z.number(),\n width: z.number().optional(),\n align: z.enum(['left', 'center', 'right']).optional(),\n})\n\nconst ImageImageLayerSchema = z.object({\n type: z.literal('image'),\n url: z.string(),\n x: z.number(),\n y: z.number(),\n width: z.number(),\n height: z.number(),\n opacity: z.number().optional(),\n})\n\nconst ImageShapeLayerSchema = z.object({\n type: z.literal('shape'),\n shape: z.enum(['rect', 'circle', 'rounded-rect']),\n x: z.number(),\n y: z.number(),\n width: z.number(),\n height: z.number(),\n fill: z.string().optional(),\n opacity: z.number().optional(),\n})\n\nconst ImageLogoLayerSchema = z.object({\n type: z.literal('logo'),\n x: z.number(),\n y: z.number(),\n width: z.number().optional(),\n})\n\nconst ImageLayerSchema = z.discriminatedUnion('type', [\n ImageTextLayerSchema,\n ImageImageLayerSchema,\n ImageShapeLayerSchema,\n ImageLogoLayerSchema,\n])\n\nconst ImageSlideSchema = z.object({\n background: ImageBackgroundSchema,\n layers: z.array(ImageLayerSchema),\n})\n\n/** Validate image content with an array of one or more slides containing background details */\nexport const ImageContentSchema = z.object({\n slides: z.array(ImageSlideSchema).min(1),\n})\n\n// --- Video ---\n\nconst VideoTextAnimationSceneSchema = z.object({\n type: z.literal('text-animation'),\n durationSeconds: z.number().positive(),\n headline: z.string(),\n subtext: z.string().optional(),\n animation: z.enum(['fade', 'slide-up', 'typewriter']).optional(),\n background: ImageBackgroundSchema.optional(),\n})\n\nconst VideoImageRevealSceneSchema = z.object({\n type: z.literal('image-reveal'),\n durationSeconds: z.number().positive(),\n imageUrl: z.string(),\n caption: z.string().optional(),\n})\n\nconst VideoSlideSceneSchema = z.object({\n type: z.literal('slide'),\n durationSeconds: z.number().positive(),\n slide: ImageSlideSchema,\n})\n\nconst VideoCountdownSceneSchema = z.object({\n type: z.literal('countdown'),\n durationSeconds: z.number().positive(),\n from: z.number().int().positive(),\n label: z.string().optional(),\n})\n\nconst VideoSceneSchema = z.discriminatedUnion('type', [\n VideoTextAnimationSceneSchema,\n VideoImageRevealSceneSchema,\n VideoSlideSceneSchema,\n VideoCountdownSceneSchema,\n])\n\nconst VideoCaptionSchema = z.object({\n startSeconds: z.number().nonnegative(),\n endSeconds: z.number().positive(),\n text: z.string(),\n})\n\n/** Define the schema for validating video content including duration, scenes, audio, captions, and rendered URL */\nexport const VideoContentSchema = z.object({\n durationSeconds: z.number().positive(),\n scenes: z.array(VideoSceneSchema).min(1),\n audioUrl: z.string().optional(),\n captions: z.array(VideoCaptionSchema).optional(),\n renderedUrl: z.string().optional(),\n})\n\n// --- Copy ---\n\n/** Validate and parse copy content with headline, body, optional hashtags, platform, and character count */\nexport const CopyContentSchema = z.object({\n headline: z.string(),\n body: z.string(),\n hashtags: z.array(z.string()).optional(),\n platform: z.enum(['instagram', 'tiktok', 'x', 'linkedin', 'sms', 'email-subject']),\n characterCount: z.number().optional(),\n})\n\n// --- Approval ---\n// --- Content map for discriminated parse ---\n\nconst AssetFormatValues = [\n 'email',\n 'image:feed',\n 'image:story',\n 'image:carousel',\n 'video:reel',\n 'video:feed',\n 'copy:caption',\n 'copy:headline',\n 'copy:sms',\n] as const\n\nconst ContentSchemaByFormat = {\n email: EmailContentSchema,\n 'image:feed': ImageContentSchema,\n 'image:story': ImageContentSchema,\n 'image:carousel': ImageContentSchema,\n 'video:reel': VideoContentSchema,\n 'video:feed': VideoContentSchema,\n 'copy:caption': CopyContentSchema,\n 'copy:headline': CopyContentSchema,\n 'copy:sms': CopyContentSchema,\n} as const\n\n// Model-facing create payload. Keep this union derived from the same schemas\n// as parseAssetSpec so prompt and tool authors cannot invent a second shape.\nconst AssetCreatePayloadSchema = z.union([\n z.object({ format: z.literal('email'), campaignId: z.string().optional(), brand: BrandTokensSchema, content: EmailContentSchema }),\n z.object({ format: z.literal('image:feed'), campaignId: z.string().optional(), brand: BrandTokensSchema, content: ImageContentSchema }),\n z.object({ format: z.literal('image:story'), campaignId: z.string().optional(), brand: BrandTokensSchema, content: ImageContentSchema }),\n z.object({ format: z.literal('image:carousel'), campaignId: z.string().optional(), brand: BrandTokensSchema, content: ImageContentSchema }),\n z.object({ format: z.literal('video:reel'), campaignId: z.string().optional(), brand: BrandTokensSchema, content: VideoContentSchema }),\n z.object({ format: z.literal('video:feed'), campaignId: z.string().optional(), brand: BrandTokensSchema, content: VideoContentSchema }),\n z.object({ format: z.literal('copy:caption'), campaignId: z.string().optional(), brand: BrandTokensSchema, content: CopyContentSchema }),\n z.object({ format: z.literal('copy:headline'), campaignId: z.string().optional(), brand: BrandTokensSchema, content: CopyContentSchema }),\n z.object({ format: z.literal('copy:sms'), campaignId: z.string().optional(), brand: BrandTokensSchema, content: CopyContentSchema }),\n])\n\n/**\n * JSON Schema for the model-facing asset-create payload.\n *\n * `format`, `brand`, and `content` are required. `campaignId` is optional.\n * The host assigns `id`, `workspaceId`, `status`, and timestamps before it\n * calls {@link parseAssetSpec}; every content branch comes from its parser\n * schema, so this is the one reference products should mount in prompts.\n */\nexport const assetCreateJsonSchema = {\n ...z.toJSONSchema(AssetCreatePayloadSchema),\n $id: 'https://tangle.tools/schemas/asset-create.json',\n title: 'AssetCreate',\n description: 'A model-produced marketing asset payload before host metadata is assigned.',\n} as const\n\nconst AssetSpecBaseSchema = z.object({\n id: z.string(),\n workspaceId: z.string(),\n campaignId: z.string().optional(),\n format: z.enum(AssetFormatValues),\n brand: BrandTokensSchema,\n status: z.enum(['draft', 'pending_review', 'approved', 'rejected', 'scheduled', 'published']),\n scheduledAt: z.string().optional(),\n createdAt: z.string(),\n updatedAt: z.string(),\n})\n\n/**\n * Validates an unknown value as an AssetSpec, including format-specific\n * content validation. Throws ZodError on invalid input.\n */\nexport function parseAssetSpec(raw: unknown): AssetSpec {\n const base = AssetSpecBaseSchema.parse(raw)\n const contentSchema = ContentSchemaByFormat[base.format]\n const content = contentSchema.parse((raw as Record<string, unknown>).content)\n return { ...base, content } as AssetSpec\n}\n"],"mappings":";AAAA,SAAS,SAAS;AAMX,IAAM,oBAAoB,EAAE,OAAO;AAAA,EACxC,cAAc,EAAE,OAAO;AAAA,EACvB,aAAa,EAAE,OAAO;AAAA,EACtB,WAAW,EAAE,OAAO;AAAA,EACpB,YAAY,EAAE,OAAO;AAAA,EACrB,SAAS,EAAE,OAAO,EAAE,SAAS;AAAA,EAC7B,cAAc,EAAE,OAAO;AAAA,EACvB,OAAO,EAAE,OAAO;AAClB,CAAC;AAID,IAAM,yBAAyB,EAAE,OAAO;AAAA,EACtC,MAAM,EAAE,QAAQ,MAAM;AAAA,EACtB,UAAU,EAAE,OAAO;AAAA,EACnB,aAAa,EAAE,OAAO,EAAE,SAAS;AAAA,EACjC,UAAU,EAAE,OAAO,EAAE,SAAS;AAAA,EAC9B,UAAU,EAAE,OAAO,EAAE,SAAS;AAAA,EAC9B,QAAQ,EAAE,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EAAE,OAAO,EAAE,SAAS,GAAG,OAAO,mBAAmB,SAAS,kBAAkB,CAAC;AAAA,EACxI,EAAE,OAAO,EAAE,QAAQ,EAAE,QAAQ,UAAU,GAAG,YAAY,EAAE,OAAO,EAAE,SAAS,GAAG,OAAO,mBAAmB,SAAS,kBAAkB,CAAC;AACrI,CAAC;AAUM,IAAM,wBAAwB;AAAA,EACnC,GAAG,EAAE,aAAa,wBAAwB;AAAA,EAC1C,KAAK;AAAA,EACL,OAAO;AAAA,EACP,aAAa;AACf;AAEA,IAAM,sBAAsB,EAAE,OAAO;AAAA,EACnC,IAAI,EAAE,OAAO;AAAA,EACb,aAAa,EAAE,OAAO;AAAA,EACtB,YAAY,EAAE,OAAO,EAAE,SAAS;AAAA,EAChC,QAAQ,EAAE,KAAK,iBAAiB;AAAA,EAChC,OAAO;AAAA,EACP,QAAQ,EAAE,KAAK,CAAC,SAAS,kBAAkB,YAAY,YAAY,aAAa,WAAW,CAAC;AAAA,EAC5F,aAAa,EAAE,OAAO,EAAE,SAAS;AAAA,EACjC,WAAW,EAAE,OAAO;AAAA,EACpB,WAAW,EAAE,OAAO;AACtB,CAAC;AAMM,SAAS,eAAe,KAAyB;AACtD,QAAM,OAAO,oBAAoB,MAAM,GAAG;AAC1C,QAAM,gBAAgB,sBAAsB,KAAK,MAAM;AACvD,QAAM,UAAU,cAAc,MAAO,IAAgC,OAAO;AAC5E,SAAO,EAAE,GAAG,MAAM,QAAQ;AAC5B;","names":[]}
@@ -231,28 +231,6 @@ export declare const CopyContentSchema: z.ZodObject<{
231
231
  }>;
232
232
  characterCount: z.ZodOptional<z.ZodNumber>;
233
233
  }, z.core.$strip>;
234
- /** Validate approval event data including asset, action, user, timestamp, and optional fields */
235
- export declare const ApprovalEventSchema: z.ZodObject<{
236
- assetId: z.ZodString;
237
- variantId: z.ZodOptional<z.ZodString>;
238
- action: z.ZodEnum<{
239
- approved: "approved";
240
- edited: "edited";
241
- rejected: "rejected";
242
- scheduled: "scheduled";
243
- }>;
244
- editedFields: z.ZodOptional<z.ZodArray<z.ZodString>>;
245
- userId: z.ZodString;
246
- timestamp: z.ZodString;
247
- }, z.core.$strip>;
248
- /** Validate conversion metrics with nonnegative impressions, clicks, conversions, CTR, and CVR fields */
249
- export declare const ConversionMetricsSchema: z.ZodObject<{
250
- impressions: z.ZodNumber;
251
- clicks: z.ZodNumber;
252
- conversions: z.ZodNumber;
253
- ctr: z.ZodNumber;
254
- cvr: z.ZodNumber;
255
- }, z.core.$strip>;
256
234
  /**
257
235
  * JSON Schema for the model-facing asset-create payload.
258
236
  *
@@ -915,7 +893,3 @@ export declare const assetCreateJsonSchema: {
915
893
  * content validation. Throws ZodError on invalid input.
916
894
  */
917
895
  export declare function parseAssetSpec(raw: unknown): AssetSpec;
918
- /**
919
- * Safe parse — returns null instead of throwing.
920
- */
921
- export declare function safeParseAssetSpec(raw: unknown): AssetSpec | null;
@@ -1,11 +1,11 @@
1
1
  import {
2
2
  chatToolCallPart
3
- } from "../chunk-IJDPERPL.js";
3
+ } from "../chunk-PFOJRQ3Q.js";
4
4
  import "../chunk-WZ2FER6A.js";
5
5
  import "../chunk-3HUFJ5LO.js";
6
6
  import "../chunk-E4AY62T2.js";
7
7
  import "../chunk-FBVLEGEG.js";
8
- import "../chunk-CUXCWQMW.js";
8
+ import "../chunk-47UDWWUN.js";
9
9
  import "../chunk-GEYACSFW.js";
10
10
  import {
11
11
  ChatComposer
@@ -26,7 +26,7 @@ import "../chunk-FQYAJYPW.js";
26
26
  import "../chunk-NJA6X7JI.js";
27
27
  import "../chunk-MCYJON3F.js";
28
28
  import "../chunk-7YA4QNTU.js";
29
- import "../chunk-DVOJNI6T.js";
29
+ import "../chunk-V4JZ5OYC.js";
30
30
  import "../chunk-ZVEEWGDK.js";
31
31
  import "../chunk-GYDFGEJ2.js";
32
32
  import "../chunk-TXD5HXLE.js";
@@ -64,7 +64,7 @@ import {
64
64
  rowIdOf,
65
65
  storeSupportsDraftPersistence,
66
66
  streamChatRouteAsSandboxEvents
67
- } from "../chunk-4XBRPVL3.js";
67
+ } from "../chunk-RSTPXLC3.js";
68
68
  import "../chunk-6VRVRWYN.js";
69
69
  import "../chunk-YNSPVKMS.js";
70
70
  import "../chunk-3NCPXNBZ.js";
@@ -72,7 +72,7 @@ import {
72
72
  attachmentInputToPart,
73
73
  attachmentKindForMime,
74
74
  toChatMessageParts
75
- } from "../chunk-DVOJNI6T.js";
75
+ } from "../chunk-V4JZ5OYC.js";
76
76
  import "../chunk-ZVEEWGDK.js";
77
77
  import {
78
78
  ChatTurnInputError,
@@ -11,15 +11,10 @@ import {
11
11
  isChatAttachmentPart,
12
12
  isChatInteractionPart,
13
13
  isChatMentionPart,
14
- isChatPlanPart,
15
- isChatStepFinishPart,
16
- isChatTextPart,
17
- isChatToolPart,
18
- isChatWorkProductPart,
19
14
  mentionInputToPart,
20
15
  mentionPartsFromMessageParts,
21
16
  toChatMessageParts
22
- } from "../chunk-DVOJNI6T.js";
17
+ } from "../chunk-V4JZ5OYC.js";
23
18
  import "../chunk-ZVEEWGDK.js";
24
19
  import "../chunk-GYDFGEJ2.js";
25
20
  import "../chunk-TXD5HXLE.js";
@@ -299,11 +294,6 @@ export {
299
294
  isChatAttachmentPart,
300
295
  isChatInteractionPart,
301
296
  isChatMentionPart,
302
- isChatPlanPart,
303
- isChatStepFinishPart,
304
- isChatTextPart,
305
- isChatToolPart,
306
- isChatWorkProductPart,
307
297
  mentionInputToPart,
308
298
  mentionPartsFromMessageParts,
309
299
  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, and the typed input error. Split from `./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\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 * 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 reads,\n * validates, or defaults them).\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 } 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 * 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, gte, inArray, lt, sql, type SQL } from 'drizzle-orm'\nimport type { BaseSQLiteDatabase } from 'drizzle-orm/sqlite-core'\nimport {\n runSqliteStatements,\n type SqliteBatchDatabase,\n} from '../store'\nimport { BULK_DELETE_MAX_THREADS, ChatStoreInputError, threadTitleFromMessage } from './core'\nimport type { ChatMessagePart } from './parts'\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 {\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 content: string\n parts?: ChatMessagePart[]\n toolName?: string | null\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 /** 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 {\n content?: string\n parts?: ChatMessagePart[]\n toolName?: string | null\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 /** 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 /** 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 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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAUO,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;AACvB,SAAO,UAAU,SAAS,KAAK,GAAG,UAAU,MAAM,GAAG,EAAE,CAAC,WAAM;AAChE;;;ACYA,SAAS,WAAW;AACpB,SAAS,OAAO,SAAS,MAAM,aAAa,YAAY;AA+DxD,IAAM,QAAQ,MAAM,KAAK,IAAI,EAAE,WAAW,EAAE,QAAQ,iCAAiC;AAErF,IAAM,YAAY,MAAM,QAAQ,cAAc,EAAE,MAAM,YAAY,CAAC,EAAE,QAAQ,EAAE,QAAQ,kBAAkB;AAEzG,IAAM,YAAY,MAAM,QAAQ,cAAc,EAAE,MAAM,YAAY,CAAC,EAAE,QAAQ,EAAE,QAAQ,kBAAkB;AAGlG,SAAS,iBAGd,UAAkE,CAAC,GAAG;AACtE,QAAM,EAAE,gBAAgB,cAAc,GAAG,IAAI;AAC7C,QAAM,eAAe,QAAQ,sBAAuB,CAAC;AACrD,QAAM,gBAAgB,QAAQ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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, and the typed input error. Split from `./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\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 * 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 reads,\n * validates, or defaults them).\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 } 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 * 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, gte, inArray, lt, sql, type SQL } from 'drizzle-orm'\nimport type { BaseSQLiteDatabase } from 'drizzle-orm/sqlite-core'\nimport {\n runSqliteStatements,\n type SqliteBatchDatabase,\n} from '../store'\nimport { BULK_DELETE_MAX_THREADS, ChatStoreInputError, threadTitleFromMessage } from './core'\nimport type { ChatMessagePart } from './parts'\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 {\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 content: string\n parts?: ChatMessagePart[]\n toolName?: string | null\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 /** 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 {\n content?: string\n parts?: ChatMessagePart[]\n toolName?: string | null\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 /** 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 /** 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 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":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAUO,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;AACvB,SAAO,UAAU,SAAS,KAAK,GAAG,UAAU,MAAM,GAAG,EAAE,CAAC,WAAM;AAChE;;;ACYA,SAAS,WAAW;AACpB,SAAS,OAAO,SAAS,MAAM,aAAa,YAAY;AA+DxD,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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"]}
@@ -223,18 +223,8 @@ export type StorableHarnessPartKind = HarnessWirePart['type'] & ChatMessagePart[
223
223
  * kind can silently fall out (the step-finish/interaction trap).
224
224
  */
225
225
  export declare function toChatMessageParts(parts: Array<Record<string, unknown>>): ChatMessagePart[];
226
- /** Resolve whether a ChatMessagePart is specifically a ChatToolPart based on its type property */
227
- export declare function isChatToolPart(part: ChatMessagePart): part is ChatToolPart;
228
- /** Resolve whether a chat message part is a text part based on its type property */
229
- export declare function isChatTextPart(part: ChatMessagePart): part is ChatTextPart;
230
226
  /** Resolve whether a ChatMessagePart is a ChatInteractionPart based on its type property */
231
227
  export declare function isChatInteractionPart(part: ChatMessagePart): part is ChatInteractionPart;
232
- /** Resolve whether a chat message part is a persisted chat plan part */
233
- export declare function isChatPlanPart(part: ChatMessagePart): part is ChatPlanPart;
234
- /** Resolve whether a chat message part is a persisted work-product anchor */
235
- export declare function isChatWorkProductPart(part: ChatMessagePart): part is ChatWorkProductPart;
236
- /** Determine if a chat message part represents the completion of a chat step */
237
- export declare function isChatStepFinishPart(part: ChatMessagePart): part is ChatStepFinishPart;
238
228
  /** Widened to `unknown` — unlike its siblings this guard also runs over raw
239
229
  * untyped stored rows (a transcript renderer reads `message.parts` before the
240
230
  * typed projection), which is exactly what {@link mentionPartsFromMessageParts}
@@ -1,14 +1,14 @@
1
1
  // src/design-canvas-react/lazy.tsx
2
2
  import { lazy } from "react";
3
3
  var DesignCanvasLazy = lazy(
4
- () => import("./DesignCanvasEditor-IBFHC25D.js").then((m) => ({ default: m.DesignCanvasEditor }))
4
+ () => import("./DesignCanvasEditor-VJ3R7RM2.js").then((m) => ({ default: m.DesignCanvasEditor }))
5
5
  );
6
6
  var DesignCanvasChromeLazy = lazy(
7
- () => import("./DesignCanvas-BVBMDXBZ.js").then((m) => ({ default: m.DesignCanvas }))
7
+ () => import("./DesignCanvas-OWE67ZX3.js").then((m) => ({ default: m.DesignCanvas }))
8
8
  );
9
9
 
10
10
  export {
11
11
  DesignCanvasLazy,
12
12
  DesignCanvasChromeLazy
13
13
  };
14
- //# sourceMappingURL=chunk-JB2GFEOC.js.map
14
+ //# sourceMappingURL=chunk-2N7PDPLC.js.map
@@ -43,9 +43,6 @@ var STATUS_TONES = {
43
43
  approved: "success",
44
44
  superseded: "neutral"
45
45
  };
46
- function reviewQueueStateLabel(state) {
47
- return STATE_LABELS[state];
48
- }
49
46
  function workProductStatusLabel(status) {
50
47
  return STATUS_LABELS[status];
51
48
  }
@@ -335,7 +332,6 @@ function ProvenanceStamp({ provenance, backtest, className }) {
335
332
  }
336
333
 
337
334
  export {
338
- reviewQueueStateLabel,
339
335
  workProductStatusLabel,
340
336
  workProductPartsFromMessageParts,
341
337
  WorkProductCard,
@@ -346,4 +342,4 @@ export {
346
342
  QualityCheckList,
347
343
  ProvenanceStamp
348
344
  };
349
- //# sourceMappingURL=chunk-CUXCWQMW.js.map
345
+ //# sourceMappingURL=chunk-47UDWWUN.js.map