copilotz 1.0.0-rc.21 → 1.0.0-rc.23

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 (211) hide show
  1. package/CHANGELOG.md +320 -1
  2. package/README.md +217 -87
  3. package/hosts/orgs/mod.d.ts +33 -13
  4. package/hosts/orgs/mod.js +183 -84
  5. package/hosts/web/address.d.ts +11 -0
  6. package/hosts/web/address.js +46 -0
  7. package/hosts/web/assets.js +11 -5
  8. package/hosts/web/entrances.d.ts +250 -0
  9. package/hosts/web/entrances.js +362 -0
  10. package/hosts/web/host.d.ts +15 -3
  11. package/hosts/web/host.js +31 -18
  12. package/hosts/web/mod.d.ts +4 -2
  13. package/hosts/web/mod.js +6 -0
  14. package/hosts/web/node/bundle.d.ts +5 -0
  15. package/hosts/web/node/bundle.js +1 -1
  16. package/hosts/web/node/mod.d.ts +6 -4
  17. package/hosts/web/node/mod.js +6 -4
  18. package/hosts/web/node/serve.d.ts +20 -23
  19. package/hosts/web/node/serve.js +10 -21
  20. package/hosts/web/routes.d.ts +23 -17
  21. package/hosts/web/routes.js +56 -32
  22. package/hosts/web/server.d.ts +89 -44
  23. package/hosts/web/server.js +208 -108
  24. package/hosts/web/signin.d.ts +7 -10
  25. package/hosts/web/signin.js +6 -3
  26. package/hosts/web/surface.d.ts +20 -0
  27. package/hosts/web/surface.js +42 -0
  28. package/hosts/web/theme/css.d.ts +2 -1
  29. package/hosts/web/theme/css.js +9 -2
  30. package/hosts/web/tickets.d.ts +14 -1
  31. package/hosts/web/tickets.js +30 -7
  32. package/hosts/web/widget.d.ts +31 -0
  33. package/hosts/web/widget.js +429 -0
  34. package/hosts/web/widgets.d.ts +43 -0
  35. package/hosts/web/widgets.js +117 -0
  36. package/package.json +5 -1
  37. package/plugins/access/contacts/actions/forget.js +3 -1
  38. package/plugins/access/contacts/actions/start.js +18 -8
  39. package/plugins/access/contacts/collections/contact.d.ts +2 -2
  40. package/plugins/access/contacts/collections/contact.js +1 -1
  41. package/plugins/access/contacts/contract.d.ts +5 -5
  42. package/plugins/access/contacts/contract.js +5 -5
  43. package/plugins/access/contacts/mod.d.ts +4 -0
  44. package/plugins/access/contacts/mod.js +4 -0
  45. package/plugins/access/contacts/views/contact.js +1 -0
  46. package/plugins/access/dev/actions/sign-in.d.ts +1 -0
  47. package/plugins/access/dev/actions/sign-in.js +38 -0
  48. package/plugins/access/dev/mod.d.ts +17 -0
  49. package/plugins/access/dev/mod.js +31 -0
  50. package/plugins/access/dev/shared/nearby.d.ts +2 -0
  51. package/plugins/access/dev/shared/nearby.js +27 -0
  52. package/plugins/access/directory/actions/invite.js +2 -2
  53. package/plugins/access/directory/actions/org.js +11 -8
  54. package/plugins/access/directory/collections/credit-code.d.ts +1 -1
  55. package/plugins/access/google/actions/sign-in.js +2 -0
  56. package/plugins/access/google/mod.d.ts +4 -2
  57. package/plugins/access/google/mod.js +15 -2
  58. package/plugins/access/identity/actions/session.js +5 -3
  59. package/plugins/access/identity/mod.d.ts +4 -2
  60. package/plugins/access/identity/mod.js +17 -2
  61. package/plugins/access/mod.d.ts +7 -0
  62. package/plugins/access/mod.js +1 -0
  63. package/plugins/access/spaces/shared/declared.d.ts +1 -1
  64. package/plugins/access/spaces/shared/rules.d.ts +16 -5
  65. package/plugins/access/spaces/shared/rules.js +74 -6
  66. package/plugins/agents/chat/actions/send.d.ts +21 -0
  67. package/plugins/agents/chat/actions/send.js +72 -13
  68. package/plugins/agents/chat/collections/file.d.ts +15 -0
  69. package/plugins/agents/chat/collections/file.js +12 -3
  70. package/plugins/agents/chat/collections/live.d.ts +11 -0
  71. package/plugins/agents/chat/collections/live.js +11 -1
  72. package/plugins/agents/chat/collections/message.d.ts +1 -1
  73. package/plugins/agents/chat/collections/wait.d.ts +1 -1
  74. package/plugins/agents/chat/contract.d.ts +3 -2
  75. package/plugins/agents/chat/contract.js +1 -0
  76. package/plugins/agents/chat/mod.d.ts +9 -3
  77. package/plugins/agents/chat/mod.js +28 -7
  78. package/plugins/agents/chat/processors/failed.js +8 -3
  79. package/plugins/agents/chat/processors/turn.js +6 -3
  80. package/plugins/agents/chat/shared/agents.js +11 -2
  81. package/plugins/agents/chat/shared/live.d.ts +4 -2
  82. package/plugins/agents/chat/shared/live.js +2 -1
  83. package/plugins/agents/chat/shared/types.d.ts +8 -0
  84. package/plugins/agents/history/collections/outline.d.ts +2 -2
  85. package/plugins/agents/openapi/shared/files.js +2 -0
  86. package/plugins/agents/routines/collections/routine.d.ts +1 -1
  87. package/plugins/billing/credits/collections/plan.d.ts +2 -2
  88. package/plugins/billing/credits/collections/room.d.ts +1 -1
  89. package/plugins/billing/usage/collections/rollup.d.ts +2 -2
  90. package/plugins/billing/usage/collections/usage.d.ts +2 -2
  91. package/plugins/compute/cloud/actions/pool.js +2 -0
  92. package/plugins/compute/cloud/actions/remote.js +4 -2
  93. package/plugins/compute/cloud/actions/vms.js +2 -0
  94. package/plugins/compute/cloud/collections/pool-vm.d.ts +1 -1
  95. package/plugins/compute/computers/actions/admit.js +2 -0
  96. package/plugins/compute/computers/actions/code.js +2 -0
  97. package/plugins/compute/computers/actions/enrollment.js +2 -0
  98. package/plugins/compute/computers/actions/work.js +3 -0
  99. package/plugins/compute/computers/program/version.d.ts +1 -1
  100. package/plugins/compute/computers/program/version.js +1 -1
  101. package/plugins/compute/computers/resources/downloads.js +1 -1
  102. package/plugins/compute/computers/resources/previews.js +5 -2
  103. package/plugins/interfaces/maintenance/mod.d.ts +3 -1
  104. package/plugins/interfaces/maintenance/mod.js +3 -1
  105. package/plugins/interfaces/mcp/actions/call.d.ts +4 -0
  106. package/plugins/interfaces/mcp/actions/call.js +120 -18
  107. package/plugins/interfaces/mcp/actions/conversation.d.ts +1 -0
  108. package/plugins/interfaces/mcp/actions/conversation.js +49 -0
  109. package/plugins/interfaces/mcp/actions/prune.js +5 -3
  110. package/plugins/interfaces/mcp/collections/opening.d.ts +24 -0
  111. package/plugins/interfaces/mcp/collections/opening.js +28 -0
  112. package/plugins/interfaces/mcp/mod.d.ts +27 -3
  113. package/plugins/interfaces/mcp/mod.js +42 -7
  114. package/plugins/interfaces/mcp/resources/server.d.ts +13 -4
  115. package/plugins/interfaces/mcp/resources/server.js +163 -21
  116. package/plugins/interfaces/mcp/resources/tools.d.ts +88 -12
  117. package/plugins/interfaces/mcp/resources/tools.js +113 -19
  118. package/plugins/interfaces/mcp/resources/widgets.d.ts +161 -0
  119. package/plugins/interfaces/mcp/resources/widgets.js +246 -0
  120. package/plugins/interfaces/mcp/shared/keys.d.ts +25 -19
  121. package/plugins/interfaces/mcp/shared/keys.js +55 -9
  122. package/plugins/interfaces/mcp/shared/settings.d.ts +70 -37
  123. package/plugins/interfaces/mcp/shared/settings.js +64 -39
  124. package/plugins/interfaces/mcp/views/offered.d.ts +1 -1
  125. package/plugins/interfaces/mod.d.ts +2 -1
  126. package/plugins/interfaces/mod.js +2 -1
  127. package/plugins/interfaces/voice/collections/blocked.d.ts +2 -2
  128. package/plugins/interfaces/voice/collections/call.d.ts +3 -3
  129. package/plugins/interfaces/voice/contract.d.ts +1 -1
  130. package/plugins/interfaces/voice/mod.d.ts +3 -3
  131. package/plugins/interfaces/voice/mod.js +3 -3
  132. package/plugins/interfaces/voice/resources/relay.d.ts +5 -3
  133. package/plugins/interfaces/voice/resources/relay.js +17 -6
  134. package/plugins/interfaces/voice/resources/tools.js +2 -0
  135. package/plugins/interfaces/voice/shared/settings.d.ts +5 -0
  136. package/plugins/interfaces/voice/views/call.d.ts +18 -11
  137. package/plugins/interfaces/voice/views/call.js +15 -3
  138. package/plugins/interfaces/voice/views/message.d.ts +1 -1
  139. package/plugins/interfaces/web/actions/arrive.d.ts +1 -0
  140. package/plugins/interfaces/web/actions/arrive.js +120 -0
  141. package/plugins/interfaces/web/actions/prune.d.ts +1 -0
  142. package/plugins/interfaces/web/actions/prune.js +51 -0
  143. package/plugins/interfaces/web/actions/sending.d.ts +1 -0
  144. package/plugins/interfaces/web/actions/sending.js +222 -0
  145. package/plugins/interfaces/web/actions/spent.d.ts +2 -0
  146. package/plugins/interfaces/web/actions/spent.js +59 -0
  147. package/plugins/interfaces/web/collections/rate.d.ts +122 -0
  148. package/plugins/interfaces/web/collections/rate.js +37 -0
  149. package/plugins/interfaces/web/collections/visitor.d.ts +110 -0
  150. package/plugins/interfaces/web/collections/visitor.js +64 -0
  151. package/plugins/interfaces/web/contract.d.ts +4 -0
  152. package/plugins/interfaces/web/contract.js +1 -0
  153. package/plugins/interfaces/web/lines.d.ts +36 -0
  154. package/plugins/interfaces/web/lines.js +78 -0
  155. package/plugins/interfaces/web/processors/forget.d.ts +10 -0
  156. package/plugins/interfaces/web/processors/forget.js +14 -0
  157. package/plugins/interfaces/web/resources/entrance.d.ts +47 -0
  158. package/plugins/interfaces/web/resources/entrance.js +83 -0
  159. package/plugins/interfaces/web/resources/spend.d.ts +2 -0
  160. package/plugins/interfaces/web/resources/spend.js +62 -0
  161. package/plugins/interfaces/web/shared/budget.d.ts +65 -0
  162. package/plugins/interfaces/web/shared/budget.js +134 -0
  163. package/plugins/interfaces/web/shared/lines.d.ts +158 -0
  164. package/plugins/interfaces/web/shared/lines.js +156 -0
  165. package/plugins/interfaces/web/shared/secret.d.ts +33 -0
  166. package/plugins/interfaces/web/shared/secret.js +86 -0
  167. package/plugins/interfaces/whatsapp/collections/phone.d.ts +1 -1
  168. package/plugins/interfaces/whatsapp/mod.d.ts +1 -1
  169. package/plugins/interfaces/whatsapp/mod.js +1 -1
  170. package/plugins/interfaces/whatsapp/views/message.d.ts +1 -1
  171. package/plugins/models/contract.d.ts +1 -1
  172. package/plugins/models/shared/generate.js +13 -4
  173. package/plugins/models/shared/transcribe.js +7 -1
  174. package/plugins/models/shared/use.d.ts +16 -2
  175. package/plugins/models/shared/use.js +20 -0
  176. package/runtime/browsers.d.ts +153 -17
  177. package/runtime/browsers.js +336 -30
  178. package/runtime/cache.js +25 -5
  179. package/runtime/caller.d.ts +117 -0
  180. package/runtime/caller.js +215 -0
  181. package/runtime/client.d.ts +47 -3
  182. package/runtime/client.js +132 -42
  183. package/runtime/define.d.ts +30 -9
  184. package/runtime/executor.js +7 -6
  185. package/runtime/expiring.d.ts +23 -0
  186. package/runtime/expiring.js +64 -0
  187. package/runtime/links.d.ts +27 -4
  188. package/runtime/links.js +49 -11
  189. package/runtime/memory.js +102 -15
  190. package/runtime/mod.d.ts +3 -1
  191. package/runtime/mod.js +3 -1
  192. package/runtime/mongo.d.ts +12 -0
  193. package/runtime/mongo.js +44 -0
  194. package/runtime/observe.js +82 -9
  195. package/runtime/ops.d.ts +9 -1
  196. package/runtime/owner.d.ts +14 -1
  197. package/runtime/owner.js +78 -23
  198. package/runtime/reads.js +2 -2
  199. package/runtime/registry.js +9 -3
  200. package/runtime/runtime.d.ts +7 -0
  201. package/runtime/runtime.js +1 -0
  202. package/runtime/timers.js +2 -0
  203. package/runtime/views.d.ts +1 -1
  204. package/runtime/views.js +2 -2
  205. package/runtime/wire.d.ts +1 -1
  206. package/stores/sql/postgres/maintenance.d.ts +8 -1
  207. package/stores/sql/postgres/maintenance.js +76 -9
  208. package/stores/sql/postgres/mod.d.ts +12 -4
  209. package/stores/sql/postgres/mod.js +21 -8
  210. package/plugins/interfaces/mcp/shared/caller.d.ts +0 -45
  211. package/plugins/interfaces/mcp/shared/caller.js +0 -99
