@lace-cloud/chat-core 0.20.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,225 +17,8 @@ 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
- }
213
-
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;
220
- }
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
- }
20
+ // src/surfaces/canvas/canvas-tools.ts
21
+ import { ApplyUnobservedError as ApplyUnobservedError2 } from "@lace-cloud/canvas/engine";
239
22
 
240
23
  // src/contract/cancel.ts
241
24
  var Cancelled = class extends Error {
@@ -262,120 +45,6 @@ function cancellable(start, signal) {
262
45
  return untilCancelled(start(), signal);
263
46
  }
264
47
 
265
- // src/ranking/client.ts
266
- var RANK_PATH = "/api/v1/candidates/rank";
267
- var DECISIONS_PATH = "/api/v1/candidates/decisions";
268
- var RANKING_CALL_TIMEOUT_MS = 12e3;
269
- var RankingUnavailable = class extends Error {
270
- };
271
- function isRecord(value) {
272
- return typeof value === "object" && value !== null && !Array.isArray(value);
273
- }
274
- var isKind = (value) => DECISION_KINDS.includes(value);
275
- function scoreOf(value) {
276
- if (!isRecord(value)) return void 0;
277
- const { id, score, rightness } = value;
278
- return typeof id === "string" && typeof score === "number" && typeof rightness === "number" && rightness >= 0 && rightness <= 1 ? { id, score, rightness } : void 0;
279
- }
280
- function thresholdsOf(value) {
281
- if (!isRecord(value)) return void 0;
282
- const entries = Object.entries(value).map(
283
- ([kind, threshold]) => isKind(kind) && isRecord(threshold) && typeof threshold.from === "number" ? [kind, { from: threshold.from }] : void 0
284
- );
285
- return entries.every((entry) => entry !== void 0) ? Object.fromEntries(entries) : void 0;
286
- }
287
- function rankedOf(body) {
288
- if (!isRecord(body) || !Array.isArray(body.scores)) return void 0;
289
- const scores = body.scores.map(scoreOf);
290
- const thresholds = thresholdsOf(body.thresholds);
291
- return typeof body.capture_id === "string" && typeof body.head === "string" && scores.every((score) => score !== void 0) && thresholds !== void 0 ? { capture_id: body.capture_id, head: body.head, scores, thresholds } : void 0;
292
- }
293
- var NotCarried = class extends Error {
294
- };
295
- function answerOf(answer) {
296
- if (!isRecord(answer)) return "failed";
297
- if (answer.carried === false) return "uncarried";
298
- return typeof answer.status === "number" ? { status: answer.status, body: answer.body } : "failed";
299
- }
300
- var NO_ANSWER = { failed: "the request failed", unanswered: "no answer from Lace" };
301
- function rankingClient(transport) {
302
- const post = (path, body, cancel) => {
303
- if (cancel?.aborted) return Promise.resolve("cancelled");
304
- const controller = new AbortController();
305
- const reply = new Promise(
306
- (made) => made(transport(path, { method: "POST", body, signal: controller.signal }))
307
- ).then(answerOf).catch(() => "failed");
308
- let timer;
309
- const unanswered = new Promise((settle) => {
310
- timer = setTimeout(() => settle("unanswered"), RANKING_CALL_TIMEOUT_MS);
311
- });
312
- return untilCancelled(Promise.race([reply, unanswered]), cancel).catch(() => "cancelled").then((ended) => {
313
- if (ended === "unanswered" || ended === "cancelled") controller.abort();
314
- return ended;
315
- }).finally(() => clearTimeout(timer));
316
- };
317
- return {
318
- changeCall(cancel) {
319
- let ended;
320
- const send = (path, body, signal) => {
321
- if (ended !== void 0) return { made: false, reply: Promise.resolve(ended) };
322
- const reply = post(path, body, signal).then((answer) => {
323
- if (answer === "failed" || answer === "unanswered" || answer === "uncarried") {
324
- ended = answer;
325
- }
326
- return answer;
327
- });
328
- return { made: true, reply };
329
- };
330
- return {
331
- async rank(request) {
332
- const reply = await send(RANK_PATH, request, cancel).reply;
333
- if (reply === "cancelled") throw new Cancelled();
334
- if (reply === "uncarried") throw new NotCarried("the host carried nothing");
335
- if (typeof reply === "string") throw new RankingUnavailable(NO_ANSWER[reply]);
336
- const ranked = reply.status === 200 ? rankedOf(reply.body) : void 0;
337
- if (ranked !== void 0) return ranked;
338
- throw new RankingUnavailable(
339
- reply.status === 200 ? "the ranking service answered with no ranking" : `status ${reply.status}`
340
- );
341
- },
342
- decision(report) {
343
- const { made, reply } = send(DECISIONS_PATH, report);
344
- return { made, settled: reply.then(() => void 0) };
345
- }
346
- };
347
- },
348
- async outcome(decision, outcome) {
349
- await post(`${DECISIONS_PATH}/${encodeURIComponent(decision)}/outcomes`, outcome);
350
- }
351
- };
352
- }
353
-
354
- // src/hybrid/compose.ts
355
- var real = (score) => score.id !== NONE_CANDIDATE_ID;
356
- function pickOf(scores) {
357
- return scores.find(real);
358
- }
359
- function sure(ranked, kind) {
360
- const from = ranked.thresholds[kind]?.from;
361
- const pick = pickOf(ranked.scores);
362
- return from !== void 0 && pick !== void 0 && ranked.scores[0]?.id !== NONE_CANDIDATE_ID && pick.rightness >= from;
363
- }
364
- function compose({ kind, chat, ranked }) {
365
- const pick = ranked === null ? void 0 : pickOf(ranked.scores);
366
- const clm = pick === void 0 ? null : { id: pick.id, rightness: pick.rightness };
367
- if (ranked !== null && clm !== null && sure(ranked, kind)) {
368
- return { took: "clm", taken: clm.id, clm, differed: chat !== null && chat !== clm.id };
369
- }
370
- return { took: "chat", taken: chat, clm, differed: false };
371
- }
372
- function moveStands(under) {
373
- return under.every((question) => question.took === "clm");
374
- }
375
-
376
- // src/surfaces/canvas/canvas-tools.ts
377
- import { ApplyUnobservedError as ApplyUnobservedError2 } from "@lace-cloud/canvas/engine";
378
-
379
48
  // src/surfaces/canvas/change.ts
380
49
  import { ApplyUnobservedError, InputMode } from "@lace-cloud/canvas/engine";
381
50
 
@@ -387,6 +56,7 @@ import {
387
56
  // src/surfaces/canvas/enumerate.ts
388
57
  import {
389
58
  deriveNodeConfig,
59
+ nodeIdForDiagnostic,
390
60
  projectCanvasView,
391
61
  resolveInstance
392
62
  } from "@lace-cloud/proto";
@@ -417,149 +87,36 @@ function readCanvas(source) {
417
87
  });
418
88
  return {
419
89
  module: view.module_name,
420
- entry: bundle.entry,
421
90
  instances,
422
91
  wires: view.edges,
423
- groups: view.groups.map((group) => ({ id: group.id, members: group.node_ids }))
424
- };
425
- }
426
- function canvasNames(canvas) {
427
- return new Set(
428
- canvas.instances.flatMap((instance) => [
429
- instance.id,
430
- instance.name,
431
- instance.module,
432
- instance.scope,
433
- ...instance.inputs.map((input) => input.name),
434
- ...instance.outputs.map((output) => output.name)
435
- ])
436
- );
437
- }
438
- function offered(facts, rest) {
439
- return { facts, candidate: renderCandidate(facts), ...rest };
440
- }
441
- var pinFacts = (pins) => pins.map(
442
- (pin) => pin.description ? { name: pin.name, description: pin.description } : { name: pin.name }
443
- );
444
- function unwired(instance) {
445
- return instance.inputs.filter((input) => input.mode !== "wired");
446
- }
447
- function instanceFacts(instance, role) {
448
- return {
449
- id: instance.id,
450
- kind: "instance",
451
- role,
452
- module: instance.module,
453
- inputs: pinFacts(role === "target" ? unwired(instance) : instance.inputs),
454
- 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
+ }))
455
97
  };
456
98
  }
457
- function operationOptions(operations) {
458
- return operations.map(
459
- (operation) => offered(
460
- { id: operation.id, kind: "operation" },
461
- { refs: [[operation.id]], slots: { operation: operation.id }, value: operation }
462
- )
463
- );
464
- }
465
99
  function instanceOptions(instances) {
466
- return instances.map(
467
- (instance) => offered(instanceFacts(instance, "instance"), {
468
- refs: [[instance.id], [instance.name]],
469
- slots: { instance: instance.id },
470
- value: instance
471
- })
472
- );
473
- }
474
- function sourceOptions(instances) {
475
- return instances.filter((instance) => instance.outputs.length > 0).map(
476
- (instance) => offered(instanceFacts(instance, "source"), {
477
- refs: instance.outputs.map((output) => [pinRef(instance.id, output.name)]),
478
- slots: { sourceInstance: instance.id },
479
- value: instance
480
- })
481
- );
100
+ return instances.map((instance) => ({ names: [instance.id, instance.name], value: instance }));
482
101
  }
