copilotz 1.0.0-rc.12 → 1.0.0-rc.14

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 (193) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/README.md +2 -2
  3. package/hosts/orgs/mod.d.ts +3 -1
  4. package/hosts/orgs/mod.js +20 -0
  5. package/hosts/web/mod.d.ts +1 -1
  6. package/hosts/web/mod.js +1 -1
  7. package/hosts/web/orgs.d.ts +34 -0
  8. package/hosts/web/orgs.js +19 -1
  9. package/package.json +3 -3
  10. package/plugins/access/accounts/actions/model-key.d.ts +5 -0
  11. package/plugins/access/accounts/actions/model-key.js +102 -0
  12. package/plugins/access/accounts/collections/model-key.d.ts +58 -0
  13. package/plugins/access/accounts/collections/model-key.js +17 -0
  14. package/plugins/access/accounts/mod.d.ts +5 -0
  15. package/plugins/access/accounts/mod.js +14 -1
  16. package/plugins/access/accounts/resources/models.js +2 -0
  17. package/plugins/access/accounts/shared/rules.js +1 -1
  18. package/plugins/access/directory/actions/code.d.ts +4 -0
  19. package/plugins/access/directory/actions/code.js +135 -0
  20. package/plugins/access/directory/collections/credit-code.d.ts +114 -0
  21. package/plugins/access/directory/collections/credit-code.js +28 -0
  22. package/plugins/access/directory/mod.d.ts +1 -0
  23. package/plugins/access/directory/mod.js +7 -1
  24. package/plugins/access/identity/collections/credential.d.ts +1 -1
  25. package/plugins/access/spaces/actions/org.d.ts +1 -0
  26. package/plugins/access/spaces/actions/org.js +7 -0
  27. package/plugins/access/spaces/mod.js +2 -1
  28. package/plugins/agents/chat/contract.d.ts +4 -3
  29. package/plugins/agents/chat/contract.js +1 -0
  30. package/plugins/agents/chat/processors/failed.js +6 -0
  31. package/plugins/agents/chat/shared/types.d.ts +11 -0
  32. package/plugins/agents/chat/views/web/composer.d.ts +7 -2
  33. package/plugins/agents/chat/views/web/composer.js +9 -1
  34. package/plugins/agents/chat/views/web/conversation.d.ts +3 -2
  35. package/plugins/agents/chat/views/web/conversation.js +1 -1
  36. package/plugins/agents/chat/views/web/home.d.ts +3 -2
  37. package/plugins/agents/chat/views/web/home.js +1 -1
  38. package/plugins/agents/chat/views/web/message.d.ts +9 -1
  39. package/plugins/agents/chat/views/web/message.js +9 -1
  40. package/plugins/agents/chat/views/web/style.d.ts +1 -1
  41. package/plugins/agents/chat/views/web/style.js +8 -0
  42. package/plugins/agents/chat/web.d.ts +5 -1
  43. package/plugins/agents/chat/web.js +5 -1
  44. package/plugins/agents/team/views/web/agent-fields.js +3 -4
  45. package/plugins/agents/team/views/web/model-picker.d.ts +19 -0
  46. package/plugins/agents/team/views/web/model-picker.js +200 -0
  47. package/plugins/agents/team/views/web/style.d.ts +2 -2
  48. package/plugins/agents/team/views/web/style.js +48 -1
  49. package/plugins/billing/credits/actions/check.d.ts +4 -0
  50. package/plugins/billing/credits/actions/check.js +83 -0
  51. package/plugins/billing/credits/actions/manage.d.ts +9 -0
  52. package/plugins/billing/credits/actions/manage.js +266 -0
  53. package/plugins/billing/credits/actions/state.d.ts +2 -0
  54. package/plugins/billing/credits/actions/state.js +148 -0
  55. package/plugins/billing/credits/collections/credit.d.ts +110 -0
  56. package/plugins/billing/credits/collections/credit.js +31 -0
  57. package/plugins/billing/credits/collections/payment.d.ts +139 -0
  58. package/plugins/billing/credits/collections/payment.js +32 -0
  59. package/plugins/billing/credits/collections/plan.d.ts +408 -0
  60. package/plugins/billing/credits/collections/plan.js +93 -0
  61. package/plugins/billing/credits/collections/room.d.ts +85 -0
  62. package/plugins/billing/credits/collections/room.js +24 -0
  63. package/plugins/billing/credits/contract.d.ts +15 -0
  64. package/plugins/billing/credits/contract.js +11 -0
  65. package/plugins/billing/credits/mod.d.ts +30 -0
  66. package/plugins/billing/credits/mod.js +61 -0
  67. package/plugins/billing/credits/shared/apply.d.ts +66 -0
  68. package/plugins/billing/credits/shared/apply.js +102 -0
  69. package/plugins/billing/credits/shared/settings.d.ts +51 -0
  70. package/plugins/billing/credits/shared/settings.js +14 -0
  71. package/plugins/billing/credits/shared/standing.d.ts +71 -0
  72. package/plugins/billing/credits/shared/standing.js +235 -0
  73. package/plugins/billing/credits/shared/walk.d.ts +50 -0
  74. package/plugins/billing/credits/shared/walk.js +127 -0
  75. package/plugins/billing/credits/views/web/add.d.ts +25 -0
  76. package/plugins/billing/credits/views/web/add.js +92 -0
  77. package/plugins/billing/credits/views/web/budget.d.ts +16 -0
  78. package/plugins/billing/credits/views/web/budget.js +62 -0
  79. package/plugins/billing/credits/views/web/composer.d.ts +13 -0
  80. package/plugins/billing/credits/views/web/composer.js +64 -0
  81. package/plugins/billing/credits/views/web/history.d.ts +12 -0
  82. package/plugins/billing/credits/views/web/history.js +55 -0
  83. package/plugins/billing/credits/views/web/numbers.d.ts +224 -0
  84. package/plugins/billing/credits/views/web/numbers.js +250 -0
  85. package/plugins/billing/credits/views/web/org.d.ts +31 -0
  86. package/plugins/billing/credits/views/web/org.js +238 -0
  87. package/plugins/billing/credits/views/web/plan.d.ts +22 -0
  88. package/plugins/billing/credits/views/web/plan.js +65 -0
  89. package/plugins/billing/credits/views/web/staff.d.ts +20 -0
  90. package/plugins/billing/credits/views/web/staff.js +265 -0
  91. package/plugins/billing/credits/views/web/style.d.ts +9 -0
  92. package/plugins/billing/credits/views/web/style.js +186 -0
  93. package/plugins/billing/credits/views/web/types.d.ts +17 -0
  94. package/plugins/billing/credits/views/web/types.js +32 -0
  95. package/plugins/billing/credits/web.d.ts +12 -0
  96. package/plugins/billing/credits/web.js +33 -0
  97. package/plugins/billing/mod.d.ts +8 -3
  98. package/plugins/billing/mod.js +7 -3
  99. package/plugins/billing/stripe/actions/checkout.d.ts +3 -0
  100. package/plugins/billing/stripe/actions/checkout.js +171 -0
  101. package/plugins/billing/stripe/mod.d.ts +17 -0
  102. package/plugins/billing/stripe/mod.js +27 -0
  103. package/plugins/billing/stripe/shared/api.d.ts +14 -0
  104. package/plugins/billing/stripe/shared/api.js +42 -0
  105. package/plugins/billing/stripe/shared/events.d.ts +42 -0
  106. package/plugins/billing/stripe/shared/events.js +226 -0
  107. package/plugins/billing/stripe/shared/settings.d.ts +34 -0
  108. package/plugins/billing/stripe/shared/settings.js +10 -0
  109. package/plugins/billing/stripe/webhook.d.ts +17 -0
  110. package/plugins/billing/stripe/webhook.js +45 -0
  111. package/plugins/billing/usage/actions/quote.d.ts +6 -0
  112. package/plugins/billing/usage/actions/quote.js +45 -1
  113. package/plugins/billing/usage/actions/rerate.js +1 -0
  114. package/plugins/billing/usage/collections/rollup.d.ts +2 -2
  115. package/plugins/billing/usage/collections/usage.d.ts +2 -2
  116. package/plugins/billing/usage/mod.d.ts +2 -0
  117. package/plugins/billing/usage/mod.js +4 -1
  118. package/plugins/billing/usage/shared/rate.d.ts +10 -3
  119. package/plugins/billing/usage/shared/rate.js +18 -3
  120. package/plugins/billing/usage/shared/settings.d.ts +11 -1
  121. package/plugins/billing/usage/shared/use.js +5 -0
  122. package/plugins/billing/usage/views/web/org.d.ts +10 -1
  123. package/plugins/billing/usage/views/web/org.js +16 -4
  124. package/plugins/billing/web.d.ts +3 -0
  125. package/plugins/billing/web.js +3 -0
  126. package/plugins/compute/apps/actions/configure.js +2 -0
  127. package/plugins/compute/apps/shared/publish.d.ts +0 -4
  128. package/plugins/compute/apps/shared/publish.js +12 -0
  129. package/plugins/compute/cloud/actions/create.js +6 -8
  130. package/plugins/compute/cloud/actions/pool-tick.js +2 -2
  131. package/plugins/compute/cloud/actions/tick.js +13 -3
  132. package/plugins/compute/cloud/actions/vms.d.ts +0 -2
  133. package/plugins/compute/cloud/actions/vms.js +1 -3
  134. package/plugins/compute/cloud/actions/wake.js +6 -0
  135. package/plugins/compute/cloud/collections/pool-vm.d.ts +1 -1
  136. package/plugins/compute/cloud/mod.d.ts +4 -2
  137. package/plugins/compute/cloud/mod.js +7 -3
  138. package/plugins/compute/cloud/resources/tools.d.ts +3 -0
  139. package/plugins/compute/cloud/resources/tools.js +237 -0
  140. package/plugins/compute/cloud/shared/may.d.ts +15 -7
  141. package/plugins/compute/cloud/shared/may.js +19 -20
  142. package/plugins/compute/cloud/shared/meter.d.ts +3 -0
  143. package/plugins/compute/cloud/shared/meter.js +8 -3
  144. package/plugins/compute/cloud/shared/settings.d.ts +0 -5
  145. package/plugins/compute/cloud/shared/settings.js +0 -1
  146. package/plugins/compute/cloud/shared/time.d.ts +2 -0
  147. package/plugins/compute/cloud/shared/time.js +2 -0
  148. package/plugins/compute/cloud/views/web/cloud.d.ts +4 -3
  149. package/plugins/compute/cloud/views/web/cloud.js +4 -3
  150. package/plugins/compute/cloud/views/web/new.d.ts +2 -2
  151. package/plugins/compute/cloud/views/web/new.js +19 -10
  152. package/plugins/compute/cloud/web.js +3 -2
  153. package/plugins/compute/computers/actions/allowed.js +4 -2
  154. package/plugins/compute/computers/actions/approve.js +3 -2
  155. package/plugins/compute/computers/actions/env.js +2 -0
  156. package/plugins/compute/computers/program/version.d.ts +1 -1
  157. package/plugins/compute/computers/program/version.js +1 -1
  158. package/plugins/compute/computers/resources/commands.js +3 -2
  159. package/plugins/compute/computers/resources/downloads.js +1 -1
  160. package/plugins/compute/computers/shared/ask.js +9 -5
  161. package/plugins/compute/computers/shared/settings.d.ts +4 -2
  162. package/plugins/compute/computers/shared/settings.js +2 -0
  163. package/plugins/compute/computers/shared/wake.d.ts +2 -0
  164. package/plugins/compute/computers/shared/where.d.ts +5 -1
  165. package/plugins/compute/computers/shared/where.js +4 -2
  166. package/plugins/compute/computers/views/context.js +5 -1
  167. package/plugins/compute/computers/views/web/asked.js +2 -0
  168. package/plugins/compute/computers/views/web/asks.js +3 -2
  169. package/plugins/interfaces/api/collections/key.d.ts +1 -1
  170. package/plugins/interfaces/web/shared/codes.d.ts +31 -0
  171. package/plugins/interfaces/web/shared/codes.js +44 -0
  172. package/plugins/interfaces/web/shared/style.d.ts +1 -1
  173. package/plugins/interfaces/web/shared/style.js +1 -0
  174. package/plugins/interfaces/web/views/console-codes.d.ts +14 -0
  175. package/plugins/interfaces/web/views/console-codes.js +159 -0
  176. package/plugins/interfaces/web/views/console.d.ts +4 -2
  177. package/plugins/interfaces/web/views/console.js +16 -5
  178. package/plugins/interfaces/web/views/org.js +8 -2
  179. package/plugins/models/actions/offered.d.ts +34 -0
  180. package/plugins/models/actions/offered.js +186 -0
  181. package/plugins/models/contract.d.ts +5 -1
  182. package/plugins/models/mod.d.ts +6 -1
  183. package/plugins/models/mod.js +9 -1
  184. package/plugins/models/shared/catalog.json +9208 -8909
  185. package/plugins/models/shared/choice.d.ts +31 -0
  186. package/plugins/models/shared/choice.js +18 -2
  187. package/plugins/models/shared/generate.d.ts +3 -1
  188. package/plugins/models/shared/generate.js +60 -5
  189. package/plugins/models/shared/use.d.ts +6 -2
  190. package/plugins/models/shared/use.js +15 -5
  191. package/runtime/client.js +28 -5
  192. package/runtime/executor.js +2 -2
  193. package/runtime/owner.js +8 -1
