copilotz 1.0.0-rc.54 → 1.0.0-rc.56

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 (53) hide show
  1. package/AGENTS.md +61 -6
  2. package/CHANGELOG.md +94 -0
  3. package/README.md +2 -2
  4. package/hosts/web/mod.d.ts +1 -1
  5. package/hosts/web/mod.js +1 -1
  6. package/hosts/web/pt-br/chat.js +4 -0
  7. package/hosts/web/words.d.ts +7 -0
  8. package/hosts/web/words.js +10 -0
  9. package/package.json +1 -1
  10. package/plugins/access/accounts/actions/model-key.js +41 -13
  11. package/plugins/access/accounts/collections/model-key.d.ts +22 -4
  12. package/plugins/access/accounts/collections/model-key.js +31 -6
  13. package/plugins/access/accounts/shared/rules.js +5 -4
  14. package/plugins/access/accounts/views/web/accounts.js +3 -1
  15. package/plugins/access/accounts/views/web/own-keys.d.ts +12 -0
  16. package/plugins/access/accounts/views/web/own-keys.js +112 -0
  17. package/plugins/access/accounts/views/web/style.d.ts +1 -1
  18. package/plugins/access/accounts/views/web/style.js +17 -0
  19. package/plugins/access/accounts/web.d.ts +2 -1
  20. package/plugins/access/accounts/web.js +4 -1
  21. package/plugins/access/spaces/shared/agents.d.ts +12 -5
  22. package/plugins/access/spaces/shared/agents.js +19 -2
  23. package/plugins/access/spaces/views/web/agents.js +2 -1
  24. package/plugins/agents/chat/actions/welcomed.d.ts +1 -0
  25. package/plugins/agents/chat/actions/welcomed.js +20 -0
  26. package/plugins/agents/chat/collections/welcome.d.ts +23 -0
  27. package/plugins/agents/chat/collections/welcome.js +27 -0
  28. package/plugins/agents/chat/contract.d.ts +1 -1
  29. package/plugins/agents/chat/mod.js +14 -2
  30. package/plugins/agents/chat/processors/turn.js +6 -4
  31. package/plugins/agents/chat/shared/agents.d.ts +8 -6
  32. package/plugins/agents/chat/shared/agents.js +18 -22
  33. package/plugins/agents/chat/shared/types.d.ts +35 -1
  34. package/plugins/agents/chat/views/web/composer.d.ts +3 -1
  35. package/plugins/agents/chat/views/web/composer.js +4 -1
  36. package/plugins/agents/chat/views/web/conversation.js +1 -1
  37. package/plugins/agents/chat/views/web/home.d.ts +4 -1
  38. package/plugins/agents/chat/views/web/home.js +18 -1
  39. package/plugins/agents/chat/views/web/style.d.ts +1 -1
  40. package/plugins/agents/chat/views/web/style.js +2 -0
  41. package/plugins/agents/chat/views/web/welcome.d.ts +25 -0
  42. package/plugins/agents/chat/views/web/welcome.js +44 -0
  43. package/plugins/agents/chat/views/web/words.d.ts +1 -1
  44. package/plugins/agents/chat/views/web/words.js +5 -0
  45. package/plugins/compute/computers/program/version.d.ts +1 -1
  46. package/plugins/compute/computers/program/version.js +1 -1
  47. package/plugins/compute/computers/program/workloads/search.d.ts +1 -1
  48. package/plugins/compute/computers/resources/downloads.js +1 -1
  49. package/plugins/models/shared/choice.d.ts +4 -1
  50. package/plugins/models/shared/use.d.ts +3 -2
  51. package/plugins/models/shared/use.js +9 -3
  52. package/runtime/owner.d.ts +6 -0
  53. package/runtime/owner.js +15 -3
package/AGENTS.md CHANGED
@@ -4,7 +4,7 @@ A guide for coding agents (Claude Code, Codex, Cursor, Gemini) building an app w
4
4
  it whole before you write code. The last section is for work on Copilotz itself.
5
5
 
6
6
  It ships in the package (`node_modules/copilotz/AGENTS.md`, and `@copilotz/copilotz` on JSR) and
7
- goes with `copilotz@1.0.0-rc.54`. Every docs page is Markdown at
7
+ goes with `copilotz@1.0.0-rc.56`. Every docs page is Markdown at
8
8
  `https://copilotz.com/docs/<slug>.md`, and https://copilotz.com/llms.txt lists them all. When you're
9
9
  unsure of a name, fetch its page or read the package's types (`node_modules/copilotz/**/*.d.ts`).
10
10
  Don't guess.
