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,215 @@
1
+ /**
2
+ * Who's calling, as far as the network says: the caller's address, from the
3
+ * header the app's front sets, believed only through the front. What a
4
+ * plugin that limits callers by address reads them with (MCP's lines, the
5
+ * the web lines), each from its own settings (`CallerSettings`).
6
+ *
7
+ * - **With `front`** (the front's secret): a request without it came around
8
+ * the front, straight to the app: it's refused (`refused`).
9
+ * - **With `hops`:** the entry that many from the end of the header's list,
10
+ * the one the app's own proxy appended.
11
+ * - **An address that can't be read** (none, garbled, too few entries) is
12
+ * no address of its own: it's counted with every other such call, in one
13
+ * tight bucket (`unvouched`), never let through unlimited.
14
+ * - **How it's counted:** an IPv4 address by itself (also written as IPv6,
15
+ * `::ffff:a.b.c.d`); an IPv6 address by its /64 (one customer's network
16
+ * has billions of addresses).
17
+ * - **Exempt ranges** (a shared proxy's: OpenAI's) apply only to an address
18
+ * read this way, never to one the caller claims.
19
+ *
20
+ * Nothing here is kept: what limits count is the plugin's to keep.
21
+ */
22
+ /** The header the web host's front carries its secret in. */
23
+ const FRONT = "x-copilotz-front";
24
+ /** Headers that hold a list of addresses, each proxy appending its own: they need `hops`. */
25
+ const LISTS = ["x-forwarded-for"];
26
+ /** Calls whose address can't be read, all counted as one. */
27
+ export const UNVOUCHED = "unvouched";
28
+ /** Whether two strings are the same, taking as long whatever their first difference. */
29
+ const same = (a, b) => {
30
+ let differ = a.length ^ b.length;
31
+ for (let i = 0; i < Math.max(a.length, b.length); i++) {
32
+ differ |= (a.charCodeAt(i) || 0) ^ (b.charCodeAt(i) || 0);
33
+ }
34
+ return differ === 0;
35
+ };
36
+ /** Who calls, by the app's `caller` settings; undefined without them (nothing goes by address). */
37
+ export function callerFrom(request, caller) {
38
+ if (!caller)
39
+ return undefined;
40
+ if (caller.front !== undefined) {
41
+ const said = request.headers.get(FRONT);
42
+ if (said === null || !same(said, caller.front))
43
+ return "refused";
44
+ }
45
+ const list = (request.headers.get(caller.header) ?? "").split(",").map((part) => part.trim())
46
+ .filter(Boolean);
47
+ const entry = caller.hops ? list.at(-caller.hops) : list.length === 1 ? list[0] : undefined;
48
+ const at = entry ? addressOf(entry) : undefined;
49
+ if (!at)
50
+ return { counted: UNVOUCHED, exempt: false };
51
+ return { counted: countOf(at), exempt: inRanges(at, caller.exempt) };
52
+ }
53
+ /** What an address is counted as: IPv4 by itself, IPv6 by its /64. */
54
+ const countOf = (at) => at.size === 32 ? `4:${at.bits.toString(16)}` : `6:${(at.bits >> 64n).toString(16)}`;
55
+ /**
56
+ * What an address the network gave (a socket's peer, as the listener saw it)
57
+ * is counted as, as `callerFrom` counts a front's: IPv4 by itself, IPv6 by
58
+ * its /64. Undefined when it isn't an address.
59
+ */
60
+ export function countedOf(address) {
61
+ const at = addressOf(address.replace(/^\[|\]$/g, "").replace(/%.*$/, ""));
62
+ return at ? countOf(at) : undefined;
63
+ }
64
+ /**
65
+ * How many callers' worth each network counts as, by its prefix's length:
66
+ * an IPv4 address and an IPv6 /64 are one caller; an IPv4 /24 eight (a
67
+ * mobile carrier's addresses are many people's); an IPv6 /56 four (one
68
+ * home's), a /48 eight (one site's, which a tunnel broker hands out free:
69
+ * more than a home, but well under what a line takes from everyone). One
70
+ * that can't be read (`unvouched`, 0) is one.
71
+ */
72
+ export const SCALE = { 32: 1, 24: 8, 64: 1, 56: 4, 48: 8, 0: 1 };
73
+ /**
74
+ * The networks a caller counted as `counted` (`callerFrom`, `countedOf`) is
75
+ * in, narrowest first, so a limit by address holds for its neighbours too:
76
+ * an IPv4 address, then its /24; an IPv6 /64, then its /56 and its /48. Calls
77
+ * whose address can't be read are one network of their own.
78
+ */
79
+ export function networksOf(counted) {
80
+ const [family, hex] = counted.split(":");
81
+ const bits = /^[0-9a-f]{1,16}$/.test(hex ?? "") ? BigInt(`0x${hex}`) : undefined;
82
+ if (family === "4" && bits !== undefined) {
83
+ return [
84
+ { network: counted, bits: 32, scale: SCALE[32] },
85
+ { network: `4/24:${(bits >> 8n).toString(16)}`, bits: 24, scale: SCALE[24] },
86
+ ];
87
+ }
88
+ if (family === "6" && bits !== undefined) {
89
+ return [
90
+ { network: counted, bits: 64, scale: SCALE[64] },
91
+ { network: `6/56:${(bits >> 8n).toString(16)}`, bits: 56, scale: SCALE[56] },
92
+ { network: `6/48:${(bits >> 16n).toString(16)}`, bits: 48, scale: SCALE[48] },
93
+ ];
94
+ }
95
+ return [{ network: counted, bits: 0, scale: SCALE[0] }];
96
+ }
97
+ /**
98
+ * How many callers a network's tag counts as: a tag is `<bits>-<…>` (the
99
+ * the web lines tag each network a visitor came from that way, an
100
+ * HMAC after the dash: never the address). One, for anything else.
101
+ */
102
+ export const scaleOf = (tag) => SCALE[Number(tag.split("-")[0])] ?? 1;
103
+ /** An IPv4 address's 32 bits, from "a.b.c.d". */
104
+ function v4(text) {
105
+ const parts = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(text)?.slice(1).map(Number);
106
+ if (!parts || parts.some((p) => p > 255))
107
+ return undefined;
108
+ return parts.reduce((n, p) => (n << 8n) | BigInt(p), 0n);
109
+ }
110
+ /**
111
+ * An address as bits: IPv4 in 32; IPv6 in 128, unless it's an IPv4 address
112
+ * written as one (`::ffff:a.b.c.d`, `::ffff:cb00:7163`), which is IPv4.
113
+ * Undefined when it isn't an address. A zone (`%eth0`) or brackets aren't taken.
114
+ */
115
+ export function addressOf(text) {
116
+ const four = v4(text);
117
+ if (four !== undefined)
118
+ return { bits: four, size: 32 };
119
+ if (!/^[0-9a-f:.]+$/i.test(text) || text.split("::").length > 2)
120
+ return undefined;
121
+ // A dotted IPv4 at the end, as its two groups.
122
+ let written = text;
123
+ const dotted = /^(.*:)(\d{1,3}(?:\.\d{1,3}){3})$/.exec(text);
124
+ if (dotted) {
125
+ const bits = v4(dotted[2]);
126
+ if (bits === undefined)
127
+ return undefined;
128
+ written = `${dotted[1]}${(bits >> 16n).toString(16)}:${(bits & 0xffffn).toString(16)}`;
129
+ }
130
+ if (written.includes("."))
131
+ return undefined;
132
+ const [head, tail] = written.includes("::") ? written.split("::") : [written, undefined];
133
+ const left = head ? head.split(":") : [];
134
+ const right = tail ? tail.split(":") : [];
135
+ const missing = 8 - left.length - right.length;
136
+ if (tail === undefined ? left.length !== 8 : missing < 1)
137
+ return undefined;
138
+ const groups = [...left, ...Array(tail === undefined ? 0 : missing).fill("0"), ...right];
139
+ if (groups.some((g) => !/^[0-9a-f]{1,4}$/i.test(g)))
140
+ return undefined;
141
+ const bits = groups.reduce((n, g) => (n << 16n) | BigInt(parseInt(g, 16)), 0n);
142
+ // IPv4-mapped: ::ffff:0:0/96.
143
+ if (bits >> 32n === 0xffffn)
144
+ return { bits: bits & 0xffffffffn, size: 32 };
145
+ return { bits, size: 128 };
146
+ }
147
+ /** A CIDR range (`192.0.2.0/24`, `2001:db8::/32`) as its bits and prefix; undefined when malformed. */
148
+ function rangeOf(text) {
149
+ const [address, prefix, ...more] = text.split("/");
150
+ const at = addressOf(address ?? "");
151
+ const length = Number(prefix);
152
+ if (!at || more.length || !/^\d{1,3}$/.test(prefix ?? "") || length > at.size)
153
+ return undefined;
154
+ return { ...at, length };
155
+ }
156
+ /** Whether `text` is a CIDR range. */
157
+ const rangeOk = (text) => !!rangeOf(text);
158
+ /** Whether an address is in any of the ranges. */
159
+ function inRanges(at, ranges = []) {
160
+ return ranges.some((text) => {
161
+ const range = rangeOf(text);
162
+ if (!range || range.size !== at.size)
163
+ return false;
164
+ const shift = BigInt(at.size - range.length);
165
+ return (at.bits >> shift) === (range.bits >> shift);
166
+ });
167
+ }
168
+ /** This machine's and private networks' ranges: a proxy's or a load balancer's, not a caller's. */
169
+ const PRIVATE = [
170
+ "127.0.0.0/8",
171
+ "10.0.0.0/8",
172
+ "172.16.0.0/12",
173
+ "192.168.0.0/16",
174
+ "169.254.0.0/16",
175
+ "100.64.0.0/10",
176
+ "::1/128",
177
+ "fc00::/7",
178
+ "fe80::/10",
179
+ ];
180
+ /**
181
+ * Whether an address (a socket's peer) is this machine's or a private
182
+ * network's: loopback, RFC 1918, link-local, shared (100.64/10), unique
183
+ * local. A caller seen there is most likely a proxy before the app.
184
+ */
185
+ export function privateAddress(text) {
186
+ const at = addressOf(text.replace(/^\[|\]$/g, "").replace(/%.*$/, ""));
187
+ return !!at && inRanges(at, PRIVATE);
188
+ }
189
+ /** What's wrong with how a plugin reads who's calling, if anything (checked when the app starts). */
190
+ export function callerProblem(caller) {
191
+ if (!caller)
192
+ return undefined;
193
+ if (typeof caller.header !== "string" || !/^[a-z0-9-]{1,64}$/i.test(caller.header)) {
194
+ return "caller.header is a header's name (cf-connecting-ip, x-forwarded-for)";
195
+ }
196
+ if (caller.front === undefined && caller.hops === undefined) {
197
+ return "caller says why its header is believed: the front's secret (front), or hops";
198
+ }
199
+ if (caller.front !== undefined && (typeof caller.front !== "string" || caller.front.length < 16)) {
200
+ return "caller.front is the front's secret (16 characters at least)";
201
+ }
202
+ if (caller.hops !== undefined && !(Number.isInteger(caller.hops) && caller.hops > 0)) {
203
+ return "caller.hops is a whole number over 0";
204
+ }
205
+ const header = caller.header.toLowerCase();
206
+ if (header === "forwarded")
207
+ return "caller.header: Forwarded isn't read (use x-forwarded-for)";
208
+ if (LISTS.includes(header) && caller.hops === undefined) {
209
+ return `caller.header ${header} is a list whose first entries the caller writes: say its hops`;
210
+ }
211
+ const bad = (caller.exempt ?? []).find((range) => !rangeOk(range));
212
+ if (bad !== undefined)
213
+ return `caller.exempt: "${bad}" isn't a CIDR range (192.0.2.0/24)`;
214
+ return undefined;
215
+ }
@@ -6,14 +6,40 @@
6
6
  * watched there; a read's new result, pushed, runs again the parts that read
