@cognolo/runtime 0.4.2

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 (82) hide show
  1. package/LICENSE +9 -0
  2. package/README.md +56 -0
  3. package/dist/agent.d.ts +290 -0
  4. package/dist/agent.js +245 -0
  5. package/dist/bundle.d.ts +192 -0
  6. package/dist/bundle.js +133 -0
  7. package/dist/cloud.d.ts +301 -0
  8. package/dist/cloud.js +383 -0
  9. package/dist/compact.d.ts +58 -0
  10. package/dist/compact.js +138 -0
  11. package/dist/context.d.ts +169 -0
  12. package/dist/context.js +144 -0
  13. package/dist/gate.d.ts +106 -0
  14. package/dist/gate.js +82 -0
  15. package/dist/guard.d.ts +15 -0
  16. package/dist/guard.js +26 -0
  17. package/dist/help.d.ts +44 -0
  18. package/dist/help.js +79 -0
  19. package/dist/index.d.ts +25 -0
  20. package/dist/index.js +25 -0
  21. package/dist/init-cli.d.ts +40 -0
  22. package/dist/init-cli.js +317 -0
  23. package/dist/links.d.ts +39 -0
  24. package/dist/links.js +89 -0
  25. package/dist/look.d.ts +462 -0
  26. package/dist/look.js +362 -0
  27. package/dist/models.d.ts +79 -0
  28. package/dist/models.js +145 -0
  29. package/dist/outside.d.ts +102 -0
  30. package/dist/outside.js +204 -0
  31. package/dist/page.d.ts +59 -0
  32. package/dist/page.js +158 -0
  33. package/dist/passkey-browser.d.ts +40 -0
  34. package/dist/passkey-browser.js +48 -0
  35. package/dist/passkey.d.ts +64 -0
  36. package/dist/passkey.js +130 -0
  37. package/dist/pictures.d.ts +23 -0
  38. package/dist/pictures.js +58 -0
  39. package/dist/propose.d.ts +36 -0
  40. package/dist/propose.js +178 -0
  41. package/dist/rate.d.ts +97 -0
  42. package/dist/rate.js +147 -0
  43. package/dist/react/index.d.ts +7 -0
  44. package/dist/react/index.js +7 -0
  45. package/dist/react/labels.d.ts +167 -0
  46. package/dist/react/labels.js +114 -0
  47. package/dist/react/logic.d.ts +77 -0
  48. package/dist/react/logic.js +140 -0
  49. package/dist/react/page-view.d.ts +3 -0
  50. package/dist/react/page-view.js +308 -0
  51. package/dist/react/panel.d.ts +179 -0
  52. package/dist/react/panel.js +749 -0
  53. package/dist/react/use-chat.d.ts +96 -0
  54. package/dist/react/use-chat.js +252 -0
  55. package/dist/research.d.ts +109 -0
  56. package/dist/research.js +207 -0
  57. package/dist/route.d.ts +405 -0
  58. package/dist/route.js +1493 -0
  59. package/dist/search.d.ts +70 -0
  60. package/dist/search.js +112 -0
  61. package/dist/sensitive.d.ts +54 -0
  62. package/dist/sensitive.js +209 -0
  63. package/dist/setup.d.ts +93 -0
  64. package/dist/setup.js +658 -0
  65. package/dist/store-sql.d.ts +52 -0
  66. package/dist/store-sql.js +150 -0
  67. package/dist/store.d.ts +166 -0
  68. package/dist/store.js +201 -0
  69. package/dist/text.d.ts +9 -0
  70. package/dist/text.js +21 -0
  71. package/dist/tool.d.ts +66 -0
  72. package/dist/tool.js +36 -0
  73. package/dist/trust.d.ts +13 -0
  74. package/dist/trust.js +18 -0
  75. package/dist/version.d.ts +40 -0
  76. package/dist/version.js +133 -0
  77. package/dist/webmcp-browser.d.ts +20 -0
  78. package/dist/webmcp-browser.js +61 -0
  79. package/dist/workflow.d.ts +253 -0
  80. package/dist/workflow.js +310 -0
  81. package/docs/store.md +330 -0
  82. package/package.json +71 -0
