@lace-cloud/chat-core 0.19.0 → 0.21.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.cjs CHANGED
@@ -20,22 +20,12 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/index.ts
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
- DECISION_KINDS: () => DECISION_KINDS,
24
- NONE_CANDIDATE_ID: () => NONE_CANDIDATE_ID,
25
- VALUE_PLACEHOLDER: () => VALUE_PLACEHOLDER,
26
23
  canvasToolSchemas: () => canvasToolSchemas,
27
24
  canvasTools: () => canvasTools,
28
- changeOutcomes: () => changeOutcomes,
29
- compose: () => compose,
30
25
  createToolRegistry: () => createToolRegistry,
31
26
  moduleToolSchemas: () => moduleToolSchemas,
32
27
  moduleTools: () => moduleTools,
33
- partOf: () => partOf,
34
- renderCandidate: () => renderCandidate,
35
- renderCanvas: () => renderCanvas,
36
- renderRequest: () => renderRequest,
37
- sure: () => sure,
38
- trainingRows: () => trainingRows
28
+ renderCanvas: () => renderCanvas
39
29
  });
40
30
  module.exports = __toCommonJS(index_exports);
41
31
 
@@ -58,302 +48,36 @@ function createToolRegistry() {
58
48
  };
59
49
  }
60
50
 
61
- // src/questions/bounds.ts
62
- var RANK_CANDIDATES_MAX = 256;
63
- var RANK_REQUEST_MAX_CHARS = 4e3;
64
- var RANK_CANDIDATE_TEXT_MAX_CHARS = 2e3;
65
-
66
- // src/questions/types.ts
67
- var DECISION_KINDS = [
68
- "operation",
69
- "instance",
70
- "input",
71
- "module",
72
- "connection",
73
- "steps"
74
- ];
75
- var NONE_CANDIDATE_ID = "(none)";
76
-
77
- // src/questions/candidate.ts
78
- function pinRef(instance, pin) {
79
- return `${instance}.${pin}`;
80
- }
81
- function connectionId(from, to) {
82
- return `${from} \u2192 ${to}`;
83
- }
84
- var OPERATION_TEXT = {
85
- place: "place: add a registry module to the canvas as a new instance",
86
- connect: "connect: wire an output of one instance into an input of another",
87
- disconnect: "disconnect: remove the wire into an instance's input",
88
- set: "set: give an input of an instance a literal value",
89
- bind: "bind: make an input of an instance take its value from a variable of the module (`var.<name>`), so the module's caller sets it",
90
- clear: "clear: unset an input of an instance, removing the value, variable or expression it holds",
91
- rename: "rename: give an instance a new name",
92
- delete: "delete: remove an instance from the canvas",
93
- ungroup: "ungroup: dissolve a group, moving the instances inside it up beside it"
94
- };
95
- var STEPS_TEXT = {
96
- one: "one change: the request asks for a single change to the canvas",
97
- several: "several changes: the request asks for more than one change to the canvas"
98
- };
99
- var NONE_TEXT = {
100
- operation: "asks for no change these operations make",
101
- instance: "means no instance on this canvas",
102
- input: "means no input of this instance",
103
- module: "means no module of this registry listing",
104
- connection: "means no wire between these two instances"
105
- };
106
- function noneCandidate(kind) {
107
- return { id: NONE_CANDIDATE_ID, kind, text: `none of these: the request ${NONE_TEXT[kind]}` };
108
- }
109
- function rankCandidates(kind, candidates) {
110
- return kind === "steps" ? [...candidates] : [...candidates, noneCandidate(kind)];
111
- }
112
- var CUT_MARK = "\u2026";
113
- function shortened(text2, limit) {
114
- if (text2.length <= limit) return text2;
115
- const room = text2.slice(0, Math.max(limit - CUT_MARK.length + 1, 0));
116
- const end = room.search(/\s+\S*$/);
117
- const kept = end === -1 ? "" : room.slice(0, end).trimEnd();
118
- return kept === "" ? "" : `${kept}${CUT_MARK}`;
119
- }
120
- var WHOLE = { prose: Number.POSITIVE_INFINITY, names: Number.POSITIVE_INFINITY };
121
- function prose(text2, cut) {
122
- const kept = shortened(text2, cut.prose);
123
- return kept === "" && text2 !== "" ? void 0 : kept;
124
- }
125
- function listed(items, cut, render) {
126
- const kept = items.slice(0, cut.names).map(render);
127
- const more = items.length - kept.length;
128
- return [...kept, ...more > 0 ? [`and ${more} more`] : []].join(", ");
129
- }
130
- function worded(table, what, id) {
131
- const text2 = table[id];
132
- if (text2 === void 0) throw new Error(`no ${what} is named ${id}`);
133
- return text2;
134
- }
135
- var about = (instance, module2) => `instance ${instance} of module ${module2}`;
136
- var names = (pins, cut) => listed(pins, cut, (pin) => pin.name);
137
- var described = (pins, cut) => listed(pins, cut, (pin) => {
138
- const description = pin.description === void 0 ? void 0 : prose(pin.description, cut);
139
- return description === void 0 ? pin.name : `${pin.name} (${description})`;
140
- });
141
- var INSTANCE_TEXT = {
142
- instance: (f, cut) => `${about(f.id, f.module)}; inputs: ${described(f.inputs, cut)}; outputs: ${described(f.outputs, cut)}`,
143
- source: (f, cut) => `the wire starts at an output of ${about(f.id, f.module)}; its outputs: ${names(f.outputs, cut)}`,
144
- target: (f, cut) => `the wire ends at an input of ${about(f.id, f.module)}; its inputs no wire feeds: ${names(f.inputs, cut)}`
145
- };
146
- function textOf(facts, cut) {
147
- switch (facts.kind) {
148
- case "operation":
149
- return worded(OPERATION_TEXT, "operation", facts.id);
150
- case "steps":
151
- return worded(STEPS_TEXT, "reading of the steps", facts.id);
152
- case "instance":
153
- return INSTANCE_TEXT[facts.role](facts, cut);
154
- case "input": {
155
- const type = prose(facts.type, cut);
156
- return [
157
- `input ${facts.id} of ${about(facts.instance, facts.module)}`,
158
- type === void 0 ? void 0 : `type ${type}`,
159
- facts.required ? "required" : "optional",
160
- facts.state,
161
- facts.description === void 0 ? void 0 : prose(facts.description, cut)
162
- ].filter((part) => part !== void 0).join("; ");
163
- }
164
- case "module":
165
- return `registry module ${facts.id} (${facts.displayName}): ${prose(facts.description, cut) ?? ""}; system ${facts.system}; categories: ${listed(facts.categories, cut, (category) => category)}`;
166
- case "connection": {
167
- const scored = facts.score === void 0 ? "the engine's matcher gives this pair no score" : `the engine's matcher scores this pair ${facts.score}`;
168
- return `wire output ${pinRef(facts.source, facts.output)} into input ${pinRef(facts.target, facts.input)}; ${scored}`;
169
- }
170
- }
171
- }
172
- function largest(most, fits) {
173
- if (!fits(0)) return void 0;
174
- let [low, high] = [0, most];
175
- while (low < high) {
176
- const middle = Math.ceil((low + high) / 2);
177
- if (fits(middle)) low = middle;
178
- else high = middle - 1;
179
- }
180
- return low;
181
- }
182
- function fitted(facts) {
183
- const most = RANK_CANDIDATE_TEXT_MAX_CHARS;
184
- const fits = (cut) => textOf(facts, cut).length <= most;
185
- if (fits(WHOLE)) return textOf(facts, WHOLE);
186
- const proseCut = largest(most, (n) => fits({ prose: n, names: WHOLE.names }));
187
- if (proseCut !== void 0) return textOf(facts, { prose: proseCut, names: WHOLE.names });
188
- const namesCut = largest(most, (n) => fits({ prose: 0, names: n }));
189
- if (namesCut !== void 0) return textOf(facts, { prose: 0, names: namesCut });
190
- return shortened(textOf(facts, { prose: 0, names: 0 }), most);
191
- }
192
- function renderCandidate(facts) {
193
- return { id: facts.id, kind: facts.kind, text: fitted(facts) };
194
- }
195
-
196
- // src/questions/reading.ts
197
- var READING_SLOTS = [
198
- "operation",
199
- "instance",
200
- "input",
201
- "sourceInstance",
202
- "output",
203
- "targetInstance",
204
- "module"
205
- ];
206
- function statedSlots(reading) {
207
- return READING_SLOTS.filter((slot) => reading[slot] !== void 0);
208
- }
209
- function renderReading(reading) {
210
- return statedSlots(reading).map((slot) => `${slot}=${reading[slot]}`).join(", ");
211
- }
212
-
213
- // src/questions/render.ts
214
- var VALUE_PLACEHOLDER = "<value>";
215
- function literalTexts(value) {
216
- if (typeof value === "string") return [value];
217
- if (typeof value === "number" || typeof value === "boolean") return [String(value)];
218
- if (typeof value === "object" && value !== null)
219
- return Object.values(value).flatMap(literalTexts);
220
- return [];
221
- }
222
- function literals(values) {
223
- return values.flatMap(literalTexts).filter((literal) => literal !== "").sort((a, b) => b.length - a.length);
224
- }
225
- function variableName(text2) {
226
- return text2.replace(/^var\./, "");
227
- }
228
- function forms(values) {
229
- return [...new Set(literals(values).flatMap((text2) => [text2, variableName(text2)]))];
230
- }
231
- function unnamed(names2, values) {
232
- return forms(values).filter((text2) => !names2.has(text2));
233
- }
234
- function escapeRegExp(text2) {
235
- return text2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
236
- }
237
- var NAME = /^[A-Za-z0-9_-]+$/;
238
- function occurrences(literal) {
239
- const text2 = escapeRegExp(literal);
240
- return NAME.test(literal) ? new RegExp(`(?<![A-Za-z0-9_-])${text2}(?![A-Za-z0-9_-])`, "g") : new RegExp(text2, "g");
241
- }
242
- function withhold(text2, values) {
243
- return literals(values).reduce(
244
- (rest, literal) => rest.replace(occurrences(literal), VALUE_PLACEHOLDER),
245
- text2
246
- );
247
- }
248
- function holdsValue(rendered, values) {
249
- return literals(values).some((literal) => rendered.includes(literal));
250
- }
251
- function renderRequest(request, values, statement = "") {
252
- return shortened(withhold(request, values), RANK_REQUEST_MAX_CHARS - statement.length);
253
- }
51
+ // src/surfaces/canvas/canvas-tools.ts
52
+ var import_engine4 = require("@lace-cloud/canvas/engine");
254
53
 
