@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/docs/store.md ADDED
@@ -0,0 +1,330 @@
1
+ # Keeping conversations in your app (`prismaStore`, `sqlStore`, `drizzleStore`)
2
+
3
+ Cognolo keeps no conversations: they stay in your app's own database. `prismaStore` gives the route its `load`, `save`
4
+ and `list`, so you only add two tables.
5
+
6
+ ## 1. Add the tables
7
+
8
+ Copy into `schema.prisma`, then run `npx prisma migrate dev --name cognolo`. Rename the owner columns to whatever says
9
+ whose a conversation is in your app (a user id, an organisation, an environment).
10
+
11
+ ```prisma
12
+ model CognoloConversation {
13
+ id String @id @default(cuid())
14
+ userId String
15
+ title String @default("New conversation")
16
+ state String
17
+ transcript String @default("[]")
18
+ createdAt DateTime @default(now())
19
+ updatedAt DateTime @updatedAt
20
+ actions CognoloAction[]
21
+
22
+ @@index([userId, updatedAt])
23
+ }
24
+
25
+ // Every tool the assistant ran or proposed, on whose behalf, and what came of it.
26
+ model CognoloAction {
27
+ id String @id @default(cuid())
28
+ conversationId String
29
+ conversation CognoloConversation @relation(fields: [conversationId], references: [id], onDelete: Cascade)
30
+ userId String
31
+ tool String
32
+ title String
33
+ risk String
34
+ input String
35
+ status String
36
+ ok Boolean @default(true)
37
+ summary String
38
+ createdAt DateTime @default(now())
39
+ }
40
+ ```
41
+
42
+ ## 2. Pass it to the route
43
+
44
+ ```ts
45
+ import { cognoloRoute, prismaStore } from "@cognolo/runtime";
46
+
47
+ const store = prismaStore<{ userId: string }>({
48
+ db,
49
+ conversations: db.cognoloConversation,
50
+ actions: db.cognoloAction,
51
+ owner: (s) => ({ userId: s.userId }),
52
+ });
53
+
54
+ export const { POST, GET } = cognoloRoute({ ...store, open, model, env: "dev" });
55
+ ```
56
+
57
+ `owner` turns the scope your `open` returns into the columns to match. A conversation is only ever found, changed or
58
+ listed through them, never by its id alone, so one person can't open another's. If the action table's owner columns
59
+ differ, pass `actionOwner` too. With `list`, the panel shows a Recent list in an empty conversation.
60
+
61
+ **Searching earlier conversations** (off by default). Each helper also has `earlier`, which the spread passes on: this
62
+ person's newest conversations with their transcripts, through the same owner columns. Having it turns nothing on. To let
63
+ the assistant search what a person typed before ("we talked about this last week"), add `searchEarlier`:
64
+
65
+ ```ts
66
+ export const { POST, GET } = cognoloRoute({ ...store, open, model, env: "dev", searchEarlier: (s) => !s.viewingAs });
67
+ ```
68
+
69
+ Return false for any scope that isn't the person themselves (a "view as" session). With Cognolo's cloud, the owner's
70
+ switch must be on too. The search runs in your app, on your database: matching is done in code over the newest 50
71
+ conversations of the last 90 days, so it needs no index or migration. It returns only the person's own typed lines that
72
+ the assistant was actually sent (never a message the conversation filter stopped), at most 5 short snippets, and after a
73
+ search in a request nothing but a look-up runs without a person.
74
+
75
+ If `owner` gives no columns, or a column without a real value (missing, empty, or not a string or number; say the scope
76
+ has no `userId` yet), every call throws rather than matching everyone's conversations. An owner column can't be one the
77
+ store writes itself (`id`, `title`, `state` and so on). All three helpers check this. `prismaStore` needs Prisma 5 or
78
+ later: its updates are held to the owner columns as well as the id. On MySQL, give `state` and `transcript` the
79
+ `@db.LongText` attribute and `input` and `summary` `@db.Text`, as Prisma's `String` is too short there. `@db.Text` holds
80
+ only 64 KB: a long conversation, or one with pictures (up to 10 of 300 KB when you turn them on), needs `LongText`.
81
+
82
+ **Before you turn pictures on**, check that your database takes a conversation of about 3 MB in one write: every message
83
+ rewrites the `state` column, and every page load reads it. On MySQL, `max_allowed_packet` must be above 4 MB (5.7's
84
+ default is 4 MB; 8.0's is 64 MB), or a save can fail after the AI was paid for. A database that limits one value to 2 MB
85
+ (Cloudflare D1, for example) fits about 6 pictures: leave pictures off there. An app still on the old `@db.Text` advice
86
+ fails on the first picture.
87
+
88
+ **Older databases.** Some databases can't store every character: MySQL's `utf8` (not `utf8mb4`) refuses emoji, and a
89
+ Postgres made with a Windows or Latin encoding refuses emoji and most scripts. People type both, so all three helpers
90
+ handle it without any change to your database:
91
+
92
+ - `state`, `transcript` and the log's `input` are always written as plain ASCII JSON (an emoji is stored as `🌊`),
93
+ which every database accepts and which reads back exactly. Rows saved before this still load.
94
+ - Titles and the log's `title` and `summary` are written as they are, so your own pages can show them. If the database
95
+ refuses a character, the save is rolled back and written again with those fields as a quoted ASCII string; the panel's
96
+ Recent list reads that back exactly, and your server log says once that it happened. Without a transaction (`sqlStore`
97
+ with no `transaction`, `drizzleStore` with `transactions: false`) they go in that form from the start, since a second
98
+ try could repeat a log line.
99
+
100
+ A UTF-8 database (`utf8mb4` on MySQL) keeps everything as written.
101
+
102
+ # Plain SQL (`sqlStore`)
103
+
104
+ For an app without Prisma or Drizzle. Make the two tables, then give the helper a function that runs one statement with
105
+ its parameters. Values always travel as parameters; table and column names must be plain names (letters, digits,
106
+ underscores) and are refused otherwise.
107
+
108
+ ```sql
109
+ -- Postgres. For MySQL use VARCHAR(64) for the ids and owner columns, LONGTEXT for state and transcript,
110
+ -- and DATETIME for the times. For SQLite use TEXT throughout and INTEGER for ok.
111
+ CREATE TABLE cognolo_conversations (
112
+ id TEXT PRIMARY KEY,
113
+ user_id TEXT NOT NULL,
114
+ title TEXT NOT NULL DEFAULT 'New conversation',
115
+ state TEXT NOT NULL,
116
+ transcript TEXT NOT NULL DEFAULT '[]',
117
+ created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
118
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
119
+ );
120
+ CREATE INDEX cognolo_conversations_owner ON cognolo_conversations (user_id, updated_at);
121
+
122
+ CREATE TABLE cognolo_actions (
123
+ id TEXT PRIMARY KEY,
124
+ conversation_id TEXT NOT NULL REFERENCES cognolo_conversations(id) ON DELETE CASCADE,
125
+ user_id TEXT NOT NULL,
126
+ tool TEXT NOT NULL,
127
+ title TEXT NOT NULL,
128
+ risk TEXT NOT NULL,
129
+ input TEXT NOT NULL,
130
+ status TEXT NOT NULL,
131
+ ok BOOLEAN NOT NULL DEFAULT TRUE,
132
+ summary TEXT NOT NULL,
133
+ created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
134
+ );
135
+ ```
136
+
137
+ ```ts
138
+ import { cognoloRoute, sqlStore } from "@cognolo/runtime";
139
+ import { pool } from "./db"; // a pg Pool
140
+
141
+ const store = sqlStore<{ userId: string }>({
142
+ query: (sql, params) => pool.query(sql, params).then((r) => r.rows),
143
+ // So a save and its action log land together. Without it they are written one after the other.
144
+ transaction: async (fn) => {
145
+ const client = await pool.connect();
146
+ try {
147
+ await client.query("BEGIN");
148
+ const out = await fn((sql, params) => client.query(sql, params).then((r) => r.rows));
149
+ await client.query("COMMIT");
150
+ return out;
151
+ } catch (e) {
152
+ await client.query("ROLLBACK").catch(() => {}); // keep the first error
153
+ throw e;
154
+ } finally {
155
+ client.release();
156
+ }
157
+ },
158
+ owner: (s) => ({ user_id: s.userId }),
159
+ });
160
+ ```
161
+
162
+ Set `dialect: "mysql"` or `"sqlite"` for those databases (placeholders become `?`), and `conversations` / `actions` if
163
+ your tables have other names (`actions: false` keeps no log).
164
+
165
+ # Drizzle (`drizzleStore`)
166
+
167
+ Add the two tables to your schema and run `drizzle-kit generate` then `migrate`. This is the Postgres version; for MySQL
168
+ or SQLite use that dialect's table and column builders with the same property names.
169
+
170
+ ```ts
171
+ import { boolean, pgTable, text, timestamp, index } from "drizzle-orm/pg-core";
172
+
173
+ export const cognoloConversations = pgTable("cognolo_conversations", {
174
+ id: text("id").primaryKey(),
175
+ userId: text("user_id").notNull(),
176
+ title: text("title").notNull().default("New conversation"),
177
+ state: text("state").notNull(),
178
+ transcript: text("transcript").notNull().default("[]"),
179
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
180
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
181
+ }, (t) => [index("cognolo_conversations_owner").on(t.userId, t.updatedAt)]);
182
+
183
+ export const cognoloActions = pgTable("cognolo_actions", {
184
+ id: text("id").primaryKey(),
185
+ conversationId: text("conversation_id").notNull().references(() => cognoloConversations.id, { onDelete: "cascade" }),
186
+ userId: text("user_id").notNull(),
187
+ tool: text("tool").notNull(),
188
+ title: text("title").notNull(),
189
+ risk: text("risk").notNull(),
190
+ input: text("input").notNull(),
191
+ status: text("status").notNull(),
192
+ ok: boolean("ok").notNull().default(true),
193
+ summary: text("summary").notNull(),
194
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
195
+ });
196
+ ```
197
+
198
+ ```ts
199
+ import { and, desc, eq } from "drizzle-orm";
200
+ import { cognoloRoute, drizzleStore } from "@cognolo/runtime";
201
+
202
+ const store = drizzleStore<{ userId: string }>({
203
+ db,
204
+ conversations: cognoloConversations,
205
+ actions: cognoloActions,
206
+ ops: { eq, and, desc },
207
+ owner: (s) => ({ userId: s.userId }),
208
+ });
209
+ ```
210
+
211
+ A save and its action log go in one transaction. For a driver without transactions (Neon over HTTP, Cloudflare D1),
212
+ set `transactions: false`; the owner check stays in every statement. Remember to add the schema file to
213
+ `drizzle.config`'s `schema` setting.
214
+
215
+ `owner` names the table's properties (here `userId`), not the database columns. An owner key the table doesn't have is
216
+ refused, so a typo can't quietly match every row.
217
+
218
+ # Passkeys for approving changes that can't be undone (runtime 0.3.0)
219
+
220
+ A change that can't be undone (and any the owner ticks in Cognolo) is approved with the person's passkey: their
221
+ fingerprint, face or device PIN, tied to exactly what they approved. Passkeys and the marks of approvals already used
222
+ live in one more table in your database, next to the conversations. Until it is set up, approving stays a click, and the
223
+ owner's Safety check says so.
224
+
225
+ **Prisma**
226
+
227
+ ```prisma
228
+ model CognoloPasskey {
229
+ id String @id
230
+ kind String
231
+ userId String
232
+ credentialId String?
233
+ publicKey String?
234
+ alg Int?
235
+ info String?
236
+ createdAt String
237
+
238
+ @@index([userId, kind])
239
+ }
240
+ ```
241
+
242
+ Then `npx prisma migrate dev --name cognolo-passkeys`, and `passkeys: db.cognoloPasskey` in `prismaStore`.
243
+
244
+ **Plain SQL** (Postgres; adjust the types for MySQL or SQLite)
245
+
246
+ ```sql
247
+ CREATE TABLE IF NOT EXISTS cognolo_passkeys (
248
+ id TEXT PRIMARY KEY, kind TEXT NOT NULL, user_id TEXT NOT NULL,
249
+ credential_id TEXT, public_key TEXT, alg INTEGER, info TEXT, created_at TEXT NOT NULL
250
+ );
251
+ CREATE INDEX IF NOT EXISTS cognolo_passkeys_owner ON cognolo_passkeys (user_id, kind);
252
+ ```
253
+
254
+ Then `passkeys: "cognolo_passkeys"` in `sqlStore`.
255
+
256
+ **Drizzle:** `cognoloPasskeys` in `lib/cognolo/schema-passkeys.ts` (what `npx cognolo init` writes), included in
257
+ drizzle.config, then `passkeys: cognoloPasskeys` in `drizzleStore`.
258
+
259
+ The owner columns are the same as the conversations'. `created_at` is text, set by the runtime. Each row is written once
260
+ and never inside a transaction, so an approval's mark is in the database before the change runs, and the same approval
261
+ sent twice, even to two servers, runs once.
262
+
263
+ Set `COGNOLO_ORIGINS` to every address people open the app at (comma-separated); passkeys are checked against those and
264
+ work only on the address they were set up on. Optionally pass `passkey: { freshSignIn }` to `cognoloRoute`, returning
265
+ true when the person signed in again just now; it is asked before every passkey is set up.
266
+
267
+ # Calls from people's own AI (runtime 0.4.0, Prisma only for now)
268
+
269
+ People's own AI (an agent in the person's browser) can call the reads the owner ticks, through the app's gate. Those
270
+ calls belong to no conversation, so they go in their own table when you keep one; otherwise they are in Cognolo's record
271
+ only. Optional.
272
+
273
+ ```prisma
274
+ model CognoloOutsideAction {
275
+ id String @id @default(cuid())
276
+ userId String
277
+ via String
278
+ tool String
279
+ title String
280
+ risk String
281
+ input String
282
+ status String
283
+ ok Boolean @default(true)
284
+ summary String
285
+ createdAt DateTime @default(now())
286
+
287
+ @@index([userId, createdAt])
288
+ }
289
+ ```
290
+
291
+ A tool's title and description go to people's own AI as they are (capped), so keep them to fixed words you would show
292
+ any outside agent: nothing built from records or settings at run time.
293
+
294
+ Then `npx prisma migrate dev --name cognolo-outside-actions`, and `outsideActions: db.cognoloOutsideAction` in
295
+ `prismaStore`. The owner columns are the action log's (`actionOwner`, else `owner`). `status` is `ran` or `denied`; a
296
+ refusal is written once per person, kind and window, so an agent calling in a loop can't fill the table.
297
+
298
+ ## Sharing the limits across servers
299
+
300
+ The limits on people's own AI (calls, records, and the pause for the whole environment) are counted in each server's
301
+ memory unless you give them a place every server sees. With more than one server, or before Production, add two tables
302
+ (Postgres or MySQL):
303
+
304
+ ```prisma
305
+ model CognoloOutsideCount {
306
+ key String @id
307
+ n Int @default(0)
308
+ value String?
309
+ until DateTime
310
+
311
+ @@index([until])
312
+ }
313
+
314
+ model CognoloOutsideSeen {
315
+ set String
316
+ id String
317
+ until DateTime
318
+
319
+ @@id([set, id])
320
+ @@index([until])
321
+ }
322
+ ```
323
+
324
+ Then `outsideCounts: { counts: db.cognoloOutsideCount, seen: db.cognoloOutsideSeen }` in `prismaStore`. Record ids are
325
+ stored hashed; rows are cleared once they no longer matter (a day or two at most). Records are counted one result at a
326
+ time on each server; two servers acting at the same moment can each let one result through past a limit, nothing more.
327
+ Keys carry the environment, so two apps sharing one database need different environment names. On MySQL two first calls
328
+ in the same minute can fail (the call is refused, never let through); Postgres has no such gap. The fuse's state is
329
+ changed only by a conditional write (one `UPDATE ... WHERE` on its old value), so a trip and the owner's acknowledgement
330
+ on two servers can't overwrite each other. SQLite isn't supported.
package/package.json ADDED
@@ -0,0 +1,71 @@
1
+ {
2
+ "name": "@cognolo/runtime",
3
+ "version": "0.4.2",
4
+ "description": "Cognolo's runtime: an AI assistant inside your own web app that acts through your app's own functions and permission checks, with a person approving changes.",
5
+ "type": "module",
6
+ "license": "SEE LICENSE IN LICENSE",
7
+ "publishConfig": {
8
+ "access": "public"
9
+ },
10
+ "main": "./dist/index.js",
11
+ "types": "./dist/index.d.ts",
12
+ "bin": {
13
+ "cognolo": "dist/init-cli.js"
14
+ },
15
+ "exports": {
16
+ ".": {
17
+ "types": "./dist/index.d.ts",
18
+ "default": "./dist/index.js"
19
+ },
20
+ "./react": {
21
+ "types": "./dist/react/index.d.ts",
22
+ "default": "./dist/react/index.js"
23
+ },
24
+ "./setup": {
25
+ "types": "./dist/setup.d.ts",
26
+ "default": "./dist/setup.js"
27
+ }
28
+ },
29
+ "files": [
30
+ "dist",
31
+ "docs/store.md"
32
+ ],
33
+ "sideEffects": false,
34
+ "engines": {
35
+ "node": ">=20"
36
+ },
37
+ "scripts": {
38
+ "build": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\" && tsc -p tsconfig.build.json --removeComments && tsc -p tsconfig.build.json --emitDeclarationOnly",
39
+ "prepare": "npm run build",
40
+ "prepack": "npm run build",
41
+ "smoke": "node scripts/smoke.mjs",
42
+ "test": "tsx --import ./test/env.ts --test test/*.test.ts",
43
+ "eval": "tsx eval/run.ts",
44
+ "read": "tsx reader/cli.ts",
45
+ "answer": "tsx scripts/answer.ts",
46
+ "propose": "tsx reader/propose-cli.ts",
47
+ "github-app": "tsx github/serve.ts",
48
+ "typecheck": "tsc --noEmit"
49
+ },
50
+ "peerDependencies": {
51
+ "@anthropic-ai/sdk": "^1.6.0",
52
+ "zod": "^4.6.7",
53
+ "react": "^18.2.0 || ^19.0.0"
54
+ },
55
+ "devDependencies": {
56
+ "@anthropic-ai/sdk": "^1.6.0",
57
+ "@types/node": "^20",
58
+ "@types/react": "^19.3.0",
59
+ "@types/react-dom": "^19.3.0",
60
+ "react": "^19.3.1",
61
+ "react-dom": "^19.3.1",
62
+ "tsx": "^4.23.15",
63
+ "typescript": "^5",
64
+ "zod": "^4.6.7"
65
+ },
66
+ "peerDependenciesMeta": {
67
+ "react": {
68
+ "optional": true
69
+ }
70
+ }
71
+ }