copilotz 1.0.0-rc.37 → 1.0.0-rc.38

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.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,27 @@
1
+ ## 1.0.0-rc.38 — 2026-11-10
2
+
3
+ - **MCP 2026-07-28 cacheable results, widget read schemas, cross-origin MCP lines, and
4
+ `/.well-known/`:**
5
+ - `resources/list`, `resources/templates/list` and `resources/read` now include `ttlMs` and
6
+ `cacheScope` on MCP `2026-07-28` (`CacheableResult`), and handshake versions (`2025-11-25` and
7
+ earlier) omit them on `tools/list` and resource results where `CacheableResult` does not exist.
8
+ - Widget tool inputs (`_reads` and `copilotz_read`'s `reads`) now declare their `items` object
9
+ schema so strict MCP clients accept `tools/list` when widgets are enabled.
10
+ - Stateless routes (`Route.crossOrigin`) enforce their own `Origin` rules without reading session
11
+ cookies, so an MCP line's `origins` (including `"*"`) answers browser preflights (`OPTIONS`) and
12
+ cross-origin `POST`s with CORS headers while keeping no-browser-origin (`403`) as the default.
13
+ - `webPage`'s `/*` catch-all leaves `/.well-known/*` as `404` when no plugin serves a route there,
14
+ instead of answering discovery probes with the HTML page.
15
+ - **A person's next message answers the question an agent waits on them for,** as the web says it
16
+ does ("Waiting on your answer: your next message replies"). `chat.send` finds it when a message
17
+ names none (`replyTo`): the newest question to its sender in that chat that an agent still waits
18
+ on; else one asked of them elsewhere by an agent whose turn waits in that chat, so what they tell
19
+ it there resumes that turn instead of starting a second one beside it. Never for a message sent
20
+ for them (`via`: a routine's), nor to an agent it doesn't go to (`to`, `@mentions`). Until now
21
+ only WhatsApp found it (its own lookup is gone; a quoted message still names what it answers): on
22
+ the web, an answer in the chat an agent opened to ask went to nobody, and the asking turn, with
23
+ whatever waited on it (an answer to hand back to another space), never resumed.
24
+
1
25
  ## 1.0.0-rc.37 — 2026-11-10
2
26
 
3
27
  **Upgrading.** The web shell says nine new words, which an app in another language gives under
package/README.md CHANGED
@@ -162,7 +162,7 @@ OPENAI_API_KEY=sk-… node salon.ts # or bun salon.ts, or deno run -A salon.t
162
162
  ```
163
163
 
164
164
  On Deno, map the name `copilotz` in `deno.json`
165
- (`"copilotz": "jsr:@copilotz/copilotz@^1.0.0-rc.37"`) so the imports read the same everywhere.
165
+ (`"copilotz": "jsr:@copilotz/copilotz@^1.0.0-rc.38"`) so the imports read the same everywhere.
166
166
  Copilotz runs on Node, Deno and Bun, and it's built on web standards for Cloudflare Workers and the
167
167
  browser.
168
168
 
@@ -258,7 +258,9 @@ export const webPage = definePlugin({
258
258
  });
259
259
  },
260
260
  "/*": async (request, { runtime }) => {
261
- if (request.method !== "GET" || !navigating(request)) {
261
+ const path = new URL(request.url).pathname;
262
+ if (request.method !== "GET" || !navigating(request) ||
263
+ path === "/.well-known" || path.startsWith("/.well-known/")) {
262
264
  return json({ error: "Not found" }, 404);
263
265
  }
264
266
  const served = of(runtime);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "copilotz",
3
- "version": "1.0.0-rc.37",
3
+ "version": "1.0.0-rc.38",
4
4
  "description": "Copilotz: one runtime for Node, Deno, Bun, Cloudflare Workers and the browser.",
5
5
  "keywords": [
6
6
  "agents",
@@ -7,8 +7,11 @@
7
7
  * said, agents read it later, and none answers it (what someone did on a
8
8
  * page beside the chat). A contact's goes to the sender of what it replies
9
9
  * to, else the thread's agents: never whom it names, though it too may say
10
- * something to nobody (`to: []`). It replies only to a message of the same conversation that its
11
- * sender reads. Only agents answering in
10
+ * something to nobody (`to: []`). It replies to the message it names (`replyTo`), one of the
11
+ * same conversation that its sender reads; naming none, to the question an agent still waits
12
+ * on its sender for (`awaited`: asked here, else asked elsewhere by an agent whose turn waits
13
+ * here), so a page need not say what its next message answers; never when sent for the person
14
+ * (`via`), nor to an agent it doesn't go to. Only agents answering in
12
15
  * its space answer there: naming one that doesn't fails (`not_here`). Its
13
16
  * files are the sender's own uploads (`chat.attach`), named by id: a call
14
17
  * carries no file's content, so a message of ten large ones goes as quickly
@@ -70,6 +73,33 @@ async function mentionsIn(ctx, text, thread, roster, members) {
70
73
  }
71
74
  return mentions(text, named);
72
75
  }
76
+ /**
77
+ * The question a message naming none answers: the newest one an agent still
78
+ * waits on its sender for, asked in this conversation; else asked of them
79
+ * elsewhere by an agent whose turn waits here (what they tell it here is their
80
+ * answer, and resumes that turn, not a second one). Only an agent the message
81
+ * goes to, when it names any (`to`, `@mentions`). Questions here are read as
82
+ * the sender, as they read them; waits, and what a wait here asked elsewhere
83
+ * (only its id is used), as the system: they're the agents' own.
84
+ */
85
+ async function awaited(ctx, thread, sender, named) {
86
+ const system = ctx.as();
87
+ const waits = system.db.collection("wait");
88
+ const asked = await ctx.db.collection("message").find({ thread, to: sender, replyTo: { $exists: false }, expectReply: { $ne: false } }, { sort: { at: -1 }, limit: 5 });
89
+ for (const question of asked) {
90
+ if (named && !named.includes(question.from))
91
+ continue;
92
+ if (await waits.findOne({ waitingFor: question._id }))
93
+ return question;
94
+ }
95
+ const open = (await waits.find({ thread, "waitingFor.0": { $exists: true } }))
96
+ .filter((w) => !named || named.includes(w.agent));
97
+ const ids = open.flatMap((w) => w.waitingFor);
98
+ if (!ids.length)
99
+ return null;
100
+ const [elsewhere] = await system.db.collection("message").find({ _id: { $in: ids }, to: sender, from: { $in: open.map((w) => w.agent) } }, { sort: { at: -1 }, limit: 1 });
101
+ return elsewhere ?? null;
102
+ }
73
103
  /** Who a message is from, pinned to whoever sends it: a person by id, a contact as `contact:<id>`. */
74
104
  const fromOf = (actor) => actor?.kind === "person"
75
105
  ? actor.id
@@ -185,15 +215,21 @@ export const sendAction = defineAction({
185
215
  const named = input.thread ?? allowed.thread;
186
216
  const threadId = named ?? crypto.randomUUID();
187
217
  const existing = named ? await threads.findOne({ _id: threadId }) : null;
188
- // What it answers: a message the sender reads, in this conversation (else it answers nothing).
189
- const found = input.replyTo
190
- ? await ctx.db.collection("message").findOne({ _id: input.replyTo })
191
- : null;
192
- const replied = found?.thread === threadId ? found : null;
218
+ const from = fromOf(ctx.actor) ?? input.from ?? "user";
193
219
  const where = existing ? existing.in : input.in;
194
220
  const roster = await rosterOf(ctx, where);
195
221
  const members = existing ? existing.agents ?? [] : roster.default;
196
222
  const mentioned = contact ? [] : await mentionsIn(ctx, said, threadId, roster, members);
223
+ // What it answers: the message it names, one the sender reads in this conversation; naming
224
+ // none, the question an agent waits on its sender for (not when sent for them: a routine's).
225
+ const found = input.replyTo
226
+ ? await ctx.db.collection("message").findOne({ _id: input.replyTo })
227
+ : null;
228
+ const replied = input.replyTo
229
+ ? found?.thread === threadId ? found : null
230
+ : existing && !input.via && !nobody
231
+ ? await awaited(ctx, threadId, from, contact ? undefined : input.to ?? (mentioned.length ? mentioned : undefined))
232
+ : null;
197
233
  const asked = (contact ? (nobody ? [] : undefined) : input.to) ??
198
234
  (mentioned.length ? mentioned : replied ? [replied.from] : members);
199
235
  // Agents answer only where they work: one named that doesn't is refused; one gone, left out.
@@ -264,7 +300,7 @@ export const sendAction = defineAction({
264
300
  }
265
301
  : {}),
266
302
  thread: threadId,
267
- from: fromOf(ctx.actor) ?? input.from ?? "user",
303
+ from,
268
304
  ...(where ? { in: where } : {}),
269
305
  to: [...to],
270
306
  text: said,
@@ -1,2 +1,2 @@
1
1
  /** The computer program's version, as `computer.info` and `--version` say it, and its builds are named. */
2
- export declare const VERSION = "1.0.0-rc.37";
2
+ export declare const VERSION = "1.0.0-rc.38";
@@ -1,2 +1,2 @@
1
1
  /** The computer program's version, as `computer.info` and `--version` say it, and its builds are named. */
2
- export const VERSION = "1.0.0-rc.37";
2
+ export const VERSION = "1.0.0-rc.38";
@@ -14,7 +14,7 @@
14
14
  *
15
15
  * ```ts
16
16
  * plugins: [...plugins, await computerDownloads()]
17
- * plugins: [...plugins, await computerDownloads({ dir: "dist/computer/1.0.0-rc.37" })]
17
+ * plugins: [...plugins, await computerDownloads({ dir: "dist/computer/1.0.0-rc.38" })]
18
18
  * plugins: [...plugins, await computerDownloads({ url: "https://downloads.example.com/computer/" })]
19
19
  * ```
20
20
  */
@@ -88,17 +88,68 @@ const fault = (id, code, message, data) => ({
88
88
  });
89
89
  const failed = (status, id, code, message, data) => ({ status, body: fault(id, code, message, data) });
90
90
  const isObject = (value) => !!value && typeof value === "object" && !Array.isArray(value);
91
+ /** Which `Access-Control-Allow-Origin` a line answers `origin` with; undefined when refused. */
92
+ const allowedOrigin = (line, origin) => {
93
+ if (origin === null)
94
+ return undefined;
95
+ const allowed = line.origins ?? [];
96
+ if (allowed.includes("*"))
97
+ return "*";
98
+ return allowed.includes(origin) ? origin : undefined;
99
+ };
100
+ /** CORS headers for an allowed browser `Origin` (and preflight, when the method isn't POST). */
101
+ function corsOf(request, allowed) {
102
+ if (allowed === undefined)
103
+ return { cors: {} };
104
+ const cors = {
105
+ "access-control-allow-origin": allowed,
106
+ "access-control-expose-headers": "mcp-session-id",
107
+ ...(allowed === "*" ? {} : { vary: "Origin" }),
108
+ };
109
+ if (request.method.toUpperCase() !== "O" + "PTIONS")
110
+ return { cors };
111
+ const asked = (request.headers.get("access-control-request-headers") ?? "")
112
+ .split(",")
113
+ .map((h) => h.trim().toLowerCase())
114
+ .filter((h) => /^mcp-param-[a-z0-9-]{1,64}$/.test(h));
115
+ return {
116
+ cors,
117
+ preflight: new Response(null, {
118
+ status: 204,
119
+ headers: {
120
+ ...cors,
121
+ "access-control-allow-methods": "POST, OPTIONS",
122
+ "access-control-allow-headers": [
123
+ "content-type",
124
+ "accept",
125
+ "mcp-session-id",
126
+ "mcp-protocol-version",
127
+ "mcp-method",
128
+ "mcp-name",
129
+ "authorization",
130
+ ...asked,
131
+ ].join(", "),
132
+ "cache-control": "no-store",
133
+ },
134
+ }),
135
+ };
136
+ }
91
137
  /**
92
138
  * Answers a request to `/mcp/<name>`. The app's widgets (the template, and snapshots of what a
93
139
  * View reads) are its `widgets` resource, when it has one.
94
140
  */
95
- export const serveMcp = async (request, { runtime }) => {
141
+ export const serveMcp = Object.assign(async (request, { runtime }) => {
96
142
  const resources = runtime.describe().resources;
97
143
  const url = new URL(request.url);
98
144
  const name = url.pathname.slice(PATH.length).replace(/\/$/, "");
99
145
  const line = /^[\w-]{1,60}$/.test(name) ? serverOf({ resources }, name) : undefined;
100
146
  if (!line)
101
147
  return respond(404, fault(undefined, REQUEST, "No MCP server here"));
148
+ const origin = request.headers.get("origin");
149
+ const allowed = allowedOrigin(line, origin);
150
+ const { cors, preflight } = corsOf(request, allowed);
151
+ if (preflight)
152
+ return preflight;
102
153
  if (request.method !== "POST") {
103
154
  return new Response(null, {
104
155
  status: 405,
@@ -106,31 +157,30 @@ export const serveMcp = async (request, { runtime }) => {
106
157
  });
107
158
  }
108
159
  // A browser's page: only from an origin the line names (none, unless it says).
109
- const origin = request.headers.get("origin");
110
- if (origin !== null && !(line.origins ?? []).includes(origin)) {
160
+ if (origin !== null && allowed === undefined) {
111
161
  return respond(403, fault(undefined, REQUEST, "Not from this origin"));
112
162
  }
113
163
  // Around the app's front, straight to it: refused, when the front vouches for callers.
114
164
  const caller = callerFrom(request, callerOf({ resources }), line.exempt);
115
165
  if (caller === "refused") {
116
- return respond(403, fault(undefined, REQUEST, "Not through the app's front"));
166
+ return respond(403, fault(undefined, REQUEST, "Not through the app's front"), cors);
117
167
  }
118
168
  if (!/^application\/json\b/i.test(request.headers.get("content-type") ?? "")) {
119
- return respond(415, fault(undefined, REQUEST, "Send JSON (application/json)"));
169
+ return respond(415, fault(undefined, REQUEST, "Send JSON (application/json)"), cors);
120
170
  }
121
171
  const text = await bodyOf(request, line.limits.body);
122
172
  if (text === undefined)
123
- return respond(413, fault(undefined, REQUEST, "Too large"));
173
+ return respond(413, fault(undefined, REQUEST, "Too large"), cors);
124
174
  let parsed;
125
175
  try {
126
176
  parsed = JSON.parse(text);
127
177
  }
128
178
  catch {
129
- return respond(400, fault(undefined, PARSE, "Parse error"));
179
+ return respond(400, fault(undefined, PARSE, "Parse error"), cors);
130
180
  }
131
181
  const links = linksOf(resources);
132
182
  if (!links)
133
- return respond(500, fault(undefined, INTERNAL, "Internal error"));
183
+ return respond(500, fault(undefined, INTERNAL, "Internal error"), cors);
134
184
  const org = resources.org?.id;
135
185
  const context = {
136
186
  runtime,
@@ -146,13 +196,13 @@ export const serveMcp = async (request, { runtime }) => {
146
196
  // Batches were MCP's only in 2025-03-26.
147
197
  const version = request.headers.get("mcp-protocol-version") ?? UNSAID;
148
198
  if (version !== UNSAID || !parsed.length || parsed.length > BATCH) {
149
- return respond(400, fault(undefined, REQUEST, `One message a request (from 2025-03-26, ${BATCH} at most)`));
199
+ return respond(400, fault(undefined, REQUEST, `One message a request (from 2025-03-26, ${BATCH} at most)`), cors);
150
200
  }
151
201
  // More tool calls than one caller may run at once could never be served: not a busy moment.
152
202
  const calls = parsed.filter((m) => isObject(m) && m.method === "tools/call").length;
153
203
  const most = line.limits.addressAtOnce;
154
204
  if (caller && !caller.exempt && calls > most) {
155
- return respond(400, fault(undefined, REQUEST, `A batch takes at most ${most} tool calls (addressAtOnce)`));
205
+ return respond(400, fault(undefined, REQUEST, `A batch takes at most ${most} tool calls (addressAtOnce)`), cors);
156
206
  }
157
207
  const bodies = [];
158
208
  for (const message of parsed) {
@@ -164,12 +214,12 @@ export const serveMcp = async (request, { runtime }) => {
164
214
  const busyAll = bodies.length > 0 &&
165
215
  bodies.every((b) => b.error?.code === BUSY);
166
216
  return bodies.length
167
- ? respond(busyAll ? 503 : 200, bodies, busyAll ? AGAIN : {})
168
- : respond(202);
217
+ ? respond(busyAll ? 503 : 200, bodies, busyAll ? { ...AGAIN, ...cors } : cors)
218
+ : respond(202, undefined, cors);
169
219
  }
170
220
  const { status, body, again } = await answered(context, parsed, false);
171
- return respond(status, body, again ? AGAIN : {});
172
- };
221
+ return respond(status, body, again ? { ...AGAIN, ...cors } : cors);
222
+ }, { crossOrigin: true });
173
223
  /** A request's id, when it's one JSON-RPC takes. */
174
224
  const idOf = (id) => (typeof id === "string" && id.length <= 200) || Number.isSafeInteger(id) ? id : undefined;
175
225
  /** A request's body as text, or undefined past `limit` bytes. */
@@ -257,10 +307,13 @@ async function answered(c, raw, batched) {
257
307
  if (wrong)
258
308
  return failed(400, rpc, wrong.code, wrong.message);
259
309
  }
260
- const ok = (result) => ({
261
- status: 200,
262
- body: { jsonrpc: "2.0", id: rpc, result: modern ? modernOf(c.line, result) : result },
263
- });
310
+ const ok = (result, cache = false) => {
311
+ const withCache = cache && modern ? { ...result, ttlMs: TTL_MS, cacheScope: "public" } : result;
312
+ return {
313
+ status: 200,
314
+ body: { jsonrpc: "2.0", id: rpc, result: modern ? modernOf(c.line, withCache) : withCache },
315
+ };
316
+ };
264
317
  // A method it doesn't have is a 404 to a modern client (MCP 2026-07-28); else errors in the body.
265
318
  const status = (code) => !batched && modern && code === METHOD ? 404 : 200;
266
319
  try {
@@ -279,9 +332,7 @@ async function answered(c, raw, batched) {
279
332
  const template = await templateOf(c.line, c.widgets, c.origin);
280
333
  return ok({
281
334
  tools: listed(c.line, c.resources, names, c.runtime.describe().actions, template?.uri),
282
- ttlMs: TTL_MS,
283
- cacheScope: "public",
284
- });
335
+ }, true);
285
336
  }
286
337
  case "resources/list":
287
338
  case "resources/templates/list":
@@ -294,15 +345,15 @@ async function answered(c, raw, batched) {
294
345
  if (!await withWidgets(c))
295
346
  return failed(status(METHOD), rpc, METHOD, "Method not found");
296
347
  if (method === "resources/list") {
297
- return ok(await resourcesListed(c.line, c.widgets, c.origin));
348
+ return ok(await resourcesListed(c.line, c.widgets, c.origin), true);
298
349
  }
299
350
  if (method === "resources/templates/list")
300
- return ok({ resourceTemplates: [] });
351
+ return ok({ resourceTemplates: [] }, true);
301
352
  const read = await resourceRead(c.line, c.widgets, c.origin, params.uri);
302
353
  if (!read) {
303
354
  return failed(status(PARAMS), rpc, PARAMS, `No such resource: ${String(params.uri).slice(0, 200)}`);
304
355
  }
305
- return ok(read);
356
+ return ok(read, true);
306
357
  }
307
358
  case "tools/call": {
308
359
  const tool = params.name;
@@ -88,6 +88,24 @@ function mcpHintsOf(line, name, tool) {
88
88
  /** What a widget's call carries beside its input: its grant, and the reads to answer after. */
89
89
  export const GRANT = "_grant";
90
90
  export const READS = "_reads";
91
+ /** One read a widget asks for (`readsOf` in widgets.ts): a named query on a collection, keyed. */
92
+ const READ_ITEM = {
93
+ type: "object",
94
+ properties: {
95
+ key: { type: "string" },
96
+ read: {
97
+ type: "object",
98
+ properties: {
99
+ collection: { type: "string" },
100
+ query: { type: "string" },
101
+ params: { type: "object", additionalProperties: true },
102
+ },
103
+ additionalProperties: true,
104
+ },
105
+ },
106
+ required: ["key", "read"],
107
+ additionalProperties: false,
108
+ };
91
109
  /** An input as a widget's call takes it: with its grant (and, for an Action, reads to answer). */
92
110
  const forWidgets = (input, reads) => ({
93
111
  ...input,
@@ -99,7 +117,14 @@ const forWidgets = (input, reads) => ({
99
117
  },
100
118
  _call: { type: "string", description: "This call's own id: a retry of it sends the same." },
101
119
  ...(reads
102
- ? { [READS]: { type: "array", maxItems: 32, description: "Reads to answer after it." } }
120
+ ? {
121
+ [READS]: {
122
+ type: "array",
123
+ maxItems: 32,
124
+ items: READ_ITEM,
125
+ description: "Reads to answer after it.",
126
+ },
127
+ }
103
128
  : {}),
104
129
  },
105
130
  });
@@ -110,7 +135,7 @@ const readTool = () => ({
110
135
  description: "What a widget of this app reads, as its conversation: named queries only.",
111
136
  inputSchema: forWidgets({
112
137
  type: "object",
113
- properties: { reads: { type: "array", maxItems: 32 } },
138
+ properties: { reads: { type: "array", maxItems: 32, items: READ_ITEM } },
114
139
  required: ["reads"],
115
140
  }, false),
116
141
  annotations: {
@@ -129,7 +129,7 @@ export type DeclaredServer = {
129
129
  * model isn't shown the field, and nobody else gets a chat there.
130
130
  */
131
131
  handles?: boolean;
132
- /** The browser origins it answers (`Origin`): none unless said (no browser calls MCP). */
132
+ /** The browser origins it answers (`Origin`, or `"*"` for any): none unless said (no browser calls MCP). */
133
133
  origins?: string[];
134
134
  /**
135
135
  * Its widgets (with the app's `widgets` resource, `widgetsOf`): the template's options. A server
@@ -165,8 +165,9 @@ export function problemOf(name, line, resources, actions = [], views = []) {
165
165
  if (exempt)
166
166
  return exempt;
167
167
  for (const origin of line.origins ?? []) {
168
- if (!originOk(origin))
169
- return `"${origin}" isn't an origin (https://example.com)`;
168
+ if (origin !== "*" && !originOk(origin)) {
169
+ return `"${origin}" isn't an origin (https://example.com, or "*")`;
170
+ }
170
171
  }
171
172
  const domain = line.widgets?.domain;
172
173
  if (domain !== undefined &&
@@ -5,7 +5,6 @@ import { connected, send } from "../shared/number.js";
5
5
  import { mediaOf, tapOf, wordsOf } from "../shared/payload.js";
6
6
  import { MAX_FILE_BYTES } from "../shared/settings.js";
7
7
  import { may } from "../../../access/spaces/contract.js";
8
- import { CONTACT } from "../../../access/contacts/contract.js";
9
8
  import { GAP, QUIET } from "../collections/number.js";
10
9
  import { CUSTOMERS } from "../shared/customers.js";
11
10
  const HOUR = 3_600_000;
@@ -118,7 +117,7 @@ async function customer(ctx, on, received, phone, event) {
118
117
  return;
119
118
  // Answered once they've been quiet a moment: a burst of short messages gets one answer.
120
119
  const quiet = Math.round((on.number.quiet ?? QUIET) * 1000);
121
- const sending = (thread) => written(ctx, on, as, `${CONTACT}${contact}`, thread, message, {
120
+ const sending = (thread) => written(ctx, on, as, thread, message, {
122
121
  ...brings,
123
122
  ...(quiet ? { quiet } : {}),
124
123
  });
@@ -308,7 +307,7 @@ async function linked(ctx, on, { from, message }, phone, event) {
308
307
  const brings = await broughtBy(ctx, on, from, message, there);
309
308
  if (!brings)
310
309
  return;
311
- const sending = (thread) => written(ctx, on, there, person.id, thread, message, { ...brings, in: space._id });
310
+ const sending = (thread) => written(ctx, on, there, thread, message, { ...brings, in: space._id });
312
311
  try {
313
312
  await sending(phone.thread ?? await opened(ctx, on, phone, event));
314
313
  }
@@ -356,13 +355,13 @@ async function opened(ctx, on, phone, event) {
356
355
  const digest = async (text) => [...new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text)))]
357
356
  .map((b) => b.toString(16).padStart(2, "0")).join("");
358
357
  /**
359
- * Says what a message brings, as them (`as`, whom messages name `sender`),
360
- * in `thread`: as the reply to what it answers, a tap with what it meant and
358
+ * Says what a message brings, as them (`as`), in `thread`: as the reply to
359
+ * what it quotes, else what `chat.send` finds it answers, a tap with what it meant and
361
360
  * the addition it was in. "Typing…" is kept up while agents answer it (see
362
361
  * processors/typing.ts).
363
362
  */
364
- async function written(ctx, on, as, sender, thread, message, brings) {
365
- const { replyTo, key } = await answered(ctx, as, sender, thread, message);
363
+ async function written(ctx, on, as, thread, message, brings) {
364
+ const { replyTo, key } = await answered(ctx, thread, message);
366
365
  const tap = tapOf(message);
367
366
  const at = new Date().toISOString();
368
367
  await ctx.as().db.collection("whatsapp_typing").replaceOne({ _id: thread }, { number: on.number._id, wamid: message.id, at, shown: at }, { upsert: true });
@@ -375,11 +374,10 @@ async function written(ctx, on, as, sender, thread, message, brings) {
375
374
  }
376
375
  /**
377
376
  * The message this one answers: the agent's message it quotes or taps (and
378
- * the addition the tap was in), else the latest question an agent waits on
379
- * them (`sender`, as messages name them) for in this conversation (only its
380
- * messages are read, as them: what this job reads labels what it writes).
377
+ * the addition the tap was in). Else `chat.send` finds it: the question an
378
+ * agent waits on them for.
381
379
  */
382
- async function answered(ctx, as, sender, thread, message) {
380
+ async function answered(ctx, thread, message) {
383
381
  const quoted = message.context?.id;
384
382
  if (quoted) {
385
383
  // Only what went out in this chat: a quote of another answers nothing here.
@@ -388,12 +386,6 @@ async function answered(ctx, as, sender, thread, message) {
388
386
  if (sent)
389
387
  return { replyTo: sent.message, ...(sent.key ? { key: sent.key } : {}) };
390
388
  }
391
- const asked = await as.db.collection("message").find({ thread, to: sender, replyTo: { $exists: false }, expectReply: { $ne: false } }, { sort: { at: -1 }, limit: 5 });
392
- const waits = ctx.as().db.collection("wait");
393
- for (const question of asked) {
394
- if (await waits.findOne({ waitingFor: question._id }))
395
- return { replyTo: question._id };
396
- }
397
389
  return {};
398
390
  }
399
391
  /** `/new`, `/space [name]`, `/help`. */