@lace-cloud/chat-core 0.20.0 → 0.21.1

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