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,20 @@
1
+ export type DisplayMode = "inline" | "pip" | "fullscreen";
2
+ /** What a widget's host does for its Views (see widget.tsx). */
3
+ export type SurfaceHost = {
4
+ display(mode: DisplayMode): Promise<DisplayMode | undefined>;
5
+ tell(text: string): Promise<void>;
6
+ remind(text: string): Promise<void>;
7
+ openLink(url: string): Promise<void>;
8
+ /** Asks the reads again every `ms` until the returned function is called. */
9
+ every(ms: number): () => void;
10
+ };
11
+ /** The widget host's, once it runs (and for tests). */
12
+ export declare function setSurface(next: SurfaceHost | undefined): void;
13
+ export declare const surface: () => "page" | "widget";
14
+ export declare const display: (mode: DisplayMode) => Promise<DisplayMode | undefined>;
15
+ export declare const tell: (text: string) => Promise<void>;
16
+ export declare const remind: (text: string) => Promise<void>;
17
+ /** Only links to the web (http, https) are opened. */
18
+ export declare function openLink(url: string): Promise<void>;
19
+ /** In a widget, its reads asked again every `ms` while the caller is mounted (at least a second). */
20
+ export declare function useRefresh(ms: number): void;
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Where a page's Views are drawn, and what they may ask of it: the web host's own page
3
+ * (`"page"`), or a widget inside an outside assistant's conversation (`"widget"`: an MCP Apps
4
+ * host such as ChatGPT, see widget.tsx). One View serves both: what only a widget can do is a
5
+ * no-op on the page, so a View calls these from its handlers without asking where it is.
6
+ *
7
+ * - `surface()`: `"page"` or `"widget"`.
8
+ * - `display(mode)`: asks the widget's host for a display mode (`inline`, `pip`, `fullscreen`);
9
+ * it answers the mode it set. On the page, nothing changes (it answers `undefined`).
10
+ * - `tell(text)`: a message from the user into the assistant's conversation, which starts its
11
+ * model's turn. Use sparingly: it speaks for the user.
12
+ * - `remind(text)`: what the assistant's model should know next time it answers (what the user
13
+ * did in the widget), replacing what this widget said before. Never personal data.
14
+ * - `openLink(url)`: opens a link outside (the host's way, in a widget; a new tab on the page).
15
+ * - `useRefresh(ms)`: while the component that calls it is mounted, a widget asks its reads again
16
+ * every `ms` (a payment's status): the page needs nothing, its reads are pushed.
17
+ *
18
+ * The widget host sets them (`setSurface`); nothing else does.
19
+ */
20
+ import { useEffect } from "react";
21
+ let host;
22
+ /** The widget host's, once it runs (and for tests). */
23
+ export function setSurface(next) {
24
+ host = next;
25
+ }
26
+ export const surface = () => host ? "widget" : "page";
27
+ export const display = (mode) => host ? host.display(mode) : Promise.resolve(undefined);
28
+ export const tell = (text) => host ? host.tell(text) : Promise.resolve();
29
+ export const remind = (text) => host ? host.remind(text) : Promise.resolve();
30
+ /** Only links to the web (http, https) are opened. */
31
+ export function openLink(url) {
32
+ if (!/^https?:\/\//i.test(url))
33
+ return Promise.resolve();
34
+ if (host)
35
+ return host.openLink(url);
36
+ globalThis.open?.(url, "_blank", "noopener,noreferrer");
37
+ return Promise.resolve();
38
+ }
39
+ /** In a widget, its reads asked again every `ms` while the caller is mounted (at least a second). */
40
+ export function useRefresh(ms) {
41
+ useEffect(() => host?.every(Math.max(1_000, ms)), [ms]);
42
+ }
@@ -1,6 +1,7 @@
1
1
  /**
2
2
  * A theme as the page's CSS variables: its tokens for a light screen, those
3
- * for a dark one under `prefers-color-scheme: dark`, the radii that scale
3
+ * for a dark one under `prefers-color-scheme: dark` (or when the page's root
4
+ * says `data-theme="dark"`, as a widget's host does), the radii that scale
4
5
  * from `radius`, and the fonts. `themeOf` is the app's theme: the defaults,
5
6
  * with the front ends' `theme` resources merged over them in order, as every
6
7
  * resource merges, except that `font` and `logo` are each given whole. A
@@ -1,6 +1,7 @@
1
1
  /**
2
2
  * A theme as the page's CSS variables: its tokens for a light screen, those
3
- * for a dark one under `prefers-color-scheme: dark`, the radii that scale
3
+ * for a dark one under `prefers-color-scheme: dark` (or when the page's root
4
+ * says `data-theme="dark"`, as a widget's host does), the radii that scale
4
5
  * from `radius`, and the fonts. `themeOf` is the app's theme: the defaults,
5
6
  * with the front ends' `theme` resources merged over them in order, as every
6
7
  * resource merges, except that `font` and `logo` are each given whole. A
@@ -107,10 +108,16 @@ export function themeCss(theme) {
107
108
  "font-mono": theme.font?.mono ?? SYSTEM_MONO,
108
109
  ...theme.light,
109
110
  });
111
+ // Dark by the system's preference, unless the page says which (`data-theme`: a widget's
112
+ // host says light or dark, whatever the system prefers).
110
113
  return [
111
114
  `:root {\n color-scheme: ${dark.length ? "light dark" : "light"};\n${root.join("\n")}\n}`,
112
115
  ...(dark.length
113
- ? [`@media (prefers-color-scheme: dark) {\n:root {\n${dark.join("\n")}\n}\n}`]
116
+ ? [
117
+ `@media (prefers-color-scheme: dark) {\n:root:not([data-theme="light"]) {\n${dark.join("\n")}\n}\n}`,
118
+ `:root[data-theme="dark"] {\n color-scheme: dark;\n${dark.join("\n")}\n}`,
119
+ `:root[data-theme="light"] {\n color-scheme: light;\n}`,
120
+ ]
114
121
  : []),
115
122
  ].join("\n");
116
123
  }
@@ -3,6 +3,13 @@
3
3
  * session stays in an httpOnly cookie its code never sees; a ticket works
4
4
  * once, for a minute, and the runtime's `admit` turns it into the person.
5
5
  *
6
+ * Each actor has `perMinute` tickets a minute (30 unless said), however many
7
+ * tabs and reconnects that is: past it, `issue` refuses (a public `too_many`
8
+ * failure, its `retryAfter` the seconds until the minute's out), and
9
+ * `/connect` answers 429. Tickets past their minute are dropped as they pass
10
+ * (see runtime/expiring.ts), never by looking through them all. Signing out
11
+ * ends an actor's tickets not yet used (`end`).
12
+ *
6
13
  * ```ts
7
14
  * const tickets = createTickets();
8
15
  * const runtime = await createRuntime({ store, plugins, admit: tickets.admit });
@@ -10,11 +17,17 @@
10
17
  */
11
18
  import type { Actor } from "../../runtime/mod.js";
12
19
  export type Tickets = {
13
- /** A ticket for this person, for one connection. */
20
+ /** A ticket for this actor, for one connection; refused (`too_many`) past its minute's. */
14
21
  issue(actor: Actor): string;
15
22
  /** Who a ticket is for, once; undefined when it's unknown, used or old. */
16
23
  admit(ticket: string): Actor | undefined;
24
+ /**
25
+ * Their tickets not yet used are no one's (signed out): what was handed
26
+ * out before lets nobody in after.
27
+ */
28
+ end?(actor: Actor): void;
17
29
  };
18
30
  export declare function createTickets(options?: {
19
31
  ms?: number;
32
+ perMinute?: number;
20
33
  }): Tickets;
@@ -1,21 +1,44 @@
1
+ import { failure } from "../../runtime/errors.js";
2
+ import { expiring } from "../../runtime/expiring.js";
3
+ const MINUTE = 60_000;
1
4
  export function createTickets(options = {}) {
5
+ const perMinute = options.perMinute ?? 30;
2
6
  const ms = options.ms ?? 60_000;
3
- const issued = new Map();
7
+ const issued = expiring(ms);
8
+ /** Each actor's tickets this minute, and when its minute began. */
9
+ const counted = expiring(MINUTE);
10
+ /** Each actor's tickets handed out lately (some used, or past), to end them all at once. */
11
+ const theirs = expiring(ms);
4
12
  return {
5
13
  issue(actor) {
14
+ const who = `${actor.kind}:${actor.id}`;
6
15
  const now = Date.now();
7
- for (const [ticket, kept] of issued)
8
- if (kept.until < now)
9
- issued.delete(ticket);
16
+ const minute = counted.get(who) ?? { count: 0, since: now };
17
+ if (minute.count >= perMinute) {
18
+ throw Object.assign(failure("too_many", "Too many connections at once: try again in a minute", {
19
+ public: true,
20
+ }), { retryAfter: Math.max(1, Math.ceil((minute.since + MINUTE - now) / 1000)) });
21
+ }
22
+ if (!minute.count)
23
+ counted.set(who, minute);
24
+ minute.count++;
10
25
  const bytes = crypto.getRandomValues(new Uint8Array(32));
11
26
  const ticket = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
12
- issued.set(ticket, { actor, until: now + ms });
27
+ issued.set(ticket, actor);
28
+ const kept = (theirs.get(who) ?? []).filter((t) => issued.get(t));
29
+ theirs.set(who, [...kept, ticket]);
13
30
  return ticket;
14
31
  },
15
32
  admit(ticket) {
16
- const kept = issued.get(ticket);
33
+ const actor = issued.get(ticket);
17
34
  issued.delete(ticket);
18
- return kept && kept.until > Date.now() ? kept.actor : undefined;
35
+ return actor;
36
+ },
37
+ end(actor) {
38
+ const who = `${actor.kind}:${actor.id}`;
39
+ for (const ticket of theirs.get(who) ?? [])
40
+ issued.delete(ticket);
41
+ theirs.delete(who);
19
42
  },
20
43
  };
21
44
  }
@@ -0,0 +1,31 @@
1
+ import { type Client, type Known } from "../../runtime/client.js";
2
+ import type { Plugins, Viewer } from "../../runtime/mod.js";
3
+ export type WidgetOptions = {
4
+ plugins: Plugins;
5
+ root: Element;
6
+ /** How long it waits for its tool's result before saying there's nothing to show (15 s). */
7
+ wait?: number;
8
+ };
9
+ /** What a tool result carries for its widget (see plugins/interfaces/mcp/resources/widgets.ts). */
10
+ export type WidgetMeta = {
11
+ view: string;
12
+ item: unknown;
13
+ hints: Record<string, unknown>;
14
+ viewer: Viewer;
15
+ reads: Known;
16
+ grant: string;
17
+ /** The line's tool for each Action the widget may call. */
18
+ tools: Record<string, string>;
19
+ /** The line's read tool. */
20
+ read: string;
21
+ };
22
+ type Json = Record<string, unknown>;
23
+ /**
24
+ * A result's `_meta`, wherever its host put it: on the result, or (ChatGPT) on the MCP result
25
+ * it wraps (`call_tool_result`, `mcp_tool_result`).
26
+ */
27
+ export declare function metaOf(result: unknown): Json;
28
+ /** The widget's part of a result, when it has one. */
29
+ export declare function widgetOf(result: unknown): WidgetMeta | undefined;
30
+ export declare function widget(options: WidgetOptions): Promise<Client | undefined>;
31
+ export {};
@@ -0,0 +1,429 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ /**
3
+ * The widget host, in the browser: an app's web Views drawn inside an outside assistant's
4
+ * conversation (an MCP Apps host: ChatGPT, Claude…), as the web host draws them on the app's own
5
+ * page. The server's half is widgets.ts (the template this runs in, and snapshots); the MCP
6
+ * interface's lines say which tool's calls are shown through which View
7
+ * (`plugins/interfaces/mcp`).
8
+ *
9
+ * - **The bridge** is MCP Apps' (postMessage JSON-RPC with the host: `ui/initialize`, its host
10
+ * context, `ui/notifications/tool-result`, `host-context-changed`, `tools/call`,
11
+ * `ui/request-display-mode`, `ui/message`, `ui/update-model-context`, `ui/open-link`), and
12
+ * ChatGPT's `window.openai` where the host answers that instead (`toolResponseMetadata`,
13
+ * `callTool`, `requestDisplayMode`, `sendFollowUpMessage`, `openExternal`, `openai:set_globals`).
14
+ * - **What it draws** comes in the tool result's `_meta` (the host's, never the model's):
15
+ * `copilotz/widget`, the View, its item and hints, who looks, what the View reads (answered on
16
+ * the server: the first paint asks nothing), the widget's grant, and which tools stand for
17
+ * which Actions. It observes the View with hints `{ …, mode, surface: "widget" }`, `mode` the
18
+ * host's display mode (`inline`, `pip`, `fullscreen`): a change observes it again.
19
+ * - **Reads it hadn't** go in one call of the line's read tool (`copilotz_read`) per pass,
20
+ * with the grant. **Handlers' calls** (`ctx.call(action, input)`) go as the line's tool for
21
+ * that Action, with the grant and the reads watched, whose new answers come back with it: the
22
+ * widget redraws in that one round trip. An Action the line doesn't offer is refused here.
23
+ * - **Nothing is pushed** to a widget: it asks its reads again when it's shown again, and while
24
+ * a View asks (`useRefresh`, a payment's status).
25
+ * - **Its look** is the app's theme (the template carries its variables and fonts), dark or
26
+ * light as the host says (`data-theme`), its height told to the host as it changes.
27
+ * - **What Views ask of it** (`display`, `tell`, `remind`, `openLink`: surface.ts) goes to the
28
+ * host; links to the web open the host's way.
29
+ *
30
+ * ```ts
31
+ * // widgets.tsx, bundled with { split: false } for `widgetsOf({ code, plugins })`
32
+ * await widget({ plugins: [brandTheme, bookingWeb], root: document.getElementById("app")! });
33
+ * ```
34
+ */
35
+ import { useLayoutEffect } from "react";
36
+ import { createRoot } from "react-dom/client";
37
+ import { connect } from "../../runtime/client.js";
38
+ import { Part } from "./part.js";
39
+ import { session } from "./session.js";
40
+ import { BASE } from "./style.js";
41
+ import { openLink, setSurface } from "./surface.js";
42
+ import { ThemeContext } from "./theme/context.js";
43
+ import { themeCss, themeOf } from "./theme/css.js";
44
+ const isObject = (value) => !!value && typeof value === "object" && !Array.isArray(value);
45
+ /**
46
+ * A result's `_meta`, wherever its host put it: on the result, or (ChatGPT) on the MCP result
47
+ * it wraps (`call_tool_result`, `mcp_tool_result`).
48
+ */
49
+ export function metaOf(result) {
50
+ if (!isObject(result))
51
+ return {};
52
+ const own = isObject(result._meta) ? result._meta : isObject(result.meta) ? result.meta : {};
53
+ const wrapped = [
54
+ result.call_tool_result,
55
+ result.mcp_tool_result,
56
+ own.call_tool_result,
57
+ own.mcp_tool_result,
58
+ ].find(isObject);
59
+ const inner = wrapped && isObject(wrapped._meta) ? wrapped._meta : {};
60
+ return { ...inner, ...own };
61
+ }
62
+ /** The widget's part of a result, when it has one. */
63
+ export function widgetOf(result) {
64
+ const meta = metaOf(result);
65
+ const found = (isObject(result) && result["copilotz/widget"]) ?? meta["copilotz/widget"];
66
+ if (!isObject(found) || typeof found.view !== "string" || typeof found.grant !== "string") {
67
+ return undefined;
68
+ }
69
+ return found;
70
+ }
71
+ const textOf = (result) => (result.content ?? []).map((c) => c.text ?? "").join("\n").trim();
72
+ const openai = () => globalThis.openai;
73
+ /** The MCP Apps bridge: JSON-RPC over postMessage with the host (the parent frame). */
74
+ function bridgeOf() {
75
+ let next = 0;
76
+ const pending = new Map();
77
+ const listeners = new Set();
78
+ // The host's origin, once its first answer says it: from then on, only it is written to, and
79
+ // only it is heard (until then the host is unknown: a sandbox's origin is the host's to choose).
80
+ let origin = "*";
81
+ const top = globalThis;
82
+ const inFrame = top.parent !== undefined && top.parent !== globalThis;
83
+ addEventListener("message", (event) => {
84
+ if (event.source !== globalThis.parent)
85
+ return;
86
+ if (origin !== "*" && event.origin !== origin)
87
+ return;
88
+ const message = event.data;
89
+ if (!isObject(message) || message.jsonrpc !== "2.0")
90
+ return;
91
+ if (typeof message.id === "number" && !("method" in message)) {
92
+ const waiting = pending.get(message.id);
93
+ if (!waiting)
94
+ return;
95
+ pending.delete(message.id);
96
+ if (origin === "*" && event.origin && event.origin !== "null")
97
+ origin = event.origin;
98
+ if (message.error)
99
+ waiting.reject(message.error);
100
+ else
101
+ waiting.resolve(message.result);
102
+ return;
103
+ }
104
+ if (typeof message.method !== "string")
105
+ return;
106
+ // The host asks before it takes the widget down: it's told yes.
107
+ if (message.method === "ui/resource-teardown" && "id" in message) {
108
+ globalThis.parent.postMessage({ jsonrpc: "2.0", id: message.id, result: {} }, origin);
109
+ }
110
+ for (const listen of listeners) {
111
+ listen(message.method, isObject(message.params) ? message.params : {});
112
+ }
113
+ });
114
+ return {
115
+ inFrame,
116
+ request: (method, params, timeout = 30_000) => new Promise((resolve, reject) => {
117
+ if (!inFrame)
118
+ return reject(new Error("No host"));
119
+ const id = ++next;
120
+ const timer = setTimeout(() => {
121
+ pending.delete(id);
122
+ reject(Object.assign(new Error("The host didn't answer"), { code: "unavailable" }));
123
+ }, timeout);
124
+ pending.set(id, {
125
+ resolve: (v) => (clearTimeout(timer), resolve(v)),
126
+ reject: (e) => (clearTimeout(timer), reject(e)),
127
+ });
128
+ globalThis.parent.postMessage({ jsonrpc: "2.0", id, method, params }, origin);
129
+ }),
130
+ notify: (method, params) => {
131
+ if (inFrame)
132
+ globalThis.parent.postMessage({ jsonrpc: "2.0", method, params }, origin);
133
+ },
134
+ listen: (fn) => listeners.add(fn),
135
+ };
136
+ }
137
+ /** Once the template's own look is replaced by the host's, its copy goes. */
138
+ function Painted() {
139
+ useLayoutEffect(() => document.getElementById("copilotz-first-paint")?.remove(), []);
140
+ return null;
141
+ }
142
+ export async function widget(options) {
143
+ const react = createRoot(options.root);
144
+ const theme = themeOf(options.plugins);
145
+ const css = themeCss(theme);
146
+ const draw = (node) => react.render(_jsxs(ThemeContext, { value: theme, children: [_jsx("style", { href: "copilotz-theme", precedence: "copilotz", children: css }), _jsx("style", { href: "copilotz-base", precedence: "copilotz", children: BASE }), _jsx("style", { href: "copilotz-widget", precedence: "copilotz", children: WIDGET_CSS }), _jsx(Painted, {}), node] }));
147
+ draw(null);
148
+ const bridge = bridgeOf();
149
+ let mode = "inline";
150
+ const setTheme = (said) => {
151
+ if (said === "dark" || said === "light")
152
+ document.documentElement.dataset.theme = said;
153
+ };
154
+ const setMode = (said) => said === "inline" || said === "pip" || said === "fullscreen" ? said : undefined;
155
+ // What the tool's result said, from the bridge's notification or ChatGPT's globals.
156
+ let found;
157
+ const arrived = Promise.withResolvers();
158
+ const take = (result) => {
159
+ const meta = widgetOf(result);
160
+ if (meta && !found) {
161
+ found = meta;
162
+ arrived.resolve(meta);
163
+ }
164
+ };
165
+ // Set once the View is shown: what a change of the host's context does.
166
+ const context = {};
167
+ bridge.listen((method, params) => {
168
+ if (method === "ui/notifications/tool-result")
169
+ take(params);
170
+ if (method === "ui/notifications/host-context-changed")
171
+ context.changed?.(params);
172
+ });
173
+ // MCP Apps' handshake; a host that doesn't answer it is ChatGPT's own API alone.
174
+ let standard = false;
175
+ try {
176
+ const answer = await bridge.request("ui/initialize", {
177
+ protocolVersion: "2026-01-26",
178
+ clientInfo: { name: "copilotz-widget", version: "1" },
179
+ appInfo: { name: "copilotz-widget", version: "1" },
180
+ capabilities: {},
181
+ appCapabilities: { availableDisplayModes: ["inline", "pip", "fullscreen"] },
182
+ }, 1_500);
183
+ standard = true;
184
+ const context = isObject(answer?.hostContext) ? answer.hostContext : {};
185
+ setTheme(context.theme);
186
+ mode = setMode(context.displayMode) ?? mode;
187
+ bridge.notify("ui/notifications/initialized", {});
188
+ }
189
+ catch {
190
+ // ChatGPT's API, where it's all there is.
191
+ }
192
+ const globals = () => {
193
+ const api = openai();
194
+ if (!api)
195
+ return;
196
+ setTheme(api.theme);
197
+ take(api.toolResponseMetadata);
198
+ return api;
199
+ };
200
+ globals();
201
+ addEventListener("openai:set_globals", () => {
202
+ const before = mode;
203
+ const api = globals();
204
+ const now = setMode(api?.displayMode);
205
+ if (now && now !== before)
206
+ context.changed?.({ displayMode: now });
207
+ });
208
+ if (!standard)
209
+ mode = setMode(openai()?.displayMode) ?? mode;
210
+ // ChatGPT may set its globals after the page loads: look again a while.
211
+ const looking = setInterval(globals, 200);
212
+ const timer = setTimeout(() => arrived.resolve(undefined), options.wait ?? 15_000);
213
+ const meta = await arrived.promise;
214
+ clearInterval(looking);
215
+ clearTimeout(timer);
216
+ if (!meta) {
217
+ draw(_jsx("div", { className: "copilotz-widget-empty", role: "status" }));
218
+ return undefined;
219
+ }
220
+ /** A tool call through the host: MCP Apps' `tools/call`, else ChatGPT's `callTool`. */
221
+ const callTool = async (name, args) => {
222
+ if (standard) {
223
+ try {
224
+ return await bridge.request("tools/call", { name, arguments: args });
225
+ }
226
+ catch (error) {
227
+ const said = String(error?.message ?? "");
228
+ const code = error?.code;
229
+ if (!openai()?.callTool ||
230
+ !(code === -32601 || /not found|unsupported|not supported/i.test(said))) {
231
+ throw error;
232
+ }
233
+ }
234
+ }
235
+ const api = openai();
236
+ if (!api?.callTool) {
237
+ throw Object.assign(new Error("This widget can't call its app here"), {
238
+ code: "unavailable",
239
+ });
240
+ }
241
+ return await api.callTool(name, args);
242
+ };
243
+ // Each reply brings a new grant (one in use never runs out; one that leaked does).
244
+ const renew = (result) => {
245
+ const grant = metaOf(result)["copilotz/grant"];
246
+ if (typeof grant === "string")
247
+ meta.grant = grant;
248
+ };
249
+ const answersOf = (result) => {
250
+ const reads = metaOf(result)["copilotz/reads"];
251
+ return Array.isArray(reads) ? reads : [];
252
+ };
253
+ const client = connect({
254
+ plugins: options.plugins,
255
+ known: meta.reads ?? [],
256
+ link: {
257
+ read: async (reads) => {
258
+ const result = await callTool(meta.read, { reads, _grant: meta.grant });
259
+ renew(result);
260
+ const answers = new Map(answersOf(result));
261
+ const failed = {
262
+ error: { message: textOf(result) || "Couldn't read", code: "unavailable" },
263
+ };
264
+ return reads.map(({ key }) => ({ key, ...(answers.get(key) ?? failed) }));
265
+ },
266
+ call: async (action, input) => {
267
+ const tool = meta.tools?.[action];
268
+ if (!tool) {
269
+ throw Object.assign(new Error(`${action} isn't offered in this widget`), {
270
+ code: "forbidden",
271
+ });
272
+ }
273
+ const result = await callTool(tool, {
274
+ ...(isObject(input) ? input : {}),
275
+ _grant: meta.grant,
276
+ // Its own id: the line runs a call once by it (a host may number requests again).
277
+ _call: crypto.randomUUID(),
278
+ _reads: client.watching(),
279
+ });
280
+ renew(result);
281
+ const answers = answersOf(result);
282
+ if (answers.length)
283
+ client.update(answers);
284
+ const said = metaOf(result);
285
+ if (result.isError) {
286
+ const error = isObject(said["copilotz/error"]) ? said["copilotz/error"] : {};
287
+ throw Object.assign(new Error(String(error.message ?? textOf(result))), error);
288
+ }
289
+ return said["copilotz/result"];
290
+ },
291
+ },
292
+ });
293
+ session.client = client;
294
+ session.viewer = meta.viewer;
295
+ // What Views ask of their host (surface.ts).
296
+ const intervals = new Set();
297
+ setSurface({
298
+ display: async (wanted) => {
299
+ if (standard) {
300
+ try {
301
+ const answer = await bridge.request("ui/request-display-mode", { mode: wanted });
302
+ const now = setMode(answer?.mode);
303
+ if (now && now !== mode)
304
+ context.changed?.({ displayMode: now });
305
+ return now ?? mode;
306
+ }
307
+ catch {
308
+ // ChatGPT's own, below.
309
+ }
310
+ }
311
+ await openai()?.requestDisplayMode?.({ mode: wanted }).catch(() => { });
312
+ const now = setMode(openai()?.displayMode);
313
+ if (now && now !== mode)
314
+ context.changed?.({ displayMode: now });
315
+ return now ?? mode;
316
+ },
317
+ tell: async (text) => {
318
+ if (standard) {
319
+ try {
320
+ await bridge.request("ui/message", { role: "user", content: { type: "text", text } });
321
+ return;
322
+ }
323
+ catch {
324
+ // ChatGPT's own, below.
325
+ }
326
+ }
327
+ await openai()?.sendFollowUpMessage?.({ prompt: text, scrollToBottom: true });
328
+ },
329
+ remind: async (text) => {
330
+ if (standard) {
331
+ try {
332
+ await bridge.request("ui/update-model-context", { content: [{ type: "text", text }] });
333
+ return;
334
+ }
335
+ catch {
336
+ // ChatGPT's own, below.
337
+ }
338
+ }
339
+ const api = openai();
340
+ if (api?.updateModelContext) {
341
+ await api.updateModelContext({ content: [{ type: "text", text }] });
342
+ }
343
+ else
344
+ api?.setWidgetState?.({ note: text });
345
+ },
346
+ openLink: async (url) => {
347
+ if (standard) {
348
+ try {
349
+ await bridge.request("ui/open-link", { url });
350
+ return;
351
+ }
352
+ catch {
353
+ // ChatGPT's own, below.
354
+ }
355
+ }
356
+ const api = openai();
357
+ if (api?.openExternal)
358
+ api.openExternal({ href: url });
359
+ else
360
+ globalThis.open?.(url, "_blank", "noopener,noreferrer");
361
+ },
362
+ every: (ms) => {
363
+ const timer = setInterval(() => {
364
+ if (document.visibilityState === "visible")
365
+ void client.refresh().catch(() => { });
366
+ }, ms);
367
+ intervals.add(timer);
368
+ return () => {
369
+ clearInterval(timer);
370
+ intervals.delete(timer);
371
+ };
372
+ },
373
+ });
374
+ let shown;
375
+ const show = () => {
376
+ const observed = client.observe("web", meta.view, meta.item, {
377
+ viewer: meta.viewer,
378
+ hints: { ...meta.hints, mode, surface: "widget" },
379
+ part: (part, key) => _jsx(Part, { part: part }, key),
380
+ });
381
+ draw(_jsx(Part, { part: observed }));
382
+ const old = shown;
383
+ shown = observed;
384
+ void observed.ready.then(() => old?.close());
385
+ };
386
+ context.changed = (said) => {
387
+ setTheme(said.theme);
388
+ const now = setMode(said.displayMode);
389
+ if (now && now !== mode) {
390
+ mode = now;
391
+ show();
392
+ }
393
+ };
394
+ show();
395
+ // Shown again (the conversation scrolled back to it, the app reopened): what it shows now.
396
+ document.addEventListener("visibilitychange", () => {
397
+ if (document.visibilityState === "visible")
398
+ void client.refresh().catch(() => { });
399
+ });
400
+ // Links to the web open the host's way; nothing navigates the widget itself.
401
+ document.addEventListener("click", (event) => {
402
+ const link = event.target?.closest?.("a");
403
+ if (!link || event.defaultPrevented || link.hasAttribute("download"))
404
+ return;
405
+ event.preventDefault();
406
+ if (/^https?:$/.test(link.protocol))
407
+ void openLink(link.href);
408
+ });
409
+ // Its height, as it changes: the host sizes the frame to it.
410
+ let told = 0;
411
+ new ResizeObserver(() => {
412
+ const height = Math.ceil(document.documentElement.scrollHeight);
413
+ if (height === told)
414
+ return;
415
+ told = height;
416
+ bridge.notify("ui/notifications/size-changed", {
417
+ width: Math.ceil(document.documentElement.clientWidth),
418
+ height,
419
+ });
420
+ openai()?.notifyIntrinsicHeight?.(height);
421
+ }).observe(document.body);
422
+ return client;
423
+ }
424
+ /** A widget's page: its frame is the host's, so the page has no height of its own to fill. */
425
+ const WIDGET_CSS = `
426
+ html, body { height: auto; min-height: 0; background: var(--background); }
427
+ #app { height: auto; }
428
+ .copilotz-widget-empty { min-height: 48px; }
429
+ `;