package/CHANGELOG.md CHANGED
@@ -1,3 +1,44 @@
1
+ ## 1.0.0-rc.14 — 2026-11-02
2
+
3
+ - **Credits** (`plugins/billing/credits`): what an org can spend. Plans, credits and payments are
4
+ its own rows, the balance is walked from them and the ledger, and one check stops model calls,
5
+ computers and builds at the limit, in plain words. Staff set plans, give credits, waive usage or
6
+ seats, and record payments; gift codes wait in the directory.
7
+ - **Stripe** (`plugins/billing/stripe`): Checkout, the customer portal and signed webhooks, for one
8
+ or more accounts. A subscription's credits come with its paid invoice.
9
+ - **Prices:** a use on an org's own key costs nothing; a plan can name a price list; `usage.quotes`;
10
+ the model picker shows the org's real price.
11
+ - **Removed:** the cloud plugin's `create` and `budgetUsd` settings. Anyone in an org but its guests
12
+ makes a computer; what the org can spend keeps the cost.
13
+ - **Fixed:** model use listeners are awaited, so a late record isn't lost; a VM's seconds stop at
14
+ its lease, so an org closed for days isn't charged for a VM long gone.
15
+ - `composerNotes`, a note above the composer from another front end.
16
+
17
+ ## 1.0.0-rc.13 — 2026-11-01
18
+
19
+ - **Choose an agent's model from the catalog, with your own key.** The agent editor searches every
20
+ provider and model in the models.dev catalog an agent can work with (`models.offered`): those with
21
+ a protocol we speak and an address of their own. An org's owners and admins add a key for a
22
+ provider right there (`modelKey.set`): it's sealed, shows only its end, and its agents' calls to
23
+ that provider use it, over the app's. Those uses are tagged `paid: "own-key"`. The catalog now
24
+ keeps names, release dates, and which models can't call tools or answer in text.
25
+ - **Secrets stay out of the log.** `env.set` and `apps.configure` recorded their input, so a space's
26
+ or an app's secret was kept in plain text in its `action.started` event, sealed field or not. Both
27
+ are unrecorded now. Secrets set before this remain in events already written: rotate them.
28
+ - **Agents manage cloud computers.** `list_computers`, `create_computer` and `manage_computer` (add,
29
+ remove, rename, default, destroy) work in the conversation's space, as the person the agent works
30
+ for, through the same Actions and rules a person has. Nothing asks first except destroying, which
31
+ loses the disk: like publishing, it's asked every time and only "once" allows it. A person's own
32
+ machine isn't an agent's to manage. An agent in a space with no computer is told it can make one.
33
+ - **A query an Action runs knows who asks.** Named queries called from an Action or a transaction
34
+ lost the actor for what they call themselves, so a query asking another Action could fail, or
35
+ answer as though nobody asked.
36
+ - **A read's answer no longer overwrites something newer.** The owner answers a batch of reads once
37
+ its slowest is ready, so a change could be pushed before the answer that didn't include it. The
38
+ client then showed the older answer until the read next changed: on a page's first load (the push
39
+ was dropped) and after a reconnect (the push was overwritten). What's pushed while a read is asked
40
+ for now wins over its answer, and a connection that's been replaced is no longer listened to.
41
+
1
42
  ## 1.0.0-rc.12 — 2026-11-01