483
- function targetOptions(instances, source) {
484
- return instances.filter((instance) => instance.scope === source.scope && instance.id !== source.id).filter((instance) => unwired(instance).length > 0).map(
485
- (instance) => offered(instanceFacts(instance, "target"), {
486
- refs: unwired(instance).map((input) => [pinRef(instance.id, input.name)]),
487
- slots: { targetInstance: instance.id },
488
- value: instance
489
- })
490
- );
491
- }
492
- var INPUT_STATE = {
493
- empty: "not set",
494
- literal: "set",
495
- variable: "set",
496
- expression: "set",
497
- wired: "wired"
498
- };
499
- function inputOptions(instance, inputs) {
500
- return inputs.map(
501
- (input) => offered(
502
- {
503
- id: input.name,
504
- kind: "input",
505
- instance: instance.id,
506
- module: instance.module,
507
- type: input.type,
508
- required: input.required,
509
- state: INPUT_STATE[input.mode],
510
- ...input.description === void 0 ? {} : { description: input.description }
511
- },
512
- { refs: [[input.name]], slots: { input: input.name }, value: input }
513
- )
514
- );
515
- }
516
- var STEPS = ["one", "several"];
517
- function stepsOptions() {
518
- 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 }));
519
104
  }
520
105
  function moduleId(row) {
521
106
  return `${row.author}/${row.name}`;
522
107
  }
523
108
  function moduleOptions(rows) {
524
- return rows.map(
525
- (row) => offered(
526
- {
527
- id: moduleId(row),
528
- kind: "module",
529
- displayName: row.displayName,
530
- description: row.description,
531
- system: row.system,
532
- categories: row.categories
533
- },
534
- { refs: [[moduleId(row)], [row.name]], slots: { module: moduleId(row) }, value: row }
535
- )
536
- );
109
+ return rows.map((row) => ({ names: [moduleId(row), row.name], value: row }));
537
110
  }
