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
package/hosts/web/host.js CHANGED
@@ -1,10 +1,11 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  /**
3
- * The web host, in the browser: it connects as the signed-in person (a
4
- * ticket from `/connect`, which trades the session cookie), observes the web
5
- * shell for the address it's at (its path, where the person works, `?in=`,
6
- * and its other parameters), and draws it with React, each part a
7
- * component redrawn on its own. Where you are is the address: links are
3
+ * The web host, in the browser: it connects as whoever the browser is (a
4
+ * ticket from `/connect`, which trades the cookie the server keeps: the
5
+ * signed-in person, or a web line's visitor, let in when the page asks,
6
+ * `arrive`), observes the web shell for the address it's at (its path, where
7
+ * the person works, `?in=`, and its other parameters), and draws it with
8
+ * React, each part a component redrawn on its own. Where you are is the address: links are
8
9
  * followed without reloading, back and forward work, two tabs differ. The
9
10
  * connection is kept for `LazyView`, which observes a View on demand.
10
11
  *
@@ -57,13 +58,23 @@ export async function signOut() {
57
58
  location.assign("/");
58
59
  }
59
60
  const config = () => JSON.parse(document.getElementById("copilotz-config")?.textContent ?? "{}");
60
- /** A ticket for one connection, or nothing when nobody is signed in. */
61
- async function ticket() {
62
- const response = await fetch("/connect", { method: "POST" });
61
+ /**
62
+ * A ticket for one connection, or nothing when the browser is nobody: from
63
+ * the app the page is (its `base`, with many orgs: an org's web line is its
64
+ * own, there).
65
+ */
66
+ async function ticket(arrive) {
67
+ const response = await fetch(`${config().base ?? ""}/connect`, {
68
+ method: "POST",
69
+ headers: { "content-type": "application/json" },
70
+ body: JSON.stringify(arrive ?? {}),
71
+ });
63
72
  if (response.status === 401)
64
73
  return undefined;
65
- if (!response.ok)
66
- throw new Error(`Couldn't connect: ${response.statusText}`);
74
+ if (!response.ok) {
75
+ const said = await response.json().catch(() => null);
76
+ throw new Error(said?.error ?? `Couldn't connect: ${response.statusText}`);
77
+ }
67
78
  return await response.json();
68
79
  }
69
80
  export async function web(options) {
@@ -84,16 +95,18 @@ export async function web(options) {
84
95
  draw(null);
85
96
  // Installable, and told when a new version is ready (see pwa.ts).
86
97
  registerWorker();
87
- const first = await ticket();
98
+ const first = await ticket(options.arrive);
88
99
  if (!first) {
89
100
  // Still signed in, but no longer in this org (with many): into another of theirs.
90
101
  if (await reenter())
91
102
  return undefined;
92
- draw(_jsx(SignIn, { config: config() }));
103
+ draw(_jsx(SignIn, { signIn: config().signIn ?? {} }));
93
104
  return undefined;
94
105
  }
106
+ const person = first.actor.kind === "person";
95
107
  // The person's orgs (when the server serves many), asked while the connection is made.
96
- void loadOrgs();
108
+ if (person)
109
+ void loadOrgs();
97
110
  let fresh = first.ticket;
98
111
  const url = options.url ??
99
112
  `${location.protocol === "https:" ? "wss" : "ws"}://${location.host}${config().socket ?? "/oxian"}`;
@@ -103,7 +116,7 @@ export async function web(options) {
103
116
  ticket: async () => {
104
117
  const kept = fresh;
105
118
  fresh = undefined;
106
- const next = kept ?? (await ticket())?.ticket;
119
+ const next = kept ?? (await ticket(options.arrive))?.ticket;
107
120
  if (!next) {
108
121
  location.reload();
109
122
  throw new Error("Signed out");
@@ -113,15 +126,15 @@ export async function web(options) {
113
126
  plugins: options.plugins,
114
127
  });
115
128
  await client.ready;
116
- // Who they are (their id), and what they're shown as (their name).
129
+ // Who they are (a person by their id; a contact as messages name it), and their name.
117
130
  const viewer = {
118
- kind: "person",
119
- name: first.person,
131
+ kind: first.actor.kind,
132
+ name: person ? first.actor.id : `${first.actor.kind}:${first.actor.id}`,
120
133
  ...(first.name ? { label: first.name } : {}),
121
134
  };
122
135
  session.client = client;
123
136
  session.viewer = viewer;
124
- let space = (await options.start?.(client, first.person))?.space;
137
+ let space = (await options.start?.(client, first.actor))?.space;
125
138
  let shown;
126
139
  const show = () => {
127
140
  const asked = new URLSearchParams(location.search).get("in");
@@ -10,10 +10,11 @@
10
10
  * on those variables. The server half is `server.ts` (with
11
11
  * `tickets.ts`), for the process that serves the page.
12
12
  */
13
- export { go, signOut, web, type WebOptions, type Where } from "./host.js";
13
+ export { go, signOut, web, type WebOptions, type Where, type Who } from "./host.js";
14
14
  export { appBase } from "./base.js";
15
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
+ export { display, type DisplayMode, openLink, remind, surface, tell, useRefresh, } from "./surface.js";
17
18
  export { LazyView } from "./lazy.js";
18
19
  export { Palette } from "./palette/palette.js";
19
20
  export { closePalette, openPalette, type PaletteControl, type PaletteDialog, type PaletteGroup, type PaletteItem, type PaletteStep, } from "./palette/state.js";
@@ -66,4 +67,5 @@ export { AudioPlayer } from "./toolkit/audio-player.js";
66
67
  export { Waveform } from "./toolkit/waveform.js";
67
68
  export { resample } from "./toolkit/resample.js";
68
69
  export { clock } from "./toolkit/clock.js";
69
- export type { Client } from "../../runtime/client.js";
70
+ export { type Client, type ClientLink, connect, type Known } from "../../runtime/client.js";
71
+ export type { Widgets } from "./widgets.js";
package/hosts/web/mod.js CHANGED
@@ -15,6 +15,9 @@ export { appBase } from "./base.js";
15
15
  // Orgs, when the server serves many (`hosts/orgs`): the person's, and going between them.
16
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
+ // Where Views are drawn (the page, or a widget in an outside assistant), and what a widget asks of
19
+ // its host: no-ops on the page.
20
+ export { display, openLink, remind, surface, tell, useRefresh, } from "./surface.js";
18
21
  export { LazyView } from "./lazy.js";
19
22
  // The command palette: the page's (the shell shows it), and opening it at a step from anywhere.
20
23
  export { Palette } from "./palette/palette.js";
@@ -74,3 +77,6 @@ export { AudioPlayer } from "./toolkit/audio-player.js";
74
77
  export { Waveform } from "./toolkit/waveform.js";
75
78
  export { resample } from "./toolkit/resample.js";
76
79
  export { clock } from "./toolkit/clock.js";
80
+ // The client a page connects with (over Oxian, or over a host's link: a widget's), for an app's
81
+ // own tests and hosts too.
82
+ export { connect } from "../../runtime/client.js";
@@ -2,6 +2,11 @@ import type { Code } from "../server.js";
2
2
  export type BundleOptions = {
3
3
  /** Minified, for production (the default); `false` keeps names and React's checks. */
4
4
  minify?: boolean;
5
+ /**
6
+ * Split where the code imports lazily (the default); `false` makes one file, lazy imports
7
+ * inlined: what a widget's template needs (an outside assistant's sandbox loads one page).
8
+ */
9
+ split?: boolean;
5
10
  };
6
11
  /** Bundles a page's entry (a path, or a `file:` URL such as `new URL("./browser.js", import.meta.url)`). */
7
12
  export declare function bundle(entry: string | URL, options?: BundleOptions): Promise<Code>;
@@ -22,7 +22,7 @@ export async function bundle(entry, options = {}) {
22
22
  const result = await esbuild.build({
23
23
  entryPoints: [path],
24
24
  bundle: true,
25
- splitting: true,
25
+ splitting: options.split ?? true,
26
26
  format: "esm",
27
27
  platform: "browser",
28
28
  target: "es2022",
@@ -2,9 +2,10 @@
2
2
  * The web host on Node: what an app needs beside `webServer` to serve it
3
3
  * there. `bundle` makes the browser's code with esbuild (code splitting, as on
4
4
  * Deno), and `serve` listens with Node's HTTP server, taking browsers'
5
- * sockets through Oxian's Node adapter; `listen` does it for any fetch
6
- * handler, each socket going to the runtime it's for (a host with one runtime
7
- * per org). Bun and Deno run it too.
5
+ * sockets through Oxian's Node adapter (with no `code`, it serves the app's
6
+ * routes alone); `listen` does it for any fetch handler, each socket going to
7
+ * the runtime it's for (a host with one runtime per org). Bun and Deno run it
8
+ * too.
8
9
  *
9
10
  * ```ts
10
11
  * import { createRuntime } from "copilotz";
@@ -23,7 +24,8 @@
23
24
  * port: 8080,
24
25
  * });
25
26
  * console.log(`${server.url}`);
27
+ * process.once("SIGTERM", () => server.close({ drain: 8_000 }));
26
28
  * ```
27
29
  */
28
30
  export { bundle, type BundleOptions } from "./bundle.js";
29
- export { listen, type Listener, type ListenOptions, type RouteListener, type RoutesOptions, serve, type ServeOptions, serveRoutes, } from "./serve.js";
31
+ export { listen, type Listener, type ListenOptions, serve, type ServeOptions, type Server, } from "./serve.js";
@@ -2,9 +2,10 @@
2
2
  * The web host on Node: what an app needs beside `webServer` to serve it
3
3
  * there. `bundle` makes the browser's code with esbuild (code splitting, as on
4
4
  * Deno), and `serve` listens with Node's HTTP server, taking browsers'
5
- * sockets through Oxian's Node adapter; `listen` does it for any fetch
6
- * handler, each socket going to the runtime it's for (a host with one runtime
7
- * per org). Bun and Deno run it too.
5
+ * sockets through Oxian's Node adapter (with no `code`, it serves the app's
6
+ * routes alone); `listen` does it for any fetch handler, each socket going to
7
+ * the runtime it's for (a host with one runtime per org). Bun and Deno run it
8
+ * too.
8
9
  *
9
10
  * ```ts
10
11
  * import { createRuntime } from "copilotz";
@@ -23,7 +24,8 @@
23
24
  * port: 8080,
24
25
  * });
25
26
  * console.log(`${server.url}`);
27
+ * process.once("SIGTERM", () => server.close({ drain: 8_000 }));
26
28
  * ```
27
29
  */
28
30
  export { bundle } from "./bundle.js";
29
- export { listen, serve, serveRoutes, } from "./serve.js";
31
+ export { listen, serve, } from "./serve.js";
@@ -6,20 +6,21 @@
6
6
  * plugins' routes included, as on any runtime). Bun and Deno run it too,
7
7
  * through their Node compatibility.
8
8
  *
9
- * - `serve`: one runtime's web host (`webServer`), its socket to that runtime.
10
- * - `serveRoutes`: an app without the web app (on WhatsApp, on the phone):
11
- * its routes alone (`routeHost`), and `/health`.
9
+ * - `serve`: one runtime's web host (`webServer`), its socket to that
10
+ * runtime: whatever the app's plugins make of it. With the page's code, the
11
+ * web app; without, its routes alone (on WhatsApp, on the phone) and
12
+ * `/health`.
12
13
  * - `listen`: any fetch handler, with the Hypervisor each socket goes to
13
14
  * picked per request: a host with a runtime per org names the one a request
14
15
  * is for (`hosts/orgs`: its `openRuntime`).
15
16
  *
16
17
  * A route may take a socket of its own (`host.upgrade()`, see `routes.ts`):
17
18
  * any path but the runtime's goes to the handler, upgrades too, and Oxian's
18
- * adapter takes the socket the handler accepts.
19
+ * adapter takes the socket the handler accepts. Each request it hands on
20
+ * says where it came from (the socket's peer: `clientAddress`), which what's
21
+ * this machine's alone goes by (dev sign-in).
19
22
  */
20
23
  import type { Hypervisor } from "oxianjs";
21
- import type { Runtime } from "../../../runtime/mod.js";
22
- import { type Front } from "../routes.js";
23
24
  import { type WebServerOptions } from "../server.js";
24
25
  /** Where to listen. */
25
26
  type Address = {
@@ -50,29 +51,25 @@ export type Listener = {
50
51
  finished: Promise<void>;
51
52
  shutdown(): Promise<void>;
52
53
  };
53
- export type RoutesOptions = Address & {
54
- runtime: Runtime;
55
- /** The app's front (a Cloudflare worker before it), as `webServer` takes it. */
56
- front?: Front;
57
- };
58
- /** A route host listening. It owns its runtime: `close` stops listening, then closes it. */
59
- export type RouteListener = Listener & {
60
- /** Stops listening (its sockets close), then the runtime, passing `drain` on (`Runtime.close`). */
54
+ /** The web host listening: `shutdown` stops listening; `close` does, then closes its runtime. */
55
+ export type Server = Listener & {
56
+ /**
57
+ * Stops listening (its sockets close), then the runtime, passing `drain`
58
+ * on (`Runtime.close`): a deploy's SIGTERM gives running turns a while.
59
+ * Asked again, it's the same close.
60
+ */
61
61
  close(options?: {
62
62
  drain?: number;
63
63
  }): Promise<void>;
64
64
  };
65
65
  /**
66
- * Serves the web host for a runtime that declares the `socket` transport
67
- * (`createRuntime({ transports: [socket], admit: tickets.admit })`).
68
- */
69
- export declare function serve(options: ServeOptions): Promise<Listener>;
70
- /**
71
- * Serves an app's routes alone (`routeHost`): its webhooks and sockets, and
72
- * `/health`. Its runtime's own socket (`/oxian`, when it declares one: remote
73
- * executors) goes to it, as `serve`'s does.
66
+ * Serves the web host for a runtime: its routes, and what the app's plugins
67
+ * and these options make of it (the page with `code`, browsers with
68
+ * `tickets` and a runtime that declares the `socket` transport:
69
+ * `createRuntime({ transports: [socket], admit: tickets.admit })`). The
70
+ * runtime's socket (`/oxian`: browsers, remote executors) goes to it.
74
71
  */
75
- export declare function serveRoutes(options: RoutesOptions): Promise<RouteListener>;
72
+ export declare function serve(options: ServeOptions): Promise<Server>;
76
73
  /** Serves a fetch handler, each socket going to the Hypervisor `hypervisor` picks for it. */
77
74
  export declare function listen(options: ListenOptions): Promise<Listener>;
78
75
  export {};
@@ -1,37 +1,26 @@
1
1
  import { serve as oxian } from "oxianjs/adapters/node";
2
- import { hostRouted, routeHost } from "../routes.js";
2
+ import { hostRouted } from "../routes.js";
3
3
  import { socket, webServer } from "../server.js";
4
4
  /**
5
- * Serves the web host for a runtime that declares the `socket` transport
6
- * (`createRuntime({ transports: [socket], admit: tickets.admit })`).
5
+ * Serves the web host for a runtime: its routes, and what the app's plugins
6
+ * and these options make of it (the page with `code`, browsers with
7
+ * `tickets` and a runtime that declares the `socket` transport:
8
+ * `createRuntime({ transports: [socket], admit: tickets.admit })`). The
9
+ * runtime's socket (`/oxian`: browsers, remote executors) goes to it.
7
10
  */
8
11
  export async function serve(options) {
9
12
  const { hostname, port, signal, ...web } = options;
10
- const hypervisor = web.runtime.hypervisor;
11
- const routed = hostRouted(web.runtime, web.front ? { front: web.front } : {});
12
- return await listen({
13
+ const { runtime } = web;
14
+ const routed = hostRouted(runtime, web.front ? { front: web.front } : {});
15
+ const listener = await listen({
13
16
  // Every request for the socket goes to the Hypervisor, so `webServer` never upgrades one;
14
17
  // a host a route takes (a preview's) has no socket of the app's, though.
15
18
  fetch: webServer({ ...web, upgrade: () => new Response(null, { status: 426 }) }),
16
- hypervisor: (request) => routed(request) ? undefined : hypervisor,
19
+ hypervisor: (request) => routed(request) ? undefined : runtime.hypervisor,
17
20
  hostname,
18
21
  port,
19
22
  signal,
20
23
  });
21
- }
22
- /**
23
- * Serves an app's routes alone (`routeHost`): its webhooks and sockets, and
24
- * `/health`. Its runtime's own socket (`/oxian`, when it declares one: remote
25
- * executors) goes to it, as `serve`'s does.
26
- */
27
- export async function serveRoutes(options) {
28
- const { runtime, front, ...address } = options;
29
- const routed = hostRouted(runtime, front ? { front } : {});
30
- const listener = await listen({
31
- ...address,
32
- fetch: routeHost(runtime, front ? { front } : {}),
33
- hypervisor: (request) => routed(request) ? undefined : runtime.hypervisor,
34
- });
35
24
  // Closing takes a while (the runtime's drain): asked again, it's the same close.
36
25
  let closed;
37
26
  // What it's given goes on to the runtime's close: how long running work may take to finish.
@@ -3,13 +3,14 @@
3
3
  * A path ending in `/` takes everything under it; any other, itself alone.
4
4
  *
5
5
  * - `{ path, action }`: the request becomes a call to that Action (its input
6
- * an `HttpRequest`), as the person its session cookie signs in, or else a
6
+ * an `HttpRequest`), as whoever the request is (the app's entrances say:
7
+ * the person its session signs in, a web line's visitor), or else a
7
8
  * visitor (`{ kind: "visitor", id: "" }`): the Action's `allow` decides.
8
9
  * It answers with an `HttpAnswer`. Webhooks, OAuth callbacks, an API.
9
10
  * - `{ path, serve }`: a function that answers the request itself, here in
10
11
  * the host's process: files as they are (downloads), or an API that must
11
12
  * stream, choose call ids or keep a request's secrets out of the log. It's
12
- * given the runtime and who the request's session signs in (`Served`). It
13
+ * given the runtime and who the request is (`Served`). It
13
14
  * may take a WebSocket (a voice call's relay): `host.upgrade()` accepts
14
15
  * the request's upgrade, and it answers with the response that gives.
15
16
  * - `{ host, serve }` (or `action`): every request to a host, whatever its
@@ -35,6 +36,7 @@
35
36
  */
36
37
  import { type RouteWebSocket } from "oxianjs/http";
37
38
  import type { Actor, Infer, Resources, Runtime } from "../../runtime/mod.js";
39
+ import type { Widgets } from "./widgets.js";
38
40
  export type Route = ({
39
41
  path: string;
40
42
  } | {
@@ -47,14 +49,20 @@ export type Route = ({
47
49
  serve(request: Request, host: Served): Response | Promise<Response>;
48
50
  });
49
51
  /**
50
- * What a `serve` route is given: the runtime, who the request's session
51
- * signs in, and the host the request is for (as the front says, when it's
52
- * trusted: not always `request.url`'s).
52
+ * What a `serve` route is given: the runtime, who the request is (by the
53
+ * app's entrances), and the host the request is for (as the front says,
54
+ * when it's trusted: not always `request.url`'s).
53
55
  */
54
56
  export type Served = {
55
57
  runtime: Runtime;
56
58
  whom(): Promise<Actor | null>;
57
59
  host: string;
60
+ /**
61
+ * The app's widgets, when its web host has them (`webServer({ widgets })`): the template
62
+ * an outside assistant draws its Views in, and snapshots of what a View reads (see
63
+ * widgets.ts). What the MCP interface's lines show tool calls through.
64
+ */
65
+ widgets?: Widgets;
58
66
  /**
59
67
  * Accepts the request's WebSocket upgrade (a `GET` with `upgrade:
60
68
  * websocket`; anything else throws): the socket, open once the route
@@ -138,6 +146,12 @@ export type HttpAnswer = {
138
146
  };
139
147
  /** Who calls when nobody's signed in. */
140
148
  export declare const VISITOR: Actor;
149
+ /**
150
+ * A request's body, `most` bytes at most: undefined past it, said by its
151
+ * `content-length` before anything is read, or found while reading, which
152
+ * stops there (the rest is never read).
153
+ */
154
+ export declare function bodyOf(request: Request, most: number): Promise<Uint8Array | undefined>;
141
155
  /**
142
156
  * Whether a route by host takes a request: for what must decide at once,
143
157
  * before anything asynchronous (Node's socket upgrade).
@@ -152,22 +166,14 @@ export declare function hostRouted(runtime: Runtime, options?: {
152
166
  */
153
167
  export declare function hostServer(runtime: Runtime, whom: (request: Request) => Promise<Actor | null>, options?: {
154
168
  front?: Front;
169
+ widgets?: Widgets;
155
170
  }): (request: Request) => Promise<Response> | undefined;
156
171
  /**
157
172
  * Answers the requests a plugin's route takes; undefined for any other. `whom`
158
- * says who the request's session signs in, if anyone. A request to a host a
159
- * route takes is that route's, whatever its path; any other goes by path.
173
+ * says who the request is, if anyone. A request to a host a route takes is
174
+ * that route's, whatever its path; any other goes by path.
160
175
  */
161
176
  export declare function routeServer(runtime: Runtime, whom: (request: Request) => Promise<Actor | null>, options?: {
162
177
  front?: Front;
178
+ widgets?: Widgets;
163
179
  }): (request: Request) => Promise<Response> | undefined;
164
- /**
165
- * A host for an app without the web app (on WhatsApp, on the phone): its
166
- * routes alone, by host and then by path, their sockets included; `GET
167
- * /health`, unless a route takes it; and 404 for anything else. Nobody signs
168
- * in here: a route's Action is called as a visitor, and its `allow` decides.
169
- * `serveRoutes` (`copilotz/web/node`) listens with it.
170
- */
171
- export declare function routeHost(runtime: Runtime, options?: {
172
- front?: Front;
173
- }): (request: Request) => Promise<Response>;
@@ -3,13 +3,14 @@
3
3
  * A path ending in `/` takes everything under it; any other, itself alone.
4
4
  *
5
5
  * - `{ path, action }`: the request becomes a call to that Action (its input
6
- * an `HttpRequest`), as the person its session cookie signs in, or else a
6
+ * an `HttpRequest`), as whoever the request is (the app's entrances say:
7
+ * the person its session signs in, a web line's visitor), or else a
7
8
  * visitor (`{ kind: "visitor", id: "" }`): the Action's `allow` decides.
8
9
  * It answers with an `HttpAnswer`. Webhooks, OAuth callbacks, an API.
9
10
  * - `{ path, serve }`: a function that answers the request itself, here in
10
11
  * the host's process: files as they are (downloads), or an API that must
11
12
  * stream, choose call ids or keep a request's secrets out of the log. It's
12
- * given the runtime and who the request's session signs in (`Served`). It
13
+ * given the runtime and who the request is (`Served`). It
13
14
  * may take a WebSocket (a voice call's relay): `host.upgrade()` accepts
14
15
  * the request's upgrade, and it answers with the response that gives.
15
16
  * - `{ host, serve }` (or `action`): every request to a host, whatever its
@@ -96,7 +97,7 @@ export const httpRequest = {
96
97
  export const VISITOR = { kind: "visitor", id: "" };
97
98
  /** Paths the web host answers itself. */
98
99
  const OWN = ["/app/", "/assets/", "/files/", "/oxian", "/connect", "/signin", "/signout"];
99
- /** Bodies larger than this are refused (10 MB). */
100
+ /** Bodies larger than this are refused (10 MB): a 413 once that's known, the rest never read. */
100
101
  const MAX_BODY = 10 * 1024 * 1024;
101
102
  const textual = (type) => !type || /^text\/|json|xml|x-www-form-urlencoded|javascript/.test(type);
102
103
  const STATUS = {
@@ -105,7 +106,48 @@ const STATUS = {
105
106
  not_found: 404,
106
107
  unauthorized: 401,
107
108
  };
109
+ /** What a refusal says when its own words aren't for anyone (`public`), by its code. */
110
+ const SAID = {
111
+ forbidden: "Forbidden",
112
+ invalid: "Not a request this takes",
113
+ not_found: "Not found",
114
+ unauthorized: "Unauthorized",
115
+ };
108
116
  const plain = (status, text) => new Response(text, { status, headers: { "content-type": "text/plain; charset=utf-8" } });
117
+ /**
118
+ * A request's body, `most` bytes at most: undefined past it, said by its
119
+ * `content-length` before anything is read, or found while reading, which
120
+ * stops there (the rest is never read).
121
+ */
122
+ export async function bodyOf(request, most) {
123
+ if (!request.body)
124
+ return new Uint8Array();
125
+ if (Number(request.headers.get("content-length") ?? 0) > most) {
126
+ await request.body.cancel().catch(() => { });
127
+ return undefined;
128
+ }
129
+ const reader = request.body.getReader();
130
+ const chunks = [];
131
+ let size = 0;
132
+ for (;;) {
133
+ const { done, value } = await reader.read();
134
+ if (done)
135
+ break;
136
+ size += value.length;
137
+ if (size > most) {
138
+ await reader.cancel().catch(() => { });
139
+ return undefined;
140
+ }
141
+ chunks.push(value);
142
+ }
143
+ const bytes = new Uint8Array(size);
144
+ let at = 0;
145
+ for (const chunk of chunks) {
146
+ bytes.set(chunk, at);
147
+ at += chunk.length;
148
+ }
149
+ return bytes;
150
+ }
109
151
  /** Reads a request as an Action takes it. */
110
152
  async function read(request, url) {
111
153
  const headers = {};
@@ -122,8 +164,8 @@ async function read(request, url) {
122
164
  };
123
165
  if (!request.body)
124
166
  return asked;
125
- const bytes = new Uint8Array(await request.arrayBuffer());
126
- if (bytes.length > MAX_BODY)
167
+ const bytes = await bodyOf(request, MAX_BODY);
168
+ if (!bytes)
127
169
  return plain(413, "Too large");
128
170
  if (textual(headers["content-type"] ?? "")) {
129
171
  return { ...asked, body: new TextDecoder().decode(bytes) };
@@ -198,9 +240,10 @@ async function answered(runtime, name, route, request, url, served) {
198
240
  return answer(await runtime.call(route.action, asked, { actor }));
199
241
  }
200
242
  catch (error) {
201
- const code = error.code;
243
+ // A refusal answers its code's status, and its words only when they're for anyone.
244
+ const { code, public: open } = (error ?? {});
202
245
  if (code && STATUS[code]) {
203
- return plain(STATUS[code], error instanceof Error ? error.message : String(error));
246
+ return plain(STATUS[code], open === true && error instanceof Error ? error.message : SAID[code]);
204
247
  }
205
248
  console.error(`routes.${name}:`, error instanceof Error ? error.message : error);
206
249
  return plain(500, "Something went wrong");
@@ -233,13 +276,13 @@ export function hostServer(runtime, whom, options = {}) {
233
276
  const found = hosts.find((h) => hostMatches(h.pattern, host) && (!h.route.methods || h.route.methods.includes(request.method)));
234
277
  if (!found)
235
278
  return undefined;
236
- return answered(runtime, found.name, found.route, request, new URL(request.url), served(runtime, request, whom, host));
279
+ return answered(runtime, found.name, found.route, request, new URL(request.url), served(runtime, request, whom, host, options.widgets));
237
280
  };
238
281
  }
239
282
  /**
240
283
  * Answers the requests a plugin's route takes; undefined for any other. `whom`
241
- * says who the request's session signs in, if anyone. A request to a host a
242
- * route takes is that route's, whatever its path; any other goes by path.
284
+ * says who the request is, if anyone. A request to a host a route takes is
285
+ * that route's, whatever its path; any other goes by path.
243
286
  */
244
287
  export function routeServer(runtime, whom, options = {}) {
245
288
  const { paths } = declared(runtime);
@@ -256,33 +299,14 @@ export function routeServer(runtime, whom, options = {}) {
256
299
  const found = match(url, request.method);
257
300
  if (!found)
258
301
  return undefined;
259
- return answered(runtime, found.name, found.route, request, url, served(runtime, request, whom, hostOf(request, options.front)));
260
- };
261
- }
262
- /** Where a host without the web app says it's up. */
263
- const HEALTH = "/health";
264
- /**
265
- * A host for an app without the web app (on WhatsApp, on the phone): its
266
- * routes alone, by host and then by path, their sockets included; `GET
267
- * /health`, unless a route takes it; and 404 for anything else. Nobody signs
268
- * in here: a route's Action is called as a visitor, and its `allow` decides.
269
- * `serveRoutes` (`copilotz/web/node`) listens with it.
270
- */
271
- export function routeHost(runtime, options = {}) {
272
- const routes = routeServer(runtime, () => Promise.resolve(null), options);
273
- return async (request) => {
274
- const answering = routes(request);
275
- if (answering)
276
- return await answering;
277
- const healthy = (request.method === "GET" || request.method === "HEAD") &&
278
- new URL(request.url).pathname === HEALTH;
279
- return healthy ? plain(200, "ok") : plain(404, "Not found");
302
+ return answered(runtime, found.name, found.route, request, url, served(runtime, request, whom, hostOf(request, options.front), options.widgets));
280
303
  };
281
304
  }
282
305
  /** What a `serve` route is given for a request. */
283
- const served = (runtime, request, whom, host) => ({
306
+ const served = (runtime, request, whom, host, widgets) => ({
284
307
  runtime,
285
308
  whom: () => whom(request),
286
309
  host,
310
+ ...(widgets ? { widgets } : {}),
287
311
  upgrade: (options) => upgradeWebSocket(request, options),
288
312
  });