2
43
 
3
44
  - **An agent can hand work to itself in another space.** "Itself" now means the same agent in the
package/README.md CHANGED
@@ -22,7 +22,7 @@ bun add copilotz # Bun
22
22
  deno add jsr:@copilotz/copilotz # Deno (or `deno add npm:copilotz`)
23
23
  ```
24
24
 
25
- On Deno, name it `copilotz` in `deno.json` (`"copilotz": "jsr:@copilotz/copilotz@^1.0.0-rc.12"`),
25
+ On Deno, name it `copilotz` in `deno.json` (`"copilotz": "jsr:@copilotz/copilotz@^1.0.0-rc.14"`),
26
26
  and the imports below are the same everywhere. Some pieces need a package of their own, installed
27
27
  beside it: `esbuild` to bundle the web host on Node, `@electric-sql/pglite` for PostgreSQL in the
28
28
  process, and `@types/react` for the front ends' types.
@@ -204,7 +204,7 @@ and an app serves it from there by default:
204
204
  import { computerDownloads } from "copilotz/plugins/compute/downloads";
205
205
 
206
206
  plugins: [...plugins, await computerDownloads()], // this Copilotz's release
207
- plugins: [...plugins, await computerDownloads({ dir: "dist/computer/1.0.0-rc.12" })], // its own: /computer/download/
207
+ plugins: [...plugins, await computerDownloads({ dir: "dist/computer/1.0.0-rc.14" })], // its own: /computer/download/
208
208
  plugins: [...plugins, await computerDownloads({ url: "https://downloads.example.com/computer/" })], // or elsewhere
209
209
  ```
