@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,192 @@
1
+ import { type KeyObject } from "node:crypto";
2
+ import { z } from "zod";
3
+ import type { Policy } from "./agent.js";
4
+ export declare const BundleSchema: z.ZodObject<{
5
+ app: z.ZodString;
6
+ env: z.ZodString;
7
+ key: z.ZodOptional<z.ZodString>;
8
+ version: z.ZodNumber;
9
+ issuedAt: z.ZodISODateTime;
10
+ expiresAt: z.ZodISODateTime;
11
+ rules: z.ZodArray<z.ZodObject<{
12
+ id: z.ZodString;
13
+ text: z.ZodString;
14
+ restricts: z.ZodBoolean;
15
+ on: z.ZodBoolean;
16
+ audience: z.ZodDefault<z.ZodEnum<{
17
+ assistant: "assistant";
18
+ code: "code";
19
+ }>>;
20
+ }, z.core.$strip>>;
21
+ facts: z.ZodDefault<z.ZodArray<z.ZodObject<{
22
+ text: z.ZodString;
23
+ about: z.ZodArray<z.ZodString>;
24
+ }, z.core.$strip>>>;
25
+ skills: z.ZodRecord<z.ZodString, z.ZodNumber>;
26
+ ruleOff: z.ZodEnum<{
27
+ ask: "ask";
28
+ allow: "allow";
29
+ }>;
30
+ offline: z.ZodEnum<{
31
+ readonly: "readonly";
32
+ lastknown: "lastknown";
33
+ }>;
34
+ maxSteps: z.ZodNumber;
35
+ limits: z.ZodDefault<z.ZodObject<{
36
+ runTokens: z.ZodOptional<z.ZodNumber>;
37
+ paused: z.ZodOptional<z.ZodString>;
38
+ readonly: z.ZodOptional<z.ZodString>;
39
+ notice: z.ZodOptional<z.ZodString>;
40
+ people: z.ZodOptional<z.ZodObject<{
41
+ cap: z.ZodNumber;
42
+ holders: z.ZodArray<z.ZodString>;
43
+ }, z.core.$strip>>;
44
+ savedWorkflows: z.ZodOptional<z.ZodObject<{
45
+ max: z.ZodNumber;
46
+ full: z.ZodString;
47
+ }, z.core.$strip>>;
48
+ meter: z.ZodOptional<z.ZodObject<{
49
+ plan: z.ZodString;
50
+ stops: z.ZodBoolean;
51
+ testing: z.ZodOptional<z.ZodBoolean>;
52
+ questions: z.ZodObject<{
53
+ pct: z.ZodNumber;
54
+ of: z.ZodNumber;
55
+ }, z.core.$strip>;
56
+ actions: z.ZodOptional<z.ZodObject<{
57
+ pct: z.ZodNumber;
58
+ of: z.ZodNumber;
59
+ }, z.core.$strip>>;
60
+ today: z.ZodOptional<z.ZodObject<{
61
+ pct: z.ZodNumber;
62
+ of: z.ZodNumber;
63
+ }, z.core.$strip>>;
64
+ resets: z.ZodString;
65
+ }, z.core.$strip>>;
66
+ }, z.core.$strip>>;
67
+ drafts: z.ZodDefault<z.ZodArray<z.ZodString>>;
68
+ whiteLabel: z.ZodDefault<z.ZodBoolean>;
69
+ logo: z.ZodCatch<z.ZodDefault<z.ZodBoolean>>;
70
+ reveal: z.ZodCatch<z.ZodDefault<z.ZodArray<z.ZodString>>>;
71
+ model: z.ZodCatch<z.ZodOptional<z.ZodObject<{
72
+ id: z.ZodString;
73
+ effort: z.ZodOptional<z.ZodEnum<{
74
+ low: "low";
75
+ medium: "medium";
76
+ high: "high";
77
+ }>>;
78
+ }, z.core.$strip>>>;
79
+ passkey: z.ZodCatch<z.ZodDefault<z.ZodObject<{
80
+ tools: z.ZodDefault<z.ZodArray<z.ZodString>>;
81
+ clickOnly: z.ZodDefault<z.ZodBoolean>;
82
+ clickTools: z.ZodDefault<z.ZodArray<z.ZodString>>;
83
+ }, z.core.$strip>>>;
84
+ outside: z.ZodCatch<z.ZodDefault<z.ZodObject<{
85
+ on: z.ZodDefault<z.ZodBoolean>;
86
+ tools: z.ZodDefault<z.ZodArray<z.ZodString>>;
87
+ ack: z.ZodDefault<z.ZodCatch<z.ZodNumber>>;
88
+ changes: z.ZodCatch<z.ZodOptional<z.ZodObject<{
89
+ all: z.ZodDefault<z.ZodBoolean>;
90
+ tools: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodEnum<{
91
+ ask: "ask";
92
+ "ask-irreversible": "ask-irreversible";
93
+ never: "never";
94
+ }>>>;
95
+ perHour: z.ZodCatch<z.ZodOptional<z.ZodNumber>>;
96
+ }, z.core.$strip>>>;
97
+ }, z.core.$strip>>>;
98
+ protect: z.ZodCatch<z.ZodDefault<z.ZodObject<{
99
+ hide: z.ZodCatch<z.ZodDefault<z.ZodArray<z.ZodCatch<z.ZodString>>>>;
100
+ mask: z.ZodCatch<z.ZodDefault<z.ZodArray<z.ZodCatch<z.ZodString>>>>;
101
+ }, z.core.$strip>>>;
102
+ screen: z.ZodDefault<z.ZodEnum<{
103
+ off: "off";
104
+ watching: "watching";
105
+ stopping: "stopping";
106
+ }>>;
107
+ filter: z.ZodCatch<z.ZodDefault<z.ZodString>>;
108
+ suggest: z.ZodCatch<z.ZodDefault<z.ZodString>>;
109
+ search: z.ZodCatch<z.ZodDefault<z.ZodString>>;
110
+ pictures: z.ZodCatch<z.ZodDefault<z.ZodString>>;
111
+ research: z.ZodOptional<z.ZodUnknown>;
112
+ page: z.ZodCatch<z.ZodDefault<z.ZodString>>;
113
+ workflows: z.ZodDefault<z.ZodObject<{
114
+ use: z.ZodBoolean;
115
+ schedule: z.ZodBoolean;
116
+ }, z.core.$strip>>;
117
+ published: z.ZodCatch<z.ZodDefault<z.ZodArray<z.ZodUnknown>>>;
118
+ help: z.ZodCatch<z.ZodDefault<z.ZodArray<z.ZodUnknown>>>;
119
+ look: z.ZodCatch<z.ZodOptional<z.ZodUnknown>>;
120
+ }, z.core.$strip>;
121
+ export type Bundle = z.infer<typeof BundleSchema>;
122
+ /**
123
+ * What travels over the wire. The signature covers the exact payload text, so nothing has to be re-serialised to check it.
124
+ * With `alg: "ed25519-sha512"` it is an Ed25519 signature over the 64-byte SHA-512 digest of the payload's UTF-8 bytes
125
+ * (what a key service that signs only short messages can do); with no `alg`, over the payload's bytes themselves.
126
+ */
127
+ export interface SignedBundle {
128
+ /** The bundle as JSON text. */
129
+ payload: string;
130
+ /** Base64 Ed25519 signature. */
131
+ signature: string;
132
+ alg?: typeof BUNDLE_ALG;
133
+ }
134
+ export declare const BUNDLE_ALG = "ed25519-sha512";
135
+ /**
136
+ * Cognolo's production public keys (Ed25519, PEM): one signs, one waits in case the first is ever lost. Used when an app
137
+ * gives no key of its own. Replacing a key means shipping a runtime with the new list first.
138
+ */
139
+ export declare const COGNOLO_PUBLIC_KEYS: readonly string[];
140
+ /** One key, a list, or PEM text holding one or more keys, as Ed25519 key objects (left out: `COGNOLO_PUBLIC_KEYS`). Throws on anything else. */
141
+ export declare function publicKeys(given?: KeyObject | string | readonly (KeyObject | string)[]): KeyObject[];
142
+ /** The cloud's side (and the tests'), in the original form: a signature over the payload itself. Refuses to sign a bundle that is not valid. */
143
+ export declare function signBundle(bundle: z.input<typeof BundleSchema>, privateKey: KeyObject): SignedBundle;
144
+ /**
145
+ * The cloud's side, hash-then-sign (`alg: "ed25519-sha512"`). `signer` is a private key, or a function that signs the 64
146
+ * digest bytes as a plain message (AWS KMS: `Sign` with `ED25519_SHA_512` and `MessageType: "RAW"`). Refuses to sign a
147
+ * bundle that is not valid.
148
+ */
149
+ export declare function signBundleHashed(bundle: z.input<typeof BundleSchema>, signer: KeyObject | ((digest: Buffer) => Uint8Array | Promise<Uint8Array>)): Promise<SignedBundle>;
150
+ export type Rejection = "unsigned" | "bad_signature" | "malformed" | "wrong_app" | "wrong_environment" | "wrong_key" | "expired" | "older";
151
+ /** A key's fingerprint as a bundle carries it: the first 16 hex characters of its SHA-256. */
152
+ export declare const keyPrint: (key: string) => string;
153
+ export type Verified = {
154
+ ok: true;
155
+ bundle: Bundle;
156
+ } | {
157
+ ok: false;
158
+ reason: Rejection;
159
+ message: string;
160
+ };
161
+ export interface VerifyOptions {
162
+ /**
163
+ * Cognolo's public key (a KeyObject, or PEM text, which may hold several), or a list of them: a bundle any one of them
164
+ * signed is accepted. Must be Ed25519. Left out: `COGNOLO_PUBLIC_KEYS`.
165
+ */
166
+ publicKey?: KeyObject | string | readonly (KeyObject | string)[];
167
+ /** The environment this app runs in. A bundle for any other environment is refused, even if it is genuinely signed. */
168
+ env: string;
169
+ /** The app, if the host knows it. */
170
+ app?: string;
171
+ /**
172
+ * The app's own key. Given, a bundle must name this key's fingerprint, so one made for another key (another account's app
173
+ * of the same name, say) is refused even though Cognolo signed it.
174
+ */
175
+ key?: string;
176
+ /** The version of the last bundle accepted: anything older is refused (an old signed bundle cannot be played back). */
177
+ lastVersion?: number;
178
+ now?: Date;
179
+ }
180
+ /** The app's side. The signature is checked before anything inside the payload is trusted or even parsed. */
181
+ export declare function verifyBundle(signed: unknown, o: VerifyOptions): Verified;
182
+ /**
183
+ * Turns the last verified bundle into the policy the agent loop uses. `current` is asked on every call, so a new bundle,
184
+ * an expiry or a lost connection takes effect at once (and for a call that is waiting for approval, when it is approved).
185
+ * - With a live bundle: the rule guards plus the skill levels (`guardedPolicy` over `trustPolicy`).
186
+ * - With no bundle, an expired one, or Cognolo unreachable and the bundle saying "readonly": reads only.
187
+ * - Unreachable but the bundle says "lastknown" and has not expired: keep using it.
188
+ */
189
+ export declare function policyFromBundle<C>(current: () => {
190
+ bundle: Bundle | null;
191
+ reachable: boolean;
192
+ }, now?: () => Date): Policy<C>;
package/dist/bundle.js ADDED
@@ -0,0 +1,133 @@
1
+ import { createHash, createPublicKey, sign, verify } from "node:crypto";
2
+ import { z } from "zod";
3
+ import { guardedPolicy } from "./guard.js";
4
+ import { TRUST_LEVELS, trustPolicy } from "./trust.js";
5
+ const MeterUse = z.object({ pct: z.number().int().min(0).max(10000), of: z.number().int().positive().max(1e9) });
6
+ export const BundleSchema = z.object({
7
+ app: z.string().min(1),
8
+ env: z.string().min(1),
9
+ key: z.string().regex(/^[0-9a-f]{16}$/).optional(),
10
+ version: z.number().int().nonnegative(),
11
+ issuedAt: z.iso.datetime(),
12
+ expiresAt: z.iso.datetime(),
13
+ rules: z.array(z.object({ id: z.string().min(1), text: z.string(), restricts: z.boolean(), on: z.boolean(), audience: z.enum(["assistant", "code"]).default("assistant") })),
14
+ facts: z.array(z.object({ text: z.string().max(1000), about: z.array(z.string().max(120)).max(40) })).max(5000).default([]),
15
+ skills: z.record(z.string(), z.number().int().min(0).max(3)),
16
+ ruleOff: z.enum(["ask", "allow"]),
17
+ offline: z.enum(["readonly", "lastknown"]),
18
+ maxSteps: z.number().int().positive(),
19
+ limits: z.object({
20
+ runTokens: z.number().int().positive().optional(),
21
+ paused: z.string().max(200).optional(),
22
+ readonly: z.string().max(200).optional(),
23
+ notice: z.string().max(200).optional(),
24
+ people: z.object({ cap: z.number().int().positive().max(100000), holders: z.array(z.string().regex(/^[0-9a-f]{32}$/)).max(100000) }).optional(),
25
+ savedWorkflows: z.object({ max: z.number().int().positive().max(1000), full: z.string().max(200) }).optional(),
26
+ meter: z.object({
27
+ plan: z.string().min(1).max(40),
28
+ stops: z.boolean(),
29
+ testing: z.boolean().optional(),
30
+ questions: MeterUse,
31
+ actions: MeterUse.optional(),
32
+ today: MeterUse.optional(),
33
+ resets: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
34
+ }).optional(),
35
+ }).default({}),
36
+ drafts: z.array(z.string().min(1).max(64)).max(500).default([]),
37
+ whiteLabel: z.boolean().default(false),
38
+ logo: z.boolean().default(false).catch(false),
39
+ reveal: z.array(z.string().max(64)).max(50).default([]).catch([]),
40
+ model: z.object({ id: z.string().max(64), effort: z.enum(["low", "medium", "high"]).optional() }).optional().catch(undefined),
41
+ passkey: z.object({ tools: z.array(z.string().min(1).max(64)).max(500).default([]), clickOnly: z.boolean().default(false), clickTools: z.array(z.string().min(1).max(64)).max(500).default([]) }).default({ tools: [], clickOnly: false, clickTools: [] }).catch({ tools: [], clickOnly: false, clickTools: [] }),
42
+ outside: z.object({ on: z.boolean().default(false), tools: z.array(z.string().min(1).max(64)).max(200).default([]), ack: z.number().int().min(0).max(1e9).catch(0).default(0),
43
+ changes: z.object({ all: z.boolean().default(false), tools: z.record(z.string().min(1).max(64), z.enum(["ask", "ask-irreversible", "never"])).default({}), perHour: z.number().int().min(1).max(200).optional().catch(undefined) }).optional().catch(undefined) }).default({ on: false, tools: [], ack: 0 }).catch({ on: false, tools: [], ack: 0 }),
44
+ protect: z.object({ hide: z.array(z.string().max(64).catch("")).max(500).default([]).catch([]), mask: z.array(z.string().max(64).catch("")).max(500).default([]).catch([]) }).default({ hide: [], mask: [] }).catch({ hide: [], mask: [] }),
45
+ screen: z.enum(["off", "watching", "stopping"]).default("off"),
46
+ filter: z.string().max(20).default("off").catch("off"),
47
+ suggest: z.string().max(20).default("off").catch("off"),
48
+ search: z.string().max(20).default("off").catch("off"),
49
+ pictures: z.string().max(20).default("off").catch("off"),
50
+ research: z.unknown().optional(),
51
+ page: z.string().max(20).default("off").catch("off"),
52
+ workflows: z.object({ use: z.boolean(), schedule: z.boolean() }).default({ use: false, schedule: false }),
53
+ published: z.array(z.unknown()).default([]).catch([]),
54
+ help: z.array(z.unknown()).default([]).catch([]),
55
+ look: z.unknown().optional().catch(undefined),
56
+ });
57
+ export const BUNDLE_ALG = "ed25519-sha512";
58
+ export const COGNOLO_PUBLIC_KEYS = [
59
+ "-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEATUG3UYKZOsgML3kJJj+otGzjxjDEeC1tDvo/q+uLvRU=\n-----END PUBLIC KEY-----\n",
60
+ "-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEAOBQFCnVchzWKnii5aegrz4d26Xhf2Q+KUQuENLeNu/4=\n-----END PUBLIC KEY-----\n",
61
+ ];
62
+ export function publicKeys(given) {
63
+ const list = given === undefined ? COGNOLO_PUBLIC_KEYS : Array.isArray(given) ? given : [given];
64
+ const keys = list.flatMap((k) => (typeof k !== "string" ? [k] : (k.match(/-----BEGIN PUBLIC KEY-----[\s\S]*?-----END PUBLIC KEY-----/g) ?? [k]).map((pem) => createPublicKey(pem))));
65
+ if (keys.length === 0)
66
+ throw new Error("No Cognolo public key: set COGNOLO_PUBLIC_KEY or pass publicKey.");
67
+ if (keys.some((k) => k.asymmetricKeyType !== "ed25519"))
68
+ throw new Error("The Cognolo public key must be an Ed25519 key.");
69
+ return keys;
70
+ }
71
+ const digest = (payload) => createHash("sha512").update(payload, "utf8").digest();
72
+ export function signBundle(bundle, privateKey) {
73
+ const payload = JSON.stringify(BundleSchema.parse(bundle));
74
+ return { payload, signature: sign(null, Buffer.from(payload, "utf8"), privateKey).toString("base64") };
75
+ }
76
+ export async function signBundleHashed(bundle, signer) {
77
+ const payload = JSON.stringify(BundleSchema.parse(bundle));
78
+ const d = digest(payload);
79
+ const sig = typeof signer === "function" ? await signer(d) : sign(null, d, signer);
80
+ return { payload, signature: Buffer.from(sig).toString("base64"), alg: BUNDLE_ALG };
81
+ }
82
+ export const keyPrint = (key) => createHash("sha256").update(key).digest("hex").slice(0, 16);
83
+ export function verifyBundle(signed, o) {
84
+ const no = (reason, message) => ({ ok: false, reason, message });
85
+ const keys = publicKeys(o.publicKey);
86
+ const s = signed;
87
+ if (!s || typeof s !== "object" || typeof s.payload !== "string" || typeof s.signature !== "string" || !s.signature)
88
+ return no("unsigned", "The bundle is not signed.");
89
+ const bad = no("bad_signature", "The signature does not match, so the bundle was not made by Cognolo or was changed on the way.");
90
+ if (s.alg !== undefined && s.alg !== BUNDLE_ALG)
91
+ return bad;
92
+ const message = s.alg === BUNDLE_ALG ? digest(s.payload) : Buffer.from(s.payload, "utf8");
93
+ const sig = Buffer.from(s.signature, "base64");
94
+ if (!keys.some((key) => { try {
95
+ return verify(null, message, key, sig);
96
+ }
97
+ catch {
98
+ return false;
99
+ } }))
100
+ return bad;
101
+ let json;
102
+ try {
103
+ json = JSON.parse(s.payload);
104
+ }
105
+ catch {
106
+ return no("malformed", "The bundle is not valid JSON.");
107
+ }
108
+ const parsed = BundleSchema.safeParse(json);
109
+ if (!parsed.success)
110
+ return no("malformed", `The bundle is not in the expected shape: ${parsed.error.issues.map((i) => `${i.path.join(".") || "bundle"} ${i.message}`).join("; ")}`);
111
+ const b = parsed.data;
112
+ if (b.env !== o.env)
113
+ return no("wrong_environment", `The bundle is for "${b.env}", but this app runs in "${o.env}".`);
114
+ if (o.app !== undefined && b.app !== o.app)
115
+ return no("wrong_app", `The bundle is for "${b.app}", not "${o.app}".`);
116
+ if (o.key !== undefined && b.key !== keyPrint(o.key))
117
+ return no("wrong_key", "The bundle was not made for this app's key.");
118
+ if ((o.now ?? new Date()).getTime() >= Date.parse(b.expiresAt))
119
+ return no("expired", "The bundle has expired.");
120
+ if (o.lastVersion !== undefined && b.version < o.lastVersion)
121
+ return no("older", `The bundle is version ${b.version}, older than the ${o.lastVersion} already accepted.`);
122
+ return { ok: true, bundle: b };
123
+ }
124
+ export function policyFromBundle(current, now = () => new Date()) {
125
+ const readsOnly = (tool) => (tool.risk === "read" ? "auto" : { deny: "Cognolo can't be reached right now, so only lookups are allowed.", own: true });
126
+ return (tool, input, ctx) => {
127
+ const { bundle, reachable } = current();
128
+ if (!bundle || now().getTime() >= Date.parse(bundle.expiresAt) || (!reachable && bundle.offline === "readonly"))
129
+ return readsOnly(tool, input, ctx);
130
+ const level = (t) => { const n = bundle.skills[t.name]; return n === undefined ? undefined : TRUST_LEVELS[n]; };
131
+ return guardedPolicy({ isOn: (id) => bundle.rules.some((r) => r.id === id && r.on), ruleText: (id) => bundle.rules.find((r) => r.id === id)?.text, ruleOff: bundle.ruleOff, base: trustPolicy({ levelOf: level, isDraft: (t) => bundle.drafts.includes(t.name) }) })(tool, input, ctx);
132
+ };
133
+ }
@@ -0,0 +1,301 @@
1
+ import type { OutsideDoor } from "./gate.js";
2
+ import { type HelpArticle } from "./help.js";
3
+ import { type ResearchSwitches } from "./research.js";
4
+ import { type KeyObject } from "node:crypto";
5
+ import type { AgentEvent, Policy } from "./agent.js";
6
+ import { type RunInfo, type Workflow } from "./workflow.js";
7
+ import { type CloudLook, type Layout, type LookField } from "./look.js";
8
+ export interface CloudOptions {
9
+ /** The environment's key, `COGNOLO_KEY`: `cog_live_…` or `cog_test_…`. */
10
+ key: string;
11
+ /** Where the Cognolo cloud is. Required for now: there is no default until the real service exists. */
12
+ baseUrl: string;
13
+ /** Cognolo's public key (Ed25519), PEM text holding one or more, or a list; a bundle any of them signed is accepted. Left out: the runtime's built-in COGNOLO_PUBLIC_KEYS. */
14
+ publicKey?: KeyObject | string | readonly (KeyObject | string)[];
15
+ /** The environment this app runs in. A bundle for another one is refused. */
16
+ env: string;
17
+ app?: string;
18
+ /** The deployed git commit; defaults to COGNOLO_COMMIT, then the commit common hosts set (Vercel, Render, Railway, Netlify, Cloudflare Pages, Heroku, GitHub Actions). */
19
+ commit?: string;
20
+ /** The customer organisation shown in the badge, if the host knows it. */
21
+ tenant?: string | (() => string | undefined);
22
+ /** How many tools this app has, reported on the heartbeat. */
23
+ toolCount?: number;
24
+ /** How old the rules may be before the next use checks for new ones. Default 30 seconds. */
25
+ intervalMs?: number;
26
+ /** How often `start()` tells the cloud the app is alive (and sends any waiting events). Default 15 minutes. */
27
+ heartbeatMs?: number;
28
+ /** Cut off any request to the cloud after this long. Default 5 seconds. */
29
+ timeoutMs?: number;
30
+ /** How long the conversation filter may hold up a message before it goes through unchecked. Default 300 ms. */
31
+ screenTimeoutMs?: number;
32
+ /**
33
+ * Parts of the panel's look the owner can't change from the cloud, because the app sets them itself (`true`: all of
34
+ * them). Reported on the heartbeat, so the cloud's Look page can say so.
35
+ */
36
+ lockLook?: true | readonly LookField[];
37
+ /**
38
+ * Where the owner may place the panel from the Look page. Default (left out): all of `docked`, `card` and `window`, so
39
+ * owners can choose with no code. Give a shorter list if some layouts don't suit your
40
+ * pages, or `[]` (or lock `layout` in `lockLook`) to keep the panel's own `layout` always. A layout the cloud sends that
41
+ * isn't allowed is dropped before it reaches the panel. Reported on the heartbeat.
42
+ */
43
+ layouts?: readonly Layout[];
44
+ /** Send inputs, previews, summaries and reasons with the audit events. Off by default: they can hold customers' data. */
45
+ includeDetails?: boolean;
46
+ fetch?: typeof fetch;
47
+ now?: () => Date;
48
+ }
49
+ export interface CloudStatus {
50
+ /** `live` keys are for a production environment, `test` keys are not. */
51
+ keyKind: "live" | "test";
52
+ /** The running commit and the customer organisation, for the badge. */
53
+ commit: string | null;
54
+ tenant: string | null;
55
+ /** The bundle in use (its version is the rules version for the badge), or null before the first good one. */
56
+ rulesVersion: number | null;
57
+ expiresAt: string | null;
58
+ /** Whether the last attempt got a good bundle (or "unchanged"). False means the cloud is down or sent one we refused. */
59
+ reachable: boolean;
60
+ /** Why the last attempt failed, for logs. Never contains the key. */
61
+ lastError: string | null;
62
+ lastAttemptAt: string | null;
63
+ /** Audit events waiting to be sent, and how many were dropped (queue full, or refused by the cloud). */
64
+ queued: number;
65
+ dropped: number;
66
+ /** Whether the bundle in use lets this app remove the "Powered by Cognolo" credit. False with no bundle, so the credit shows. */
67
+ whiteLabel: boolean;
68
+ /** Whether the bundle in use lets the panel show the company's logo (Growth and up; also any white-label plan). */
69
+ logo?: boolean;
70
+ /**
71
+ * True when the last check for rules failed and the assistant can only look things up until one works. Rules that are
72
+ * merely old are not "limited": the next message checks for new ones first.
73
+ */
74
+ limited: boolean;
75
+ /** True when the rules are over `intervalMs` old, or expired: normal on an unused app, and the next message checks first. */
76
+ stale?: boolean;
77
+ /** True while a check for rules is out, so a page load can tell the panel to ask again in a moment. */
78
+ checking?: boolean;
79
+ }
80
+ export interface CognoloCloud<C = unknown> {
81
+ /** Pass to `runTurn`. Reads only what is in memory and never waits for the network. */
82
+ policy: Policy<C>;
83
+ /**
84
+ * What the assistant is told for a person who holds these tools: the owner's rules that are on and meant for it, and the
85
+ * code facts about those tools and the records they touch (`chooseContext`). Null when there is no bundle or nothing to
86
+ * say. Kept after the bundle expires: a rule only makes the assistant do less. Reads memory only; never waits.
87
+ */
88
+ context(tools: string[]): string | null;
89
+ /** `maxSteps` from the bundle in use, or 10. */
90
+ maxSteps(): number;
91
+ /** The owner's limits on AI use from the last verified bundle, kept after it expires (they only stop things). Reads memory only. */
92
+ limits(): {
93
+ runTokens?: number;
94
+ paused?: string;
95
+ readonly?: string;
96
+ notice?: string;
97
+ people?: {
98
+ cap: number;
99
+ holders: string[];
100
+ };
101
+ savedWorkflows?: {
102
+ max: number;
103
+ full: string;
104
+ };
105
+ meter?: UsageMeter;
106
+ };
107
+ /** A person's id as the cloud may see it: a hash keyed with this environment's key, so Cognolo never sees the id. */
108
+ who?(person: string): string;
109
+ /**
110
+ * A page load or an opened panel: check for new rules in the background when they are old. Only on a cold start (no
111
+ * bundle and no check yet) does it wait, never longer than `maxMs` (default 2 seconds). Never throws.
112
+ */
113
+ ready(maxMs?: number): Promise<void>;
114
+ /**
115
+ * Before a message: check now whether the rules changed and wait for the answer, retrying once on a failure, never
116
+ * longer than `maxMs` (default 2 seconds) in all. Unchanged rules cost one small "not modified" answer. Never throws.
117
+ */
118
+ fresh?(maxMs?: number): Promise<void>;
119
+ /** Fetch the bundle now, send the heartbeat and any waiting events. Never throws. */
120
+ refresh(): Promise<void>;
121
+ /** Hand over the events of a turn (`runTurn`'s `events`), including what its model calls used. Returns at once; sending happens in the background. `work` says what the turn was for; default "chat". */
122
+ /** `protect`: the app's own fields to protect (`RouteOptions.protect`), added to the owner's for any details sent. */
123
+ record(events: AgentEvent[], work?: string, run?: RunInfo, protect?: {
124
+ hide?: readonly string[];
125
+ mask?: readonly string[];
126
+ }): void;
127
+ /** The owner's workflow switches from a live bundle; both off with no live bundle. Reads memory only. */
128
+ workflows(): {
129
+ use: boolean;
130
+ schedule: boolean;
131
+ };
132
+ /** The workflows the owner published app-wide, from a live bundle only; none with no live bundle. Reads memory only. */
133
+ published(): Workflow[];
134
+ /** The ids of published workflows in the live bundle that this runtime couldn't read (a newer shape, say). */
135
+ publishedUnreadable?(): string[];
136
+ /** The owner's help articles, from a live bundle only (a withdrawn article must not live on offline). */
137
+ help?(): HelpArticle[];
138
+ /**
139
+ * Send the cloud a copy of the workflows kept in the app, so the owner can read them. Each is added or updated by its id;
140
+ * copies shared before (by this person or anyone else) stay until their ids are in `remove`. Ids must be unique across
141
+ * the whole environment, not per person: a second "w1" replaces the first. `replace: true` sends the whole list and
142
+ * replaces every copy this environment shared (as 0.2.0 always did): use it if you share everything after each save.
143
+ * `author` is an opaque label the host chooses for who shared them (never a name or email: a hash, say). With
144
+ * `instructions: false` (the owner's per-app choice) their text stays in the app and only name, summary and tools go.
145
+ * In an app sold to many businesses the copies reach the software maker's Cognolo account, not the person's employer:
146
+ * there, share with `instructions: false`, or tell the person plainly who reads them. Resolves to whether the cloud took
147
+ * it (a removal that fails is not sent again by itself: share again); never throws.
148
+ */
149
+ shareWorkflows(list: Workflow[], opts?: {
150
+ instructions?: boolean;
151
+ author?: string;
152
+ remove?: string[];
153
+ replace?: boolean;
154
+ }): Promise<boolean>;
155
+ /** Send waiting events now. Never throws. */
156
+ flush(): Promise<void>;
157
+ /** Say that a workflow run has finished: one row with the run's tags and no content. Returns at once. */
158
+ endRun(run: RunInfo): void;
159
+ /**
160
+ * The conversation filter, before the model sees a person's message. Sends nothing unless the bundle in use (live) says
161
+ * the owner switched it on. Waits at most `screenTimeoutMs`; on any error, timeout or odd answer the message goes through.
162
+ * Only the end of `previous` (the assistant's reply before the message) is sent. Never throws.
163
+ */
164
+ screen(message: string, previous?: string): Promise<{
165
+ pass: true;
166
+ clear?: true;
167
+ } | {
168
+ pass: false;
169
+ reply: string;
170
+ topic?: string;
171
+ }>;
172
+ /** A person's one-click ask for a topic to be allowed: only the fixed-list id goes. Never throws; false when not sent. */
173
+ askAllow?(topic: string): Promise<boolean>;
174
+ /** Whether a live bundle lets people send the assistant's one-line request to the business. */
175
+ suggestOn?(): boolean;
176
+ /** The owner let the assistant search a person's earlier conversations (a live bundle only). */
177
+ searchOn?(): boolean;
178
+ /** The owner let people add pictures (a live bundle only). */
179
+ picturesOn?(): boolean;
180
+ /** The owner's web research switches (task 74), from a live bundle only: it lets the assistant do more. False otherwise. */
181
+ research?(): ResearchSwitches | false;
182
+ /** The owner let the assistant read the page the person is on (a live bundle only). */
183
+ pageOn?(): boolean;
184
+ /** Field names the owner lets the AI read in full. With no live bundle, none: everything sensitive stays masked. */
185
+ reveal?(): string[];
186
+ /**
187
+ * Fields the owner marked to protect. Taken from the last signed bundle even when it is out of date, since it
188
+ * only ever adds protection; with none, the names Cognolo recognises still are.
189
+ */
190
+ protect?(): {
191
+ hide: string[];
192
+ mask: string[];
193
+ };
194
+ /**
195
+ * The tools that need a passkey beyond the irreversible ones, from the last verified bundle even once it's out
196
+ * of date (it only adds); whether the owner let this environment approve them with a click, and the irreversible tools
197
+ * the owner let a click approve (both from a live bundle only).
198
+ */
199
+ passkey?(): {
200
+ tools: string[];
201
+ clickOnly: boolean;
202
+ clickTools?: string[];
203
+ };
204
+ /** Task 124: whether people's own AI may come in here, and the reads it may use; off with no live bundle. */
205
+ /** `changes`: which changes people's own AI may ask for (`outsideMayAsk`); missing means none. */
206
+ outside?(): {
207
+ on: boolean;
208
+ tools: string[];
209
+ ack: number;
210
+ changes?: {
211
+ all: boolean;
212
+ tools: Record<string, "ask" | "ask-irreversible" | "never">;
213
+ perHour?: number;
214
+ };
215
+ };
216
+ /** The fuse on people's own AI tripped here: the codes of the people whose AI read the most, and whether it now stays off. Counts and codes only. */
217
+ reportFuse?(t: {
218
+ top: string[];
219
+ stopped: boolean;
220
+ }): void;
221
+ /**
222
+ * Reads that don't name the records they return (no `refs`), as people have opened them since this server started, so
223
+ * the owner sees they can't be offered to people's own AI. Names only; sent with the heartbeat.
224
+ */
225
+ noteUnnamedReads?(names: string[]): void;
226
+ /** Whether passkeys are asked for here, and if not why, for the owner's Safety check. Sent with the heartbeat. */
227
+ /** `firstSetup`: how a person's first passkey is trusted. `held`: Production with no fresh sign-in, so none can be set up and changes that need one wait. */
228
+ reportPasskeys?(r: {
229
+ mode: "passkey" | "click-only";
230
+ why?: "no-table" | "no-address" | "owner";
231
+ firstSetup: "fresh" | "trust" | "held";
232
+ }): void;
233
+ /** A passkey was set up. Only these facts go, never who or the key. */
234
+ notePasskey?(s: {
235
+ synced: boolean;
236
+ aaguid: string;
237
+ firstSetup: "fresh" | "trust" | "added";
238
+ }): void;
239
+ /**
240
+ * The owner's model for this environment, from the last signed bundle even once it's out of date, so a short
241
+ * outage never switches models mid-day; null before any bundle (the app's own model then).
242
+ */
243
+ model?(): {
244
+ model: string;
245
+ effort?: "low" | "medium" | "high";
246
+ } | null;
247
+ /** Whether the owner's model choice applies here: "pinned" when code or COGNOLO_MODEL fixes it, "own" for the app's own model client. */
248
+ reportModelChoice?(state: "applies" | "pinned" | "own"): void;
249
+ /** Sends one request line the person chose to send. Only the line and the environment go. Never throws; false when not taken. */
250
+ suggest?(line: string): Promise<boolean>;
251
+ /** The conversation filter here, from the last verified bundle (kept after it expires): `off` unless the owner chose `watching` or `stopping`. */
252
+ filter?(): "off" | "watching" | "stopping";
253
+ /** Counts a flag raised, or one ended early, for the owner's view. Only the kind goes: no text, no person. */
254
+ noteFilter?(kind: "flagged" | "released"): void;
255
+ /** One question asked (a person's message, or a workflow started, that reached the AI). Counted by the cloud against the plan; carries nothing of what was asked. */
256
+ asked?(work: "chat" | "workflow" | "outside", who?: string, outside?: {
257
+ via: OutsideDoor;
258
+ id: string;
259
+ }): void;
260
+ /**
261
+ * The owner's look for the panel, from the last verified bundle (kept after it expires: it grants nothing, and should not
262
+ * flip mid-conversation on a short outage), minus what the app locked. Null before any bundle. Reads memory only.
263
+ */
264
+ look(): {
265
+ version: number;
266
+ look: CloudLook;
267
+ } | null;
268
+ /** Remember whether the panel's credit was seen on screen, and tell the cloud with the next heartbeat (soon, if it changed). */
269
+ reportCredit(state: "shown" | "hidden"): void;
270
+ /** Whether the AI provider accepted the model key on the last call (`refused`: it turned it down). Told to the cloud with the next heartbeat (soon, if it changed). Never the key. */
271
+ reportModelKey?(state: "ok" | "refused"): void;
272
+ /**
273
+ * Check for rules once now, then send a heartbeat every `heartbeatMs` (and any waiting events), so the dashboard knows
274
+ * the app is alive. It never checks for rules on a timer: use does that. Does not keep the process alive. A server
275
+ * without timers can skip this: each use that finds the last heartbeat older than `heartbeatMs` sends one.
276
+ */
277
+ start(): void;
278
+ stop(): void;
279
+ status(): CloudStatus;
280
+ }
281
+ export declare const LOCAL: Set<string>;
282
+ /** The panel's usage ring: the business's allowance used, in steps of 5%. */
283
+ export type UsageMeter = {
284
+ plan: string;
285
+ stops: boolean;
286
+ testing?: boolean;
287
+ questions: {
288
+ pct: number;
289
+ of: number;
290
+ };
291
+ actions?: {
292
+ pct: number;
293
+ of: number;
294
+ };
295
+ today?: {
296
+ pct: number;
297
+ of: number;
298
+ };
299
+ resets: string;
300
+ };
301
+ export declare function cognoloCloud<C = unknown>(o: CloudOptions): CognoloCloud<C>;