copilotz 1.0.0-rc.13 → 1.0.0-rc.15

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 (156) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README.md +2 -2
  3. package/hosts/orgs/mod.d.ts +4 -1
  4. package/hosts/orgs/mod.js +44 -6
  5. package/hosts/web/mod.d.ts +1 -1
  6. package/hosts/web/mod.js +1 -1
  7. package/hosts/web/orgs.d.ts +36 -0
  8. package/hosts/web/orgs.js +21 -3
  9. package/package.json +3 -3
  10. package/plugins/access/directory/actions/code.d.ts +4 -0
  11. package/plugins/access/directory/actions/code.js +135 -0
  12. package/plugins/access/directory/actions/org.js +13 -3
  13. package/plugins/access/directory/collections/credit-code.d.ts +114 -0
  14. package/plugins/access/directory/collections/credit-code.js +28 -0
  15. package/plugins/access/directory/mod.d.ts +1 -0
  16. package/plugins/access/directory/mod.js +7 -1
  17. package/plugins/access/spaces/actions/org.d.ts +1 -0
  18. package/plugins/access/spaces/actions/org.js +7 -0
  19. package/plugins/access/spaces/mod.js +2 -1
  20. package/plugins/access/spaces/views/web/org-about.js +3 -3
  21. package/plugins/agents/chat/contract.d.ts +3 -3
  22. package/plugins/agents/chat/processors/failed.js +6 -0
  23. package/plugins/agents/chat/shared/types.d.ts +11 -0
  24. package/plugins/agents/chat/views/web/composer.d.ts +7 -2
  25. package/plugins/agents/chat/views/web/composer.js +9 -1
  26. package/plugins/agents/chat/views/web/conversation.d.ts +3 -2
  27. package/plugins/agents/chat/views/web/conversation.js +1 -1
  28. package/plugins/agents/chat/views/web/home.d.ts +3 -2
  29. package/plugins/agents/chat/views/web/home.js +1 -1
  30. package/plugins/agents/chat/views/web/message.d.ts +9 -1
  31. package/plugins/agents/chat/views/web/message.js +9 -1
  32. package/plugins/agents/chat/views/web/style.d.ts +1 -1
  33. package/plugins/agents/chat/views/web/style.js +8 -0
  34. package/plugins/agents/chat/web.d.ts +5 -1
  35. package/plugins/agents/chat/web.js +5 -1
  36. package/plugins/agents/team/views/web/model-picker.js +9 -4
  37. package/plugins/billing/credits/actions/check.d.ts +4 -0
  38. package/plugins/billing/credits/actions/check.js +83 -0
  39. package/plugins/billing/credits/actions/manage.d.ts +9 -0
  40. package/plugins/billing/credits/actions/manage.js +266 -0
  41. package/plugins/billing/credits/actions/state.d.ts +2 -0
  42. package/plugins/billing/credits/actions/state.js +148 -0
  43. package/plugins/billing/credits/collections/credit.d.ts +110 -0
  44. package/plugins/billing/credits/collections/credit.js +31 -0
  45. package/plugins/billing/credits/collections/payment.d.ts +139 -0
  46. package/plugins/billing/credits/collections/payment.js +32 -0
  47. package/plugins/billing/credits/collections/plan.d.ts +408 -0
  48. package/plugins/billing/credits/collections/plan.js +93 -0
  49. package/plugins/billing/credits/collections/room.d.ts +85 -0
  50. package/plugins/billing/credits/collections/room.js +24 -0
  51. package/plugins/billing/credits/contract.d.ts +15 -0
  52. package/plugins/billing/credits/contract.js +11 -0
  53. package/plugins/billing/credits/mod.d.ts +30 -0
  54. package/plugins/billing/credits/mod.js +61 -0
  55. package/plugins/billing/credits/shared/apply.d.ts +66 -0
  56. package/plugins/billing/credits/shared/apply.js +102 -0
  57. package/plugins/billing/credits/shared/settings.d.ts +51 -0
  58. package/plugins/billing/credits/shared/settings.js +14 -0
  59. package/plugins/billing/credits/shared/standing.d.ts +71 -0
  60. package/plugins/billing/credits/shared/standing.js +235 -0
  61. package/plugins/billing/credits/shared/walk.d.ts +50 -0
  62. package/plugins/billing/credits/shared/walk.js +127 -0
  63. package/plugins/billing/credits/views/web/add.d.ts +25 -0
  64. package/plugins/billing/credits/views/web/add.js +92 -0
  65. package/plugins/billing/credits/views/web/budget.d.ts +16 -0
  66. package/plugins/billing/credits/views/web/budget.js +62 -0
  67. package/plugins/billing/credits/views/web/composer.d.ts +13 -0
  68. package/plugins/billing/credits/views/web/composer.js +64 -0
  69. package/plugins/billing/credits/views/web/history.d.ts +12 -0
  70. package/plugins/billing/credits/views/web/history.js +55 -0
  71. package/plugins/billing/credits/views/web/numbers.d.ts +224 -0
  72. package/plugins/billing/credits/views/web/numbers.js +250 -0
  73. package/plugins/billing/credits/views/web/org.d.ts +31 -0
  74. package/plugins/billing/credits/views/web/org.js +238 -0
  75. package/plugins/billing/credits/views/web/plan.d.ts +22 -0
  76. package/plugins/billing/credits/views/web/plan.js +65 -0
  77. package/plugins/billing/credits/views/web/staff.d.ts +20 -0
  78. package/plugins/billing/credits/views/web/staff.js +265 -0
  79. package/plugins/billing/credits/views/web/style.d.ts +9 -0
  80. package/plugins/billing/credits/views/web/style.js +186 -0
  81. package/plugins/billing/credits/views/web/types.d.ts +17 -0
  82. package/plugins/billing/credits/views/web/types.js +32 -0
  83. package/plugins/billing/credits/web.d.ts +12 -0
  84. package/plugins/billing/credits/web.js +33 -0
  85. package/plugins/billing/mod.d.ts +8 -3
  86. package/plugins/billing/mod.js +7 -3
  87. package/plugins/billing/stripe/actions/checkout.d.ts +3 -0
  88. package/plugins/billing/stripe/actions/checkout.js +171 -0
  89. package/plugins/billing/stripe/mod.d.ts +17 -0
  90. package/plugins/billing/stripe/mod.js +27 -0
  91. package/plugins/billing/stripe/shared/api.d.ts +14 -0
  92. package/plugins/billing/stripe/shared/api.js +42 -0
  93. package/plugins/billing/stripe/shared/events.d.ts +42 -0
  94. package/plugins/billing/stripe/shared/events.js +226 -0
  95. package/plugins/billing/stripe/shared/settings.d.ts +34 -0
  96. package/plugins/billing/stripe/shared/settings.js +10 -0
  97. package/plugins/billing/stripe/webhook.d.ts +17 -0
  98. package/plugins/billing/stripe/webhook.js +45 -0
  99. package/plugins/billing/usage/actions/quote.d.ts +6 -0
  100. package/plugins/billing/usage/actions/quote.js +45 -1
  101. package/plugins/billing/usage/actions/rerate.js +1 -0
  102. package/plugins/billing/usage/mod.d.ts +2 -0
  103. package/plugins/billing/usage/mod.js +4 -1
  104. package/plugins/billing/usage/shared/rate.d.ts +10 -3
  105. package/plugins/billing/usage/shared/rate.js +18 -3
  106. package/plugins/billing/usage/shared/settings.d.ts +11 -1
  107. package/plugins/billing/usage/shared/use.js +5 -0
  108. package/plugins/billing/usage/views/web/org.d.ts +10 -1
  109. package/plugins/billing/usage/views/web/org.js +16 -4
  110. package/plugins/billing/web.d.ts +3 -0
  111. package/plugins/billing/web.js +3 -0
  112. package/plugins/compute/apps/shared/publish.d.ts +0 -4
  113. package/plugins/compute/apps/shared/publish.js +12 -0
  114. package/plugins/compute/cloud/actions/create.js +6 -8
  115. package/plugins/compute/cloud/actions/pool-tick.js +2 -2
  116. package/plugins/compute/cloud/actions/tick.js +13 -3
  117. package/plugins/compute/cloud/actions/vms.d.ts +0 -2
  118. package/plugins/compute/cloud/actions/vms.js +1 -3
  119. package/plugins/compute/cloud/actions/wake.js +6 -0
  120. package/plugins/compute/cloud/mod.d.ts +2 -2
  121. package/plugins/compute/cloud/mod.js +2 -2
  122. package/plugins/compute/cloud/shared/may.d.ts +15 -7
  123. package/plugins/compute/cloud/shared/may.js +19 -20
  124. package/plugins/compute/cloud/shared/meter.d.ts +3 -0
  125. package/plugins/compute/cloud/shared/meter.js +8 -3
  126. package/plugins/compute/cloud/shared/settings.d.ts +0 -5
  127. package/plugins/compute/cloud/shared/settings.js +0 -1
  128. package/plugins/compute/cloud/shared/time.d.ts +2 -0
  129. package/plugins/compute/cloud/shared/time.js +2 -0
  130. package/plugins/compute/cloud/views/web/cloud.d.ts +4 -3
  131. package/plugins/compute/cloud/views/web/cloud.js +4 -3
  132. package/plugins/compute/cloud/views/web/new.d.ts +2 -2
  133. package/plugins/compute/cloud/views/web/new.js +19 -10
  134. package/plugins/compute/cloud/web.js +3 -2
  135. package/plugins/compute/computers/program/version.d.ts +1 -1
  136. package/plugins/compute/computers/program/version.js +1 -1
  137. package/plugins/compute/computers/resources/downloads.js +1 -1
  138. package/plugins/interfaces/web/shared/codes.d.ts +31 -0
  139. package/plugins/interfaces/web/shared/codes.js +44 -0
  140. package/plugins/interfaces/web/shared/orgs.d.ts +1 -1
  141. package/plugins/interfaces/web/shared/orgs.js +1 -1
  142. package/plugins/interfaces/web/shared/style.d.ts +1 -1
  143. package/plugins/interfaces/web/shared/style.js +3 -0
  144. package/plugins/interfaces/web/views/console-codes.d.ts +14 -0
  145. package/plugins/interfaces/web/views/console-codes.js +159 -0
  146. package/plugins/interfaces/web/views/console.d.ts +4 -2
  147. package/plugins/interfaces/web/views/console.js +24 -10
  148. package/plugins/interfaces/web/views/org.js +12 -6
  149. package/plugins/interfaces/web/views/orgs.js +13 -3
  150. package/plugins/models/actions/offered.d.ts +2 -0
  151. package/plugins/models/actions/offered.js +52 -6
  152. package/plugins/models/shared/generate.d.ts +2 -1
  153. package/plugins/models/shared/generate.js +26 -4
  154. package/plugins/models/shared/use.d.ts +6 -2
  155. package/plugins/models/shared/use.js +15 -5
  156. package/runtime/owner.js +8 -1
