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