7
7
  * it. Handlers' calls and events go to the owner, as the person.
8
8
  *
9
+ * Or over a link of its host's (`link`): reads asked and Actions called by
10
+ * whatever carries them (an outside assistant's widget bridge, a server
11
+ * answering as the person), with no pushes: what's shown is asked again when
12
+ * the host says (`refresh`), or set from what came back (`update`). Seeded
13
+ * with answers already known (`known`: a snapshot), its first pass reads none
14
+ * of them. What it knows of the reads watched now is `known()`: a snapshot,
15
+ * by the same keys.
16
+ *
9
17
  * It loads front ends only (their Views, and their resources): the plugins
10
18
  * they build on live with the owner.
11
19
  */
12
20
  import { createWorker } from "oxianjs";
21
+ import { type Answer, type Remote } from "./browsers.js";
13
22
  import type { Plugins } from "./define.js";
14
23
  import { type Observers } from "./observe.js";
15
24
  /** What a client's transport is: the one Oxian workers connect with. */
16
25
  export type ClientTransport = Parameters<typeof createWorker>[0]["transport"];
26
+ /**
27
+ * What carries a client's reads and calls when it isn't Oxian (see `connect`): each answers as
28
+ * the person, under the rules, as the owner answers a browser.
29
+ */
30
+ export type ClientLink = {
31
+ /** Answers a batch of reads, by the key each was asked under. */
32
+ read(reads: {
33
+ key: string;
34
+ read: Remote;
35
+ }[]): Promise<({
36
+ key: string;
37
+ } & Answer)[]>;
38
+ call(action: string, input: unknown): Promise<unknown>;
39
+ emit?(type: string, data: Record<string, unknown>): Promise<void>;
40
+ };
41
+ /** Reads' answers by their keys: what a client knows (a snapshot), or is seeded with. */
42
+ export type Known = [key: string, answer: Answer][];
17
43
  export type Client = {
18
44
  /** Observes a View here, as the person: its reads come from the owner, and follow its changes. */
19
45
  observe: Observers["observe"];
@@ -23,15 +49,33 @@ export type Client = {
23
49
  emit(type: string, data?: Record<string, unknown>): Promise<void>;
24
50
  /** Resolves when no part is running here. */
25
51
  idle(): Promise<void>;
52
+ /** What it knows of the reads watched now, by key: a snapshot to seed another client with. */
53
+ known(): Known;
54
+ /** The reads watched now, by key: what to ask answers for, after a call over a link. */
55
+ watching(): {
56
+ key: string;
57
+ read: Remote;
58
+ }[];
59
+ /** Asks every read watched here again; what changed shows. For a link, which isn't pushed to. */
60
+ refresh(): Promise<void>;
61
+ /** Reads' new answers, by key, from elsewhere (a call's reply): those watched here show them. */
62
+ update(answers: Known): void;
26
63
  /** Connected, and the owner knows who it is. */
27
64
  ready: Promise<void>;
28
65
  close(): Promise<void>;
29
66
  };
30
67
  export declare function connect(options: {
68
+ /** Its front ends: the Views it draws, and their resources. */
69
+ plugins: Plugins;
70
+ /** Answers already known, by read key (a snapshot): the first pass reads none of them. */
71
+ known?: Known;
72
+ } & ({
31
73
  transport: ClientTransport;
32
74
  /** What it shows to connect: a one-time ticket from its host, asked for each new connection. */
33
75
  ticket(): Promise<string>;
34
- /** Its front ends: the Views it draws, and their resources. */
35
- plugins: Plugins;
36
76
  id?: string;
37
- }): Client;
77
+ link?: undefined;
78
+ } | {
79
+ link: ClientLink;
80
+ transport?: undefined;
81
+ })): Client;
package/runtime/client.js CHANGED
@@ -6,6 +6,14 @@
6
6
  * watched there; a read's new result, pushed, runs again the parts that read
