@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.
- package/LICENSE +9 -0
- package/README.md +56 -0
- package/dist/agent.d.ts +290 -0
- package/dist/agent.js +245 -0
- package/dist/bundle.d.ts +192 -0
- package/dist/bundle.js +133 -0
- package/dist/cloud.d.ts +301 -0
- package/dist/cloud.js +383 -0
- package/dist/compact.d.ts +58 -0
- package/dist/compact.js +138 -0
- package/dist/context.d.ts +169 -0
- package/dist/context.js +144 -0
- package/dist/gate.d.ts +106 -0
- package/dist/gate.js +82 -0
- package/dist/guard.d.ts +15 -0
- package/dist/guard.js +26 -0
- package/dist/help.d.ts +44 -0
- package/dist/help.js +79 -0
- package/dist/index.d.ts +25 -0
- package/dist/index.js +25 -0
- package/dist/init-cli.d.ts +40 -0
- package/dist/init-cli.js +317 -0
- package/dist/links.d.ts +39 -0
- package/dist/links.js +89 -0
- package/dist/look.d.ts +462 -0
- package/dist/look.js +362 -0
- package/dist/models.d.ts +79 -0
- package/dist/models.js +145 -0
- package/dist/outside.d.ts +102 -0
- package/dist/outside.js +204 -0
- package/dist/page.d.ts +59 -0
- package/dist/page.js +158 -0
- package/dist/passkey-browser.d.ts +40 -0
- package/dist/passkey-browser.js +48 -0
- package/dist/passkey.d.ts +64 -0
- package/dist/passkey.js +130 -0
- package/dist/pictures.d.ts +23 -0
- package/dist/pictures.js +58 -0
- package/dist/propose.d.ts +36 -0
- package/dist/propose.js +178 -0
- package/dist/rate.d.ts +97 -0
- package/dist/rate.js +147 -0
- package/dist/react/index.d.ts +7 -0
- package/dist/react/index.js +7 -0
- package/dist/react/labels.d.ts +167 -0
- package/dist/react/labels.js +114 -0
- package/dist/react/logic.d.ts +77 -0
- package/dist/react/logic.js +140 -0
- package/dist/react/page-view.d.ts +3 -0
- package/dist/react/page-view.js +308 -0
- package/dist/react/panel.d.ts +179 -0
- package/dist/react/panel.js +749 -0
- package/dist/react/use-chat.d.ts +96 -0
- package/dist/react/use-chat.js +252 -0
- package/dist/research.d.ts +109 -0
- package/dist/research.js +207 -0
- package/dist/route.d.ts +405 -0
- package/dist/route.js +1493 -0
- package/dist/search.d.ts +70 -0
- package/dist/search.js +112 -0
- package/dist/sensitive.d.ts +54 -0
- package/dist/sensitive.js +209 -0
- package/dist/setup.d.ts +93 -0
- package/dist/setup.js +658 -0
- package/dist/store-sql.d.ts +52 -0
- package/dist/store-sql.js +150 -0
- package/dist/store.d.ts +166 -0
- package/dist/store.js +201 -0
- package/dist/text.d.ts +9 -0
- package/dist/text.js +21 -0
- package/dist/tool.d.ts +66 -0
- package/dist/tool.js +36 -0
- package/dist/trust.d.ts +13 -0
- package/dist/trust.js +18 -0
- package/dist/version.d.ts +40 -0
- package/dist/version.js +133 -0
- package/dist/webmcp-browser.d.ts +20 -0
- package/dist/webmcp-browser.js +61 -0
- package/dist/workflow.d.ts +253 -0
- package/dist/workflow.js +310 -0
- package/docs/store.md +330 -0
- package/package.json +71 -0
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { type ConversationStore } from "./store.js";
|
|
2
|
+
/** Runs one SQL statement with its parameters and gives back the rows (none for an insert or update). */
|
|
3
|
+
export type SqlQuery = (sql: string, params: unknown[]) => Promise<Record<string, unknown>[]>;
|
|
4
|
+
/**
|
|
5
|
+
* Conversations in two plain SQL tables (copy them from `docs/store.md`), for an app with no Prisma or Drizzle. `query` runs
|
|
6
|
+
* one statement with parameters, never with values pasted into the text: with `pg`,
|
|
7
|
+
* `(sql, p) => pool.query(sql, p).then((r) => r.rows)`. Give `transaction` too, so a save and its action log land together
|
|
8
|
+
* (with `pg`, run the function on one client between BEGIN and COMMIT); without it they are written one after the other.
|
|
9
|
+
* Table and owner column names must be plain names (letters, digits, underscores). `owner` gives the owner columns as the
|
|
10
|
+
* table names them (`{ user_id: s.userId }`).
|
|
11
|
+
*/
|
|
12
|
+
export declare function sqlStore<S>(o: {
|
|
13
|
+
query: SqlQuery;
|
|
14
|
+
transaction?: <T>(fn: (query: SqlQuery) => Promise<T>) => Promise<T>;
|
|
15
|
+
/** Placeholders and quoting: `postgres` ($1, "name"), `mysql` (?, `name`) or `sqlite` (?, "name"). Default `postgres`. */
|
|
16
|
+
dialect?: "postgres" | "mysql" | "sqlite";
|
|
17
|
+
/** Default `cognolo_conversations`. */
|
|
18
|
+
conversations?: string;
|
|
19
|
+
/** Default `cognolo_actions`; `false` keeps no log. */
|
|
20
|
+
actions?: string | false;
|
|
21
|
+
owner(scope: S): Record<string, unknown>;
|
|
22
|
+
actionOwner?(scope: S): Record<string, unknown>;
|
|
23
|
+
/** How many the Recent list shows (default 30, at most 200). */
|
|
24
|
+
recent?: number;
|
|
25
|
+
/** The passkey table (`cognolo_passkeys` in `docs/store.md`), once it exists. Left out: changes that need a passkey are click-only, and the owner is told. */
|
|
26
|
+
passkeys?: string;
|
|
27
|
+
}): ConversationStore<S>;
|
|
28
|
+
/**
|
|
29
|
+
* Conversations in two Drizzle tables (copy them from `docs/store.md`). Pass your `db`, the two tables, and Drizzle's own
|
|
30
|
+
* `eq`, `and` and `desc` (so Cognolo doesn't depend on Drizzle). `owner` gives the owner columns as the table's properties
|
|
31
|
+
* name them (`{ userId: s.userId }`). A save and its action log are written in one transaction (see `transactions`).
|
|
32
|
+
*/
|
|
33
|
+
export declare function drizzleStore<S>(o: {
|
|
34
|
+
db: any;
|
|
35
|
+
conversations: any;
|
|
36
|
+
actions?: any;
|
|
37
|
+
ops: {
|
|
38
|
+
eq: (col: any, v: unknown) => any;
|
|
39
|
+
and: (...c: any[]) => any;
|
|
40
|
+
desc: (col: any) => any;
|
|
41
|
+
};
|
|
42
|
+
owner(scope: S): Record<string, unknown>;
|
|
43
|
+
actionOwner?(scope: S): Record<string, unknown>;
|
|
44
|
+
recent?: number;
|
|
45
|
+
/**
|
|
46
|
+
* `false` for a driver without transactions (Neon over HTTP, Cloudflare D1): a save and its log are then written one after
|
|
47
|
+
* the other. The owner check stays in every statement either way. Default `true`.
|
|
48
|
+
*/
|
|
49
|
+
transactions?: boolean;
|
|
50
|
+
/** The passkey table (`cognoloPasskeys` in `docs/store.md`), once it exists. Left out: changes that need a passkey are click-only. */
|
|
51
|
+
passkeys?: any;
|
|
52
|
+
}): ConversationStore<S>;
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { decode, encode, logRow, ownerCols, parse, passkeyData, passkeyOf, putOnce, shown, storedText, when, withSafeText } from "./store.js";
|
|
3
|
+
const PLAIN = /^[A-Za-z_][A-Za-z0-9_]{0,62}$/;
|
|
4
|
+
const cap = (n) => Math.max(1, Math.min(Math.floor(n ?? 30), 200));
|
|
5
|
+
export function sqlStore(o) {
|
|
6
|
+
const dialect = o.dialect ?? "postgres";
|
|
7
|
+
const q = (name) => {
|
|
8
|
+
if (!PLAIN.test(name))
|
|
9
|
+
throw new Error(`"${name}" isn't a plain table or column name.`);
|
|
10
|
+
return dialect === "mysql" ? "`" + name + "`" : `"${name}"`;
|
|
11
|
+
};
|
|
12
|
+
const conv = q(o.conversations ?? "cognolo_conversations");
|
|
13
|
+
const acts = o.actions === false ? null : q(o.actions ?? "cognolo_actions");
|
|
14
|
+
const pk = o.passkeys ? q(o.passkeys) : null;
|
|
15
|
+
const p = (n) => (dialect === "postgres" ? `$${n}` : "?");
|
|
16
|
+
const matching = (cols, from) => Object.keys(cols).map((k, i) => `${q(k)} = ${p(from + i)}`).join(" AND ");
|
|
17
|
+
const insert = (table, row) => `INSERT INTO ${table} (${Object.keys(row).map(q).join(", ")}) VALUES (${Object.keys(row).map((_, i) => p(i + 1)).join(", ")})`;
|
|
18
|
+
const bindable = (v) => (typeof v === "boolean" && dialect === "sqlite" ? (v ? 1 : 0) : v);
|
|
19
|
+
const inTx = (fn) => (o.transaction ? o.transaction(fn) : fn(o.query));
|
|
20
|
+
const writeLog = async (query, scope, id, audit, safe) => {
|
|
21
|
+
if (!acts)
|
|
22
|
+
return;
|
|
23
|
+
for (const a of audit) {
|
|
24
|
+
const row = { id: randomUUID(), conversation_id: id, ...ownerCols(o.actionOwner ?? o.owner, scope), ...logRow(a, safe) };
|
|
25
|
+
await query(insert(acts, row), Object.values(row).map(bindable));
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
return {
|
|
29
|
+
async load(scope, id) {
|
|
30
|
+
const own = ownerCols(o.owner, scope);
|
|
31
|
+
const rows = await o.query(`SELECT id, title, state, transcript FROM ${conv} WHERE id = ${p(1)} AND ${matching(own, 2)}`, [id, ...Object.values(own)]);
|
|
32
|
+
return rows[0] ? decode(rows[0]) : null;
|
|
33
|
+
},
|
|
34
|
+
async save(scope, c, audit) {
|
|
35
|
+
const own = ownerCols(o.owner, scope);
|
|
36
|
+
const d = encode(c);
|
|
37
|
+
if (c.id) {
|
|
38
|
+
const id = c.id;
|
|
39
|
+
await withSafeText((safe) => inTx(async (query) => {
|
|
40
|
+
const mine = await query(`SELECT id FROM ${conv} WHERE id = ${p(1)} AND ${matching(own, 2)}`, [id, ...Object.values(own)]);
|
|
41
|
+
if (!mine.length)
|
|
42
|
+
throw new Error("No such conversation for this person.");
|
|
43
|
+
await query(`UPDATE ${conv} SET state = ${p(1)}, transcript = ${p(2)}, updated_at = CURRENT_TIMESTAMP WHERE id = ${p(3)} AND ${matching(own, 4)}`, [d.state, d.transcript, id, ...Object.values(own)]);
|
|
44
|
+
await writeLog(query, scope, id, audit, safe);
|
|
45
|
+
}), !!o.transaction);
|
|
46
|
+
return id;
|
|
47
|
+
}
|
|
48
|
+
const id = randomUUID();
|
|
49
|
+
await withSafeText((safe) => inTx(async (query) => {
|
|
50
|
+
const row = { id, ...own, title: storedText(c.title, safe), ...d };
|
|
51
|
+
await query(insert(conv, row), Object.values(row));
|
|
52
|
+
await writeLog(query, scope, id, audit, safe);
|
|
53
|
+
}), !!o.transaction);
|
|
54
|
+
return id;
|
|
55
|
+
},
|
|
56
|
+
async list(scope) {
|
|
57
|
+
const own = ownerCols(o.owner, scope);
|
|
58
|
+
const rows = await o.query(`SELECT id, title, updated_at FROM ${conv} WHERE ${matching(own, 1)} ORDER BY updated_at DESC LIMIT ${cap(o.recent)}`, Object.values(own));
|
|
59
|
+
return rows.map((r) => ({ id: String(r.id), title: shown(r.title), at: when(r.updated_at) }));
|
|
60
|
+
},
|
|
61
|
+
async earlier(scope, limit) {
|
|
62
|
+
const own = ownerCols(o.owner, scope);
|
|
63
|
+
const rows = await o.query(`SELECT id, title, transcript, updated_at FROM ${conv} WHERE ${matching(own, 1)} ORDER BY updated_at DESC LIMIT ${cap(limit)}`, Object.values(own));
|
|
64
|
+
return rows.map((r) => ({ id: String(r.id), title: shown(r.title), at: when(r.updated_at), transcript: parse(r.transcript, []) }));
|
|
65
|
+
},
|
|
66
|
+
...(pk ? {
|
|
67
|
+
passkeys: {
|
|
68
|
+
keys: async (scope) => {
|
|
69
|
+
const own = ownerCols(o.owner, scope);
|
|
70
|
+
const rows = await o.query(`SELECT id, credential_id, public_key, alg, info, created_at FROM ${pk} WHERE kind = ${p(1)} AND ${matching(own, 2)}`, ["key", ...Object.values(own)]);
|
|
71
|
+
return rows.map((r) => passkeyOf({ id: r.id, credentialId: r.credential_id, publicKey: r.public_key, alg: r.alg, info: r.info, createdAt: r.created_at })).filter((k) => !!k);
|
|
72
|
+
},
|
|
73
|
+
put: (scope, row) => { const r = { ...passkeyData(row, true), ...ownerCols(o.owner, scope) }; return putOnce(() => o.query(insert(pk, r), Object.values(r))); },
|
|
74
|
+
},
|
|
75
|
+
} : {}),
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
export function drizzleStore(o) {
|
|
79
|
+
const { eq, and, desc } = o.ops;
|
|
80
|
+
const pk = o.passkeys;
|
|
81
|
+
const inTx = (fn) => (o.transactions === false ? fn(o.db) : o.db.transaction(fn));
|
|
82
|
+
const t = o.conversations;
|
|
83
|
+
const col = (table, k) => {
|
|
84
|
+
if (!Object.prototype.hasOwnProperty.call(table, k) || !table[k] || typeof table[k] !== "object")
|
|
85
|
+
throw new Error(`The table has no column "${k}" for the owner.`);
|
|
86
|
+
return table[k];
|
|
87
|
+
};
|
|
88
|
+
const mine = (own, ...extra) => and(...extra, ...Object.entries(own).map(([k, v]) => eq(col(t, k), v)));
|
|
89
|
+
const writeLog = async (tx, scope, id, audit, safe) => {
|
|
90
|
+
if (!o.actions || !audit.length)
|
|
91
|
+
return;
|
|
92
|
+
const who = ownerCols(o.actionOwner ?? o.owner, scope);
|
|
93
|
+
for (const k of Object.keys(who))
|
|
94
|
+
col(o.actions, k);
|
|
95
|
+
await tx.insert(o.actions).values(audit.map((a) => ({ id: randomUUID(), conversationId: id, ...who, ...logRow(a, safe) })));
|
|
96
|
+
};
|
|
97
|
+
const retry = o.transactions !== false;
|
|
98
|
+
return {
|
|
99
|
+
async load(scope, id) {
|
|
100
|
+
const rows = await o.db.select({ id: t.id, title: t.title, state: t.state, transcript: t.transcript }).from(t).where(mine(ownerCols(o.owner, scope), eq(t.id, id))).limit(1);
|
|
101
|
+
return rows[0] ? decode(rows[0]) : null;
|
|
102
|
+
},
|
|
103
|
+
async save(scope, c, audit) {
|
|
104
|
+
const own = ownerCols(o.owner, scope);
|
|
105
|
+
const d = encode(c);
|
|
106
|
+
if (c.id) {
|
|
107
|
+
const id = c.id;
|
|
108
|
+
await withSafeText((safe) => inTx(async (tx) => {
|
|
109
|
+
const found = await tx.select({ id: t.id }).from(t).where(mine(own, eq(t.id, id))).limit(1);
|
|
110
|
+
if (!found.length)
|
|
111
|
+
throw new Error("No such conversation for this person.");
|
|
112
|
+
await tx.update(t).set({ ...d, updatedAt: new Date() }).where(mine(own, eq(t.id, id)));
|
|
113
|
+
await writeLog(tx, scope, id, audit, safe);
|
|
114
|
+
}), retry);
|
|
115
|
+
return id;
|
|
116
|
+
}
|
|
117
|
+
for (const k of Object.keys(own))
|
|
118
|
+
col(t, k);
|
|
119
|
+
const id = randomUUID();
|
|
120
|
+
await withSafeText((safe) => inTx(async (tx) => {
|
|
121
|
+
await tx.insert(t).values({ id, ...own, title: storedText(c.title, safe), ...d });
|
|
122
|
+
await writeLog(tx, scope, id, audit, safe);
|
|
123
|
+
}), retry);
|
|
124
|
+
return id;
|
|
125
|
+
},
|
|
126
|
+
async list(scope) {
|
|
127
|
+
const rows = await o.db.select({ id: t.id, title: t.title, updatedAt: t.updatedAt }).from(t).where(mine(ownerCols(o.owner, scope))).orderBy(desc(t.updatedAt)).limit(cap(o.recent));
|
|
128
|
+
return rows.map((r) => ({ id: String(r.id), title: shown(r.title), at: when(r.updatedAt) }));
|
|
129
|
+
},
|
|
130
|
+
async earlier(scope, limit) {
|
|
131
|
+
const rows = await o.db.select({ id: t.id, title: t.title, transcript: t.transcript, updatedAt: t.updatedAt }).from(t).where(mine(ownerCols(o.owner, scope))).orderBy(desc(t.updatedAt)).limit(cap(limit));
|
|
132
|
+
return rows.map((r) => ({ id: String(r.id), title: shown(r.title), at: when(r.updatedAt), transcript: parse(r.transcript, []) }));
|
|
133
|
+
},
|
|
134
|
+
...(pk ? {
|
|
135
|
+
passkeys: {
|
|
136
|
+
keys: async (scope) => {
|
|
137
|
+
const own = ownerCols(o.owner, scope);
|
|
138
|
+
const rows = await o.db.select().from(pk).where(and(eq(pk.kind, "key"), ...Object.entries(own).map(([k, v]) => eq(col(pk, k), v))));
|
|
139
|
+
return rows.map((r) => passkeyOf(r)).filter((k) => !!k);
|
|
140
|
+
},
|
|
141
|
+
put: (scope, row) => {
|
|
142
|
+
const own = ownerCols(o.owner, scope);
|
|
143
|
+
for (const k of Object.keys(own))
|
|
144
|
+
col(pk, k);
|
|
145
|
+
return putOnce(() => o.db.insert(pk).values({ ...passkeyData(row, false), ...own }));
|
|
146
|
+
},
|
|
147
|
+
},
|
|
148
|
+
} : {}),
|
|
149
|
+
};
|
|
150
|
+
}
|
package/dist/store.d.ts
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
import { type AgentState } from "./agent.js";
|
|
2
|
+
import type { AuditRow, SavedConversation, TranscriptEntry } from "./route.js";
|
|
3
|
+
import type { OutsideCounts } from "./outside.js";
|
|
4
|
+
import type { RunInfo } from "./workflow.js";
|
|
5
|
+
import type { EarlierConversation } from "./search.js";
|
|
6
|
+
import type { PasskeyInfo, StoredPasskey } from "./passkey.js";
|
|
7
|
+
/** One saved conversation in the panel's "Recent" list. */
|
|
8
|
+
export interface ConversationSummary {
|
|
9
|
+
id: string;
|
|
10
|
+
title: string;
|
|
11
|
+
at: string;
|
|
12
|
+
}
|
|
13
|
+
/** The three storage functions the route takes. */
|
|
14
|
+
export interface ConversationStore<S> {
|
|
15
|
+
load(scope: S, id: string): Promise<SavedConversation | null>;
|
|
16
|
+
save(scope: S, conv: {
|
|
17
|
+
id?: string;
|
|
18
|
+
title: string;
|
|
19
|
+
state: AgentState;
|
|
20
|
+
transcript: TranscriptEntry[];
|
|
21
|
+
run?: RunInfo;
|
|
22
|
+
}, audit: AuditRow[]): Promise<string>;
|
|
23
|
+
list(scope: S): Promise<ConversationSummary[]>;
|
|
24
|
+
/** This person's newest conversations with their transcripts, for searching what they typed. Owner-checked like `list`. */
|
|
25
|
+
earlier?(scope: S, limit: number): Promise<EarlierConversation[]>;
|
|
26
|
+
/** This person's passkeys, and the marks of approvals already used. Given only when the passkey table is set up. */
|
|
27
|
+
passkeys?: PasskeyStore<S>;
|
|
28
|
+
/** Calls from people's own AI (no conversation), with their `via`. Given only when the host keeps that table. */
|
|
29
|
+
outsideLog?(scope: S, rows: AuditRow[]): Promise<void>;
|
|
30
|
+
/** Where the limits on people's own AI are counted, shared by every server. Given only when the host keeps those tables. */
|
|
31
|
+
outsideCounts?: OutsideCounts;
|
|
32
|
+
}
|
|
33
|
+
/** A row of the passkey table: a passkey (`key`) or the mark of an approval already used (`used`). */
|
|
34
|
+
export type PasskeyRow = {
|
|
35
|
+
id: string;
|
|
36
|
+
kind: "key" | "used";
|
|
37
|
+
createdAt: string;
|
|
38
|
+
credentialId?: string;
|
|
39
|
+
publicKey?: string;
|
|
40
|
+
alg?: number;
|
|
41
|
+
info?: PasskeyInfo;
|
|
42
|
+
};
|
|
43
|
+
/**
|
|
44
|
+
* The passkey table. `keys` gives only this person's passkeys (through the owner columns). `put` writes a row
|
|
45
|
+
* once and gives false when its id is already there; it is never inside a transaction, so a used mark is in the database
|
|
46
|
+
* before the change it guards runs, and the same approval sent twice, even to two servers, runs once.
|
|
47
|
+
*/
|
|
48
|
+
export interface PasskeyStore<S> {
|
|
49
|
+
keys(scope: S): Promise<StoredPasskey[]>;
|
|
50
|
+
put(scope: S, row: PasskeyRow): Promise<boolean>;
|
|
51
|
+
}
|
|
52
|
+
/** The database refused a second row with the same id (Prisma P2002, Postgres 23505, SQLite, MySQL 1062). */
|
|
53
|
+
export declare const uniqueRefused: (e: unknown) => boolean;
|
|
54
|
+
/**
|
|
55
|
+
* The passkey table isn't there yet (Prisma P2021, Postgres 42P01, MySQL 1146, SQLite). Codes are read only from an error's
|
|
56
|
+
* code fields and messages only for the two exact phrases, so a timeout that mentions "1146 ms" is never taken for it: this
|
|
57
|
+
* decides whether approving falls back to a click (Fable's review).
|
|
58
|
+
*/
|
|
59
|
+
export declare const tableMissing: (e: unknown) => boolean;
|
|
60
|
+
/** A stored passkey from its row, or null when the row isn't a whole one. */
|
|
61
|
+
export declare function passkeyOf(r: Record<string, unknown>): StoredPasskey | null;
|
|
62
|
+
/** A passkey row's columns as the store writes them (`created_at` style for SQL, `createdAt` style otherwise). */
|
|
63
|
+
export declare const passkeyData: (row: PasskeyRow, snake: boolean) => Record<string, unknown>;
|
|
64
|
+
/** Inserts once: true when written, false when that id is already there; any other error is thrown. */
|
|
65
|
+
export declare function putOnce(write: () => Promise<unknown>): Promise<boolean>;
|
|
66
|
+
interface ConversationModel {
|
|
67
|
+
findFirst(args: any): Promise<any>;
|
|
68
|
+
findMany(args: any): Promise<any[]>;
|
|
69
|
+
create(args: any): any;
|
|
70
|
+
update(args: any): any;
|
|
71
|
+
}
|
|
72
|
+
interface ActionModel {
|
|
73
|
+
create(args: any): any;
|
|
74
|
+
}
|
|
75
|
+
type Conv = {
|
|
76
|
+
state: AgentState;
|
|
77
|
+
transcript: TranscriptEntry[];
|
|
78
|
+
run?: RunInfo;
|
|
79
|
+
};
|
|
80
|
+
export declare const parse: <T>(s: unknown, fallback: T) => T;
|
|
81
|
+
export declare const asciiJson: (v: unknown) => string;
|
|
82
|
+
/**
|
|
83
|
+
* A title or summary for its column. `safe`: any character a database could refuse makes it a quoted JSON string of plain
|
|
84
|
+
* ASCII. Either way, text starting with a quote is quoted too, so `shown` always reads back exactly what was meant.
|
|
85
|
+
*/
|
|
86
|
+
export declare const storedText: (s: string, safe?: boolean) => string;
|
|
87
|
+
export declare const shown: (v: unknown) => string;
|
|
88
|
+
/** The database refused a character (Postgres 22P05 or 22021, MySQL 1366 "Incorrect string value", or the like). */
|
|
89
|
+
export declare const encodingRefused: (e: unknown) => boolean;
|
|
90
|
+
/**
|
|
91
|
+
* Writes once as is, and again with safe text if the database refused a character. Only for a write that rolls back on
|
|
92
|
+
* failure (a transaction), so the second try can never leave a half-written first one behind.
|
|
93
|
+
*/
|
|
94
|
+
export declare function withSafeText<T>(write: (safe: boolean) => Promise<T>, canRetry: boolean): Promise<T>;
|
|
95
|
+
export declare const encode: (c: Conv) => {
|
|
96
|
+
state: string;
|
|
97
|
+
transcript: string;
|
|
98
|
+
};
|
|
99
|
+
export declare function decode(row: {
|
|
100
|
+
id: string;
|
|
101
|
+
title: string;
|
|
102
|
+
state: unknown;
|
|
103
|
+
transcript: unknown;
|
|
104
|
+
}): SavedConversation;
|
|
105
|
+
export declare const logRow: (a: AuditRow, safe?: boolean) => {
|
|
106
|
+
tool: string;
|
|
107
|
+
title: string;
|
|
108
|
+
risk: string;
|
|
109
|
+
input: string;
|
|
110
|
+
status: "declined" | "ran" | "proposed" | "approved" | "denied" | "noted";
|
|
111
|
+
ok: boolean;
|
|
112
|
+
summary: string;
|
|
113
|
+
};
|
|
114
|
+
export declare const when: (v: unknown) => string;
|
|
115
|
+
/**
|
|
116
|
+
* The owner columns for a scope, refused when they could match more than one person's rows: none at all, or one whose
|
|
117
|
+
* value is missing. (Prisma reads `{ userId: undefined }` as "any user", so a scope without its id would open everyone's.)
|
|
118
|
+
*/
|
|
119
|
+
export declare function ownerOf<S>(owner: (scope: S) => Record<string, unknown>, scope: S): Record<string, unknown>;
|
|
120
|
+
/** Columns the helpers write themselves; an owner column with one of these names would overwrite it. */
|
|
121
|
+
export declare const RESERVED: Set<string>;
|
|
122
|
+
export declare function ownerCols<S>(owner: (scope: S) => Record<string, unknown>, scope: S): Record<string, unknown>;
|
|
123
|
+
/**
|
|
124
|
+
* The limits on people's own AI over two Prisma models, so every server shares them. Rows say until when they matter, and
|
|
125
|
+
* are cleared away at most once a minute per server. Record ids arrive hashed.
|
|
126
|
+
*/
|
|
127
|
+
export declare function prismaCounts(m: {
|
|
128
|
+
counts: any;
|
|
129
|
+
seen: any;
|
|
130
|
+
}, now?: () => number): OutsideCounts;
|
|
131
|
+
/**
|
|
132
|
+
* Conversations in two Prisma models (copy them from `docs/store.md`). `owner` names the columns that say whose a
|
|
133
|
+
* conversation is, from the scope `open` returned (for example `{ organizationId, userEmail }`): a conversation is found,
|
|
134
|
+
* changed and listed only through them, never by its id alone. `actionOwner` does the same for the action log when its
|
|
135
|
+
* columns differ (defaults to `owner`). Leave `actions` out to keep no log.
|
|
136
|
+
*/
|
|
137
|
+
export declare function prismaStore<S>(o: {
|
|
138
|
+
db: {
|
|
139
|
+
$transaction(ops: unknown[]): Promise<unknown>;
|
|
140
|
+
};
|
|
141
|
+
conversations: ConversationModel;
|
|
142
|
+
actions?: ActionModel;
|
|
143
|
+
owner(scope: S): Record<string, unknown>;
|
|
144
|
+
actionOwner?(scope: S): Record<string, unknown>;
|
|
145
|
+
/** How many the Recent list shows (default 30). */
|
|
146
|
+
recent?: number;
|
|
147
|
+
/**
|
|
148
|
+
* Calls from people's own AI, which belong to no conversation (`CognoloOutsideAction` in `docs/store.md`): owner columns
|
|
149
|
+
* as `actionOwner`, the action log's columns and `via`. Left out: they are in the cloud's record only.
|
|
150
|
+
*/
|
|
151
|
+
outsideActions?: ActionModel;
|
|
152
|
+
/**
|
|
153
|
+
* Where the limits on people's own AI are counted, so every server shares them (`CognoloOutsideCount` and
|
|
154
|
+
* `CognoloOutsideSeen` in `docs/store.md`; Postgres or MySQL). Left out: each server counts in its own memory.
|
|
155
|
+
*/
|
|
156
|
+
outsideCounts?: {
|
|
157
|
+
counts: any;
|
|
158
|
+
seen: any;
|
|
159
|
+
};
|
|
160
|
+
/** The passkey model (`CognoloPasskey`), once its migration has run. Left out: changes that need a passkey are click-only, and the owner is told. */
|
|
161
|
+
passkeys?: {
|
|
162
|
+
findMany(args: any): Promise<any[]>;
|
|
163
|
+
create(args: any): Promise<unknown>;
|
|
164
|
+
};
|
|
165
|
+
}): ConversationStore<S>;
|
|
166
|
+
export {};
|
package/dist/store.js
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { emptyState } from "./agent.js";
|
|
3
|
+
const codes = (e) => {
|
|
4
|
+
const x = e;
|
|
5
|
+
return [x?.code, x?.errno, x?.meta?.code, x?.message ?? e, x?.cause && x.cause !== e ? codes(x.cause) : ""].map((v) => String(v ?? "")).join(" ");
|
|
6
|
+
};
|
|
7
|
+
export const uniqueRefused = (e) => /P2002|23505|SQLITE_CONSTRAINT_PRIMARYKEY|SQLITE_CONSTRAINT_UNIQUE|ER_DUP_ENTRY|\b1062\b|duplicate key|UNIQUE constraint failed/i.test(codes(e));
|
|
8
|
+
export const tableMissing = (e) => {
|
|
9
|
+
const x = e;
|
|
10
|
+
if (!x || typeof x !== "object")
|
|
11
|
+
return false;
|
|
12
|
+
const code = [x.code, x.errno, x.meta?.code].map((v) => String(v ?? ""));
|
|
13
|
+
if (code.some((c) => c === "P2021" || c === "42P01" || c === "1146" || c === "ER_NO_SUCH_TABLE"))
|
|
14
|
+
return true;
|
|
15
|
+
if (/^(SQLITE_ERROR: )?no such table: \S+$/i.test(String(x.message ?? "").trim()) || /^relation "[^"]+" does not exist$/i.test(String(x.message ?? "").trim()))
|
|
16
|
+
return true;
|
|
17
|
+
return x.cause && x.cause !== e ? tableMissing(x.cause) : false;
|
|
18
|
+
};
|
|
19
|
+
export function passkeyOf(r) {
|
|
20
|
+
const alg = Number(r.alg);
|
|
21
|
+
const info = parse(r.info, null);
|
|
22
|
+
if (typeof r.credentialId !== "string" || typeof r.publicKey !== "string" || (alg !== -7 && alg !== -257) || !info || typeof info.rpId !== "string")
|
|
23
|
+
return null;
|
|
24
|
+
return { id: String(r.id), credentialId: r.credentialId, publicKey: r.publicKey, alg, createdAt: when(r.createdAt), info };
|
|
25
|
+
}
|
|
26
|
+
export const passkeyData = (row, snake) => {
|
|
27
|
+
const d = { id: row.id, kind: row.kind, credentialId: row.credentialId ?? null, publicKey: row.publicKey ?? null, alg: row.alg ?? null, info: row.info ? asciiJson(row.info) : null, createdAt: row.createdAt };
|
|
28
|
+
return snake ? { id: d.id, kind: d.kind, credential_id: d.credentialId, public_key: d.publicKey, alg: d.alg, info: d.info, created_at: d.createdAt } : d;
|
|
29
|
+
};
|
|
30
|
+
export async function putOnce(write) {
|
|
31
|
+
try {
|
|
32
|
+
await write();
|
|
33
|
+
return true;
|
|
34
|
+
}
|
|
35
|
+
catch (e) {
|
|
36
|
+
if (uniqueRefused(e))
|
|
37
|
+
return false;
|
|
38
|
+
throw e;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
export const parse = (s, fallback) => { try {
|
|
42
|
+
return typeof s === "string" ? JSON.parse(s) : fallback;
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
return fallback;
|
|
46
|
+
} };
|
|
47
|
+
const escapeAll = (s) => s.replace(/[\u007f-]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`);
|
|
48
|
+
export const asciiJson = (v) => escapeAll(JSON.stringify(v));
|
|
49
|
+
export const storedText = (s, safe = false) => (safe && /[^\x20-\x7e]/.test(s) ? escapeAll(JSON.stringify(s)) : s.startsWith('"') ? JSON.stringify(s) : s);
|
|
50
|
+
export const shown = (v) => {
|
|
51
|
+
const t = String(v ?? "");
|
|
52
|
+
if (t.startsWith('"'))
|
|
53
|
+
try {
|
|
54
|
+
const s = JSON.parse(t);
|
|
55
|
+
if (typeof s === "string")
|
|
56
|
+
return s;
|
|
57
|
+
}
|
|
58
|
+
catch { }
|
|
59
|
+
return t;
|
|
60
|
+
};
|
|
61
|
+
export const encodingRefused = (e) => {
|
|
62
|
+
const x = e;
|
|
63
|
+
return /22P05|22021|1366|ER_TRUNCATED_WRONG_VALUE|incorrect string value|has no equivalent in encoding|invalid byte sequence|character set|collation/i
|
|
64
|
+
.test([x?.code, x?.errno, x?.meta?.code, x?.meta?.message, x?.message ?? e].map((v) => String(v ?? "")).join(" "));
|
|
65
|
+
};
|
|
66
|
+
let warned = false;
|
|
67
|
+
export async function withSafeText(write, canRetry) {
|
|
68
|
+
if (!canRetry)
|
|
69
|
+
return write(true);
|
|
70
|
+
try {
|
|
71
|
+
return await write(false);
|
|
72
|
+
}
|
|
73
|
+
catch (e) {
|
|
74
|
+
if (!encodingRefused(e))
|
|
75
|
+
throw e;
|
|
76
|
+
if (!warned) {
|
|
77
|
+
warned = true;
|
|
78
|
+
console.warn("Cognolo: the database refused a character in a conversation title or log line, so it was saved escaped. A UTF-8 database (utf8mb4 on MySQL) stores it as written.");
|
|
79
|
+
}
|
|
80
|
+
return write(true);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
export const encode = (c) => ({ state: asciiJson(c.run ? { ...c.state, run: c.run } : c.state), transcript: asciiJson(c.transcript) });
|
|
84
|
+
export function decode(row) {
|
|
85
|
+
const { run, ...state } = parse(row.state, emptyState());
|
|
86
|
+
return { id: row.id, title: shown(row.title), state: { ...emptyState(), ...state }, transcript: parse(row.transcript, []), ...(run ? { run } : {}) };
|
|
87
|
+
}
|
|
88
|
+
export const logRow = (a, safe = false) => ({ tool: a.tool, title: storedText(a.title, safe), risk: a.risk, input: asciiJson(a.input ?? null), status: a.status, ok: a.ok, summary: storedText(a.summary.slice(0, 1000), safe) });
|
|
89
|
+
export const when = (v) => new Date(typeof v === "string" && /^\d{4}-\d\d-\d\d[ T]\d\d:\d\d(:\d\d(\.\d+)?)?$/.test(v) ? `${v.replace(" ", "T")}Z` : v ?? 0).toISOString();
|
|
90
|
+
export function ownerOf(owner, scope) {
|
|
91
|
+
const o = owner(scope);
|
|
92
|
+
const entries = o && typeof o === "object" ? Object.entries(o) : [];
|
|
93
|
+
const good = (v) => (typeof v === "string" && v.trim() !== "") || (typeof v === "number" && Number.isFinite(v));
|
|
94
|
+
if (!entries.length || !entries.every(([, v]) => good(v)))
|
|
95
|
+
throw new Error("The store's owner must give every owner column a value (a non-empty string or a number), from the scope open returned.");
|
|
96
|
+
return o;
|
|
97
|
+
}
|
|
98
|
+
export const RESERVED = new Set(["id", "title", "state", "transcript", "created_at", "updated_at", "createdAt", "updatedAt", "conversation_id", "conversationId", "tool", "risk", "input", "status", "ok", "summary", "kind", "credential_id", "credentialId", "public_key", "publicKey", "alg", "info"]);
|
|
99
|
+
export function ownerCols(owner, scope) {
|
|
100
|
+
const o = ownerOf(owner, scope);
|
|
101
|
+
for (const k of Object.keys(o))
|
|
102
|
+
if (RESERVED.has(k))
|
|
103
|
+
throw new Error(`"${k}" can't be an owner column: the store writes that column itself.`);
|
|
104
|
+
return o;
|
|
105
|
+
}
|
|
106
|
+
export function prismaCounts(m, now = Date.now) {
|
|
107
|
+
let swept = 0;
|
|
108
|
+
const sweep = () => {
|
|
109
|
+
const t = now();
|
|
110
|
+
if (t - swept < 60_000)
|
|
111
|
+
return;
|
|
112
|
+
swept = t;
|
|
113
|
+
const before = new Date(t);
|
|
114
|
+
void Promise.all([m.counts.deleteMany({ where: { until: { lt: before } } }), m.seen.deleteMany({ where: { until: { lt: before } } })]).catch(() => { });
|
|
115
|
+
};
|
|
116
|
+
return {
|
|
117
|
+
async add(key, by, until) {
|
|
118
|
+
sweep();
|
|
119
|
+
const row = await m.counts.upsert({ where: { key }, create: { key, n: by, until: new Date(until) }, update: { n: { increment: by }, until: new Date(until) }, select: { n: true } });
|
|
120
|
+
return Number(row.n);
|
|
121
|
+
},
|
|
122
|
+
async has(set, ids) {
|
|
123
|
+
if (!ids.length)
|
|
124
|
+
return new Set();
|
|
125
|
+
const rows = (await m.seen.findMany({ where: { set, id: { in: ids } }, select: { id: true } }));
|
|
126
|
+
return new Set(rows.map((r) => r.id));
|
|
127
|
+
},
|
|
128
|
+
async size(set) { return Number(await m.seen.count({ where: { set } })); },
|
|
129
|
+
async put(set, ids, until) { if (ids.length)
|
|
130
|
+
await m.seen.createMany({ data: ids.map((id) => ({ set, id, until: new Date(until) })), skipDuplicates: true }); },
|
|
131
|
+
async clear(set) { await m.seen.deleteMany({ where: { set } }); },
|
|
132
|
+
async read(key) {
|
|
133
|
+
const row = (await m.counts.findUnique({ where: { key }, select: { value: true, until: true } }));
|
|
134
|
+
return row && new Date(row.until).getTime() >= now() ? row.value : null;
|
|
135
|
+
},
|
|
136
|
+
async swap(key, from, to, until) {
|
|
137
|
+
const data = { value: to, until: new Date(until) };
|
|
138
|
+
const old = from === null ? { OR: [{ value: null }, { until: { lt: new Date(now()) } }] } : { value: from, until: { gte: new Date(now()) } };
|
|
139
|
+
if (Number((await m.counts.updateMany({ where: { key, ...old }, data })).count) === 1)
|
|
140
|
+
return true;
|
|
141
|
+
if (from !== null)
|
|
142
|
+
return false;
|
|
143
|
+
try {
|
|
144
|
+
await m.counts.create({ data: { key, n: 0, ...data } });
|
|
145
|
+
return true;
|
|
146
|
+
}
|
|
147
|
+
catch (e) {
|
|
148
|
+
if (e?.code === "P2002")
|
|
149
|
+
return false;
|
|
150
|
+
throw e;
|
|
151
|
+
}
|
|
152
|
+
},
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
export function prismaStore(o) {
|
|
156
|
+
const own = (scope) => ownerCols(o.owner, scope);
|
|
157
|
+
const pk = o.passkeys;
|
|
158
|
+
const log = (scope, id, audit, safe) => (o.actions ? audit.map((a) => o.actions.create({ data: { conversationId: id, ...ownerCols(o.actionOwner ?? o.owner, scope), ...logRow(a, safe) } })) : []);
|
|
159
|
+
const data = encode;
|
|
160
|
+
return {
|
|
161
|
+
async load(scope, id) {
|
|
162
|
+
const row = (await o.conversations.findFirst({ where: { id, ...own(scope) } }));
|
|
163
|
+
return row ? decode(row) : null;
|
|
164
|
+
},
|
|
165
|
+
async save(scope, conv, audit) {
|
|
166
|
+
if (conv.id) {
|
|
167
|
+
if (!(await o.conversations.findFirst({ where: { id: conv.id, ...own(scope) }, select: { id: true } })))
|
|
168
|
+
throw new Error("No such conversation for this person.");
|
|
169
|
+
const id = conv.id;
|
|
170
|
+
await withSafeText((safe) => o.db.$transaction([o.conversations.update({ where: { id, ...own(scope) }, data: data(conv) }), ...log(scope, id, audit, safe)]), true);
|
|
171
|
+
return id;
|
|
172
|
+
}
|
|
173
|
+
const id = randomUUID();
|
|
174
|
+
await withSafeText((safe) => o.db.$transaction([o.conversations.create({ data: { id, ...own(scope), title: storedText(conv.title, safe), ...data(conv) } }), ...log(scope, id, audit, safe)]), true);
|
|
175
|
+
return id;
|
|
176
|
+
},
|
|
177
|
+
async list(scope) {
|
|
178
|
+
const rows = (await o.conversations.findMany({ where: own(scope), orderBy: { updatedAt: "desc" }, take: o.recent ?? 30, select: { id: true, title: true, updatedAt: true } }));
|
|
179
|
+
return rows.map((r) => ({ id: r.id, title: shown(r.title), at: when(r.updatedAt) }));
|
|
180
|
+
},
|
|
181
|
+
async earlier(scope, limit) {
|
|
182
|
+
const rows = (await o.conversations.findMany({ where: own(scope), orderBy: { updatedAt: "desc" }, take: Math.min(limit, 200), select: { id: true, title: true, transcript: true, updatedAt: true } }));
|
|
183
|
+
return rows.map((r) => ({ id: r.id, title: shown(r.title), at: when(r.updatedAt), transcript: parse(r.transcript, []) }));
|
|
184
|
+
},
|
|
185
|
+
...(o.outsideCounts ? { outsideCounts: prismaCounts(o.outsideCounts) } : {}),
|
|
186
|
+
...(o.outsideActions ? {
|
|
187
|
+
async outsideLog(scope, rows) {
|
|
188
|
+
const cols = ownerCols(o.actionOwner ?? o.owner, scope);
|
|
189
|
+
if ("via" in cols)
|
|
190
|
+
throw new Error("An owner column called via would clash with the outside log's own column.");
|
|
191
|
+
await withSafeText((safe) => o.db.$transaction(rows.map((a) => o.outsideActions.create({ data: { ...cols, ...logRow(a, safe), via: a.via ?? "webmcp" } }))), true);
|
|
192
|
+
},
|
|
193
|
+
} : {}),
|
|
194
|
+
...(pk ? {
|
|
195
|
+
passkeys: {
|
|
196
|
+
keys: async (scope) => (await pk.findMany({ where: { kind: "key", ...own(scope) } })).map(passkeyOf).filter((k) => !!k),
|
|
197
|
+
put: (scope, row) => putOnce(() => pk.create({ data: { ...passkeyData(row, false), ...own(scope) } })),
|
|
198
|
+
},
|
|
199
|
+
} : {}),
|
|
200
|
+
};
|
|
201
|
+
}
|
package/dist/text.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Text taken from code, made safe to keep: anything shaped like a key or token is blanked, control characters and
|
|
3
|
+
* runs of space are flattened, and it is cut to a length. It is still only data, never an instruction.
|
|
4
|
+
*/
|
|
5
|
+
export declare function clip(text: string, max?: number): string;
|
|
6
|
+
/** The text with anything shaped like a key or a token blanked, nothing else changed. */
|
|
7
|
+
export declare const redact: (text: string) => string;
|
|
8
|
+
/** Whether the text holds anything shaped like a key or a token. */
|
|
9
|
+
export declare const hasSecret: (text: string) => boolean;
|
package/dist/text.js
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
const INVISIBLE = new RegExp(`[${String.fromCharCode(0)}-${String.fromCharCode(31)}${String.fromCharCode(127)}${String.fromCharCode(0x200b)}-${String.fromCharCode(0x200f)}${String.fromCharCode(0x2028)}-${String.fromCharCode(0x202f)}]+`, "g");
|
|
2
|
+
const SECRETS = [
|
|
3
|
+
/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(-----END [A-Z ]*PRIVATE KEY-----|$)/g,
|
|
4
|
+
/\b(sk|pk|rk)_(live|test)_[A-Za-z0-9]{8,}/g,
|
|
5
|
+
/\bcog_(live|test)_[A-Za-z0-9_-]{8,}/g,
|
|
6
|
+
/\bAKIA[0-9A-Z]{16}\b/g,
|
|
7
|
+
/\bgh[pousr]_[A-Za-z0-9]{20,}/g,
|
|
8
|
+
/\bxox[baprs]-[A-Za-z0-9-]{10,}/g,
|
|
9
|
+
/\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{5,}/g,
|
|
10
|
+
/\b[A-Fa-f0-9]{32,}\b/g,
|
|
11
|
+
/\b[A-Za-z0-9+/_-]{40,}={0,2}/g,
|
|
12
|
+
];
|
|
13
|
+
export function clip(text, max = 220) {
|
|
14
|
+
let t = text;
|
|
15
|
+
for (const r of SECRETS)
|
|
16
|
+
t = t.replace(r, "[redacted]");
|
|
17
|
+
t = t.replace(INVISIBLE, " ").replace(/\s+/g, " ").trim();
|
|
18
|
+
return t.length > max ? `${t.slice(0, max - 1)}…` : t;
|
|
19
|
+
}
|
|
20
|
+
export const redact = (text) => SECRETS.reduce((t, r) => t.replace(r, "[redacted]"), text);
|
|
21
|
+
export const hasSecret = (text) => SECRETS.some((r) => new RegExp(r.source, r.flags.replace("g", "")).test(text));
|