@@ -0,0 +1,43 @@
1
+ import { type Known } from "../../runtime/client.js";
2
+ import type { Actor, Plugins, Runtime, Viewer } from "../../runtime/mod.js";
3
+ /** Bundled code, as `bundle` makes it (one file, for a widget: `split: false`). */
4
+ type Code = {
5
+ entry: string;
6
+ files: Record<string, string | Uint8Array>;
7
+ };
8
+ export type WidgetsOptions = {
9
+ /**
10
+ * The widget host and the app's widget front ends, bundled as one file
11
+ * (`bundle(entry, { split: false })`), or a function that bundles it, once.
12
+ * Its entry calls `widget({ plugins, root })` (`copilotz/web/widget`).
13
+ */
14
+ code: Code | (() => Code | Promise<Code>);
15
+ /** The same front ends, here: the Views a snapshot runs, and the theme the page is in. */
16
+ plugins: Plugins;
17
+ /** The page's language (`pt-BR`), English unless said. */
18
+ lang?: string;
19
+ };
20
+ export type SnapshotOptions = {
21
+ /** Whose reads: the conversation's contact. */
22
+ actor: Actor;
23
+ viewer: Viewer;
24
+ /** The View, its item and hints, as the widget will observe them first. */
25
+ view: string;
26
+ item: unknown;
27
+ hints: Record<string, unknown>;
28
+ /** The most bytes kept (256 KiB): past it, none. */
29
+ limit?: number;
30
+ /** How long it waits for the View's reads (5 s): past it, what it has. */
31
+ wait?: number;
32
+ };
33
+ export type Widgets = {
34
+ /** The template, for the app at `origin` (its fonts come from there), and its version. */
35
+ page(origin: string): Promise<{
36
+ html: string;
37
+ version: string;
38
+ }>;
39
+ /** What the View reads, answered as the actor, by the client's keys. */
40
+ snapshot(runtime: Pick<Runtime, "query">, options: SnapshotOptions): Promise<Known>;
41
+ };
42
+ export declare function widgetsOf(options: WidgetsOptions): Widgets;
43
+ export {};
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Widgets, the server's half: an app's web Views drawn inside an outside assistant's
3
+ * conversation (an MCP Apps host: ChatGPT, Claude…), where the MCP interface's lines show a
4
+ * tool's call through a View of the app's (`plugins/interfaces/mcp`). The browser's half is
5
+ * `widget.tsx`, which this bundles for: the template the assistant loads, and the reads the
6
+ * View makes, answered here first, so a widget draws at once.
7
+ *
8
+ * - **The template** (`page(origin)`): one HTML page with the widget host and the app's widget
9
+ * front ends inlined as one module (bundled without split chunks: the assistant's sandbox
10
+ * loads nothing else of the app's code), in the app's theme (its variables, light and dark,
11
+ * dark also by the host's word: `data-theme`), its fonts from the app's own origin (`origin`:
12
+ * the stylesheet's address made whole, which the line's CSP lets in). Its `version` is a hash
13
+ * of the page: a new deploy is a new template.
14
+ * - **A snapshot** (`snapshot(runtime, …)`): the View the tool's call is shown through, run
15
+ * here as the conversation's contact with the same front ends, its reads answered by the
16
+ * runtime as that contact (queries only, each its `allow`, under the rules, without private
17
+ * fields: exactly what the widget could read itself), and what it read, by the client's keys,
18
+ * kept: the widget is seeded with it, so its first paint asks nothing. Past `limit` bytes
19
+ * (256 KiB), nothing is kept: the widget reads it all itself.
20
+ *
21
+ * A widget reads only through queries (named reads with an `allow`): a direct read of a
22
+ * collection is refused here and in the widget's own reads (MCP's `copilotz_read`).
23
+ *
24
+ * ```ts
25
+ * const widgets = widgetsOf({
26
+ * code: await bundle(new URL("./widgets.tsx", import.meta.url), { split: false }),
27
+ * plugins: [brandTheme, bookingWeb],
28
+ * });
29
+ * await serve({ runtime, widgets, port: 8080 });
30
+ * ```
31
+ */
32
+ import { answeredAs } from "../../runtime/browsers.js";
33
+ import { connect } from "../../runtime/client.js";
34
+ import { invalid } from "../../runtime/errors.js";
35
+ import { BASE } from "./style.js";
36
+ import { fontsOf, preloadsOf, themeCss, themeOf } from "./theme/css.js";
37
+ const LIMIT = 256 * 1024;
38
+ const WAIT = 5_000;
39
+ /** Text that can't end the attribute it goes in. */
40
+ const quoted = (text) => text.replaceAll("&", "&amp;").replaceAll('"', "&quot;").replaceAll("<", "&lt;");
41
+ const sha = async (text) => [
42
+ ...new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text))),
43
+ ].map((b) => b.toString(16).padStart(2, "0")).join("");
44
+ export function widgetsOf(options) {
45
+ let bundled;
46
+ const code = () => bundled ??= Promise.resolve(typeof options.code === "function" ? options.code() : options.code)
47
+ .then((made) => {
48
+ const names = Object.keys(made.files);
49
+ if (names.length !== 1 || !(made.entry in made.files)) {
50
+ throw new Error("widgets: the code is one file (bundle it with { split: false }), with its entry");
51
+ }
52
+ const file = made.files[made.entry];
53
+ return typeof file === "string" ? file : new TextDecoder().decode(file);
54
+ });
55
+ const theme = themeOf(options.plugins);
56
+ const pages = new Map();
57
+ const page = (origin) => {
58
+ const at = new URL(origin).origin;
59
+ let made = pages.get(at);
60
+ if (!made) {
61
+ made = code().then(async (script) => {
62
+ const fonts = fontsOf(theme);
63
+ const whole = (path) => path.startsWith("/") ? `${at}${path}` : path;
64
+ const css = `${themeCss(theme)}\n${BASE}`.replaceAll("<", "\\3c ");
65
+ const html = `<!doctype html>
66
+ <html lang="${quoted(options.lang ?? "en")}">
67
+ <head>
68
+ <meta charset="utf-8">
69
+ <meta name="viewport" content="width=device-width, initial-scale=1">
70
+ ${preloadsOf(theme).map(({ href, type }) => `<link rel="preload" href="${quoted(whole(href))}" as="font" type="${type}" crossorigin>\n`).join("")}${fonts ? `<link rel="stylesheet" href="${quoted(whole(fonts))}" crossorigin>\n` : ""}<style id="copilotz-first-paint">${css}</style>
71
+ <script id="copilotz-config" type="application/json">${JSON.stringify({ origin: at }).replaceAll("<", "\\u003c")}</script>
72
+ </head>
73
+ <body>
74
+ <div id="app"></div>
75
+ <script type="module">${
76
+ // Nothing in the code may end its element, in any case, or open a comment there.
77
+ script.replace(/<\/(script)/gi, "<\\/$1").replaceAll("<!--", "<\\!--")}</script>
78
+ </body>
79
+ </html>`;
80
+ return { html, version: (await sha(html)).slice(0, 12) };
81
+ });
82
+ made.catch(() => pages.delete(at));
83
+ pages.set(at, made);
84
+ }
85
+ return made;
86
+ };
87
+ const snapshot = async (runtime, asked) => {
88
+ const { actor } = asked;
89
+ const client = connect({
90
+ plugins: options.plugins,
91
+ link: {
92
+ read: (reads) => Promise.all(reads.map(({ key, read }) => answeredAs(runtime, actor, key, read))),
93
+ call: () => Promise.reject(invalid("A snapshot calls nothing")),
94
+ },
95
+ });
96
+ const seen = client.observe("web", asked.view, asked.item, {
97
+ viewer: asked.viewer,
98
+ hints: asked.hints,
99
+ part: () => null,
100
+ });
101
+ let timer;
102
+ try {
103
+ await Promise.race([
104
+ seen.ready.then(() => client.idle()),
105
+ new Promise((resolve) => timer = setTimeout(resolve, asked.wait ?? WAIT)),
106
+ ]);
107
+ const known = client.known();
108
+ return JSON.stringify(known).length <= (asked.limit ?? LIMIT) ? known : [];
109
+ }
110
+ finally {
111
+ clearTimeout(timer);
112
+ seen.close();
113
+ await client.close();
114
+ }
115
+ };
116
+ return { page, snapshot };
117
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "copilotz",
3
- "version": "1.0.0-rc.21",
3
+ "version": "1.0.0-rc.23",
4
4
  "description": "Copilotz: one runtime for Node, Deno, Bun, Cloudflare Workers and the browser.",
5
5
  "keywords": [
6
6
  "agents",
@@ -134,6 +134,10 @@
134
134
  "types": "./hosts/web/server.d.ts",
135
135
  "default": "./hosts/web/server.js"
136
136
  },
137
+ "./web/widget": {
138
+ "types": "./hosts/web/widget.d.ts",
139
+ "default": "./hosts/web/widget.js"
140
+ },
137
141
  "./web/tickets": {
138
142
  "types": "./hosts/web/tickets.d.ts",
139
143
  "default": "./hosts/web/tickets.js"
@@ -3,7 +3,9 @@
3
3
  * space its record lives in. Its memberships go, which ends its access to
4
4
  * every chat at once (`member.deleted`), and so does its record
5
5
  * (`contact.deleted`: the WhatsApp plugin erases its phone, but not a block
6
- * on it, kept by a hash). With `chats`, its chats go too, with everything
6
+ * on it, kept by a hash; the web lines end a visitor's cookie and its
7
+ * browsers' connections). With
8
+ * `chats`, its chats go too, with everything
7
9
  * chat and its plugins keep of them (`chat.erase`), each only for someone
8
10
  * who manages that chat's space.
9
11
  *
@@ -4,9 +4,12 @@
4
4
  * proved who they are (Meta's signed webhook names the phone), with an id
5
5
  * from what brought them (`id`), so a retry makes the same one; starting
6
6
  * one that exists changes only its name, if that changed. Its record is
7
- * shared with it on its own (it reads it, and the agent working for it does).
7
+ * shared with it on its own (it reads it, and the agent working for it
8
+ * does): a start cut short between the two (an owner restarted) shares it
9
+ * when it's started again.
8
10
  */
9
11
  import { defineAction } from "../../../../runtime/mod.js";
12
+ import { CONTACT } from "../collections/contact.js";
10
13
  export const startAction = defineAction({
11
14
  description: "Makes a contact: someone outside the org who came by a line",
12
15
  input: {
@@ -26,10 +29,22 @@ export const startAction = defineAction({
26
29
  const contacts = ctx.db.collection("contact");
27
30
  const id = input.id ?? `c-${crypto.randomUUID()}`;
28
31
  const name = input.name?.trim();
29
- const known = await contacts.findOne({ _id: id });
32
+ const share = () => ctx.call("member.set", {
33
+ space: id,
34
+ on: "contact",
35
+ member: { kind: "contact", id },
36
+ role: "viewer",
37
+ });
38
+ // Its record, and its share of it (the record's own key, and the contact's).
39
+ const [known, shared] = await Promise.all([
40
+ contacts.findOne({ _id: id }),
41
+ ctx.as().db.collection("member").findOne({ _id: `${CONTACT}${id}|${CONTACT}${id}` }),
42
+ ]);
30
43
  if (known) {
31
44
  if (name && known.name !== name)
32
45
  await contacts.updateOne({ _id: id }, { $set: { name } });
46
+ if (!shared)
47
+ await share();
33
48
  return { contact: id };
34
49
  }
35
50
  await contacts.insertOne({
@@ -39,12 +54,7 @@ export const startAction = defineAction({
39
54
  ...(name ? { name } : {}),
40
55
  at: new Date().toISOString(),
41
56
  });
42
- await ctx.call("member.set", {
43
- space: id,
44
- on: "contact",
45
- member: { kind: "contact", id },
46
- role: "viewer",
47
- });
57
+ await share();
48
58
  return { contact: id };
49
59
  },
50
60
  });
@@ -15,7 +15,7 @@ declare const contactSchema: {
15
15
  readonly in: {
16
16
  readonly type: "string";
17
17
  };
18
- /** Where it first came from: `whatsapp`. */
18
+ /** Where it first came from: `whatsapp`, `voice`, `mcp`, `web`. */
19
19
  readonly via: {
20
20
  readonly type: "string";
21
21
  };
@@ -39,7 +39,7 @@ export declare const contact: {
39
39
  readonly in: {
40
40
  readonly type: "string";
41
41
  };
42
- /** Where it first came from: `whatsapp`. */
42
+ /** Where it first came from: `whatsapp`, `voice`, `mcp`, `web`. */
43
43
  readonly via: {
44
44
  readonly type: "string";
45
45
  };
@@ -14,7 +14,7 @@ const contactSchema = {
14
14
  properties: {
15
15
  /** The space of the line it first came by. */
16
16
  in: { type: "string" },
17
- /** Where it first came from: `whatsapp`. */
17
+ /** Where it first came from: `whatsapp`, `voice`, `mcp`, `web`. */
18
18
  via: { type: "string" },
19
19
  /** What it's called: its WhatsApp profile's name. */
20
20
  name: { type: "string" },
@@ -1,10 +1,10 @@
1
1
  /**
2
2
  * The contacts plugin's contract: what other plugins and apps may import:
3
3
  * the shape of a contact, how one shows as an actor (`contact:<id>`, a
4
- * message's `from`), and whose work an actor's is (`contactOf(event.actor)`:
5
- * the contact's id, also for the agent working for them). They reach the
6
- * rest by name: its collection (`contact`, and its `names` query), its
7
- * Actions (`contact.start`, `contact.chat`, `contact.forget`) and the
8
- * event its record's erasure is (`contact.deleted`).
4
+ * message's `from`), whose work an actor's is (`contactOf(event.actor)`:
5
+ * the contact's id, also for the agent working for them). They reach the rest by name:
6
+ * its collection (`contact`, and its `names` query), its Actions (`contact.start`,
7
+ * `contact.chat`, `contact.forget`) and the event its record's erasure is
8
+ * (`contact.deleted`).
9
9
  */
10
10
  export { CONTACT, type Contact, contactOf } from "./collections/contact.js";
@@ -1,10 +1,10 @@
1
1
  /**
2
2
  * The contacts plugin's contract: what other plugins and apps may import:
3
3
  * the shape of a contact, how one shows as an actor (`contact:<id>`, a
4
- * message's `from`), and whose work an actor's is (`contactOf(event.actor)`:
5
- * the contact's id, also for the agent working for them). They reach the
6
- * rest by name: its collection (`contact`, and its `names` query), its
7
- * Actions (`contact.start`, `contact.chat`, `contact.forget`) and the
8
- * event its record's erasure is (`contact.deleted`).
4
+ * message's `from`), whose work an actor's is (`contactOf(event.actor)`:
5
+ * the contact's id, also for the agent working for them). They reach the rest by name:
6
+ * its collection (`contact`, and its `names` query), its Actions (`contact.start`,
7
+ * `contact.chat`, `contact.forget`) and the event its record's erasure is
8
+ * (`contact.deleted`).
9
9
  */
10
10
  export { CONTACT, contactOf } from "./collections/contact.js";
@@ -16,9 +16,13 @@
16
16
  * and see them by name ("People here: Ana": a `names` source, `contact:`).
17
17
  * - **Erasing one** (`contact.forget`, by its space's managers) ends its
18
18
  * access at once and deletes its record, and with `chats` its chats.
19
+ * - **Lines** bring contacts in: WhatsApp's, the phone's, MCP's and the web's (`webLines`, in
20
+ * the web interface: visitors of a page) are interfaces of their own; contacts keeps what
21
+ * every line shares.
19
22
  *
20
23
  * ```ts
21
24
  * plugins: [models, chat, ...access] // access brings contacts
25
+ * resources: { spaces: { support: { name: "Support", agents: ["guide"] } } }
22
26
  * ```
23
27
  */
24
28
  import { type Plugin } from "../../../runtime/mod.js";
@@ -16,9 +16,13 @@
16
16
  * and see them by name ("People here: Ana": a `names` source, `contact:`).
17
17
  * - **Erasing one** (`contact.forget`, by its space's managers) ends its
18
18
  * access at once and deletes its record, and with `chats` its chats.
19
+ * - **Lines** bring contacts in: WhatsApp's, the phone's, MCP's and the web's (`webLines`, in
20
+ * the web interface: visitors of a page) are interfaces of their own; contacts keeps what
21
+ * every line shares.
19
22
  *
20
23
  * ```ts
21
24
  * plugins: [models, chat, ...access] // access brings contacts
25
+ * resources: { spaces: { support: { name: "Support", agents: ["guide"] } } }
22
26
  * ```
23
27
  */
24
28
  import { definePlugin } from "../../../runtime/mod.js";
@@ -10,6 +10,7 @@ const FROM = {
10
10
  whatsapp: "writing on WhatsApp",
11
11
  voice: "on a phone call: they hear what you write, read aloud. The number they call from " +
12
12
  "isn't proof of who they are",
13
+ web: "chatting on the website, with nothing that proves who they are",
13
14
  };
14
15
  export const contactView = (_thread, ctx) => {
15
16
  const principal = principalOf(ctx.actor);
@@ -0,0 +1 @@
1
+ export declare const signInAction: import("../../../../runtime/define.js").ActionDef;
@@ -0,0 +1,38 @@
1
+ /**
2
+ * `dev.sign-in`: someone signs in by the name they type, for trying things
3
+ * out. A plain name (`ana`) is a person by that id; an email is one too,
4
+ * with that email (so invitations to it reach them), named by its first
5
+ * part. The web host calls it, as the system, only from this machine
6
+ * (`local`); it's never anyone's to call.
7
+ */
8
+ import { defineAction } from "../../../../runtime/mod.js";
9
+ const EMAIL = /^[a-z0-9._+-]{1,64}@[a-z0-9.-]{1,64}$/;
10
+ const NAME = /^[a-z0-9._-]{1,40}$/;
11
+ export const signInAction = defineAction({
12
+ description: "Signs in by name, on this machine: the person, and a new session",
13
+ // Unrecorded: its result is the session's secret.
14
+ record: false,
15
+ input: {
16
+ type: "object",
17
+ properties: { name: { type: "string", maxLength: 129 } },
18
+ required: ["name"],
19
+ additionalProperties: false,
20
+ },
21
+ run: async (ctx, input) => {
22
+ const person = input.name.trim().toLowerCase();
23
+ const email = EMAIL.test(person);
24
+ if (!email && !NAME.test(person)) {
25
+ throw Object.assign(new Error("A name (letters, digits, . _ -) or an email"), {
26
+ code: "invalid",
27
+ public: true,
28
+ });
29
+ }
30
+ await ctx.call("person.set", {
31
+ person,
32
+ ...(email ? { email: person } : {}),
33
+ name: email ? person.split("@")[0] : person,
34
+ });
35
+ const { session } = await ctx.call("session.start", { person });
36
+ return { person, session };
37
+ },
38
+ });
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Dev sign-in: people sign in by the name they type, from this machine only,
3
+ * for trying an app out (with the identity plugin). It declares itself to
4
+ * the web host (`signIn.dev`, `local`): the page shows a field for the name,
5
+ * and `POST /signin/dev` `{ name }` from a loopback address, to a loopback
6
+ * host, with nothing saying a proxy forwarded it, sets the session's cookie.
7
+ * Leave it out of a deployed app: an app whose `links` origin is public
8
+ * (not this machine, nor one on its network) doesn't start with it, since a
9
+ * proxy on its machine that says nothing of whom it forwards for would make
10
+ * anyone this machine.
11
+ *
12
+ * ```ts
13
+ * plugins: [...access, ...(process.env.DEV ? [devSignIn] : [])]
14
+ * ```
15
+ */
16
+ import { type Plugin } from "../../../runtime/mod.js";
17
+ export declare const devSignIn: Plugin;
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Dev sign-in: people sign in by the name they type, from this machine only,
3
+ * for trying an app out (with the identity plugin). It declares itself to
4
+ * the web host (`signIn.dev`, `local`): the page shows a field for the name,
5
+ * and `POST /signin/dev` `{ name }` from a loopback address, to a loopback
6
+ * host, with nothing saying a proxy forwarded it, sets the session's cookie.
7
+ * Leave it out of a deployed app: an app whose `links` origin is public
8
+ * (not this machine, nor one on its network) doesn't start with it, since a
9
+ * proxy on its machine that says nothing of whom it forwards for would make
10
+ * anyone this machine.
11
+ *
12
+ * ```ts
13
+ * plugins: [...access, ...(process.env.DEV ? [devSignIn] : [])]
14
+ * ```
15
+ */
16
+ import { definePlugin } from "../../../runtime/mod.js";
17
+ import { signInAction } from "./actions/sign-in.js";
18
+ import { publicOrigin } from "./shared/nearby.js";
19
+ export const devSignIn = definePlugin({
20
+ name: "dev-sign-in",
21
+ requires: ["identity"],
22
+ actions: { "dev.sign-in": signInAction },
23
+ resources: { signIn: { dev: { action: "dev.sign-in", local: true } } },
24
+ check(merged) {
25
+ const origin = publicOrigin(merged.resources);
26
+ if (origin) {
27
+ throw new Error(`devSignIn signs in by name, for this machine only, but the app's links origin ` +
28
+ `(${origin}) is public: leave devSignIn out of a deployed app`);
29
+ }
30
+ },
31
+ });
@@ -0,0 +1,2 @@
1
+ /** The app's public origin, if its `links` resource says it's somewhere public; else undefined. */
2
+ export declare function publicOrigin(resources: Record<string, unknown>): string | undefined;
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Whether the app is somewhere public: the origin its `links` resource says
3
+ * it's at (where its links and pages are), unless that's this machine or one
4
+ * on its network (`localhost`, a `.local` name, a loopback, private or
5
+ * link-local address: `privateAddress`). Dev sign-in doesn't start in one.
6
+ */
7
+ import { privateAddress } from "../../../../runtime/mod.js";
8
+ /** Whether a host name is this machine's or one on its network. */
9
+ const nearby = (hostname) => {
10
+ const name = hostname.replace(/^\[|\]$/g, "").toLowerCase();
11
+ return name === "localhost" || name.endsWith(".localhost") || name.endsWith(".local") ||
12
+ privateAddress(name);
13
+ };
14
+ /** The app's public origin, if its `links` resource says it's somewhere public; else undefined. */
15
+ export function publicOrigin(resources) {
16
+ const origin = resources.links?.origin;
17
+ if (typeof origin !== "string" || !origin)
18
+ return undefined;
19
+ let host;
20
+ try {
21
+ host = new URL(origin).hostname;
22
+ }
23
+ catch {
24
+ return origin;
25
+ }
26
+ return nearby(host) ? undefined : origin;
27
+ }
@@ -4,7 +4,7 @@
4
4
  * theirs when they sign in, and accepting one makes them belong, with the
5
5
  * invitation's role for their first entering. All are the system's.
6
6
  */
7
- import { defineAction, forbidden } from "../../../../runtime/mod.js";
7
+ import { defineAction, failure } from "../../../../runtime/mod.js";
8
8
  export const sendInviteAction = defineAction({
9
9
  description: "Invites an email to an org, with a role",
10
10
  input: {
@@ -93,7 +93,7 @@ export const answerInviteAction = defineAction({
93
93
  const invites = ctx.db.collection("invite");
94
94
  const found = await invites.findOne({ _id: input.invite });
95
95
  if (!found || found.email !== input.email.toLowerCase()) {
96
- throw forbidden("No such invitation for you.");
96
+ throw failure("forbidden", "No such invitation for you.", { public: true });
97
97
  }
98
98
  await ctx.transaction(async (tx) => {
99
99
  if (input.accept) {
@@ -11,7 +11,7 @@
11
11
  * - `org.leave`: someone no longer belongs (their org took them out);
12
12
  * - `org.suspend`, `org.rename`, `org.report` (its summary), `org.list`.
13
13
  */
14
- import { defineAction, forbidden } from "../../../../runtime/mod.js";
14
+ import { defineAction, failure } from "../../../../runtime/mod.js";
15
15
  import { isStaff, placementOf } from "../shared/settings.js";
16
16
  const person = { type: "string" };
17
17
  export const createOrgAction = defineAction({
@@ -105,19 +105,22 @@ export const enterOrgAction = defineAction({
105
105
  },
106
106
  run: async (ctx, input) => {
107
107
  const org = await ctx.db.collection("org").findOne({ _id: input.org });
108
- if (!org)
109
- throw forbidden("No such org, or not one you belong to.");
108
+ if (!org) {
109
+ throw failure("forbidden", "No such org, or not one you belong to.", { public: true });
110
+ }
110
111
  const memberships = ctx.db.collection("membership");
111
112
  const mine = await memberships.findOne({ _id: `${input.org}|${input.person}` });
112
113
  // Staff who belong to an org go in as one of its people, unless they ask.
113
114
  const staff = (!mine || input.staff === true) &&
114
115
  await isStaff(ctx, input.person, input.email);
115
- if (!mine && !staff)
116
- throw forbidden("No such org, or not one you belong to.");
116
+ if (!mine && !staff) {
117
+ throw failure("forbidden", "No such org, or not one you belong to.", { public: true });
118
+ }
117
119
  if (input.staff === true && !staff)
118
- throw forbidden("Staff only.");
119
- if (org.suspended && !staff)
120
- throw forbidden("This org is suspended.");
120
+ throw failure("forbidden", "Staff only.", { public: true });
121
+ if (org.suspended && !staff) {
122
+ throw failure("forbidden", "This org is suspended.", { public: true });
123
+ }
121
124
  if (mine) {
122
125
  await memberships.updateOne({ _id: mine._id }, {
123
126
  $set: { entered: new Date().toISOString() },
@@ -94,9 +94,9 @@ export declare const creditCode: {
94
94
  queries?: Record<string, import("../../../../runtime/define.js").QueryDef<{
95
95
  [x: string]: unknown;
96
96
  person?: string | undefined;
97
- until?: string | undefined;
98
97
  note?: string | undefined;
99
98
  org?: string | undefined;
99
+ until?: string | undefined;
100
100
  expires?: string | undefined;
101
101
  revoked?: string | undefined;
102
102
  claimed?: string | undefined;
@@ -9,6 +9,8 @@ import { verify } from "../shared/jwt.js";
9
9
  import { settingsOf } from "../shared/settings.js";
10
10
  export const signInAction = defineAction({
11
11
  description: "Signs in with a Google ID token: the person, and a new session",
12
+ // Unrecorded: its input is the ID token and its result the session's secret.
13
+ record: false,
12
14
  input: {
13
15
  type: "object",
14
16
  properties: { idToken: { type: "string" } },
@@ -2,7 +2,9 @@
2
2
  * Google sign-in: `google.sign-in` turns a Google ID token into a person
3
3
  * and a session (with the identity plugin). The `google` resource's
4
4
  * `clientId` is your OAuth client's (or several): tokens issued for another
5
- * app are refused.
5
+ * app are refused. It declares itself to the web host (`signIn.google`):
6
+ * the page shows Google's button for the first client id, and
7
+ * `POST /signin/google` `{ idToken }` sets the session's cookie.
6
8
  *
7
9
  * ```ts
8
10
  * plugins: [spaces, identity, googleSignIn, definePlugin({
@@ -10,7 +12,7 @@
10
12
  * resources: { google: { clientId: "1234.apps.googleusercontent.com" } },
11
13
  * })]
12
14
  * const { session } = await runtime.call("google.sign-in", { idToken });
13
- * // Set-Cookie: session=<session>; HttpOnly; Secure; SameSite=Lax; Path=/
15
+ * // Set-Cookie: __Host-session=<session>; HttpOnly; SameSite=Lax; Path=/; …; Secure
14
16
  * ```
15
17
  */
16
18
  import { type Plugin } from "../../../runtime/mod.js";
@@ -2,7 +2,9 @@
2
2
  * Google sign-in: `google.sign-in` turns a Google ID token into a person
3
3
  * and a session (with the identity plugin). The `google` resource's
4
4
  * `clientId` is your OAuth client's (or several): tokens issued for another
5
- * app are refused.
5
+ * app are refused. It declares itself to the web host (`signIn.google`):
6
+ * the page shows Google's button for the first client id, and
7
+ * `POST /signin/google` `{ idToken }` sets the session's cookie.
6
8
  *
7
9
  * ```ts
8
10
  * plugins: [spaces, identity, googleSignIn, definePlugin({
@@ -10,7 +12,7 @@
10
12
  * resources: { google: { clientId: "1234.apps.googleusercontent.com" } },
11
13
  * })]
12
14
  * const { session } = await runtime.call("google.sign-in", { idToken });
13
- * // Set-Cookie: session=<session>; HttpOnly; Secure; SameSite=Lax; Path=/
15
+ * // Set-Cookie: __Host-session=<session>; HttpOnly; SameSite=Lax; Path=/; …; Secure
14
16
  * ```
15
17
  */
16
18
  import { definePlugin } from "../../../runtime/mod.js";
@@ -23,6 +25,17 @@ export const googleSignIn = definePlugin({
23
25
  requires: ["identity"],
24
26
  actions: { "google.sign-in": signInAction },
25
27
  adapters: { googleKeys: { google: googleKeys() } },
28
+ resources: {
29
+ // The page's button is for the web client: the first id, when there are several.
30
+ signIn: {
31
+ google: {
32
+ action: "google.sign-in",
33
+ page: (resources) => ({
34
+ clientId: [settingsOf({ resources }).clientId].flat()[0],
35
+ }),
36
+ },
37
+ },
38
+ },
26
39
  check(merged) {
27
40
  if (!settingsOf(merged).clientId)
28
41
  throw new Error("set the google resource's clientId");
@@ -35,16 +35,18 @@ export const startSession = defineAction({
35
35
  });
36
36
  export const endSession = defineAction({
37
37
  description: "Ends the session whose secret is shown",
38
+ // Unrecorded: its input is the secret.
39
+ record: false,
38
40
  input: {
39
41
  type: "object",
40
- properties: { session: { type: "string" } },
41
- required: ["session"],
42
+ properties: { secret: { type: "string" } },
43
+ required: ["secret"],
42
44
  additionalProperties: false,
43
45
  },
44
46
  allow: people,
45
47
  run: async (ctx, input) => {
46
48
  const ended = await ctx.as().db.collection("credential").deleteOne({
47
- _id: await hash(input.session),
49
+ _id: await hash(input.secret),
48
50
  person: ctx.actor.id,
49
51
  kind: "session",
50
52
  });