package/CHANGELOG.md CHANGED
@@ -1,3 +1,27 @@
1
+ ## 1.0.0-rc.15 — 2026-11-02
2
+
3
+ - **Enter as staff, in your own org too.** Staff who belong to an org go in as one of its people, as
4
+ before, but can now ask to go in as staff: from the console, or the org switcher. They keep their
5
+ role, get the staff tools, and "Continue as Owner" takes them back. `POST /orgs/enter` takes
6
+ `staff: true`, `org.enter` takes `staff`, and `GET /orgs` says `asStaff`, which `asStaff()` now
7
+ reads instead of guessing from membership.
8
+
9
+ ## 1.0.0-rc.14 — 2026-11-02
10
+
11
+ - **Credits** (`plugins/billing/credits`): what an org can spend. Plans, credits and payments are
12
+ its own rows, the balance is walked from them and the ledger, and one check stops model calls,
13
+ computers and builds at the limit, in plain words. Staff set plans, give credits, waive usage or
14
+ seats, and record payments; gift codes wait in the directory.
15
+ - **Stripe** (`plugins/billing/stripe`): Checkout, the customer portal and signed webhooks, for one
16
+ or more accounts. A subscription's credits come with its paid invoice.
17
+ - **Prices:** a use on an org's own key costs nothing; a plan can name a price list; `usage.quotes`;
18
+ the model picker shows the org's real price.
19
+ - **Removed:** the cloud plugin's `create` and `budgetUsd` settings. Anyone in an org but its guests
20
+ makes a computer; what the org can spend keeps the cost.
21
+ - **Fixed:** model use listeners are awaited, so a late record isn't lost; a VM's seconds stop at
22
+ its lease, so an org closed for days isn't charged for a VM long gone.
23
+ - `composerNotes`, a note above the composer from another front end.
24
+
1
25
  ## 1.0.0-rc.13 — 2026-11-01