255
- // src/examples/rows.ts
256
- function hashFraction(key) {
257
- let hash = 2166136261;
258
- for (const char of key) {
259
- hash ^= char.codePointAt(0) ?? 0;
260
- hash = Math.imul(hash, 16777619) >>> 0;
54
+ // src/contract/cancel.ts
55
+ var Cancelled = class extends Error {
56
+ constructor() {
57
+ super("the call was cancelled");
261
58
  }
262
- return hash / 2 ** 32;
263
- }
264
- function partOf(key) {
265
- const at2 = hashFraction(key);
266
- return at2 < 0.6 ? "train" : at2 < 0.8 ? "calibration" : "held_out";
267
- }
268
- function trainingRows(turn, part) {
269
- return turn.questions.map(({ candidates, label, chat }) => ({
270
- request: turn.request,
271
- statement: turn.statement,
272
- candidates,
273
- label,
274
- part,
275
- origin: turn.origin,
276
- turn: turn.id,
277
- chat
278
- }));
279
- }
280
-
281
- // src/ranking/client.ts
282
- var RANK_PATH = "/api/v1/candidates/rank";
283
- var DECISIONS_PATH = "/api/v1/candidates/decisions";
284
- var RankingUnavailable = class extends Error {
285
59
  };
286
- function isRecord(value) {
287
- return typeof value === "object" && value !== null && !Array.isArray(value);
60
+ function stopIfCancelled(signal) {
61
+ if (signal?.aborted) throw new Cancelled();
288
62
  }
289
- var isKind = (value) => DECISION_KINDS.includes(value);
290
- function scoreOf(value) {
291
- if (!isRecord(value)) return void 0;
292
- const { id, score, rightness } = value;
293
- return typeof id === "string" && typeof score === "number" && typeof rightness === "number" && rightness >= 0 && rightness <= 1 ? { id, score, rightness } : void 0;
294
- }
295
- function thresholdsOf(value) {
296
- if (!isRecord(value)) return void 0;
297
- const entries = Object.entries(value).map(
298
- ([kind, threshold]) => isKind(kind) && isRecord(threshold) && typeof threshold.from === "number" ? [kind, { from: threshold.from }] : void 0
299
- );
300
- return entries.every((entry) => entry !== void 0) ? Object.fromEntries(entries) : void 0;
301
- }
302
- function rankedOf(body) {
303
- if (!isRecord(body) || !Array.isArray(body.scores)) return void 0;
304
- const scores = body.scores.map(scoreOf);
305
- const thresholds = thresholdsOf(body.thresholds);
306
- 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;
307
- }
308
- function rankingClient(transport) {
309
- const post = (path, body) => transport(path, { method: "POST", body }).catch(() => ({ status: 0, body: void 0 }));
310
- return {
311
- async rank(request) {
312
- const { status, body } = await post(RANK_PATH, request);
313
- const ranked = status === 200 ? rankedOf(body) : void 0;
314
- if (ranked === void 0) {
315
- throw new RankingUnavailable(
316
- status === 200 ? "the ranking service answered with no ranking" : `status ${status}`
317
- );
318
- }
319
- return ranked;
320
- },
321
- async decision(report) {
322
- await post(DECISIONS_PATH, report);
323
- },
324
- async outcome(decision, outcome) {
325
- await post(`${DECISIONS_PATH}/${encodeURIComponent(decision)}/outcomes`, outcome);
326
- }
63
+ function untilCancelled(work, signal) {
64
+ if (signal === void 0) return work;
65
+ let stop = () => {
327
66
  };
67
+ const cancelled = new Promise((_, fail) => {
68
+ stop = () => fail(new Cancelled());
69
+ if (signal.aborted) stop();
70
+ else signal.addEventListener("abort", stop, { once: true });
71
+ });
72
+ return Promise.race([work, cancelled]).finally(() => signal.removeEventListener("abort", stop));
328
73
  }
329
-
330
- // src/hybrid/compose.ts
331
- var real = (score) => score.id !== NONE_CANDIDATE_ID;
332
- function pickOf(scores) {
333
- return scores.find(real);
334
- }
335
- function sure(ranked, kind) {
336
- const from = ranked.thresholds[kind]?.from;
337
- const pick = pickOf(ranked.scores);
338
- return from !== void 0 && pick !== void 0 && ranked.scores[0]?.id !== NONE_CANDIDATE_ID && pick.rightness >= from;
339
- }
340
- function compose({ kind, chat, ranked }) {
341
- const pick = ranked === null ? void 0 : pickOf(ranked.scores);
342
- const clm = pick === void 0 ? null : { id: pick.id, rightness: pick.rightness };
343
- if (ranked !== null && clm !== null && sure(ranked, kind)) {
344
- return { took: "clm", taken: clm.id, clm, differed: chat !== null && chat !== clm.id };
345
- }
346
- return { took: "chat", taken: chat, clm, differed: false };
347
- }
348
- function moveStands(under) {
349
- return under.every((question) => question.took === "clm");
74
+ function cancellable(start, signal) {
75
+ if (signal?.aborted) return Promise.reject(new Cancelled());
76
+ return untilCancelled(start(), signal);
350
77
  }
351
78
 
352
- // src/surfaces/canvas/canvas-tools.ts
353
- var import_engine5 = require("@lace-cloud/canvas/engine");
354
-
355
79
  // src/surfaces/canvas/change.ts
356
- var import_engine4 = require("@lace-cloud/canvas/engine");
80
+ var import_engine3 = require("@lace-cloud/canvas/engine");
357
81
 
358
82
  // src/surfaces/canvas/commands.ts
359
83
  var import_engine2 = require("@lace-cloud/canvas/engine");
@@ -387,149 +111,36 @@ function readCanvas(source) {
387
111
  });
388
112
  return {
389
113
  module: view.module_name,
390
- entry: bundle.entry,
391
114
  instances,
392
115
  wires: view.edges,
393
- groups: view.groups.map((group) => ({ id: group.id, members: group.node_ids }))
394
- };
395
- }
396
- function canvasNames(canvas) {
397
- return new Set(
398
- canvas.instances.flatMap((instance) => [
399
- instance.id,
400
- instance.name,
401
- instance.module,
402
- instance.scope,
403
- ...instance.inputs.map((input) => input.name),
404
- ...instance.outputs.map((output) => output.name)
405
- ])
406
- );
407
- }
408
- function offered(facts, rest) {
409
- return { facts, candidate: renderCandidate(facts), ...rest };
410
- }
411
- var pinFacts = (pins) => pins.map(
412
- (pin) => pin.description ? { name: pin.name, description: pin.description } : { name: pin.name }
413
- );
414
- function unwired(instance) {
415
- return instance.inputs.filter((input) => input.mode !== "wired");
416
- }
417
- function instanceFacts(instance, role) {
418
- return {
419
- id: instance.id,
420
- kind: "instance",
421
- role,
422
- module: instance.module,
423
- inputs: pinFacts(role === "target" ? unwired(instance) : instance.inputs),
424
- outputs: pinFacts(instance.outputs)
116
+ groups: view.groups.map((group) => ({ id: group.id, members: group.node_ids })),
117
+ diagnostics: source.diagnostics.map((diagnostic) => ({
118
+ diagnostic,
119
+ node: (0, import_proto.nodeIdForDiagnostic)(view, diagnostic)
120
+ }))
425
121
  };
426
122
  }
427
- function operationOptions(operations) {
428
- return operations.map(
429
- (operation) => offered(
430
- { id: operation.id, kind: "operation" },
431
- { refs: [[operation.id]], slots: { operation: operation.id }, value: operation }
432
- )
433
- );
434
- }
435
123
  function instanceOptions(instances) {
436
- return instances.map(
437
- (instance) => offered(instanceFacts(instance, "instance"), {
438
- refs: [[instance.id], [instance.name]],
439
- slots: { instance: instance.id },
440
- value: instance
441
- })
442
- );
443
- }
444
- function sourceOptions(instances) {
445
- return instances.filter((instance) => instance.outputs.length > 0).map(
446
- (instance) => offered(instanceFacts(instance, "source"), {
447
- refs: instance.outputs.map((output) => [pinRef(instance.id, output.name)]),
448
- slots: { sourceInstance: instance.id },
449
- value: instance
450
- })
451
- );
452
- }
453
- function targetOptions(instances, source) {
454
- return instances.filter((instance) => instance.scope === source.scope && instance.id !== source.id).filter((instance) => unwired(instance).length > 0).map(
455
- (instance) => offered(instanceFacts(instance, "target"), {
456
- refs: unwired(instance).map((input) => [pinRef(instance.id, input.name)]),
457
- slots: { targetInstance: instance.id },
458
- value: instance
459
- })
460
- );
461
- }
462
- var INPUT_STATE = {
463
- empty: "not set",
464
- literal: "set",
465
- variable: "set",
466
- expression: "set",
467
- wired: "wired"
468
- };
469
- function inputOptions(instance, inputs) {
470
- return inputs.map(
471
- (input) => offered(
472
- {
473
- id: input.name,
474
- kind: "input",
475
- instance: instance.id,
476
- module: instance.module,
477
- type: input.type,
478
- required: input.required,
479
- state: INPUT_STATE[input.mode],
480
- ...input.description === void 0 ? {} : { description: input.description }
481
- },
482
- { refs: [[input.name]], slots: { input: input.name }, value: input }
483
- )
484
- );
124
+ return instances.map((instance) => ({ names: [instance.id, instance.name], value: instance }));
485
125
  }
486
- var STEPS = ["one", "several"];
487
- function stepsOptions() {
488
- return STEPS.map((id) => offered({ id, kind: "steps" }, { refs: [], slots: {}, value: id }));
126
+ function pinOptions(pins) {
127
+ return pins.map((pin) => ({ names: [pin.name], value: pin }));
489
128
  }
490
129
  function moduleId(row) {
491
130
  return `${row.author}/${row.name}`;
492
131
  }
493
132
  function moduleOptions(rows) {
494
- return rows.map(
495
- (row) => offered(
496
- {
497
- id: moduleId(row),
498
- kind: "module",
499
- displayName: row.displayName,
500
- description: row.description,
501
- system: row.system,
502
- categories: row.categories
503
- },
504
- { refs: [[moduleId(row)], [row.name]], slots: { module: moduleId(row) }, value: row }
505
- )
506
- );
133
+ return rows.map((row) => ({ names: [moduleId(row), row.name], value: row }));
507
134
  }
508
- function connectionOptions(source, target, scored) {
509
- const between = scored.filter(
510
- (each) => each.sourceInstance === source.name && each.targetInstance === target.name
511
- );
512
- return source.outputs.flatMap(
513
- (output) => unwired(target).map((input) => {
514
- const pair = { output: output.name, input: input.name };
515
- const from = pinRef(source.id, pair.output);
516
- const to = pinRef(target.id, pair.input);
517
- const match = between.find(
518
- (each) => each.output === pair.output && each.input === pair.input
519
- );
520
- return offered(
521
- {
522
- id: connectionId(from, to),
523
- kind: "connection",
524
- source: source.id,
525
- output: pair.output,
526
- target: target.id,
527
- input: pair.input,
528
- ...match === void 0 ? {} : { score: match.score }
529
- },
530
- { refs: [[from, to]], slots: pair, value: pair }
531
- );
532
- })
135
+ function pinRef(instance, pin) {
136
+ return `${instance}.${pin}`;
137
+ }
138
+ function connectionId(from, to) {
139
+ return `${from} \u2192 ${to}`;
140
+ }
141
+ function pairListing(source, target, scored, pin) {
142
+ return scored.filter((pair) => pair.sourceInstance === source.name && pair.targetInstance === target.name).filter((pair) => pin.output === void 0 || pair.output === pin.output).filter((pair) => pin.input === void 0 || pair.input === pin.input).map(
143
+ (pair) => `${connectionId(pinRef(source.id, pair.output), pinRef(target.id, pair.input))} (score ${pair.score})`
533
144
  );
534
145
  }
535
146
 
@@ -547,21 +158,19 @@ function errorText(error) {
547
158
  }
548
159
  return error instanceof Error ? error.message : String(error);
549
160
  }
550
- function registrationOf(schema, run, failed) {
161
+ function registration(schema, run) {
162
+ const none = {};
551
163
  return {
552
164
  schema,
553
- async handler(input) {
165
+ async handler(input, signal) {
554
166
  try {
555
- return await run(input);
167
+ return await run(input, signal);
556
168
  } catch (error) {
557
- return failed({ content: errorText(error), isError: true });
169
+ return { ...none, content: errorText(error), isError: true };
558
170
  }
559
171
  }
560
172
  };
561
173
  }
562
- function registration(schema, run) {
563
- return registrationOf(schema, run, (failure) => failure);
564
- }
565
174
  var NO_INPUT = { type: "object", properties: {}, additionalProperties: false };
566
175
 
567
176
  // src/surfaces/canvas/commands.ts
@@ -581,10 +190,10 @@ function commandEnd(path, error) {
581
190
  text: `lace ${path} did not finish cleanly (exit ${error.code}: ${error.stderrTail})`
582
191
  };
583
192
  }
584
- async function runCommand(commands, path, args) {
193
+ async function runCommand(commands, path, args, signal = new AbortController().signal) {
585
194
  const documents = [];
586
195
  try {
587
- for await (const document of commands.invoke(path, args, new AbortController().signal).events) {
196
+ for await (const document of commands.invoke(path, args, signal).events) {
588
197
  documents.push(document);
589
198
  }
590
199
  } catch (error) {
@@ -626,176 +235,14 @@ function trimRegistryList(list) {
626
235
  truncated: list.truncated
627
236
  };
628
237
  }
629
- function trimRegistryDescribe(described2) {
238
+ function trimRegistryDescribe(described) {
630
239
  return {
631
- module: moduleId(described2),
632
- version: described2.version,
633
- source: described2.source,
634
- verdict: described2.verdict,
635
- inputs: described2.interface.inputs,
636
- outputs: described2.interface.outputs
637
- };
638
- }
639
-
640
- // src/surfaces/canvas/outcome.ts
641
- var import_engine3 = require("@lace-cloud/canvas/engine");
642
- function instanceAt(canvas, scope, name) {
643
- return canvas.instances.find((instance) => instance.scope === scope && instance.name === name);
644
- }
645
- function presenceOf(canvas, scope, name) {
646
- const instance = instanceAt(canvas, scope, name);
647
- return instance === void 0 ? null : { instance: instance.name, module: instance.module };
648
- }
649
- function bindingOf(canvas, scope, name, inputName) {
650
- const input = instanceAt(canvas, scope, name)?.inputs.find((each) => each.name === inputName);
651
- if (input === void 0) return null;
652
- if (input.sensitive) return { mode: input.mode };
653
- return {
654
- mode: input.mode,
655
- value: input.value,
656
- variable: input.variable,
657
- expression: input.expression,
658
- wiredSource: input.wired_source
659
- };
660
- }
661
- function at({ target, after }) {
662
- return after !== null && "instance" in after ? after.instance : target.instance;
663
- }
664
- function targetState(canvas, record) {
665
- const { scope, input } = record.target;
666
- return input === void 0 ? presenceOf(canvas, scope, at(record)) : bindingOf(canvas, scope, at(record), input);
667
- }
668
- function follow(record, previous, frame) {
669
- const name = at(record);
670
- const { scope } = record.target;
671
- const was = instanceAt(previous, scope, name);
672
- if (was === void 0 || instanceAt(frame, scope, name) !== void 0) return record;
673
- const fresh = frame.instances.filter(
674
- (each) => each.module === was.module && instanceAt(previous, each.scope, each.name) === void 0
675
- );
676
- const one = (found2) => found2.length === 1 ? found2[0] : void 0;
677
- const moved2 = one(fresh.filter((each) => each.name === name)) ?? one(fresh.filter((each) => each.scope === scope));
678
- if (moved2 === void 0) return record;
679
- const { after } = record;
680
- return {
681
- ...record,
682
- target: { ...record.target, scope: moved2.scope, instance: moved2.name },
683
- after: after !== null && "instance" in after ? { ...after, instance: moved2.name } : after
684
- };
685
- }
686
- var decided = (state) => state === null ? null : "mode" in state ? [state.mode, state.wiredSource] : state.module;
687
- var moved = (state, from) => state !== null && "mode" in state ? !(0, import_engine3.deepEqual)(state, from) : !(0, import_engine3.deepEqual)(decided(state), decided(from));
688
- var OPERATION_OF_MODE = {
689
- literal: "set",
690
- variable: "bind",
691
- empty: "clear",
692
- wired: "connect"
693
- };
694
- function answered(record, state, canvas) {
695
- if (state === null || !("mode" in state) || record.target.input === void 0) return {};
696
- const name = (kind, candidate) => {
697
- const question = record.questions.findIndex(
698
- (each) => each.kind === kind && candidate !== void 0 && each.candidates.includes(candidate)
699
- );
700
- return question === -1 || candidate === void 0 ? {} : { question, candidate };
701
- };
702
- const after = record.after;
703
- if (after !== null && "mode" in after && after.mode !== state.mode) {
704
- return name("operation", OPERATION_OF_MODE[state.mode]);
705
- }
706
- if (state.mode !== "wired" || state.wiredSource === void 0) return {};
707
- const [, source, output] = /^module\.([^.]+)\.(.+)$/.exec(state.wiredSource) ?? [];
708
- const { scope } = record.target;
709
- const from = instanceAt(canvas, scope, source ?? "");
710
- const to = instanceAt(canvas, scope, at(record));
711
- return from === void 0 || to === void 0 || output === void 0 ? {} : name("connection", connectionId(pinRef(from.id, output), pinRef(to.id, record.target.input)));
712
- }
713
- function frameOutcomes(record, was, previous, frame, canvas, own) {
714
- const state = targetState(canvas, record);
715
- if ((0, import_engine3.deepEqual)(state, record.before)) return [{ event: "reverted" }];
716
- const changes = (from) => !(0, import_engine3.deepEqual)(decided(state), decided(from));
717
- if (changes(was) && changes(record.after)) {
718
- const event = own.has(frame.revision) ? "changed_again" : "hand_edited";
719
- return [{ event, ...answered(record, state, canvas) }];
720
- }
721
- if (moved(state, record.after)) return [];
722
- const saved = previous?.unsaved === true && !frame.unsaved ? [{ event: "saved" }] : [];
723
- const generated = previous?.ungenerated === true && !frame.ungenerated ? [{ event: "generated" }] : [];
724
- return [...saved, ...generated];
725
- }
726
- function changeOutcomes(record, frames, own = new Set(record.revision === void 0 ? [] : [record.revision])) {
727
- const canvases = frames.map(readCanvas);
728
- const reached = /* @__PURE__ */ new Map();
729
- let carried = record;
730
- frames.forEach((frame, index) => {
731
- const was = index > 0 ? targetState(canvases[index - 1], carried) : record.after;
732
- if (index > 0) carried = follow(carried, canvases[index - 1], canvases[index]);
733
- for (const outcome of frameOutcomes(
734
- carried,
735
- was,
736
- frames[index - 1],
737
- frame,
738
- canvases[index],
739
- own
740
- )) {
741
- if (!reached.has(outcome.event)) reached.set(outcome.event, outcome);
742
- }
743
- });
744
- return { record: carried, outcomes: [...reached.values()] };
745
- }
746
- function outcomeObserver(transport) {
747
- const client = rankingClient(transport);
748
- const followed = /* @__PURE__ */ new Map();
749
- const own = /* @__PURE__ */ new Set();
750
- let previous;
751
- let flying = 0;
752
- const returned = /* @__PURE__ */ new Set();
753
- let held = [];
754
- const fold = (source) => {
755
- const frames = previous === void 0 ? [source] : [previous, source];
756
- previous = source;
757
- for (const [id, each] of followed) {
758
- const { record, outcomes } = changeOutcomes(each.record, frames, own);
759
- followed.set(id, { record, reported: each.reported });
760
- for (const outcome of outcomes.filter(({ event }) => !each.reported.has(event))) {
761
- each.reported.add(outcome.event);
762
- void client.outcome(id, outcome);
763
- }
764
- }
765
- };
766
- const landed = (revision) => {
767
- flying -= 1;
768
- if (revision !== void 0) returned.add(revision);
769
- if (flying > 0) return;
770
- const frames = held;
771
- held = [];
772
- for (const frame of frames) {
773
- if (returned.has(frame.revision)) own.add(frame.revision);
774
- fold(frame);
775
- }
776
- returned.clear();
777
- };
778
- return {
779
- async own(apply) {
780
- flying += 1;
781
- let revision;
782
- try {
783
- const result = await apply();
784
- revision = result.success ? result.revision : void 0;
785
- return result;
786
- } finally {
787
- landed(revision);
788
- }
789
- },
790
- follow(records) {
791
- for (const record of records.filter((each) => each.reported)) {
792
- followed.set(record.id, { record, reported: /* @__PURE__ */ new Set() });
793
- }
794
- },
795
- frame(source) {
796
- if (flying > 0) held.push(source);
797
- else fold(source);
798
- }
240
+ module: moduleId(described),
241
+ version: described.version,
242
+ source: described.source,
243
+ verdict: described.verdict,
244
+ inputs: described.interface.inputs,
245
+ outputs: described.interface.outputs
799
246
  };
800
247
  }
801
248
 
@@ -809,425 +256,177 @@ function endError(end) {
809
256
  function latest(source) {
810
257
  let unsubscribe = () => {
811
258
  };
812
- const frame = new Promise((resolve, reject) => {
813
- unsubscribe = source.subscribe(resolve, (end) => reject(endError(end)));
259
+ const frame = new Promise((resolve2, reject) => {
260
+ unsubscribe = source.subscribe(resolve2, (end) => reject(endError(end)));
814
261
  });
815
262
  return frame.finally(() => unsubscribe());
816
263
  }
817
264
 
818
- // src/surfaces/canvas/render.ts
819
- var import_proto2 = require("@lace-cloud/proto");
820
- function inputText(input) {
821
- if (input.mode === "empty") {
822
- return `${input.name} (${input.required ? "required, " : ""}not set)`;
823
- }
824
- if (input.mode === "wired") return `${input.name} (wired)`;
825
- if (input.sensitive) return `${input.name} (sensitive, value withheld)`;
826
- const shown = {
827
- literal: JSON.stringify(input.value),
828
- variable: `var.${input.variable}`,
829
- expression: `${input.expression}`
830
- };
831
- return `${input.name} = ${shown[input.mode]}`;
832
- }
833
- function instanceLines(instance) {
834
- return [
835
- `- ${instance.id}: module ${instance.module}`,
836
- ` inputs: [${instance.inputs.map(inputText).join("; ")}]`,
837
- ` outputs: [${instance.outputs.map((output) => output.name).join(", ")}]`
838
- ];
839
- }
840
- function unsetRequired(instance) {
841
- return instance.inputs.filter((input) => input.required && input.mode === "empty").map((input) => `- ${instance.id}.${input.name}`);
842
- }
843
- function diagnosticLine(diagnostic) {
844
- const where = [
845
- ["instance", diagnostic.instance_id],
846
- ["input", diagnostic.input_name],
847
- ["address", diagnostic.address],
848
- ["file", diagnostic.file],
849
- ["line", diagnostic.line]
850
- ].filter(([, value]) => value !== void 0).map(([label, value]) => `${label} ${value}`);
851
- return `- ${[`${diagnostic.severity}: ${diagnostic.message}`, ...where].join("; ")}`;
852
- }
853
- var yesNo = (flag) => flag ? "yes" : "no";
854
- function section(title, lines) {
855
- return [`${title} (${lines.length}):`, ...lines];
856
- }
857
- function renderCanvas(source) {
858
- const canvas = readCanvas(source);
859
- return [
860
- `Canvas of module ${canvas.module}`,
861
- `Instances (${canvas.instances.length}):`,
862
- ...canvas.instances.flatMap(instanceLines),
863
- ...section(
864
- "Wires",
865
- canvas.wires.map(
866
- (wire) => `- ${wire.source_output ? `${wire.source}.${wire.source_output}` : (0, import_proto2.callText)(wire.source)} \u2192 ${wire.target}.${wire.target_input}`
867
- )
868
- ),
869
- ...section("Required inputs not set", canvas.instances.flatMap(unsetRequired)),
870
- ...section(
871
- "Groups",
872
- canvas.groups.map((group) => `- ${group.id}: ${group.members.join(", ")}`)
873
- ),
874
- ...section("Diagnostics", source.diagnostics.map(diagnosticLine)),
875
- [
876
- `Standing: unsaved edits: ${yesNo(source.unsaved)}`,
877
- `saved edits not generated to Terraform: ${yesNo(source.ungenerated)}`,
878
- `conflict with the Terraform on disk: ${yesNo(source.conflict !== null)}`,
879
- `Terraform refused, canvas locked: ${yesNo(source.sourceRefused)}`
880
- ].join("; ")
881
- ].join("\n");
882
- }
883
- function renderTarget(target) {
884
- const pin = target.input === void 0 ? target.instance : `${target.instance}.${target.input}`;
885
- return `${pin} in ${target.scope}`;
886
- }
887
- function renderState(state) {
888
- if (state === null) return "absent";
889
- if (!("mode" in state)) return `an instance of module ${state.module}`;
890
- const shown = {
891
- empty: "not set",
892
- literal: `literal ${VALUE_PLACEHOLDER}`,
893
- variable: `variable ${VALUE_PLACEHOLDER}`,
894
- expression: `expression ${VALUE_PLACEHOLDER}`,
895
- wired: `wired from ${state.wiredSource}`
896
- };
897
- return shown[state.mode];
898
- }
899
-
900
265
  // src/surfaces/canvas/resolve.ts
901
- var WORD = /[A-Za-z0-9_-]+/g;
902
- var DOTTED = /[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)+/g;
903
- var SLASHED = /[A-Za-z0-9_-]+(?:\/[A-Za-z0-9_-]+)+/g;
904
- function found(text2, pattern) {
905
- return [...text2.matchAll(pattern)].map((match) => ({ term: match[0], at: match.index }));
906
- }
907
- function runs({ term, at: at2 }) {
908
- const parts = term.split(".");
909
- const starts = parts.map((_, index) => at2 + parts.slice(0, index).join(".").length + index);
910
- return parts.flatMap(
911
- (_, start) => parts.slice(start).map((_2, length) => ({
912
- term: parts.slice(start, start + length + 1).join("."),
913
- at: starts[start]
914
- }))
915
- );
916
- }
917
- function moduleReferences(text2) {
918
- return found(text2, SLASHED).map((each) => each.term);
919
- }
920
- function firstAt(names2, key) {
921
- return names2.reduce(
922
- (at2, { term, at: offset }) => at2.set(key(term), Math.min(offset, at2.get(key(term)) ?? offset)),
923
- /* @__PURE__ */ new Map()
924
- );
925
- }
926
- function termsOf(text2) {
927
- const names2 = [
928
- ...found(text2, WORD),
929
- ...found(text2, DOTTED).flatMap(runs),
930
- ...found(text2, SLASHED)
931
- ];
932
- return {
933
- exact: firstAt(names2, (term) => term),
934
- folded: firstAt(names2, (term) => term.toLowerCase()),
935
- words: found(text2, WORD).map(({ term }) => term.toLowerCase())
936
- };
937
- }
938
- function vocabulary(option) {
939
- const text2 = [option.candidate.id, option.candidate.text, ...option.refs.flat()].join(" ");
940
- return new Set(
941
- found(text2.toLowerCase(), WORD).flatMap(({ term }) => [term, ...term.split(/[_-]/)])
942
- );
943
- }
944
- var FUNCTION_WORDS = new Set(
945
- "a about after all am an and any are as at be been but by can could did do does each every for from had has have he her his i if in into is it its may me might must my no nor not of off on onto or our out over per shall she should so some than that the their them then these they this those to up upon us via was we were will with would you your".split(
946
- " "
947
- )
948
- );
949
- function span(words, index, covered) {
950
- if (!covered.has(words[index])) return 0;
951
- const outside = (word) => !covered.has(word) && !FUNCTION_WORDS.has(word);
952
- const before = words.slice(0, index).reverse().findIndex(outside);
953
- const after = words.slice(index + 1).findIndex(outside);
954
- return words.slice(before === -1 ? 0 : index - before, after === -1 ? words.length : index + 1 + after).filter((word) => !FUNCTION_WORDS.has(word)).length;
955
- }
956
- var NothingOffered = class extends Error {
957
- constructor(label) {
958
- super(`the canvas offers no ${label} for this change`);
959
- this.label = label;
960
- }
961
- };
962
- var Undecided = class extends Error {
963
- constructor(kind, label, candidates, ranking2) {
964
- super(`the ${label} was not decided`);
965
- this.kind = kind;
966
- this.label = label;
967
- this.candidates = candidates;
968
- this.ranking = ranking2;
969
- }
970
- };
971
- var NAMED_ALTERNATIVES = 3;
972
- var NONE_OVER = "none of these";
973
- function named(options, { words }, terms, fold) {
974
- const hits = options.map((option) => ({
975
- option,
976
- refs: option.refs.map((ref) => ref.map(fold)).filter((ref) => ref.every((part) => terms.has(part)))
977
- })).filter((hit) => hit.refs.length > 0);
978
- const extended = (ref) => ref.length === 1 && hits.some(
979
- (other) => other.refs.some(
980
- (longer) => longer.some((part) => part !== ref[0] && part.split(".").includes(ref[0]))
981
- )
982
- );
983
- const covers = new Map(options.map((option) => [option, vocabulary(option)]));
984
- const outspanned = (option, ref) => {
985
- const word = ref[0].toLowerCase();
986
- const places = words.flatMap((each, index) => each === word ? [index] : []);
987
- const own = covers.get(option) ?? /* @__PURE__ */ new Set();
988
- return ref.length === 1 && !/[./]/.test(word) && places.length > 0 && places.every(
989
- (index) => options.some(
990
- (other) => other !== option && span(words, index, covers.get(other) ?? /* @__PURE__ */ new Set()) > span(words, index, own)
991
- )
992
- );
993
- };
994
- const at2 = (ref) => Math.min(...ref.map((part) => terms.get(part) ?? Number.POSITIVE_INFINITY));
995
- return hits.map((hit) => ({
996
- ...hit,
997
- refs: hit.refs.filter((ref) => !extended(ref) && !outspanned(hit.option, ref))
998
- })).filter((hit) => hit.refs.length > 0).map((hit) => ({ ...hit, at: Math.min(...hit.refs.map(at2)) })).sort((a, b) => a.at - b.at);
999
- }
1000
- function apart(hits) {
1001
- const key = (ref) => ref.join(" ");
1002
- return hits.every((hit) => {
1003
- const others = hits.filter((other) => other !== hit);
1004
- const own = hit.refs.some(
1005
- (ref) => !others.some((other) => other.refs.some((each) => key(each) === key(ref)))
1006
- );
1007
- const inside = others.some(
1008
- (other) => hit.option.candidate.id.startsWith(`${other.option.candidate.id}.`)
266
+ var first = (option) => option.names.slice(0, 1);
267
+ var every = (option) => option.names;
268
+ var STEPS = [
269
+ { folded: false, names: first },
270
+ { folded: false, names: every },
271
+ { folded: true, names: first },
272
+ { folded: true, names: every }
273
+ ];
274
+ function resolve(options, stated) {
275
+ const step = STEPS.map((each) => {
276
+ const key = (name) => {
277
+ const normal = name.normalize("NFC");
278
+ return each.folded ? normal.toLowerCase() : normal;
279
+ };
280
+ const hits = options.filter(
281
+ (option) => each.names(option).some((name) => key(name) === key(stated))
1009
282
  );
1010
- return own && !inside;
1011
- });
283
+ return { folded: each.folded, hits };
284
+ }).find((each) => each.hits.length > 0);
285
+ if (step === void 0) return { kind: "none" };
286
+ return step.hits.length === 1 ? { kind: "one", option: step.hits[0], folded: step.folded } : { kind: "several", options: step.hits };
1012
287
  }
1013
- var NAME_STEPS = [
1014
- {
1015
- how: "exact",
1016
- hits: (options, terms) => named(options, terms, terms.exact, (part) => part)
1017
- },
1018
- {
1019
- how: "unique",
1020
- hits: (options, terms) => named(options, terms, terms.folded, (part) => part.toLowerCase())
1021
- }
288
+
289
+ // src/surfaces/canvas/stated.ts
290
+ var STATED_SLOTS = [
291
+ "instance",
292
+ "input",
293
+ "sourceInstance",
294
+ "output",
295
+ "targetInstance",
296
+ "module"
1022
297
  ];
1023
- function read(options, reading) {
1024
- return options.filter(
1025
- (option) => statedSlots(option.slots).every((slot) => reading[slot] === option.slots[slot])
1026
- );
298
+ function slotsStated(stated) {
299
+ return STATED_SLOTS.filter((slot) => stated[slot] !== void 0);
1027
300
  }
1028
- function answerOf(options, reading) {
1029
- const named2 = read(options, reading);
1030
- return named2.length === 1 ? named2[0] : void 0;
1031
- }
1032
- var PART = RANK_CANDIDATES_MAX - 1;
1033
- function partsOf(items) {
1034
- return Array.from(
1035
- { length: Math.ceil(items.length / PART) },
1036
- (_, n) => items.slice(n * PART, (n + 1) * PART)
1037
- );
301
+
302
+ // src/surfaces/canvas/withhold.ts
303
+ var VALUE_PLACEHOLDER = "<value>";
304
+ function literalTexts(value) {
305
+ if (typeof value === "string") return [value];
306
+ if (typeof value === "number" || typeof value === "boolean") return [String(value)];
307
+ if (typeof value === "object" && value !== null)
308
+ return Object.values(value).flatMap(literalTexts);
309
+ return [];
1038
310
  }
1039
- function partHolding(candidates, id) {
1040
- return partsOf(candidates).find((part) => part.some((each) => each.id === id)) ?? [];
1041
- }
1042
- function factsOf(options, part) {
1043
- const byId = new Map(options.map((option) => [option.candidate.id, option.facts]));
1044
- return part.flatMap((candidate) => byId.get(candidate.id) ?? []);
1045
- }
1046
- async function rankPart(rank, request, statement, kind, part) {
1047
- const ranked = await rank({ request, statement, candidates: rankCandidates(kind, part) });
1048
- const pick = part.find((candidate) => candidate.id === pickOf(ranked.scores)?.id);
1049
- if (pick === void 0) throw new Error("the ranking names no candidate of the set");
1050
- return { part, ranked, pick };
1051
- }
1052
- async function rankWithin(rank, request, statement, kind, candidates) {
1053
- const parts = partsOf(candidates);
1054
- if (parts.length === 1) return rankPart(rank, request, statement, kind, candidates);
1055
- const rounds = [];
1056
- for (const part of parts) rounds.push(await rankWithin(rank, request, statement, kind, part));
1057
- const final = await rankWithin(
1058
- rank,
1059
- request,
1060
- statement,
1061
- kind,
1062
- rounds.map((round) => round.pick)
1063
- );
1064
- const holding = rounds.find((round) => round.pick.id === final.pick.id);
1065
- if (holding === void 0) throw new Error("the ranking names no candidate of the set");
1066
- return holding;
311
+ var GO_ESCAPES = {
312
+ "\x07": "\\a",
313
+ "\b": "\\b",
314
+ "\f": "\\f",
315
+ "\n": "\\n",
316
+ "\r": "\\r",
317
+ " ": "\\t",
318
+ "\v": "\\v",
319
+ '"': '\\"',
320
+ "\\": "\\\\"
321
+ };
322
+ var GO_PRINTABLE = /^[ \p{L}\p{M}\p{N}\p{P}\p{S}]$/u;
323
+ function goEscaped(char) {
324
+ const code = char.codePointAt(0) ?? 0;
325
+ if (GO_ESCAPES[char] !== void 0) return GO_ESCAPES[char];
326
+ if (GO_PRINTABLE.test(char)) return char;
327
+ const [mark, width] = code < 128 ? ["x", 2] : code < 65536 ? ["u", 4] : ["U", 8];
328
+ return `\\${mark}${code.toString(16).padStart(width, "0")}`;
329
+ }
330
+ function writtenForms(literal) {
331
+ const quoted = [JSON.stringify(literal), `"${[...literal].map(goEscaped).join("")}"`];
332
+ return [literal, ...quoted, ...quoted.map((form) => form.slice(1, -1))];
333
+ }
334
+ function forms(value) {
335
+ const all = literalTexts(value).filter((literal) => literal !== "").flatMap(writtenForms);
336
+ return [...new Set(all)].sort((a, b) => b.length - a.length);
1067
337
  }
1068
- async function ranking(ask, statement, kind, candidates) {
1069
- if (ask.rank === void 0) {
1070
- return { ranking: { ranked: null, failed: "Lace did not rank" }, part: candidates };
1071
- }
1072
- try {
1073
- const { part, ranked } = await rankWithin(ask.rank, ask.request, statement, kind, candidates);
1074
- return { ranking: { ranked, parts: part.length < candidates.length }, part };
1075
- } catch (error) {
1076
- const failed = `Lace could not rank: ${error instanceof Error ? error.message : String(error)}`;
1077
- return { ranking: { ranked: null, failed }, part: candidates };
1078
- }
338
+ function escapeRegExp(text2) {
339
+ return text2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1079
340
  }
1080
- var asAsked = (ranking2) => ranking2 === null || ranking2.ranked === null || ranking2.parts ? null : ranking2.ranked;
1081
- async function twoSystems(ask, kind, label, options, stated) {
1082
- const candidates = options.map((option2) => option2.candidate);
1083
- const readings = options.map((option2) => option2.slots);
1084
- const chat = stated === void 0 ? answerOf(options, ask.reading) : options.find((option2) => option2.value === stated);
1085
- const read2 = await ranking(ask, ask.statement, kind, candidates);
1086
- const composed = compose({
1087
- kind,
1088
- chat: chat?.candidate.id ?? null,
1089
- ranked: asAsked(read2.ranking)
1090
- });
1091
- const option = options.find((each) => each.candidate.id === composed.taken);
1092
- if (option === void 0) throw new Undecided(kind, label, candidates, read2.ranking);
1093
- const alternative = ask.alternative === void 0 ? null : await ranking(ask, ask.alternative.statement, kind, candidates).then(({ ranking: ranking2 }) => {
1094
- const ranked2 = asAsked(ranking2);
1095
- const pick = ranked2 === null ? void 0 : pickOf(ranked2.scores);
1096
- const named2 = options.find((each) => each.candidate.id === pick?.id);
1097
- return pick === void 0 || ranked2 === null || named2 === void 0 ? null : { id: pick.id, sure: sure(ranked2, kind), slots: named2.slots };
1098
- });
1099
- const ranked = read2.ranking.ranked;
1100
- const others = ranked === null ? [] : ranked.scores.filter((score) => score.id !== NONE_CANDIDATE_ID);
1101
- const part = composed.took === "clm" ? read2.part : partHolding(candidates, option.candidate.id);
1102
- return {
1103
- kind,
1104
- label,
1105
- option,
1106
- how: composed.took,
1107
- offered: candidates.length,
1108
- candidates: part,
1109
- facts: factsOf(options, part),
1110
- others: [],
1111
- chat: chat?.candidate.id ?? null,
1112
- ranking: read2.ranking,
1113
- composed,
1114
- over: [
1115
- ...ranked?.scores[0]?.id === NONE_CANDIDATE_ID ? [NONE_OVER] : [],
1116
- ...others.slice(1, NAMED_ALTERNATIVES + 1).map((score) => score.id)
1117
- ],
1118
- alternative,
1119
- readings
1120
- };
341
+ var NAME = /^[A-Za-z0-9_-]+$/;
342
+ function occurrences(form) {
343
+ const text2 = escapeRegExp(form);
344
+ return NAME.test(form) ? new RegExp(`(?<![A-Za-z0-9_-])${text2}(?![A-Za-z0-9_-])`, "gi") : new RegExp(text2, "gi");
1121
345
  }
1122
- function byName(ask, kind, label, options) {
1123
- const settled = (option, how, hits) => ({
1124
- kind,
1125
- label,
1126
- option,
1127
- how,
1128
- offered: options.length,
1129
- candidates: options.map((each) => each.candidate),
1130
- facts: options.map((each) => each.facts),
1131
- others: hits.filter((hit) => hit.option !== option).map((hit) => hit.option.candidate.id),
1132
- chat: answerOf(options, ask.reading)?.candidate.id ?? null,
1133
- ranking: null,
1134
- composed: null,
1135
- over: [],
1136
- alternative: null,
1137
- readings: options.map((each) => each.slots)
1138
- });
1139
- const step = NAME_STEPS.map((each) => ({
1140
- how: each.how,
1141
- hits: each.hits(options, ask.terms)
1142
- })).find((each) => each.hits.length > 0);
1143
- if (step === void 0) return void 0;
1144
- if (step.hits.length === 1) return settled(step.hits[0].option, step.how, step.hits);
1145
- if (!apart(step.hits)) return void 0;
1146
- const agreed = read(
1147
- step.hits.map((hit) => hit.option),
1148
- ask.reading
346
+ function withhold(text2, value) {
347
+ return forms(value).reduce(
348
+ (rest, form) => rest.replace(occurrences(form), VALUE_PLACEHOLDER),
349
+ text2
1149
350
  );
1150
- return agreed.length === 1 ? settled(agreed[0], "agreed", step.hits) : settled(step.hits[0].option, "first", step.hits);
1151
- }
1152
- async function decide(ask, kind, label, options, stated) {
1153
- if (options.length === 0) throw new NothingOffered(label);
1154
- return byName(ask, kind, label, options) ?? twoSystems(ask, kind, label, options, stated);
1155
351
  }
1156
352
 
1157
353
  // src/surfaces/canvas/change.ts
1158
354
  var Unapplicable = class extends Error {
1159
355
  };
1160
- function isRecord2(value) {
356
+ function isRecord(value) {
1161
357
  return typeof value === "object" && value !== null && !Array.isArray(value);
1162
358
  }
1163
359
  var present = (value) => value !== void 0 && value !== null;
1164
- function readingOf(index, name, stated) {
1165
- if (!isRecord2(stated)) {
1166
- throw new InvalidInput(`change ${index + 1}: \`${name}\` is an object of names`);
1167
- }
1168
- return Object.fromEntries(
1169
- READING_SLOTS.flatMap((slot) => {
1170
- const value = stated[slot];
1171
- return typeof value === "string" ? [[slot, value]] : [];
1172
- })
1173
- );
1174
- }
1175
360
  function parseChanges(input) {
1176
361
  const { changes } = input;
1177
- if (!Array.isArray(changes)) throw new InvalidInput("`changes` is a list of changes");
362
+ if (!Array.isArray(changes) || changes.length === 0) {
363
+ throw new InvalidInput("`changes` is a list of one or more changes");
364
+ }
1178
365
  return changes.map((entry, index) => {
1179
- if (!isRecord2(entry) || typeof entry.request !== "string") {
1180
- throw new InvalidInput(`change ${index + 1} needs \`request\`: the developer's own words`);
1181
- }
1182
- if (!present(entry.modelReading)) {
1183
- throw new InvalidInput(
1184
- `change ${index + 1} needs \`modelReading\`: your own reading of the change, an object of the names you stated`
1185
- );
366
+ const which = `change ${index + 1}`;
367
+ if (!isRecord(entry)) throw new InvalidInput(`${which} is an object`);
368
+ const operation = OPERATIONS.find((each) => each.id === entry.operation);
369
+ if (operation === void 0) {
370
+ const ids = OPERATIONS.map((each) => each.id).join(", ");
371
+ throw new InvalidInput(`${which} needs \`operation\`: one of ${ids}`);
1186
372
  }
1187
- const alternative = present(entry.alternativeReading) ? { alternative: readingOf(index, "alternativeReading", entry.alternativeReading) } : {};
373
+ const names = STATED_SLOTS.flatMap((slot) => {
374
+ const name = entry[slot];
375
+ if (!present(name) || name === "") return [];
376
+ if (typeof name !== "string") {
377
+ throw new InvalidInput(`${which}: \`${slot}\` is a name, as the canvas lists it`);
378
+ }
379
+ return [[slot, name]];
380
+ });
1188
381
  return {
1189
- request: entry.request,
1190
- values: [entry.value].filter(present),
1191
- reading: readingOf(index, "modelReading", entry.modelReading),
1192
- ...alternative
382
+ operation,
383
+ stated: Object.fromEntries(names),
384
+ value: present(entry.value) ? entry.value : void 0
1193
385
  };
1194
386
  });
1195
387
  }
1196
- function inputEdit(canvas, instance, inputName) {
1197
- const state = (of) => bindingOf(of, instance.scope, instance.name, inputName);
1198
- return {
1199
- target: () => ({ scope: instance.scope, instance: instance.name, input: inputName }),
1200
- before: state(canvas),
1201
- after: state
1202
- };
388
+ var LISTED = 12;
389
+ function listed(names) {
390
+ const kept = names.slice(0, LISTED);
391
+ const more = names.length - kept.length;
392
+ return [...kept, ...more > 0 ? [`and ${more} more`] : []].join(", ");
1203
393
  }
1204
- function instanceEdit(canvas, instance, nameAfter) {
1205
- return {
1206
- target: () => ({ scope: instance.scope, instance: instance.name }),
1207
- before: presenceOf(canvas, instance.scope, instance.name),
1208
- after: (of) => presenceOf(of, instance.scope, nameAfter)
1209
- };
394
+ var candidates = (names) => `Candidates: ${listed(names)}.`;
395
+ var listedBy = (slot) => slot === "module" ? "registry" : "canvas";
396
+ function unresolvedText(slot, label, unresolved, instead) {
397
+ switch (unresolved.kind) {
398
+ case "missing":
399
+ return `this change states no \`${slot}\`. ${instead}`;
400
+ case "none":
401
+ return `no ${label} is named \`${unresolved.stated}\`. ${instead}`;
402
+ case "several":
403
+ return `\`${unresolved.stated}\` names more than one ${label}: ${listed(unresolved.names)}. Name one as the ${listedBy(slot)} lists it.`;
404
+ }
405
+ }
406
+ var nothingOffered = (label) => `the canvas offers no ${label} for this change.`;
407
+ function reasons(each) {
408
+ return each.map((why, i) => i === 0 ? why : why[0].toUpperCase() + why.slice(1)).join(" ");
1210
409
  }
1211
- function given(values, what) {
1212
- if (values.length === 0) {
1213
- throw new Unapplicable(`this change needs ${what}: pass it in \`value\``);
410
+ var whyOf = (picked) => "why" in picked ? [picked.why] : [];
411
+ function given(change, what) {
412
+ if (change.value === void 0) {
413
+ throw new Unapplicable(`this change needs ${what}: pass it in \`value\`.`);
1214
414
  }
1215
- return values[0];
415
+ return change.value;
1216
416
  }
1217
- function givenName(values, what) {
1218
- const name = given(values, what);
1219
- if (typeof name !== "string") throw new Unapplicable(`${what} is text: pass it in \`value\``);
417
+ function givenName(change, what) {
418
+ const name = given(change, what);
419
+ if (typeof name !== "string") throw new Unapplicable(`${what} is text: pass it in \`value\`.`);
1220
420
  return name;
1221
421
  }
422
+ function variableName(text2) {
423
+ return text2.replace(/^var\./, "");
424
+ }
1222
425
  var EVERY_MODE = ["empty", "literal", "variable", "expression", "wired"];
1223
- async function pickInput({ canvas, pick }, modes) {
1224
- const offered2 = (instance2) => instance2.inputs.filter((input2) => modes.includes(input2.mode));
1225
- const instance = await pick(
1226
- "instance",
1227
- "instance",
1228
- instanceOptions(canvas.instances.filter((each) => offered2(each).length > 0))
1229
- );
1230
- const input = await pick("input", "input", inputOptions(instance, offered2(instance)));
426
+ function pickInput({ canvas, pick }, modes, offered) {
427
+ const instance = pick("instance", "instance", instanceOptions(canvas.instances));
428
+ const inputs = instance.inputs.filter((input2) => modes.includes(input2.mode));
429
+ const input = pick("input", offered(instance), pinOptions(inputs));
1231
430
  return { instance, input };
1232
431
  }
1233
432
  function updateInput(instance, input, binding) {
@@ -1244,164 +443,256 @@ function updateInput(instance, input, binding) {
1244
443
  };
1245
444
  }
1246
445
  var CATALOG_LIMIT = 500;
446
+ var SEARCH = "Find it with lace_search_module_registry and name it as `author/name`.";
447
+ function moduleRef(stated) {
448
+ const at = stated.lastIndexOf("@");
449
+ if (at < 1) return { ref: stated, query: stated.split("/").at(-1) ?? "" };
450
+ const ref = stated.slice(0, at);
451
+ const version = stated.slice(at + 1);
452
+ if (version === "") {
453
+ throw new Unapplicable(
454
+ "`module` ends in `@` with no version after it. Name the version, as `author/name@version`, or leave out `@` to place the version the registry lists."
455
+ );
456
+ }
457
+ return { ref, query: ref.split("/").at(-1) ?? "", version };
458
+ }
1247
459
  var place = {
1248
460
  id: "place",
461
+ text: "place: add a registry module to the canvas as a new instance",
462
+ slots: ["module"],
1249
463
  takesValue: false,
1250
- async plan({ canvas, request, ports, pick, note }) {
1251
- const [query] = moduleReferences(request).map((reference) => reference.split("/").slice(-1)[0]);
1252
- const listing = await runCommand(ports.commands, "registry list", {
1253
- axis: "module",
1254
- limit: CATALOG_LIMIT,
1255
- query
1256
- });
464
+ async plan({ change, ports, signal, name, note }) {
465
+ const stated = change.stated.module === void 0 ? void 0 : moduleRef(change.stated.module);
466
+ const version = stated?.version;
467
+ if (stated === void 0 || stated.query === "") {
468
+ throw new Unapplicable(
469
+ unresolvedText("module", "registry module", { kind: "missing" }, SEARCH)
470
+ );
471
+ }
472
+ const listing = await cancellable(
473
+ () => runCommand(
474
+ ports.commands,
475
+ "registry list",
476
+ { axis: "module", limit: CATALOG_LIMIT, query: stated.query },
477
+ signal
478
+ ),
479
+ signal
480
+ );
1257
481
  if (listing.failed !== void 0) throw new Error(listing.failed.text);
1258
- for (const document of listing.documents) {
1259
- if (document.truncated) {
1260
- note(
1261
- `The registry listing was cut at ${CATALOG_LIMIT} modules, so the module meant may not have been a candidate. Name it as \`author/name\`, or find it with lace_search_module_registry.`
1262
- );
1263
- }
482
+ if (listing.documents.some((document) => document.truncated)) {
483
+ note(
484
+ `The registry listing was cut at ${CATALOG_LIMIT} modules, so the module meant may not have been a candidate. Name it as \`author/name\`, or find it with lace_search_module_registry.`
485
+ );
1264
486
  }
1265
- const rows = listing.documents.flatMap((document) => document.items);
1266
- const row = await pick("module", "registry module", moduleOptions(rows));
1267
- const placed = (result) => result.created.map((ref) => ref.id).join(", ");
487
+ const module2 = name(
488
+ "module",
489
+ stated.ref,
490
+ moduleOptions(listing.documents.flatMap((document) => document.items))
491
+ );
492
+ if (module2.kind !== "one") {
493
+ throw new Unapplicable(unresolvedText("module", "registry module", module2, SEARCH));
494
+ }
495
+ const row = module2.value;
1268
496
  return {
1269
497
  action: {
1270
- place_module: { author: row.author, name: row.name, version: row.version }
498
+ place_module: { author: row.author, name: row.name, version: version ?? row.version }
1271
499
  },
1272
- summary: (result) => `placed ${moduleId(row)} ${row.version} as ${placed(result)}`,
1273
- target: (result) => ({ scope: canvas.entry, instance: placed(result) }),
1274
- before: null,
1275
- after: (of, result) => result.created.map((ref) => presenceOf(of, ref.scope, ref.id)).find((presence) => presence !== null) ?? null
500
+ summary: (result) => `placed ${moduleId(row)} ${version === void 0 ? row.version : withhold(version, change.value)} as ${result.created.map((ref) => ref.id).join(", ")}`
1276
501
  };
1277
502
  }
1278
503
  };
504
+ function autoConnect(canvas, source, target, ends, note) {
505
+ const between = (reading) => reading.wires.filter((wire) => wire.source === source.id && wire.target === target.id).map(
506
+ (wire) => connectionId(
507
+ pinRef(wire.source, wire.source_output),
508
+ pinRef(wire.target, wire.target_input)
509
+ )
510
+ );
511
+ const before = new Set(between(canvas));
512
+ return {
513
+ action: { auto_connect: ends },
514
+ summary(result, after) {
515
+ const wired = between(after).filter((wire) => !before.has(wire));
516
+ const ties = result.ties.map(
517
+ (pair) => connectionId(pinRef(source.id, pair.output), pinRef(target.id, pair.input))
518
+ );
519
+ const choose = "Send it again naming the `output` and the `input` the developer means.";
520
+ if (wired.length === 0) {
521
+ throw new Unapplicable(
522
+ ties.length > 0 ? `more than one pair fits equally well, so nothing was wired: ${listed(ties)}. ${choose}` : `the engine wired nothing from ${source.id} into ${target.id}.`
523
+ );
524
+ }
525
+ if (ties.length > 0) {
526
+ note(`Not connected, more than one pair fits equally well: ${listed(ties)}. ${choose}`);
527
+ }
528
+ return `connected ${source.id} to ${target.id}: ${wired.join(", ")}`;
529
+ }
530
+ };
531
+ }
1279
532
  var connect = {
1280
533
  id: "connect",
534
+ text: "connect: wire an output of one instance into an input of another",
535
+ slots: ["sourceInstance", "output", "targetInstance", "input"],
1281
536
  takesValue: false,
1282
- async plan({ canvas, ports, pick }) {
1283
- const source = await pick("instance", "source instance", sourceOptions(canvas.instances));
1284
- const target = await pick(
1285
- "instance",
1286
- "target instance",
1287
- targetOptions(canvas.instances, source)
1288
- );
1289
- const scored = await ports.editor.wiringCandidates({
1290
- scope: source.scope,
537
+ async plan({ canvas, change, ports, signal, choose, note }) {
538
+ const instances = instanceOptions(canvas.instances);
539
+ const sourcePicked = choose("sourceInstance", "instance", instances);
540
+ const targetPicked = choose("targetInstance", "instance", instances);
541
+ if (!("value" in sourcePicked) || !("value" in targetPicked)) {
542
+ throw new Unapplicable(reasons([...whyOf(sourcePicked), ...whyOf(targetPicked)]));
543
+ }
544
+ const [source, target] = [sourcePicked.value, targetPicked.value];
545
+ if (source.id === target.id) {
546
+ throw new Unapplicable(
547
+ `\`sourceInstance\` and \`targetInstance\` both name ${source.id}: a connect wires one instance into another.`
548
+ );
549
+ }
550
+ const ends = {
551
+ scope: target.scope,
552
+ source_scope: source.scope,
1291
553
  source: source.name,
1292
554
  target: target.name
1293
- });
1294
- const pair = await pick("connection", "connection", connectionOptions(source, target, scored));
555
+ };
556
+ const stated = { output: change.stated.output, input: change.stated.input };
557
+ if (stated.output === void 0 && stated.input === void 0) {
558
+ return autoConnect(canvas, source, target, ends, note);
559
+ }
560
+ const output = stated.output === void 0 ? void 0 : choose("output", `output of ${source.id}`, pinOptions(source.outputs));
561
+ const input = stated.input === void 0 ? void 0 : choose("input", `input of ${target.id}`, pinOptions(target.inputs));
562
+ const whys = [...output ? whyOf(output) : [], ...input ? whyOf(input) : []];
563
+ if (output === void 0 || input === void 0) {
564
+ const [named, unnamed] = output === void 0 ? ["input", "output"] : ["output", "input"];
565
+ const scored = await cancellable(
566
+ () => ports.editor.wiringCandidates({
567
+ scope: ends.scope,
568
+ sourceScope: ends.source_scope,
569
+ source: ends.source,
570
+ target: ends.target
571
+ }),
572
+ signal
573
+ );
574
+ const pairs = pairListing(source, target, scored, {
575
+ ...output && "value" in output ? { output: output.value.name } : {},
576
+ ...input && "value" in input ? { input: input.value.name } : {}
577
+ });
578
+ whys.push(
579
+ `this change states \`${named}\` and no \`${unnamed}\`: state both, or neither to wire the two instances as the canvas does. ${pairs.length > 0 ? candidates(pairs) : `The engine's matcher pairs no output of ${source.id} with an input of ${target.id}.`}`
580
+ );
581
+ throw new Unapplicable(reasons(whys));
582
+ }
583
+ if (!("value" in output) || !("value" in input)) throw new Unapplicable(reasons(whys));
584
+ const [from, to] = [output.value.name, input.value.name];
1295
585
  return {
1296
- action: {
1297
- connect: {
1298
- scope: target.scope,
1299
- source_scope: source.scope,
1300
- source: source.name,
1301
- target: target.name,
1302
- source_output: pair.output,
1303
- target_input: pair.input
1304
- }
1305
- },
1306
- summary: () => `connected ${source.id}.${pair.output} \u2192 ${target.id}.${pair.input}`,
1307
- ...inputEdit(canvas, target, pair.input)
586
+ action: { connect: { ...ends, source_output: from, target_input: to } },
587
+ summary: () => `connected ${connectionId(pinRef(source.id, from), pinRef(target.id, to))}`
1308
588
  };
1309
589
  }
1310
590
  };
1311
591
  var disconnect = {
1312
592
  id: "disconnect",
593
+ text: "disconnect: remove the wire into an instance's input",
594
+ slots: ["instance", "input"],
1313
595
  takesValue: false,
1314
596
  async plan(resolving) {
1315
- const { instance, input } = await pickInput(resolving, ["wired"]);
597
+ const { instance, input } = pickInput(resolving, ["wired"], (of) => `wired input of ${of.id}`);
1316
598
  return {
1317
599
  action: {
1318
600
  disconnect: { scope: instance.scope, target: instance.name, input_name: input.name }
1319
601
  },
1320
- summary: () => `disconnected ${instance.id}.${input.name}`,
1321
- ...inputEdit(resolving.canvas, instance, input.name)
602
+ summary: () => `disconnected ${pinRef(instance.id, input.name)}`
1322
603
  };
1323
604
  }
1324
605
  };
1325
606
  var set = {
1326
607
  id: "set",
608
+ text: "set: give an input of an instance a literal value",
609
+ slots: ["instance", "input"],
1327
610
  takesValue: true,
1328
611
  async plan(resolving) {
1329
- const value = given(resolving.values, "the value the developer gave");
1330
- const { instance, input } = await pickInput(resolving, EVERY_MODE);
612
+ const value = given(resolving.change, "the value the developer gave");
613
+ const { instance, input } = pickInput(resolving, EVERY_MODE, (of) => `input of ${of.id}`);
1331
614
  const shown = input.sensitive ? "(sensitive, value withheld)" : `= ${JSON.stringify(value)}`;
1332
615
  return {
1333
- action: updateInput(instance, input, { mode: import_engine4.InputMode.INPUT_MODE_LITERAL, value }),
1334
- summary: () => `set ${instance.id}.${input.name} ${shown}`,
1335
- ...inputEdit(resolving.canvas, instance, input.name)
616
+ action: updateInput(instance, input, { mode: import_engine3.InputMode.INPUT_MODE_LITERAL, value }),
617
+ summary: () => `set ${pinRef(instance.id, input.name)} ${shown}`
1336
618
  };
1337
619
  }
1338
620
  };
1339
621
  var bind = {
1340
622
  id: "bind",
623
+ text: "bind: make an input of an instance take its value from a variable of the module (`var.<name>`), so the module's caller sets it",
624
+ slots: ["instance", "input"],
1341
625
  takesValue: true,
1342
626
  async plan(resolving) {
1343
- const variable = variableName(givenName(resolving.values, "the variable's name"));
1344
- const { instance, input } = await pickInput(resolving, EVERY_MODE);
627
+ const variable = variableName(givenName(resolving.change, "the variable's name"));
628
+ const { instance, input } = pickInput(resolving, EVERY_MODE, (of) => `input of ${of.id}`);
1345
629
  return {
1346
- action: updateInput(instance, input, { mode: import_engine4.InputMode.INPUT_MODE_VARIABLE, variable }),
1347
- summary: () => `bound ${instance.id}.${input.name} to var.${variable}`,
1348
- ...inputEdit(resolving.canvas, instance, input.name)
630
+ action: updateInput(instance, input, { mode: import_engine3.InputMode.INPUT_MODE_VARIABLE, variable }),
631
+ summary: () => `bound ${pinRef(instance.id, input.name)} to var.${variable}`
1349
632
  };
1350
633
  }
1351
634
  };
1352
635
  var clear = {
1353
636
  id: "clear",
637
+ text: "clear: unset an input of an instance, removing the value, variable or expression it holds",
638
+ slots: ["instance", "input"],
1354
639
  takesValue: false,
1355
640
  async plan(resolving) {
1356
- const { instance, input } = await pickInput(resolving, ["literal", "variable", "expression"]);
641
+ const { instance, input } = pickInput(
642
+ resolving,
643
+ ["literal", "variable", "expression"],
644
+ (of) => `input of ${of.id} that holds a value`
645
+ );
1357
646
  return {
1358
- action: updateInput(instance, input, { mode: import_engine4.InputMode.INPUT_MODE_EMPTY }),
1359
- summary: () => `cleared ${instance.id}.${input.name}`,
1360
- ...inputEdit(resolving.canvas, instance, input.name)
647
+ action: updateInput(instance, input, { mode: import_engine3.InputMode.INPUT_MODE_EMPTY }),
648
+ summary: () => `cleared ${pinRef(instance.id, input.name)}`
1361
649
  };
1362
650
  }
1363
651
  };
1364
652
  var rename = {
1365
653
  id: "rename",
654
+ text: "rename: give an instance a new name",
655
+ slots: ["instance"],
1366
656
  takesValue: true,
1367
- async plan({ canvas, values, pick }) {
1368
- const name = givenName(values, "the new name");
1369
- const instance = await pick("instance", "instance", instanceOptions(canvas.instances));
657
+ async plan({ canvas, change, pick }) {
658
+ const name = givenName(change, "the new name");
659
+ const instance = pick("instance", "instance", instanceOptions(canvas.instances));
1370
660
  return {
1371
661
  action: {
1372
662
  rename_instance: { scope: instance.scope, old_id: instance.name, new_id: name }
1373
663
  },
1374
- summary: () => `renamed ${instance.id} to ${name}`,
1375
- ...instanceEdit(canvas, instance, name)
664
+ summary: () => `renamed ${instance.id} to ${name}`
1376
665
  };
1377
666
  }
1378
667
  };
1379
668
  var remove = {
1380
669
  id: "delete",
670
+ text: "delete: remove an instance from the canvas",
671
+ slots: ["instance"],
1381
672
  takesValue: false,
1382
673
  async plan({ canvas, pick }) {
1383
- const instance = await pick("instance", "instance", instanceOptions(canvas.instances));
674
+ const instance = pick("instance", "instance", instanceOptions(canvas.instances));
1384
675
  return {
1385
676
  action: { delete_instance: { scope: instance.scope, instance_id: instance.name } },
1386
- summary: () => `deleted ${instance.id}`,
1387
- ...instanceEdit(canvas, instance, instance.name)
677
+ summary: () => `deleted ${instance.id}`
1388
678
  };
1389
679
  }
1390
680
  };
1391
681
  var ungroup = {
1392
682
  id: "ungroup",
683
+ text: "ungroup: dissolve a group, moving the instances inside it up beside it",
684
+ slots: ["instance"],
1393
685
  takesValue: false,
1394
686
  async plan({ canvas, pick }) {
1395
687
  const groups = new Set(canvas.groups.map((group2) => group2.id));
1396
- const group = await pick(
688
+ const group = pick(
1397
689
  "instance",
1398
690
  "group",
1399
691
  instanceOptions(canvas.instances.filter((instance) => groups.has(instance.id)))
1400
692
  );
1401
693
  return {
1402
694
  action: { ungroup: { scope: group.scope, group_id: group.name } },
1403
- summary: () => `ungrouped ${group.id}`,
1404
- ...instanceEdit(canvas, group, group.name)
695
+ summary: () => `ungrouped ${group.id}`
1405
696
  };
1406
697
  }
1407
698
  };
@@ -1416,362 +707,215 @@ var OPERATIONS = [
1416
707
  remove,
1417
708
  ungroup
1418
709
  ];
1419
- var Fell = class extends Error {
1420
- constructor(label) {
1421
- super(`the ${label} fell to System Two`);
1422
- this.label = label;
1423
- }
1424
- };
1425
- function heldMore(decisions) {
1426
- return decisions.some(
1427
- (decision) => decision.others.length > 0 || decision.kind === "steps" && decision.option.value === "several"
1428
- );
1429
- }
1430
- var twoSystems2 = (decision) => decision.composed !== null;
1431
- var composedOf = (decisions) => decisions.flatMap((decision) => decision.composed === null ? [] : [decision.composed]);
1432
- function movedText(operation, error) {
1433
- return error instanceof Fell || error instanceof Undecided ? `the ${error.label} under Lace's ${operation} fell to your reading` : `Lace's ${operation} did not resolve: ${errorText(error)}`;
1434
- }
1435
- function statedFacts(names2, reading) {
1436
- const fact = (slot, name) => slot === "operation" ? OPERATIONS.some((operation) => operation.id === name) : slot === "module" ? moduleReferences(name)[0] === name : names2.has(name);
1437
- return Object.fromEntries(
1438
- statedSlots(reading).flatMap((slot) => {
1439
- const name = reading[slot];
1440
- return name !== void 0 && fact(slot, name) ? [[slot, name]] : [];
1441
- })
1442
- );
710
+ var CANCELLED = { kind: "cancelled" };
711
+ var NOT_RUN = { kind: "notRun" };
712
+ function unusedLines({ operation, stated, value }) {
713
+ const unused = slotsStated(stated).filter((slot) => !operation.slots.includes(slot));
714
+ return [
715
+ ...unused.map((slot) => `\`${slot}\` is not used by ${operation.id}.`),
716
+ ...value !== void 0 && !operation.takesValue ? [`The \`value\` sent with this change was not used: ${operation.id} takes none.`] : []
717
+ ];
1443
718
  }
1444
- var asItIs = (apply) => apply();
1445
- async function resolveAndApply(ports, own, change, call, trail, notApplied) {
719
+ async function resolveAndApply(ports, change, signal, note) {
1446
720
  const canvas = readCanvas(await latest(ports.source));
1447
- const names2 = canvasNames(canvas);
1448
- const values = [...forms(change.values), ...unnamed(names2, call)];
1449
- const statementOf = (reading) => withhold(renderReading(statedFacts(names2, reading)), values);
1450
- const statement = statementOf(change.reading);
1451
- const alternative = change.alternative === void 0 ? void 0 : { statement: statementOf(change.alternative), reading: change.alternative };
1452
- const statements = [statement, ...alternative === void 0 ? [] : [alternative.statement]];
1453
- const request = renderRequest(
1454
- change.request,
1455
- values,
1456
- statements.reduce((longest, each) => each.length > longest.length ? each : longest)
1457
- );
1458
- const rankable = !holdsValue(withhold([request, ...statements].join(" "), [...names2]), values);
1459
- const rank = ports.transport === void 0 ? void 0 : rankingClient(ports.transport).rank;
1460
- if (!rankable && rank !== void 0) {
1461
- trail.notes.push(
1462
- "This change's words or reading hold a value of the call inside a word, so Lace did not rank it."
1463
- );
1464
- }
1465
- const main = {
1466
- request,
1467
- terms: termsOf(request.split(VALUE_PLACEHOLDER).join(" ")),
1468
- statement,
1469
- reading: change.reading,
1470
- ...rankable ? { rank } : {}
721
+ const name = (slot, stated, options) => {
722
+ if (stated === void 0) return { kind: "missing" };
723
+ const resolved = resolve(options, stated);
724
+ const echoed = withhold(stated, change.value);
725
+ switch (resolved.kind) {
726
+ case "one": {
727
+ const [listedAs] = resolved.option.names;
728
+ const where = slot === "module" ? "in the registry" : "on the canvas";
729
+ if (resolved.folded) note(`Your \`${slot}\` ${echoed} is \`${listedAs}\` ${where}.`);
730
+ return { kind: "one", value: resolved.option.value };
731
+ }
732
+ case "several":
733
+ return {
734
+ kind: "several",
735
+ stated: echoed,
736
+ names: resolved.options.map((each) => each.names[0])
737
+ };
738
+ case "none":
739
+ return { kind: "none", stated: echoed };
740
+ }
741
+ };
742
+ const choose = (slot, label, options) => {
743
+ if (options.length === 0) return { why: nothingOffered(label) };
744
+ const named = name(slot, change.stated[slot], options);
745
+ if (named.kind === "one") return { value: named.value };
746
+ const offered = options.map((option) => option.names[0]);
747
+ return { why: unresolvedText(slot, label, named, candidates(offered)) };
1471
748
  };
1472
- const ask = { ...main, ...alternative === void 0 ? {} : { alternative } };
1473
- const resolvingInto = (into, trial) => ({
749
+ const resolving = {
1474
750
  canvas,
1475
- request,
1476
- values: change.values,
751
+ change,
1477
752
  ports,
1478
- async pick(kind, label, options) {
1479
- const decision = await decide(ask, kind, label, options);
1480
- into.decisions.push(decision);
1481
- if (trial && !moveStands(composedOf(into.decisions.slice(1)))) throw new Fell(label);
1482
- return decision.option.value;
753
+ signal,
754
+ name,
755
+ choose,
756
+ pick(slot, label, options) {
757
+ const picked = choose(slot, label, options);
758
+ if ("why" in picked) throw new Unapplicable(picked.why);
759
+ return picked.value;
1483
760
  },
1484
- note: (line) => into.notes.push(line)
1485
- });
1486
- const planUnder = (decision, into, trial) => {
1487
- into.decisions.push(decision);
1488
- return decision.option.value.plan(resolvingInto(into, trial));
1489
- };
1490
- const first = await decide(ask, "operation", "operation", operationOptions(OPERATIONS));
1491
- const statedOperation = operationOptions(OPERATIONS).find(
1492
- (each) => each.candidate.id === first.chat
1493
- );
1494
- const moveRule = async () => {
1495
- if (first.how !== "clm" || statedOperation === void 0 || statedOperation.value === first.option.value) {
1496
- return { operation: first.option.value, plan: await planUnder(first, trail, false) };
1497
- }
1498
- const trial = { decisions: [], notes: [] };
1499
- try {
1500
- const planned = await planUnder(first, trial, true);
1501
- trail.decisions.push(...trial.decisions);
1502
- trail.notes.push(...trial.notes);
1503
- return { operation: first.option.value, plan: planned };
1504
- } catch (error) {
1505
- trail.moved = withhold(movedText(first.option.value.id, error), change.values);
1506
- const standing = {
1507
- ...first,
1508
- option: statedOperation,
1509
- how: "chat",
1510
- composed: {
1511
- took: "chat",
1512
- taken: statedOperation.candidate.id,
1513
- clm: first.composed?.clm ?? null,
1514
- differed: false
1515
- },
1516
- alternative: first.alternative?.id === first.option.candidate.id ? null : first.alternative
1517
- };
1518
- return { operation: statedOperation.value, plan: await planUnder(standing, trail, false) };
1519
- }
761
+ note
1520
762
  };
1521
- const { operation, plan } = await moveRule();
1522
- const unread = trail.decisions.every((decision) => decision.others.length === 0);
1523
- if (unread && main.rank !== void 0 && trail.decisions.some(twoSystems2)) {
1524
- await decide(main, "steps", "steps", stepsOptions(), "one").then(
1525
- (decision) => trail.decisions.push(decision)
1526
- );
1527
- }
1528
- if (change.values.length > 0 && !operation.takesValue && !heldMore(trail.decisions)) {
1529
- trail.notes.push(
1530
- `The \`value\` sent with this change was not used: ${operation.id} takes none.`
1531
- );
1532
- }
1533
- const lace = Object.assign({}, ...trail.decisions.map((each) => each.option.slots));
1534
- const stated = statedSlots(change.reading);
1535
- for (const slot of stated.filter(
1536
- (slot2) => !trail.decisions.some(
1537
- (decision) => decision.readings.some((each) => each[slot2] === change.reading[slot2])
1538
- )
1539
- )) {
1540
- trail.notes.push(
1541
- `Your reading's ${slot} ${change.reading[slot]} is not one of Lace's candidates${slot in lace ? `; Lace read ${lace[slot]}` : ""}.`
1542
- );
1543
- }
1544
- const asked = trail.decisions.filter(
1545
- (decision) => decision.alternative?.sure === true && decision.alternative.id !== decision.option.candidate.id
1546
- );
1547
- if (asked.length > 0) {
763
+ for (const line of unusedLines(change)) note(line);
764
+ const plan = await change.operation.plan(resolving);
765
+ stopIfCancelled(signal);
766
+ const result = await ports.editor.apply([plan.action]);
767
+ if (!result.success) {
768
+ const refusals = result.errors.map((error) => error.message).join("; ");
1548
769
  return {
1549
- kind: "asked",
1550
- lace,
1551
- alternative: Object.assign(
1552
- {},
1553
- ...trail.decisions.map(
1554
- (decision) => asked.includes(decision) ? decision.alternative?.slots : decision.option.slots
1555
- )
1556
- )
770
+ kind: "notApplied",
771
+ why: `the engine refused it: ${withhold(refusals, change.value)}`
1557
772
  };
1558
773
  }
1559
- const result = await own(() => ports.editor.apply([plan.action]));
1560
- if (!result.success) {
1561
- const reasons = result.errors.map((error) => error.message).join("; ");
1562
- return notApplied(`the engine refused it: ${reasons}`);
1563
- }
1564
774
  const after = readCanvas(await latest(ports.source));
1565
- const record = {
1566
- id: crypto.randomUUID(),
1567
- target: plan.target(result),
1568
- before: plan.before,
1569
- after: plan.after(after, result),
1570
- ...result.revision === void 0 ? {} : { revision: result.revision },
1571
- questions: trail.decisions.map((decision) => ({
1572
- kind: decision.kind,
1573
- candidates: decision.candidates.map((candidate) => candidate.id)
1574
- })),
1575
- reported: false
1576
- };
1577
- return {
1578
- kind: "applied",
1579
- summary: plan.summary(result),
1580
- record,
1581
- canvas: after,
1582
- withheld: unnamed(names2, call)
1583
- };
775
+ return { kind: "applied", summary: plan.summary(result, after) };
1584
776
  }
1585
- async function runChange(ports, own, change, call, trail) {
1586
- const notApplied = (why) => ({
1587
- kind: "notApplied",
1588
- why: withhold(why, change.values)
1589
- });
777
+ async function runChange(ports, change, signal, note) {
1590
778
  try {
1591
- return await resolveAndApply(ports, own, change, call, trail, notApplied);
779
+ return await resolveAndApply(ports, change, signal, note);
1592
780
  } catch (error) {
1593
- if (error instanceof import_engine4.ApplyUnobservedError) {
1594
- return { kind: "unobserved", end: withhold(endText(error.end), change.values) };
1595
- }
1596
- if (error instanceof Undecided) {
1597
- trail.undecided = error;
1598
- const candidates = error.candidates.map((candidate) => candidate.id).join(", ");
1599
- return notApplied(
1600
- `the ${error.label} was not decided: ${rankingText(error.ranking)}, and your reading names none of its candidates: ${candidates}. Send this change again with \`modelReading\` naming one as the canvas lists it.`
1601
- );
781
+ if (error instanceof import_engine3.ApplyUnobservedError) {
782
+ return { kind: "unobserved", end: withhold(endText(error.end), change.value) };
1602
783
  }
1603
- return notApplied(errorText(error));
784
+ if (error instanceof Cancelled) return CANCELLED;
785
+ if (error instanceof Unapplicable) return { kind: "notApplied", why: error.message };
786
+ return { kind: "notApplied", why: withhold(errorText(error), change.value) };
1604
787
  }
1605
788
  }
1606
- function rankingText(ranking2) {
1607
- if (ranking2.ranked === null) return ranking2.failed;
1608
- const [first] = ranking2.ranked.scores;
1609
- const read2 = first?.id === NONE_CANDIDATE_ID ? `read ${NONE_OVER} first` : `ranked ${first?.id} first`;
1610
- return `Lace was not sure, ${read2}`;
1611
- }
1612
- function decisionLine(decision, moved2) {
1613
- const also = `the request also names ${decision.others.join(", ")}`;
1614
- const named2 = {
1615
- exact: ["named in the request"],
1616
- unique: ["named in the request, ignoring case"],
1617
- first: ["named in the request first", also],
1618
- agreed: ["named in the request and in your reading", also]
1619
- };
1620
- const basis = decision.how === "clm" ? [
1621
- `Lace's pick of ${decision.offered}`,
1622
- ...decision.offered > decision.candidates.length ? [`ranked in parts, as ${decision.offered} candidates are more than one ranking holds`] : [],
1623
- ...decision.over.map((candidate) => `over ${candidate}`),
1624
- ...decision.composed?.differed ? [`your reading named ${decision.chat}`] : []
1625
- ] : decision.how === "chat" ? [
1626
- "your reading",
1627
- moved2 !== void 0 && decision.kind === "operation" ? moved2 : decision.ranking === null ? "Lace did not rank" : rankingText(decision.ranking)
1628
- ] : named2[decision.how];
1629
- return ` ${decision.label}: ${decision.option.candidate.id} (${basis.join(", ")})`;
1630
- }
1631
- function outcomeLines(number, outcome, trail) {
789
+ function outcomeLine(number, outcome) {
1632
790
  const head = `Change ${number}:`;
1633
- const lines = trail.decisions.map((decision) => decisionLine(decision, trail.moved));
1634
791
  switch (outcome.kind) {
1635
- case "applied": {
1636
- const moved2 = trail.moved === void 0 ? "" : " Lace's operation did not stand and yours did, marked below.";
1637
- const unsure = trail.decisions.some(
1638
- (decision) => decision.how === "chat" && (trail.moved === void 0 || decision.kind !== "operation")
1639
- );
1640
- const stood = unsure ? " Where Lace was not sure, your reading stood, marked below." : "";
1641
- const differed = trail.decisions.some((decision) => decision.composed?.differed) ? " Lace's reading differed from yours and stood, marked below: tell the developer." : "";
1642
- const others = trail.decisions.flatMap((decision) => decision.others);
1643
- const unapplied = others.length > 0 ? `; nothing was applied for ${others.join(", ")}` : "";
1644
- const more = heldMore(trail.decisions) ? ` This entry held more than one change and only this one was applied${unapplied}. Send the rest, one entry per change.` : "";
1645
- return [`${head} applied. ${outcome.summary}.${more}${moved2}${stood}${differed}`, ...lines];
1646
- }
1647
- case "asked":
1648
- return [
1649
- `${head} not applied. Lace is sure your alternative reading means another change than the one it decided.`,
1650
- ` Your reading: ${renderReading(outcome.lace)}`,
1651
- ` Your alternative reading: ${renderReading(outcome.alternative)}`,
1652
- " Ask the developer which is meant, then send that one."
1653
- ];
792
+ case "applied":
793
+ return `${head} applied. ${outcome.summary}.`;
1654
794
  case "notApplied":
1655
- return [`${head} not applied. Reason: ${outcome.why}`, ...lines];
795
+ return `${head} not applied. Reason: ${outcome.why}`;
796
+ case "cancelled":
797
+ return `${head} not applied. The call was cancelled before it applied.`;
1656
798
  case "unobserved":
1657
- return [
1658
- `${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.`,
1659
- ...lines
1660
- ];
799
+ return `${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.`;
800
+ case "notRun":
801
+ return `${head} not run. The session's stream ended before it, so it was not sent.`;
1661
802
  }
1662
803
  }
1663
- function questionOf(decision) {
1664
- const taken = decision.option.candidate.id;
1665
- return {
1666
- kind: decision.kind,
1667
- capture_id: asAsked(decision.ranking)?.capture_id ?? null,
1668
- chat: decision.chat,
1669
- clm: decision.composed?.clm ?? null,
1670
- took: decision.composed === null ? "named" : decision.composed.took,
1671
- taken
1672
- };
1673
- }
1674
- function undecidedOf(undecided) {
1675
- const ranked = asAsked(undecided.ranking);
1676
- const pick = ranked === null ? void 0 : pickOf(ranked.scores);
1677
- return {
1678
- kind: undecided.kind,
1679
- capture_id: ranked?.capture_id ?? null,
1680
- chat: null,
1681
- clm: pick === void 0 ? null : { id: pick.id, rightness: pick.rightness },
1682
- took: "chat",
1683
- taken: null
1684
- };
1685
- }
1686
- function reportOf(id, trail, applied, asked) {
1687
- const questions = [
1688
- ...trail.decisions.map(questionOf),
1689
- ...trail.undecided === void 0 ? [] : [undecidedOf(trail.undecided)]
1690
- ];
1691
- return questions.some((question) => question.took !== "named") ? { id, surface: "canvas", questions, applied, asked } : void 0;
1692
- }
1693
- async function applyChanges(ports, changes, own = asItIs) {
1694
- const call = changes.flatMap((change) => change.values);
1695
- const client = ports.transport === void 0 ? void 0 : rankingClient(ports.transport);
804
+ async function applyChanges(ports, changes, signal) {
1696
805
  const lines = [];
1697
- let applied = [];
1698
- const reports = [];
1699
- let last;
806
+ let ended = false;
1700
807
  for (const [index, change] of changes.entries()) {
1701
- const trail = { decisions: [], notes: [] };
1702
- const outcome = await runChange(ports, own, change, call, trail);
808
+ const notes = [];
809
+ const outcome = ended ? NOT_RUN : signal?.aborted ? CANCELLED : await runChange(ports, change, signal, (line) => notes.push(line));
810
+ ended = ended || outcome.kind === "unobserved";
1703
811
  lines.push(
1704
- ...outcomeLines(index + 1, outcome, trail),
1705
- ...trail.notes.map((line) => ` ${line}`)
812
+ outcomeLine(index + 1, outcome),
813
+ ...outcome.kind === "cancelled" || outcome.kind === "notRun" ? [] : notes.map((line) => ` ${line}`)
1706
814
  );
1707
- if (outcome.kind === "applied") {
1708
- const { canvas } = outcome;
1709
- const before = last;
1710
- applied = [
1711
- ...before === void 0 ? [] : applied.map((each) => ({ ...each, record: follow(each.record, before, canvas) })),
1712
- { record: outcome.record, withheld: outcome.withheld, trail }
1713
- ];
1714
- last = canvas;
1715
- } else if (outcome.kind !== "unobserved") {
1716
- const report = reportOf(crypto.randomUUID(), trail, null, outcome.kind === "asked");
1717
- if (report !== void 0) reports.push(report);
1718
- }
1719
815
  }
1720
- const left = last;
1721
- const records = left === void 0 ? [] : applied.map(({ record, withheld, trail }) => {
1722
- const settled = { ...record, after: targetState(left, record) };
1723
- const report = reportOf(record.id, trail, appliedText(settled, withheld), false);
1724
- if (report !== void 0) reports.push(report);
1725
- return { ...settled, reported: report !== void 0 && client !== void 0 };
1726
- });
1727
- if (client !== void 0) await Promise.all(reports.map((report) => client.decision(report)));
1728
- return { text: lines.join("\n"), applied: records };
816
+ return lines.join("\n");
1729
817
  }
1730
- function appliedText(record, withheld) {
1731
- return withhold(
1732
- `${renderTarget(record.target)}: ${renderState(record.before)} \u2192 ${renderState(record.after)}`,
1733
- withheld
1734
- );
818
+
819
+ // src/surfaces/canvas/render.ts
820
+ var import_proto2 = require("@lace-cloud/proto");
821
+ function inputText(input) {
822
+ if (input.mode === "empty") {
823
+ return `${input.name} (${input.required ? "required, " : ""}not set)`;
824
+ }
825
+ if (input.mode === "wired") return `${input.name} (wired)`;
826
+ if (input.sensitive) return `${input.name} (sensitive, value withheld)`;
827
+ const shown = {
828
+ literal: JSON.stringify(input.value),
829
+ variable: `var.${input.variable}`,
830
+ expression: `${input.expression}`
831
+ };
832
+ return `${input.name} = ${shown[input.mode]}`;
833
+ }
834
+ function instanceLines(instance) {
835
+ return [
836
+ `- ${instance.id}: module ${instance.module}`,
837
+ ` inputs: [${instance.inputs.map(inputText).join("; ")}]`,
838
+ ` outputs: [${instance.outputs.map((output) => output.name).join(", ")}]`
839
+ ];
840
+ }
841
+ function unsetRequired(instance) {
842
+ return instance.inputs.filter((input) => input.required && input.mode === "empty").map((input) => `- ${pinRef(instance.id, input.name)}`);
843
+ }
844
+ function diagnosticLine({ diagnostic, node }) {
845
+ const scoped = diagnostic.module_key === void 0 ? diagnostic.instance_id : `${diagnostic.instance_id} in module ${diagnostic.module_key}`;
846
+ const instance = node ?? (diagnostic.instance_id === void 0 ? void 0 : scoped);
847
+ const where = [
848
+ ["instance", instance],
849
+ ["input", diagnostic.input_name],
850
+ ["address", diagnostic.address],
851
+ ["file", diagnostic.file],
852
+ ["line", diagnostic.line]
853
+ ].filter(([, value]) => value !== void 0).map(([label, value]) => `${label} ${value}`);
854
+ return `- ${[`${diagnostic.severity}: ${diagnostic.message}`, ...where].join("; ")}`;
855
+ }
856
+ var yesNo = (flag) => flag ? "yes" : "no";
857
+ function section(title, lines) {
858
+ return [`${title} (${lines.length}):`, ...lines];
859
+ }
860
+ function renderCanvas(source) {
861
+ const canvas = readCanvas(source);
862
+ return [
863
+ `Canvas of module ${canvas.module}`,
864
+ `Instances (${canvas.instances.length}):`,
865
+ ...canvas.instances.flatMap(instanceLines),
866
+ ...section(
867
+ "Wires",
868
+ canvas.wires.map(
869
+ (wire) => `- ${connectionId(
870
+ wire.source_output ? pinRef(wire.source, wire.source_output) : (0, import_proto2.callText)(wire.source),
871
+ pinRef(wire.target, wire.target_input)
872
+ )}`
873
+ )
874
+ ),
875
+ ...section("Required inputs not set", canvas.instances.flatMap(unsetRequired)),
876
+ ...section(
877
+ "Groups",
878
+ canvas.groups.map((group) => `- ${group.id}: ${group.members.join(", ")}`)
879
+ ),
880
+ ...section("Diagnostics", canvas.diagnostics.map(diagnosticLine)),
881
+ [
882
+ `Standing: unsaved edits: ${yesNo(source.unsaved)}`,
883
+ `saved edits not generated to Terraform: ${yesNo(source.ungenerated)}`,
884
+ `conflict with the Terraform on disk: ${yesNo(source.conflict !== null)}`,
885
+ `Terraform refused, canvas locked: ${yesNo(source.sourceRefused)}`
886
+ ].join("; ")
887
+ ].join("\n");
1735
888
  }
1736
889
 
1737
890
  // src/surfaces/canvas/canvas-tools.ts
1738
- var READING_PROPERTIES = {
1739
- operation: {
1740
- type: "string",
1741
- enum: OPERATIONS.map((operation) => operation.id),
1742
- description: OPERATIONS.map((operation) => OPERATION_TEXT[operation.id]).join("; ")
1743
- },
891
+ var STATED_PROPERTIES = {
1744
892
  instance: {
1745
893
  type: "string",
1746
- description: "The instance a set, bind, clear, disconnect, rename or delete works on, or the group an ungroup dissolves."
894
+ description: "The instance a set, bind, clear, disconnect, rename or delete works on, or the group an ungroup dissolves: its canvas path (`group.child`) or its own id."
1747
895
  },
1748
896
  input: {
1749
897
  type: "string",
1750
898
  description: "The input a set, bind, clear or disconnect works on, or a connect wires into."
1751
899
  },
1752
- sourceInstance: {
1753
- type: "string",
1754
- description: "The instance a connect wires from."
1755
- },
900
+ sourceInstance: { type: "string", description: "The instance a connect wires from." },
1756
901
  output: { type: "string", description: "The output a connect wires from." },
1757
- targetInstance: {
1758
- type: "string",
1759
- description: "The instance a connect wires into."
1760
- },
902
+ targetInstance: { type: "string", description: "The instance a connect wires into." },
1761
903
  module: {
1762
904
  type: "string",
1763
- description: "The registry module a place adds, as `author/name`."
905
+ description: "The registry module a place adds, as `author/name`, and `author/name@version` to place a version other than the one the registry lists."
1764
906
  }
1765
907
  };
1766
- var READING = { type: "object", properties: READING_PROPERTIES, additionalProperties: false };
1767
908
  var CHANGE = {
1768
909
  name: "lace_change_module_canvas",
1769
910
  title: "Change module canvas",
1770
911
  description: [
1771
- "Changes a Lace module canvas. Do not read the canvas before calling it. For each change pass the developer's own words in `request`, one entry per change: this tool resolves which operation, instances, inputs, outputs and registry modules are meant.",
1772
- "`request` carries the words and never a literal value: pass each literal the developer gave (an input's value, an instance's new name, the name of the variable an input is bound to) in `value`, one change per entry, each with its own `value`. Lace withholds `value` from what it ranks and keeps, and keeps the words of `request` as written; the tool selects and never writes a value of its own.",
1773
- "Every result of this tool carries the current canvas. On every call pass your own reading of each change in `modelReading`: always its `operation`, and any instance, input, output or registry module the developer named, as the canvas lists it once a result has shown you the canvas. Never put a value in `modelReading`. Where the words bear a second reading, pass it in `alternativeReading`.",
1774
- "Lace reads the words too and applies its own reading where it is sure, yours otherwise; where the two differ the result says so: tell the developer. When Lace is also sure of your alternative reading, nothing is applied and the result shows both: ask the developer. A change neither reading settles is not applied, and the result names the part and its candidates: send it again naming one as the canvas lists it, with the developer's own words. Do not save or generate unless the developer asked."
912
+ "Changes a Lace module canvas: places registry modules, wires and unwires instances, sets, binds and clears inputs, and renames, deletes and ungroups instances.",
913
+ "State each change as the canvas lists it: its `operation`, and each instance, input, output and registry module it works on by the name the canvas gives it.",
914
+ "Pass each literal the developer gave (an input's value, an instance's new name, the variable an input is bound to) in `value`, one change per entry.",
915
+ "A connect that names no `output` and no `input` wires the two instances as the canvas does when one is dragged onto the other.",
916
+ "A change that names nothing on the canvas, or a name that fits several things, is not applied, and the result lists its candidates: ask the developer which is meant, or send the change again naming one.",
917
+ "A place whose module the registry lists nothing for points to lace_search_module_registry.",
918
+ "Every result carries the current canvas. Do not save or generate unless the developer asked."
1775
919
  ].join(" "),
1776
920
  inputSchema: {
1777
921
  type: "object",
@@ -1783,17 +927,17 @@ var CHANGE = {
1783
927
  items: {
1784
928
  type: "object",
1785
929
  properties: {
1786
- request: {
930
+ operation: {
1787
931
  type: "string",
1788
- description: "One change, in the developer's own words, and never a literal value: that goes in `value`."
932
+ enum: OPERATIONS.map((operation) => operation.id),
933
+ description: OPERATIONS.map((operation) => operation.text).join("; ")
1789
934
  },
935
+ ...STATED_PROPERTIES,
1790
936
  value: {
1791
- description: "The literal the developer gave for this change: an input's value, an instance's new name, or the name of the variable an input is bound to (`var.<name>`). One value per entry: a change with a value of its own is an entry of its own."
1792
- },
1793
- modelReading: READING,
1794
- alternativeReading: READING
937
+ description: "The literal the developer gave for this change: an input's value, an instance's new name, or the name of the variable an input is bound to (`var.<name>`)."
938
+ }
1795
939
  },
1796
- required: ["request", "modelReading"],
940
+ required: ["operation"],
1797
941
  additionalProperties: false
1798
942
  }
1799
943
  }
@@ -1805,7 +949,7 @@ var CHANGE = {
1805
949
  var DESCRIBE = {
1806
950
  name: "lace_describe_module_canvas",
1807
951
  title: "Describe module canvas",
1808
- description: "Describes a Lace module canvas (its module instances with their inputs and outputs, the wires between them, the groups, the diagnostics, and whether it holds unsaved or ungenerated edits) for answering questions about it. Not needed before making changes.",
952
+ description: "Describes a Lace module canvas: its module instances with their inputs and outputs, the wires between them, the groups, the diagnostics, and whether it holds unsaved or ungenerated edits. Read it before a change when you do not know the names the canvas gives its instances, inputs and outputs.",
1809
953
  inputSchema: NO_INPUT
1810
954
  };
1811
955
  var SAVE = {
@@ -1850,19 +994,20 @@ function generateSaid(event) {
1850
994
  }
1851
995
  }
1852
996
  function unobserved(error) {
1853
- if (!(error instanceof import_engine5.ApplyUnobservedError)) throw error;
997
+ if (!(error instanceof import_engine4.ApplyUnobservedError)) throw error;
1854
998
  return {
1855
999
  text: `The session's stream ended (${endText(error.end)}) before the canvas showed this, so the canvas below is from before it.`,
1856
1000
  isError: false
1857
1001
  };
1858
1002
  }
1859
- var NO_RECORDS = { applied: [] };
1003
+ function cancelledSaid(operation, sent) {
1004
+ return {
1005
+ 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.`,
1006
+ isError: false
1007
+ };
1008
+ }
1860
1009
  function canvasTools(ports) {
1861
1010
  const [change, describe, save, generate] = canvasToolSchemas;
1862
- const observer = ports.transport === void 0 ? void 0 : outcomeObserver(ports.transport);
1863
- const dispose = observer === void 0 ? () => {
1864
- } : ports.source.subscribe(observer.frame, () => {
1865
- });
1866
1011
  const attempt = (run) => run().catch((error) => [{ text: errorText(error), isError: true }]);
1867
1012
  const answer = async (said2) => ({
1868
1013
  content: [
@@ -1872,31 +1017,28 @@ function canvasTools(ports) {
1872
1017
  ].join("\n"),
1873
1018
  isError: said2.some((each) => each.isError)
1874
1019
  });
1875
- const registrations = [
1876
- registrationOf(
1877
- change,
1878
- async (input) => {
1879
- try {
1880
- const { text: text2, applied } = await applyChanges(ports, parseChanges(input), observer?.own);
1881
- observer?.follow(applied);
1882
- return { ...await answer([{ text: text2, isError: false }]), applied };
1883
- } catch (error) {
1884
- if (!(error instanceof InvalidInput)) throw error;
1885
- return { ...await answer([{ text: errorText(error), isError: true }]), ...NO_RECORDS };
1886
- }
1887
- },
1888
- (failure) => ({ ...failure, ...NO_RECORDS })
1889
- ),
1020
+ return [
1021
+ registration(change, async (input, signal) => {
1022
+ try {
1023
+ const text2 = await applyChanges(ports, parseChanges(input), signal);
1024
+ return answer([{ text: text2, isError: false }]);
1025
+ } catch (error) {
1026
+ if (!(error instanceof InvalidInput)) throw error;
1027
+ return answer([{ text: errorText(error), isError: true }]);
1028
+ }
1029
+ }),
1890
1030
  registration(describe, () => answer([])),
1891
1031
  registration(
1892
1032
  save,
1893
- async () => answer(
1033
+ async (_input, signal) => answer(
1894
1034
  await attempt(async () => {
1035
+ if (signal?.aborted) return [cancelledSaid("save", false)];
1895
1036
  const saved = { text: "Saved the canvas.", isError: false };
1896
1037
  try {
1897
- await ports.editor.save();
1038
+ await untilCancelled(ports.editor.save(), signal);
1898
1039
  return [saved];
1899
1040
  } catch (error) {
1041
+ if (error instanceof Cancelled) return [cancelledSaid("save", true)];
1900
1042
  return [saved, unobserved(error)];
1901
1043
  }
1902
1044
  })
@@ -1904,12 +1046,17 @@ function canvasTools(ports) {
1904
1046
  ),
1905
1047
  registration(
1906
1048
  generate,
1907
- async () => answer(
1049
+ async (_input, signal) => answer(
1908
1050
  await attempt(async () => {
1051
+ if (signal?.aborted) return [cancelledSaid("Generate", false)];
1909
1052
  const said2 = [];
1053
+ const events = ports.editor.generate()[Symbol.asyncIterator]();
1910
1054
  try {
1911
- for await (const event of ports.editor.generate()) said2.push(...generateSaid(event));
1055
+ for (let next = await untilCancelled(events.next(), signal); next.done !== true; next = await untilCancelled(events.next(), signal)) {
1056
+ said2.push(...generateSaid(next.value));
1057
+ }
1912
1058
  } catch (error) {
1059
+ if (error instanceof Cancelled) return [...said2, cancelledSaid("Generate", true)];
1913
1060
  said2.push(unobserved(error));
1914
1061
  }
1915
1062
  return said2;
@@ -1917,7 +1064,6 @@ function canvasTools(ports) {
1917
1064
  )
1918
1065
  )
1919
1066
  ];
1920
- return Object.assign(registrations, { dispose });
1921
1067
  }
1922
1068
 
1923
1069
  // src/surfaces/canvas/module-tools.ts
@@ -1927,7 +1073,7 @@ var VALIDATE = {
1927
1073
  description: "Runs `lace module validate` on a module's Terraform on disk, not on its canvas: canvas edits reach the Terraform after Save and Generate. Returns the verdict (whether the module is in Lace style) and the diagnostics.",
1928
1074
  inputSchema: NO_INPUT
1929
1075
  };
1930
- var SEARCH = {
1076
+ var SEARCH2 = {
1931
1077
  name: "lace_search_module_registry",
1932
1078
  title: "Search module registry",
1933
1079
  description: "Searches the Lace module registry. Returns each published module as `author/name` with its latest version, its description, its system and its categories.",
@@ -1957,7 +1103,7 @@ var DESCRIBE2 = {
1957
1103
  };
1958
1104
  var moduleToolSchemas = [
1959
1105
  VALIDATE,
1960
- SEARCH,
1106
+ SEARCH2,
1961
1107
  DESCRIBE2
1962
1108
  ];
1963
1109
  function said(run, trim) {
@@ -1969,7 +1115,7 @@ function said(run, trim) {
1969
1115
  };
1970
1116
  }
1971
1117
  function moduleTool(schema, run) {
1972
- return registrationOf(schema, run, (failure) => failure);
1118
+ return registration(schema, run);
1973
1119
  }
1974
1120
  function text(value) {
1975
1121
  return typeof value === "string" ? value : void 0;
@@ -1979,28 +1125,35 @@ function moduleTools({ commands }) {
1979
1125
  return [
1980
1126
  moduleTool(
1981
1127
  validate,
1982
- async () => said(await runCommand(commands, "module validate", {}), trimValidate)
1128
+ async (_input, signal) => said(await runCommand(commands, "module validate", {}, signal), trimValidate)
1983
1129
  ),
1984
1130
  moduleTool(
1985
1131
  search,
1986
- async (input) => said(
1987
- await runCommand(commands, "registry list", {
1988
- axis: "module",
1989
- query: text(input.query),
1990
- system: text(input.system),
1991
- category: text(input.category)
1992
- }),
1132
+ async (input, signal) => said(
1133
+ await runCommand(
1134
+ commands,
1135
+ "registry list",
1136
+ {
1137
+ axis: "module",
1138
+ query: text(input.query),
1139
+ system: text(input.system),
1140
+ category: text(input.category)
1141
+ },
1142
+ signal
1143
+ ),
1993
1144
  trimRegistryList
1994
1145
  )
1995
1146
  ),
1996
- moduleTool(describe, async (input) => {
1147
+ moduleTool(describe, async (input, signal) => {
1997
1148
  const module2 = text(input.module);
1998
1149
  if (module2 === void 0) throw new InvalidInput("`module` is the module as `author/name`");
1999
1150
  return said(
2000
- await runCommand(commands, "registry describe", {
2001
- artifact: `module/${module2}`,
2002
- version: text(input.version)
2003
- }),
1151
+ await runCommand(
1152
+ commands,
1153
+ "registry describe",
1154
+ { artifact: `module/${module2}`, version: text(input.version) },
1155
+ signal
1156
+ ),
2004
1157
  trimRegistryDescribe
2005
1158
  );
2006
1159
  })
@@ -2008,21 +1161,11 @@ function moduleTools({ commands }) {
2008
1161
  }
2009
1162
  // Annotate the CommonJS export names for ESM import in node:
2010
1163
  0 && (module.exports = {
2011
- DECISION_KINDS,
2012
- NONE_CANDIDATE_ID,
2013
- VALUE_PLACEHOLDER,
2014
1164
  canvasToolSchemas,
2015
1165
  canvasTools,
2016
- changeOutcomes,
2017
- compose,
2018
1166
  createToolRegistry,
2019
1167
  moduleToolSchemas,
2020
1168
  moduleTools,
2021
- partOf,
2022
- renderCandidate,
2023
- renderCanvas,
2024
- renderRequest,
2025
- sure,
2026
- trainingRows
1169
+ renderCanvas
2027
1170
  });
2028
1171
  //# sourceMappingURL=index.cjs.map