@marktiderman/genesis-chat 0.4.0 → 0.6.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.
package/package.json CHANGED
@@ -1,10 +1,31 @@
1
1
  {
2
2
  "name": "@marktiderman/genesis-chat",
3
- "version": "0.4.0",
3
+ "version": "0.6.0",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "sideEffects": false,
7
7
  "description": "Chat for Genesis apps, in the app's own Supabase: conversations of kinds the app defines (direct, group, cohort, support ticket) with members, observers and internal notes; messages with replies, threads, topics, mentions, reactions, edits and deletes; photos, files, voice notes and videos; read state, live updates and typing over private Realtime topics; an outbox for push, transcripts and storage cleanup. A headless core, React hooks, web and native renderers on Genesis UI, and a server runner. Part of the Genesis framework.",
8
+ "keywords": [
9
+ "genesis",
10
+ "genesis-framework",
11
+ "chat",
12
+ "messaging",
13
+ "supabase",
14
+ "realtime",
15
+ "react",
16
+ "react-native",
17
+ "messages",
18
+ "dm",
19
+ "group-chat",
20
+ "voice-notes",
21
+ "video-messages",
22
+ "inbox",
23
+ "support-tickets"
24
+ ],
25
+ "homepage": "https://github.com/marktiderman/genesis/tree/main/packages/chat#readme",
26
+ "bugs": {
27
+ "url": "https://github.com/marktiderman/genesis/issues"
28
+ },
8
29
  "repository": {
9
30
  "type": "git",
10
31
  "url": "git+https://github.com/marktiderman/genesis.git",
@@ -52,6 +73,10 @@
52
73
  "./server": {
53
74
  "types": "./dist/server.d.ts",
54
75
  "import": "./dist/server.js"
76
+ },
77
+ "./ai": {
78
+ "types": "./dist/ai.d.ts",
79
+ "import": "./dist/ai.js"
55
80
  }
56
81
  },
57
82
  "files": [
@@ -61,12 +86,13 @@
61
86
  "README.md"
62
87
  ],
63
88
  "dependencies": {
64
- "@marktiderman/genesis-features": "^0.7.0",
89
+ "@marktiderman/genesis-features": "^0.8.0",
65
90
  "frimousse": "0.4.0"
66
91
  },
67
92
  "peerDependencies": {
93
+ "@marktiderman/genesis-ai": ">=0.1.0 <1.0.0",
68
94
  "@marktiderman/genesis-core": ">=1.17.0 <3.0.0",
69
- "@marktiderman/genesis-ui": "^2.23.0",
95
+ "@marktiderman/genesis-ui": ">=2.21.0 <3.0.0",
70
96
  "@marktiderman/genesis-ui-native": ">=2.9.0 <4.0.0",
71
97
  "@supabase/supabase-js": "^2.118.0",
72
98
  "@tanstack/react-query": "^5.0.0",
@@ -75,9 +101,13 @@
75
101
  "react": "^19.0.0",
76
102
  "react-dom": "^19.0.0",
77
103
  "react-native": ">=0.76.0",
78
- "react-native-safe-area-context": ">=4.0.0"
104
+ "react-native-safe-area-context": ">=4.0.0",
105
+ "zod": "^3.25.0 || ^4.0.0"
79
106
  },
80
107
  "peerDependenciesMeta": {
108
+ "@marktiderman/genesis-ai": {
109
+ "optional": true
110
+ },
81
111
  "@marktiderman/genesis-core": {
82
112
  "optional": true
83
113
  },
@@ -137,29 +167,39 @@
137
167
  },
138
168
  "react-native-safe-area-context": {
139
169
  "optional": true
170
+ },
171
+ "zod": {
172
+ "optional": true
140
173
  }
141
174
  },