210
210
 
@@ -26,7 +26,9 @@
26
26
  * `{ suspended?, name? }`; `POST …/<id>/move` `{ schema }` (its rows to
27
27
  * another schema); `GET …/<id>/export` (its rows, as SQL); `POST
28
28
  * …/<id>/delete` `{ confirm: <its name> }`. The app does the rows'
29
- * part (`operations`). Staff enter any org with `/orgs/enter`.
29
+ * part (`operations`). Staff enter any org with `/orgs/enter`. Gift codes:
30
+ * `GET /console/codes`; `POST /console/codes` `{ amount, expires?, until?,
31
+ * note? }` (the code, shown this once); `POST /console/codes/revoke` `{ id }`.
30
32
  * - Hosts orgs claimed (`claimHost` in an org's `directory` resource: a
31
33
  * preview's `<id>-preview.copilotz.app`, an app's): with the app's own
32
34
  * hosts named (`hosts`), a request to any other host is the org's that
package/hosts/orgs/mod.js CHANGED
@@ -88,6 +88,8 @@ export function orgsHost(options) {
88
88
  });
89
89
  claims.delete(name);
90
90
  },
91
+ /** A gift code's credits, for this org. */
92
+ claimCode: (code, person) => directory.call("code.claim", { code, org: org.id, person }),
91
93
  /** The host is no longer the org's. */
92
94
  releaseHost: async (host) => {
93
95
  const name = plainHost(host);
@@ -488,6 +490,24 @@ export function orgsHost(options) {
488
490
  return json({ error: "Staff only" }, { status: 403 });
489
491
  return json(await directory.call("org.list", {}));
490
492
  }
493
+ case "GET /console/codes": {
494
+ if (!await staffOnly(request))
495
+ return json({ error: "Staff only" }, { status: 403 });
496
+ return json(await directory.call("code.list", {}));
497
+ }
498
+ case "POST /console/codes": {
499
+ const who = await staffOnly(request);
500
+ if (!who)
501
+ return json({ error: "Staff only" }, { status: 403 });
502
+ const body = await request.json().catch(() => ({}));
503
+ return await directory.call("code.create", { ...body, by: who.person }).then((made) => json(made), (error) => json({ error: error.message }, { status: 400 }));
504
+ }
505
+ case "POST /console/codes/revoke": {
506
+ if (!await staffOnly(request))
507
+ return json({ error: "Staff only" }, { status: 403 });
508
+ const body = await request.json().catch(() => ({}));
509
+ return await directory.call("code.revoke", { id: body.id }).then(() => json({}), (error) => json({ error: error.message }, { status: 400 }));
510
+ }
491
511
  }