@@ -64,12 +64,12 @@ There's no project generator. Set a project up as the docs' courses do, on Node
64
64
  ```sh
65
65
  mkdir my-app && cd my-app
66
66
  npm init -y && npm pkg set type=module
67
- npm install copilotz@1.0.0-rc.54 react@19 react-dom@19
67
+ npm install copilotz@1.0.0-rc.56 react@19 react-dom@19
68
68
  npm install -D typescript @types/node @types/react @types/react-dom esbuild
69
69
  ```
70
70
 
71
71
  Pin the version: npm's `latest` tag still points at an early release candidate. On Deno, run
72
- `deno add jsr:@copilotz/copilotz` and map `"copilotz": "jsr:@copilotz/copilotz@^1.0.0-rc.54"` in
72
+ `deno add jsr:@copilotz/copilotz` and map `"copilotz": "jsr:@copilotz/copilotz@^1.0.0-rc.56"` in
73
73
  `deno.json`, so imports read the same.
74
74
 
75
75
  Node runs `.ts` files as they are, so there's no build step. It doesn't run `.tsx`: tests that load
@@ -110,7 +110,7 @@ line `@AGENTS.md` (Claude Code reads `CLAUDE.md`, and follows the import). Keep
110
110
  ```markdown
111
111
  # AGENTS.md
112
112
 
113
- This app runs on Copilotz (copilotz@1.0.0-rc.54). Read node_modules/copilotz/AGENTS.md first;
113
+ This app runs on Copilotz (copilotz@1.0.0-rc.56). Read node_modules/copilotz/AGENTS.md first;
114
114
  https://copilotz.com/llms.txt lists the docs, as Markdown.
115
115
 
116
116
  - `npm test` runs every test offline, with a scripted model: run it after each change.
@@ -329,6 +329,61 @@ Test what callers may not do as well: call as someone else, and `assert.rejects`
329
329
  - **Online:** `devSignIn` is for this machine only; Copilotz won't start it with a public origin.
330
330
  Keep the `links` secret (32 bytes or more) across restarts, or MCP conversations start over.
331
331
 
332
+ ## The record and bytes
333
+
334
+ **The record lasts as the store does.** Each commit appends its events to the `events` table, and
335
+ the runtime never changes or deletes one. An event is `{ seq, id, type, data, cause, actor, at }`:
336
+ `cause` is the event behind it, `actor` the whole actor (`for`, `in`, `via`), `at` its commit's
337
+ time. `action.started` holds `{ action, input, inputHash, startedAt, attempt }`, `action.completed`
338
+ the `result`, a collection's event `{ _id, doc }`. Read it with `store.events(afterSeq, limit)` in a
339
+ test or script, `runtime.subscribe` live, or SQL (`sqlite3`, `psql`,
340
+ [maintenance](https://copilotz.com/docs/operations/maintenance.md)). Plugin code reads no log.
341
+
342
+ **Kept out:** a collection's `private` fields (keys, tokens), an Action's `private` fields, an
343
+ unrecorded Action's call (`record: false`; not its writes), and collections with `events: false` or
344
+ `durable: false`. All else an Action is given stays for good.
345
+
346
+ **Large values.** A string over 16 KiB is a blob, stored once by its hash: documents and events keep
347
+ a reference, and reads load it whole unless a `projection` leaves the field out. Blobs live in the
348
+ store, or in files or a bucket (`createRuntime({ blobs })`), chosen before it fills. A file is a
349
+ string (a `data:` address, base64). Nothing deletes a blob: a value deleted or replaced stays on the
350
+ record. [Stores](https://copilotz.com/docs/operations/stores.md) and
351
+ [BC 36](https://copilotz.com/docs/build-compass/part-12-shipping/36-postgresql-and-blobs.md) have
352
+ the rest.
353
+
354
+ **A list reads names, not pictures:** its query leaves them out (`projection: { picture: 0 }`), and
355
+ each row shows `/pictures/<id>`, a route that checks who asks before it reads. With `{ actor }`,
356
+ `runtime.bytes` reads only where a rule speaks for the collection (else it's refused); `service` has
357
+ none, so it's read as the system:
358
+
359
+ ```ts
360
+ import { definePlugin, people } from "copilotz";
361
+
362
+ const PICTURE = /^data:(image\/(?:png|jpeg|gif|webp));base64,(.+)$/;
363
+
364
+ export const pictures = definePlugin({
365
+ name: "pictures",
366
+ routes: {
367
+ "/pictures/:id": async (_request, { runtime, actor, params }) => {
368
+ const none = new Response("Not found", { status: 404 });
369
+ if (!people(actor)) return none;
370
+ const kept = await runtime.bytes("service", { _id: params.id }, "picture");
371
+ if (!kept) return none;
372
+ const text = new TextDecoder().decode(await kept.read(0, kept.size));
373
+ const [, type, base64] = PICTURE.exec(text) ?? [];
374
+ if (!base64) return none;
375
+ const body = Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));
376
+ return new Response(body, {
377
+ headers: { "content-type": type, "x-content-type-options": "nosniff" },
378
+ });
379
+ },
380
+ },
381
+ });
382
+ ```
383
+
384
+ **Common mistakes:** a list reading pictures whole; a key in an Action's input or in a field that
385
+ isn't `private`; a route reading before it checks who asks; counting on a delete to erase a file.
386
+
332
387
  ## A business app's web front end
333
388
 
334
389
  Screens for people at work: lists, forms in dialogs, dates, a home, printed documents.
@@ -455,8 +510,8 @@ The pieces, by job:
455
510
  - **File and image inputs:** `FileInput` (`accept`; `chooseLabel`, `changeLabel`, `removeLabel`;
456
511
  `current` and `onRemove` for a stored file). A picture chosen shows in an `Avatar`
457
512
  (`picture={URL.createObjectURL(file)}`, `initial={false}`). The form sends it to an Action as a
458
- `data:` address, the Action `private: ["picture"]` so its record doesn't keep it twice; big files
459
- are served by a route with `runtime.bytes`.
513
+ `data:` address; `private: ["picture"]` keeps it out of the call's record, and a list shows it
514
+ from a route (The record and bytes).
460
515
 
461
516
  **Common mistakes:**
462
517
 
package/CHANGELOG.md CHANGED
@@ -1,3 +1,97 @@
1
+ ## 1.0.0-rc.56 — 2026-11-18
2
+
3
+ A security fix: `runtime.bytes` no longer serves an outside actor what no rule speaks for. And the
4
+ docs of the record and bytes.
5
+
6
+ **Security:**
7
+
8
+ - **`runtime.bytes` reads for an actor only where a rule speaks for them.** With `{ actor }`, it
9
+ read under the rules, but a collection no rule speaks for has nothing to narrow, so it answered
10
+ any actor, the anonymous one too: a route of the app's that didn't check who asked served such a
11
+ collection's files to anyone. Now an actor (anyone but the system) reads only a collection a rule
12
+ speaks for, and their scope (a key's) lists, as their own reads from outside do; elsewhere, and in
13
+ `sys.*`, it's refused (`forbidden`). Without an actor, or as a grant, it reads as the system, as
14
+ before. Chat's `/files/<id>` is unchanged for people and contacts; a key now needs
15
+ `read: ["file"]` in its scope to fetch a file there. **Upgrading:** a route that passes
16
+ `{ actor }` for a collection with no rule (`shared` or a `guard`) is now refused: check who asks
17
+ in the route, then read as the system.
18
+
19
+ **Docs:**
20
+
21
+ - **Docs: the record and bytes.** AGENTS.md says what the record keeps and how to read it back, what
22
+ stays out of it (`private`, `record: false`, keys), where large values go (blobs, kept once by
23
+ hash, never deleted) and how a route serves one with `runtime.bytes`, once it has checked who
24
+ asks. Stores, the business app's guide (pictures in a list), Build Compass chapter 36 and Events
25
+ say the rest.
26
+
27
+ ## 1.0.0-rc.55 — 2026-11-18
28
+
29
+ What an app's first minutes ask of Copilotz: a welcome, a team people can shape, models chosen by
30
+ budget rather than agent by agent, and keys of a person's own.
31
+
32
+ **Breaking, in small ways:**
33
+
34
+ - **Tiers are templates; agents hold no model where tiers apply.** Each agent does a kind of work
35
+ (one of the app's: a tier's keys, titled by the new `tierKinds` resource; or the org's own), and
36
+ the tier in force gives that kind its model chain. Agents people make do a kind too (`like`), no
37
+ longer keeping a model of their own. `tiers.pick` and per-agent picks (`modelChoice.custom`) are
38
+ gone: an org changes a tier's chain for a kind (`tiers.save`), for every agent of that kind. With
39
+ no tier chosen anywhere, the app's first applies.
40
+ - **`modelChoice.offered` answers by kind of work**: each tier's `kinds` (in place of `agents`),
41
+ `kinds` with the app's agents of each, `removed`, and `now` as `{ tier, by }`. `modelChoice.agent`
42
+ answers an agent's kind, the tier in force and its chain. The page prices a typical **message**
43
+ where the app measured one (`typicalMessage`), else a reply.
44
+ - **`agentsNamed` asks `agentSources` first**: a source's answer for one of the app's agents is an
45
+ org's own version of it, over the app's.
46
+
47
+ **Which tier, and an org's own tiers:**
48
+
49
+ - **Every conversation runs on a tier**, the first that applies: the conversation's, the person's
50
+ own default for new chats, the space's, the org's, the plan's (`tiers.choose { thread }`,
51
+ `{ mine }`, `{ space }`, `{}`). Chat passes the conversation to `agentModel`.
52
+ - **An org's tiers:** its version of one of the app's (a kind's chain, its name), new ones made from
53
+ another (`tiers.save`), the app's taken away and put back (`tiers.remove`, `tiers.restore`), kinds
54
+ of work of its own based on the app's (`tiers.kind`), and a cap on what its members choose
55
+ (`tiers.cap`). A chain set by hand keeps the `maxTokens` and `effort` of the one it replaces.
56
+ - **A typical message, measured** (`typicalMessage`: each agent's calls and tokens per message) and
57
+ **what the plan gives** (`planCredits`, credits' new `billing.credits`): the tiers say what a
58
+ message comes to, and how far the credits go. A ChatGPT-plan entry is priced at the next that
59
+ costs something.
60
+ - **On the web:** the org's Agents page (tier cards with each kind's model and fallbacks, Customize,
61
+ New tier, the members' cap, and on Free how much faster a heavier tier spends), a tier picker
62
+ beside the send button (chat's new `composerControls`), a space's default tier, and `tiers.setup`,
63
+ a short choice for a new org. Every word is the app's (`tiers.<key>`).
64
+
65
+ **The org's team** (`@copilotz/team`):
66
+
67
+ - **Every org starts with the app's agents; its owners and admins shape them.** Changing one keeps
68
+ the org's version under its name (`agent.update`); `agent.delete` takes it off the team (it leaves
69
+ every space, joins no new one), `agent.restore` puts it back, `agent.reset` drops the org's
70
+ changes. An agent made for the org (`in: "*"`) works in every space and joins new ones. Spaces
71
+ seat the org's team as they're made.
72
+ - **Making an agent starts from what it should do:** `agent.sketch` drafts its name, emoji,
73
+ description, instructions and kind of work in one quick call (the app's `cheap` model), for the
74
+ person to check; the form asks for a kind of work instead of a model where tiers apply.
75
+ - **An agent proposes one** (`propose_agent`): its person is asked as chat asks for everything, and
76
+ it's made only on their yes, where they could have made it themselves.
77
+
78
+ **A welcome, and keys of one's own:**
79
+
80
+ - **Chat's `welcome`:** steps an app and its front ends add (a View each, with roles and kinds of
81
+ org), shown once per person per org over home, in a dialog; `/?welcome=1` shows it again
82
+ (`chat.welcomed`, `welcome.seen`). Credits adds a plan step for a new team org (`billing.setup`),
83
+ whose payment page comes back to the welcome (`billing.checkout`'s new `back`).
84
+ - **A person's own API keys** (`modelKey.set { mine }`): any provider a key can be brought for; a
85
+ model call for them uses theirs, then the org's, then the app's. The Connected accounts page lists
86
+ them, and says where the org's tiers use each provider's models.
87
+
88
+ **Words:**
89
+
90
+ - **`sayText`** (`copilotz/web/words`): text the app's data holds, in the app's words where it gives
91
+ them under `text.` and the English (a tier's description, a kind of work, an agent's description);
92
+ else as it is. The tiers' and team's pages say them so.
93
+ - **The tiers' prices follow the page's language** ("2,3¢" in Portuguese).
94
+
1
95
  ## 1.0.0-rc.54 — 2026-11-17
2
96
 
3
97
  What a business app's screens still asked of the toolkit and of e-mail, and the docs that show a
package/README.md CHANGED
@@ -152,7 +152,7 @@ ana sees: Tue 10:00, Wed 15:00
152
152
  ```sh