538
- function connectionOptions(source, target, scored) {
539
- const between = scored.filter(
540
- (each) => each.sourceInstance === source.name && each.targetInstance === target.name
541
- );
542
- return source.outputs.flatMap(
543
- (output) => unwired(target).map((input) => {
544
- const pair = { output: output.name, input: input.name };
545
- const from = pinRef(source.id, pair.output);
546
- const to = pinRef(target.id, pair.input);
547
- const match = between.find(
548
- (each) => each.output === pair.output && each.input === pair.input
549
- );
550
- return offered(
551
- {
552
- id: connectionId(from, to),
553
- kind: "connection",
554
- source: source.id,
555
- output: pair.output,
556
- target: target.id,
557
- input: pair.input,
558
- ...match === void 0 ? {} : { score: match.score }
559
- },
560
- { refs: [[from, to]], slots: pair, value: pair }
561
- );
562
- })
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})`
563
120
  );
564
121
  }
565
122
 
@@ -577,21 +134,19 @@ function errorText(error) {
577
134
  }
578
135
  return error instanceof Error ? error.message : String(error);
579
136
  }
580
- function registrationOf(schema, run, failed) {
137
+ function registration(schema, run) {
138
+ const none = {};
581
139
  return {
582
140
  schema,
583
141
  async handler(input, signal) {
584
142
  try {
585
143
  return await run(input, signal);
586
144
  } catch (error) {
587
- return failed({ content: errorText(error), isError: true });
145
+ return { ...none, content: errorText(error), isError: true };
588
146
  }
589
147
  }
590
148
  };
591
149
  }
592
- function registration(schema, run) {
593
- return registrationOf(schema, run, (failure) => failure);
594
- }
595
150
  var NO_INPUT = { type: "object", properties: {}, additionalProperties: false };
596
151
 
597
152
  // src/surfaces/canvas/commands.ts
@@ -656,176 +211,14 @@ function trimRegistryList(list) {
656
211
  truncated: list.truncated
657
212
  };
658
213
  }
659
- function trimRegistryDescribe(described2) {
214
+ function trimRegistryDescribe(described) {
660
215
  return {
661
- module: moduleId(described2),
662
- version: described2.version,
663
- source: described2.source,
664
- verdict: described2.verdict,
665
- inputs: described2.interface.inputs,
666
- outputs: described2.interface.outputs
667
- };
668
- }
669
-
670
- // src/surfaces/canvas/outcome.ts
671
- import { deepEqual } from "@lace-cloud/canvas/engine";
672
- function instanceAt(canvas, scope, name) {
673
- return canvas.instances.find((instance) => instance.scope === scope && instance.name === name);
674
- }
675
- function presenceOf(canvas, scope, name) {
676
- const instance = instanceAt(canvas, scope, name);
677
- return instance === void 0 ? null : { instance: instance.name, module: instance.module };
678
- }
679
- function bindingOf(canvas, scope, name, inputName) {
680
- const input = instanceAt(canvas, scope, name)?.inputs.find((each) => each.name === inputName);
681
- if (input === void 0) return null;
682
- if (input.sensitive) return { mode: input.mode };
683
- return {
684
- mode: input.mode,
685
- value: input.value,
686
- variable: input.variable,
687
- expression: input.expression,
688
- wiredSource: input.wired_source
689
- };
690
- }
691
- function at({ target, after }) {
692
- return after !== null && "instance" in after ? after.instance : target.instance;
693
- }
694
- function targetState(canvas, record) {
695
- const { scope, input } = record.target;
696
- return input === void 0 ? presenceOf(canvas, scope, at(record)) : bindingOf(canvas, scope, at(record), input);
697
- }
698
- function follow(record, previous, frame) {
699
- const name = at(record);
700
- const { scope } = record.target;
701
- const was = instanceAt(previous, scope, name);
702
- if (was === void 0 || instanceAt(frame, scope, name) !== void 0) return record;
703
- const fresh = frame.instances.filter(
704
- (each) => each.module === was.module && instanceAt(previous, each.scope, each.name) === void 0
705
- );
706
- const one = (found2) => found2.length === 1 ? found2[0] : void 0;
707
- const moved2 = one(fresh.filter((each) => each.name === name)) ?? one(fresh.filter((each) => each.scope === scope));
708
- if (moved2 === void 0) return record;
709
- const { after } = record;
710
- return {
711
- ...record,
712
- target: { ...record.target, scope: moved2.scope, instance: moved2.name },
713
- after: after !== null && "instance" in after ? { ...after, instance: moved2.name } : after
714
- };
715
- }
716
- var decided = (state) => state === null ? null : "mode" in state ? [state.mode, state.wiredSource] : state.module;
717
- var moved = (state, from) => state !== null && "mode" in state ? !deepEqual(state, from) : !deepEqual(decided(state), decided(from));
718
- var OPERATION_OF_MODE = {
719
- literal: "set",
720
- variable: "bind",
721
- empty: "clear",
722
- wired: "connect"
723
- };
724
- function answered(record, state, canvas) {
725
- if (state === null || !("mode" in state) || record.target.input === void 0) return {};
726
- const name = (kind, candidate) => {
727
- const question = record.questions.findIndex(
728
- (each) => each.kind === kind && candidate !== void 0 && each.candidates.includes(candidate)
729
- );
730
- return question === -1 || candidate === void 0 ? {} : { question, candidate };
731
- };
732
- const after = record.after;
733
- if (after !== null && "mode" in after && after.mode !== state.mode) {
734
- return name("operation", OPERATION_OF_MODE[state.mode]);
735
- }
736
- if (state.mode !== "wired" || state.wiredSource === void 0) return {};
737
- const [, source, output] = /^module\.([^.]+)\.(.+)$/.exec(state.wiredSource) ?? [];
738
- const { scope } = record.target;
739
- const from = instanceAt(canvas, scope, source ?? "");
740
- const to = instanceAt(canvas, scope, at(record));
741
- return from === void 0 || to === void 0 || output === void 0 ? {} : name("connection", connectionId(pinRef(from.id, output), pinRef(to.id, record.target.input)));
742
- }
743
- function frameOutcomes(record, was, previous, frame, canvas, own) {
744
- const state = targetState(canvas, record);
745
- if (deepEqual(state, record.before)) return [{ event: "reverted" }];
746
- const changes = (from) => !deepEqual(decided(state), decided(from));
747
- if (changes(was) && changes(record.after)) {
748
- const event = own.has(frame.revision) ? "changed_again" : "hand_edited";
749
- return [{ event, ...answered(record, state, canvas) }];
750
- }
751
- if (moved(state, record.after)) return [];
752
- const saved = previous?.unsaved === true && !frame.unsaved ? [{ event: "saved" }] : [];
753
- const generated = previous?.ungenerated === true && !frame.ungenerated ? [{ event: "generated" }] : [];
754
- return [...saved, ...generated];
755
- }
756
- function changeOutcomes(record, frames, own = new Set(record.revision === void 0 ? [] : [record.revision])) {
757
- const canvases = frames.map(readCanvas);
758
- const reached = /* @__PURE__ */ new Map();
759
- let carried = record;
760
- frames.forEach((frame, index) => {
761
- const was = index > 0 ? targetState(canvases[index - 1], carried) : record.after;
762
- if (index > 0) carried = follow(carried, canvases[index - 1], canvases[index]);
763
- for (const outcome of frameOutcomes(
764
- carried,
765
- was,
766
- frames[index - 1],
767
- frame,
768
- canvases[index],
769
- own
770
- )) {
771
- if (!reached.has(outcome.event)) reached.set(outcome.event, outcome);
772
- }
773
- });
774
- return { record: carried, outcomes: [...reached.values()] };
775
- }
776
- function outcomeObserver(transport) {
777
- const client = rankingClient(transport);
778
- const followed = /* @__PURE__ */ new Map();
779
- const own = /* @__PURE__ */ new Set();
780
- let previous;
781
- let flying = 0;
782
- const returned = /* @__PURE__ */ new Set();
783
- let held = [];
784
- const fold = (source) => {
785
- const frames = previous === void 0 ? [source] : [previous, source];
786
- previous = source;
787
- for (const [id, each] of followed) {
788
- const { record, outcomes } = changeOutcomes(each.record, frames, own);
789
- followed.set(id, { record, reported: each.reported });
790
- for (const outcome of outcomes.filter(({ event }) => !each.reported.has(event))) {
791
- each.reported.add(outcome.event);
792
- void client.outcome(id, outcome);
793
- }
794
- }
795
- };
796
- const landed = (revision) => {
797
- flying -= 1;
798
- if (revision !== void 0) returned.add(revision);
799
- if (flying > 0) return;
800
- const frames = held;
801
- held = [];
802
- for (const frame of frames) {
803
- if (returned.has(frame.revision)) own.add(frame.revision);
804
- fold(frame);
805
- }
806
- returned.clear();
807
- };
808
- return {
809
- async own(apply) {
810
- flying += 1;
811
- let revision;
812
- try {
813
- const result = await apply();
814
- revision = result.success ? result.revision : void 0;
815
- return result;
816
- } finally {
817
- landed(revision);
818
- }
819
- },
820
- follow(records) {
821
- for (const record of records.filter((each) => each.reported)) {
822
- followed.set(record.id, { record, reported: /* @__PURE__ */ new Set() });
823
- }
824
- },
825
- frame(source) {
826
- if (flying > 0) held.push(source);
827
- else fold(source);
828
- }
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
829
222
  };
830
223
  }
831
224
 
@@ -839,426 +232,177 @@ function endError(end) {
839
232
  function latest(source) {
840
233
  let unsubscribe = () => {
841
234
  };
842
- const frame = new Promise((resolve, reject) => {
843
- unsubscribe = source.subscribe(resolve, (end) => reject(endError(end)));
235
+ const frame = new Promise((resolve2, reject) => {
236
+ unsubscribe = source.subscribe(resolve2, (end) => reject(endError(end)));
844
237
  });
845
238
  return frame.finally(() => unsubscribe());
846
239
  }
847
240
 
848
- // src/surfaces/canvas/render.ts
849
- import { callText } from "@lace-cloud/proto";
850
- function inputText(input) {
851
- if (input.mode === "empty") {
852
- return `${input.name} (${input.required ? "required, " : ""}not set)`;
853
- }
854
- if (input.mode === "wired") return `${input.name} (wired)`;
855
- if (input.sensitive) return `${input.name} (sensitive, value withheld)`;
856
- const shown = {
857
- literal: JSON.stringify(input.value),
858
- variable: `var.${input.variable}`,
859
- expression: `${input.expression}`
860
- };
861
- return `${input.name} = ${shown[input.mode]}`;
862
- }
863
- function instanceLines(instance) {
864
- return [
865
- `- ${instance.id}: module ${instance.module}`,
866
- ` inputs: [${instance.inputs.map(inputText).join("; ")}]`,
867
- ` outputs: [${instance.outputs.map((output) => output.name).join(", ")}]`
868
- ];
869
- }
870
- function unsetRequired(instance) {
871
- return instance.inputs.filter((input) => input.required && input.mode === "empty").map((input) => `- ${instance.id}.${input.name}`);
872
- }
873
- function diagnosticLine(diagnostic) {
874
- const where = [
875
- ["instance", diagnostic.instance_id],
876
- ["input", diagnostic.input_name],
877
- ["address", diagnostic.address],
878
- ["file", diagnostic.file],
879
- ["line", diagnostic.line]
880
- ].filter(([, value]) => value !== void 0).map(([label, value]) => `${label} ${value}`);
881
- return `- ${[`${diagnostic.severity}: ${diagnostic.message}`, ...where].join("; ")}`;
882
- }
883
- var yesNo = (flag) => flag ? "yes" : "no";
884
- function section(title, lines) {
885
- return [`${title} (${lines.length}):`, ...lines];
886
- }
887
- function renderCanvas(source) {
888
- const canvas = readCanvas(source);
889
- return [
890
- `Canvas of module ${canvas.module}`,
891
- `Instances (${canvas.instances.length}):`,
892
- ...canvas.instances.flatMap(instanceLines),
893
- ...section(
894
- "Wires",
895
- canvas.wires.map(
896
- (wire) => `- ${wire.source_output ? `${wire.source}.${wire.source_output}` : callText(wire.source)} \u2192 ${wire.target}.${wire.target_input}`
897
- )
898
- ),
899
- ...section("Required inputs not set", canvas.instances.flatMap(unsetRequired)),
900
- ...section(
901
- "Groups",
902
- canvas.groups.map((group) => `- ${group.id}: ${group.members.join(", ")}`)
903
- ),
904
- ...section("Diagnostics", source.diagnostics.map(diagnosticLine)),
905
- [
906
- `Standing: unsaved edits: ${yesNo(source.unsaved)}`,
907
- `saved edits not generated to Terraform: ${yesNo(source.ungenerated)}`,
908
- `conflict with the Terraform on disk: ${yesNo(source.conflict !== null)}`,
909
- `Terraform refused, canvas locked: ${yesNo(source.sourceRefused)}`
910
- ].join("; ")
911
- ].join("\n");
912
- }
913
- function renderTarget(target) {
914
- const pin = target.input === void 0 ? target.instance : `${target.instance}.${target.input}`;
915
- return `${pin} in ${target.scope}`;
916
- }
917
- function renderState(state) {
918
- if (state === null) return "absent";
919
- if (!("mode" in state)) return `an instance of module ${state.module}`;
920
- const shown = {
921
- empty: "not set",
922
- literal: `literal ${VALUE_PLACEHOLDER}`,
923
- variable: `variable ${VALUE_PLACEHOLDER}`,
924
- expression: `expression ${VALUE_PLACEHOLDER}`,
925
- wired: `wired from ${state.wiredSource}`
926
- };
927
- return shown[state.mode];
928
- }
929
-
930
241
  // src/surfaces/canvas/resolve.ts
931
- var WORD = /[A-Za-z0-9_-]+/g;
932
- var DOTTED = /[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)+/g;
933
- var SLASHED = /[A-Za-z0-9_-]+(?:\/[A-Za-z0-9_-]+)+/g;
934
- function found(text2, pattern) {
935
- return [...text2.matchAll(pattern)].map((match) => ({ term: match[0], at: match.index }));
936
- }
937
- function runs({ term, at: at2 }) {
938
- const parts = term.split(".");
939
- const starts = parts.map((_, index) => at2 + parts.slice(0, index).join(".").length + index);
940
- return parts.flatMap(
941
- (_, start) => parts.slice(start).map((_2, length) => ({
942
- term: parts.slice(start, start + length + 1).join("."),
943
- at: starts[start]
944
- }))
945
- );
946
- }
947
- function moduleReferences(text2) {
948
- return found(text2, SLASHED).map((each) => each.term);
949
- }
950
- function firstAt(names2, key) {
951
- return names2.reduce(
952
- (at2, { term, at: offset }) => at2.set(key(term), Math.min(offset, at2.get(key(term)) ?? offset)),
953
- /* @__PURE__ */ new Map()
954
- );
955
- }
956
- function termsOf(text2) {
957
- const names2 = [
958
- ...found(text2, WORD),
959
- ...found(text2, DOTTED).flatMap(runs),
960
- ...found(text2, SLASHED)
961
- ];
962
- return {
963
- exact: firstAt(names2, (term) => term),
964
- folded: firstAt(names2, (term) => term.toLowerCase()),
965
- words: found(text2, WORD).map(({ term }) => term.toLowerCase())
966
- };
967
- }
968
- function vocabulary(option) {
969
- const text2 = [option.candidate.id, option.candidate.text, ...option.refs.flat()].join(" ");
970
- return new Set(
971
- found(text2.toLowerCase(), WORD).flatMap(({ term }) => [term, ...term.split(/[_-]/)])
972
- );
973
- }
974
- var FUNCTION_WORDS = new Set(
975
- "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(
976
- " "
977
- )
978
- );
979
- function span(words, index, covered) {
980
- if (!covered.has(words[index])) return 0;
981
- const outside = (word) => !covered.has(word) && !FUNCTION_WORDS.has(word);
982
- const before = words.slice(0, index).reverse().findIndex(outside);
983
- const after = words.slice(index + 1).findIndex(outside);
984
- return words.slice(before === -1 ? 0 : index - before, after === -1 ? words.length : index + 1 + after).filter((word) => !FUNCTION_WORDS.has(word)).length;
985
- }
986
- var NothingOffered = class extends Error {
987
- constructor(label) {
988
- super(`the canvas offers no ${label} for this change`);
989
- this.label = label;
990
- }
991
- };
992
- var Undecided = class extends Error {
993
- constructor(kind, label, candidates, ranking2) {
994
- super(`the ${label} was not decided`);
995
- this.kind = kind;
996
- this.label = label;
997
- this.candidates = candidates;
998
- this.ranking = ranking2;
999
- }
1000
- };
1001
- var NAMED_ALTERNATIVES = 3;
1002
- var NONE_OVER = "none of these";
1003
- function named(options, { words }, terms, fold) {
1004
- const hits = options.map((option) => ({
1005
- option,
1006
- refs: option.refs.map((ref) => ref.map(fold)).filter((ref) => ref.every((part) => terms.has(part)))
1007
- })).filter((hit) => hit.refs.length > 0);
1008
- const extended = (ref) => ref.length === 1 && hits.some(
1009
- (other) => other.refs.some(
1010
- (longer) => longer.some((part) => part !== ref[0] && part.split(".").includes(ref[0]))
1011
- )
1012
- );
1013
- const covers = new Map(options.map((option) => [option, vocabulary(option)]));
1014
- const outspanned = (option, ref) => {
1015
- const word = ref[0].toLowerCase();
1016
- const places = words.flatMap((each, index) => each === word ? [index] : []);
1017
- const own = covers.get(option) ?? /* @__PURE__ */ new Set();
1018
- return ref.length === 1 && !/[./]/.test(word) && places.length > 0 && places.every(
1019
- (index) => options.some(
1020
- (other) => other !== option && span(words, index, covers.get(other) ?? /* @__PURE__ */ new Set()) > span(words, index, own)
1021
- )
1022
- );
1023
- };
1024
- const at2 = (ref) => Math.min(...ref.map((part) => terms.get(part) ?? Number.POSITIVE_INFINITY));
1025
- return hits.map((hit) => ({
1026
- ...hit,
1027
- refs: hit.refs.filter((ref) => !extended(ref) && !outspanned(hit.option, ref))
1028
- })).filter((hit) => hit.refs.length > 0).map((hit) => ({ ...hit, at: Math.min(...hit.refs.map(at2)) })).sort((a, b) => a.at - b.at);
1029
- }
1030
- function apart(hits) {
1031
- const key = (ref) => ref.join(" ");
1032
- return hits.every((hit) => {
1033
- const others = hits.filter((other) => other !== hit);
1034
- const own = hit.refs.some(
1035
- (ref) => !others.some((other) => other.refs.some((each) => key(each) === key(ref)))
1036
- );
1037
- const inside = others.some(
1038
- (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))
1039
258
  );
1040
- return own && !inside;
1041
- });
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 };
1042
263
  }
1043
- var NAME_STEPS = [
1044
- {
1045
- how: "exact",
1046
- hits: (options, terms) => named(options, terms, terms.exact, (part) => part)
1047
- },
1048
- {
1049
- how: "unique",
1050
- hits: (options, terms) => named(options, terms, terms.folded, (part) => part.toLowerCase())
1051
- }
264
+
265
+ // src/surfaces/canvas/stated.ts
266
+ var STATED_SLOTS = [
267
+ "instance",
268
+ "input",
269
+ "sourceInstance",
270
+ "output",
271
+ "targetInstance",
272
+ "module"
1052
273
  ];
1053
- function read(options, reading) {
1054
- return options.filter(
1055
- (option) => statedSlots(option.slots).every((slot) => reading[slot] === option.slots[slot])
1056
- );
274
+ function slotsStated(stated) {
275
+ return STATED_SLOTS.filter((slot) => stated[slot] !== void 0);
1057
276
  }
1058
- function answerOf2(options, reading) {
1059
- const named2 = read(options, reading);
1060
- return named2.length === 1 ? named2[0] : void 0;
1061
- }
1062
- var PART = RANK_CANDIDATES_MAX - 1;
1063
- function partsOf(items) {
1064
- return Array.from(
1065
- { length: Math.ceil(items.length / PART) },
1066
- (_, n) => items.slice(n * PART, (n + 1) * PART)
1067
- );
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 [];
1068
286
  }
1069
- function partHolding(candidates, id) {
1070
- return partsOf(candidates).find((part) => part.some((each) => each.id === id)) ?? [];
1071
- }
1072
- function factsOf(options, part) {
1073
- const byId = new Map(options.map((option) => [option.candidate.id, option.facts]));
1074
- return part.flatMap((candidate) => byId.get(candidate.id) ?? []);
1075
- }
1076
- async function rankPart(rank, request, statement, kind, part) {
1077
- const ranked = await rank({ request, statement, candidates: rankCandidates(kind, part) });
1078
- const pick = part.find((candidate) => candidate.id === pickOf(ranked.scores)?.id);
1079
- if (pick === void 0) throw new Error("the ranking names no candidate of the set");
1080
- return { part, ranked, pick };
1081
- }
1082
- async function rankWithin(rank, request, statement, kind, candidates) {
1083
- const parts = partsOf(candidates);
1084
- if (parts.length === 1) return rankPart(rank, request, statement, kind, candidates);
1085
- const rounds = [];
1086
- for (const part of parts) rounds.push(await rankWithin(rank, request, statement, kind, part));
1087
- const final = await rankWithin(
1088
- rank,
1089
- request,
1090
- statement,
1091
- kind,
1092
- rounds.map((round) => round.pick)
1093
- );
1094
- const holding = rounds.find((round) => round.pick.id === final.pick.id);
1095
- if (holding === void 0) throw new Error("the ranking names no candidate of the set");
1096
- 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);
1097
313
  }
1098
- var NOT_RANKED = { ranked: null, failed: "Lace did not rank" };
1099
- async function ranking(ask, statement, kind, candidates) {
1100
- if (ask.rank === void 0) return { ranking: NOT_RANKED, part: candidates };
1101
- try {
1102
- const { part, ranked } = await rankWithin(ask.rank, ask.request, statement, kind, candidates);
1103
- return { ranking: { ranked, parts: part.length < candidates.length }, part };
1104
- } catch (error) {
1105
- if (error instanceof Cancelled) throw error;
1106
- if (error instanceof NotCarried) return { ranking: NOT_RANKED, part: candidates };
1107
- const failed = `Lace could not rank: ${error instanceof Error ? error.message : String(error)}`;
1108
- return { ranking: { ranked: null, failed }, part: candidates };
1109
- }
314
+ function escapeRegExp(text2) {
315
+ return text2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1110
316
  }
1111
- var asAsked = (ranking2) => ranking2 === null || ranking2.ranked === null || ranking2.parts ? null : ranking2.ranked;
1112
- async function twoSystems(ask, kind, label, options, stated) {
1113
- const candidates = options.map((option2) => option2.candidate);
1114
- const readings = options.map((option2) => option2.slots);
1115
- const chat = stated === void 0 ? answerOf2(options, ask.reading) : options.find((option2) => option2.value === stated);
1116
- const read2 = await ranking(ask, ask.statement, kind, candidates);
1117
- const composed = compose({
1118
- kind,
1119
- chat: chat?.candidate.id ?? null,
1120
- ranked: asAsked(read2.ranking)
1121
- });
1122
- const option = options.find((each) => each.candidate.id === composed.taken);
1123
- if (option === void 0) throw new Undecided(kind, label, candidates, read2.ranking);
1124
- const alternative = ask.alternative === void 0 ? null : await ranking(ask, ask.alternative.statement, kind, candidates).then(({ ranking: ranking2 }) => {
1125
- const ranked2 = asAsked(ranking2);
1126
- const pick = ranked2 === null ? void 0 : pickOf(ranked2.scores);
1127
- const named2 = options.find((each) => each.candidate.id === pick?.id);
1128
- return pick === void 0 || ranked2 === null || named2 === void 0 ? null : { id: pick.id, sure: sure(ranked2, kind), slots: named2.slots };
1129
- });
1130
- const ranked = read2.ranking.ranked;
1131
- const others = ranked === null ? [] : ranked.scores.filter((score) => score.id !== NONE_CANDIDATE_ID);
1132
- const part = composed.took === "clm" ? read2.part : partHolding(candidates, option.candidate.id);
1133
- return {
1134
- kind,
1135
- label,
1136
- option,
1137
- how: composed.took,
1138
- offered: candidates.length,
1139
- candidates: part,
1140
- facts: factsOf(options, part),
1141
- others: [],
1142
- chat: chat?.candidate.id ?? null,
1143
- ranking: read2.ranking,
1144
- composed,
1145
- over: [
1146
- ...ranked?.scores[0]?.id === NONE_CANDIDATE_ID ? [NONE_OVER] : [],
1147
- ...others.slice(1, NAMED_ALTERNATIVES + 1).map((score) => score.id)
1148
- ],
1149
- alternative,
1150
- readings
1151
- };
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");
1152
321
  }
1153
- function byName(ask, kind, label, options) {
1154
- const settled = (option, how, hits) => ({
1155
- kind,
1156
- label,
1157
- option,
1158
- how,
1159
- offered: options.length,
1160
- candidates: options.map((each) => each.candidate),
1161
- facts: options.map((each) => each.facts),
1162
- others: hits.filter((hit) => hit.option !== option).map((hit) => hit.option.candidate.id),
1163
- chat: answerOf2(options, ask.reading)?.candidate.id ?? null,
1164
- ranking: null,
1165
- composed: null,
1166
- over: [],
1167
- alternative: null,
1168
- readings: options.map((each) => each.slots)
1169
- });
1170
- const step = NAME_STEPS.map((each) => ({
1171
- how: each.how,
1172
- hits: each.hits(options, ask.terms)
1173
- })).find((each) => each.hits.length > 0);
1174
- if (step === void 0) return void 0;
1175
- if (step.hits.length === 1) return settled(step.hits[0].option, step.how, step.hits);
1176
- if (!apart(step.hits)) return void 0;
1177
- const agreed = read(
1178
- step.hits.map((hit) => hit.option),
1179
- ask.reading
322
+ function withhold(text2, value) {
323
+ return forms(value).reduce(
324
+ (rest, form) => rest.replace(occurrences(form), VALUE_PLACEHOLDER),
325
+ text2
1180
326
  );
1181
- return agreed.length === 1 ? settled(agreed[0], "agreed", step.hits) : settled(step.hits[0].option, "first", step.hits);
1182
- }
1183
- async function decide(ask, kind, label, options, stated) {
1184
- if (options.length === 0) throw new NothingOffered(label);
1185
- return byName(ask, kind, label, options) ?? twoSystems(ask, kind, label, options, stated);
1186
327
  }
1187
328
 
1188
329
  // src/surfaces/canvas/change.ts
1189
330
  var Unapplicable = class extends Error {
1190
331
  };
1191
- function isRecord2(value) {
332
+ function isRecord(value) {
1192
333
  return typeof value === "object" && value !== null && !Array.isArray(value);
1193
334
  }
1194
335
  var present = (value) => value !== void 0 && value !== null;
1195
- function readingOf(index, name, stated) {
1196
- if (!isRecord2(stated)) {
1197
- throw new InvalidInput(`change ${index + 1}: \`${name}\` is an object of names`);
1198
- }
1199
- return Object.fromEntries(
1200
- READING_SLOTS.flatMap((slot) => {
1201
- const value = stated[slot];
1202
- return typeof value === "string" ? [[slot, value]] : [];
1203
- })
1204
- );
1205
- }
1206
336
  function parseChanges(input) {
1207
337
  const { changes } = input;
1208
- 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
+ }
1209
341
  return changes.map((entry, index) => {
1210
- if (!isRecord2(entry) || typeof entry.request !== "string") {
1211
- throw new InvalidInput(`change ${index + 1} needs \`request\`: the developer's own words`);
1212
- }
1213
- if (!present(entry.modelReading)) {
1214
- throw new InvalidInput(
1215
- `change ${index + 1} needs \`modelReading\`: your own reading of the change, an object of the names you stated`
1216
- );
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}`);
1217
348
  }
1218
- 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
+ });
1219
357
  return {
1220
- request: entry.request,
1221
- values: [entry.value].filter(present),
1222
- reading: readingOf(index, "modelReading", entry.modelReading),
1223
- ...alternative
358
+ operation,
359
+ stated: Object.fromEntries(names),
360
+ value: present(entry.value) ? entry.value : void 0
1224
361
  };
1225
362
  });
1226
363
  }
1227
- function inputEdit(canvas, instance, inputName) {
1228
- const state = (of) => bindingOf(of, instance.scope, instance.name, inputName);
1229
- return {
1230
- target: () => ({ scope: instance.scope, instance: instance.name, input: inputName }),
1231
- before: state(canvas),
1232
- after: state
1233
- };
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(", ");
1234
369
  }
1235
- function instanceEdit(canvas, instance, nameAfter) {
1236
- return {
1237
- target: () => ({ scope: instance.scope, instance: instance.name }),
1238
- before: presenceOf(canvas, instance.scope, instance.name),
1239
- after: (of) => presenceOf(of, instance.scope, nameAfter)
1240
- };
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
+ }
1241
381
  }
1242
- function given(values, what) {
1243
- if (values.length === 0) {
1244
- throw new Unapplicable(`this change needs ${what}: pass it in \`value\``);
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(" ");
385
+ }
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\`.`);
1245
390
  }