7
7
  * it. Handlers' calls and events go to the owner, as the person.
8
8
  *
9
+ * Or over a link of its host's (`link`): reads asked and Actions called by
10
+ * whatever carries them (an outside assistant's widget bridge, a server
11
+ * answering as the person), with no pushes: what's shown is asked again when
12
+ * the host says (`refresh`), or set from what came back (`update`). Seeded
13
+ * with answers already known (`known`: a snapshot), its first pass reads none
14
+ * of them. What it knows of the reads watched now is `known()`: a snapshot,
15
+ * by the same keys.
16
+ *
9
17
  * It loads front ends only (their Views, and their resources): the plugins
10
18
  * they build on live with the owner.
11
19
  */
@@ -30,9 +38,8 @@ const keyOf = (read) => canonical(read);
30
38
  const WATCHED = "@";
31
39
  export function connect(options) {
32
40
  const registry = merge(options.plugins, { elsewhere: true });
33
- const attempt = { attemptId: crypto.randomUUID(), epoch: Date.now() };
34
41
  /** What the owner said each watched read came to. */
35
- const known = new Map();
42
+ const known = new Map(options.known ?? []);
36
43
  /** Reads asked for, not yet answered, by key. */
37
44
  const asked = new Map();
38
45
  /** Every read the Views here are watching, by key: what a new connection asks for again. */
@@ -45,47 +52,87 @@ export function connect(options) {
45
52
  /** Connections the owner has opened to this client (its session streams). */
46
53
  let sessions = 0;
47
54
  let batch = [];
48
- const worker = createWorker({
49
- id: options.id ?? `browser-${crypto.randomUUID()}`,
50
- transport: options.transport,
51
- activate: ({ workerId }) => ({ identity: { workerId, ...attempt } }),
52
- register: async () => ({
53
- credential: { kind: "registration", capability: await options.ticket() },
54
- expiresAtMs: Date.now() + 60_000,
55
- }),
56
- capacity: 1,
57
- hostCalls: { maxConcurrent: 64 },
58
- workloads: {
59
- // What the owner tells: each line, the new results of the reads one commit
60
- // changed. A new connection after the first watches nothing yet: what's
61
- // shown is asked for again.
62
- [SESSION]: async ({ input }) => {
63
- const session = ++sessions;
64
- if (session > 1)
65
- void rewatch();
66
- // A line: what one commit changed, shown at once.
67
- for await (const line of lines(input)) {
68
- // A newer connection has asked for everything again: this one's news is older.
69
- if (session !== sessions)
70
- break;
71
- const changed = [];
72
- for (const { key, ...now } of line) {
73
- if (racing.has(key))
74
- racing.set(key, now);
75
- if (!known.has(key))
76
- continue;
77
- known.set(key, now);
78
- changed.push(WATCHED + key);
55
+ /** One enrolment: a worker that comes in with a new ticket, and keeps its connection after. */
56
+ const enrol = (over) => {
57
+ const attempt = { attemptId: crypto.randomUUID(), epoch: Date.now() };
58
+ return createWorker({
59
+ id: over.id,
60
+ transport: over.transport,
61
+ activate: ({ workerId }) => ({ identity: { workerId, ...attempt } }),
62
+ register: async () => ({
63
+ credential: { kind: "registration", capability: await over.ticket() },
64
+ expiresAtMs: Date.now() + 60_000,
65
+ }),
66
+ capacity: 1,
67
+ hostCalls: { maxConcurrent: 64 },
68
+ workloads: {
69
+ // What the owner tells: each line, the new results of the reads one commit
70
+ // changed. A new connection after the first watches nothing yet: what's
71
+ // shown is asked for again.
72
+ [SESSION]: async ({ input }) => {
73
+ const session = ++sessions;
74
+ if (session > 1)
75
+ void rewatch();
76
+ // A line: what one commit changed, shown at once.
77
+ for await (const line of lines(input)) {
78
+ // A newer connection has asked for everything again: this one's news is older.
79
+ if (session !== sessions)
80
+ break;
81
+ const changed = [];
82
+ for (const { key, ...now } of line) {
83
+ if (racing.has(key))
84
+ racing.set(key, now);
85
+ if (!known.has(key))
86
+ continue;
87
+ known.set(key, now);
88
+ changed.push(WATCHED + key);
89
+ }
90
+ if (changed.length)
91
+ observers.changed(changed.map((c) => [c, [{}]]));
79
92
  }
80
- if (changed.length)
81
- observers.changed(changed.map((c) => [c, [{}]]));
82
- }
93
+ },
83
94
  },
84
- },
85
- });
95
+ });
96
+ };
86
97
  let closed = false;
87
- /** Asks the owner, as the person. While the connection is coming back, it waits and asks then. */
88
- const ask = async (workload, body) => {
98
+ const oxian = options.link === undefined
99
+ ? {
100
+ transport: options.transport,
101
+ ticket: options.ticket,
102
+ id: options.id ?? `browser-${crypto.randomUUID()}`,
103
+ }
104
+ : undefined;
105
+ let worker = oxian ? enrol(oxian) : undefined;
106
+ /**
107
+ * Once in, its way back refused (who it was ended: signed out, erased, and
108
+ * its resume credential with it; or an owner that never knew it), it comes
109
+ * in again with a new ticket, which only a browser that's still someone gets
110
+ * (a page's `ticket` reloads it otherwise). One never let in stays out.
111
+ */
112
+ const follow = (current, again = 0) => {
113
+ current.closed.catch(() => { });
114
+ // Back in after having been in: a refusal (a busy moment) is tried again, longer apart.
115
+ const retry = () => {
116
+ if (closed || current !== worker || !again)
117
+ return;
118
+ setTimeout(() => {
119
+ if (closed || current !== worker)
120
+ return;
121
+ worker = enrol(oxian);
122
+ follow(worker, again + 1);
123
+ }, Math.min(500 * 2 ** (again - 1), 5_000));
124
+ };
125
+ void current.ready.then(() => current.closed.then((result) => {
126
+ if (closed || current !== worker || result.reason !== "reenrollment_required")
127
+ return;
128
+ worker = enrol(oxian);
129
+ follow(worker, 1);
130
+ })).catch(retry);
131
+ };
132
+ if (worker)
133
+ follow(worker);
134
+ /** Asks the owner over Oxian, as the person. While the connection is coming back, it waits and asks then. */
135
+ const viaOxian = async (workload, body) => {
89
136
  let call;
90
137
  for (let waited = 0, delay = 50;; delay = Math.min(delay * 2, 1_000)) {
91
138
  try {
@@ -105,6 +152,25 @@ export function connect(options) {
105
152
  throw Object.assign(new Error(answer.error.message), answer.error);
106
153
  return answer.value;
107
154
  };
155
+ /** Asks the owner, as the person: over Oxian, or over the host's link. */
156
+ const ask = async (workload, body) => {
157
+ const link = options.link;
158
+ if (!link)
159
+ return await viaOxian(workload, body);
160
+ switch (workload) {
161
+ case READ:
162
+ return await link.read(body.reads);
163
+ case CALL:
164
+ return await link.call(body.action, body.input);
165
+ case EMIT:
166
+ if (!link.emit)
167
+ throw invalid("This client's link emits no events");
168
+ return await link.emit(body.type, body.data);
169
+ default:
170
+ // Nothing is watched over a link: there's nothing to stop watching.
171
+ return undefined;
172
+ }
173
+ };
108
174
  /** Asks for reads; each comes to what it was pushed meanwhile, or else to its answer. */
109
175
  const reading = async (reads) => {
110
176
  for (const { key } of reads)
@@ -231,15 +297,39 @@ export function connect(options) {
231
297
  void ask(UNWATCH, { keys: [key] }).catch(() => { });
232
298
  },
233
299
  });
300
+ /** New answers, by key: those watched here, when they differ, run again what read them. */
301
+ const update = (answers) => {
302
+ const changed = [];
303
+ for (const [key, answer] of answers) {
304
+ if (!watching.has(key))
305
+ continue;
306
+ if (canonical(known.get(key) ?? null) === canonical(answer))
307
+ continue;
308
+ known.set(key, answer);
309
+ changed.push(WATCHED + key);
310
+ }
311
+ if (changed.length)
312
+ observers.changed(changed.map((c) => [c, [{}]]));
313
+ };
234
314
  return {
235
315
  observe: observers.observe,
236
316
  call: (action, input) => ask(CALL, { action, input: input ?? {} }),
237
317
  emit: (type, data) => ask(EMIT, { type, data: data ?? {} }),
238
318
  idle: observers.idle,
239
- ready: worker.ready.then(() => { }),
319
+ known: () => [...watching.keys()].flatMap((key) => known.has(key) ? [[key, known.get(key)]] : []),
320
+ watching: () => [...watching].map(([key, read]) => ({ key, read })),
321
+ refresh: async () => {
322
+ const reads = [...watching].map(([key, read]) => ({ key, read }));
323
+ if (!reads.length)
324
+ return;
325
+ const answers = await reading(reads);
326
+ update(answers.map(({ key, ...answer }) => [key, answer]));
327
+ },
328
+ update,
329
+ ready: worker ? worker.ready.then(() => { }) : Promise.resolve(),
240
330
  close: () => {
241
331
  closed = true;
242
- return worker.stop();
332
+ return worker ? worker.stop() : Promise.resolve();
243
333
  },
244
334
  };
245
335
  }
@@ -93,7 +93,19 @@ export type Context = {
93
93
  processor: string;
94
94
  key: string;
95
95
  }): Promise<boolean>;
96
- /** Renders `item` through the View registered for its kind and the renderer (see Views). */
96
+ /**
97
+ * Ends an actor's browsers, when who they were ends (signed out, erased):
98
+ * each connection closes, and comes back only with a new ticket. How many
99
+ * it ended.
100
+ *
101
+ * Like `cancel`, it checks nothing of who asks: plugins are trusted code,
102
+ * and it's theirs to call only once who the actor was has ended (a sign-out,
103
+ * an erasure the rules allowed). It reaches only this runtime's browsers:
104
+ * with the orgs host, each org's runtime has its own owner, so one org's
105
+ * code never ends another org's browsers.
106
+ */
107
+ disconnect(actor: Actor): Promise<number>;
108
+ /** Renders `item` through the View registered for its kind and the medium (see Views). */
97
109
  render: Render;
98
110
  /**
99
111
  * Appends a document to a records collection, and returns its `_id`. It
@@ -157,14 +169,16 @@ export type ReadContext = {
157
169
  export type Merged = {
158
170
  resources: Resources;
159
171
  adapters: Adapters;
172
+ /** Every plugin's Actions, by name: whether one a declaration names is there. */
173
+ actions: Readonly<Record<string, ActionDef>>;
160
174
  /** Calls an unrecorded Action, as a read does (another plugin's check: `models.check`). */
161
175
  call<R = unknown>(action: string, input?: unknown): Promise<R>;
162
176
  };
163
177
  /**
164
178
  * Views present data to a medium. A plugin registers them by kind (a
165
- * collection's name, `tool:<name>`, a named datum) and renderer (a medium:
166
- * `llm`, later `react`). The runtime gives neither name a meaning; for a kind
167
- * and renderer, the last plugin's View wins.
179
+ * collection's name, `tool:<name>`, a named datum) and medium (`llm`,
180
+ * `web`…). The runtime gives neither name a meaning; for a kind
181
+ * and medium, the last plugin's View wins.
168
182
  */
169
183
  export type Views = Record<string, Record<string, ViewDef>>;
170
184
  /** A View: an item, for a medium. Its context says what showing another View returns there. */
@@ -183,10 +197,10 @@ export type RenderOptions = {
183
197
  viewer?: Viewer;
184
198
  hints?: Record<string, unknown>;
185
199
  };
186
- /** Renders through the View for a kind and renderer; undefined when there is none. */
187
- export type Render = (renderer: string, kind: string, item: unknown, options?: RenderOptions) => Promise<unknown>;
200
+ /** Renders through the View for a kind and medium; undefined when there is none. */
201
+ export type Render = (medium: string, kind: string, item: unknown, options?: RenderOptions) => Promise<unknown>;
188
202
  /**
189
- * A read inside a View: it returns at once. While `loading`, the renderer
203
+ * A read inside a View: it returns at once. While `loading`, the runtime
190
204
  * waits for it and runs the View again, until a pass reads nothing new.
191
205
  */
192
206
  export type Read<T> = {
@@ -214,7 +228,7 @@ export type ViewContext<Shown = unknown> = {
214
228
  };
215
229
  resources: Resources;
216
230
  /** The medium being rendered. */
217
- renderer: string;
231
+ medium: string;
218
232
  /** The kind being rendered: a medium's default View (kind `"*"`) renders any kind. */
219
233
  kind: string;
220
234
  viewer?: Viewer;
@@ -223,7 +237,7 @@ export type ViewContext<Shown = unknown> = {
223
237
  /** What the caller asked for (`mode`: a density, …). Open-ended. */
224
238
  hints: Record<string, unknown>;
225
239
  /**
226
- * Renders `item` through its kind's View in this renderer; undefined when
240
+ * Renders `item` through its kind's View in this medium; undefined when
227
241
  * there is none. Observed, the shown View is a part of its own: it runs
228
242
  * again on its own when what it read changes (see `Owner.observe`).
229
243
  */
@@ -442,12 +456,19 @@ export type Labels = {
442
456
  * to what the actor reaches). `undefined`: the collection has no rule, so code
443
457
  * acting for the actor reads and writes it unchecked. Runs in the owner, on
444
458
  * every operation an actor's work makes, with read access to everything.
459
+ *
460
+ * Asked about a browser's own read (`direct`) before it's watched, a rule may
461
+ * refuse it (throwing, `forbidden`) when it won't watch it as asked: a
462
+ * contact's that doesn't name what of its own it reads would run again on
463
+ * every change to the collection.
445
464
  */
446
465
  export type Guard = (actor: Actor, operation: {
447
466
  collection: string;
448
467
  /** Reads, or writes (inserts, updates, replaces and deletes). */
449
468
  access: "read" | "write";
450
469
  filter?: Filter;
470
+ /** A browser's own read, asked before it's watched. */
471
+ direct?: true;
451
472
  }, ctx: ReadContext) => Filter | true | undefined | Promise<Filter | true | undefined>;
452
473
  /** Plugins, in order; a theme's bundle is a list of its own, so lists may nest. */
453
474
  export type Plugins = (Plugin | Plugins)[];
@@ -7,7 +7,7 @@ import { createWorker } from "oxianjs";
7
7
  import { collection } from "./collection.js";
8
8
  import { isRead, RESULTS } from "./ops.js";
9
9
  import { compile, events, fingerprint, invalid, json, merge, unprivate } from "./registry.js";
10
- import { renderer } from "./views.js";
10
+ import { presenter } from "./views.js";
11
11
  import { refuseBlobKeys } from "./blobs.js";
12
12
  import { querying as queryingOver, reading as readingOver } from "./reads.js";
13
13
  import { noMetrics } from "./metrics.js";
@@ -148,7 +148,8 @@ export function createExecutor(options) {
148
148
  },
149
149
  unschedule: async (timer) => Number(await run({ op: "unschedule", timer })) > 0,
150
150
  cancel: async (target) => Boolean(await run({ op: "cancel", ...target })),
151
- render: renderer(registry.views, () => reading(run, job.record, actor)),
151
+ disconnect: async (actor) => Number(await run({ op: "disconnect", actor: { kind: actor.kind, id: actor.id } })),
152
+ render: presenter(registry.views, () => reading(run, job.record, actor)),
152
153
  record: job.record,
153
154
  metrics,
154
155
  resources: registry.resources,
@@ -278,9 +279,9 @@ export function createExecutor(options) {
278
279
  async send(request) {
279
280
  const tx = "tx" in request ? request.tx : undefined;
280
281
  const end = "end" in request ? request.end : undefined;
281
- // A cancel stops other work: it writes nothing of this call's.
282
+ // A cancel stops other work, a disconnect ends browsers: neither writes this call's.
282
283
  const writes = tx !== undefined ||
283
- request.ops.some((op) => !isRead(op) && op.op !== "cancel");
284
+ request.ops.some((op) => !isRead(op) && op.op !== "cancel" && op.op !== "disconnect");
284
285
  const carry = pending && writes && (tx === undefined || !carrying.has(tx));
285
286
  if (carry && tx !== undefined)
286
287
  carrying.add(tx);
@@ -357,10 +358,10 @@ export function createExecutor(options) {
357
358
  ...(request.actor ? { actor: request.actor, outside: true } : {}),
358
359
  }), job.record, request.actor)(request.collection, request.query, request.params);
359
360
  case "render":
360
- return renderer(registry.views, () => reading((op) => job.send({
361
+ return presenter(registry.views, () => reading((op) => job.send({
361
362
  ops: [op],
362
363
  ...(request.actor ? { actor: request.actor, outside: true } : {}),
363
- }), job.record, request.actor))(request.renderer, request.view, request.item, {
364
+ }), job.record, request.actor))(request.medium, request.view, request.item, {
364
365
  ...(request.viewer ? { viewer: request.viewer } : {}),
365
366
  ...(request.hints ? { hints: request.hints } : {}),
366
367
  });