153
153
  npm install copilotz@next # Node 24+ (npm, pnpm, yarn)
154
154
  bun add copilotz@next # Bun
155
- deno add jsr:@copilotz/copilotz@^1.0.0-rc.54 # Deno 2.9+ (or `deno add npm:copilotz@next`)
155
+ deno add jsr:@copilotz/copilotz@^1.0.0-rc.56 # Deno 2.9+ (or `deno add npm:copilotz@next`)
156
156
  ```
157
157
 
158
158
  Until 1.0, the release candidates are on npm's `next` tag, and a plain `npm install copilotz` or
@@ -166,7 +166,7 @@ OPENAI_API_KEY=sk-… node salon.ts # or bun salon.ts, or deno run -A salon.t
166
166
  ```
167
167
 
168
168
  On Deno, map the name `copilotz` in `deno.json`
169
- (`"copilotz": "jsr:@copilotz/copilotz@^1.0.0-rc.54"`) so the imports read the same everywhere.
169
+ (`"copilotz": "jsr:@copilotz/copilotz@^1.0.0-rc.56"`) so the imports read the same everywhere.
170
170
  Copilotz runs on Node 24+, Deno 2.9+ and Bun, and it's built on web standards for Cloudflare Workers
171
171
  and the browser.
172
172
 