1246
- return values[0];
391
+ return change.value;
1247
392
  }
1248
- function givenName(values, what) {
1249
- const name = given(values, what);
1250
- 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\`.`);
1251
396
  return name;
1252
397
  }
398
+ function variableName(text2) {
399
+ return text2.replace(/^var\./, "");
400
+ }
1253
401
  var EVERY_MODE = ["empty", "literal", "variable", "expression", "wired"];
1254
- async function pickInput({ canvas, pick }, modes) {
1255
- const offered2 = (instance2) => instance2.inputs.filter((input2) => modes.includes(input2.mode));
1256
- const instance = await pick(
1257
- "instance",
1258
- "instance",
1259
- instanceOptions(canvas.instances.filter((each) => offered2(each).length > 0))
1260
- );
1261
- 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));
1262
406
  return { instance, input };
1263
407
  }
1264
408
  function updateInput(instance, input, binding) {
@@ -1275,171 +419,256 @@ function updateInput(instance, input, binding) {
1275
419
  };
1276
420
  }
1277
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
+ }
1278
435
  var place = {
1279
436
  id: "place",
437
+ text: "place: add a registry module to the canvas as a new instance",
438
+ slots: ["module"],
1280
439
  takesValue: false,
1281
- async plan({ canvas, request, ports, signal, pick, note }) {
1282
- const [query] = moduleReferences(request).map((reference) => reference.split("/").slice(-1)[0]);
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
+ }
1283
448
  const listing = await cancellable(
1284
449
  () => runCommand(
1285
450
  ports.commands,
1286
451
  "registry list",
1287
- { axis: "module", limit: CATALOG_LIMIT, query },
452
+ { axis: "module", limit: CATALOG_LIMIT, query: stated.query },
1288
453
  signal
1289
454
  ),
1290
455
  signal
1291
456
  );
1292
457
  if (listing.failed !== void 0) throw new Error(listing.failed.text);
1293
- for (const document of listing.documents) {
1294
- if (document.truncated) {
1295
- note(
1296
- `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.`
1297
- );
1298
- }
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));
1299
470
  }