package/dist/setup.js ADDED
@@ -0,0 +1,658 @@
1
+ import { installSpec, RUNTIME_VERSION } from "./version.js";
2
+ const MODULE = /^[@~A-Za-z0-9_./-]{1,100}$/;
3
+ export function addCognoloFiles(c) {
4
+ if (c.framework === "express")
5
+ return addExpressFiles(c);
6
+ const base = c.base === "src/" ? "src/" : "";
7
+ const dbModule = c.dbModule && MODULE.test(c.dbModule) ? c.dbModule : "@/lib/db";
8
+ const signIn = c.signIn && c.signIn !== "replit-auth" && Object.prototype.hasOwnProperty.call(OPEN, c.signIn) ? c.signIn : "unknown";
9
+ const seen = signIn === "unknown" && c.signInSeen && /^[A-Za-z .()-]{1,40}$/.test(c.signInSeen) ? c.signInSeen : null;
10
+ const files = [];
11
+ const commands = [`npm install ${installSpec(RUNTIME_VERSION)} @anthropic-ai/sdk zod`];
12
+ const lib = `${base}lib/cognolo`;
13
+ const tables = [];
14
+ if (c.store === "prisma") {
15
+ if (c.prismaSchema === null) {
16
+ tables.push("The tables: there is no prisma/schema.prisma, so nothing was added. Copy the CognoloConversation and CognoloAction models from the @cognolo/runtime storage guide (docs/store.md) into your schema.");
17
+ }
18
+ else {
19
+ prismaModels(c.prismaSchema ?? "", files);
20
+ tables.push(`The tables: three models are in prisma/schema.prisma (conversations, the action log and passkeys), and \`db\` is imported from ${dbModule}.`);
21
+ }
22
+ tables.push("On MySQL, add @db.Text to state, transcript, input and summary: Prisma's String is too short there for a conversation.");
23
+ commands.push("npx prisma migrate dev --name cognolo");
24
+ }
25
+ else if (c.store === "drizzle") {
26
+ files.push({ path: `${lib}/schema.ts`, action: "create", content: DRIZZLE_TABLES }, { path: `${lib}/schema-passkeys.ts`, action: "create", content: DRIZZLE_PASSKEYS });
27
+ tables.push(`The tables: ${lib}/schema.ts (and schema-passkeys.ts, which it includes) are written for Postgres, and \`db\` is imported from ${dbModule}. For MySQL or SQLite, use that dialect's table builders.`);
28
+ tables.push(`Add ${lib}/schema.ts to the \`schema\` setting in drizzle.config, or drizzle-kit won't make the tables.`);
29
+ tables.push("If your database driver has no transactions (Neon over HTTP, Cloudflare D1), set `transactions: false` on drizzleStore in assistant.ts.");
30
+ commands.push("npx drizzle-kit generate", "npx drizzle-kit migrate");
31
+ }
32
+ else {
33
+ files.push({ path: "migrations/cognolo.sql", action: "create", content: SQL_TABLES }, { path: "migrations/cognolo-passkeys.sql", action: "create", content: SQL_PASSKEYS });
34
+ tables.push(`The tables: migrations/cognolo.sql and cognolo-passkeys.sql are written for Postgres, and a \`pool\` (from the pg package) is imported from ${dbModule}.`);
35
+ commands.push('psql "$DATABASE_URL" -f migrations/cognolo.sql', 'psql "$DATABASE_URL" -f migrations/cognolo-passkeys.sql');
36
+ }
37
+ const clerkFresh = signIn === "clerk" && Number(/\d+/.exec(c.signInVersion ?? "")?.[0] ?? 0) >= 7;
38
+ files.push({ path: `${lib}/assistant.ts`, action: "create", content: assistantFile(c.store, signIn, dbModule, undefined, clerkFresh) });
39
+ files.push({ path: `${base}app/api/assistant/route.ts`, action: "create", content: ROUTE_FILE });
40
+ files.push({ path: `${base}components/cognolo-assistant.tsx`, action: "create", content: PANEL_FILE });
41
+ if (!/^ANTHROPIC_API_KEY=/m.test(c.envExample ?? ""))
42
+ files.push({ path: ".env.example", action: "append", content: ENV_LINES });
43
+ const layout = c.layouts && c.assistantAt === undefined ? signedInLayout(c.layouts, base) : null;
44
+ const placed = layout ? withPanel(layout.content, layout.path, base) : null;
45
+ if (layout && placed)
46
+ files.push({ path: layout.path, action: "edit", content: placed, original: layout.content });
47
+ const check = [
48
+ signIn === "unknown"
49
+ ? `Who the person is: \`open\` in ${lib}/assistant.ts refuses every request until you fill it in with your own sign-in check.${seen ? ` Your app seems to use ${seen}, but Cognolo couldn't tell which version, so it didn't fill it in.` : ""} Nothing was guessed.`
50
+ : signIn === "clerk"
51
+ ? "Who the person is: `open` uses your Clerk sign-in and keeps each person's conversations by their Clerk user id. If people work inside organisations, add the organisation to the scope as well."
52
+ : "Who the person is: `open` uses your Auth.js sign-in and keeps each person's conversations by their user id, never their email. Auth.js leaves the id out of the session unless your session callback adds it (session.user.id = token.sub); until then the assistant refuses everyone.",
53
+ ...(signIn === "clerk"
54
+ ? [clerkFresh
55
+ ? "Passkeys: before anyone sets one up, Clerk is asked whether they signed in again in the last 10 minutes (signedInJustNow), so a script in their session can't add its own; someone who didn't is asked to sign in again first."
56
+ : "Passkeys: Cognolo couldn't confirm your Clerk version has re-verification (@clerk/nextjs 7 does), so it didn't add the fresh sign-in check. With 7 or later, add to assistant.ts `async function signedInJustNow() { const { has } = await auth(); return has({ reverification: \"strict\" }); }` and `passkey: { freshSignIn: signedInJustNow }` in cognoloRoute. Without it, a person's first passkey is trusted on first use (and none can be set up on Production)."]
57
+ : []),
58
+ ...(signIn === "next-auth" ? ["Passkeys: before anyone sets one up, they must have signed in within the last 10 minutes, so a script in their session can't add its own. Auth.js doesn't record when someone signed in, so add it in auth.ts: in the jwt callback, `if (user) token.signedInAt = Date.now()` (never copy it from an `update()`); in the session callback, `session.signedInAt = token.signedInAt`; and tell TypeScript about it with `declare module \"next-auth\" { interface Session { signedInAt?: number } }`. With database sessions, add a `createdAt` column to the Session table and use that, never anything worked out from `expires` (it moves forward). Until then, setting up a passkey asks people to sign in again and says what the app is missing."] : []),
59
+ "Which tools they hold: `tools` starts empty, so the assistant can only talk. Add the tools this person may use, and only those.",
60
+ "The business's time zone: set `timeZone` in open() (for example Europe/London), so \"today\" means the business's day. Without it, the assistant uses UTC.",
61
+ ...tables,
62
+ layout && placed
63
+ ? `The panel: <CognoloAssistantPanel /> is added to \`${layout.path}\`, right after {children}, so it shows on the signed-in pages that layout covers: a floating button in the bottom corner. If something else sits in that corner, add side="left" in ${base}components/cognolo-assistant.tsx; to put the button in your own header, move the line.`
64
+ : c.assistantAt
65
+ ? `The panel: your app already uses the assistant${SAFE_PATH.test(c.assistantAt) ? ` (in \`${c.assistantAt}\`)` : ""}, so no second button was added. ${base}components/cognolo-assistant.tsx is there if you want it instead.`
66
+ : PANEL_BY_HAND,
67
+ "The settings: copy the new lines in .env.example into each environment's own settings, with its own key from Cognolo.",
68
+ ...(c.baseGuessed ? ["The folders: these files assume your app is in app/ at the top. If it is in src/app/, move lib/, app/api/ and components/ under src/."] : []),
69
+ ];
70
+ return { files, check, commands };
71
+ }
72
+ export function setupSummary(plan) {
73
+ const edited = plan.files.find((f) => f.action === "edit");
74
+ return [
75
+ `Adds the Cognolo assistant to this app. Conversations stay in your own database; Cognolo runs no migration. Files marked "added to the end" only gain lines${edited ? `, and the only existing code it changes is one import and one line in \`${edited.path}\`` : "; no other existing code changes"}.`,
76
+ "",
77
+ "**Files**",
78
+ ...plan.files.map((f) => `- \`${f.path}\` (${f.action === "append" ? "added to the end" : f.action === "edit" ? "one import and one line added" : "new"})`),
79
+ "",
80
+ "**Check before merging**",
81
+ ...plan.check.map((x) => `- [ ] ${x}`),
82
+ "",
83
+ "**After merging, run**",
84
+ "```sh",
85
+ ...plan.commands,
86
+ "```",
87
+ ].join("\n");
88
+ }
89
+ const SIGN_IN = String.raw `(?:(?:auth|currentUser|getUser|getSession|getCurrentUser)\s*\(\s*\)|getServerSession\s*\([^()]*\))`;
90
+ const GUARDS_ITSELF = /\bauth\.protect\s*\(|\bredirectToSignIn\s*\(|\brequire(User|Auth|Session|SignIn|Login)\s*\(/;
91
+ const CHILDREN = /(?<=(?:(?<!=)>|\})\s*)\{\s*children\s*\}/g;
92
+ const SAFE_PATH = /^[\w@()[\]./ -]{1,200}$/;
93
+ export const PANEL_BY_HAND = "The panel: add <CognoloAssistantPanel /> (from components/cognolo-assistant.tsx) to your signed-in layout, after {children}.";
94
+ function codeOnly(src) {
95
+ const out = src.split("");
96
+ let i = 0, open = false;
97
+ const blank = (from, to) => { for (let k = from; k < to && k < out.length; k++)
98
+ if (out[k] !== "\n" && out[k] !== "\r")
99
+ out[k] = " "; };
100
+ while (i < src.length) {
101
+ const c = src[i], d = src[i + 1];
102
+ if (c === "/" && d === "/") {
103
+ const e = src.indexOf("\n", i);
104
+ const end = e < 0 ? src.length : e;
105
+ blank(i, end);
106
+ i = end;
107
+ continue;
108
+ }
109
+ if (c === "/" && d === "*") {
110
+ const e = src.indexOf("*/", i + 2);
111
+ if (e < 0)
112
+ open = true;
113
+ const end = e < 0 ? src.length : e + 2;
114
+ blank(i, end);
115
+ i = end;
116
+ continue;
117
+ }
118
+ if (c === '"' || c === "'" || c === "`") {
119
+ let j = i + 1;
120
+ while (j < src.length && src[j] !== c && !(c !== "`" && src[j] === "\n"))
121
+ j += src[j] === "\\" ? 2 : 1;
122
+ if (j >= src.length || src[j] !== c)
123
+ open = true;
124
+ if (c === "'" && /[A-Za-z]/.test(src[i - 1] ?? ""))
125
+ open = true;
126
+ blank(i + 1, j);
127
+ i = j + 1;
128
+ continue;
129
+ }
130
+ i++;
131
+ }
132
+ return { code: out.join(""), open };
133
+ }
134
+ const readable = (_content, r) => !r.open;
135
+ function sendsAwayIfSignedOut(code) {
136
+ if (GUARDS_ITSELF.test(code))
137
+ return true;
138
+ const names = new Set();
139
+ for (const m of code.matchAll(new RegExp(String.raw `\b(?:const|let|var)\s+(\w+)\s*(?::[^=;]+)?=\s*(?:await\s+)?${SIGN_IN}`, "g")))
140
+ names.add(m[1]);
141
+ for (const m of code.matchAll(new RegExp(String.raw `\b(?:const|let|var)\s*\{([^}]*)\}\s*(?::[^=;]+)?=\s*(?:await\s+)?${SIGN_IN}`, "g"))) {
142
+ for (const part of m[1].split(",")) {
143
+ const n = part.split(":").pop().split("=")[0].trim();
144
+ if (/^\w+$/.test(n))
145
+ names.add(n);
146
+ }
147
+ }
148
+ const redirect = String.raw `\s*\{?\s*(?:return\s+)?(?:redirect|redirectToSignIn)\s*\(`;
149
+ if (new RegExp(String.raw `\bif\s*\(\s*!\s*\(\s*await\s+${SIGN_IN}\s*\)\s*\)` + redirect).test(code))
150
+ return true;
151
+ for (const n of names) {
152
+ if (new RegExp(String.raw `\bif\s*\(\s*!\s*\(?\s*${n}(?:\??\.(?:user|id|userId|session)\b)*\s*\)?\s*(?:\|\|[^)]*)?\)` + redirect).test(code))
153
+ return true;
154
+ }
155
+ return false;
156
+ }
157
+ export function signedInLayout(layouts, base = "") {
158
+ const dir = (p) => p.replace(/\/layout\.[jt]sx$/, "");
159
+ const root = `${base}app`;
160
+ const ok = layouts.filter((l) => {
161
+ if (typeof l.path !== "string" || typeof l.content !== "string" || !SAFE_PATH.test(l.path) || l.path.includes(".."))
162
+ return false;
163
+ if (!/\/layout\.[jt]sx$/.test(l.path) || !l.path.startsWith(`${root}/`) || dir(l.path) === root || l.content.includes("�"))
164
+ return false;
165
+ const r = codeOnly(l.content);
166
+ if (!readable(l.content, r) || /<(html|body)\b/.test(r.code) || /CognoloAssistant/.test(l.content))
167
+ return false;
168
+ return sendsAwayIfSignedOut(r.code) && withPanel(l.content, l.path, base) !== null;
169
+ });
170
+ const top = [...ok].sort((a, b) => a.path.split("/").length - b.path.split("/").length)[0];
171
+ if (!top)
172
+ return null;
173
+ return ok.every((l) => l === top || dir(l.path).startsWith(`${dir(top.path)}/`)) ? top : null;
174
+ }
175
+ function panelImport(layoutPath, base) {
176
+ const from = layoutPath.split("/").slice(0, -1), to = `${base}components/cognolo-assistant`.split("/");
177
+ let same = 0;
178
+ while (same < from.length && same < to.length - 1 && from[same] === to[same])
179
+ same++;
180
+ const up = from.length - same;
181
+ return `${up ? "../".repeat(up) : "./"}${to.slice(same).join("/")}`;
182
+ }
183
+ export function withPanel(content, layoutPath = "app/(app)/layout.tsx", base = "") {
184
+ if (content.includes("�"))
185
+ return null;
186
+ const r = codeOnly(content);
187
+ if (!readable(content, r))
188
+ return null;
189
+ const code = r.code;
190
+ const kids = [...code.matchAll(CHILDREN)];
191
+ if (kids.length !== 1 || (content.match(CHILDREN) ?? []).length !== 1)
192
+ return null;
193
+ const nl = content.includes("\r\n") ? "\r\n" : "\n";
194
+ const line = `import { CognoloAssistantPanel } from "${panelImport(layoutPath, base)}";`;
195
+ const exportAt = code.search(/^\uFEFF?export\s+default\b/m);
196
+ if (exportAt < 0)
197
+ return null;
198
+ const imports = [...code.matchAll(/^import\b(?:[^;]*?\bfrom\s*(["'])[^"'\n]*\1|\s*(["'])[^"'\n]*\2)[ \t]*;?/gm)];
199
+ let at, ins;
200
+ if (imports.length) {
201
+ const m = imports[imports.length - 1];
202
+ if (m.index > exportAt)
203
+ return null;
204
+ at = m.index + m[0].length;
205
+ const eol = content.indexOf("\n", at);
206
+ const end = eol < 0 ? content.length : content[eol - 1] === "\r" ? eol - 1 : eol;
207
+ if (!code.slice(at, end).trim())
208
+ at = end;
209
+ ins = nl + line;
210
+ }
211
+ else {
212
+ const directive = /^(?)[ \t]*(["'])use (client|server)\2[ \t]*;?/.exec(content);
213
+ if (directive) {
214
+ at = directive[0].length;
215
+ ins = nl + line;
216
+ }
217
+ else if (/(["'])use (client|server)\1/.test(content))
218
+ return null;
219
+ else {
220
+ at = content.startsWith("") ? 1 : 0;
221
+ ins = line + nl;
222
+ }
223
+ }
224
+ const k = kids[0].index + kids[0][0].length;
225
+ if (k <= at)
226
+ return null;
227
+ return content.slice(0, at) + ins + content.slice(at, k) + "<CognoloAssistantPanel />" + content.slice(k);
228
+ }
229
+ const PRISMA_PASSKEY_MODEL = `
230
+ // Cognolo: passkeys for approving changes that can't be undone, and the marks of approvals already used.
231
+ model CognoloPasskey {
232
+ id String @id
233
+ kind String
234
+ userId String
235
+ credentialId String?
236
+ publicKey String?
237
+ alg Int?
238
+ info String?
239
+ createdAt String
240
+
241
+ @@index([userId, kind])
242
+ }
243
+ `;
244
+ function prismaModels(schema, files) {
245
+ if (!/model\s+CognoloConversation\b/.test(schema))
246
+ files.push({ path: "prisma/schema.prisma", action: "append", content: PRISMA_MODELS + PRISMA_PASSKEY_MODEL });
247
+ else if (!/model\s+CognoloPasskey\b/.test(schema))
248
+ files.push({ path: "prisma/schema.prisma", action: "append", content: PRISMA_PASSKEY_MODEL });
249
+ }
250
+ const PRISMA_MODELS = `
251
+ // Cognolo: the assistant's conversations and its action log, kept in your own database.
252
+ model CognoloConversation {
253
+ id String @id @default(cuid())
254
+ userId String
255
+ title String @default("New conversation")
256
+ state String
257
+ transcript String @default("[]")
258
+ createdAt DateTime @default(now())
259
+ updatedAt DateTime @updatedAt
260
+ actions CognoloAction[]
261
+
262
+ @@index([userId, updatedAt])
263
+ }
264
+
265
+ model CognoloAction {
266
+ id String @id @default(cuid())
267
+ conversationId String
268
+ conversation CognoloConversation @relation(fields: [conversationId], references: [id], onDelete: Cascade)
269
+ userId String
270
+ tool String
271
+ title String
272
+ risk String
273
+ input String
274
+ status String
275
+ ok Boolean @default(true)
276
+ summary String
277
+ createdAt DateTime @default(now())
278
+ }
279
+ `;
280
+ const DRIZZLE_TABLES = `import { boolean, index, pgTable, text, timestamp } from "drizzle-orm/pg-core";
281
+
282
+ // Cognolo: the assistant's conversations and its action log, kept in your own database.
283
+ export const cognoloConversations = pgTable("cognolo_conversations", {
284
+ id: text("id").primaryKey(),
285
+ userId: text("user_id").notNull(),
286
+ title: text("title").notNull().default("New conversation"),
287
+ state: text("state").notNull(),
288
+ transcript: text("transcript").notNull().default("[]"),
289
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
290
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
291
+ }, (t) => [index("cognolo_conversations_owner").on(t.userId, t.updatedAt)]);
292
+
293
+ export const cognoloActions = pgTable("cognolo_actions", {
294
+ id: text("id").primaryKey(),
295
+ conversationId: text("conversation_id").notNull().references(() => cognoloConversations.id, { onDelete: "cascade" }),
296
+ userId: text("user_id").notNull(),
297
+ tool: text("tool").notNull(),
298
+ title: text("title").notNull(),
299
+ risk: text("risk").notNull(),
300
+ input: text("input").notNull(),
301
+ status: text("status").notNull(),
302
+ ok: boolean("ok").notNull().default(true),
303
+ summary: text("summary").notNull(),
304
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
305
+ });
306
+
307
+ export * from "./schema-passkeys";
308
+ `;
309
+ const DRIZZLE_PASSKEYS = `import { index, integer, pgTable, text } from "drizzle-orm/pg-core";
310
+
311
+ // Cognolo: passkeys for approving changes that can't be undone, and the marks of approvals already used.
312
+ export const cognoloPasskeys = pgTable("cognolo_passkeys", {
313
+ id: text("id").primaryKey(),
314
+ kind: text("kind").notNull(),
315
+ userId: text("user_id").notNull(),
316
+ credentialId: text("credential_id"),
317
+ publicKey: text("public_key"),
318
+ alg: integer("alg"),
319
+ info: text("info"),
320
+ createdAt: text("created_at").notNull(),
321
+ }, (t) => [index("cognolo_passkeys_owner").on(t.userId, t.kind)]);
322
+ `;
323
+ const SQL_PASSKEYS = `-- Cognolo: passkeys for approving changes that can't be undone, and the marks of approvals already used (Postgres).
324
+ CREATE TABLE IF NOT EXISTS cognolo_passkeys (
325
+ id TEXT PRIMARY KEY,
326
+ kind TEXT NOT NULL,
327
+ user_id TEXT NOT NULL,
328
+ credential_id TEXT,
329
+ public_key TEXT,
330
+ alg INTEGER,
331
+ info TEXT,
332
+ created_at TEXT NOT NULL
333
+ );
334
+ CREATE INDEX IF NOT EXISTS cognolo_passkeys_owner ON cognolo_passkeys (user_id, kind);
335
+ `;
336
+ const SQL_TABLES = `-- Cognolo: the assistant's conversations and its action log, kept in your own database (Postgres).
337
+ CREATE TABLE IF NOT EXISTS cognolo_conversations (
338
+ id TEXT PRIMARY KEY,
339
+ user_id TEXT NOT NULL,
340
+ title TEXT NOT NULL DEFAULT 'New conversation',
341
+ state TEXT NOT NULL,
342
+ transcript TEXT NOT NULL DEFAULT '[]',
343
+ created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
344
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
345
+ );
346
+ CREATE INDEX IF NOT EXISTS cognolo_conversations_owner ON cognolo_conversations (user_id, updated_at);
347
+
348
+ CREATE TABLE IF NOT EXISTS cognolo_actions (
349
+ id TEXT PRIMARY KEY,
350
+ conversation_id TEXT NOT NULL REFERENCES cognolo_conversations(id) ON DELETE CASCADE,
351
+ user_id TEXT NOT NULL,
352
+ tool TEXT NOT NULL,
353
+ title TEXT NOT NULL,
354
+ risk TEXT NOT NULL,
355
+ input TEXT NOT NULL,
356
+ status TEXT NOT NULL,
357
+ ok BOOLEAN NOT NULL DEFAULT TRUE,
358
+ summary TEXT NOT NULL,
359
+ created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
360
+ );
361
+ `;
362
+ const ROUTE_FILE = `import { assistantRoute } from "@/lib/cognolo/assistant";
363
+
364
+ // The assistant panel talks to this. Everything runs as the signed-in person; see lib/cognolo/assistant.ts.
365
+ export const { POST, GET } = assistantRoute;
366
+ `;
367
+ const PANEL_FILE = `"use client";
368
+
369
+ import { CognoloAssistant } from "@cognolo/runtime/react";
370
+
371
+ // The assistant's button and panel. Put it in your signed-in layout.
372
+ export function CognoloAssistantPanel() {
373
+ return <CognoloAssistant endpoint="/api/assistant" floating />;
374
+ }
375
+ `;
376
+ const ENV_LINES = `
377
+ # Cognolo: the assistant. Each environment gets its own key from Cognolo's Setup page.
378
+ ANTHROPIC_API_KEY=
379
+ COGNOLO_KEY=
380
+ COGNOLO_URL=
381
+ # Optional: leave empty to trust Cognolo's own signing keys, built into the runtime. Several keys may go here, one after another.
382
+ COGNOLO_PUBLIC_KEY=
383
+ COGNOLO_ENV=
384
+ # Every address people open the app at, comma-separated (https://shop.example,https://www.shop.example), so approving a
385
+ # change that can't be undone asks for the person's passkey. Empty: approving takes a click, and the owner is told.
386
+ COGNOLO_ORIGINS=
387
+ `;
388
+ const OPEN = {
389
+ "next-auth": {
390
+ imports: 'import { auth } from "@/auth";',
391
+ body: ` const session = await auth();
392
+ if (!session?.user) throw new AssistantUnavailable("Sign in to use the assistant.");
393
+ const userId = session.user.id;
394
+ if (!userId) throw new AssistantUnavailable("The assistant isn't set up yet: add the user's id to the session in auth.ts (session.user.id = token.sub).");`,
395
+ fresh: `// Before a passkey is set up, the person must have signed in within the last 10 minutes, so a script in someone's
396
+ // session can't add a passkey of its own. auth.ts records when they signed in (signedInAt).
397
+ async function signedInJustNow(): Promise<boolean> {
398
+ const at = ((await auth()) as { signedInAt?: unknown } | null)?.signedInAt;
399
+ if (typeof at !== "number") throw new AssistantUnavailable("Sign in again to set up a passkey. If that doesn't help, the app isn't recording when people sign in (signedInAt in auth.ts).");
400
+ return recentSignIn(at);
401
+ }`,
402
+ },
403
+ clerk: {
404
+ imports: 'import { auth } from "@clerk/nextjs/server";',
405
+ body: ` const { userId } = await auth();
406
+ if (!userId) throw new AssistantUnavailable("Sign in to use the assistant.");`,
407
+ fresh: `// Before a passkey is set up, Clerk is asked whether the person signed in again in the last 10 minutes ("strict"), so a
408
+ // script in someone's session can't add a passkey of its own.
409
+ async function signedInJustNow(): Promise<boolean> {
410
+ const { has } = await auth();
411
+ return has({ reverification: "strict" });
412
+ }`,
413
+ },
414
+ unknown: {
415
+ imports: "",
416
+ body: ` // TODO: find the signed-in person with your own sign-in check, and refuse if there is none. Until this is written,
417
+ // the assistant answers nobody: Cognolo didn't guess who your users are.
418
+ const userId: string | null = null;
419
+ if (!userId) throw new AssistantUnavailable("The assistant isn't set up yet: fill in open() in lib/cognolo/assistant.ts.");`,
420
+ },
421
+ };
422
+ const openExpress = (signIn, lib) => ({
423
+ imports: "",
424
+ body: ` const userId = signedIn.get(req);
425
+ if (!userId) throw new AssistantUnavailable(${signIn === "unknown" ? `"The assistant isn't set up yet: fill in signedInUser() in ${lib}/express.ts."` : `"Sign in to use the assistant."`});`,
426
+ });
427
+ const WHO_EXPRESS = {
428
+ "replit-auth": `// Replit Auth: the signed-in person's Replit user id (claims.sub), never their email.
429
+ function signedInUser(req: ExpressRequest): string | null {
430
+ const r = req as ExpressRequest & { isAuthenticated?: () => boolean; user?: { claims?: { sub?: unknown } } };
431
+ const sub = r.isAuthenticated?.() ? r.user?.claims?.sub : undefined;
432
+ return typeof sub === "string" && sub ? sub : null;
433
+ }`,
434
+ unknown: `// TODO: return the signed-in person's user id (never their email) from your own sign-in, or null if nobody is signed
435
+ // in. Until this is written, the assistant answers nobody: Cognolo didn't guess who your users are.
436
+ // For example, with Passport sessions:
437
+ // const r = req as ExpressRequest & { isAuthenticated?: () => boolean; user?: { id?: unknown } };
438
+ // return r.isAuthenticated?.() && r.user?.id ? String(r.user.id) : null;
439
+ function signedInUser(_req: ExpressRequest): string | null {
440
+ return null;
441
+ }`,
442
+ };
443
+ function expressAdapter(signIn) {
444
+ return `import express, { type ErrorRequestHandler, type Express, type Request as ExpressRequest, type RequestHandler, type Response as ExpressResponse } from "express";
445
+ import { assistantRoute, signedIn } from "./assistant";
446
+
447
+ // Added by Cognolo: serves the assistant at /api/assistant from this app's own server. Mount it after your sign-in is set
448
+ // up (sessions, Passport), so the person is known, with the check your own pages use for signed-in people:
449
+ // mountCognolo(app, yourSignInCheck).
450
+
451
+ ${WHO_EXPRESS[signIn]}
452
+
453
+ async function handle(req: ExpressRequest, res: ExpressResponse) {
454
+ // Only JSON, as the assistant's panel sends: a form posted from another website can't speak for the signed-in person.
455
+ if (req.method === "POST" && !req.is("application/json")) {
456
+ res.status(415).json({ error: "Send JSON." });
457
+ return;
458
+ }
459
+ try {
460
+ // A standard web Request, as the assistant's route expects. The person comes from the server's own session, never
461
+ // from anything the browser sends.
462
+ const web = new Request(new URL(req.originalUrl, "http://localhost"), {
463
+ method: req.method,
464
+ // The headers the assistant checks (where a request came from and through which address, and the browser for a passkey) and the sign-in cookie.
465
+ headers: Object.fromEntries([["content-type", "application/json"], ["accept", req.get("accept") ?? "application/json"], ...["origin", "sec-fetch-site", "user-agent", "cookie", "host", "x-forwarded-for", "x-forwarded-host", "forwarded", "x-real-ip"].flatMap((h) => { const v = req.get(h); return v ? [[h, v]] : []; })]),
466
+ ...(req.method === "POST" ? { body: JSON.stringify(req.body ?? {}) } : {}),
467
+ });
468
+ const userId = signedInUser(req);
469
+ if (userId) signedIn.set(web, userId);
470
+ const route = req.method === "POST" ? assistantRoute.POST : assistantRoute.GET;
471
+ const answer = await route(web, { params: Promise.resolve({}) });
472
+ res.status(answer.status);
473
+ answer.headers.forEach((value, name) => { if (name !== "content-length") res.setHeader(name, value); });
474
+ res.send(Buffer.from(await answer.arrayBuffer()));
475
+ } catch (e) {
476
+ console.error("Cognolo assistant:", e);
477
+ res.status(500).json({ error: "The assistant ran into a problem. Please try again." });
478
+ }
479
+ }
480
+
481
+ /** A request the JSON reader refused (too large, not JSON), answered the way the assistant's route answers. */
482
+ const readFailed: ErrorRequestHandler = (err, _req, res, next) => {
483
+ if (res.headersSent) return next(err);
484
+ const tooLarge = (err as { status?: number }).status === 413;
485
+ res.status(tooLarge ? 413 : 400).json({ error: tooLarge ? "That's too large to send." : "Send JSON." });
486
+ };
487
+
488
+ /** \`guards\`: the checks your own pages use for signed-in people (for example Replit Auth's isAuthenticated), run first. */
489
+ export function mountCognolo(app: Express, ...guards: RequestHandler[]) {
490
+ app.post("/api/assistant", ...guards, express.json({ limit: "2mb" }), handle, readFailed);
491
+ app.get("/api/assistant", ...guards, handle);
492
+ }
493
+ `;
494
+ }
495
+ const PANEL_FILE_VITE = `import { CognoloAssistant } from "@cognolo/runtime/react";
496
+
497
+ // The assistant's button and panel. Put it in the part of your app signed-in people see.
498
+ export function CognoloAssistantPanel() {
499
+ return <CognoloAssistant endpoint="/api/assistant" floating />;
500
+ }
501
+ `;
502
+ const dirOf = (d, fallback) => (d && /^[\w-]+(\/[\w-]+)*$/.test(d) ? d : fallback);
503
+ function addExpressFiles(c) {
504
+ const server = dirOf(c.serverDir, "server");
505
+ const client = dirOf(c.clientDir, "client/src");
506
+ const dbModule = c.dbModule && MODULE.test(c.dbModule) ? c.dbModule : "../db";
507
+ const dbNote = c.dbModule ? "" : ` (check this path: Cognolo didn't find ${server}/db.ts)`;
508
+ const signIn = c.signIn === "replit-auth" ? "replit-auth" : "unknown";
509
+ const lib = `${server}/cognolo`;
510
+ const files = [];
511
+ const commands = [`npm install ${installSpec(RUNTIME_VERSION)} @anthropic-ai/sdk zod`];
512
+ const tables = [];
513
+ if (c.store === "prisma") {
514
+ if (c.prismaSchema === null)
515
+ tables.push("The tables: there is no prisma/schema.prisma, so nothing was added. Copy the CognoloConversation and CognoloAction models from the @cognolo/runtime storage guide (docs/store.md) into your schema.");
516
+ else {
517
+ prismaModels(c.prismaSchema ?? "", files);
518
+ tables.push(`The tables: three models are in prisma/schema.prisma (conversations, the action log and passkeys), and \`db\` is imported from ${dbModule} (in ${lib}/)${dbNote}.`);
519
+ }
520
+ commands.push("npx prisma migrate dev --name cognolo");
521
+ }
522
+ else if (c.store === "drizzle") {
523
+ files.push({ path: `${lib}/schema.ts`, action: "create", content: DRIZZLE_TABLES }, { path: `${lib}/schema-passkeys.ts`, action: "create", content: DRIZZLE_PASSKEYS });
524
+ tables.push(`The tables: ${lib}/schema.ts (and schema-passkeys.ts, which it includes) are written for Postgres, and \`db\` is imported from ${dbModule} (in ${lib}/)${dbNote}. Add ./${lib}/schema.ts to the \`schema\` setting in drizzle.config (it can be a list), or the tables won't be made. When you make them, read what it proposes before agreeing: it compares your whole database.`);
525
+ commands.push(c.pushScript ? "npm run db:push" : "npx drizzle-kit push");
526
+ }
527
+ else {
528
+ files.push({ path: "migrations/cognolo.sql", action: "create", content: SQL_TABLES }, { path: "migrations/cognolo-passkeys.sql", action: "create", content: SQL_PASSKEYS });
529
+ tables.push(`The tables: migrations/cognolo.sql and cognolo-passkeys.sql are written for Postgres, and a \`pool\` (from the pg package) is imported from ${dbModule} (in ${lib}/)${dbNote}.`);
530
+ commands.push('psql "$DATABASE_URL" -f migrations/cognolo.sql', 'psql "$DATABASE_URL" -f migrations/cognolo-passkeys.sql');
531
+ }
532
+ files.push({ path: `${lib}/assistant.ts`, action: "create", content: assistantFile(c.store, signIn, dbModule, lib) });
533
+ files.push({ path: `${lib}/express.ts`, action: "create", content: expressAdapter(signIn) });
534
+ files.push({ path: `${client}/components/cognolo-assistant.tsx`, action: "create", content: PANEL_FILE_VITE });
535
+ if (!/^ANTHROPIC_API_KEY=/m.test(c.envExample ?? ""))
536
+ files.push({ path: ".env.example", action: "append", content: ENV_LINES });
537
+ const check = [
538
+ signIn === "replit-auth"
539
+ ? `Who the person is: ${lib}/express.ts uses your Replit Auth sign-in and keeps each person's conversations by their Replit user id.`
540
+ : `Who the person is: signedInUser() in ${lib}/express.ts returns nobody until you fill it in with your own sign-in (the user's id, never their email), so the assistant refuses everyone until then. Nothing was guessed.`,
541
+ "Which tools they hold: `tools` starts empty, so the assistant can only talk. Add the tools this person may use, and only those.",
542
+ "The business's time zone: set `timeZone` in open() (for example Europe/London), so \"today\" means the business's day. Without it, the assistant uses UTC.",
543
+ ...tables,
544
+ signIn === "replit-auth"
545
+ ? `The route: in the file that sets up your server's routes (often ${server}/routes.ts), after setupAuth, add \`import { mountCognolo } from "./cognolo/express";\` and \`mountCognolo(app, isAuthenticated);\`, with isAuthenticated from your Replit Auth file, so someone whose sign-in has ended is turned away as your own pages do.`
546
+ : `The route: in the file that sets up your server's routes (often ${server}/routes.ts), after your sign-in is set up, add \`import { mountCognolo } from "./cognolo/express";\` and \`mountCognolo(app, yourSignInCheck);\`, passing the check your own pages use for signed-in people, if you have one.`,
547
+ "Pictures: if your server already reads JSON for every route (app.use(express.json())), raise its limit to 2mb, or pictures sent to the assistant are refused.",
548
+ `The panel: add <CognoloAssistantPanel /> (from ${client}/components/cognolo-assistant.tsx) to the part of your app signed-in people see, such as ${client}/App.tsx. It's a floating button in the bottom corner. If the front end runs on its own port while you develop, send /api to the server (Vite's server.proxy).`,
549
+ "The settings: put the new lines in .env.example into each environment's own settings (on Replit, its Secrets), with its own key from Cognolo.",
550
+ ];
551
+ return { files, check, commands };
552
+ }
553
+ const LOAD_SETTINGS = `
554
+ // The settings \`npx cognolo key\` wrote into .env.cognolo (kept out of git), when this app keeps them there.
555
+ try { (process as { loadEnvFile?: (file: string) => void }).loadEnvFile?.(".env.cognolo"); } catch { /* not there: they come from the app's own settings */ }
556
+ `;
557
+ function assistantFile(store, signIn, dbModule, express, clerkFresh = false) {
558
+ const open = express ? openExpress(signIn === "replit-auth" ? "replit-auth" : "unknown", express) : OPEN[signIn];
559
+ const o = signIn === "clerk" && !clerkFresh ? { ...open, fresh: undefined } : open;
560
+ const storeImport = store === "prisma" ? "prismaStore" : store === "drizzle" ? "drizzleStore" : "sqlStore";
561
+ const extra = store === "drizzle"
562
+ ? `import { and, desc, eq } from "drizzle-orm";\nimport { db } from "${dbModule}";\nimport { cognoloActions, cognoloConversations, cognoloPasskeys } from "./schema";`
563
+ : store === "prisma" ? `import { db } from "${dbModule}";` : `import { pool } from "${dbModule}";`;
564
+ const storeCode = store === "prisma"
565
+ ? `const store = prismaStore<Scope>({
566
+ db,
567
+ conversations: db.cognoloConversation,
568
+ actions: db.cognoloAction,
569
+ passkeys: db.cognoloPasskey,
570
+ owner: (s) => ({ userId: s.userId }),
571
+ });`
572
+ : store === "drizzle"
573
+ ? `const store = drizzleStore<Scope>({
574
+ db,
575
+ conversations: cognoloConversations,
576
+ actions: cognoloActions,
577
+ passkeys: cognoloPasskeys,
578
+ ops: { eq, and, desc },
579
+ owner: (s) => ({ userId: s.userId }),
580
+ // transactions: false, // for a driver without transactions (Neon over HTTP, Cloudflare D1)
581
+ });`
582
+ : `const store = sqlStore<Scope>({
583
+ query: (sql, params) => pool.query(sql, params).then((r) => r.rows),
584
+ // So a save and its action log land together.
585
+ transaction: async (fn) => {
586
+ const client = await pool.connect();
587
+ try {
588
+ await client.query("BEGIN");
589
+ const out = await fn((sql, params) => client.query(sql, params).then((r) => r.rows));
590
+ await client.query("COMMIT");
591
+ return out;
592
+ } catch (e) {
593
+ // The first error is the one worth seeing, even if the rollback fails too.
594
+ await client.query("ROLLBACK").catch(() => {});
595
+ throw e;
596
+ } finally {
597
+ client.release();
598
+ }
599
+ },
600
+ passkeys: "cognolo_passkeys",
601
+ owner: (s) => ({ user_id: s.userId }),
602
+ });`;
603
+ return `import Anthropic from "@anthropic-ai/sdk";
604
+ import { AssistantUnavailable, claudeModel, cognoloCloud, cognoloRoute, ${storeImport}, ${o.fresh && signIn === "next-auth" ? "recentSignIn, " : ""}type CognoloCloud, type ModelClient, type ToolDef } from "@cognolo/runtime";
605
+ ${extra}
606
+ ${o.imports ? `${o.imports}\n` : ""}${express ? LOAD_SETTINGS : ""}
607
+ // Added by Cognolo. Check ${express ? "signedInUser() in express.ts" : "open()"} before you merge: who the person is, and which tools they hold.
608
+
609
+ /** What your tools receive when they run. Add whatever they need (the person, their organisation). */
610
+ type Ctx = { userId: string };
611
+ /** Whose conversations these are: each person sees only their own. */
612
+ type Scope = { userId: string };
613
+
614
+ ${storeCode}
615
+
616
+ function model(): ModelClient {
617
+ if (!process.env.ANTHROPIC_API_KEY) throw new AssistantUnavailable("The assistant isn't set up on this server yet: add an ANTHROPIC_API_KEY.");
618
+ return claudeModel({ client: new Anthropic() });
619
+ }
620
+
621
+ // Rules and reporting from Cognolo, when this environment has a key. Without these settings the assistant says it isn't
622
+ // set up, in development as on a live server.
623
+ const g = globalThis as unknown as { __cognoloCloud?: CognoloCloud<Ctx> };
624
+ function cloud(): CognoloCloud<Ctx> | undefined {
625
+ const { COGNOLO_KEY: key, COGNOLO_URL: baseUrl, COGNOLO_PUBLIC_KEY: publicKey, COGNOLO_ENV: env } = process.env;
626
+ if (!key || !baseUrl || !env) return undefined;
627
+ // Without COGNOLO_PUBLIC_KEY the runtime trusts Cognolo's own signing keys.
628
+ g.__cognoloCloud ??= cognoloCloud<Ctx>({ key, baseUrl, publicKey: publicKey ? publicKey.replace(/\\\\n/g, "\\n") : undefined, env });
629
+ g.__cognoloCloud.start();
630
+ return g.__cognoloCloud;
631
+ }
632
+
633
+ /** The tools this person may use. It starts empty, so the assistant can only talk until you add them. */
634
+ function toolsFor(_userId: string): ToolDef<Ctx>[] {
635
+ return [];
636
+ }
637
+ ${o.fresh ? `\n${o.fresh}\n` : ""}
638
+ ${express ? "/** Who is signed in, for each request the Express adapter (express.ts) passes on: set by the server, never by the browser. */\nexport const signedIn = new WeakMap<Request, string>();\n\n" : ""}export const assistantRoute = cognoloRoute<Ctx, Scope>({
639
+ env: process.env.COGNOLO_ENV || "local",
640
+ get cloud() { return cloud(); },
641
+ async open(${express ? "req" : ""}) {
642
+ ${o.body}
643
+ return {
644
+ scope: { userId },
645
+ ctx: { userId },
646
+ // Who this is, for plans that count people (the same user id as the scope).
647
+ person: userId,
648
+ // The business's time zone, so "today" means its day; without it, UTC. For example: timeZone: "Europe/London",
649
+ tools: toolsFor(userId),
650
+ system: "You help people use this app. Use the tools you are given; if you can't do something, say so plainly.",
651
+ };
652
+ },
653
+ model,
654
+ ...store,${o.fresh ? "\n // Asked before every passkey is set up (see signedInJustNow above).\n passkey: { freshSignIn: signedInJustNow }," : ""}
655
+ });
656
+ `;
657
+ }
658
+ export { compareVersions, installSpec, isVersion, RELEASES, RUNTIME_VERSION, updatePlan } from "./version.js";