@@ -11,7 +11,7 @@
11
11
  */
12
12
  export { go, signOut, web, type WebOptions, type Where, type Who } from "./host.js";
13
13
  export { appBase } from "./base.js";
14
- export { type Blanks, defineWords, fill, formatDate, formatDateTime, formatList, formatNumber, formatTime, knownWords, lang, type Phrase, type Say, setWords, type Words, wordsOf, } from "./words.js";
14
+ export { type Blanks, defineWords, fill, formatDate, formatDateTime, formatList, formatNumber, formatTime, knownWords, lang, type Phrase, type Say, sayText, setWords, type Words, wordsOf, } from "./words.js";
15
15
  export { message, node, Part } from "./part.js";
16
16
  export { display, type DisplayMode, openLink, remind, surface, tell, useRefresh, } from "./surface.js";
17
17
  export { LazyView } from "./lazy.js";
package/hosts/web/mod.js CHANGED
@@ -12,7 +12,7 @@
12
12
  export { go, signOut, web } from "./host.js";
13
13
  export { appBase } from "./base.js";
14
14
  // The words every front end says, by key: the app's `words` resource over the English.
15
- export { defineWords, fill, formatDate, formatDateTime, formatList, formatNumber, formatTime, knownWords, lang, setWords, wordsOf, } from "./words.js";
15
+ export { defineWords, fill, formatDate, formatDateTime, formatList, formatNumber, formatTime, knownWords, lang, sayText, setWords, wordsOf, } from "./words.js";
16
16
  export { message, node, Part } from "./part.js";