1300
- const rows = listing.documents.flatMap((document) => document.items);
1301
- const row = await pick("module", "registry module", moduleOptions(rows));
1302
- const placed = (result) => result.created.map((ref) => ref.id).join(", ");
471
+ const row = module.value;
1303
472
  return {
1304
473
  action: {
1305
- place_module: { author: row.author, name: row.name, version: row.version }
474
+ place_module: { author: row.author, name: row.name, version: version ?? row.version }
1306
475
  },
1307
- summary: (result) => `placed ${moduleId(row)} ${row.version} as ${placed(result)}`,
1308
- target: (result) => ({ scope: canvas.entry, instance: placed(result) }),
1309
- before: null,
1310
- 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(", ")}`
1311
477
  };
1312
478
  }
1313
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
+ }
1314
508
  var connect = {
1315
509
  id: "connect",
510
+ text: "connect: wire an output of one instance into an input of another",
511
+ slots: ["sourceInstance", "output", "targetInstance", "input"],
1316
512
  takesValue: false,
1317
- async plan({ canvas, ports, signal, pick }) {
1318
- const source = await pick("instance", "source instance", sourceOptions(canvas.instances));
1319
- const target = await pick(
1320
- "instance",
1321
- "target instance",
1322
- targetOptions(canvas.instances, source)
1323
- );
1324
- const scored = await cancellable(
1325
- () => ports.editor.wiringCandidates({
1326
- scope: source.scope,
1327
- source: source.name,
1328
- target: target.name
1329
- }),
1330
- signal
1331
- );
1332
- const pair = await pick("connection", "connection", connectionOptions(source, target, scored));
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,
529
+ source: source.name,
530
+ target: target.name
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];
1333
561
  return {
1334
- action: {
1335
- connect: {
1336
- scope: target.scope,
1337
- source_scope: source.scope,
1338
- source: source.name,
1339
- target: target.name,
1340
- source_output: pair.output,
1341
- target_input: pair.input
1342
- }
1343
- },
1344
- summary: () => `connected ${source.id}.${pair.output} \u2192 ${target.id}.${pair.input}`,
1345
- ...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))}`
1346
564
  };
1347
565
  }
1348
566
  };
1349
567
  var disconnect = {
1350
568
  id: "disconnect",
569
+ text: "disconnect: remove the wire into an instance's input",
570
+ slots: ["instance", "input"],
1351
571
  takesValue: false,
1352
572
  async plan(resolving) {
1353
- const { instance, input } = await pickInput(resolving, ["wired"]);
573
+ const { instance, input } = pickInput(resolving, ["wired"], (of) => `wired input of ${of.id}`);
1354
574
  return {
1355
575
  action: {
1356
576
  disconnect: { scope: instance.scope, target: instance.name, input_name: input.name }
1357
577
  },
1358
- summary: () => `disconnected ${instance.id}.${input.name}`,
1359
- ...inputEdit(resolving.canvas, instance, input.name)
578
+ summary: () => `disconnected ${pinRef(instance.id, input.name)}`
1360
579
  };
1361
580
  }
1362
581
  };
1363
582
  var set = {
1364
583
  id: "set",
584
+ text: "set: give an input of an instance a literal value",
585
+ slots: ["instance", "input"],
1365
586
  takesValue: true,
1366
587
  async plan(resolving) {
1367
- const value = given(resolving.values, "the value the developer gave");
1368
- 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}`);
1369
590
  const shown = input.sensitive ? "(sensitive, value withheld)" : `= ${JSON.stringify(value)}`;
1370
591
  return {
1371
592
  action: updateInput(instance, input, { mode: InputMode.INPUT_MODE_LITERAL, value }),
1372
- summary: () => `set ${instance.id}.${input.name} ${shown}`,
1373
- ...inputEdit(resolving.canvas, instance, input.name)
593
+ summary: () => `set ${pinRef(instance.id, input.name)} ${shown}`
1374
594
  };
1375
595
  }
1376
596
  };
1377
597
  var bind = {
1378
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"],
1379
601
  takesValue: true,
1380
602
  async plan(resolving) {
1381
- const variable = variableName(givenName(resolving.values, "the variable's name"));
1382
- 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}`);
1383
605
  return {
1384
606
  action: updateInput(instance, input, { mode: InputMode.INPUT_MODE_VARIABLE, variable }),
1385
- summary: () => `bound ${instance.id}.${input.name} to var.${variable}`,
1386
- ...inputEdit(resolving.canvas, instance, input.name)
607
+ summary: () => `bound ${pinRef(instance.id, input.name)} to var.${variable}`
1387
608
  };