492
512
  if (url.pathname.startsWith("/console/orgs/")) {
493
513
  if (!await staffOnly(request))
@@ -12,7 +12,7 @@
12
12
  */
13
13
  export { go, signOut, web, type WebOptions, type Where } from "./host.js";
14
14
  export { appBase } from "./base.js";
15
- export { answerOrgInvite, arrived, asStaff, type ConsoleOrg, consoleOrgs, createOrg, currentOrg, deleteOrg, enterOrg, exportOrgUrl, moveOrg, type Org, type OrgInvite, orgName, type Orgs, type OrgsState, refreshOrgs, type Switching, updateOrg, useOrgs, useSwitching, } from "./orgs.js";
15
+ export { answerOrgInvite, arrived, asStaff, type ConsoleOrg, consoleOrgs, createGiftCode, createOrg, currentOrg, deleteOrg, enterOrg, exportOrgUrl, type GiftCode, giftCodes, moveOrg, type Org, type OrgInvite, orgName, type Orgs, type OrgsState, refreshOrgs, revokeGiftCode, type Switching, updateOrg, useOrgs, useSwitching, } from "./orgs.js";
16
16
  export { message, node, Part } from "./part.js";
17
17
  export { LazyView } from "./lazy.js";
18
18
  export { Palette } from "./palette/palette.js";
package/hosts/web/mod.js CHANGED
@@ -13,7 +13,7 @@
13
13
  export { go, signOut, web } from "./host.js";
14
14
  export { appBase } from "./base.js";
15
15
  // Orgs, when the server serves many (`hosts/orgs`): the person's, and going between them.
16
- export { answerOrgInvite, arrived, asStaff, consoleOrgs, createOrg, currentOrg, deleteOrg, enterOrg, exportOrgUrl, moveOrg, orgName, refreshOrgs, updateOrg, useOrgs, useSwitching, } from "./orgs.js";
16
+ export { answerOrgInvite, arrived, asStaff, consoleOrgs, createGiftCode, createOrg, currentOrg, deleteOrg, enterOrg, exportOrgUrl, giftCodes, moveOrg, orgName, refreshOrgs, revokeGiftCode, updateOrg, useOrgs, useSwitching, } from "./orgs.js";
17
17
  export { message, node, Part } from "./part.js";
18
18
  export { LazyView } from "./lazy.js";
19
19
  // The command palette: the page's (the shell shows it), and opening it at a step from anywhere.
@@ -110,3 +110,37 @@ export declare function moveOrg(org: string, schema: string): Promise<{
110
110
  export declare const exportOrgUrl: (org: string) => string;
111
111
  /** Deletes an org for good: `name`, its exact name, confirms it. */
112
112
  export declare function deleteOrg(org: string, name: string): Promise<void>;
113
+ /** A gift code as staff's console lists it: never the code itself, which is only kept hashed. */
114
+ export type GiftCode = {
115
+ id: string;
116
+ /** Enough to tell them apart: it can't be claimed with this. */
117
+ short: string;
118
+ /** USD. */
119
+ amount: number;
120
+ /** The first day its credits no longer count (`YYYY-MM-DD`); none: they don't lapse. */
121
+ expires?: string;
122
+ /** The last moment it can be claimed (ISO); none: until it is. */
123
+ until?: string;
124
+ note?: string;
125
+ by: string;
126
+ at: string;
127
+ /** Who took it, for which org, and when. */
128
+ org?: string;
129
+ person?: string;
130
+ claimed?: string;
131
+ revoked?: string;
132
+ };
133
+ /** Gift codes, newest first, for staff's console. */
134
+ export declare function giftCodes(): Promise<GiftCode[]>;
135
+ /** Makes a gift code: the answer's `code` is the only time it's ever shown. */
136
+ export declare const createGiftCode: (code: {
137
+ amount: number;
138
+ expires?: string;
139
+ until?: string;
140
+ note?: string;
141
+ }) => Promise<{
142
+ code: string;
143
+ id: string;
144
+ }>;
145
+ /** Takes back a gift code nobody has claimed. */
146
+ export declare function revokeGiftCode(id: string): Promise<void>;
package/hosts/web/orgs.js CHANGED
@@ -13,7 +13,8 @@
13
13
  * - Staff's console: `consoleOrgs()`, `updateOrg(id, { suspended?, name? })`,
14
14
  * `moveOrg(id, schema)`, `exportOrgUrl(id)` (its rows, as SQL, to save)
15
15
  * and `deleteOrg(id, name)` (its exact name confirms it). An app that
16
- * doesn't do one says so (`unsupported`).
16
+ * doesn't do one says so (`unsupported`). Gift codes: `giftCodes()`,
17
+ * `createGiftCode(...)` (the code itself, this once) and `revokeGiftCode(id)`.
17
18
  *
18
19
  * It's the page's own HTTP, same origin, with the cookies the server set.
19
20
  */
@@ -223,3 +224,20 @@ export const exportOrgUrl = (org) => `/console/orgs/${encodeURIComponent(org)}/e
223
224
  export async function deleteOrg(org, name) {
224
225
  await post(`/console/orgs/${encodeURIComponent(org)}/delete`, { confirm: name });
225
226
  }
227
+ /** Gift codes, newest first, for staff's console. */
228
+ export async function giftCodes() {
229
+ const response = await fetch("/console/codes", { headers: { accept: "application/json" } });
230
+ const answer = await response.json().catch(() => ({}));
231
+ if (!response.ok) {
232
+ throw Object.assign(new Error(answer.error ?? response.statusText), {
233
+ code: codeOf(response.status),
234
+ });
235
+ }
236
+ return answer.codes;
237
+ }
238
+ /** Makes a gift code: the answer's `code` is the only time it's ever shown. */
239
+ export const createGiftCode = (code) => post("/console/codes", code);
240
+ /** Takes back a gift code nobody has claimed. */
241
+ export async function revokeGiftCode(id) {
242
+ await post("/console/codes/revoke", { id });
243
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "copilotz",
3
- "version": "1.0.0-rc.12",
3
+ "version": "1.0.0-rc.14",
4
4
  "description": "Copilotz: one runtime for Node, Deno, Bun, Cloudflare Workers and the browser.",
5
5
  "keywords": [
6
6
  "agents",
@@ -87,8 +87,8 @@
87
87
  "default": "./plugins/billing/mod.js"
88
88
  },
89
89
  "./plugins/billing/web": {
90
- "types": "./plugins/billing/usage/web.d.ts",
91
- "default": "./plugins/billing/usage/web.js"
90
+ "types": "./plugins/billing/web.d.ts",
91
+ "default": "./plugins/billing/web.js"
92
92
  },
93
93
  "./plugins/billing/terminal": {
94
94
  "types": "./plugins/billing/terminal.d.ts",
@@ -0,0 +1,5 @@
1
+ export declare const modelKeySet: import("../../../../runtime/define.js").ActionDef;
2
+ export declare const modelKeyRemove: import("../../../../runtime/define.js").ActionDef;
3
+ export declare const modelKeyMay: import("../../../../runtime/define.js").ActionDef;
4
+ export declare const modelKeyList: import("../../../../runtime/define.js").ActionDef;
5
+ export declare const modelKeyOpen: import("../../../../runtime/define.js").ActionDef;
@@ -0,0 +1,102 @@
1
+ /**
2
+ * An org's own keys for model providers (see collections/model-key.ts), as the
3
+ * models plugin's `modelKeys` resource names them. Its owners and admins change
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`.
7
+ *
8
+ * All unrecorded: a key is in no event, as its input or its answer.
9
+ */
10
+ import { defineAction, forbidden, inPerson, invalid, people, } from "../../../../runtime/mod.js";
11
+ import { runsOrg } from "../../spaces/contract.js";
12
+ import { seal, unseal } from "../shared/seal.js";
13
+ import { settingsOf } from "../shared/settings.js";
14
+ 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}`;
17
+ /** Whether whoever asks runs the org: only they change its keys. */
18
+ const runs = (ctx) => ctx.call("org.me", {})
19
+ .then((me) => !!me.staff || runsOrg(me.role ?? null), () => false);
20
+ const SHOW = 4;
21
+ /** A long key's last characters, to tell it apart; a short one shows nothing of itself. */
22
+ const hintOf = (key) => key.length >= 16 ? `••••${key.slice(-SHOW)}` : "••••";
23
+ export const modelKeySet = defineAction({
24
+ description: "Adds or replaces the org's own key for a model provider",
25
+ record: false,
26
+ input: {
27
+ type: "object",
28
+ properties: {
29
+ provider: { type: "string" },
30
+ key: { type: "string", minLength: 1, maxLength: 4096 },
31
+ },
32
+ required: ["provider", "key"],
33
+ additionalProperties: false,
34
+ },
35
+ allow: inPerson,
36
+ run: async (ctx, input) => {
37
+ if (!await runs(ctx))
38
+ throw forbidden("Only the org's owners and admins change its keys.");
39
+ if (!await ctx.call("models.keyable", { provider: input.provider })) {
40
+ throw invalid(`A key can't be added for "${input.provider}".`);
41
+ }
42
+ const key = input.key.trim();
43
+ if (!key || /\s/.test(key))
44
+ throw invalid("That doesn't look like a key.");
45
+ const sealed = await seal(settingsOf(ctx).key, boundTo(ctx, input.provider), {
46
+ access: key,
47
+ account: input.provider,
48
+ });
49
+ 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 });
51
+ return { provider: input.provider, hint };
52
+ },
53
+ });
54
+ export const modelKeyRemove = defineAction({
55
+ description: "Removes the org's own key for a model provider",
56
+ record: false,
57
+ input: {
58
+ type: "object",
59
+ properties: { provider: { type: "string" } },
60
+ required: ["provider"],
61
+ additionalProperties: false,
62
+ },
63
+ allow: inPerson,
64
+ run: async (ctx, input) => {
65
+ if (!await runs(ctx))
66
+ throw forbidden("Only the org's owners and admins change its keys.");
67
+ await keysOf(ctx).deleteOne({ _id: input.provider });
68
+ return { removed: true };
69
+ },
70
+ });
71
+ export const modelKeyMay = defineAction({
72
+ description: "Whether you may change the org's keys for model providers",
73
+ record: false,
74
+ input: { type: "object", additionalProperties: false },
75
+ allow: people,
76
+ run: async (ctx) => ({ set: await runs(ctx) }),
77
+ });
78
+ // No `allow`: only the system (a model call, the models plugin) asks these.
79
+ export const modelKeyList = defineAction({
80
+ record: false,
81
+ input: { type: "object", additionalProperties: false },
82
+ run: async (ctx) => (await keysOf(ctx).find({})).map((k) => ({
83
+ provider: k._id,
84
+ ...(k.hint ? { hint: k.hint } : {}),
85
+ })),
86
+ });
87
+ export const modelKeyOpen = defineAction({
88
+ record: false,
89
+ input: {
90
+ type: "object",
91
+ properties: { provider: { type: "string" } },
92
+ required: ["provider"],
93
+ additionalProperties: false,
94
+ },
95
+ run: async (ctx, input) => {
96
+ const found = await keysOf(ctx).findOne({ _id: input.provider });
97
+ if (!found)
98
+ return null;
99
+ const { access } = await unseal(settingsOf(ctx).key, boundTo(ctx, input.provider), found.sealed);
100
+ return access;
101
+ },
102
+ });
@@ -0,0 +1,58 @@
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.
6
+ */
7
+ import { type Infer } from "../../../../runtime/mod.js";
8
+ declare const modelKeySchema: {
9
+ readonly type: "object";
10
+ readonly properties: {
11
+ readonly hint: {
12
+ readonly type: "string";
13
+ };
14
+ readonly by: {
15
+ readonly type: "string";
16
+ };
17
+ readonly at: {
18
+ readonly type: "string";
19
+ };
20
+ };
21
+ readonly required: readonly ["by", "at"];
22
+ };
23
+ export declare const modelKey: {
24
+ schema: {
25
+ readonly type: "object";
26
+ readonly properties: {
27
+ readonly hint: {
28
+ readonly type: "string";
29
+ };
30
+ readonly by: {
31
+ readonly type: "string";
32
+ };
33
+ readonly at: {
34
+ readonly type: "string";
35
+ };
36
+ };
37
+ readonly required: readonly ["by", "at"];
38
+ };
39
+ events?: boolean;
40
+ records?: boolean;
41
+ durable?: false;
42
+ indexes?: string[][];
43
+ private?: string[];
44
+ queries?: Record<string, import("../../../../runtime/define.js").QueryDef<{
45
+ [x: string]: unknown;
46
+ hint?: string | undefined;
47
+ at: string;
48
+ by: string;
49
+ } & {
50
+ _id: string;
51
+ }>> | undefined;
52
+ vectors?: string[];
53
+ };
54
+ export type ModelKeyDoc = Infer<typeof modelKeySchema> & {
55
+ _id: string;
56
+ sealed: unknown;
57
+ };
58
+ export {};
@@ -0,0 +1,17 @@
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.
6
+ */
7
+ import { defineCollection } from "../../../../runtime/mod.js";
8
+ const modelKeySchema = {
9
+ type: "object",
10
+ properties: {
11
+ hint: { type: "string" },
12
+ by: { type: "string" },
13
+ at: { type: "string" },
14
+ },
15
+ required: ["by", "at"],
16
+ };
17
+ export const modelKey = defineCollection({ schema: modelKeySchema, private: ["sealed"] });
@@ -31,6 +31,11 @@
31
31
  * (resources/models.ts); without a connection the call fails