17
17
  // Where Views are drawn (the page, or a widget in an outside assistant), and what a widget asks of
18
18
  // its host: no-ops on the page.
@@ -161,6 +161,10 @@ export const chat = {
161
161
  "chat.notFoundTitle": "Conversa não encontrada",
162
162
  "chat.notInSpace": "Você não está neste espaço",
163
163
  "chat.notInSpaceBody": "As conversas daqui são para os membros. Escolha um dos seus espaços para começar uma, ou peça a alguém daqui para convidar você.",
164
+ "chat.welcomeStep": "{at} de {count}",
165
+ "chat.welcomeBack": "Voltar",
166
+ "chat.welcomeNext": "Próximo",
167
+ "chat.welcomeDone": "Começar",
164
168
  "chat.notYourSpaceTitle": "Este espaço não é seu",
165
169
  "chat.ofMinutes": {
166
170
  one: ", de no máximo {count} minuto",
@@ -60,6 +60,13 @@ export declare const fill: (text: string, blanks: Blanks) => string;
60
60
  export declare function wordsOf(plugins: Plugins): Words;
61
61
  /** Sets the words the page says (`web` does, from its plugins); returns how to put back what was. */
62
62
  export declare function setWords(words: Words): () => void;
63
+ /**
64
+ * Text the app's data holds, in the app's words when it gives them: what the server sends as the
65
+ * app declared it (a tier's description, a kind of work's title, an agent's description). The
66
+ * app gives them under `text.` and the English as it is (`"text.Quick answers.": "Respostas
67
+ * rápidas."`); text it gives none for (one an org wrote) shows as it is.
68
+ */
69
+ export declare function sayText(text: string): string;
63
70
  /** Every key Copilotz's front ends define (those loaded), with its English. */
64
71
  export declare const knownWords: () => Record<string, Phrase>;
65
72
  /** The page's language (its `<html lang>`), English unless said. */
@@ -98,6 +98,16 @@ export function setWords(words) {
98
98
  given = before;
99
99
  };
100
100
  }
101
+ /**
102
+ * Text the app's data holds, in the app's words when it gives them: what the server sends as the
103
+ * app declared it (a tier's description, a kind of work's title, an agent's description). The
104
+ * app gives them under `text.` and the English as it is (`"text.Quick answers.": "Respostas
105
+ * rápidas."`); text it gives none for (one an org wrote) shows as it is.
106
+ */
107
+ export function sayText(text) {
108
+ const phrase = given[`text.${text}`];
109
+ return phrase === undefined ? text : render(phrase);
110
+ }
101
111
  /** Every key Copilotz's front ends define (those loaded), with its English. */
102
112
  export const knownWords = () => Object.fromEntries(english);
103
113
  /** The page's language (its `<html lang>`), English unless said. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "copilotz",
3
- "version": "1.0.0-rc.54",
3
+ "version": "1.0.0-rc.56",
4
4
  "description": "The open-source runtime that makes your app usable by people, your own agents and their assistants.",
5
5
  "keywords": [
6
6
  "agents",
@@ -2,8 +2,14 @@
2
2
  * An org's own keys for model providers (see collections/model-key.ts), as the
3
3
  * models plugin's `modelKeys` resource names them. Its owners and admins change
4
4
  * them, in person: `modelKey.set` `{ provider, key }` and `modelKey.remove`
5
- * `{ provider }`; `modelKey.may` says whether the person asking can. For
6
- * trusted code only: `modelKey.list` (nothing secret) and `modelKey.open`.
5
+ * `{ provider }`; `modelKey.may` says whether the person asking can.
6
+ *
7
+ * A person's own (`mine`): any person keeps keys of their own the same way
8
+ * (`modelKey.set { provider, key, mine: true }`, `modelKey.remove { …, mine }`),
9
+ * listed to them alone (`modelKey.mine`); a model call for them (made by them,
10
+ * or an agent working for them) uses theirs first, then the org's, then the
11
+ * app's. For trusted code only: `modelKey.list` (the org's, nothing secret)
12
+ * and `modelKey.open` `{ provider, person? }`.
7
13
  *
8
14
  * All unrecorded: a key is in no event, as its input or its answer.
9
15
  */
@@ -12,8 +18,10 @@ import { runsOrg } from "../../spaces/contract.js";
12
18
  import { seal, unseal } from "../shared/seal.js";
13
19
  import { settingsOf } from "../shared/settings.js";
14
20
  const keysOf = (ctx) => ctx.as().db.collection("modelKey");
15
- /** What a sealed key is bound to, so it can't be moved to another provider or org. */
16
- const boundTo = (ctx, provider) => `modelKey:${ctx.resources.org?.id ?? ""}:${provider}`;
21
+ /** What a sealed key is bound to, so it can't be moved to another provider, org or person. */
22
+ const boundTo = (ctx, provider, person) => `modelKey:${ctx.resources.org?.id ?? ""}:${person ? `person:${person}:` : ""}${provider}`;
23
+ /** Where a person's own key for a provider is kept. */
24
+ const ownId = (person, provider) => `person:${person}:${provider}`;
17
25
  /** Whether whoever asks runs the org: only they change its keys. */
18
26
  const runs = (ctx) => ctx.call("org.me", {})
19
27
  .then((me) => !!me.staff || runsOrg(me.role ?? null), () => false);
@@ -21,33 +29,45 @@ const SHOW = 4;
21
29
  /** A long key's last characters, to tell it apart; a short one shows nothing of itself. */
22
30
  const hintOf = (key) => key.length >= 16 ? `••••${key.slice(-SHOW)}` : "••••";
23
31
  export const modelKeySet = defineAction({
24
- description: "Adds or replaces the org's own key for a model provider",
32
+ description: "Adds or replaces a key for a model provider: the org's, or your own (mine)",
25
33
  record: false,
26
34
  input: {
27
35
  type: "object",
28
36
  properties: {
29
37
  provider: { type: "string" },
30
38
  key: { type: "string", minLength: 1, maxLength: 4096 },
39
+ /** Your own, used when agents work for you; else the org's. */
40
+ mine: { type: "boolean" },
31
41
  },
32
42
  required: ["provider", "key"],
33
43
  additionalProperties: false,
34
44
  },
35
45
  allow: inPerson,
36
46
  run: async (ctx, input) => {
37
- if (!await runs(ctx))
47
+ const person = input.mine ? ctx.actor.id : undefined;
48
+ if (!person && !await runs(ctx)) {
38
49
  throw forbidden("Only the org's owners and admins change its keys.");
50
+ }
39
51
  if (!await ctx.call("models.keyable", { provider: input.provider })) {
40
52
  throw invalid(`A key can't be added for "${input.provider}".`);
41
53
  }
42
54
  const key = input.key.trim();
43
55
  if (!key || /\s/.test(key))
44
56
  throw invalid("That doesn't look like a key.");
45
- const sealed = await seal(settingsOf(ctx).key, boundTo(ctx, input.provider), {
57
+ const sealed = await seal(settingsOf(ctx).key, boundTo(ctx, input.provider, person), {
46
58
  access: key,
47
59
  account: input.provider,
48
60
  });
49
61
  const hint = hintOf(key);
50
- await keysOf(ctx).updateOne({ _id: input.provider }, { $set: { sealed, hint, by: ctx.actor.id, at: new Date().toISOString() } }, { upsert: true });
62
+ await keysOf(ctx).updateOne({ _id: person ? ownId(person, input.provider) : input.provider }, {
63
+ $set: {
64
+ sealed,
65
+ hint,
66
+ by: ctx.actor.id,
67
+ ...(person ? { person, provider: input.provider } : {}),
68
+ at: new Date().toISOString(),
69
+ },
70
+ }, { upsert: true });
51
71
  return { provider: input.provider, hint };
52
72
  },
53
73
  });
@@ -56,12 +76,16 @@ export const modelKeyRemove = defineAction({
56
76
  record: false,
57
77
  input: {
58
78
  type: "object",
59
- properties: { provider: { type: "string" } },
79
+ properties: { provider: { type: "string" }, mine: { type: "boolean" } },
60
80
  required: ["provider"],
61
81
  additionalProperties: false,
62
82
  },
63
83
  allow: inPerson,
64
84
  run: async (ctx, input) => {
85
+ if (input.mine) {
86
+ await keysOf(ctx).deleteOne({ _id: ownId(ctx.actor.id, input.provider) });
87
+ return { removed: true };
88
+ }
65
89
  if (!await runs(ctx))
66
90
  throw forbidden("Only the org's owners and admins change its keys.");
67
91
  await keysOf(ctx).deleteOne({ _id: input.provider });
@@ -79,7 +103,7 @@ export const modelKeyMay = defineAction({
79
103
  export const modelKeyList = defineAction({
80
104
  record: false,
81
105
  input: { type: "object", additionalProperties: false },
82
- run: async (ctx) => (await keysOf(ctx).find({})).map((k) => ({
106
+ run: async (ctx) => (await keysOf(ctx).find({ person: { $exists: false } })).map((k) => ({
83
107
  provider: k._id,
84
108
  ...(k.hint ? { hint: k.hint } : {}),
85
109
  })),
@@ -88,15 +112,19 @@ export const modelKeyOpen = defineAction({
88
112
  record: false,
89
113
  input: {
90
114
  type: "object",
91
- properties: { provider: { type: "string" } },
115
+ properties: { provider: { type: "string" }, person: { type: "string" } },
92
116
  required: ["provider"],
93
117
  additionalProperties: false,
94
118
  },
95
119
  run: async (ctx, input) => {
96
- const found = await keysOf(ctx).findOne({ _id: input.provider });
120
+ // The person's own first, then the org's.
121
+ const own = input.person
122
+ ? await keysOf(ctx).findOne({ _id: ownId(input.person, input.provider) })
123
+ : null;
124
+ const found = own ?? await keysOf(ctx).findOne({ _id: input.provider });
97
125
  if (!found)
98
126
  return null;
99
- const { access } = await unseal(settingsOf(ctx).key, boundTo(ctx, input.provider), found.sealed);
127
+ const { access } = await unseal(settingsOf(ctx).key, boundTo(ctx, input.provider, own ? input.person : undefined), found.sealed);
100
128
  return access;
101
129
  },
102
130
  });
@@ -1,8 +1,10 @@
1
1
  /**
2
- * An org's own key for a model provider (`_id`, the provider's id): sealed, in
3
- * a private field, as an account's tokens are, with its last characters to tell
4
- * it apart. Nobody reads the collection: `modelKey.list` says what's kept, and
5
- * `modelKey.open` opens one for a model call.
2
+ * An org's own key for a model provider (`_id`, the provider's id), or a
3
+ * person's own (`person:<id>:<provider>`, with `person` and `provider`):
4
+ * sealed, in a private field, as an account's tokens are, with its last
5
+ * characters to tell it apart. Nobody reads the collection: `modelKey.list`
6
+ * says what the org keeps, the query `mine` what the person asking keeps
7
+ * (never the key), and `modelKey.open` opens one for a model call.
6
8
  */
7
9
  import { type Infer } from "../../../../runtime/mod.js";
8
10
  declare const modelKeySchema: {
@@ -11,6 +13,13 @@ declare const modelKeySchema: {
11
13
  readonly hint: {
12
14
  readonly type: "string";
13
15
  };
16
+ /** A person's own: whose, and for which provider. */
17
+ readonly person: {
18
+ readonly type: "string";
19
+ };
20
+ readonly provider: {
21
+ readonly type: "string";
22
+ };
14
23
  readonly by: {
15
24
  readonly type: "string";
16
25
  };
@@ -27,6 +36,13 @@ export declare const modelKey: {
27
36
  readonly hint: {
28
37
  readonly type: "string";
29
38
  };
39
+ /** A person's own: whose, and for which provider. */
40
+ readonly person: {
41
+ readonly type: "string";
42
+ };
43
+ readonly provider: {
44
+ readonly type: "string";
45
+ };
30
46
  readonly by: {
31
47
  readonly type: "string";
32
48
  };
@@ -43,6 +59,8 @@ export declare const modelKey: {
43
59
  private?: string[];
44
60
  queries?: Record<string, import("../../../../runtime/define.js").QueryDef<{
45
61
  [x: string]: unknown;
62
+ person?: string | undefined;
63
+ provider?: string | undefined;
46
64
  hint?: string | undefined;
47
65
  at: string;
48
66
  by: string;
@@ -1,17 +1,42 @@
1
1
  /**
2
- * An org's own key for a model provider (`_id`, the provider's id): sealed, in
3
- * a private field, as an account's tokens are, with its last characters to tell
4
- * it apart. Nobody reads the collection: `modelKey.list` says what's kept, and
5
- * `modelKey.open` opens one for a model call.
2
+ * An org's own key for a model provider (`_id`, the provider's id), or a
3
+ * person's own (`person:<id>:<provider>`, with `person` and `provider`):
4
+ * sealed, in a private field, as an account's tokens are, with its last
5
+ * characters to tell it apart. Nobody reads the collection: `modelKey.list`
6
+ * says what the org keeps, the query `mine` what the person asking keeps
7
+ * (never the key), and `modelKey.open` opens one for a model call.
6
8
  */
7
- import { defineCollection } from "../../../../runtime/mod.js";
9
+ import { defineCollection, people, personOf } from "../../../../runtime/mod.js";
8
10
  const modelKeySchema = {
9
11
  type: "object",
10
12
  properties: {
11
13
  hint: { type: "string" },
14
+ /** A person's own: whose, and for which provider. */
15
+ person: { type: "string" },
16
+ provider: { type: "string" },
12
17
  by: { type: "string" },
13
18
  at: { type: "string" },
14
19
  },
15
20
  required: ["by", "at"],
16
21
  };
17
- export const modelKey = defineCollection({ schema: modelKeySchema, private: ["sealed"] });
22
+ export const modelKey = defineCollection({
23
+ schema: modelKeySchema,
24
+ private: ["sealed"],
25
+ queries: {
26
+ /** `mine` `{}`: the person's own keys: each provider, and its last characters. */
27
+ mine: {
28
+ allow: people,
29
+ run: async (keys, _, ctx) => {
30
+ const person = personOf(ctx.actor);
31
+ if (!person)
32
+ return [];
33
+ const found = await keys.find({ person });
34
+ return found.map((k) => ({
35
+ provider: k.provider ?? k._id,
36
+ ...(k.hint ? { hint: k.hint } : {}),
37
+ at: k.at,
38
+ }));
39
+ },
40
+ },
41
+ },
42
+ });
@@ -10,12 +10,13 @@
10
10
  import { failure } from "../../../../runtime/mod.js";
11
11
  const NOBODY = { _id: { $in: [] } };
12
12
  export const rules = (actor, { collection, access, direct }) => {
13
- if (collection === "account" && direct && access === "write") {
14
- throw failure("forbidden", "Accounts change through their Actions.", { public: true });
13
+ if ((collection === "account" || collection === "modelKey") && direct && access === "write") {
14
+ throw failure("forbidden", "Accounts and keys change through their Actions.", { public: true });
15
15
  }
16
- return collection === "account"
16
+ // A person reads their own accounts, and their own keys (never a key itself: it's private).
17
+ return collection === "account" || collection === "modelKey"
17
18
  ? actor.kind === "person" ? { person: actor.id } : NOBODY
18
- : collection === "accountFlow" || collection === "modelKey"
19
+ : collection === "accountFlow"
19
20
  ? NOBODY
20
21
  : undefined;
21
22
  };
@@ -27,7 +27,9 @@ export const accountsView = (_, ctx) => {
27
27
  if (!providers || !accounts) {
28
28
  return (_jsxs(Page, { title: TITLE, description: ABOUT, icon: "lock", density: density, children: [_jsx(Title, { text: TITLE }), style, _jsx("div", { className: "account-skeleton", "aria-busy": "true", children: _jsx(Skeleton, { height: 112, radius: "xl" }) })] }));
29
29
  }
30
- return (_jsxs(Page, { title: TITLE, description: ABOUT, icon: "lock", density: density, children: [_jsx(Title, { text: TITLE }), style, _jsx(AccountsBody, { providers: providers, accounts: accounts, query: query, call: ctx.call })] }));
30
+ // The person's own API keys, below their accounts (`accounts.keys`).
31
+ const keys = ctx.show("accounts.keys", {});
32
+ return (_jsxs(Page, { title: TITLE, description: ABOUT, icon: "lock", density: density, children: [_jsx(Title, { text: TITLE }), style, _jsx(AccountsBody, { providers: providers, accounts: accounts, query: query, call: ctx.call }), keys] }));
31
33
  };
32
34
  function AccountsBody({ providers, accounts, query, call }) {
33
35
  const asked = providers.some((p) => p.name === query.connect) ? query.connect : undefined;
@@ -0,0 +1,12 @@
1
+ /**
2
+ * The person's own API keys, on the Connected accounts page: for any provider
3
+ * a key can be brought for, theirs alone (`modelKey.set { mine }`): agents
4
+ * working for them use it for that provider's models, before the org's key and
5
+ * the app's, and the org isn't charged for those calls. Each key shows its
6
+ * last characters, and where the org's tiers use that provider's models
7
+ * ("Used for Decides and Checks on Everyday"), or that none does yet, so a key
8
+ * that would sit unused says so. Removing one is in place.
9
+ */
10
+ import { type ReactNode } from "react";
11
+ import type { ViewContext } from "../../../../../runtime/mod.js";
12
+ export declare const ownKeysView: (_: unknown, ctx: ViewContext<ReactNode>) => ReactNode;