1388
609
  }
1389
610
  };
1390
611
  var clear = {
1391
612
  id: "clear",
613
+ text: "clear: unset an input of an instance, removing the value, variable or expression it holds",
614
+ slots: ["instance", "input"],
1392
615
  takesValue: false,
1393
616
  async plan(resolving) {
1394
- 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
+ );
1395
622
  return {
1396
623
  action: updateInput(instance, input, { mode: InputMode.INPUT_MODE_EMPTY }),
1397
- summary: () => `cleared ${instance.id}.${input.name}`,
1398
- ...inputEdit(resolving.canvas, instance, input.name)
624
+ summary: () => `cleared ${pinRef(instance.id, input.name)}`
1399
625
  };
1400
626
  }
1401
627
  };
1402
628
  var rename = {
1403
629
  id: "rename",
630
+ text: "rename: give an instance a new name",
631
+ slots: ["instance"],
1404
632
  takesValue: true,
1405
- async plan({ canvas, values, pick }) {
1406
- const name = givenName(values, "the new name");
1407
- 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));
1408
636
  return {
1409
637
  action: {
1410
638
  rename_instance: { scope: instance.scope, old_id: instance.name, new_id: name }
1411
639
  },
1412
- summary: () => `renamed ${instance.id} to ${name}`,
1413
- ...instanceEdit(canvas, instance, name)
640
+ summary: () => `renamed ${instance.id} to ${name}`
1414
641
  };
1415
642
  }
1416
643
  };
1417
644
  var remove = {
1418
645
  id: "delete",
646
+ text: "delete: remove an instance from the canvas",
647
+ slots: ["instance"],
1419
648
  takesValue: false,
1420
649
  async plan({ canvas, pick }) {
1421
- const instance = await pick("instance", "instance", instanceOptions(canvas.instances));
650
+ const instance = pick("instance", "instance", instanceOptions(canvas.instances));
1422
651
  return {
1423
652
  action: { delete_instance: { scope: instance.scope, instance_id: instance.name } },
1424
- summary: () => `deleted ${instance.id}`,
1425
- ...instanceEdit(canvas, instance, instance.name)
653
+ summary: () => `deleted ${instance.id}`
1426
654
  };
1427
655
  }
1428
656
  };
1429
657
  var ungroup = {
1430
658
  id: "ungroup",
659
+ text: "ungroup: dissolve a group, moving the instances inside it up beside it",
660
+ slots: ["instance"],
1431
661
  takesValue: false,
1432
662
  async plan({ canvas, pick }) {
1433
663
  const groups = new Set(canvas.groups.map((group2) => group2.id));
1434
- const group = await pick(
664
+ const group = pick(
1435
665
  "instance",
1436
666
  "group",
1437
667
  instanceOptions(canvas.instances.filter((instance) => groups.has(instance.id)))
1438
668
  );
1439
669
  return {
1440
670
  action: { ungroup: { scope: group.scope, group_id: group.name } },
1441
- summary: () => `ungrouped ${group.id}`,
1442
- ...instanceEdit(canvas, group, group.name)
671
+ summary: () => `ungrouped ${group.id}`
1443
672
  };
1444
673
  }
1445
674
  };
@@ -1455,379 +684,214 @@ var OPERATIONS = [
1455
684
  ungroup
1456
685
  ];
1457
686
  var CANCELLED = { kind: "cancelled" };
1458
- var Fell = class extends Error {
1459
- constructor(label) {
1460
- super(`the ${label} fell to System Two`);
1461
- this.label = label;
1462
- }
1463
- };
1464
- function heldMore(decisions) {
1465
- return decisions.some(
1466
- (decision) => decision.others.length > 0 || decision.kind === "steps" && decision.option.value === "several"
1467
- );
1468
- }
1469
- var twoSystems2 = (decision) => decision.composed !== null;
1470
- var composedOf = (decisions) => decisions.flatMap((decision) => decision.composed === null ? [] : [decision.composed]);
1471
- function movedText(operation, error) {
1472
- 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)}`;
1473
- }
1474
- function statedFacts(names2, reading) {
1475
- const fact = (slot, name) => slot === "operation" ? OPERATIONS.some((operation) => operation.id === name) : slot === "module" ? moduleReferences(name)[0] === name : names2.has(name);
1476
- return Object.fromEntries(
1477
- statedSlots(reading).flatMap((slot) => {
1478
- const name = reading[slot];
1479
- return name !== void 0 && fact(slot, name) ? [[slot, name]] : [];
1480
- })
1481
- );
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
+ ];
1482
694
  }
1483
- var asItIs = (apply) => apply();
1484
- async function resolveAndApply(ports, own, change, call, client, signal, trail, notApplied) {
695
+ async function resolveAndApply(ports, change, signal, note) {
1485
696
  const canvas = readCanvas(await latest(ports.source));
1486
- const names2 = canvasNames(canvas);
1487
- const values = [...forms(change.values), ...unnamed(names2, call)];
1488
- const statementOf = (reading) => withhold(renderReading(statedFacts(names2, reading)), values);
1489
- const statement = statementOf(change.reading);
1490
- const alternative = change.alternative === void 0 ? void 0 : { statement: statementOf(change.alternative), reading: change.alternative };
1491
- const statements = [statement, ...alternative === void 0 ? [] : [alternative.statement]];
1492
- const request = renderRequest(
1493
- change.request,
1494
- values,
1495
- statements.reduce((longest, each) => each.length > longest.length ? each : longest)
1496
- );
1497
- const rankable = !holdsValue(withhold([request, ...statements].join(" "), [...names2]), values);
1498
- const rank = client?.rank;
1499
- const main = {
1500
- request,
1501
- terms: termsOf(request.split(VALUE_PLACEHOLDER).join(" ")),
1502
- statement,
1503
- reading: change.reading,
1504
- ...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
+ }
1505
717
  };
1506
- const ask = { ...main, ...alternative === void 0 ? {} : { alternative } };
1507
- const decided2 = (on, kind, label, options, stated2) => {
1508
- stopIfCancelled(signal);
1509
- return decide(on, kind, label, options, stated2);
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)) };
1510
724
  };
1511
- const resolvingInto = (into, trial) => ({
725
+ const resolving = {
1512
726
  canvas,
1513
- request,
1514
- values: change.values,
727
+ change,
1515
728
  ports,
1516
729
  signal,
1517
- async pick(kind, label, options) {
1518
- const decision = await decided2(ask, kind, label, options);
1519
- into.decisions.push(decision);
1520
- if (trial && !moveStands(composedOf(into.decisions.slice(1)))) throw new Fell(label);
1521
- return decision.option.value;
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;
1522
736
  },
1523
- note: (line) => into.notes.push(line)
1524
- });
1525
- const planUnder = (decision, into, trial) => {
1526
- into.decisions.push(decision);
1527
- return decision.option.value.plan(resolvingInto(into, trial));
737
+ note
1528
738
  };
1529
- const first = await decided2(ask, "operation", "operation", operationOptions(OPERATIONS));
1530
- const statedOperation = operationOptions(OPERATIONS).find(
1531
- (each) => each.candidate.id === first.chat
1532
- );
1533
- const moveRule = async () => {
1534
- if (first.how !== "clm" || statedOperation === void 0 || statedOperation.value === first.option.value) {
1535
- return { operation: first.option.value, plan: await planUnder(first, trail, false) };
1536
- }
1537
- const trial = { decisions: [], notes: [] };
1538
- try {
1539
- const planned = await planUnder(first, trial, true);
1540
- trail.decisions.push(...trial.decisions);
1541
- trail.notes.push(...trial.notes);
1542
- return { operation: first.option.value, plan: planned };
1543
- } catch (error) {
1544
- stopIfCancelled(signal);
1545
- trail.moved = withhold(movedText(first.option.value.id, error), change.values);
1546
- const standing = {
1547
- ...first,
1548
- option: statedOperation,
1549
- how: "chat",
1550
- composed: {
1551
- took: "chat",
1552
- taken: statedOperation.candidate.id,
1553
- clm: first.composed?.clm ?? null,
1554
- differed: false
1555
- },
1556
- alternative: first.alternative?.id === first.option.candidate.id ? null : first.alternative
1557
- };
1558
- return { operation: statedOperation.value, plan: await planUnder(standing, trail, false) };
1559
- }
1560
- };
1561
- const { operation, plan } = await moveRule();
1562
- const unread = trail.decisions.every((decision) => decision.others.length === 0);
1563
- if (unread && main.rank !== void 0 && trail.decisions.some(twoSystems2)) {
1564
- const steps = await decided2(main, "steps", "steps", stepsOptions(), "one");
1565
- if (steps.ranking !== NOT_RANKED) trail.decisions.push(steps);
1566
- }
1567
- if (change.values.length > 0 && !operation.takesValue && !heldMore(trail.decisions)) {
1568
- trail.notes.push(
1569
- `The \`value\` sent with this change was not used: ${operation.id} takes none.`
1570
- );
1571
- }
1572
- const lace = Object.assign({}, ...trail.decisions.map((each) => each.option.slots));
1573
- const stated = statedSlots(change.reading);
1574
- for (const slot of stated.filter(
1575
- (slot2) => !trail.decisions.some(
1576
- (decision) => decision.readings.some((each) => each[slot2] === change.reading[slot2])
1577
- )
1578
- )) {
1579
- trail.notes.push(
1580
- `Your reading's ${slot} ${change.reading[slot]} is not one of Lace's candidates${slot in lace ? `; Lace read ${lace[slot]}` : ""}.`
1581
- );
1582
- }
1583
- const asked = trail.decisions.filter(
1584
- (decision) => decision.alternative?.sure === true && decision.alternative.id !== decision.option.candidate.id
1585
- );
1586
- if (asked.length > 0) {
1587
- return {
1588
- kind: "asked",
1589
- lace,
1590
- alternative: Object.assign(
1591
- {},
1592
- ...trail.decisions.map(
1593
- (decision) => asked.includes(decision) ? decision.alternative?.slots : decision.option.slots
1594
- )
1595
- )
1596
- };
1597
- }
739
+ for (const line of unusedLines(change)) note(line);
740
+ const plan = await change.operation.plan(resolving);
1598
741
  stopIfCancelled(signal);