32
32
  * `account_missing`, and a list of models moves on. Its uses are metered
33
33
  * as the person's plan's (`paid: "subscription"`), at no cost to the app.
34
+ * - **An org's own keys for model providers** (`modelKey`, the models
35
+ * plugin's `modelKeys` resource): its owners and admins add one (`modelKey.set`)
36
+ * for any provider that can take one; each is sealed as tokens are, kept per
37
+ * org and shows only its last characters; its agents' calls to that provider
38
+ * use it (`modelKey.open`, trusted code only), over the app's.
34
39
  * - `account.changed` says when an account is connected, lost or
35
40
  * disconnected: the audit trail, with nothing secret in it.
36
41
  *
@@ -31,6 +31,11 @@
31
31
  * (resources/models.ts); without a connection the call fails
32
32
  * `account_missing`, and a list of models moves on. Its uses are metered
33
33
  * as the person's plan's (`paid: "subscription"`), at no cost to the app.
34
+ * - **An org's own keys for model providers** (`modelKey`, the models
35
+ * plugin's `modelKeys` resource): its owners and admins add one (`modelKey.set`)
36
+ * for any provider that can take one; each is sealed as tokens are, kept per
37
+ * org and shows only its last characters; its agents' calls to that provider
38
+ * use it (`modelKey.open`, trusted code only), over the app's.
34
39
  * - `account.changed` says when an account is connected, lost or