2
26
 
3
27
  - **Choose an agent's model from the catalog, with your own key.** The agent editor searches every
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.13"`),
25
+ On Deno, name it `copilotz` in `deno.json` (`"copilotz": "jsr:@copilotz/copilotz@^1.0.0-rc.15"`),
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.13" })], // its own: /computer/download/
207
+ plugins: [...plugins, await computerDownloads({ dir: "dist/computer/1.0.0-rc.15" })], // 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,10 @@
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` `{ org, staff:
30
+ * true }`, their own too; without it, they go into theirs as its people. Gift codes:
31
+ * `GET /console/codes`; `POST /console/codes` `{ amount, expires?, until?,
32
+ * note? }` (the code, shown this once); `POST /console/codes/revoke` `{ id }`.
30
33
  * - Hosts orgs claimed (`claimHost` in an org's `directory` resource: a
31
34
  * preview's `<id>-preview.copilotz.app`, an app's): with the app's own
32
35
  * 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);
@@ -163,8 +165,13 @@ export function orgsHost(options) {
163
165
  return { person: actor.id, email };
164
166
  };
165
167
  /** Goes into an org: the directory lets them in; the org knows them, and gives them a session. */
166
- const enter = async (request, url, who, org) => {
167
- const { org: info, role, staff } = await directory.call("org.enter", { org, person: who.person, ...(who.email ? { email: who.email } : {}) });
168
+ const enter = async (request, url, who, org, asStaff = false) => {
169
+ const { org: info, role, staff } = await directory.call("org.enter", {
170
+ org,
171
+ person: who.person,
172
+ ...(who.email ? { email: who.email } : {}),
173
+ ...(asStaff ? { staff: true } : {}),
174
+ });
168
175
  const cell = await cellOf(info);
169
176
  cell.last = Date.now();
170
177
  report(cell);
@@ -175,7 +182,7 @@ export function orgsHost(options) {
175
182
  ...(profile?.name ? { name: profile.name } : {}),
176
183
  ...(profile?.picture ? { picture: profile.picture } : {}),
177
184
  });
178
- if (!staff) {
185
+ if (!staff || role) {
179
186
  await cell.runtime.call("org.join", { person: who.person, ...(role ? { role } : {}) });
180
187
  }
181
188
  // A session they hold already, for this org and this person, stays.
@@ -198,6 +205,17 @@ export function orgsHost(options) {
198
205
  ],
199
206
  };
200
207
  };
208
+ /** Whether the session a request holds in an org is staff's. */
209
+ const heldAsStaff = async (request, org) => {
210
+ const secret = cookieOf(request, sessionOf(org));
211
+ const info = secret ? await orgInfo(org) : null;
212
+ if (!info || info.suspended)
213
+ return false;
214
+ const actor = await (await cellOf(info)).runtime
215
+ .query("credential.actor", { secret: secret })
216
+ .catch(() => null);
217
+ return actor?.staff === true;
218
+ };
201
219
  /** Whether a request's session for an org's cell is still good there. */
202
220
  const heldIn = async (cell, request) => {
203
221
  const secret = cookieOf(request, sessionOf(cell.org.id));
@@ -424,13 +442,15 @@ export function orgsHost(options) {
424
442
  ? directory.call("invite.mine", { email: who.email })
425
443
  : Promise.resolve({ invites: [] }),
426
444
  ]);
445
+ const current = cookieOf(request, CURRENT) ?? null;
427
446
  return json({
428
447
  person: who.person,
429
448
  email: who.email,
430
- current: cookieOf(request, CURRENT) ?? null,
449
+ current,
431
450
  orgs,
432
451
  invites,
433
452
  staff,
453
+ asStaff: staff && !!current && await heldAsStaff(request, current),
434
454
  });
435
455
  }
436
456
  case "POST /orgs": {
@@ -452,8 +472,8 @@ export function orgsHost(options) {
452
472
  const who = await signedIn(request);
453
473
  if (!who)
454
474
  return json({ error: "Not signed in" }, { status: 401 });
455
- const { org } = await request.json();
456
- const entered = await enter(request, url, who, String(org));
475
+ const { org, staff } = await request.json();
476
+ const entered = await enter(request, url, who, String(org), staff === true);
457
477
  return json({ org: entered.org }, { cookies: entered.cookies });
458
478
  }
459
479
  case "POST /orgs/invites/answer": {
@@ -488,6 +508,24 @@ export function orgsHost(options) {
488
508
  return json({ error: "Staff only" }, { status: 403 });
489
509
  return json(await directory.call("org.list", {}));
490
510
  }
511
+ case "GET /console/codes": {
512
+ if (!await staffOnly(request))
513
+ return json({ error: "Staff only" }, { status: 403 });
514
+ return json(await directory.call("code.list", {}));
515
+ }
516
+ case "POST /console/codes": {
517
+ const who = await staffOnly(request);
518
+ if (!who)
519
+ return json({ error: "Staff only" }, { status: 403 });
520
+ const body = await request.json().catch(() => ({}));
521
+ return await directory.call("code.create", { ...body, by: who.person }).then((made) => json(made), (error) => json({ error: error.message }, { status: 400 }));
522
+ }
523
+ case "POST /console/codes/revoke": {
524
+ if (!await staffOnly(request))
525
+ return json({ error: "Staff only" }, { status: 403 });
526
+ const body = await request.json().catch(() => ({}));
527
+ return await directory.call("code.revoke", { id: body.id }).then(() => json({}), (error) => json({ error: error.message }, { status: 400 }));
528
+ }
491
529
  }
492
530
  if (url.pathname.startsWith("/console/orgs/")) {
493
531
  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.
@@ -23,6 +23,8 @@ export type Orgs = {
23
23
  invites: OrgInvite[];
24
24
  /** Platform staff, who go into any org. */
25
25
  staff: boolean;
26
+ /** The session they hold in the org they're in is staff's, one of theirs or not. */
27
+ asStaff: boolean;
26
28
  };
27
29
  /** An org as staff's console lists it, with what it last reported of itself. */
28
30
  export type ConsoleOrg = Org & {
@@ -110,3 +112,37 @@ export declare function moveOrg(org: string, schema: string): Promise<{
110
112
  export declare const exportOrgUrl: (org: string) => string;
111
113
  /** Deletes an org for good: `name`, its exact name, confirms it. */
112
114
  export declare function deleteOrg(org: string, name: string): Promise<void>;
115
+ /** A gift code as staff's console lists it: never the code itself, which is only kept hashed. */
116
+ export type GiftCode = {
117
+ id: string;
118
+ /** Enough to tell them apart: it can't be claimed with this. */
119
+ short: string;
120
+ /** USD. */
121
+ amount: number;
122
+ /** The first day its credits no longer count (`YYYY-MM-DD`); none: they don't lapse. */
123
+ expires?: string;
124
+ /** The last moment it can be claimed (ISO); none: until it is. */
125
+ until?: string;
126
+ note?: string;
127
+ by: string;
128
+ at: string;
129
+ /** Who took it, for which org, and when. */
130
+ org?: string;
131
+ person?: string;
132
+ claimed?: string;
133
+ revoked?: string;
134
+ };
135
+ /** Gift codes, newest first, for staff's console. */
136
+ export declare function giftCodes(): Promise<GiftCode[]>;
137
+ /** Makes a gift code: the answer's `code` is the only time it's ever shown. */
138
+ export declare const createGiftCode: (code: {
139
+ amount: number;
140
+ expires?: string;
141
+ until?: string;
142
+ note?: string;
143
+ }) => Promise<{
144
+ code: string;
145
+ id: string;
146
+ }>;
147
+ /** Takes back a gift code nobody has claimed. */
148
+ 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
  */
@@ -86,7 +87,7 @@ export function useOrgs() {
86
87
  /** The org the session is in: one of theirs, or (for staff) one they've gone into. */
87
88
  export const currentOrg = (orgs) => orgs.orgs.find((o) => o.id === orgs.current);
88
89
  /** Whether they're in an org as platform staff, not as one of its people. */
89
- export const asStaff = (orgs) => orgs.staff && !!orgs.current && !orgs.orgs.some((o) => o.id === orgs.current);
90
+ export const asStaff = (orgs) => orgs.asStaff === true;
90
91
  /** What an org is called where it shows: everyone's own is "Personal". */
91
92
  export const orgName = (org) => org.kind === "personal" ? "Personal" : org.name;
92
93
  /** What a refusal's status means: not let (403), not done by this app (501), or not so (else). */
@@ -143,7 +144,7 @@ async function into(to, move) {
143
144
  }
144
145
  /** Goes into an org (one of theirs; any, for staff), and starts over at its home. */
145
146
  export function enterOrg(org, staff = false) {
146
- return into({ id: org.id, name: org.name, kind: org.kind, ...(staff ? { staff: true } : {}) }, () => post("/orgs/enter", { org: org.id })).then(() => { });
147
+ return into({ id: org.id, name: org.name, kind: org.kind, ...(staff ? { staff: true } : {}) }, () => post("/orgs/enter", { org: org.id, ...(staff ? { staff: true } : {}) })).then(() => { });
147
148
  }
148
149
  /** Makes a team org, its maker its owner, and goes into it. */
149
150
  export function createOrg(name) {
@@ -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.13",
3
+ "version": "1.0.0-rc.15",
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,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
+ });
@@ -90,10 +90,16 @@ export const myOrgsAction = defineAction({
90
90
  },
91
91
  });
92
92
  export const enterOrgAction = defineAction({
93
- description: "Whether someone may go into an org, and how: the role they join with, and where it lives",
93
+ description: "Whether someone may go into an org, and how: the role they join with, whether as staff " +
94
+ "(asked for, or staff who don't belong to it), and where it lives",
94
95
  input: {
95
96
  type: "object",
96
- properties: { org: { type: "string" }, person, email: { type: "string" } },
97
+ properties: {
98
+ org: { type: "string" },
99
+ person,
100
+ email: { type: "string" },
101
+ staff: { type: "boolean" },
102
+ },
97
103
  required: ["org", "person"],
98
104
  additionalProperties: false,
99
105
  },
@@ -103,9 +109,13 @@ export const enterOrgAction = defineAction({
103
109
  throw forbidden("No such org, or not one you belong to.");
104
110
  const memberships = ctx.db.collection("membership");
105
111
  const mine = await memberships.findOne({ _id: `${input.org}|${input.person}` });
106
- const staff = !mine && await isStaff(ctx, input.person, input.email);
112
+ // Staff who belong to an org go in as one of its people, unless they ask.
113
+ const staff = (!mine || input.staff === true) &&
114
+ await isStaff(ctx, input.person, input.email);
107
115
  if (!mine && !staff)
108
116
  throw forbidden("No such org, or not one you belong to.");
117
+ if (input.staff === true && !staff)
118
+ throw forbidden("Staff only.");
109
119
  if (org.suspended && !staff)
110
120
  throw forbidden("This org is suspended.");
111
121
  if (mine) {
@@ -0,0 +1,114 @@
1
+ /**
2
+ * Gift codes: credits waiting to be claimed into an org, which may not exist
3
+ * yet. Kept here because they aren't any org's until someone claims one. Only a
4
+ * code's hash is kept (`_id`), and the code is shown once. A purchase made
5
+ * outside the app can wait the same way.
6
+ */
7
+ import { type Infer } from "../../../../runtime/mod.js";
8
+ declare const creditCodeSchema: {
9
+ readonly type: "object";
10
+ readonly properties: {
11
+ /** USD, and the first day the credits no longer count (`YYYY-MM-DD`); none: they don't lapse. */
12
+ readonly amount: {
13
+ readonly type: "number";
14
+ };
15
+ readonly expires: {
16
+ readonly type: "string";
17
+ };
18
+ /** The last moment it can be claimed; none: until it is. */
19
+ readonly until: {
20
+ readonly type: "string";
21
+ };
22
+ /** What it's for, as the credits will say. */
23
+ readonly note: {
24
+ readonly type: "string";
25
+ };
26
+ readonly by: {
27
+ readonly type: "string";
28
+ };
29
+ readonly at: {
30
+ readonly type: "string";
31
+ };
32
+ /** Who took it, and when; or that it was taken back. */
33
+ readonly org: {
34
+ readonly type: "string";
35
+ };
36
+ readonly person: {
37
+ readonly type: "string";
38
+ };
39
+ readonly claimed: {
40
+ readonly type: "string";
41
+ };
42
+ readonly revoked: {
43
+ readonly type: "string";
44
+ };
45
+ };
46
+ readonly required: readonly ["amount", "by", "at"];
47
+ };
48
+ export declare const creditCode: {
49
+ schema: {
50
+ readonly type: "object";
51
+ readonly properties: {
52
+ /** USD, and the first day the credits no longer count (`YYYY-MM-DD`); none: they don't lapse. */
53
+ readonly amount: {
54
+ readonly type: "number";
55
+ };
56
+ readonly expires: {
57
+ readonly type: "string";
58
+ };
59
+ /** The last moment it can be claimed; none: until it is. */
60
+ readonly until: {
61
+ readonly type: "string";
62
+ };
63
+ /** What it's for, as the credits will say. */
64
+ readonly note: {
65
+ readonly type: "string";
66
+ };
67
+ readonly by: {
68
+ readonly type: "string";
69
+ };
70
+ readonly at: {
71
+ readonly type: "string";
72
+ };
73
+ /** Who took it, and when; or that it was taken back. */
74
+ readonly org: {
75
+ readonly type: "string";
76
+ };
77
+ readonly person: {
78
+ readonly type: "string";
79
+ };
80
+ readonly claimed: {
81
+ readonly type: "string";
82
+ };
83
+ readonly revoked: {
84
+ readonly type: "string";
85
+ };
86
+ };
87
+ readonly required: readonly ["amount", "by", "at"];
88
+ };
89
+ events?: boolean;
90
+ records?: boolean;
91
+ durable?: false;
92
+ indexes?: string[][];
93
+ private?: string[];
94
+ queries?: Record<string, import("../../../../runtime/define.js").QueryDef<{
95
+ [x: string]: unknown;
96
+ until?: string | undefined;
97
+ person?: string | undefined;
98
+ note?: string | undefined;
99
+ org?: string | undefined;
100
+ expires?: string | undefined;
101
+ revoked?: string | undefined;
102
+ claimed?: string | undefined;
103
+ at: string;
104
+ by: string;
105
+ amount: number;
106
+ } & {
107
+ _id: string;
108
+ }>> | undefined;
109
+ vectors?: string[];
110
+ };
111
+ export type CreditCode = Infer<typeof creditCodeSchema> & {
112
+ _id: string;
113
+ };
114
+ export {};
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Gift codes: credits waiting to be claimed into an org, which may not exist
3
+ * yet. Kept here because they aren't any org's until someone claims one. Only a
4
+ * code's hash is kept (`_id`), and the code is shown once. A purchase made
5
+ * outside the app can wait the same way.
6
+ */
7
+ import { defineCollection } from "../../../../runtime/mod.js";
8
+ const creditCodeSchema = {
9
+ type: "object",
10
+ properties: {
11
+ /** USD, and the first day the credits no longer count (`YYYY-MM-DD`); none: they don't lapse. */
12
+ amount: { type: "number" },
13
+ expires: { type: "string" },
14
+ /** The last moment it can be claimed; none: until it is. */
15
+ until: { type: "string" },
16
+ /** What it's for, as the credits will say. */
17
+ note: { type: "string" },
18
+ by: { type: "string" },
19
+ at: { type: "string" },
20
+ /** Who took it, and when; or that it was taken back. */
21
+ org: { type: "string" },
22
+ person: { type: "string" },
23
+ claimed: { type: "string" },
24
+ revoked: { type: "string" },
25
+ },
26
+ required: ["amount", "by", "at"],
27
+ };
28
+ export const creditCode = defineCollection({ schema: creditCodeSchema });
@@ -18,6 +18,7 @@ export type { Org } from "./collections/org.js";
18
18
  export type { Membership } from "./collections/membership.js";
19
19
  export type { Invite } from "./collections/invite.js";
20
20
  export type { OrgHost } from "./collections/org-host.js";
21
+ export type { CreditCode } from "./collections/credit-code.js";
21
22
  export type { DirectorySettings } from "./shared/settings.js";
22
23
  export declare const directory: Plugin;
23
24
  export default directory;
@@ -17,6 +17,8 @@ import { definePlugin } from "../../../runtime/mod.js";
17
17
  import { createOrgAction, deleteOrgAction, enterOrgAction, getOrgAction, leaveOrgAction, listOrgsAction, myOrgsAction, placeOrgAction, renameOrgAction, reportOrgAction, suspendOrgAction, } from "./actions/org.js";
18
18
  import { answerInviteAction, cancelInviteAction, myInvitesAction, orgInvitesAction, sendInviteAction, } from "./actions/invite.js";
19
19
  import { claimHostAction, releaseHostAction } from "./actions/host.js";
20
+ import { claimCodeAction, createCodeAction, listCodesAction, revokeCodeAction, } from "./actions/code.js";
21
+ import { creditCode } from "./collections/credit-code.js";
20
22
  import { invite } from "./collections/invite.js";
21
23
  import { membership } from "./collections/membership.js";
22
24
  import { org } from "./collections/org.js";
@@ -25,7 +27,7 @@ import { staff } from "./collections/staff.js";
25
27
  export const directory = definePlugin({
26
28
  name: "directory",
27
29
  requires: ["identity"],
28
- collections: { org, membership, invite, staff, orgHost },
30
+ collections: { org, membership, invite, staff, orgHost, creditCode },
29
31
  actions: {
30
32
  "org.create": createOrgAction,
31
33
  "org.mine": myOrgsAction,
@@ -45,6 +47,10 @@ export const directory = definePlugin({
45
47
  "invite.cancel": cancelInviteAction,
46
48
  "host.claim": claimHostAction,
47
49
  "host.release": releaseHostAction,
50
+ "code.create": createCodeAction,
51
+ "code.claim": claimCodeAction,
52
+ "code.list": listCodesAction,
53
+ "code.revoke": revokeCodeAction,
48
54
  },
49
55
  });
50
56
  export default directory;