142
175
  "devDependencies": {
143
- "@marktiderman/genesis-core": "^2.1.0",
144
- "@marktiderman/genesis-notifications": "^0.3.2",
145
- "@marktiderman/genesis-ui": "^2.23.0",
146
- "@marktiderman/genesis-ui-native": "^3.1.0",
176
+ "@ai-sdk/anthropic": "4.0.85",
177
+ "@marktiderman/genesis-ai": "^0.2.0",
178
+ "@marktiderman/genesis-core": "^2.4.0",
179
+ "@marktiderman/genesis-notifications": "^0.4.0",
180
+ "@marktiderman/genesis-ui": "^2.25.1",
181
+ "@marktiderman/genesis-ui-native": "^3.2.2",
147
182
  "@supabase/supabase-js": "^2.118.0",
148
- "@tanstack/react-query": "^5.75.0",
183
+ "@tanstack/react-query": "^5.104.5",
149
184
  "@testing-library/react": "^16.3.2",
150
185
  "@types/node": "^22",
151
186
  "@types/react": "^19.2.14",
152
187
  "@types/react-dom": "^19.2.3",
153
- "happy-dom": "^20.9.0",
188
+ "ai": "7.0.148",
189
+ "happy-dom": "^21.0.4",
154
190
  "hls.js": "1.7.3",
155
191
  "lucide-react": "^1.28.0",
156
192
  "react": "^19.2.5",
157
193
  "react-dom": "^19.2.5",
158
194
  "tsup": "^8.3.0",
159
195
  "typescript": "~6.0.3",
160
- "vitest": "^4.1.12"
196
+ "vitest": "^5.0.5",
197
+ "zod": "^4.6.6"
161
198
  },
