@lace-cloud/chat-core 0.19.0 → 0.20.0

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/dist/index.d.mts CHANGED
@@ -12,7 +12,7 @@ type ToolResult = {
12
12
  isError?: boolean;
13
13
  };
14
14
 
15
- type ToolHandler<R extends ToolResult = ToolResult> = (input: Record<string, unknown>) => Promise<R>;
15
+ type ToolHandler<R extends ToolResult = ToolResult> = (input: Record<string, unknown>, signal?: AbortSignal) => Promise<R>;
16
16
  type ToolRegistration<R extends ToolResult = ToolResult> = {
17
17
  schema: ToolSchema;
18
18
  handler: ToolHandler<R>;
@@ -113,10 +113,14 @@ type DecisionReport = {
113
113
  type Transport = (path: `/api/v1/candidates/${string}`, init: {
114
114
  readonly method: 'POST';
115
115
  readonly body: unknown;
116
- }) => Promise<{
116
+ readonly signal: AbortSignal;
117
+ }) => Promise<Answered | {
118
+ readonly carried: false;
119
+ }>;
120
+ type Answered = {
117
121
  readonly status: number;
118
122
  readonly body: unknown;
119
- }>;
123
+ };
120
124
  type RankRequest = {
121
125
  readonly request: string;
122
126
  readonly statement: string;
@@ -261,4 +265,4 @@ declare function changeOutcomes(record: ChangeRecord, frames: readonly CanvasSou
261
265
 
262
266
  declare function renderCanvas(source: CanvasSource): string;
263
267
 
264
- export { type Candidate, type CandidateFacts, type CanvasEditor, type CanvasToolPorts, type CanvasTools, type ChangeOutcome, type ChangeRecord, type ChangeResult, type ChangeState, type ChangeTarget, type Composed, DECISION_KINDS, type DecisionKind, type DecisionReport, type InputBinding, type InstancePresence, type LabelledQuestion, type LabelledTurn, type ModuleToolPorts, type ModuleToolResult, type ModuleTools, NONE_CANDIDATE_ID, type Origin, type OutcomeReport, type Part, type Question, type RankRequest, type Ranked, type Readings, type Score, type Threshold, type Thresholds, type Took, type ToolHandler, type ToolRegistration, type ToolRegistry, type ToolResult, type ToolSchema, type TrainingRow, type Transport, VALUE_PLACEHOLDER, canvasToolSchemas, canvasTools, changeOutcomes, compose, createToolRegistry, moduleToolSchemas, moduleTools, partOf, renderCandidate, renderCanvas, renderRequest, sure, trainingRows };
268
+ export { type Answered, type Candidate, type CandidateFacts, type CanvasEditor, type CanvasToolPorts, type CanvasTools, type ChangeOutcome, type ChangeRecord, type ChangeResult, type ChangeState, type ChangeTarget, type Composed, DECISION_KINDS, type DecisionKind, type DecisionReport, type InputBinding, type InstancePresence, type LabelledQuestion, type LabelledTurn, type ModuleToolPorts, type ModuleToolResult, type ModuleTools, NONE_CANDIDATE_ID, type Origin, type OutcomeReport, type Part, type Question, type RankRequest, type Ranked, type Readings, type Score, type Threshold, type Thresholds, type Took, type ToolHandler, type ToolRegistration, type ToolRegistry, type ToolResult, type ToolSchema, type TrainingRow, type Transport, VALUE_PLACEHOLDER, canvasToolSchemas, canvasTools, changeOutcomes, compose, createToolRegistry, moduleToolSchemas, moduleTools, partOf, renderCandidate, renderCanvas, renderRequest, sure, trainingRows };
package/dist/index.d.ts CHANGED
@@ -12,7 +12,7 @@ type ToolResult = {
12
12
  isError?: boolean;
13
13
  };
14
14
 
15
- type ToolHandler<R extends ToolResult = ToolResult> = (input: Record<string, unknown>) => Promise<R>;
15
+ type ToolHandler<R extends ToolResult = ToolResult> = (input: Record<string, unknown>, signal?: AbortSignal) => Promise<R>;
16
16
  type ToolRegistration<R extends ToolResult = ToolResult> = {
17
17
  schema: ToolSchema;
18
18
  handler: ToolHandler<R>;
@@ -113,10 +113,14 @@ type DecisionReport = {
113
113
  type Transport = (path: `/api/v1/candidates/${string}`, init: {
114
114
  readonly method: 'POST';
115
115
  readonly body: unknown;
116
- }) => Promise<{
116
+ readonly signal: AbortSignal;
117
+ }) => Promise<Answered | {
118
+ readonly carried: false;
119
+ }>;
120
+ type Answered = {
117
121
  readonly status: number;
118
122
  readonly body: unknown;
119
- }>;
123
+ };
120
124
  type RankRequest = {
121
125
  readonly request: string;
122
126
  readonly statement: string;
@@ -261,4 +265,4 @@ declare function changeOutcomes(record: ChangeRecord, frames: readonly CanvasSou
261
265
 
262
266
  declare function renderCanvas(source: CanvasSource): string;
263
267
 
264
- export { type Candidate, type CandidateFacts, type CanvasEditor, type CanvasToolPorts, type CanvasTools, type ChangeOutcome, type ChangeRecord, type ChangeResult, type ChangeState, type ChangeTarget, type Composed, DECISION_KINDS, type DecisionKind, type DecisionReport, type InputBinding, type InstancePresence, type LabelledQuestion, type LabelledTurn, type ModuleToolPorts, type ModuleToolResult, type ModuleTools, NONE_CANDIDATE_ID, type Origin, type OutcomeReport, type Part, type Question, type RankRequest, type Ranked, type Readings, type Score, type Threshold, type Thresholds, type Took, type ToolHandler, type ToolRegistration, type ToolRegistry, type ToolResult, type ToolSchema, type TrainingRow, type Transport, VALUE_PLACEHOLDER, canvasToolSchemas, canvasTools, changeOutcomes, compose, createToolRegistry, moduleToolSchemas, moduleTools, partOf, renderCandidate, renderCanvas, renderRequest, sure, trainingRows };
268
+ export { type Answered, type Candidate, type CandidateFacts, type CanvasEditor, type CanvasToolPorts, type CanvasTools, type ChangeOutcome, type ChangeRecord, type ChangeResult, type ChangeState, type ChangeTarget, type Composed, DECISION_KINDS, type DecisionKind, type DecisionReport, type InputBinding, type InstancePresence, type LabelledQuestion, type LabelledTurn, type ModuleToolPorts, type ModuleToolResult, type ModuleTools, NONE_CANDIDATE_ID, type Origin, type OutcomeReport, type Part, type Question, type RankRequest, type Ranked, type Readings, type Score, type Threshold, type Thresholds, type Took, type ToolHandler, type ToolRegistration, type ToolRegistry, type ToolResult, type ToolSchema, type TrainingRow, type Transport, VALUE_PLACEHOLDER, canvasToolSchemas, canvasTools, changeOutcomes, compose, createToolRegistry, moduleToolSchemas, moduleTools, partOf, renderCandidate, renderCanvas, renderRequest, sure, trainingRows };
package/dist/index.mjs CHANGED
@@ -237,9 +237,35 @@ function trainingRows(turn, part) {
237
237
  }));
238
238
  }
239
239
 
240
+ // src/contract/cancel.ts
241
+ var Cancelled = class extends Error {
242
+ constructor() {
243
+ super("the call was cancelled");
244
+ }
245
+ };
246
+ function stopIfCancelled(signal) {
247
+ if (signal?.aborted) throw new Cancelled();
248
+ }
249
+ function untilCancelled(work, signal) {
250
+ if (signal === void 0) return work;
251
+ let stop = () => {
252
+ };
253
+ const cancelled = new Promise((_, fail) => {
254
+ stop = () => fail(new Cancelled());
255
+ if (signal.aborted) stop();
256
+ else signal.addEventListener("abort", stop, { once: true });
257
+ });
258
+ return Promise.race([work, cancelled]).finally(() => signal.removeEventListener("abort", stop));
259
+ }
260
+ function cancellable(start, signal) {
261
+ if (signal?.aborted) return Promise.reject(new Cancelled());
262
+ return untilCancelled(start(), signal);
263
+ }
264
+
240
265
  // src/ranking/client.ts
241
266
  var RANK_PATH = "/api/v1/candidates/rank";
242
267
  var DECISIONS_PATH = "/api/v1/candidates/decisions";
268
+ var RANKING_CALL_TIMEOUT_MS = 12e3;
243
269
  var RankingUnavailable = class extends Error {
244
270
  };
245
271
  function isRecord(value) {
@@ -264,21 +290,60 @@ function rankedOf(body) {
264
290
  const thresholds = thresholdsOf(body.thresholds);
265
291
  return typeof body.capture_id === "string" && typeof body.head === "string" && scores.every((score) => score !== void 0) && thresholds !== void 0 ? { capture_id: body.capture_id, head: body.head, scores, thresholds } : void 0;
266
292
  }
293
+ var NotCarried = class extends Error {
294
+ };
295
+ function answerOf(answer) {
296
+ if (!isRecord(answer)) return "failed";
297
+ if (answer.carried === false) return "uncarried";
298
+ return typeof answer.status === "number" ? { status: answer.status, body: answer.body } : "failed";
299
+ }
300
+ var NO_ANSWER = { failed: "the request failed", unanswered: "no answer from Lace" };
267
301
  function rankingClient(transport) {
268
- const post = (path, body) => transport(path, { method: "POST", body }).catch(() => ({ status: 0, body: void 0 }));
302
+ const post = (path, body, cancel) => {
303
+ if (cancel?.aborted) return Promise.resolve("cancelled");
304
+ const controller = new AbortController();
305
+ const reply = new Promise(
306
+ (made) => made(transport(path, { method: "POST", body, signal: controller.signal }))
307
+ ).then(answerOf).catch(() => "failed");
308
+ let timer;
309
+ const unanswered = new Promise((settle) => {
310
+ timer = setTimeout(() => settle("unanswered"), RANKING_CALL_TIMEOUT_MS);
311
+ });
312
+ return untilCancelled(Promise.race([reply, unanswered]), cancel).catch(() => "cancelled").then((ended) => {
313
+ if (ended === "unanswered" || ended === "cancelled") controller.abort();
314
+ return ended;
315
+ }).finally(() => clearTimeout(timer));
316
+ };
269
317
  return {
270
- async rank(request) {
271
- const { status, body } = await post(RANK_PATH, request);
272
- const ranked = status === 200 ? rankedOf(body) : void 0;
273
- if (ranked === void 0) {
274
- throw new RankingUnavailable(
275
- status === 200 ? "the ranking service answered with no ranking" : `status ${status}`
276
- );
277
- }
278
- return ranked;
279
- },
280
- async decision(report) {
281
- await post(DECISIONS_PATH, report);
318
+ changeCall(cancel) {
319
+ let ended;
320
+ const send = (path, body, signal) => {
321
+ if (ended !== void 0) return { made: false, reply: Promise.resolve(ended) };
322
+ const reply = post(path, body, signal).then((answer) => {
323
+ if (answer === "failed" || answer === "unanswered" || answer === "uncarried") {
324
+ ended = answer;
325
+ }
326
+ return answer;
327
+ });
328
+ return { made: true, reply };
329
+ };
330
+ return {
331
+ async rank(request) {
332
+ const reply = await send(RANK_PATH, request, cancel).reply;
333
+ if (reply === "cancelled") throw new Cancelled();
334
+ if (reply === "uncarried") throw new NotCarried("the host carried nothing");
335
+ if (typeof reply === "string") throw new RankingUnavailable(NO_ANSWER[reply]);
336
+ const ranked = reply.status === 200 ? rankedOf(reply.body) : void 0;
337
+ if (ranked !== void 0) return ranked;
338
+ throw new RankingUnavailable(
339
+ reply.status === 200 ? "the ranking service answered with no ranking" : `status ${reply.status}`
340
+ );
341
+ },
342
+ decision(report) {
343
+ const { made, reply } = send(DECISIONS_PATH, report);
344
+ return { made, settled: reply.then(() => void 0) };
345
+ }
346
+ };
282
347
  },
283
348
  async outcome(decision, outcome) {
284
349
  await post(`${DECISIONS_PATH}/${encodeURIComponent(decision)}/outcomes`, outcome);
@@ -515,9 +580,9 @@ function errorText(error) {
515
580
  function registrationOf(schema, run, failed) {
516
581
  return {
517
582
  schema,
518
- async handler(input) {
583
+ async handler(input, signal) {
519
584
  try {
520
- return await run(input);
585
+ return await run(input, signal);
521
586
  } catch (error) {
522
587
  return failed({ content: errorText(error), isError: true });
523
588
  }
@@ -546,10 +611,10 @@ function commandEnd(path, error) {
546
611
  text: `lace ${path} did not finish cleanly (exit ${error.code}: ${error.stderrTail})`
547
612
  };
548
613
  }
549
- async function runCommand(commands, path, args) {
614
+ async function runCommand(commands, path, args, signal = new AbortController().signal) {
550
615
  const documents = [];
551
616
  try {
552
- for await (const document of commands.invoke(path, args, new AbortController().signal).events) {
617
+ for await (const document of commands.invoke(path, args, signal).events) {
553
618
  documents.push(document);
554
619
  }
555
620
  } catch (error) {
@@ -990,7 +1055,7 @@ function read(options, reading) {
990
1055
  (option) => statedSlots(option.slots).every((slot) => reading[slot] === option.slots[slot])
991
1056
  );
992
1057
  }
993
- function answerOf(options, reading) {
1058
+ function answerOf2(options, reading) {
994
1059
  const named2 = read(options, reading);
995
1060
  return named2.length === 1 ? named2[0] : void 0;
996
1061
  }
@@ -1030,14 +1095,15 @@ async function rankWithin(rank, request, statement, kind, candidates) {
1030
1095
  if (holding === void 0) throw new Error("the ranking names no candidate of the set");
1031
1096
  return holding;
1032
1097
  }
1098
+ var NOT_RANKED = { ranked: null, failed: "Lace did not rank" };
1033
1099
  async function ranking(ask, statement, kind, candidates) {
1034
- if (ask.rank === void 0) {
1035
- return { ranking: { ranked: null, failed: "Lace did not rank" }, part: candidates };
1036
- }
1100
+ if (ask.rank === void 0) return { ranking: NOT_RANKED, part: candidates };
1037
1101
  try {
1038
1102
  const { part, ranked } = await rankWithin(ask.rank, ask.request, statement, kind, candidates);
1039
1103
  return { ranking: { ranked, parts: part.length < candidates.length }, part };
1040
1104
  } catch (error) {
1105
+ if (error instanceof Cancelled) throw error;
1106
+ if (error instanceof NotCarried) return { ranking: NOT_RANKED, part: candidates };
1041
1107
  const failed = `Lace could not rank: ${error instanceof Error ? error.message : String(error)}`;
1042
1108
  return { ranking: { ranked: null, failed }, part: candidates };
1043
1109
  }
@@ -1046,7 +1112,7 @@ var asAsked = (ranking2) => ranking2 === null || ranking2.ranked === null || ran
1046
1112
  async function twoSystems(ask, kind, label, options, stated) {
1047
1113
  const candidates = options.map((option2) => option2.candidate);
1048
1114
  const readings = options.map((option2) => option2.slots);
1049
- const chat = stated === void 0 ? answerOf(options, ask.reading) : options.find((option2) => option2.value === stated);
1115
+ const chat = stated === void 0 ? answerOf2(options, ask.reading) : options.find((option2) => option2.value === stated);
1050
1116
  const read2 = await ranking(ask, ask.statement, kind, candidates);
1051
1117
  const composed = compose({
1052
1118
  kind,
@@ -1094,7 +1160,7 @@ function byName(ask, kind, label, options) {
1094
1160
  candidates: options.map((each) => each.candidate),
1095
1161
  facts: options.map((each) => each.facts),
1096
1162
  others: hits.filter((hit) => hit.option !== option).map((hit) => hit.option.candidate.id),
1097
- chat: answerOf(options, ask.reading)?.candidate.id ?? null,
1163
+ chat: answerOf2(options, ask.reading)?.candidate.id ?? null,
1098
1164
  ranking: null,
1099
1165
  composed: null,
1100
1166
  over: [],
@@ -1212,13 +1278,17 @@ var CATALOG_LIMIT = 500;
1212
1278
  var place = {
1213
1279
  id: "place",
1214
1280
  takesValue: false,
1215
- async plan({ canvas, request, ports, pick, note }) {
1281
+ async plan({ canvas, request, ports, signal, pick, note }) {
1216
1282
  const [query] = moduleReferences(request).map((reference) => reference.split("/").slice(-1)[0]);
1217
- const listing = await runCommand(ports.commands, "registry list", {
1218
- axis: "module",
1219
- limit: CATALOG_LIMIT,
1220
- query
1221
- });
1283
+ const listing = await cancellable(
1284
+ () => runCommand(
1285
+ ports.commands,
1286
+ "registry list",
1287
+ { axis: "module", limit: CATALOG_LIMIT, query },
1288
+ signal
1289
+ ),
1290
+ signal
1291
+ );
1222
1292
  if (listing.failed !== void 0) throw new Error(listing.failed.text);
1223
1293
  for (const document of listing.documents) {
1224
1294
  if (document.truncated) {
@@ -1244,18 +1314,21 @@ var place = {
1244
1314
  var connect = {
1245
1315
  id: "connect",
1246
1316
  takesValue: false,
1247
- async plan({ canvas, ports, pick }) {
1317
+ async plan({ canvas, ports, signal, pick }) {
1248
1318
  const source = await pick("instance", "source instance", sourceOptions(canvas.instances));
1249
1319
  const target = await pick(
1250
1320
  "instance",
1251
1321
  "target instance",
1252
1322
  targetOptions(canvas.instances, source)
1253
1323
  );
1254
- const scored = await ports.editor.wiringCandidates({
1255
- scope: source.scope,
1256
- source: source.name,
1257
- target: target.name
1258
- });
1324
+ const scored = await cancellable(
1325
+ () => ports.editor.wiringCandidates({
1326
+ scope: source.scope,
1327
+ source: source.name,
1328
+ target: target.name
1329
+ }),
1330
+ signal
1331
+ );
1259
1332
  const pair = await pick("connection", "connection", connectionOptions(source, target, scored));
1260
1333
  return {
1261
1334
  action: {
@@ -1381,6 +1454,7 @@ var OPERATIONS = [
1381
1454
  remove,
1382
1455
  ungroup
1383
1456
  ];
1457
+ var CANCELLED = { kind: "cancelled" };
1384
1458
  var Fell = class extends Error {
1385
1459
  constructor(label) {
1386
1460
  super(`the ${label} fell to System Two`);
@@ -1407,7 +1481,7 @@ function statedFacts(names2, reading) {
1407
1481
  );
1408
1482
  }
1409
1483
  var asItIs = (apply) => apply();
1410
- async function resolveAndApply(ports, own, change, call, trail, notApplied) {
1484
+ async function resolveAndApply(ports, own, change, call, client, signal, trail, notApplied) {
1411
1485
  const canvas = readCanvas(await latest(ports.source));
1412
1486
  const names2 = canvasNames(canvas);
1413
1487
  const values = [...forms(change.values), ...unnamed(names2, call)];
@@ -1421,12 +1495,7 @@ async function resolveAndApply(ports, own, change, call, trail, notApplied) {
1421
1495
  statements.reduce((longest, each) => each.length > longest.length ? each : longest)
1422
1496
  );
1423
1497
  const rankable = !holdsValue(withhold([request, ...statements].join(" "), [...names2]), values);
1424
- const rank = ports.transport === void 0 ? void 0 : rankingClient(ports.transport).rank;
1425
- if (!rankable && rank !== void 0) {
1426
- trail.notes.push(
1427
- "This change's words or reading hold a value of the call inside a word, so Lace did not rank it."
1428
- );
1429
- }
1498
+ const rank = client?.rank;
1430
1499
  const main = {
1431
1500
  request,
1432
1501
  terms: termsOf(request.split(VALUE_PLACEHOLDER).join(" ")),
@@ -1435,13 +1504,18 @@ async function resolveAndApply(ports, own, change, call, trail, notApplied) {
1435
1504
  ...rankable ? { rank } : {}
1436
1505
  };
1437
1506
  const ask = { ...main, ...alternative === void 0 ? {} : { alternative } };
1507
+ const decided2 = (on, kind, label, options, stated2) => {
1508
+ stopIfCancelled(signal);
1509
+ return decide(on, kind, label, options, stated2);
1510
+ };
1438
1511
  const resolvingInto = (into, trial) => ({
1439
1512
  canvas,
1440
1513
  request,
1441
1514
  values: change.values,
1442
1515
  ports,
1516
+ signal,
1443
1517
  async pick(kind, label, options) {
1444
- const decision = await decide(ask, kind, label, options);
1518
+ const decision = await decided2(ask, kind, label, options);
1445
1519
  into.decisions.push(decision);
1446
1520
  if (trial && !moveStands(composedOf(into.decisions.slice(1)))) throw new Fell(label);
1447
1521
  return decision.option.value;
@@ -1452,7 +1526,7 @@ async function resolveAndApply(ports, own, change, call, trail, notApplied) {
1452
1526
  into.decisions.push(decision);
1453
1527
  return decision.option.value.plan(resolvingInto(into, trial));
1454
1528
  };
1455
- const first = await decide(ask, "operation", "operation", operationOptions(OPERATIONS));
1529
+ const first = await decided2(ask, "operation", "operation", operationOptions(OPERATIONS));
1456
1530
  const statedOperation = operationOptions(OPERATIONS).find(
1457
1531
  (each) => each.candidate.id === first.chat
1458
1532
  );
@@ -1467,6 +1541,7 @@ async function resolveAndApply(ports, own, change, call, trail, notApplied) {
1467
1541
  trail.notes.push(...trial.notes);
1468
1542
  return { operation: first.option.value, plan: planned };
1469
1543
  } catch (error) {
1544
+ stopIfCancelled(signal);
1470
1545
  trail.moved = withhold(movedText(first.option.value.id, error), change.values);
1471
1546
  const standing = {
1472
1547
  ...first,
@@ -1486,9 +1561,8 @@ async function resolveAndApply(ports, own, change, call, trail, notApplied) {
1486
1561
  const { operation, plan } = await moveRule();
1487
1562
  const unread = trail.decisions.every((decision) => decision.others.length === 0);
1488
1563
  if (unread && main.rank !== void 0 && trail.decisions.some(twoSystems2)) {
1489
- await decide(main, "steps", "steps", stepsOptions(), "one").then(
1490
- (decision) => trail.decisions.push(decision)
1491
- );
1564
+ const steps = await decided2(main, "steps", "steps", stepsOptions(), "one");
1565
+ if (steps.ranking !== NOT_RANKED) trail.decisions.push(steps);
1492
1566
  }
1493
1567
  if (change.values.length > 0 && !operation.takesValue && !heldMore(trail.decisions)) {
1494
1568
  trail.notes.push(
@@ -1521,6 +1595,7 @@ async function resolveAndApply(ports, own, change, call, trail, notApplied) {
1521
1595
  )
1522
1596
  };
1523
1597
  }
1598
+ stopIfCancelled(signal);
1524
1599
  const result = await own(() => ports.editor.apply([plan.action]));
1525
1600
  if (!result.success) {
1526
1601
  const reasons = result.errors.map((error) => error.message).join("; ");
@@ -1547,17 +1622,18 @@ async function resolveAndApply(ports, own, change, call, trail, notApplied) {
1547
1622
  withheld: unnamed(names2, call)
1548
1623
  };
1549
1624
  }
1550
- async function runChange(ports, own, change, call, trail) {
1625
+ async function runChange(ports, own, change, call, client, signal, trail) {
1551
1626
  const notApplied = (why) => ({
1552
1627
  kind: "notApplied",
1553
1628
  why: withhold(why, change.values)
1554
1629
  });
1555
1630
  try {
1556
- return await resolveAndApply(ports, own, change, call, trail, notApplied);
1631
+ return await resolveAndApply(ports, own, change, call, client, signal, trail, notApplied);
1557
1632
  } catch (error) {
1558
1633
  if (error instanceof ApplyUnobservedError) {
1559
1634
  return { kind: "unobserved", end: withhold(endText(error.end), change.values) };
1560
1635
  }
1636
+ if (error instanceof Cancelled) return CANCELLED;
1561
1637
  if (error instanceof Undecided) {
1562
1638
  trail.undecided = error;
1563
1639
  const candidates = error.candidates.map((candidate) => candidate.id).join(", ");
@@ -1618,6 +1694,8 @@ function outcomeLines(number, outcome, trail) {
1618
1694
  ];
1619
1695
  case "notApplied":
1620
1696
  return [`${head} not applied. Reason: ${outcome.why}`, ...lines];
1697
+ case "cancelled":
1698
+ return [`${head} not applied. The call was cancelled before it applied.`];
1621
1699
  case "unobserved":
1622
1700
  return [
1623
1701
  `${head} sent, and the engine answered it, but the session's stream ended (${outcome.end}) before the canvas showed it, so whether it applied cannot be read here. Do not send it again before the canvas is open again.`,
@@ -1655,19 +1733,19 @@ function reportOf(id, trail, applied, asked) {
1655
1733
  ];
1656
1734
  return questions.some((question) => question.took !== "named") ? { id, surface: "canvas", questions, applied, asked } : void 0;
1657
1735
  }
1658
- async function applyChanges(ports, changes, own = asItIs) {
1736
+ async function applyChanges(ports, changes, own = asItIs, signal) {
1659
1737
  const call = changes.flatMap((change) => change.values);
1660
- const client = ports.transport === void 0 ? void 0 : rankingClient(ports.transport);
1738
+ const client = ports.transport === void 0 ? void 0 : rankingClient(ports.transport).changeCall(signal);
1661
1739
  const lines = [];
1662
1740
  let applied = [];
1663
- const reports = [];
1741
+ const unapplied = [];
1664
1742
  let last;
1665
1743
  for (const [index, change] of changes.entries()) {
1666
1744
  const trail = { decisions: [], notes: [] };
1667
- const outcome = await runChange(ports, own, change, call, trail);
1745
+ const outcome = signal?.aborted ? CANCELLED : await runChange(ports, own, change, call, client, signal, trail);
1668
1746
  lines.push(
1669
1747
  ...outcomeLines(index + 1, outcome, trail),
1670
- ...trail.notes.map((line) => ` ${line}`)
1748
+ ...outcome.kind === "cancelled" ? [] : trail.notes.map((line) => ` ${line}`)
1671
1749
  );
1672
1750
  if (outcome.kind === "applied") {
1673
1751
  const { canvas } = outcome;
@@ -1677,19 +1755,32 @@ async function applyChanges(ports, changes, own = asItIs) {
1677
1755
  { record: outcome.record, withheld: outcome.withheld, trail }
1678
1756
  ];
1679
1757
  last = canvas;
1680
- } else if (outcome.kind !== "unobserved") {
1758
+ } else if (outcome.kind !== "unobserved" && outcome.kind !== "cancelled") {
1681
1759
  const report = reportOf(crypto.randomUUID(), trail, null, outcome.kind === "asked");
1682
- if (report !== void 0) reports.push(report);
1760
+ if (report !== void 0) unapplied.push(report);
1683
1761
  }
1684
1762
  }
1685
1763
  const left = last;
1686
- const records = left === void 0 ? [] : applied.map(({ record, withheld, trail }) => {
1687
- const settled = { ...record, after: targetState(left, record) };
1688
- const report = reportOf(record.id, trail, appliedText(settled, withheld), false);
1689
- if (report !== void 0) reports.push(report);
1690
- return { ...settled, reported: report !== void 0 && client !== void 0 };
1764
+ const settled = left === void 0 ? [] : applied.map(({ record, withheld, trail }) => {
1765
+ const standing = { ...record, after: targetState(left, record) };
1766
+ const report = reportOf(record.id, trail, appliedText(standing, withheld), false);
1767
+ return { record: standing, report };
1691
1768
  });
1692
- if (client !== void 0) await Promise.all(reports.map((report) => client.decision(report)));
1769
+ const reports = [
1770
+ ...signal?.aborted ? [] : unapplied,
1771
+ ...settled.flatMap(({ report }) => report === void 0 ? [] : [report])
1772
+ ];
1773
+ const sent = client === void 0 ? [] : reports.map((report) => ({ report, ...client.decision(report) }));
1774
+ const made = new Set(sent.flatMap(({ report, made: made2 }) => made2 ? [report] : []));
1775
+ try {
1776
+ await untilCancelled(Promise.all(sent.map(({ settled: settled2 }) => settled2)), signal);
1777
+ } catch (error) {
1778
+ if (!(error instanceof Cancelled)) throw error;
1779
+ }
1780
+ const records = settled.map(({ record, report }) => ({
1781
+ ...record,
1782
+ reported: report !== void 0 && made.has(report)
1783
+ }));
1693
1784
  return { text: lines.join("\n"), applied: records };
1694
1785
  }
1695
1786
  function appliedText(record, withheld) {
@@ -1821,6 +1912,12 @@ function unobserved(error) {
1821
1912
  isError: false
1822
1913
  };
1823
1914
  }
1915
+ function cancelledSaid(operation, sent) {
1916
+ return {
1917
+ text: sent ? `The call was cancelled after the ${operation} was sent: it goes on in the engine, and the canvas below may be from before it ends.` : `The call was cancelled before the ${operation} was sent: nothing was done.`,
1918
+ isError: false
1919
+ };
1920
+ }
1824
1921
  var NO_RECORDS = { applied: [] };
1825
1922
  function canvasTools(ports) {
1826
1923
  const [change, describe, save, generate] = canvasToolSchemas;
@@ -1840,9 +1937,14 @@ function canvasTools(ports) {
1840
1937
  const registrations = [
1841
1938
  registrationOf(
1842
1939
  change,
1843
- async (input) => {
1940
+ async (input, signal) => {
1844
1941
  try {
1845
- const { text: text2, applied } = await applyChanges(ports, parseChanges(input), observer?.own);
1942
+ const { text: text2, applied } = await applyChanges(
1943
+ ports,
1944
+ parseChanges(input),
1945
+ observer?.own,
1946
+ signal
1947
+ );
1846
1948
  observer?.follow(applied);
1847
1949
  return { ...await answer([{ text: text2, isError: false }]), applied };
1848
1950
  } catch (error) {
@@ -1855,13 +1957,15 @@ function canvasTools(ports) {
1855
1957
  registration(describe, () => answer([])),
1856
1958
  registration(
1857
1959
  save,
1858
- async () => answer(
1960
+ async (_input, signal) => answer(
1859
1961
  await attempt(async () => {
1962
+ if (signal?.aborted) return [cancelledSaid("save", false)];
1860
1963
  const saved = { text: "Saved the canvas.", isError: false };
1861
1964
  try {
1862
- await ports.editor.save();
1965
+ await untilCancelled(ports.editor.save(), signal);
1863
1966
  return [saved];
1864
1967
  } catch (error) {
1968
+ if (error instanceof Cancelled) return [cancelledSaid("save", true)];
1865
1969
  return [saved, unobserved(error)];
1866
1970
  }
1867
1971
  })
@@ -1869,12 +1973,17 @@ function canvasTools(ports) {
1869
1973
  ),
1870
1974
  registration(
1871
1975
  generate,
1872
- async () => answer(
1976
+ async (_input, signal) => answer(
1873
1977
  await attempt(async () => {
1978
+ if (signal?.aborted) return [cancelledSaid("Generate", false)];
1874
1979
  const said2 = [];
1980
+ const events = ports.editor.generate()[Symbol.asyncIterator]();
1875
1981
  try {
1876
- for await (const event of ports.editor.generate()) said2.push(...generateSaid(event));
1982
+ for (let next = await untilCancelled(events.next(), signal); next.done !== true; next = await untilCancelled(events.next(), signal)) {
1983
+ said2.push(...generateSaid(next.value));
1984
+ }
1877
1985
  } catch (error) {
1986
+ if (error instanceof Cancelled) return [...said2, cancelledSaid("Generate", true)];
1878
1987
  said2.push(unobserved(error));
1879
1988
  }
1880
1989
  return said2;
@@ -1944,28 +2053,35 @@ function moduleTools({ commands }) {
1944
2053
  return [
1945
2054
  moduleTool(
1946
2055
  validate,
1947
- async () => said(await runCommand(commands, "module validate", {}), trimValidate)
2056
+ async (_input, signal) => said(await runCommand(commands, "module validate", {}, signal), trimValidate)
1948
2057
  ),
1949
2058
  moduleTool(
1950
2059
  search,
1951
- async (input) => said(
1952
- await runCommand(commands, "registry list", {
1953
- axis: "module",
1954
- query: text(input.query),
1955
- system: text(input.system),
1956
- category: text(input.category)
1957
- }),
2060
+ async (input, signal) => said(
2061
+ await runCommand(
2062
+ commands,
2063
+ "registry list",
2064
+ {
2065
+ axis: "module",
2066
+ query: text(input.query),
2067
+ system: text(input.system),
2068
+ category: text(input.category)
2069
+ },
2070
+ signal
2071
+ ),
1958
2072
  trimRegistryList
1959
2073
  )
1960
2074
  ),
1961
- moduleTool(describe, async (input) => {
2075
+ moduleTool(describe, async (input, signal) => {
1962
2076
  const module = text(input.module);
1963
2077
  if (module === void 0) throw new InvalidInput("`module` is the module as `author/name`");
1964
2078
  return said(
1965
- await runCommand(commands, "registry describe", {
1966
- artifact: `module/${module}`,
1967
- version: text(input.version)
1968
- }),
2079
+ await runCommand(
2080
+ commands,
2081
+ "registry describe",
2082
+ { artifact: `module/${module}`, version: text(input.version) },
2083
+ signal
2084
+ ),
1969
2085
  trimRegistryDescribe
1970
2086
  );
1971
2087
  })