35
40
  * disconnected: the audit trail, with nothing secret in it.
36
41
  *
@@ -53,6 +58,8 @@ import { refreshAction } from "./actions/refresh.js";
53
58
  import { tokenAction } from "./actions/token.js";
54
59
  import { account } from "./collections/account.js";
55
60
  import { accountFlow } from "./collections/flow.js";
61
+ import { modelKey } from "./collections/model-key.js";
62
+ import { modelKeyList, modelKeyMay, modelKeyOpen, modelKeyRemove, modelKeySet, } from "./actions/model-key.js";
56
63
  import { changed } from "./events/changed.js";
57
64
  import { chatgpt } from "./resources/chatgpt.js";
58
65
  import { chatgptCost, chatgptModels } from "./resources/models.js";
@@ -73,7 +80,7 @@ const sendable = (address) => {
73
80
  };
74
81
  export const accounts = definePlugin({
75
82
  name: "accounts",
76
- collections: { account, accountFlow },
83
+ collections: { account, accountFlow, modelKey },
77
84
  actions: {
78
85
  "account.connect": connectAction,
79
86
  "account.complete": completeAction,
@@ -81,6 +88,11 @@ export const accounts = definePlugin({
81
88
  "account.disconnect": disconnectAction,
82
89
  "account.refresh": refreshAction,
83
90
  "account.token": tokenAction,
91
+ "modelKey.set": modelKeySet,
92
+ "modelKey.remove": modelKeyRemove,
93
+ "modelKey.may": modelKeyMay,
94
+ "modelKey.list": modelKeyList,
95
+ "modelKey.open": modelKeyOpen,
84
96
  },
85
97
  events: { "account.changed": changed },
86
98
  guard: rules,
@@ -88,6 +100,7 @@ export const accounts = definePlugin({
88
100
  accounts: {},
89
101
  accountProviders: { chatgpt },
90
102
  provider: { chatgpt: chatgptModels },
103
+ modelKeys: { open: "modelKey.open", list: "modelKey.list", may: "modelKey.may" },
91
104
  cost: { "chatgpt/*": chatgptCost },
92
105
  routes: { accounts: { path: CALLBACK, action: "account.callback", methods: ["GET"] } },
93
106
  },
@@ -6,6 +6,8 @@ export const accountHeaders = (provider) => async ({ call }) => {
6
6
  return (await call("account.token", { provider })).headers;
7
7
  };
8
8
  export const chatgptModels = {
9
+ title: "ChatGPT plan",
10
+ note: "Runs on the plan of whoever asks: each person connects their own.",
9
11
  adapter: "openai",
10
12
  catalog: "openai",
11
13
  baseURL: "https://chatgpt.com/backend-api/codex",
@@ -1,6 +1,6 @@
1
1
  const NOBODY = { _id: { $in: [] } };
2
2
  export const rules = (actor, { collection }) => collection === "account"
3
3
  ? actor.kind === "person" ? { person: actor.id } : NOBODY
4
- : collection === "accountFlow"
4
+ : collection === "accountFlow" || collection === "modelKey"
5
5
  ? NOBODY
6
6
  : undefined;
@@ -0,0 +1,4 @@
1
+ export declare const createCodeAction: import("../../../../runtime/define.js").ActionDef;
2
+ export declare const claimCodeAction: import("../../../../runtime/define.js").ActionDef;
3
+ export declare const listCodesAction: import("../../../../runtime/define.js").ActionDef;
4
+ export declare const revokeCodeAction: import("../../../../runtime/define.js").ActionDef;
@@ -0,0 +1,135 @@
1
+ /**
2
+ * Gift codes (see collections/credit-code.ts). All the system's: staff ask
3
+ * through the console, orgs through their `directory` resource. None is
4
+ * recorded, so a code is in no event.
5
+ *
6
+ * - `code.create` `{ amount, expires?, until?, note?, by }`: a new code, shown
7
+ * this once;
8
+ * - `code.claim` `{ code, org, person }`: its credits, for that org. Claimed
9
+ * already by the same org, it answers the same, so a grant that failed can be
10
+ * tried again; by another, it's refused;
11
+ * - `code.list` `{}`, newest first, and `code.revoke` `{ id }`, while unclaimed.
12
+ */
13
+ import { defineAction, failure, invalid } from "../../../../runtime/mod.js";
14
+ const ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
15
+ /** 130 random bits, as people can read and type them. */
16
+ function newCode() {
17
+ const bytes = crypto.getRandomValues(new Uint8Array(26));
18
+ const chars = [...bytes].map((byte) => ALPHABET[byte % 32]).join("");
19
+ return `GIFT-${chars.match(/.{1,5}/g).join("-")}`;
20
+ }
21
+ /** How it's kept: typed in any case, with or without its dashes. */
22
+ async function hashOf(code) {
23
+ const plain = code.toUpperCase().replace(/[^0-9A-Z]/g, "");
24
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(plain));
25
+ return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");
26
+ }
27
+ const shown = (doc) => ({
28
+ id: doc._id,
29
+ // Enough to tell them apart: it can't be claimed with this.
30
+ short: doc._id.slice(0, 8),
31
+ amount: doc.amount,
32
+ ...(doc.expires ? { expires: doc.expires } : {}),
33
+ ...(doc.until ? { until: doc.until } : {}),
34
+ ...(doc.note ? { note: doc.note } : {}),
35
+ by: doc.by,
36
+ at: doc.at,
37
+ ...(doc.org ? { org: doc.org, person: doc.person, claimed: doc.claimed } : {}),
38
+ ...(doc.revoked ? { revoked: doc.revoked } : {}),
39
+ });
40
+ export const createCodeAction = defineAction({
41
+ description: "Makes a gift code of credits; it's shown this once",
42
+ record: false,
43
+ input: {
44
+ type: "object",
45
+ properties: {
46
+ amount: { type: "number", exclusiveMinimum: 0 },
47
+ expires: { type: "string", pattern: "^\\d{4}-\\d{2}-\\d{2}$" },
48
+ until: { type: "string" },
49
+ note: { type: "string", maxLength: 200 },
50
+ by: { type: "string" },
51
+ },
52
+ required: ["amount", "by"],
53
+ additionalProperties: false,
54
+ },
55
+ run: async (ctx, input) => {
56
+ const code = newCode();
57
+ const _id = await hashOf(code);
58
+ await ctx.db.collection("creditCode").insertOne({
59
+ _id,
60
+ ...input,
61
+ at: new Date().toISOString(),
62
+ });
63
+ return { code, id: _id };
64
+ },
65
+ });
66
+ export const claimCodeAction = defineAction({
67
+ description: "Claims a gift code for an org",
68
+ record: false,
69
+ input: {
70
+ type: "object",
71
+ properties: {
72
+ code: { type: "string" },
73
+ org: { type: "string" },
74
+ person: { type: "string" },
75
+ },
76
+ required: ["code", "org", "person"],
77
+ additionalProperties: false,
78
+ },
79
+ run: async (ctx, input) => {
80
+ const codes = ctx.db.collection("creditCode");
81
+ const _id = await hashOf(input.code);
82
+ const invalidCode = () => failure("invalid_code", "That code isn't valid. Check it and try again.");
83
+ const answer = (doc) => ({
84
+ id: _id.slice(0, 16),
85
+ amount: doc.amount,
86
+ ...(doc.expires ? { expires: doc.expires } : {}),
87
+ ...(doc.note ? { note: doc.note } : {}),
88
+ });
89
+ const doc = await codes.findOne({ _id });
90
+ if (!doc || doc.revoked)
91
+ throw invalidCode();
92
+ if (doc.org === input.org)
93
+ return answer(doc);
94
+ if (doc.org)
95
+ throw failure("used_code", "That code has already been used.");
96
+ const now = new Date().toISOString();
97
+ if (doc.until && doc.until <= now)
98
+ throw failure("expired_code", "That code has expired.");
99
+ // One writer: only one claim finds it unclaimed.
100
+ const { modifiedCount } = await codes.updateOne({ _id, org: { $exists: false }, revoked: { $exists: false } }, { $set: { org: input.org, person: input.person, claimed: now } });
101
+ if (modifiedCount)
102
+ return answer(doc);
103
+ const now2 = await codes.findOne({ _id });
104
+ if (now2?.org === input.org)
105
+ return answer(now2);
106
+ throw failure("used_code", "That code has already been used.");
107
+ },
108
+ });
109
+ export const listCodesAction = defineAction({
110
+ description: "Gift codes, newest first",
111
+ record: false,
112
+ input: { type: "object", additionalProperties: false },
113
+ run: async (ctx) => ({
114
+ codes: (await ctx.db.collection("creditCode").find({}, {
115
+ sort: { at: -1 },
116
+ limit: 200,
117
+ })).map(shown),
118
+ }),
119
+ });
120
+ export const revokeCodeAction = defineAction({
121
+ description: "Takes back a gift code nobody has claimed",
122
+ record: false,
123
+ input: {
124
+ type: "object",
125
+ properties: { id: { type: "string" } },
126
+ required: ["id"],
127
+ additionalProperties: false,
128
+ },
129
+ run: async (ctx, input) => {
130
+ const { modifiedCount } = await ctx.db.collection("creditCode").updateOne({ _id: input.id, org: { $exists: false } }, { $set: { revoked: new Date().toISOString() } });
131
+ if (!modifiedCount)
132
+ throw invalid("It's been claimed, or there's no such code.");
133
+ return {};
134
+ },
135
+ });