162
199
  "genesis": {
200
+ "layer": "primitive",
201
+ "group": "collaboration",
202
+ "owner": "@marktiderman",
163
203
  "blocks": {
164
204
  "chat": {
165
205
  "feature": {
@@ -0,0 +1,161 @@
1
+ // @feat:chat
2
+ import { anthropic } from "@marktiderman/genesis-ai/anthropic";
3
+ import { defineAi, type AiContext } from "@marktiderman/genesis-ai";
4
+ import { memoryStore, runTask } from "@marktiderman/genesis-ai/server";
5
+ import { describe, expect, it } from "vitest";
6
+ import { CHAT_AI_REFUSALS, chatDraftReplyTask, chatRecapTask, type ChatAiDb } from "../ai/index";
7
+ import { createChatAssistant, type AssistantMessage } from "../server/assistant";
8
+
9
+ const CONV = "11111111-1111-4111-8111-111111111111";
10
+ const COACH = "c0000000-0000-4000-8000-000000000001";
11
+ const CLIENT = "c0000000-0000-4000-8000-000000000002";
12
+
13
+ type Row = Record<string, unknown>;
14
+ const rows: Row[] = [
15
+ { id: "m1", seq: 1, sender_id: CLIENT, body: "Week one done <b>finally</b>", created_at: "2026-10-20T09:00:00Z", kind: "text", visibility: "everyone", deleted_at: null, moderation: null },
16
+ { id: "m2", seq: 2, sender_id: COACH, body: "Great work. Same plan next week?", created_at: "2026-10-20T10:00:00Z", kind: "text", visibility: "everyone", deleted_at: null, moderation: null },
17
+ { id: "m3", seq: 3, sender_id: COACH, body: "Watch her sleep", created_at: "2026-10-20T10:05:00Z", kind: "text", visibility: "observers", deleted_at: null, moderation: null },
18
+ { id: "m4", seq: 4, sender_id: CLIENT, body: "Can we move Thursday to Friday?", created_at: "2026-10-21T08:00:00Z", kind: "text", visibility: "everyone", deleted_at: null, moderation: null },
19
+ ];
20
+
21
+ /** A genesis_chat client as the caller: just the queries the loaders make. */
22
+ function fakeDb(opts: { member?: Row | null; observer?: boolean; messages?: Row[] } = {}): ChatAiDb {
23
+ const query = (table: string) => {
24
+ const filters: Array<[string, unknown]> = [];
25
+ const builder = {
26
+ select: () => builder,
27
+ eq: (col: string, value: unknown) => (filters.push([col, value]), builder),
28
+ is: () => builder,
29
+ order: () => builder,
30
+ limit: async () => ({ data: [...(opts.messages ?? rows)].sort((a, b) => Number(b.seq) - Number(a.seq)), error: null }),
31
+ maybeSingle: async () => ({ data: opts.member === undefined ? { last_read_seq: 2 } : opts.member, error: null }),
32
+ };
33
+ if (table !== "members" && table !== "messages") throw new Error(table);
34
+ return builder;
35
+ };
36
+ return {
37
+ schema: () => ({
38
+ from: query,
39
+ rpc: async (fn: string) => (fn === "i_observe" ? { data: opts.observer ?? false, error: null } : { data: null, error: { code: "42883" } }),
40
+ }),
41
+ };
42
+ }
43
+
44
+ const names: Record<string, string> = { [COACH]: "Mark", [CLIENT]: "Sam" };
45
+ const resolveName = async (_db: ChatAiDb, id: string) => names[id];
46
+
47
+ function recordingFetch() {
48
+ const calls: Array<{ headers: Record<string, string>; body: Record<string, any> }> = [];
49
+ const fetch = async (_url: unknown, init?: RequestInit) => {
50
+ calls.push({ headers: Object.fromEntries(new Headers(init?.headers).entries()), body: JSON.parse(String(init?.body)) });
51
+ return new Response(
52
+ JSON.stringify({ id: "msg", type: "message", role: "assistant", model: "claude-sonnet-5-5", content: [{ type: "text", text: "- Sam asks to move Thursday." }], stop_reason: "end_turn", usage: { input_tokens: 10, output_tokens: 5 } }),
53
+ { headers: { "content-type": "application/json" } },
54
+ );
55
+ };
56
+ return { calls, fetch: fetch as typeof globalThis.fetch };
57
+ }
58
+
59
+ function setup(db = fakeDb()) {
60
+ const wire = recordingFetch();
61
+ const store = memoryStore({ consents: "all" });
62
+ const ai = defineAi({ vendors: [anthropic({ apiKey: "test", fetch: wire.fetch })], models: { default: { model: "claude-sonnet-5-5", effort: "low" } }, store, gate: () => true, maxRetries: 0 });
63
+ const ctx: AiContext<ChatAiDb> = { tenantId: null, personId: COACH, db };
64
+ return { ai, ctx, store, calls: wire.calls };
65
+ }
66
+
67
+ /** What both paths send, normalised: the AI SDK sends system and content as blocks. */
68
+ const normalise = (call: { headers: Record<string, string>; body: Record<string, any> }) => {
69
+ const text = (v: unknown) => (typeof v === "string" ? v : (v as Array<{ text: string }>).map((b) => b.text).join(""));
70
+ return {
71
+ version: call.headers["anthropic-version"],
72
+ beta: call.headers["anthropic-beta"]?.split(",").includes("server-side-fallback-2026-07-01"),
73
+ model: call.body.model,
74
+ max_tokens: call.body.max_tokens,
75
+ effort: call.body.output_config?.effort,
76
+ fallbacks: call.body.fallbacks,
77
+ system: text(call.body.system),
78
+ prompt: text(call.body.messages[0].content),
79
+ sampling: ["temperature", "top_p", "top_k"].filter((k) => k in call.body),
80
+ };
81
+ };
82
+
83
+ const asAssistant = (r: Row[], observer: boolean): AssistantMessage[] =>
84
+ r.map((m) => ({
85
+ senderId: m.sender_id as string,
86
+ body: m.body as string,
87
+ createdAt: m.created_at as string,
88
+ kind: "text" as const,
89
+ visibility: m.visibility as "everyone" | "observers",
90
+ deletedAt: null,
91
+ moderation: null,
92
+ })).filter((m) => observer || m.visibility === "everyone");
93
+
94
+ describe("chat.recap", () => {
95
+ it("sends what createChatAssistant sends for the same conversation", async () => {
96
+ const { ai, ctx, calls, store } = setup();
97
+ const result = await runTask(ai, chatRecapTask({ resolveName }), { conversationId: CONV }, ctx);
98
+ expect(result).toMatchObject({ ok: true, output: { text: "- Sam asks to move Thursday." } });
99
+
100
+ const legacy = recordingFetch();
101
+ await createChatAssistant({ apiKey: "test", fetch: legacy.fetch }).recap({
102
+ messages: asAssistant(rows, false),
103
+ since: "2026-10-20T10:00:00Z",
104
+ me: COACH,
105
+ resolveName: (id) => names[id],
106
+ });
107
+ expect(normalise(calls[0]!)).toEqual(normalise(legacy.calls[0]!));
108
+ expect(normalise(calls[0]!)).toMatchObject({ version: "2026-10-21", beta: true, model: "claude-sonnet-5-5", max_tokens: 4000, effort: "low", fallbacks: "default", sampling: [] });
109
+ expect(normalise(calls[0]!).prompt).toContain("Can we move Thursday to Friday?");
110
+ expect(normalise(calls[0]!).prompt).not.toContain("Watch her sleep");
111
+ expect(normalise(calls[0]!).prompt).toContain("‹b›finally‹/b›");
112
+ expect(store.rows[0]!.manifest).toEqual([{ name: "messages", tokens: expect.any(Number), ids: ["m1", "m2", "m3", "m4"] }]);
113
+ });
114
+
115
+ it("includes internal notes only when the database says the caller observes", async () => {
116
+ const { ai, ctx, calls } = setup(fakeDb({ observer: true, member: { last_read_seq: 0 } }));
117
+ await runTask(ai, chatRecapTask({ resolveName }), { conversationId: CONV }, ctx);
118
+ expect(normalise(calls[0]!).prompt).toContain("You (internal note): Watch her sleep");
119
+ });
120
+
121
+ it("stops before the model for a non-member, and when nothing is new", async () => {
122
+ let s = setup(fakeDb({ member: null }));
123
+ expect(await runTask(s.ai, chatRecapTask(), { conversationId: CONV }, s.ctx)).toEqual({ ok: false, outcome: "forbidden", message: CHAT_AI_REFUSALS.notMember });
124
+ s = setup(fakeDb({ member: { last_read_seq: 4 } }));
125
+ expect(await runTask(s.ai, chatRecapTask(), { conversationId: CONV }, s.ctx)).toEqual({ ok: false, outcome: "invalid_input", message: CHAT_AI_REFUSALS.empty });
126
+ expect(s.calls).toHaveLength(0);
127
+ });
128
+
129
+ it("counts only messages the transcript will show: a sender's own hidden message is not something to recap", async () => {
130
+ // Row level security returns a hidden message to its sender; the transcript leaves it out.
131
+ const hidden = [{ id: "h1", seq: 1, sender_id: COACH, body: "Removed by moderation", created_at: "2026-10-20T09:00:00Z", kind: "text", visibility: "everyone", deleted_at: null, moderation: "hidden" }];
132
+ let s = setup(fakeDb({ member: { last_read_seq: 0 }, messages: hidden }));
133
+ expect(await runTask(s.ai, chatRecapTask(), { conversationId: CONV }, s.ctx)).toEqual({ ok: false, outcome: "invalid_input", message: CHAT_AI_REFUSALS.empty });
134
+ s = setup(fakeDb({ member: { last_read_seq: 0 }, messages: hidden }));
135
+ expect(await runTask(s.ai, chatDraftReplyTask(), { conversationId: CONV }, s.ctx)).toEqual({ ok: false, outcome: "invalid_input", message: CHAT_AI_REFUSALS.draftEmpty });
136
+ expect(s.calls).toHaveLength(0);
137
+ });
138
+
139
+ it("takes only a conversation id from the client", async () => {
140
+ const { ai, ctx, calls } = setup();
141
+ expect(await runTask(ai, chatRecapTask(), { conversationId: "not-a-uuid" }, ctx)).toMatchObject({ ok: false, outcome: "invalid_input" });
142
+ expect(await runTask(ai, chatRecapTask({ can: () => false }), { conversationId: CONV }, ctx)).toMatchObject({ ok: false, outcome: "forbidden" });
143
+ expect(calls).toHaveLength(0);
144
+ });
145
+ });
146
+
147
+ describe("chat.draft-reply", () => {
148
+ it("sends what createChatAssistant sends, with the coach's voice from the server", async () => {
149
+ const { ai, ctx, calls } = setup();
150
+ const task = chatDraftReplyTask({ resolveName, voice: async () => "warm, brief" });
151
+ expect(await runTask(ai, task, { conversationId: CONV }, ctx)).toMatchObject({ ok: true });
152
+ const legacy = recordingFetch();
153
+ await createChatAssistant({ apiKey: "test", fetch: legacy.fetch }).draftReply({
154
+ messages: asAssistant(rows, false),
155
+ voice: "warm, brief",
156
+ me: COACH,
157
+ resolveName: (id) => names[id],
158
+ });
159
+ expect(normalise(calls[0]!)).toEqual(normalise(legacy.calls[0]!));
160
+ });
161
+ });
@@ -0,0 +1,195 @@
1
+ // @feat:chat
2
+ /**
3
+ * Chat's AI tasks for `@marktiderman/genesis-ai`: the recap ("catch me up") and a reply draft,
4
+ * promoted from the main app's loader (G4). The only part of chat that imports genesis-ai, an
5
+ * optional peer: install it (and `zod`) to use this subpath. Server only: register the tasks with
6
+ * `createAiHandler` and call them by id from the client (`useAiTask("chat.recap")`).
7
+ *
8
+ * Everything is read as the caller (`ctx.db` is their own Supabase client, so row level security
9
+ * applies): their membership and last-read position, `genesis_chat.i_observe` for whether
10
+ * internal notes and hidden messages are theirs to see, and the latest 200 messages. The client
11
+ * sends only the conversation id. The prompts and request are `createChatAssistant`'s: the same
12
+ * system prompts, transcript fencing, model, effort and refusal fallback.
13
+ */
14
+ import { defineTask, GuardrailError, type AiContext, type TaskDefinition } from "@marktiderman/genesis-ai";
15
+ // `zod/v4` is Zod 4 in both Zod 3.25+ and Zod 4, so apps on either can install this.
16
+ import { z } from "zod/v4";
17
+ import { draftPrompt, draftSystem, recapPrompt, recapSystem, type AssistantMessage } from "../server/assistant";
18
+
19
+ const MAX_MESSAGES = 200;
20
+
21
+ /** The part of a Supabase client the loaders use: the caller's own, signed in as them. */
22
+ export interface ChatAiDb {
23
+ // Loose on purpose: a client typed by an app's Database narrows these to its own names.
24
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
25
+ schema: (name: "genesis_chat") => any;
26
+ }
27
+
28
+ export interface ChatAiTaskOptions {
29
+ /** Who may run it, such as "coaches only". Default: any member of the conversation. */
30
+ can?: ((ctx: AiContext<ChatAiDb>, args: { conversationId: string }) => boolean | Promise<boolean>) | undefined;
31
+ /** A member's display name, read as the caller (e.g. from the app's `profile_cards`). */
32
+ resolveName?: ((db: ChatAiDb, userId: string) => Promise<string | null | undefined>) | undefined;
33
+ /** The model alias. Default `default`. */
34
+ model?: string | undefined;
35
+ /** The FeatureId the gate checks. Default `chat`. */
36
+ feature?: string | undefined;
37
+ /**
38
+ * What kind of conversation this is, as a noun phrase ("a coaching conversation", "a support
39
+ * ticket"), as `createChatAssistant` takes it. The prompts say "a conversation" without it.
40
+ */
41
+ context?: string | undefined;
42
+ }
43
+
44
+ export interface DraftTaskOptions extends ChatAiTaskOptions {
45
+ /** How the coach writes ("warm, brief, first names, no emoji"), read on the server. */
46
+ voice?: ((ctx: AiContext<ChatAiDb>) => Promise<string | null | undefined>) | undefined;
47
+ }
48
+
49
+ /** What the loaders return and the prompts read. */
50
+ export interface LoadedConversation {
51
+ [key: string]: unknown;
52
+ messages: AssistantMessage[];
53
+ since: string | null;
54
+ me: string;
55
+ observer: boolean;
56
+ resolveName: (userId: string) => Promise<string | null | undefined>;
57
+ voice?: string | undefined;
58
+ }
59
+
60
+ export const CHAT_AI_REFUSALS = {
61
+ notMember: "You can only use this on a conversation you're in.",
62
+ empty: "Nothing to catch up on yet.",
63
+ draftEmpty: "Nothing to reply to yet.",
64
+ } as const;
65
+
66
+ type MessageRow = {
67
+ id: string;
68
+ seq: number;
69
+ sender_id: string | null;
70
+ body: string | null;
71
+ created_at: string;
72
+ kind: string;
73
+ visibility: string;
74
+ deleted_at: string | null;
75
+ moderation: string | null;
76
+ };
77
+
78
+ const args = z.object({ conversationId: z.uuid() });
79
+
80
+ /**
81
+ * A message the prompt will show this reader. The same filter as `transcriptLines`: row level
82
+ * security still returns a sender their own hidden message, which the transcript leaves out.
83
+ */
84
+ const hasText = (m: MessageRow, observer: boolean) =>
85
+ m.kind === "text" &&
86
+ m.deleted_at === null &&
87
+ Boolean((m.body ?? "").trim()) &&
88
+ (observer || (m.visibility !== "observers" && m.moderation !== "hidden"));
89
+
90
+ /**
91
+ * Reads a conversation as the caller. Stops with `forbidden` when they aren't a member and
92
+ * `invalid_input` when there's nothing to work from (for the recap: nothing new since they read).
93
+ */
94
+ async function loadConversation(
95
+ ctx: AiContext<ChatAiDb> & { layer: (name: string, text: string, ids?: readonly string[]) => void },
96
+ conversationId: string,
97
+ options: ChatAiTaskOptions,
98
+ mode: "recap" | "draft",
99
+ ): Promise<LoadedConversation> {
100
+ const chat = ctx.db.schema("genesis_chat");
101
+ const member = await chat
102
+ .from("members")
103
+ .select("last_read_seq")
104
+ .eq("conversation_id", conversationId)
105
+ .eq("user_id", ctx.personId)
106
+ .is("left_at", null)
107
+ .maybeSingle();
108
+ if (member.error) throw new Error(`chat.${mode}: reading membership failed (${member.error.code ?? "?"})`);
109
+ if (!member.data) throw new GuardrailError(CHAT_AI_REFUSALS.notMember, "forbidden");
110
+ const lastRead = Number((member.data as { last_read_seq: number | null }).last_read_seq ?? 0);
111
+
112
+ const observes = await chat.rpc("i_observe", { p_conversation_id: conversationId });
113
+ const observer = !observes.error && observes.data === true;
114
+
115
+ const rows = await chat
116
+ .from("messages")
117
+ .select("id, seq, sender_id, body, created_at, kind, visibility, deleted_at, moderation")
118
+ .eq("conversation_id", conversationId)
119
+ .order("seq", { ascending: false })
120
+ .limit(MAX_MESSAGES);
121
+ if (rows.error) throw new Error(`chat.${mode}: reading messages failed (${rows.error.code ?? "?"})`);
122
+ const recent = [...((rows.data ?? []) as MessageRow[])].reverse();
123
+ if (!recent.some((m) => hasText(m, observer))) {
124
+ throw new GuardrailError(mode === "draft" ? CHAT_AI_REFUSALS.draftEmpty : CHAT_AI_REFUSALS.empty, "invalid_input");
125
+ }
126
+
127
+ let since: string | null = null;
128
+ if (mode === "recap") {
129
+ // The last-read message may be one this person can't see (an internal note, a hidden one):
130
+ // the newest visible one at or before it marks where "new" starts.
131
+ since = recent.filter((m) => m.seq <= lastRead).at(-1)?.created_at ?? null;
132
+ if (lastRead > 0 && !recent.some((m) => m.seq > lastRead && hasText(m, observer))) throw new GuardrailError(CHAT_AI_REFUSALS.empty, "invalid_input");
133
+ }
134
+
135
+ const messages: AssistantMessage[] = recent.map((m) => ({
136
+ senderId: m.sender_id,
137
+ body: m.body ?? "",
138
+ createdAt: m.created_at,
139
+ kind: m.kind === "system" ? "system" : "text",
140
+ visibility: m.visibility === "observers" ? "observers" : "everyone",
141
+ deletedAt: m.deleted_at,
142
+ moderation: m.moderation === "hidden" || m.moderation === "flagged" ? m.moderation : null,
143
+ }));
144
+ ctx.layer(
145
+ "messages",
146
+ messages.map((m) => m.body).join("\n"),
147
+ recent.map((m) => m.id),
148
+ );
149
+
150
+ const names = new Map<string, string | null | undefined>();
151
+ const resolveName = async (userId: string) => {
152
+ if (!options.resolveName) return null;
153
+ if (!names.has(userId)) names.set(userId, await options.resolveName(ctx.db, userId));
154
+ return names.get(userId);
155
+ };
156
+ return { messages, since, me: ctx.personId, observer, resolveName };
157
+ }
158
+
159
+ /** "Catch me up": a short recap of what came in since the caller last read the conversation. */
160
+ export function chatRecapTask(options: ChatAiTaskOptions = {}): TaskDefinition<{ conversationId: string }, LoadedConversation, { text: string }, ChatAiDb> {
161
+ return defineTask<{ conversationId: string }, LoadedConversation, { text: string }, ChatAiDb>({
162
+ id: "chat.recap",
163
+ version: 1,
164
+ feature: options.feature ?? "chat",
165
+ model: options.model ?? "default",
166
+ maxTokens: 4000,
167
+ args,
168
+ ...(options.can ? { can: options.can } : {}),
169
+ load: (ctx, { conversationId }) => loadConversation(ctx, conversationId, options, "recap"),
170
+ system: recapSystem(options.context),
171
+ prompt: (loaded) => recapPrompt(loaded),
172
+ output: "text",
173
+ });
174
+ }
175
+
176
+ /** A draft of the caller's next message, in their voice. Nothing is sent: a person decides. */
177
+ export function chatDraftReplyTask(options: DraftTaskOptions = {}): TaskDefinition<{ conversationId: string }, LoadedConversation, { text: string }, ChatAiDb> {
178
+ return defineTask<{ conversationId: string }, LoadedConversation, { text: string }, ChatAiDb>({
179
+ id: "chat.draft-reply",
180
+ version: 1,
181
+ feature: options.feature ?? "chat",
182
+ model: options.model ?? "default",
183
+ maxTokens: 4000,
184
+ args,
185
+ ...(options.can ? { can: options.can } : {}),
186
+ load: async (ctx, { conversationId }) => {
187
+ const loaded = await loadConversation(ctx, conversationId, options, "draft");
188
+ const voice = (await options.voice?.(ctx))?.trim();
189
+ return voice ? { ...loaded, voice } : loaded;
190
+ },
191
+ system: draftSystem(options.context),
192
+ prompt: (loaded) => draftPrompt(loaded),
193
+ output: "text",
194
+ });
195
+ }
@@ -152,3 +152,54 @@ describe("base64Utf8", () => {
152
152
  expect(base64Utf8("é/ü")).toBe(Buffer.from("é/ü").toString("base64"));
153
153
  });
154
154
  });
155
+
156
+ describe("createTusUpload's transport port", () => {
157
+ it("sends through the transport it's given, with chat's path, bucket, type and the person's headers", async () => {
158
+ const seen: { path: string; bucket: string; contentType: string; headers: Record<string, string>; bytes: number }[] = [];
159
+ const upload = createTusUpload({
160
+ supabaseUrl: URL_,
161
+ userId: USER,
162
+ getAccessToken: async () => "jwt",
163
+ apikey: "pk",
164
+ newId: () => "id9",
165
+ transport: {
166
+ async send(record, source, info) {
167
+ const bytes = await source.read(0, source.size);
168
+ seen.push({ path: record.path, bucket: info.bucket, contentType: info.contentType, headers: await info.headers(), bytes: bytes.byteLength });
169
+ record.done = true;
170
+ return record.path;
171
+ },
172
+ },
173
+ });
174
+ const f = file(10);
175
+ const path = await upload(CONV, f);
176
+ expect(path).toBe(`${CONV}/${USER}/id9.jpg`);
177
+ expect(seen).toEqual([{ path, bucket: "genesis-chat", contentType: "image/jpeg", headers: { authorization: "Bearer jwt", apikey: "pk" }, bytes: 10 }]);
178
+ // Done once: the same file again is the same path, without another send.
179
+ expect(await upload(CONV, f)).toBe(path);
180
+ expect(seen).toHaveLength(1);
181
+ });
182
+
183
+ it("keeps chat's file checks before the transport, and a rename the transport asks for", async () => {
184
+ const send = vi.fn(async (_record: { path: string }, _source: unknown, _info: unknown, renamePath: () => string) => renamePath());
185
+ let n = 0;
186
+ const upload = createTusUpload({ supabaseUrl: URL_, userId: USER, getAccessToken: async () => "jwt", newId: () => `id${++n}`, transport: { send } });
187
+ await expect(upload(CONV, { data: new Uint8Array(1).buffer, name: "run.exe", contentType: "application/x-msdownload" })).rejects.toMatchObject({ code: "22023" });
188
+ expect(send).not.toHaveBeenCalled();
189
+ expect(await upload(CONV, file(3))).toBe(`${CONV}/${USER}/id2.jpg`);
190
+ });
191
+
192
+ it("turns a transport's failures into chat's errors: refusals keep their kind, the rest are transient", async () => {
193
+ const failing = (error: unknown) =>
194
+ createTusUpload({ supabaseUrl: URL_, userId: USER, getAccessToken: async () => "jwt", transport: { send: async () => Promise.reject(error) } });
195
+ const forbidden = await failing(Object.assign(new Error("no"), { failure: "forbidden" }))(CONV, file(3)).catch((e: unknown) => e);
196
+ expect(forbidden).toBeInstanceOf(ChatError);
197
+ expect((forbidden as ChatError).forbidden).toBe(true);
198
+ const invalid = await failing(Object.assign(new Error("bad"), { failure: "invalid" }))(CONV, file(3)).catch((e: unknown) => e);
199
+ expect((invalid as ChatError).code).toBe("22023");
200
+ const network = await failing(new TypeError("Network request failed"))(CONV, file(3)).catch((e: unknown) => e);
201
+ expect((network as ChatError).transient).toBe(true);
202
+ const own = new ChatError("Sign in to send files", "42501", "upload");
203
+ expect(await failing(own)(CONV, file(3)).catch((e: unknown) => e)).toBe(own);
204
+ });
205
+ });
@@ -135,7 +135,7 @@ export {
135
135
  export { useVoiceRecorder, voiceNoteFile, type UseVoiceRecorderOptions } from "./use-voice-recorder";
136
136
  export { invertedRows, buildThreadRows, rowKey, type ThreadRow, type BuildRowsOptions } from "./rows";
137
137
  export { messageActionsFor, canReactTo, QUICK_REACTIONS, type MessageActionId, type MessageActionContext } from "./actions";
138
- export { createTusUpload, base64Utf8, TUS_CHUNK_BYTES, type TusUploadOptions } from "./tus";
138
+ export { createTusUpload, base64Utf8, TUS_CHUNK_BYTES, type TusUploadOptions, type TusTransport, type TusUploadRecord, type TusUploadSource, type TusSendInfo } from "./tus";
139
139
  export {
140
140
  CHAT_PUSH_CATEGORY,
141
141
  CHAT_REPLY_ACTION,