1599
- const result = await own(() => ports.editor.apply([plan.action]));
742
+ const result = await ports.editor.apply([plan.action]);
1600
743
  if (!result.success) {
1601
- const reasons = result.errors.map((error) => error.message).join("; ");
1602
- return notApplied(`the engine refused it: ${reasons}`);
744
+ const refusals = result.errors.map((error) => error.message).join("; ");
745
+ return {
746
+ kind: "notApplied",
747
+ why: `the engine refused it: ${withhold(refusals, change.value)}`
748
+ };
1603
749
  }
1604
750
  const after = readCanvas(await latest(ports.source));
1605
- const record = {
1606
- id: crypto.randomUUID(),
1607
- target: plan.target(result),
1608
- before: plan.before,
1609
- after: plan.after(after, result),
1610
- ...result.revision === void 0 ? {} : { revision: result.revision },
1611
- questions: trail.decisions.map((decision) => ({
1612
- kind: decision.kind,
1613
- candidates: decision.candidates.map((candidate) => candidate.id)
1614
- })),
1615
- reported: false
1616
- };
1617
- return {
1618
- kind: "applied",
1619
- summary: plan.summary(result),
1620
- record,
1621
- canvas: after,
1622
- withheld: unnamed(names2, call)
1623
- };
751
+ return { kind: "applied", summary: plan.summary(result, after) };
1624
752
  }
