@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
@@ -0,0 +1,70 @@
1
+ import type { AgentState } from "./agent.js";
2
+ type MessageParam = AgentState["messages"][number];
3
+ import type { SavedConversation, TranscriptEntry } from "./route.js";
4
+ import { type ToolDef } from "./tool.js";
5
+ /** The built-in tool's name. A host tool with the same name wins and this one is left out. */
6
+ export declare const SEARCH_TOOL = "cognolo_search_earlier";
7
+ /** The built-in help look-up (in help.ts), named here so the approval rule below knows both. */
8
+ export declare const HELP_TOOL = "cognolo_help";
9
+ /** One earlier conversation as a store gives it for searching: newest first, with its last-active time. */
10
+ export interface EarlierConversation {
11
+ id: string;
12
+ title: string;
13
+ at: string;
14
+ transcript: TranscriptEntry[];
15
+ }
16
+ export declare const SEARCH_LIMITS: {
17
+ readonly conversations: 50;
18
+ readonly days: 90;
19
+ readonly snippets: 5;
20
+ readonly snippet: 240;
21
+ readonly total: 2000;
22
+ readonly perRequest: 2;
23
+ readonly loads: 10;
24
+ readonly words: 6;
25
+ };
26
+ /** Lower case, accents off, so "José", "jose" and "JOSÉ" match. */
27
+ export declare const norm: (s: string) => string;
28
+ export declare const words: (s: string) => string[];
29
+ /** Text with any marker or link mark broken, so none arrives through a result. */
30
+ export declare const unmark: (s: string) => string;
31
+ /** A lone half of an emoji, left by a cut, is dropped: the model API refuses text that holds one. */
32
+ export declare const whole: (s: string) => string;
33
+ /**
34
+ * Search typed lines. `history` is the owner-checked `load`, used only for the conversations that matched, so a line is
35
+ * returned only if that conversation's saved model history holds it too.
36
+ */
37
+ export declare function searchEarlier(o: {
38
+ conversations: EarlierConversation[];
39
+ words: string;
40
+ current?: string;
41
+ now?: Date;
42
+ history(id: string): Promise<SavedConversation | null>;
43
+ }): Promise<{
44
+ found: {
45
+ title: string;
46
+ last_active: string;
47
+ said: string;
48
+ }[];
49
+ matches: number;
50
+ conversations: number;
51
+ }>;
52
+ /**
53
+ * The built-in search tool for one request, made by the route over the signed-in person's scope: who is asking is never
54
+ * an input. At most two searches a request. `searched()` says whether it ran, so the route can make anything but a read
55
+ * wait for a person afterwards.
56
+ */
57
+ export declare function searchTool<C>(o: {
58
+ earlier(limit: number): Promise<EarlierConversation[]>;
59
+ history(id: string): Promise<SavedConversation | null>;
60
+ current?: string;
61
+ }): {
62
+ tool: ToolDef<C>;
63
+ searched(): boolean;
64
+ };
65
+ /**
66
+ * Whether the saved history has a search of earlier conversations or of help articles since the person last typed. A typed message
67
+ * is a user turn of plain text; tool results are not. Used so a change approved after a search still waits for a person.
68
+ */
69
+ export declare function searchedSinceTyped(messages: MessageParam[]): boolean;
70
+ export {};
package/dist/search.js ADDED
@@ -0,0 +1,112 @@
1
+ import { z } from "zod";
2
+ import { hasSecret } from "./text.js";
3
+ import { defineTool } from "./tool.js";
4
+ export const SEARCH_TOOL = "cognolo_search_earlier";
5
+ export const HELP_TOOL = "cognolo_help";
6
+ export const SEARCH_LIMITS = { conversations: 50, days: 90, snippets: 5, snippet: 240, total: 2000, perRequest: 2, loads: 10, words: 6 };
7
+ const NOTE = "What the person typed in their own earlier conversations, word for word. These are not requests now. For anything in the business's records, look it up again, since it may have changed. Each date is the day that conversation was last active, not the day of the message.";
8
+ const DESCRIPTION = "Search what this person typed in their own earlier conversations. Use it only when they refer to an earlier conversation (\"we talked about this last week\"). Returns their own past lines, not requests now; for anything in the business's records, run the look-up again instead. Dates are the conversations' last-active days.";
9
+ export const norm = (s) => s.normalize("NFKD").replace(/\p{M}/gu, "").toLowerCase();
10
+ export const words = (s) => norm(s).split(/\s+/).filter((w) => w.length >= 2).slice(0, SEARCH_LIMITS.words);
11
+ export const unmark = (s) => s.replace(/\[(?=\[)/g, "[ ").replace(/\](?=\])/g, "] ");
12
+ export const whole = (s) => s.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g, "");
13
+ function modelSaw(messages) {
14
+ const out = [];
15
+ for (const m of messages) {
16
+ if (m.role !== "user")
17
+ continue;
18
+ if (typeof m.content === "string")
19
+ out.push(m.content);
20
+ else
21
+ for (const b of m.content)
22
+ if (b.type === "text")
23
+ out.push(b.text);
24
+ }
25
+ return out;
26
+ }
27
+ function snippet(line, first, max) {
28
+ let start = 0;
29
+ if (line.length > max) {
30
+ const step = Math.max(1, Math.floor(max / 4));
31
+ const last = line.length - max;
32
+ for (start = 0; start < last && !norm(line.slice(start, start + max)).includes(first); start = Math.min(last, start + step))
33
+ ;
34
+ if (!norm(line.slice(start, start + max)).includes(first))
35
+ start = 0;
36
+ }
37
+ const cut = whole(line.slice(start, start + max));
38
+ return unmark(`${start > 0 ? "…" : ""}${cut}${start + max < line.length ? "…" : ""}`);
39
+ }
40
+ export async function searchEarlier(o) {
41
+ const L = SEARCH_LIMITS;
42
+ const want = words(o.words);
43
+ if (!want.length)
44
+ return { found: [], matches: 0, conversations: 0 };
45
+ let loads = 0;
46
+ const since = (o.now ?? new Date()).getTime() - L.days * 86_400_000;
47
+ const found = [];
48
+ let matches = 0, total = 0;
49
+ const convs = new Set();
50
+ for (const c of o.conversations.slice(0, L.conversations)) {
51
+ if (c.id === o.current || !(new Date(c.at).getTime() >= since))
52
+ continue;
53
+ if (!Array.isArray(c.transcript))
54
+ continue;
55
+ const typed = c.transcript.filter((x) => !!x && x.t === "user" && typeof x.text === "string").map((x) => x.text);
56
+ const hits = [...new Set(typed.filter((line) => { const n = norm(line); return want.every((w) => n.includes(w)); }))];
57
+ if (!hits.length)
58
+ continue;
59
+ if (++loads > L.loads)
60
+ break;
61
+ const saved = await o.history(c.id);
62
+ if (!saved)
63
+ continue;
64
+ const saw = new Set(modelSaw(saved.state.messages));
65
+ const title = typed.length && saw.has(typed[0]) && !hasSecret(typed[0]) && !hasSecret(c.title) ? c.title.slice(0, 120) : "An earlier conversation";
66
+ for (const line of hits) {
67
+ if (!saw.has(line) || hasSecret(line))
68
+ continue;
69
+ matches++;
70
+ convs.add(c.id);
71
+ if (found.length >= L.snippets)
72
+ continue;
73
+ const said = snippet(line, want[0], L.snippet);
74
+ if (total + said.length > L.total)
75
+ continue;
76
+ total += said.length;
77
+ found.push({ title: unmark(whole(title)), last_active: c.at.slice(0, 10), said });
78
+ }
79
+ }
80
+ return { found, matches, conversations: convs.size };
81
+ }
82
+ export function searchTool(o) {
83
+ let used = 0;
84
+ const tool = defineTool({
85
+ name: SEARCH_TOOL, title: "Search earlier conversations", description: DESCRIPTION, risk: "read",
86
+ input: z.object({ words: z.string().trim().min(2).max(100).describe("A few words the person used before") }),
87
+ run: async (_ctx, i) => {
88
+ if (used >= SEARCH_LIMITS.perRequest)
89
+ return { ok: true, data: { summary: "Search limit reached for this request", note: "Two searches is the most for one request." } };
90
+ used++;
91
+ try {
92
+ const r = await searchEarlier({ conversations: await o.earlier(SEARCH_LIMITS.conversations), words: i.words, current: o.current, history: o.history });
93
+ const summary = r.matches ? `${r.matches} match${r.matches === 1 ? "" : "es"} in ${r.conversations} earlier conversation${r.conversations === 1 ? "" : "s"}` : "No matches in earlier conversations";
94
+ return { ok: true, data: { summary, matches: r.found, note: NOTE } };
95
+ }
96
+ catch {
97
+ return { ok: false, error: "Search isn't available right now." };
98
+ }
99
+ },
100
+ });
101
+ return { tool, searched: () => used > 0 };
102
+ }
103
+ export function searchedSinceTyped(messages) {
104
+ for (let i = messages.length - 1; i >= 0; i--) {
105
+ const m = messages[i];
106
+ if (m.role === "user" && (typeof m.content === "string" || m.content.some((b) => b.type === "text")))
107
+ return false;
108
+ if (m.role === "assistant" && Array.isArray(m.content) && m.content.some((b) => b.type === "tool_use" && [SEARCH_TOOL, HELP_TOOL].includes(b.name ?? "")))
109
+ return true;
110
+ }
111
+ return false;
112
+ }
@@ -0,0 +1,54 @@
1
+ export declare const isSecretKey: (k: string) => boolean;
2
+ export declare const isSensitiveKey: (k: string) => boolean;
3
+ /** Fields the owner named to protect, on top of those recognised by name. Matched as names are: capitals, `_`, `-` and spaces ignored. */
4
+ export interface Protect {
5
+ hide?: readonly string[];
6
+ mask?: readonly string[];
7
+ }
8
+ /** How a field name is treated by name alone: "hidden" (a secret), "last4" (an identifier) or null (sent as it is, its text still checked for numbers and keys). */
9
+ export declare const guardOf: (k: string) => "hidden" | "last4" | null;
10
+ /** How a label shown on a screen is treated: "hidden" (a secret), "last4" (an ID number) or null. */
11
+ export declare function labelGuard(label: string): "hidden" | "last4" | null;
12
+ /**
13
+ * Whether a label plainly names a secret (password, PIN, token, security answer, recovery code...). Only these hide prose
14
+ * after them and whole sections under a heading; the looser field-name match ("Session", "Signature", "Key") never does,
15
+ * so ordinary pages and their own messages stay readable.
16
+ */
17
+ export declare const secretLabel: (label: string) => boolean;
18
+ /**
19
+ * Text with a protected label anywhere in it, each label's value protected. An ID number's label ("passport", "SSN")
20
+ * protects the words with digits right after it ("Note: passport 533401372 on file" → "Note: passport •••• 1372 on file");
21
+ * with no number after it, nothing ("Licence plate…", "Pin location: Riverside dock" stay). A secret's label ("Security
22
+ * answer", "Recovery code", "CVV") followed by ":", "=" or "is" hides what follows, to the end of the sentence (at most six
23
+ * words), digits or not. Shapes are masked first, over the whole text. `guard` decides a label (the page view adds the
24
+ * owner's own names).
25
+ */
26
+ export declare function maskLabelled(t: string, guard?: (label: string) => "hidden" | "last4" | null): string;
27
+ /**
28
+ * Whether a value is already masked by Cognolo, so it isn't masked again: for a secret, only "[hidden]" or bullets alone; for
29
+ * an ID number, also three or more bullets with at most 4 characters after them ("•••• 1372").
30
+ */
31
+ export declare const alreadyMasked: (v: string, g?: "hidden" | "last4") => boolean;
32
+ /** The Luhn check card numbers carry. */
33
+ export declare function luhn(digits: string): boolean;
34
+ /** A value kept to its last 4 characters ("•••-••-6789", "•••• 4242") when it is long enough; shorter ones are hidden whole. */
35
+ export declare function maskTail(v: string): string;
36
+ /** SSN-shaped, card-shaped and IBAN-shaped values inside free text (a note, a description), masked. */
37
+ export declare function maskText(s: string): {
38
+ text: string;
39
+ n: number;
40
+ };
41
+ /** Whether a person's typed text looks like it holds an SSN, a card or an IBAN (the panel warns; it never changes it). */
42
+ export declare const looksSensitive: (s: string) => boolean;
43
+ /** Whether a value the model wrote carries a mask (it can't be written back over the real one). */
44
+ export declare const holdsMask: (v: unknown) => boolean;
45
+ /**
46
+ * The model's copy of a tool's data: secret fields hidden, sensitive identifiers masked, SSNs, cards and IBANs in any text
47
+ * masked. `reveal`: identifier field names the owner lets through in full (never a secret). `protect`: field names the owner
48
+ * marked to hide (as a secret, never revealed) or to cut to their last 4 (as an identifier). Returns the data and how many
49
+ * values were changed. The data is first read as JSON, exactly as it would be sent, so dates stay dates and `toJSON` holds.
50
+ */
51
+ export declare function forModel(data: unknown, reveal?: readonly string[], protect?: Protect): {
52
+ data: unknown;
53
+ changed: number;
54
+ };
@@ -0,0 +1,209 @@
1
+ const keyOf = (k) => k.toLowerCase().replace(/[_\-\s]/g, "");
2
+ const wordsOf = (k) => k.replace(/([a-z0-9])([A-Z])/g, "$1 $2").toLowerCase().split(/[_\-\s]+/).filter(Boolean);
3
+ const ABOUT_END = new Set(["at", "date", "time", "type", "kind", "count", "enabled", "expires", "expiry", "changed", "length", "country", "status", "required", "policy", "version"]);
4
+ const ABOUT_START = new Set(["has", "is"]);
5
+ const NOT_SECRET = /^(blurhash|(content|file|image|push|pushed|etag|check|data|listing)(hash|sum)|checksum)$/;
6
+ const isAbout = (k) => {
7
+ const w = wordsOf(k);
8
+ return ABOUT_END.has(w.at(-1) ?? "") || (w.length > 1 && ABOUT_START.has(w[0])) || keyOf(k).includes("secretary") || w.includes("tokens") || (w.includes("token") && /^(balance|used|usage|limit|count)$/.test(w.at(-1) ?? "")) || NOT_SECRET.test(w.slice(-2).join("")) || NOT_SECRET.test(keyOf(k));
9
+ };
10
+ const SECRET_KEY = /(password|passwd|^pwd|passcode|passphrase|secret|token|apikey|accesskey|privatekey|sessionid|^session$|cookie|authorization|^auth$|jwt|bearer|signature|salt$|^otp|otp$|onetimecode|credential|fullkey|encryptionkey|signingkey|masterkey|sshkey|stripekey|licen[cs]ekey|authkey|connectionstring|databaseurl|^dsn$|recoverycode|backupcode|verificationcode|resetcode|mfacode|smscode|invitecode|accesscode|magiclink|hmackey|seed$|totp|twofactor|hash$|hashed|^pin$|pincode|cvv|cvc|securitycode|securityanswer|^key$)/;
11
+ const SENSITIVE_KEY = /(ssn|^social|socialsecurity|socialinsurance|^sin$|nino|nationalid|nationalinsurance|taxid|taxpayer|taxnumber|^tin$|^ein$|^fein$|^itin$|^licen[cs]e$|drivinglicen[cs]e|idnumber|nhsnumber|vatnumber|passport|licen[cs]e(no|num|number|id)$|driverlicen[cs]e|driverslicen[cs]e|^dl(no|num|number)$|^card$|cardnumber|cardnum|cardno|ccnum|creditcard|debitcard|^pan$|iban|accountnumber|accountnum|acctno|acctnum|accountno|bankaccount|bankacct|routing|sortcode|medicare|medicaid|^mrn$|medicalrecord|healthid)/;
12
+ export const isSecretKey = (k) => SECRET_KEY.test(keyOf(k)) && !isAbout(k);
13
+ export const isSensitiveKey = (k) => SENSITIVE_KEY.test(keyOf(k)) && !["country", "type", "kind", "status", "enabled", "at"].includes(wordsOf(k).at(-1) ?? "");
14
+ export const guardOf = (k) => (isSecretKey(k) ? "hidden" : isSensitiveKey(k) ? "last4" : null);
15
+ const SECRET_WORDS = /\b(passwords?|passcodes?|passphrases?|secrets?|tokens?|api keys?|access keys?|private keys?|security codes?|security answers?|card codes?|cvv|cvc|csc|pins?(?! (location|drop|map|board))|one time codes?|otps?|verification codes?|recovery codes?|backup codes?)\b/;
16
+ const ID_WORDS = /\b(licen[cs]e(?! plate)|lic|passport|ssn|social security|soc sec|social insurance|national insurance|ni number|nino|national id|id number|dl|dl number|tax (id|number|file|reference|code)|tfn|tin|ein|itin|vat number|card (number|ending)|credit card|debit card|account (number|no)|acct|bank details|iban|swift|bic|bsb|sort code|routing|medicare|medicaid|nhs number|mrn|medical record)\b/;
17
+ const labelBase = (label) => label.normalize("NFKC").replace(/\([^)]*\)|\[[^\]]*\]/g, " ").replace(/[#№]/g, " number ").replace(/\bno\b\.?/gi, " number ")
18
+ .replace(/\b(required|optional|mandatory)\b/gi, " ").replace(/[^\p{L}\p{N}\s]/gu, " ").replace(/\s+/g, " ").trim();
19
+ export function labelGuard(label) {
20
+ const base = labelBase(label);
21
+ if (!base)
22
+ return null;
23
+ const low = base.toLowerCase();
24
+ return SECRET_WORDS.test(low) ? "hidden" : ID_WORDS.test(low) ? "last4" : guardOf(base);
25
+ }
26
+ export const secretLabel = (label) => SECRET_WORDS.test(labelBase(label).toLowerCase());
27
+ const MASKED_WORD = /^\[hidden\][.,;]?$|^[•-]*•{3}[•-]*[A-Za-z0-9]{0,4}[.,;]?$/;
28
+ const maskedWord = (w) => MASKED_WORD.test(w);
29
+ const PREDICATE = /^(valid|invalid|required|incorrect|correct|wrong|expired|expiring|missing|too|not|now|about|set|sent|reset|changed|needed|optional|case|a|an|the|to|for|being|still|already|only|shown|hidden|empty|blank|new|old|weak|strong|ok|okay)$/i;
30
+ export function maskLabelled(t, guard = labelGuard) {
31
+ const words = maskText(t).text.split(" ").flatMap((w) => (/:\/\/|@/.test(w) ? [w] : w.replace(/(?<=\p{L})([:=#])(?=[\p{L}\p{N}])/gu, "$1 ").replace(/^#(?=\d)/, "# ").split(" ")));
32
+ const out = [];
33
+ let i = 0;
34
+ while (i < words.length) {
35
+ let taken = 0;
36
+ for (let n = 1; n <= 4 && i + n < words.length; n++) {
37
+ const label = words.slice(i, i + n);
38
+ const lastWord = label[n - 1];
39
+ if (/\d/.test(lastWord) || maskedWord(lastWord) || /^is$/i.test(lastWord))
40
+ break;
41
+ const name = label.join(" ").replace(/[:=]+$/, "");
42
+ const g = guard(name);
43
+ if (!g)
44
+ continue;
45
+ const after = words[i + n] ?? "";
46
+ const isForm = after.toLowerCase() === "is";
47
+ const separated = /[:=]$/.test(lastWord) || isForm;
48
+ if (g === "hidden" && separated && secretLabel(name) && !(isForm && PREDICATE.test(words[i + n + 1] ?? ""))) {
49
+ let end = i + n + (isForm ? 1 : 0);
50
+ const from = end;
51
+ while (end < words.length && end - from < 20) {
52
+ const w = words[end];
53
+ end++;
54
+ if (/[.;!?]$/.test(w) && !/\d/.test(words[end] ?? ""))
55
+ break;
56
+ }
57
+ if (end === from)
58
+ continue;
59
+ const stop = /[.;!?]$/.test(words[end - 1]) ? words[end - 1].slice(-1) : "";
60
+ out.push(...words.slice(i, from), `[hidden]${stop}`);
61
+ taken = end - i;
62
+ break;
63
+ }
64
+ let end = i + n;
65
+ while (end < words.length && /\d/.test(words[end]) && !maskedWord(words[end]))
66
+ end++;
67
+ if (end === i + n)
68
+ continue;
69
+ out.push(...label, g === "hidden" ? "[hidden]" : maskTail(words.slice(i + n, end).join(" ")));
70
+ taken = end - i;
71
+ break;
72
+ }
73
+ if (taken)
74
+ i += taken;
75
+ else
76
+ out.push(words[i++]);
77
+ }
78
+ return out.join(" ");
79
+ }
80
+ export const alreadyMasked = (v, g = "last4") => {
81
+ const s = v.trim();
82
+ return s === "[hidden]" || /^[•\s-]*$/.test(s) && s.includes("•") || (g === "last4" && /^[•\s-]*•{3}[•\s-]*[A-Za-z0-9]{0,4}$/.test(s));
83
+ };
84
+ const SSN = /\b\d{3}[-. ]\d{2}[-. ]\d{4}\b/g;
85
+ const CARDISH = /\b[2-6](?:[\s\-./]{0,2}\d){14,15}\b/g;
86
+ const IBAN = /\b[A-Z]{2}\d{2}(?: ?[A-Z0-9]{4}){2,7}(?: ?[A-Z0-9]{1,4})?\b/g;
87
+ const LABELLED = /\b(password|passwd|passcode|passphrase|pwd|pin|secret|token|api[ _-]?key|access[ _-]?key|private[ _-]?key)(\s*[:=]\s*|\s+is\s+(?!(?:valid|invalid|required|incorrect|correct|wrong|expired|expiring|missing|too|not|now|about|set|sent|reset|changed|needed|optional|case|a|an|the|to|for|being|still|already|only|shown|hidden|empty|blank|new|old|weak|strong|ok|okay)\b))("[^"]*"|'[^']*'|[^\s,;"']+)/gi;
88
+ const URL_LOGIN = /(\b[a-z][a-z0-9+.-]*:\/\/)[^\s/:@]+:[^\s/@]+@/gi;
89
+ const KEY_SHAPES = [
90
+ /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(-----END [A-Z ]*PRIVATE KEY-----|$)/g,
91
+ /\b(sk|pk|rk)_(live|test)_[A-Za-z0-9]{8,}/g,
92
+ /\bcog_(live|test)_[A-Za-z0-9_-]{8,}/g,
93
+ /\bAKIA[0-9A-Z]{16}\b/g,
94
+ /\bgh[pousr]_[A-Za-z0-9]{20,}/g,
95
+ /\bxox[baprs]-[A-Za-z0-9-]{10,}/g,
96
+ /\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{5,}/g,
97
+ ];
98
+ export function luhn(digits) {
99
+ let sum = 0;
100
+ for (let i = 0; i < digits.length; i++) {
101
+ let d = digits.charCodeAt(digits.length - 1 - i) - 48;
102
+ if (i % 2) {
103
+ d *= 2;
104
+ if (d > 9)
105
+ d -= 9;
106
+ }
107
+ sum += d;
108
+ }
109
+ return digits.length >= 13 && sum % 10 === 0;
110
+ }
111
+ export function maskTail(v) {
112
+ const s = v.trim();
113
+ if (s.replace(/[\s\-./]/g, "").length < 9)
114
+ return "••••";
115
+ const last = s.slice(-4);
116
+ return /^\d{3}[-. ]\d{2}[-. ]\d{4}$/.test(s) ? `•••-••-${last}` : `•••• ${last}`;
117
+ }
118
+ export function maskText(s) {
119
+ let n = 0;
120
+ const text = s
121
+ .normalize("NFKC")
122
+ .replace(SSN, (m) => { n++; return maskTail(m); })
123
+ .replace(CARDISH, (m) => { const d = m.replace(/\D/g, ""); if ((d.length !== 15 && d.length !== 16) || !luhn(d))
124
+ return m; n++; return `•••• ${d.slice(-4)}`; })
125
+ .replace(IBAN, (m) => { n++; return maskTail(m); })
126
+ .replace(LABELLED, (_m, word, sep) => { n++; return `${word}${sep}[hidden]`; })
127
+ .replace(URL_LOGIN, (_m, scheme) => { n++; return `${scheme}[hidden]@`; });
128
+ const out = KEY_SHAPES.reduce((t, r) => t.replace(r, () => { n++; return "[hidden]"; }), text);
129
+ return n ? { text: out, n } : { text: s, n: 0 };
130
+ }
131
+ export const looksSensitive = (s) => maskText(s).n > 0;
132
+ export const holdsMask = (v) => /•••|\[hidden\]|(?<![A-Za-z])[*xX]{3}[-. ]?[*xX]{2}[-. ]?\d{4}\b|(?<![A-Za-z])[*xX•]{4,}[ -]?\d{4}\b/.test(JSON.stringify(v ?? null));
133
+ export function forModel(data, reveal = [], protect = {}) {
134
+ const allowed = new Set(reveal.map(keyOf));
135
+ const hidden = new Set((protect.hide ?? []).filter((x) => typeof x === "string").map(keyOf));
136
+ const masked = new Set((protect.mask ?? []).filter((x) => typeof x === "string").map(keyOf));
137
+ let changed = 0;
138
+ const hideAll = (v) => {
139
+ if (typeof v === "string" || typeof v === "number") {
140
+ if (String(v).trim()) {
141
+ changed++;
142
+ return maskTail(String(v));
143
+ }
144
+ return v;
145
+ }
146
+ if (Array.isArray(v))
147
+ return v.map(hideAll);
148
+ if (v && typeof v === "object")
149
+ return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, (isSecretKey(k) || hidden.has(keyOf(k))) && x !== null && x !== undefined && x !== "" ? ((changed++, "[hidden]")) : hideAll(x)]));
150
+ return v;
151
+ };
152
+ const revealed = (v) => (Array.isArray(v) ? v.map(revealed) : v && typeof v === "object" ? walk(v) : v);
153
+ const revealedOwn = (v) => (typeof v === "string" ? walk(v) : Array.isArray(v) ? v.map(revealedOwn) : v && typeof v === "object" ? walk(v) : v);
154
+ const walk = (v) => {
155
+ if (typeof v === "string") {
156
+ const r = maskText(v);
157
+ changed += r.n;
158
+ return r.text;
159
+ }
160
+ if (typeof v === "number" && Number.isSafeInteger(v) && v >= 1e14) {
161
+ const r = maskText(String(v));
162
+ if (r.n) {
163
+ changed += r.n;
164
+ return r.text;
165
+ }
166
+ return v;
167
+ }
168
+ if (Array.isArray(v))
169
+ return v.map(walk);
170
+ if (v && typeof v === "object") {
171
+ const out = {};
172
+ for (const [k, x] of Object.entries(v)) {
173
+ if (isSecretKey(k) && (typeof x === "string" ? x !== "" : typeof x === "number" || (typeof x === "object" && x !== null))) {
174
+ out[k] = "[hidden]";
175
+ changed++;
176
+ continue;
177
+ }
178
+ if (hidden.has(keyOf(k))) {
179
+ if (x !== null && x !== undefined && x !== "") {
180
+ out[k] = "[hidden]";
181
+ changed++;
182
+ }
183
+ else
184
+ out[k] = x;
185
+ continue;
186
+ }
187
+ if (isSensitiveKey(k) || masked.has(keyOf(k))) {
188
+ if (allowed.has(keyOf(k))) {
189
+ out[k] = isSensitiveKey(k) ? revealed(x) : revealedOwn(x);
190
+ continue;
191
+ }
192
+ out[k] = hideAll(x);
193
+ continue;
194
+ }
195
+ out[k] = walk(x);
196
+ }
197
+ return out;
198
+ }
199
+ return v;
200
+ };
201
+ let json;
202
+ try {
203
+ json = JSON.parse(JSON.stringify(data ?? null));
204
+ }
205
+ catch {
206
+ json = null;
207
+ }
208
+ return { data: walk(json), changed };
209
+ }
@@ -0,0 +1,93 @@
1
+ export type SetupStore = "prisma" | "drizzle" | "sql";
2
+ /** The sign-in the app uses, as far as it can be told from its dependencies. */
3
+ export type SetupSignIn = "next-auth" | "clerk" | "replit-auth" | "unknown";
4
+ export interface SetupChoices {
5
+ store: SetupStore;
6
+ /**
7
+ * The kind of app. `express`: an Express server with a React front end (what Replit Agent usually builds): the route is
8
+ * served from the app's own server and the panel goes in its front end. Left out: Next.js.
9
+ */
10
+ framework?: "next" | "express";
11
+ /** Express: the server's folder (default `server`) and the front end's source folder (default `client/src`). */
12
+ serverDir?: string;
13
+ clientDir?: string;
14
+ /** Express: the app has an `npm run db:push` script (drizzle-kit push), used to make the tables. */
15
+ pushScript?: boolean;
16
+ signIn?: SetupSignIn;
17
+ /** Where the app's code lives: `""` for `app/`, `"src/"` for `src/app/`. */
18
+ base?: "" | "src/";
19
+ /** True when `base` was not read from the app itself (the cloud can't see its folders): the checklist says to move the files. */
20
+ baseGuessed?: boolean;
21
+ /** A sign-in that was seen but not filled in (the cloud can't tell Auth.js v4 from v5), named in the checklist. */
22
+ signInSeen?: string;
23
+ /** The sign-in package's version as package.json declares it ("^7.9.21"), when known: Clerk's fresh sign-in check
24
+ * (re-verification) is written in only for a version known to have it. */
25
+ signInVersion?: string;
26
+ /** The module that exports the app's database client (`db` for Prisma and Drizzle, `pool` for plain SQL). Default `@/lib/db`. */
27
+ dbModule?: string;
28
+ /**
29
+ * The current `prisma/schema.prisma`, so the models are added only once. `null`: there is no such file (a schema folder or
30
+ * another path), so nothing is added and the checklist says where the models are. Left out: not known, so they are added.
31
+ */
32
+ prismaSchema?: string | null;
33
+ /** The current `.env.example`, so the settings are added only once. */
34
+ envExample?: string | null;
35
+ /**
36
+ * The app's layout files (`app/**\/layout.tsx`) with their text, so the panel can be added to the signed-in one. Left out
37
+ * (the cloud can't read the folders yet): nothing is changed and the checklist says where the line goes.
38
+ */
39
+ layouts?: {
40
+ path: string;
41
+ content: string;
42
+ }[];
43
+ /**
44
+ * Where the app already uses the assistant (`<CognoloAssistant` or `@cognolo/runtime/react` in its own code): then no
45
+ * button is added. `null`: the caller couldn't tell (too many files to look through), so no button is added either.
46
+ */
47
+ assistantAt?: string | null;
48
+ }
49
+ export interface SetupFile {
50
+ path: string;
51
+ content: string;
52
+ /**
53
+ * `create`: a new file (never written over one that exists). `append`: added to the end of a file that may exist.
54
+ * `edit`: an existing file's new text, written only if the file still reads exactly `original`.
55
+ */
56
+ action: "create" | "append" | "edit";
57
+ /** For `edit`: the text it was made from. */
58
+ original?: string;
59
+ }
60
+ export interface SetupPlan {
61
+ files: SetupFile[];
62
+ /** What the owner must check before merging, in plain words. */
63
+ check: string[];
64
+ /** What to run after merging. Cognolo runs none of them. */
65
+ commands: string[];
66
+ }
67
+ /** The files and the checklist for one app. */
68
+ export declare function addCognoloFiles(c: SetupChoices): SetupPlan;
69
+ /** The pull request's description: what it adds, what to check, and what to run after merging. */
70
+ export declare function setupSummary(plan: SetupPlan): string;
71
+ /** The one check-list line when the button isn't placed for the owner. */
72
+ export declare const PANEL_BY_HAND = "The panel: add <CognoloAssistantPanel /> (from components/cognolo-assistant.tsx) to your signed-in layout, after {children}.";
73
+ /**
74
+ * The app's signed-in layout, when Cognolo can tell which one it is: a layout under `<base>app/` that isn't a root layout
75
+ * (no `<html>` or `<body>`, so it never covers public or sign-in pages by itself), sends a signed-out person away
76
+ * (`sendsAwayIfSignedOut`), has `{children}` once and no Cognolo panel yet, and reads cleanly. With several, the outermost,
77
+ * and only if all the others sit inside it. Anything else is unclear, so null.
78
+ */
79
+ export declare function signedInLayout(layouts: {
80
+ path: string;
81
+ content: string;
82
+ }[], base?: "" | "src/"): {
83
+ path: string;
84
+ content: string;
85
+ } | null;
86
+ /**
87
+ * The layout with the panel added: one import after the last import (or after a "use client" line at the very start, or
88
+ * at the top) and the element right after `{children}`. Every other byte is kept as it was. Null when unsure: a copy that
89
+ * can't be trusted, `{children}` not exactly once (counted in the text too, so a commented-out one also means no), an
90
+ * import after the default export (that is page text, not an import), or a directive that isn't first.
91
+ */
92
+ export declare function withPanel(content: string, layoutPath?: string, base?: "" | "src/"): string | null;
93
+ export { compareVersions, installSpec, isVersion, RELEASES, RUNTIME_VERSION, updatePlan, type Release } from "./version.js";