1625
- async function runChange(ports, own, change, call, client, signal, trail) {
1626
- const notApplied = (why) => ({
1627
- kind: "notApplied",
1628
- why: withhold(why, change.values)
1629
- });
753
+ async function runChange(ports, change, signal, note) {
1630
754
  try {
1631
- return await resolveAndApply(ports, own, change, call, client, signal, trail, notApplied);
755
+ return await resolveAndApply(ports, change, signal, note);
1632
756
  } catch (error) {
1633
757
  if (error instanceof ApplyUnobservedError) {
1634
- return { kind: "unobserved", end: withhold(endText(error.end), change.values) };
758
+ return { kind: "unobserved", end: withhold(endText(error.end), change.value) };
1635
759
  }
1636
760
  if (error instanceof Cancelled) return CANCELLED;
1637
- if (error instanceof Undecided) {
1638
- trail.undecided = error;
1639
- const candidates = error.candidates.map((candidate) => candidate.id).join(", ");
1640
- return notApplied(
1641
- `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.`
1642
- );
1643
- }
1644
- return notApplied(errorText(error));
761
+ if (error instanceof Unapplicable) return { kind: "notApplied", why: error.message };
762
+ return { kind: "notApplied", why: withhold(errorText(error), change.value) };
1645
763
  }
1646
764
  }
1647
- function rankingText(ranking2) {
1648
- if (ranking2.ranked === null) return ranking2.failed;
1649
- const [first] = ranking2.ranked.scores;
1650
- const read2 = first?.id === NONE_CANDIDATE_ID ? `read ${NONE_OVER} first` : `ranked ${first?.id} first`;
1651
- return `Lace was not sure, ${read2}`;
1652
- }
1653
- function decisionLine(decision, moved2) {
1654
- const also = `the request also names ${decision.others.join(", ")}`;
1655
- const named2 = {
1656
- exact: ["named in the request"],
1657
- unique: ["named in the request, ignoring case"],
1658
- first: ["named in the request first", also],
1659
- agreed: ["named in the request and in your reading", also]
1660
- };
1661
- const basis = decision.how === "clm" ? [
1662
- `Lace's pick of ${decision.offered}`,
1663
- ...decision.offered > decision.candidates.length ? [`ranked in parts, as ${decision.offered} candidates are more than one ranking holds`] : [],
1664
- ...decision.over.map((candidate) => `over ${candidate}`),
1665
- ...decision.composed?.differed ? [`your reading named ${decision.chat}`] : []
1666
- ] : decision.how === "chat" ? [
1667
- "your reading",
1668
- moved2 !== void 0 && decision.kind === "operation" ? moved2 : decision.ranking === null ? "Lace did not rank" : rankingText(decision.ranking)
1669
- ] : named2[decision.how];
1670
- return ` ${decision.label}: ${decision.option.candidate.id} (${basis.join(", ")})`;
1671
- }
1672
- function outcomeLines(number, outcome, trail) {
765
+ function outcomeLine(number, outcome) {
1673
766
  const head = `Change ${number}:`;
1674
- const lines = trail.decisions.map((decision) => decisionLine(decision, trail.moved));
1675
767
  switch (outcome.kind) {
1676
- case "applied": {
1677
- const moved2 = trail.moved === void 0 ? "" : " Lace's operation did not stand and yours did, marked below.";
1678
- const unsure = trail.decisions.some(
1679
- (decision) => decision.how === "chat" && (trail.moved === void 0 || decision.kind !== "operation")
1680
- );
1681
- const stood = unsure ? " Where Lace was not sure, your reading stood, marked below." : "";
1682
- const differed = trail.decisions.some((decision) => decision.composed?.differed) ? " Lace's reading differed from yours and stood, marked below: tell the developer." : "";
1683
- const others = trail.decisions.flatMap((decision) => decision.others);
1684
- const unapplied = others.length > 0 ? `; nothing was applied for ${others.join(", ")}` : "";
1685
- 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.` : "";
1686
- return [`${head} applied. ${outcome.summary}.${more}${moved2}${stood}${differed}`, ...lines];
1687
- }
1688
- case "asked":
1689
- return [
1690
- `${head} not applied. Lace is sure your alternative reading means another change than the one it decided.`,
1691
- ` Your reading: ${renderReading(outcome.lace)}`,
1692
- ` Your alternative reading: ${renderReading(outcome.alternative)}`,
1693
- " Ask the developer which is meant, then send that one."
1694
- ];
768
+ case "applied":
769
+ return `${head} applied. ${outcome.summary}.`;
1695
770
  case "notApplied":
1696
- return [`${head} not applied. Reason: ${outcome.why}`, ...lines];
771
+ return `${head} not applied. Reason: ${outcome.why}`;
1697
772
  case "cancelled":
1698
- return [`${head} not applied. The call was cancelled before it applied.`];
773
+ return `${head} not applied. The call was cancelled before it applied.`;
1699
774
  case "unobserved":
1700
- return [
1701
- `${head} sent, and the engine answered it, but the session's stream ended (${outcome.end}) before the canvas showed it, so whether it applied cannot be read here. Do not send it again before the canvas is open again.`,
1702
- ...lines
1703
- ];
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.`;
1704
778
  }
1705
779
  }
1706
- function questionOf(decision) {
1707
- const taken = decision.option.candidate.id;
1708
- return {
1709
- kind: decision.kind,
1710
- capture_id: asAsked(decision.ranking)?.capture_id ?? null,
1711
- chat: decision.chat,
1712
- clm: decision.composed?.clm ?? null,
1713
- took: decision.composed === null ? "named" : decision.composed.took,
1714
- taken
1715
- };
1716
- }
1717
- function undecidedOf(undecided) {
1718
- const ranked = asAsked(undecided.ranking);
1719
- const pick = ranked === null ? void 0 : pickOf(ranked.scores);
1720
- return {
1721
- kind: undecided.kind,
1722
- capture_id: ranked?.capture_id ?? null,
1723
- chat: null,
1724
- clm: pick === void 0 ? null : { id: pick.id, rightness: pick.rightness },
1725
- took: "chat",
1726
- taken: null
1727
- };
1728
- }
1729
- function reportOf(id, trail, applied, asked) {
1730
- const questions = [
1731
- ...trail.decisions.map(questionOf),
1732
- ...trail.undecided === void 0 ? [] : [undecidedOf(trail.undecided)]
1733
- ];
1734
- return questions.some((question) => question.took !== "named") ? { id, surface: "canvas", questions, applied, asked } : void 0;
1735
- }
1736
- async function applyChanges(ports, changes, own = asItIs, signal) {
1737
- const call = changes.flatMap((change) => change.values);
1738
- const client = ports.transport === void 0 ? void 0 : rankingClient(ports.transport).changeCall(signal);
780
+ async function applyChanges(ports, changes, signal) {
1739
781
  const lines = [];
1740
- let applied = [];
1741
- const unapplied = [];
1742
- let last;
782
+ let ended = false;
1743
783
  for (const [index, change] of changes.entries()) {
1744
- const trail = { decisions: [], notes: [] };
1745
- const outcome = signal?.aborted ? CANCELLED : await runChange(ports, own, change, call, client, signal, 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";
1746
787
  lines.push(
1747
- ...outcomeLines(index + 1, outcome, trail),
1748
- ...outcome.kind === "cancelled" ? [] : trail.notes.map((line) => ` ${line}`)
788
+ outcomeLine(index + 1, outcome),
789
+ ...outcome.kind === "cancelled" || outcome.kind === "notRun" ? [] : notes.map((line) => ` ${line}`)
1749
790
  );
1750
- if (outcome.kind === "applied") {
1751
- const { canvas } = outcome;
1752
- const before = last;
1753
- applied = [
1754
- ...before === void 0 ? [] : applied.map((each) => ({ ...each, record: follow(each.record, before, canvas) })),
1755
- { record: outcome.record, withheld: outcome.withheld, trail }
1756
- ];
1757
- last = canvas;
1758
- } else if (outcome.kind !== "unobserved" && outcome.kind !== "cancelled") {
1759
- const report = reportOf(crypto.randomUUID(), trail, null, outcome.kind === "asked");
1760
- if (report !== void 0) unapplied.push(report);
1761
- }
1762
791
  }
1763
- const left = last;
1764
- const settled = left === void 0 ? [] : applied.map(({ record, withheld, trail }) => {
1765
- const standing = { ...record, after: targetState(left, record) };
1766
- const report = reportOf(record.id, trail, appliedText(standing, withheld), false);
1767
- return { record: standing, report };
1768
- });
1769
- const reports = [
1770
- ...signal?.aborted ? [] : unapplied,
1771
- ...settled.flatMap(({ report }) => report === void 0 ? [] : [report])
1772
- ];
1773
- const sent = client === void 0 ? [] : reports.map((report) => ({ report, ...client.decision(report) }));
1774
- const made = new Set(sent.flatMap(({ report, made: made2 }) => made2 ? [report] : []));
1775
- try {
1776
- await untilCancelled(Promise.all(sent.map(({ settled: settled2 }) => settled2)), signal);
1777
- } catch (error) {
1778
- if (!(error instanceof Cancelled)) throw error;
792
+ return lines.join("\n");
793
+ }
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)`;
1779
800
  }
1780
- const records = settled.map(({ record, report }) => ({
1781
- ...record,
1782
- reported: report !== void 0 && made.has(report)
1783
- }));
1784
- return { text: lines.join("\n"), applied: records };
1785
- }
1786
- function appliedText(record, withheld) {
1787
- return withhold(
1788
- `${renderTarget(record.target)}: ${renderState(record.before)} \u2192 ${renderState(record.after)}`,
1789
- withheld
1790
- );
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");
1791
864
  }
1792
865
 
1793
866
  // src/surfaces/canvas/canvas-tools.ts
1794
- var READING_PROPERTIES = {
1795
- operation: {
1796
- type: "string",
1797
- enum: OPERATIONS.map((operation) => operation.id),
1798
- description: OPERATIONS.map((operation) => OPERATION_TEXT[operation.id]).join("; ")
1799
- },
867
+ var STATED_PROPERTIES = {
1800
868
  instance: {
1801
869
  type: "string",
1802
- 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."
1803
871
  },
1804
872
  input: {
1805
873
  type: "string",
1806
874
  description: "The input a set, bind, clear or disconnect works on, or a connect wires into."
1807
875
  },
1808
- sourceInstance: {
1809
- type: "string",
1810
- description: "The instance a connect wires from."
1811
- },
876
+ sourceInstance: { type: "string", description: "The instance a connect wires from." },
1812
877
  output: { type: "string", description: "The output a connect wires from." },
1813
- targetInstance: {
1814
- type: "string",
1815
- description: "The instance a connect wires into."
1816
- },
878
+ targetInstance: { type: "string", description: "The instance a connect wires into." },
1817
879
  module: {
1818
880
  type: "string",
1819
- 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."
1820
882
  }
1821
883
  };
1822
- var READING = { type: "object", properties: READING_PROPERTIES, additionalProperties: false };
1823
884
  var CHANGE = {
1824
885
  name: "lace_change_module_canvas",
1825
886
  title: "Change module canvas",
1826
887
  description: [
1827
- "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.",
1828
- "`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.",
1829
- "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`.",
1830
- "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."
1831
895
  ].join(" "),
1832
896
  inputSchema: {
1833
897
  type: "object",
@@ -1839,17 +903,17 @@ var CHANGE = {
1839
903
  items: {
1840
904
  type: "object",
1841
905
  properties: {
1842
- request: {
906
+ operation: {
1843
907
  type: "string",
1844
- 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("; ")
1845
910
  },
911
+ ...STATED_PROPERTIES,
1846
912
  value: {
1847
- 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."
1848
- },
1849
- modelReading: READING,
1850
- 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
+ }
1851
915
  },
1852
- required: ["request", "modelReading"],
916
+ required: ["operation"],
1853
917
  additionalProperties: false
1854
918
  }
1855
919
  }
@@ -1861,7 +925,7 @@ var CHANGE = {
1861
925
  var DESCRIBE = {
1862
926
  name: "lace_describe_module_canvas",
1863
927
  title: "Describe module canvas",
1864
- 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.",
1865
929
  inputSchema: NO_INPUT
1866
930
  };
1867
931
  var SAVE = {
@@ -1918,13 +982,8 @@ function cancelledSaid(operation, sent) {
1918
982
  isError: false
1919
983
  };
1920
984
  }
1921
- var NO_RECORDS = { applied: [] };
1922
985
  function canvasTools(ports) {
1923
986
  const [change, describe, save, generate] = canvasToolSchemas;
1924
- const observer = ports.transport === void 0 ? void 0 : outcomeObserver(ports.transport);
1925
- const dispose = observer === void 0 ? () => {
1926
- } : ports.source.subscribe(observer.frame, () => {
1927
- });
1928
987
  const attempt = (run) => run().catch((error) => [{ text: errorText(error), isError: true }]);
1929
988
  const answer = async (said2) => ({
1930
989
  content: [
@@ -1934,26 +993,16 @@ function canvasTools(ports) {
1934
993
  ].join("\n"),
1935
994
  isError: said2.some((each) => each.isError)
1936
995
  });
1937
- const registrations = [
1938
- registrationOf(
1939
- change,
1940
- async (input, signal) => {
1941
- try {
1942
- const { text: text2, applied } = await applyChanges(
1943
- ports,
1944
- parseChanges(input),
1945
- observer?.own,
1946
- signal
1947
- );
1948
- observer?.follow(applied);
1949
- return { ...await answer([{ text: text2, isError: false }]), applied };
1950
- } catch (error) {
1951
- if (!(error instanceof InvalidInput)) throw error;
1952
- return { ...await answer([{ text: errorText(error), isError: true }]), ...NO_RECORDS };
1953
- }
1954
- },
1955
- (failure) => ({ ...failure, ...NO_RECORDS })
1956
- ),
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
+ }),
1957
1006
  registration(describe, () => answer([])),
1958
1007
  registration(
1959
1008
  save,
@@ -1991,7 +1040,6 @@ function canvasTools(ports) {
1991
1040
  )
1992
1041
  )
1993
1042
  ];
1994
- return Object.assign(registrations, { dispose });
1995
1043
  }
1996
1044
 
1997
1045
  // src/surfaces/canvas/module-tools.ts
@@ -2001,7 +1049,7 @@ var VALIDATE = {
2001
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.",
2002
1050
  inputSchema: NO_INPUT
2003
1051
  };
2004
- var SEARCH = {
1052
+ var SEARCH2 = {
2005
1053
  name: "lace_search_module_registry",
2006
1054
  title: "Search module registry",
2007
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.",
@@ -2031,7 +1079,7 @@ var DESCRIBE2 = {
2031
1079
  };
2032
1080
  var moduleToolSchemas = [
2033
1081
  VALIDATE,
2034
- SEARCH,
1082
+ SEARCH2,
2035
1083
  DESCRIBE2
2036
1084
  ];
2037
1085
  function said(run, trim) {
@@ -2043,7 +1091,7 @@ function said(run, trim) {
2043
1091
  };
2044
1092
  }
2045
1093
  function moduleTool(schema, run) {
2046
- return registrationOf(schema, run, (failure) => failure);
1094
+ return registration(schema, run);
2047
1095
  }
2048
1096
  function text(value) {
2049
1097
  return typeof value === "string" ? value : void 0;
@@ -2088,21 +1136,11 @@ function moduleTools({ commands }) {
2088
1136
  ];
2089
1137
  }
2090
1138
  export {
2091
- DECISION_KINDS,
2092
- NONE_CANDIDATE_ID,
2093
- VALUE_PLACEHOLDER,
2094
1139
  canvasToolSchemas,
2095
1140
  canvasTools,
2096
- changeOutcomes,
2097
- compose,
2098
1141
  createToolRegistry,
2099
1142
  moduleToolSchemas,
2100
1143
  moduleTools,
2101
- partOf,
2102
- renderCandidate,
2103
- renderCanvas,
2104
- renderRequest,
2105
- sure,
2106
- trainingRows
1144
+ renderCanvas
2107
1145
  };
2108
1146
  //# sourceMappingURL=index.mjs.map