@lace-cloud/chat-core 0.18.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,617 +1,2108 @@
1
- // src/exhaustive.ts
2
- function assertNever(value) {
3
- throw new Error(`Unhandled closed-enum branch: ${JSON.stringify(value)}`);
1
+ // src/contract/tool-registry.ts
2
+ function createToolRegistry() {
3
+ const entries = /* @__PURE__ */ new Map();
4
+ return {
5
+ register(schema, handler) {
6
+ entries.set(schema.name, { schema, handler });
7
+ },
8
+ getHandler(name) {
9
+ return entries.get(name)?.handler;
10
+ },
11
+ listSchemas() {
12
+ return [...entries.values()].map((e) => e.schema);
13
+ },
14
+ listNames() {
15
+ return [...entries.keys()];
16
+ }
17
+ };
18
+ }
19
+
20
+ // src/questions/bounds.ts
21
+ var RANK_CANDIDATES_MAX = 256;
22
+ var RANK_REQUEST_MAX_CHARS = 4e3;
23
+ var RANK_CANDIDATE_TEXT_MAX_CHARS = 2e3;
24
+
25
+ // src/questions/types.ts
26
+ var DECISION_KINDS = [
27
+ "operation",
28
+ "instance",
29
+ "input",
30
+ "module",
31
+ "connection",
32
+ "steps"
33
+ ];
34
+ var NONE_CANDIDATE_ID = "(none)";
35
+
36
+ // src/questions/candidate.ts
37
+ function pinRef(instance, pin) {
38
+ return `${instance}.${pin}`;
39
+ }
40
+ function connectionId(from, to) {
41
+ return `${from} \u2192 ${to}`;
42
+ }
43
+ var OPERATION_TEXT = {
44
+ place: "place: add a registry module to the canvas as a new instance",
45
+ connect: "connect: wire an output of one instance into an input of another",
46
+ disconnect: "disconnect: remove the wire into an instance's input",
47
+ set: "set: give an input of an instance a literal value",
48
+ bind: "bind: make an input of an instance take its value from a variable of the module (`var.<name>`), so the module's caller sets it",
49
+ clear: "clear: unset an input of an instance, removing the value, variable or expression it holds",
50
+ rename: "rename: give an instance a new name",
51
+ delete: "delete: remove an instance from the canvas",
52
+ ungroup: "ungroup: dissolve a group, moving the instances inside it up beside it"
53
+ };
54
+ var STEPS_TEXT = {
55
+ one: "one change: the request asks for a single change to the canvas",
56
+ several: "several changes: the request asks for more than one change to the canvas"
57
+ };
58
+ var NONE_TEXT = {
59
+ operation: "asks for no change these operations make",
60
+ instance: "means no instance on this canvas",
61
+ input: "means no input of this instance",
62
+ module: "means no module of this registry listing",
63
+ connection: "means no wire between these two instances"
64
+ };
65
+ function noneCandidate(kind) {
66
+ return { id: NONE_CANDIDATE_ID, kind, text: `none of these: the request ${NONE_TEXT[kind]}` };
67
+ }
68
+ function rankCandidates(kind, candidates) {
69
+ return kind === "steps" ? [...candidates] : [...candidates, noneCandidate(kind)];
70
+ }
71
+ var CUT_MARK = "\u2026";
72
+ function shortened(text2, limit) {
73
+ if (text2.length <= limit) return text2;
74
+ const room = text2.slice(0, Math.max(limit - CUT_MARK.length + 1, 0));
75
+ const end = room.search(/\s+\S*$/);
76
+ const kept = end === -1 ? "" : room.slice(0, end).trimEnd();
77
+ return kept === "" ? "" : `${kept}${CUT_MARK}`;
78
+ }
79
+ var WHOLE = { prose: Number.POSITIVE_INFINITY, names: Number.POSITIVE_INFINITY };
80
+ function prose(text2, cut) {
81
+ const kept = shortened(text2, cut.prose);
82
+ return kept === "" && text2 !== "" ? void 0 : kept;
83
+ }
84
+ function listed(items, cut, render) {
85
+ const kept = items.slice(0, cut.names).map(render);
86
+ const more = items.length - kept.length;
87
+ return [...kept, ...more > 0 ? [`and ${more} more`] : []].join(", ");
88
+ }
89
+ function worded(table, what, id) {
90
+ const text2 = table[id];
91
+ if (text2 === void 0) throw new Error(`no ${what} is named ${id}`);
92
+ return text2;
93
+ }
94
+ var about = (instance, module) => `instance ${instance} of module ${module}`;
95
+ var names = (pins, cut) => listed(pins, cut, (pin) => pin.name);
96
+ var described = (pins, cut) => listed(pins, cut, (pin) => {
97
+ const description = pin.description === void 0 ? void 0 : prose(pin.description, cut);
98
+ return description === void 0 ? pin.name : `${pin.name} (${description})`;
99
+ });
100
+ var INSTANCE_TEXT = {
101
+ instance: (f, cut) => `${about(f.id, f.module)}; inputs: ${described(f.inputs, cut)}; outputs: ${described(f.outputs, cut)}`,
102
+ source: (f, cut) => `the wire starts at an output of ${about(f.id, f.module)}; its outputs: ${names(f.outputs, cut)}`,
103
+ target: (f, cut) => `the wire ends at an input of ${about(f.id, f.module)}; its inputs no wire feeds: ${names(f.inputs, cut)}`
104
+ };
105
+ function textOf(facts, cut) {
106
+ switch (facts.kind) {
107
+ case "operation":
108
+ return worded(OPERATION_TEXT, "operation", facts.id);
109
+ case "steps":
110
+ return worded(STEPS_TEXT, "reading of the steps", facts.id);
111
+ case "instance":
112
+ return INSTANCE_TEXT[facts.role](facts, cut);
113
+ case "input": {
114
+ const type = prose(facts.type, cut);
115
+ return [
116
+ `input ${facts.id} of ${about(facts.instance, facts.module)}`,
117
+ type === void 0 ? void 0 : `type ${type}`,
118
+ facts.required ? "required" : "optional",
119
+ facts.state,
120
+ facts.description === void 0 ? void 0 : prose(facts.description, cut)
121
+ ].filter((part) => part !== void 0).join("; ");
122
+ }
123
+ case "module":
124
+ return `registry module ${facts.id} (${facts.displayName}): ${prose(facts.description, cut) ?? ""}; system ${facts.system}; categories: ${listed(facts.categories, cut, (category) => category)}`;
125
+ case "connection": {
126
+ const scored = facts.score === void 0 ? "the engine's matcher gives this pair no score" : `the engine's matcher scores this pair ${facts.score}`;
127
+ return `wire output ${pinRef(facts.source, facts.output)} into input ${pinRef(facts.target, facts.input)}; ${scored}`;
128
+ }
129
+ }
130
+ }
131
+ function largest(most, fits) {
132
+ if (!fits(0)) return void 0;
133
+ let [low, high] = [0, most];
134
+ while (low < high) {
135
+ const middle = Math.ceil((low + high) / 2);
136
+ if (fits(middle)) low = middle;
137
+ else high = middle - 1;
138
+ }
139
+ return low;
140
+ }
141
+ function fitted(facts) {
142
+ const most = RANK_CANDIDATE_TEXT_MAX_CHARS;
143
+ const fits = (cut) => textOf(facts, cut).length <= most;
144
+ if (fits(WHOLE)) return textOf(facts, WHOLE);
145
+ const proseCut = largest(most, (n) => fits({ prose: n, names: WHOLE.names }));
146
+ if (proseCut !== void 0) return textOf(facts, { prose: proseCut, names: WHOLE.names });
147
+ const namesCut = largest(most, (n) => fits({ prose: 0, names: n }));
148
+ if (namesCut !== void 0) return textOf(facts, { prose: 0, names: namesCut });
149
+ return shortened(textOf(facts, { prose: 0, names: 0 }), most);
150
+ }
151
+ function renderCandidate(facts) {
152
+ return { id: facts.id, kind: facts.kind, text: fitted(facts) };
153
+ }
154
+
155
+ // src/questions/reading.ts
156
+ var READING_SLOTS = [
157
+ "operation",
158
+ "instance",
159
+ "input",
160
+ "sourceInstance",
161
+ "output",
162
+ "targetInstance",
163
+ "module"
164
+ ];
165
+ function statedSlots(reading) {
166
+ return READING_SLOTS.filter((slot) => reading[slot] !== void 0);
167
+ }
168
+ function renderReading(reading) {
169
+ return statedSlots(reading).map((slot) => `${slot}=${reading[slot]}`).join(", ");
170
+ }
171
+
172
+ // src/questions/render.ts
173
+ var VALUE_PLACEHOLDER = "<value>";
174
+ function literalTexts(value) {
175
+ if (typeof value === "string") return [value];
176
+ if (typeof value === "number" || typeof value === "boolean") return [String(value)];
177
+ if (typeof value === "object" && value !== null)
178
+ return Object.values(value).flatMap(literalTexts);
179
+ return [];
180
+ }
181
+ function literals(values) {
182
+ return values.flatMap(literalTexts).filter((literal) => literal !== "").sort((a, b) => b.length - a.length);
183
+ }
184
+ function variableName(text2) {
185
+ return text2.replace(/^var\./, "");
186
+ }
187
+ function forms(values) {
188
+ return [...new Set(literals(values).flatMap((text2) => [text2, variableName(text2)]))];
189
+ }
190
+ function unnamed(names2, values) {
191
+ return forms(values).filter((text2) => !names2.has(text2));
192
+ }
193
+ function escapeRegExp(text2) {
194
+ return text2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
195
+ }
196
+ var NAME = /^[A-Za-z0-9_-]+$/;
197
+ function occurrences(literal) {
198
+ const text2 = escapeRegExp(literal);
199
+ return NAME.test(literal) ? new RegExp(`(?<![A-Za-z0-9_-])${text2}(?![A-Za-z0-9_-])`, "g") : new RegExp(text2, "g");
200
+ }
201
+ function withhold(text2, values) {
202
+ return literals(values).reduce(
203
+ (rest, literal) => rest.replace(occurrences(literal), VALUE_PLACEHOLDER),
204
+ text2
205
+ );
206
+ }
207
+ function holdsValue(rendered, values) {
208
+ return literals(values).some((literal) => rendered.includes(literal));
209
+ }
210
+ function renderRequest(request, values, statement = "") {
211
+ return shortened(withhold(request, values), RANK_REQUEST_MAX_CHARS - statement.length);
4
212
  }
5
213
 
6
- // src/history.ts
7
- var DEFAULT_TURN_CAP = 50;
8
- function capRecentMessages(messages, turnCap = DEFAULT_TURN_CAP) {
9
- const limit = turnCap * 2;
10
- if (messages.length <= limit) return messages;
11
- return messages.slice(messages.length - limit);
214
+ // src/examples/rows.ts
215
+ function hashFraction(key) {
216
+ let hash = 2166136261;
217
+ for (const char of key) {
218
+ hash ^= char.codePointAt(0) ?? 0;
219
+ hash = Math.imul(hash, 16777619) >>> 0;
220
+ }
221
+ return hash / 2 ** 32;
222
+ }
223
+ function partOf(key) {
224
+ const at2 = hashFraction(key);
225
+ return at2 < 0.6 ? "train" : at2 < 0.8 ? "calibration" : "held_out";
226
+ }
227
+ function trainingRows(turn, part) {
228
+ return turn.questions.map(({ candidates, label, chat }) => ({
229
+ request: turn.request,
230
+ statement: turn.statement,
231
+ candidates,
232
+ label,
233
+ part,
234
+ origin: turn.origin,
235
+ turn: turn.id,
236
+ chat
237
+ }));
12
238
  }
13
239
 
14
- // src/telemetry.ts
15
- var MAX_SESSIONS = 100;
16
- function createTelemetry(log) {
17
- const sessionBuffer = [];
18
- let sessionCounter = 0;
19
- function recordSession(session) {
20
- if (sessionBuffer.length >= MAX_SESSIONS) sessionBuffer.shift();
21
- sessionBuffer.push(session);
240
+ // src/contract/cancel.ts
241
+ var Cancelled = class extends Error {
242
+ constructor() {
243
+ super("the call was cancelled");
22
244
  }
245
+ };
246
+ function stopIfCancelled(signal) {
247
+ if (signal?.aborted) throw new Cancelled();
248
+ }
249
+ function untilCancelled(work, signal) {
250
+ if (signal === void 0) return work;
251
+ let stop = () => {
252
+ };
253
+ const cancelled = new Promise((_, fail) => {
254
+ stop = () => fail(new Cancelled());
255
+ if (signal.aborted) stop();
256
+ else signal.addEventListener("abort", stop, { once: true });
257
+ });
258
+ return Promise.race([work, cancelled]).finally(() => signal.removeEventListener("abort", stop));
259
+ }
260
+ function cancellable(start, signal) {
261
+ if (signal?.aborted) return Promise.reject(new Cancelled());
262
+ return untilCancelled(start(), signal);
263
+ }
264
+
265
+ // src/ranking/client.ts
266
+ var RANK_PATH = "/api/v1/candidates/rank";
267
+ var DECISIONS_PATH = "/api/v1/candidates/decisions";
268
+ var RANKING_CALL_TIMEOUT_MS = 12e3;
269
+ var RankingUnavailable = class extends Error {
270
+ };
271
+ function isRecord(value) {
272
+ return typeof value === "object" && value !== null && !Array.isArray(value);
273
+ }
274
+ var isKind = (value) => DECISION_KINDS.includes(value);
275
+ function scoreOf(value) {
276
+ if (!isRecord(value)) return void 0;
277
+ const { id, score, rightness } = value;
278
+ return typeof id === "string" && typeof score === "number" && typeof rightness === "number" && rightness >= 0 && rightness <= 1 ? { id, score, rightness } : void 0;
279
+ }
280
+ function thresholdsOf(value) {
281
+ if (!isRecord(value)) return void 0;
282
+ const entries = Object.entries(value).map(
283
+ ([kind, threshold]) => isKind(kind) && isRecord(threshold) && typeof threshold.from === "number" ? [kind, { from: threshold.from }] : void 0
284
+ );
285
+ return entries.every((entry) => entry !== void 0) ? Object.fromEntries(entries) : void 0;
286
+ }
287
+ function rankedOf(body) {
288
+ if (!isRecord(body) || !Array.isArray(body.scores)) return void 0;
289
+ const scores = body.scores.map(scoreOf);
290
+ const thresholds = thresholdsOf(body.thresholds);
291
+ return typeof body.capture_id === "string" && typeof body.head === "string" && scores.every((score) => score !== void 0) && thresholds !== void 0 ? { capture_id: body.capture_id, head: body.head, scores, thresholds } : void 0;
292
+ }
293
+ var NotCarried = class extends Error {
294
+ };
295
+ function answerOf(answer) {
296
+ if (!isRecord(answer)) return "failed";
297
+ if (answer.carried === false) return "uncarried";
298
+ return typeof answer.status === "number" ? { status: answer.status, body: answer.body } : "failed";
299
+ }
300
+ var NO_ANSWER = { failed: "the request failed", unanswered: "no answer from Lace" };
301
+ function rankingClient(transport) {
302
+ const post = (path, body, cancel) => {
303
+ if (cancel?.aborted) return Promise.resolve("cancelled");
304
+ const controller = new AbortController();
305
+ const reply = new Promise(
306
+ (made) => made(transport(path, { method: "POST", body, signal: controller.signal }))
307
+ ).then(answerOf).catch(() => "failed");
308
+ let timer;
309
+ const unanswered = new Promise((settle) => {
310
+ timer = setTimeout(() => settle("unanswered"), RANKING_CALL_TIMEOUT_MS);
311
+ });
312
+ return untilCancelled(Promise.race([reply, unanswered]), cancel).catch(() => "cancelled").then((ended) => {
313
+ if (ended === "unanswered" || ended === "cancelled") controller.abort();
314
+ return ended;
315
+ }).finally(() => clearTimeout(timer));
316
+ };
23
317
  return {
24
- startSession(prompt, command) {
25
- sessionCounter += 1;
26
- const session = {
27
- sessionId: `s${sessionCounter}`,
28
- prompt,
29
- command,
30
- toolCalls: [],
31
- rounds: 0,
32
- startTime: Date.now()
318
+ changeCall(cancel) {
319
+ let ended;
320
+ const send = (path, body, signal) => {
321
+ if (ended !== void 0) return { made: false, reply: Promise.resolve(ended) };
322
+ const reply = post(path, body, signal).then((answer) => {
323
+ if (answer === "failed" || answer === "unanswered" || answer === "uncarried") {
324
+ ended = answer;
325
+ }
326
+ return answer;
327
+ });
328
+ return { made: true, reply };
329
+ };
330
+ return {
331
+ async rank(request) {
332
+ const reply = await send(RANK_PATH, request, cancel).reply;
333
+ if (reply === "cancelled") throw new Cancelled();
334
+ if (reply === "uncarried") throw new NotCarried("the host carried nothing");
335
+ if (typeof reply === "string") throw new RankingUnavailable(NO_ANSWER[reply]);
336
+ const ranked = reply.status === 200 ? rankedOf(reply.body) : void 0;
337
+ if (ranked !== void 0) return ranked;
338
+ throw new RankingUnavailable(
339
+ reply.status === 200 ? "the ranking service answered with no ranking" : `status ${reply.status}`
340
+ );
341
+ },
342
+ decision(report) {
343
+ const { made, reply } = send(DECISIONS_PATH, report);
344
+ return { made, settled: reply.then(() => void 0) };
345
+ }
33
346
  };
34
- recordSession(session);
35
- log("");
36
- log(`[${ts()}] \u2500\u2500 session ${session.sessionId} \u2500\u2500`);
37
- log(` prompt: "${truncate(prompt, 120)}"`);
38
- if (command) log(` command: /${command}`);
39
- return session;
40
- },
41
- logToolInvocation(session, name, params, result, durationMs) {
42
- const maxPreview = result.isError ? 500 : 200;
43
- const preview = truncate(result.content, maxPreview);
44
- session.toolCalls.push({
45
- name,
46
- params,
47
- durationMs,
48
- isError: result.isError ?? false,
49
- resultPreview: preview
50
- });
51
- const status = result.isError ? "ERR" : "OK";
52
- log(`[${ts()}] [${session.sessionId}] tool ${name} (${durationMs}ms) ${status}`);
53
- log(` params: ${JSON.stringify(params)}`);
54
- log(result.isError ? ` error: ${preview}` : ` result: ${preview}`);
55
347
  },
56
- endSession(session, maxToolRounds) {
57
- session.endTime = Date.now();
58
- const totalMs = session.endTime - session.startTime;
59
- const errorCount = session.toolCalls.filter((t) => t.isError).length;
60
- const toolNames = session.toolCalls.map((t) => t.name);
61
- const toolCounts = {};
62
- for (const name of toolNames) {
63
- toolCounts[name] = (toolCounts[name] ?? 0) + 1;
64
- }
65
- log(`[${ts()}] [${session.sessionId}] session end (${totalMs}ms)`);
66
- log(` rounds: ${session.rounds}`);
67
- log(` tools: ${session.toolCalls.length} call(s), ${errorCount} error(s)`);
68
- if (Object.keys(toolCounts).length > 0) {
69
- const breakdown = Object.entries(toolCounts).map(([n, c]) => `${n}\xD7${c}`).join(", ");
70
- log(` breakdown: ${breakdown}`);
71
- }
72
- if (maxToolRounds !== void 0 && session.rounds >= maxToolRounds) {
73
- log(
74
- ` \u26A0 session hit maxToolRounds (${maxToolRounds}) \u2014 possible stuck loop. Tool sequence: ${toolNames.join(" \u2192 ")}`
75
- );
348
+ async outcome(decision, outcome) {
349
+ await post(`${DECISIONS_PATH}/${encodeURIComponent(decision)}/outcomes`, outcome);
350
+ }
351
+ };
352
+ }
353
+
354
+ // src/hybrid/compose.ts
355
+ var real = (score) => score.id !== NONE_CANDIDATE_ID;
356
+ function pickOf(scores) {
357
+ return scores.find(real);
358
+ }
359
+ function sure(ranked, kind) {
360
+ const from = ranked.thresholds[kind]?.from;
361
+ const pick = pickOf(ranked.scores);
362
+ return from !== void 0 && pick !== void 0 && ranked.scores[0]?.id !== NONE_CANDIDATE_ID && pick.rightness >= from;
363
+ }
364
+ function compose({ kind, chat, ranked }) {
365
+ const pick = ranked === null ? void 0 : pickOf(ranked.scores);
366
+ const clm = pick === void 0 ? null : { id: pick.id, rightness: pick.rightness };
367
+ if (ranked !== null && clm !== null && sure(ranked, kind)) {
368
+ return { took: "clm", taken: clm.id, clm, differed: chat !== null && chat !== clm.id };
369
+ }
370
+ return { took: "chat", taken: chat, clm, differed: false };
371
+ }
372
+ function moveStands(under) {
373
+ return under.every((question) => question.took === "clm");
374
+ }
375
+
376
+ // src/surfaces/canvas/canvas-tools.ts
377
+ import { ApplyUnobservedError as ApplyUnobservedError2 } from "@lace-cloud/canvas/engine";
378
+
379
+ // src/surfaces/canvas/change.ts
380
+ import { ApplyUnobservedError, InputMode } from "@lace-cloud/canvas/engine";
381
+
382
+ // src/surfaces/canvas/commands.ts
383
+ import {
384
+ CommandExitError
385
+ } from "@lace-cloud/canvas/engine";
386
+
387
+ // src/surfaces/canvas/enumerate.ts
388
+ import {
389
+ deriveNodeConfig,
390
+ projectCanvasView,
391
+ resolveInstance
392
+ } from "@lace-cloud/proto";
393
+ function readCanvas(source) {
394
+ const { bundle } = source;
395
+ const view = projectCanvasView(bundle, void 0, {
396
+ canUndo: source.canUndo,
397
+ canRedo: source.canRedo,
398
+ unsaved: source.unsaved
399
+ });
400
+ const calls = [...view.nodes, ...view.groups];
401
+ const instances = calls.flatMap((call) => {
402
+ const owner = resolveInstance(bundle, call.id);
403
+ const config = deriveNodeConfig(bundle, call.id);
404
+ if (owner === null || config === null || call.module_key === void 0) return [];
405
+ const declared = bundle.modules[call.module_key]?.interface?.inputs ?? [];
406
+ const sensitive = new Set(declared.filter((def) => def.sensitive).map((def) => def.name));
407
+ return [
408
+ {
409
+ id: call.id,
410
+ name: owner.child.id,
411
+ scope: owner.scopeKey,
412
+ module: call.module_key,
413
+ inputs: config.inputs.map((input) => ({ ...input, sensitive: sensitive.has(input.name) })),
414
+ outputs: config.outputs
76
415
  }
77
- if (session.toolCalls.length === 0 && session.prompt.trim().length > 10) {
78
- log(` \u26A0 unmatched intent: no tools called for "${truncate(session.prompt, 100)}"`);
416
+ ];
417
+ });
418
+ return {
419
+ module: view.module_name,
420
+ entry: bundle.entry,
421
+ instances,
422
+ wires: view.edges,
423
+ groups: view.groups.map((group) => ({ id: group.id, members: group.node_ids }))
424
+ };
425
+ }
426
+ function canvasNames(canvas) {
427
+ return new Set(
428
+ canvas.instances.flatMap((instance) => [
429
+ instance.id,
430
+ instance.name,
431
+ instance.module,
432
+ instance.scope,
433
+ ...instance.inputs.map((input) => input.name),
434
+ ...instance.outputs.map((output) => output.name)
435
+ ])
436
+ );
437
+ }
438
+ function offered(facts, rest) {
439
+ return { facts, candidate: renderCandidate(facts), ...rest };
440
+ }
441
+ var pinFacts = (pins) => pins.map(
442
+ (pin) => pin.description ? { name: pin.name, description: pin.description } : { name: pin.name }
443
+ );
444
+ function unwired(instance) {
445
+ return instance.inputs.filter((input) => input.mode !== "wired");
446
+ }
447
+ function instanceFacts(instance, role) {
448
+ return {
449
+ id: instance.id,
450
+ kind: "instance",
451
+ role,
452
+ module: instance.module,
453
+ inputs: pinFacts(role === "target" ? unwired(instance) : instance.inputs),
454
+ outputs: pinFacts(instance.outputs)
455
+ };
456
+ }
457
+ function operationOptions(operations) {
458
+ return operations.map(
459
+ (operation) => offered(
460
+ { id: operation.id, kind: "operation" },
461
+ { refs: [[operation.id]], slots: { operation: operation.id }, value: operation }
462
+ )
463
+ );
464
+ }
465
+ function instanceOptions(instances) {
466
+ return instances.map(
467
+ (instance) => offered(instanceFacts(instance, "instance"), {
468
+ refs: [[instance.id], [instance.name]],
469
+ slots: { instance: instance.id },
470
+ value: instance
471
+ })
472
+ );
473
+ }
474
+ function sourceOptions(instances) {
475
+ return instances.filter((instance) => instance.outputs.length > 0).map(
476
+ (instance) => offered(instanceFacts(instance, "source"), {
477
+ refs: instance.outputs.map((output) => [pinRef(instance.id, output.name)]),
478
+ slots: { sourceInstance: instance.id },
479
+ value: instance
480
+ })
481
+ );
482
+ }
483
+ function targetOptions(instances, source) {
484
+ return instances.filter((instance) => instance.scope === source.scope && instance.id !== source.id).filter((instance) => unwired(instance).length > 0).map(
485
+ (instance) => offered(instanceFacts(instance, "target"), {
486
+ refs: unwired(instance).map((input) => [pinRef(instance.id, input.name)]),
487
+ slots: { targetInstance: instance.id },
488
+ value: instance
489
+ })
490
+ );
491
+ }
492
+ var INPUT_STATE = {
493
+ empty: "not set",
494
+ literal: "set",
495
+ variable: "set",
496
+ expression: "set",
497
+ wired: "wired"
498
+ };
499
+ function inputOptions(instance, inputs) {
500
+ return inputs.map(
501
+ (input) => offered(
502
+ {
503
+ id: input.name,
504
+ kind: "input",
505
+ instance: instance.id,
506
+ module: instance.module,
507
+ type: input.type,
508
+ required: input.required,
509
+ state: INPUT_STATE[input.mode],
510
+ ...input.description === void 0 ? {} : { description: input.description }
511
+ },
512
+ { refs: [[input.name]], slots: { input: input.name }, value: input }
513
+ )
514
+ );
515
+ }
516
+ var STEPS = ["one", "several"];
517
+ function stepsOptions() {
518
+ return STEPS.map((id) => offered({ id, kind: "steps" }, { refs: [], slots: {}, value: id }));
519
+ }
520
+ function moduleId(row) {
521
+ return `${row.author}/${row.name}`;
522
+ }
523
+ function moduleOptions(rows) {
524
+ return rows.map(
525
+ (row) => offered(
526
+ {
527
+ id: moduleId(row),
528
+ kind: "module",
529
+ displayName: row.displayName,
530
+ description: row.description,
531
+ system: row.system,
532
+ categories: row.categories
533
+ },
534
+ { refs: [[moduleId(row)], [row.name]], slots: { module: moduleId(row) }, value: row }
535
+ )
536
+ );
537
+ }
538
+ function connectionOptions(source, target, scored) {
539
+ const between = scored.filter(
540
+ (each) => each.sourceInstance === source.name && each.targetInstance === target.name
541
+ );
542
+ return source.outputs.flatMap(
543
+ (output) => unwired(target).map((input) => {
544
+ const pair = { output: output.name, input: input.name };
545
+ const from = pinRef(source.id, pair.output);
546
+ const to = pinRef(target.id, pair.input);
547
+ const match = between.find(
548
+ (each) => each.output === pair.output && each.input === pair.input
549
+ );
550
+ return offered(
551
+ {
552
+ id: connectionId(from, to),
553
+ kind: "connection",
554
+ source: source.id,
555
+ output: pair.output,
556
+ target: target.id,
557
+ input: pair.input,
558
+ ...match === void 0 ? {} : { score: match.score }
559
+ },
560
+ { refs: [[from, to]], slots: pair, value: pair }
561
+ );
562
+ })
563
+ );
564
+ }
565
+
566
+ // src/surfaces/canvas/registration.ts
567
+ import { ConnectError, reasonWire } from "@lace-cloud/canvas/engine";
568
+ var InvalidInput = class extends Error {
569
+ };
570
+ function reasonText(reason) {
571
+ return `reason ${reasonWire(reason)}`;
572
+ }
573
+ function errorText(error) {
574
+ if (error instanceof ConnectError) {
575
+ const reason = error.apiCode === void 0 ? reasonText(error.reason) : `reason ${error.apiCode}`;
576
+ return `${error.message} (${reason})`;
577
+ }
578
+ return error instanceof Error ? error.message : String(error);
579
+ }
580
+ function registrationOf(schema, run, failed) {
581
+ return {
582
+ schema,
583
+ async handler(input, signal) {
584
+ try {
585
+ return await run(input, signal);
586
+ } catch (error) {
587
+ return failed({ content: errorText(error), isError: true });
79
588
  }
80
589
  }
81
590
  };
82
591
  }
83
- function ts() {
84
- return (/* @__PURE__ */ new Date()).toISOString();
85
- }
86
- function truncate(s, max) {
87
- return s.length > max ? `${s.slice(0, max)}...` : s;
592
+ function registration(schema, run) {
593
+ return registrationOf(schema, run, (failure) => failure);
88
594
  }
595
+ var NO_INPUT = { type: "object", properties: {}, additionalProperties: false };
89
596
 
90
- // src/agent-controller.ts
91
- var DEFAULT_MAX_TOOL_ROUNDS = 25;
92
- var DEFAULT_COMPLETED_TURN_CAP = 50;
93
- var AgentController = class {
94
- constructor(opts) {
95
- this.opts = opts;
96
- this.history = [];
97
- this.completedTurns = [];
98
- this.activeTurn = null;
99
- this.transportSubscription = null;
100
- this.telemetry = createTelemetry((msg) => opts.adapter.log(msg));
101
- }
102
- /** Load persisted history and start listening for webview messages. */
103
- async init() {
104
- try {
105
- this.history = await this.opts.adapter.loadHistory(this.opts.historyKey) ?? [];
106
- } catch (err) {
107
- this.opts.adapter.log(`[Chat] history load failed, starting fresh: ${String(err)}`);
108
- this.history = [];
597
+ // src/surfaces/canvas/commands.ts
598
+ function failureText(path, failure) {
599
+ const see = failure.url === void 0 ? "" : `; see ${failure.url}`;
600
+ const why = failure.apiCode ?? failure.reason;
601
+ return `lace ${path} failed (reason ${why}): ${failure.message}${see}`;
602
+ }
603
+ function commandEnd(path, error) {
604
+ if (!(error instanceof CommandExitError)) {
605
+ return { text: `lace ${path} did not finish cleanly (${errorText(error)})` };
606
+ }
607
+ if (error.failure !== void 0) {
608
+ return { text: failureText(path, error.failure), failure: error.failure };
609
+ }
610
+ return {
611
+ text: `lace ${path} did not finish cleanly (exit ${error.code}: ${error.stderrTail})`
612
+ };
613
+ }
614
+ async function runCommand(commands, path, args, signal = new AbortController().signal) {
615
+ const documents = [];
616
+ try {
617
+ for await (const document of commands.invoke(path, args, signal).events) {
618
+ documents.push(document);
109
619
  }
110
- this.transportSubscription = this.opts.transport.onMessage(
111
- (msg) => this.handleWebviewMessage(msg)
620
+ } catch (error) {
621
+ return { documents, failed: commandEnd(path, error) };
622
+ }
623
+ return { documents };
624
+ }
625
+ function commandText(run, trim) {
626
+ return [
627
+ ...run.documents.map((document) => JSON.stringify(trim(document))),
628
+ ...run.failed === void 0 ? [] : [run.failed.text]
629
+ ].join("\n");
630
+ }
631
+ function trimValidate(report) {
632
+ return {
633
+ verdict: report.verdict,
634
+ exitClass: report.exitClass,
635
+ diagnostics: report.diagnostics,
636
+ residuals: report.residuals?.map(({ construct, subject, file, line, guidance }) => ({
637
+ construct,
638
+ subject,
639
+ file,
640
+ line,
641
+ guidance
642
+ })),
643
+ terraform: report.terraform
644
+ };
645
+ }
646
+ function trimRegistryList(list) {
647
+ return {
648
+ modules: list.items.map((row) => ({
649
+ module: moduleId(row),
650
+ version: row.version,
651
+ name: row.displayName,
652
+ description: row.description,
653
+ system: row.system,
654
+ categories: row.categories
655
+ })),
656
+ truncated: list.truncated
657
+ };
658
+ }
659
+ function trimRegistryDescribe(described2) {
660
+ return {
661
+ module: moduleId(described2),
662
+ version: described2.version,
663
+ source: described2.source,
664
+ verdict: described2.verdict,
665
+ inputs: described2.interface.inputs,
666
+ outputs: described2.interface.outputs
667
+ };
668
+ }
669
+
670
+ // src/surfaces/canvas/outcome.ts
671
+ import { deepEqual } from "@lace-cloud/canvas/engine";
672
+ function instanceAt(canvas, scope, name) {
673
+ return canvas.instances.find((instance) => instance.scope === scope && instance.name === name);
674
+ }
675
+ function presenceOf(canvas, scope, name) {
676
+ const instance = instanceAt(canvas, scope, name);
677
+ return instance === void 0 ? null : { instance: instance.name, module: instance.module };
678
+ }
679
+ function bindingOf(canvas, scope, name, inputName) {
680
+ const input = instanceAt(canvas, scope, name)?.inputs.find((each) => each.name === inputName);
681
+ if (input === void 0) return null;
682
+ if (input.sensitive) return { mode: input.mode };
683
+ return {
684
+ mode: input.mode,
685
+ value: input.value,
686
+ variable: input.variable,
687
+ expression: input.expression,
688
+ wiredSource: input.wired_source
689
+ };
690
+ }
691
+ function at({ target, after }) {
692
+ return after !== null && "instance" in after ? after.instance : target.instance;
693
+ }
694
+ function targetState(canvas, record) {
695
+ const { scope, input } = record.target;
696
+ return input === void 0 ? presenceOf(canvas, scope, at(record)) : bindingOf(canvas, scope, at(record), input);
697
+ }
698
+ function follow(record, previous, frame) {
699
+ const name = at(record);
700
+ const { scope } = record.target;
701
+ const was = instanceAt(previous, scope, name);
702
+ if (was === void 0 || instanceAt(frame, scope, name) !== void 0) return record;
703
+ const fresh = frame.instances.filter(
704
+ (each) => each.module === was.module && instanceAt(previous, each.scope, each.name) === void 0
705
+ );
706
+ const one = (found2) => found2.length === 1 ? found2[0] : void 0;
707
+ const moved2 = one(fresh.filter((each) => each.name === name)) ?? one(fresh.filter((each) => each.scope === scope));
708
+ if (moved2 === void 0) return record;
709
+ const { after } = record;
710
+ return {
711
+ ...record,
712
+ target: { ...record.target, scope: moved2.scope, instance: moved2.name },
713
+ after: after !== null && "instance" in after ? { ...after, instance: moved2.name } : after
714
+ };
715
+ }
716
+ var decided = (state) => state === null ? null : "mode" in state ? [state.mode, state.wiredSource] : state.module;
717
+ var moved = (state, from) => state !== null && "mode" in state ? !deepEqual(state, from) : !deepEqual(decided(state), decided(from));
718
+ var OPERATION_OF_MODE = {
719
+ literal: "set",
720
+ variable: "bind",
721
+ empty: "clear",
722
+ wired: "connect"
723
+ };
724
+ function answered(record, state, canvas) {
725
+ if (state === null || !("mode" in state) || record.target.input === void 0) return {};
726
+ const name = (kind, candidate) => {
727
+ const question = record.questions.findIndex(
728
+ (each) => each.kind === kind && candidate !== void 0 && each.candidates.includes(candidate)
112
729
  );
730
+ return question === -1 || candidate === void 0 ? {} : { question, candidate };
731
+ };
732
+ const after = record.after;
733
+ if (after !== null && "mode" in after && after.mode !== state.mode) {
734
+ return name("operation", OPERATION_OF_MODE[state.mode]);
113
735
  }
114
- /** Cancel any active turn and unsubscribe from the webview. */
115
- dispose() {
116
- this.activeTurn?.abort();
117
- this.activeTurn = null;
118
- this.transportSubscription?.dispose();
119
- this.transportSubscription = null;
120
- }
121
- /** Drop in-memory and persisted history. */
122
- async clearHistory() {
123
- this.history = [];
124
- this.completedTurns = [];
125
- await this.opts.adapter.saveHistory(this.opts.historyKey, []);
126
- this.opts.transport.postMessage({ type: "history-cleared" });
127
- }
128
- /** Push a context-summary banner into the chat UI. */
129
- postContextSummary(summary) {
130
- this.opts.transport.postMessage({ type: "context-summary", summary });
131
- }
132
- /** Forward a proactive suggestion from the watcher to the chat UI. */
133
- postProactiveSuggestion(suggestion) {
134
- this.opts.transport.postMessage({ type: "proactive-suggestion", suggestion });
135
- }
136
- /** Notify the chat UI that the engine is unavailable for this session. */
137
- postEngineUnavailable() {
138
- this.opts.transport.postMessage({ type: "engine-unavailable" });
139
- }
140
- async handleWebviewMessage(msg) {
141
- switch (msg.type) {
142
- case "webview-ready":
143
- this.opts.transport.postMessage({ type: "history", turns: this.completedTurns });
144
- break;
145
- case "user-turn":
146
- await this.runTurn(msg.text);
147
- break;
148
- case "cancel-turn":
149
- this.activeTurn?.abort();
150
- break;
151
- case "accept-proactive-suggestion":
152
- this.opts.adapter.log(`[Chat] proactive suggestion accepted: ${msg.id}`);
153
- break;
154
- default:
155
- assertNever(msg);
156
- }
736
+ if (state.mode !== "wired" || state.wiredSource === void 0) return {};
737
+ const [, source, output] = /^module\.([^.]+)\.(.+)$/.exec(state.wiredSource) ?? [];
738
+ const { scope } = record.target;
739
+ const from = instanceAt(canvas, scope, source ?? "");
740
+ const to = instanceAt(canvas, scope, at(record));
741
+ return from === void 0 || to === void 0 || output === void 0 ? {} : name("connection", connectionId(pinRef(from.id, output), pinRef(to.id, record.target.input)));
742
+ }
743
+ function frameOutcomes(record, was, previous, frame, canvas, own) {
744
+ const state = targetState(canvas, record);
745
+ if (deepEqual(state, record.before)) return [{ event: "reverted" }];
746
+ const changes = (from) => !deepEqual(decided(state), decided(from));
747
+ if (changes(was) && changes(record.after)) {
748
+ const event = own.has(frame.revision) ? "changed_again" : "hand_edited";
749
+ return [{ event, ...answered(record, state, canvas) }];
157
750
  }
158
- async runTurn(userText) {
159
- const model = await this.opts.adapter.selectModel();
160
- if (!model) {
161
- this.opts.transport.postMessage({ type: "no-model" });
162
- return;
751
+ if (moved(state, record.after)) return [];
752
+ const saved = previous?.unsaved === true && !frame.unsaved ? [{ event: "saved" }] : [];
753
+ const generated = previous?.ungenerated === true && !frame.ungenerated ? [{ event: "generated" }] : [];
754
+ return [...saved, ...generated];
755
+ }
756
+ function changeOutcomes(record, frames, own = new Set(record.revision === void 0 ? [] : [record.revision])) {
757
+ const canvases = frames.map(readCanvas);
758
+ const reached = /* @__PURE__ */ new Map();
759
+ let carried = record;
760
+ frames.forEach((frame, index) => {
761
+ const was = index > 0 ? targetState(canvases[index - 1], carried) : record.after;
762
+ if (index > 0) carried = follow(carried, canvases[index - 1], canvases[index]);
763
+ for (const outcome of frameOutcomes(
764
+ carried,
765
+ was,
766
+ frames[index - 1],
767
+ frame,
768
+ canvases[index],
769
+ own
770
+ )) {
771
+ if (!reached.has(outcome.event)) reached.set(outcome.event, outcome);
163
772
  }
164
- this.activeTurn = new AbortController();
165
- const signal = this.activeTurn.signal;
166
- const session = this.telemetry.startSession(userText);
167
- const systemPrompt = this.opts.buildSystemPrompt(this.opts.getAvailableSystems());
168
- const canvasFacts = this.opts.getCanvasFacts();
169
- const canvasContext = canvasFacts ? `Canvas: ${canvasFacts.nodeCount} node(s), ${canvasFacts.diagnosticCount} diagnostic(s).` : "Canvas: (state not yet loaded)";
170
- const messages = [
171
- { role: "user", content: [{ kind: "text", value: systemPrompt }] },
172
- {
173
- role: "assistant",
174
- content: [
175
- {
176
- kind: "text",
177
- value: "Understood. I am Lace, your Terraform infrastructure assistant."
178
- }
179
- ]
180
- },
181
- ...this.history,
182
- { role: "user", content: [{ kind: "text", value: `[Canvas state]
183
- ${canvasContext}` }] },
184
- { role: "assistant", content: [{ kind: "text", value: "Got it." }] },
185
- { role: "user", content: [{ kind: "text", value: userText }] }
186
- ];
187
- this.history.push({ role: "user", content: [{ kind: "text", value: userText }] });
188
- const turnToolCalls = [];
189
- let assistantAccumulated = "";
190
- const messageId = `msg-${Date.now()}`;
191
- const failSignatureCount = /* @__PURE__ */ new Map();
192
- const tools = this.opts.toolRegistry.listSchemas();
193
- const maxRounds = this.opts.maxToolRounds ?? DEFAULT_MAX_TOOL_ROUNDS;
194
- try {
195
- for (let round = 0; round < maxRounds; round++) {
196
- if (signal.aborted) break;
197
- session.rounds = round + 1;
198
- const textParts = [];
199
- const toolCalls = [];
200
- try {
201
- for await (const event of this.opts.adapter.sendRequest(model, messages, tools, signal)) {
202
- if (signal.aborted) break;
203
- if (event.type === "text") {
204
- textParts.push(event.value);
205
- assistantAccumulated += event.value;
206
- this.opts.transport.postMessage({ type: "token", text: event.value });
207
- } else if (event.type === "tool-call") {
208
- toolCalls.push({
209
- name: event.name,
210
- callId: event.callId,
211
- input: event.input
212
- });
213
- }
214
- }
215
- } catch (err) {
216
- const msg = err instanceof Error ? err.message : String(err);
217
- this.opts.adapter.log(`[Chat] sendRequest failed: ${msg}`);
218
- const line = `
219
- _Model request failed: ${msg}_`;
220
- this.opts.transport.postMessage({ type: "token", text: line });
221
- assistantAccumulated += line;
222
- break;
223
- }
224
- if (toolCalls.length === 0) break;
225
- const assistantContent = [
226
- ...textParts.map((t) => ({ kind: "text", value: t })),
227
- ...toolCalls.map(
228
- (tc) => ({
229
- kind: "tool-call",
230
- callId: tc.callId,
231
- name: tc.name,
232
- input: tc.input
233
- })
234
- )
235
- ];
236
- messages.push({ role: "assistant", content: assistantContent });
237
- this.history.push({ role: "assistant", content: assistantContent });
238
- const toolResultParts = [];
239
- let allToolsErrored = true;
240
- for (const tc of toolCalls) {
241
- if (signal.aborted) break;
242
- this.opts.transport.postMessage({
243
- type: "tool-call",
244
- callId: tc.callId,
245
- name: tc.name,
246
- input: tc.input
247
- });
248
- const handler = this.opts.toolRegistry.getHandler(tc.name);
249
- const startedAt = Date.now();
250
- let result;
251
- if (!handler) {
252
- result = { content: `Unknown tool: ${tc.name}`, isError: true };
253
- } else {
254
- try {
255
- result = await handler(tc.input);
256
- } catch (err) {
257
- result = {
258
- content: `Tool error: ${err instanceof Error ? err.message : String(err)}`,
259
- isError: true
260
- };
261
- }
262
- }
263
- const durationMs = Date.now() - startedAt;
264
- this.telemetry.logToolInvocation(session, tc.name, tc.input, result, durationMs);
265
- turnToolCalls.push({
266
- name: tc.name,
267
- input: tc.input,
268
- resultContent: result.content,
269
- isError: result.isError
270
- });
271
- if (!result.isError) {
272
- allToolsErrored = false;
273
- failSignatureCount.delete(signatureFor(tc));
274
- } else {
275
- const sig = signatureFor(tc);
276
- failSignatureCount.set(sig, (failSignatureCount.get(sig) ?? 0) + 1);
277
- }
278
- this.opts.transport.postMessage({
279
- type: "tool-result",
280
- callId: tc.callId,
281
- name: tc.name,
282
- content: result.content,
283
- isError: result.isError
284
- });
285
- toolResultParts.push({
286
- kind: "tool-result",
287
- callId: tc.callId,
288
- content: [
289
- {
290
- kind: "text",
291
- value: result.isError ? `Tool [${tc.name}] failed: ${result.content}` : result.content
292
- }
293
- ],
294
- isError: result.isError
295
- });
296
- }
297
- messages.push({ role: "user", content: toolResultParts });
298
- this.history.push({ role: "user", content: toolResultParts });
299
- if (allToolsErrored && toolCalls.length > 0) {
300
- const errorDetails = toolResultParts.flatMap((p) => p.content.map((c) => c.value)).filter(Boolean);
301
- const msg = `
302
- _All tool calls failed:
303
- ${errorDetails.map((e) => `- ${e}`).join("\n")}_`;
304
- this.opts.transport.postMessage({ type: "token", text: msg });
305
- assistantAccumulated += msg;
306
- break;
307
- }
308
- const stuck = [...failSignatureCount.entries()].find(([, count]) => count >= 2);
309
- if (stuck) {
310
- const msg = `
311
- _I'm stuck \u2014 required fields cannot be inferred. Please provide the missing values._`;
312
- this.opts.transport.postMessage({ type: "token", text: msg });
313
- assistantAccumulated += msg;
314
- break;
315
- }
316
- if (round === maxRounds - 1) {
317
- const msg = `
318
- _Reached operation limit (${maxRounds} rounds). Ask me to continue if needed._`;
319
- this.opts.transport.postMessage({ type: "token", text: msg });
320
- assistantAccumulated += msg;
321
- }
773
+ });
774
+ return { record: carried, outcomes: [...reached.values()] };
775
+ }
776
+ function outcomeObserver(transport) {
777
+ const client = rankingClient(transport);
778
+ const followed = /* @__PURE__ */ new Map();
779
+ const own = /* @__PURE__ */ new Set();
780
+ let previous;
781
+ let flying = 0;
782
+ const returned = /* @__PURE__ */ new Set();
783
+ let held = [];
784
+ const fold = (source) => {
785
+ const frames = previous === void 0 ? [source] : [previous, source];
786
+ previous = source;
787
+ for (const [id, each] of followed) {
788
+ const { record, outcomes } = changeOutcomes(each.record, frames, own);
789
+ followed.set(id, { record, reported: each.reported });
790
+ for (const outcome of outcomes.filter(({ event }) => !each.reported.has(event))) {
791
+ each.reported.add(outcome.event);
792
+ void client.outcome(id, outcome);
322
793
  }
323
- } finally {
324
- this.telemetry.endSession(session, maxRounds);
325
- this.activeTurn = null;
326
- if (signal.aborted) {
327
- this.opts.transport.postMessage({ type: "turn-cancelled" });
328
- } else {
329
- this.completedTurns.push({
330
- messageId,
331
- userText,
332
- assistantText: assistantAccumulated,
333
- toolCalls: turnToolCalls
334
- });
335
- const cap = this.opts.completedTurnCap ?? DEFAULT_COMPLETED_TURN_CAP;
336
- if (this.completedTurns.length > cap) {
337
- this.completedTurns = this.completedTurns.slice(-cap);
338
- }
339
- await this.opts.adapter.saveHistory(this.opts.historyKey, capRecentMessages(this.history));
340
- this.opts.transport.postMessage({ type: "turn-complete", messageId });
794
+ }
795
+ };
796
+ const landed = (revision) => {
797
+ flying -= 1;
798
+ if (revision !== void 0) returned.add(revision);
799
+ if (flying > 0) return;
800
+ const frames = held;
801
+ held = [];
802
+ for (const frame of frames) {
803
+ if (returned.has(frame.revision)) own.add(frame.revision);
804
+ fold(frame);
805
+ }
806
+ returned.clear();
807
+ };
808
+ return {
809
+ async own(apply) {
810
+ flying += 1;
811
+ let revision;
812
+ try {
813
+ const result = await apply();
814
+ revision = result.success ? result.revision : void 0;
815
+ return result;
816
+ } finally {
817
+ landed(revision);
818
+ }
819
+ },
820
+ follow(records) {
821
+ for (const record of records.filter((each) => each.reported)) {
822
+ followed.set(record.id, { record, reported: /* @__PURE__ */ new Set() });
341
823
  }
824
+ },
825
+ frame(source) {
826
+ if (flying > 0) held.push(source);
827
+ else fold(source);
342
828
  }
829
+ };
830
+ }
831
+
832
+ // src/surfaces/canvas/ports.ts
833
+ function endText(end) {
834
+ return end.kind === "failed" ? `failed: ${end.error.message}` : end.kind;
835
+ }
836
+ function endError(end) {
837
+ return end.kind === "failed" ? end.error : new Error("the authoring session is closed");
838
+ }
839
+ function latest(source) {
840
+ let unsubscribe = () => {
841
+ };
842
+ const frame = new Promise((resolve, reject) => {
843
+ unsubscribe = source.subscribe(resolve, (end) => reject(endError(end)));
844
+ });
845
+ return frame.finally(() => unsubscribe());
846
+ }
847
+
848
+ // src/surfaces/canvas/render.ts
849
+ import { callText } from "@lace-cloud/proto";
850
+ function inputText(input) {
851
+ if (input.mode === "empty") {
852
+ return `${input.name} (${input.required ? "required, " : ""}not set)`;
343
853
  }
344
- };
345
- function signatureFor(tc) {
346
- return `${tc.name}:${JSON.stringify(tc.input)}`;
854
+ if (input.mode === "wired") return `${input.name} (wired)`;
855
+ if (input.sensitive) return `${input.name} (sensitive, value withheld)`;
856
+ const shown = {
857
+ literal: JSON.stringify(input.value),
858
+ variable: `var.${input.variable}`,
859
+ expression: `${input.expression}`
860
+ };
861
+ return `${input.name} = ${shown[input.mode]}`;
862
+ }
863
+ function instanceLines(instance) {
864
+ return [
865
+ `- ${instance.id}: module ${instance.module}`,
866
+ ` inputs: [${instance.inputs.map(inputText).join("; ")}]`,
867
+ ` outputs: [${instance.outputs.map((output) => output.name).join(", ")}]`
868
+ ];
869
+ }
870
+ function unsetRequired(instance) {
871
+ return instance.inputs.filter((input) => input.required && input.mode === "empty").map((input) => `- ${instance.id}.${input.name}`);
872
+ }
873
+ function diagnosticLine(diagnostic) {
874
+ const where = [
875
+ ["instance", diagnostic.instance_id],
876
+ ["input", diagnostic.input_name],
877
+ ["address", diagnostic.address],
878
+ ["file", diagnostic.file],
879
+ ["line", diagnostic.line]
880
+ ].filter(([, value]) => value !== void 0).map(([label, value]) => `${label} ${value}`);
881
+ return `- ${[`${diagnostic.severity}: ${diagnostic.message}`, ...where].join("; ")}`;
882
+ }
883
+ var yesNo = (flag) => flag ? "yes" : "no";
884
+ function section(title, lines) {
885
+ return [`${title} (${lines.length}):`, ...lines];
886
+ }
887
+ function renderCanvas(source) {
888
+ const canvas = readCanvas(source);
889
+ return [
890
+ `Canvas of module ${canvas.module}`,
891
+ `Instances (${canvas.instances.length}):`,
892
+ ...canvas.instances.flatMap(instanceLines),
893
+ ...section(
894
+ "Wires",
895
+ canvas.wires.map(
896
+ (wire) => `- ${wire.source_output ? `${wire.source}.${wire.source_output}` : callText(wire.source)} \u2192 ${wire.target}.${wire.target_input}`
897
+ )
898
+ ),
899
+ ...section("Required inputs not set", canvas.instances.flatMap(unsetRequired)),
900
+ ...section(
901
+ "Groups",
902
+ canvas.groups.map((group) => `- ${group.id}: ${group.members.join(", ")}`)
903
+ ),
904
+ ...section("Diagnostics", source.diagnostics.map(diagnosticLine)),
905
+ [
906
+ `Standing: unsaved edits: ${yesNo(source.unsaved)}`,
907
+ `saved edits not generated to Terraform: ${yesNo(source.ungenerated)}`,
908
+ `conflict with the Terraform on disk: ${yesNo(source.conflict !== null)}`,
909
+ `Terraform refused, canvas locked: ${yesNo(source.sourceRefused)}`
910
+ ].join("; ")
911
+ ].join("\n");
912
+ }
913
+ function renderTarget(target) {
914
+ const pin = target.input === void 0 ? target.instance : `${target.instance}.${target.input}`;
915
+ return `${pin} in ${target.scope}`;
916
+ }
917
+ function renderState(state) {
918
+ if (state === null) return "absent";
919
+ if (!("mode" in state)) return `an instance of module ${state.module}`;
920
+ const shown = {
921
+ empty: "not set",
922
+ literal: `literal ${VALUE_PLACEHOLDER}`,
923
+ variable: `variable ${VALUE_PLACEHOLDER}`,
924
+ expression: `expression ${VALUE_PLACEHOLDER}`,
925
+ wired: `wired from ${state.wiredSource}`
926
+ };
927
+ return shown[state.mode];
347
928
  }
348
929
 
349
- // src/proactivity/rules.ts
350
- function initialRuleState() {
351
- return { prevDiagnosticErrorCount: 0 };
352
- }
353
- function errorsOf(diagnostics) {
354
- return diagnostics.filter((d) => d.severity === "error");
355
- }
356
- function matchGenerateError(event) {
357
- const err = event.generate_error;
358
- if (!err || err.diagnostics.length === 0) return null;
359
- const first = err.diagnostics[0];
360
- const location = first.instance_id ? `\`${first.instance_id}\`${first.address ? `.\`${first.address}\`` : ""}` : "";
361
- const locSuffix = location ? ` at ${location}` : "";
930
+ // src/surfaces/canvas/resolve.ts
931
+ var WORD = /[A-Za-z0-9_-]+/g;
932
+ var DOTTED = /[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)+/g;
933
+ var SLASHED = /[A-Za-z0-9_-]+(?:\/[A-Za-z0-9_-]+)+/g;
934
+ function found(text2, pattern) {
935
+ return [...text2.matchAll(pattern)].map((match) => ({ term: match[0], at: match.index }));
936
+ }
937
+ function runs({ term, at: at2 }) {
938
+ const parts = term.split(".");
939
+ const starts = parts.map((_, index) => at2 + parts.slice(0, index).join(".").length + index);
940
+ return parts.flatMap(
941
+ (_, start) => parts.slice(start).map((_2, length) => ({
942
+ term: parts.slice(start, start + length + 1).join("."),
943
+ at: starts[start]
944
+ }))
945
+ );
946
+ }
947
+ function moduleReferences(text2) {
948
+ return found(text2, SLASHED).map((each) => each.term);
949
+ }
950
+ function firstAt(names2, key) {
951
+ return names2.reduce(
952
+ (at2, { term, at: offset }) => at2.set(key(term), Math.min(offset, at2.get(key(term)) ?? offset)),
953
+ /* @__PURE__ */ new Map()
954
+ );
955
+ }
956
+ function termsOf(text2) {
957
+ const names2 = [
958
+ ...found(text2, WORD),
959
+ ...found(text2, DOTTED).flatMap(runs),
960
+ ...found(text2, SLASHED)
961
+ ];
362
962
  return {
363
- id: `gen-error-${Date.now()}`,
364
- text: `Generation failed: ${first.message}${locSuffix}. Want me to look at it?`
963
+ exact: firstAt(names2, (term) => term),
964
+ folded: firstAt(names2, (term) => term.toLowerCase()),
965
+ words: found(text2, WORD).map(({ term }) => term.toLowerCase())
365
966
  };
366
967
  }
367
- function matchErrorsAppeared(event, state) {
368
- if (!event.diagnostics) return null;
369
- const errors = errorsOf(event.diagnostics);
370
- const curr = errors.length;
371
- if (state.prevDiagnosticErrorCount !== 0 || curr === 0) return null;
372
- const summary = errors[0].message + (curr > 1 ? ` (+${curr - 1} more)` : "");
968
+ function vocabulary(option) {
969
+ const text2 = [option.candidate.id, option.candidate.text, ...option.refs.flat()].join(" ");
970
+ return new Set(
971
+ found(text2.toLowerCase(), WORD).flatMap(({ term }) => [term, ...term.split(/[_-]/)])
972
+ );
973
+ }
974
+ var FUNCTION_WORDS = new Set(
975
+ "a about after all am an and any are as at be been but by can could did do does each every for from had has have he her his i if in into is it its may me might must my no nor not of off on onto or our out over per shall she should so some than that the their them then these they this those to up upon us via was we were will with would you your".split(
976
+ " "
977
+ )
978
+ );
979
+ function span(words, index, covered) {
980
+ if (!covered.has(words[index])) return 0;
981
+ const outside = (word) => !covered.has(word) && !FUNCTION_WORDS.has(word);
982
+ const before = words.slice(0, index).reverse().findIndex(outside);
983
+ const after = words.slice(index + 1).findIndex(outside);
984
+ return words.slice(before === -1 ? 0 : index - before, after === -1 ? words.length : index + 1 + after).filter((word) => !FUNCTION_WORDS.has(word)).length;
985
+ }
986
+ var NothingOffered = class extends Error {
987
+ constructor(label) {
988
+ super(`the canvas offers no ${label} for this change`);
989
+ this.label = label;
990
+ }
991
+ };
992
+ var Undecided = class extends Error {
993
+ constructor(kind, label, candidates, ranking2) {
994
+ super(`the ${label} was not decided`);
995
+ this.kind = kind;
996
+ this.label = label;
997
+ this.candidates = candidates;
998
+ this.ranking = ranking2;
999
+ }
1000
+ };
1001
+ var NAMED_ALTERNATIVES = 3;
1002
+ var NONE_OVER = "none of these";
1003
+ function named(options, { words }, terms, fold) {
1004
+ const hits = options.map((option) => ({
1005
+ option,
1006
+ refs: option.refs.map((ref) => ref.map(fold)).filter((ref) => ref.every((part) => terms.has(part)))
1007
+ })).filter((hit) => hit.refs.length > 0);
1008
+ const extended = (ref) => ref.length === 1 && hits.some(
1009
+ (other) => other.refs.some(
1010
+ (longer) => longer.some((part) => part !== ref[0] && part.split(".").includes(ref[0]))
1011
+ )
1012
+ );
1013
+ const covers = new Map(options.map((option) => [option, vocabulary(option)]));
1014
+ const outspanned = (option, ref) => {
1015
+ const word = ref[0].toLowerCase();
1016
+ const places = words.flatMap((each, index) => each === word ? [index] : []);
1017
+ const own = covers.get(option) ?? /* @__PURE__ */ new Set();
1018
+ return ref.length === 1 && !/[./]/.test(word) && places.length > 0 && places.every(
1019
+ (index) => options.some(
1020
+ (other) => other !== option && span(words, index, covers.get(other) ?? /* @__PURE__ */ new Set()) > span(words, index, own)
1021
+ )
1022
+ );
1023
+ };
1024
+ const at2 = (ref) => Math.min(...ref.map((part) => terms.get(part) ?? Number.POSITIVE_INFINITY));
1025
+ return hits.map((hit) => ({
1026
+ ...hit,
1027
+ refs: hit.refs.filter((ref) => !extended(ref) && !outspanned(hit.option, ref))
1028
+ })).filter((hit) => hit.refs.length > 0).map((hit) => ({ ...hit, at: Math.min(...hit.refs.map(at2)) })).sort((a, b) => a.at - b.at);
1029
+ }
1030
+ function apart(hits) {
1031
+ const key = (ref) => ref.join(" ");
1032
+ return hits.every((hit) => {
1033
+ const others = hits.filter((other) => other !== hit);
1034
+ const own = hit.refs.some(
1035
+ (ref) => !others.some((other) => other.refs.some((each) => key(each) === key(ref)))
1036
+ );
1037
+ const inside = others.some(
1038
+ (other) => hit.option.candidate.id.startsWith(`${other.option.candidate.id}.`)
1039
+ );
1040
+ return own && !inside;
1041
+ });
1042
+ }
1043
+ var NAME_STEPS = [
1044
+ {
1045
+ how: "exact",
1046
+ hits: (options, terms) => named(options, terms, terms.exact, (part) => part)
1047
+ },
1048
+ {
1049
+ how: "unique",
1050
+ hits: (options, terms) => named(options, terms, terms.folded, (part) => part.toLowerCase())
1051
+ }
1052
+ ];
1053
+ function read(options, reading) {
1054
+ return options.filter(
1055
+ (option) => statedSlots(option.slots).every((slot) => reading[slot] === option.slots[slot])
1056
+ );
1057
+ }
1058
+ function answerOf2(options, reading) {
1059
+ const named2 = read(options, reading);
1060
+ return named2.length === 1 ? named2[0] : void 0;
1061
+ }
1062
+ var PART = RANK_CANDIDATES_MAX - 1;
1063
+ function partsOf(items) {
1064
+ return Array.from(
1065
+ { length: Math.ceil(items.length / PART) },
1066
+ (_, n) => items.slice(n * PART, (n + 1) * PART)
1067
+ );
1068
+ }
1069
+ function partHolding(candidates, id) {
1070
+ return partsOf(candidates).find((part) => part.some((each) => each.id === id)) ?? [];
1071
+ }
1072
+ function factsOf(options, part) {
1073
+ const byId = new Map(options.map((option) => [option.candidate.id, option.facts]));
1074
+ return part.flatMap((candidate) => byId.get(candidate.id) ?? []);
1075
+ }
1076
+ async function rankPart(rank, request, statement, kind, part) {
1077
+ const ranked = await rank({ request, statement, candidates: rankCandidates(kind, part) });
1078
+ const pick = part.find((candidate) => candidate.id === pickOf(ranked.scores)?.id);
1079
+ if (pick === void 0) throw new Error("the ranking names no candidate of the set");
1080
+ return { part, ranked, pick };
1081
+ }
1082
+ async function rankWithin(rank, request, statement, kind, candidates) {
1083
+ const parts = partsOf(candidates);
1084
+ if (parts.length === 1) return rankPart(rank, request, statement, kind, candidates);
1085
+ const rounds = [];
1086
+ for (const part of parts) rounds.push(await rankWithin(rank, request, statement, kind, part));
1087
+ const final = await rankWithin(
1088
+ rank,
1089
+ request,
1090
+ statement,
1091
+ kind,
1092
+ rounds.map((round) => round.pick)
1093
+ );
1094
+ const holding = rounds.find((round) => round.pick.id === final.pick.id);
1095
+ if (holding === void 0) throw new Error("the ranking names no candidate of the set");
1096
+ return holding;
1097
+ }
1098
+ var NOT_RANKED = { ranked: null, failed: "Lace did not rank" };
1099
+ async function ranking(ask, statement, kind, candidates) {
1100
+ if (ask.rank === void 0) return { ranking: NOT_RANKED, part: candidates };
1101
+ try {
1102
+ const { part, ranked } = await rankWithin(ask.rank, ask.request, statement, kind, candidates);
1103
+ return { ranking: { ranked, parts: part.length < candidates.length }, part };
1104
+ } catch (error) {
1105
+ if (error instanceof Cancelled) throw error;
1106
+ if (error instanceof NotCarried) return { ranking: NOT_RANKED, part: candidates };
1107
+ const failed = `Lace could not rank: ${error instanceof Error ? error.message : String(error)}`;
1108
+ return { ranking: { ranked: null, failed }, part: candidates };
1109
+ }
1110
+ }
1111
+ var asAsked = (ranking2) => ranking2 === null || ranking2.ranked === null || ranking2.parts ? null : ranking2.ranked;
1112
+ async function twoSystems(ask, kind, label, options, stated) {
1113
+ const candidates = options.map((option2) => option2.candidate);
1114
+ const readings = options.map((option2) => option2.slots);
1115
+ const chat = stated === void 0 ? answerOf2(options, ask.reading) : options.find((option2) => option2.value === stated);
1116
+ const read2 = await ranking(ask, ask.statement, kind, candidates);
1117
+ const composed = compose({
1118
+ kind,
1119
+ chat: chat?.candidate.id ?? null,
1120
+ ranked: asAsked(read2.ranking)
1121
+ });
1122
+ const option = options.find((each) => each.candidate.id === composed.taken);
1123
+ if (option === void 0) throw new Undecided(kind, label, candidates, read2.ranking);
1124
+ const alternative = ask.alternative === void 0 ? null : await ranking(ask, ask.alternative.statement, kind, candidates).then(({ ranking: ranking2 }) => {
1125
+ const ranked2 = asAsked(ranking2);
1126
+ const pick = ranked2 === null ? void 0 : pickOf(ranked2.scores);
1127
+ const named2 = options.find((each) => each.candidate.id === pick?.id);
1128
+ return pick === void 0 || ranked2 === null || named2 === void 0 ? null : { id: pick.id, sure: sure(ranked2, kind), slots: named2.slots };
1129
+ });
1130
+ const ranked = read2.ranking.ranked;
1131
+ const others = ranked === null ? [] : ranked.scores.filter((score) => score.id !== NONE_CANDIDATE_ID);
1132
+ const part = composed.took === "clm" ? read2.part : partHolding(candidates, option.candidate.id);
373
1133
  return {
374
- id: `errors-appeared-${Date.now()}`,
375
- text: `${curr} validation error${curr === 1 ? "" : "s"} appeared \u2014 ${summary}. Investigate?`
1134
+ kind,
1135
+ label,
1136
+ option,
1137
+ how: composed.took,
1138
+ offered: candidates.length,
1139
+ candidates: part,
1140
+ facts: factsOf(options, part),
1141
+ others: [],
1142
+ chat: chat?.candidate.id ?? null,
1143
+ ranking: read2.ranking,
1144
+ composed,
1145
+ over: [
1146
+ ...ranked?.scores[0]?.id === NONE_CANDIDATE_ID ? [NONE_OVER] : [],
1147
+ ...others.slice(1, NAMED_ALTERNATIVES + 1).map((score) => score.id)
1148
+ ],
1149
+ alternative,
1150
+ readings
376
1151
  };
377
1152
  }
378
- function matchAll(event, state) {
379
- return matchGenerateError(event) ?? matchErrorsAppeared(event, state);
1153
+ function byName(ask, kind, label, options) {
1154
+ const settled = (option, how, hits) => ({
1155
+ kind,
1156
+ label,
1157
+ option,
1158
+ how,
1159
+ offered: options.length,
1160
+ candidates: options.map((each) => each.candidate),
1161
+ facts: options.map((each) => each.facts),
1162
+ others: hits.filter((hit) => hit.option !== option).map((hit) => hit.option.candidate.id),
1163
+ chat: answerOf2(options, ask.reading)?.candidate.id ?? null,
1164
+ ranking: null,
1165
+ composed: null,
1166
+ over: [],
1167
+ alternative: null,
1168
+ readings: options.map((each) => each.slots)
1169
+ });
1170
+ const step = NAME_STEPS.map((each) => ({
1171
+ how: each.how,
1172
+ hits: each.hits(options, ask.terms)
1173
+ })).find((each) => each.hits.length > 0);
1174
+ if (step === void 0) return void 0;
1175
+ if (step.hits.length === 1) return settled(step.hits[0].option, step.how, step.hits);
1176
+ if (!apart(step.hits)) return void 0;
1177
+ const agreed = read(
1178
+ step.hits.map((hit) => hit.option),
1179
+ ask.reading
1180
+ );
1181
+ return agreed.length === 1 ? settled(agreed[0], "agreed", step.hits) : settled(step.hits[0].option, "first", step.hits);
380
1182
  }
381
- function advanceState(event, state) {
382
- if (!event.diagnostics) return state;
383
- return { prevDiagnosticErrorCount: errorsOf(event.diagnostics).length };
1183
+ async function decide(ask, kind, label, options, stated) {
1184
+ if (options.length === 0) throw new NothingOffered(label);
1185
+ return byName(ask, kind, label, options) ?? twoSystems(ask, kind, label, options, stated);
384
1186
  }
385
1187
 
386
- // src/proactivity/index.ts
387
- var RETRY_DELAY_MS = 1e3;
388
- var CONFIG_KEY = "proactivity";
389
- var CONFIG_ENABLED_VALUE = "on";
390
- var ProactivityWatcher = class {
391
- constructor(opts) {
392
- this.opts = opts;
393
- this.stream = null;
394
- this.ruleState = initialRuleState();
395
- this.retried = false;
396
- this.stopped = false;
397
- }
398
- start() {
399
- if (this.stopped) return;
400
- this.stream = this.opts.facts.subscribeFacts(this.opts.sessionId);
401
- this.stream.on("data", (event) => this.handleEvent(event));
402
- this.stream.on("end", () => {
403
- this.opts.adapter.log("[Proactivity] stream ended");
404
- this.stream = null;
405
- });
406
- this.stream.on("error", (err) => {
407
- this.opts.adapter.log(`[Proactivity] stream error: ${err.message}`);
408
- this.stream = null;
409
- if (!this.retried && !this.stopped) {
410
- this.retried = true;
411
- setTimeout(() => {
412
- if (!this.stopped) this.start();
413
- }, RETRY_DELAY_MS);
414
- }
415
- });
1188
+ // src/surfaces/canvas/change.ts
1189
+ var Unapplicable = class extends Error {
1190
+ };
1191
+ function isRecord2(value) {
1192
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1193
+ }
1194
+ var present = (value) => value !== void 0 && value !== null;
1195
+ function readingOf(index, name, stated) {
1196
+ if (!isRecord2(stated)) {
1197
+ throw new InvalidInput(`change ${index + 1}: \`${name}\` is an object of names`);
416
1198
  }
417
- stop() {
418
- this.stopped = true;
419
- this.stream?.cancel();
420
- this.stream = null;
1199
+ return Object.fromEntries(
1200
+ READING_SLOTS.flatMap((slot) => {
1201
+ const value = stated[slot];
1202
+ return typeof value === "string" ? [[slot, value]] : [];
1203
+ })
1204
+ );
1205
+ }
1206
+ function parseChanges(input) {
1207
+ const { changes } = input;
1208
+ if (!Array.isArray(changes)) throw new InvalidInput("`changes` is a list of changes");
1209
+ return changes.map((entry, index) => {
1210
+ if (!isRecord2(entry) || typeof entry.request !== "string") {
1211
+ throw new InvalidInput(`change ${index + 1} needs \`request\`: the developer's own words`);
1212
+ }
1213
+ if (!present(entry.modelReading)) {
1214
+ throw new InvalidInput(
1215
+ `change ${index + 1} needs \`modelReading\`: your own reading of the change, an object of the names you stated`
1216
+ );
1217
+ }
1218
+ const alternative = present(entry.alternativeReading) ? { alternative: readingOf(index, "alternativeReading", entry.alternativeReading) } : {};
1219
+ return {
1220
+ request: entry.request,
1221
+ values: [entry.value].filter(present),
1222
+ reading: readingOf(index, "modelReading", entry.modelReading),
1223
+ ...alternative
1224
+ };
1225
+ });
1226
+ }
1227
+ function inputEdit(canvas, instance, inputName) {
1228
+ const state = (of) => bindingOf(of, instance.scope, instance.name, inputName);
1229
+ return {
1230
+ target: () => ({ scope: instance.scope, instance: instance.name, input: inputName }),
1231
+ before: state(canvas),
1232
+ after: state
1233
+ };
1234
+ }
1235
+ function instanceEdit(canvas, instance, nameAfter) {
1236
+ return {
1237
+ target: () => ({ scope: instance.scope, instance: instance.name }),
1238
+ before: presenceOf(canvas, instance.scope, instance.name),
1239
+ after: (of) => presenceOf(of, instance.scope, nameAfter)
1240
+ };
1241
+ }
1242
+ function given(values, what) {
1243
+ if (values.length === 0) {
1244
+ throw new Unapplicable(`this change needs ${what}: pass it in \`value\``);
421
1245
  }
422
- handleEvent(event) {
423
- const enabled = this.opts.adapter.getConfig(CONFIG_KEY, CONFIG_ENABLED_VALUE) === CONFIG_ENABLED_VALUE;
424
- if (enabled) {
425
- const suggestion = matchAll(event, this.ruleState);
426
- if (suggestion) this.opts.onSuggestion(suggestion);
1246
+ return values[0];
1247
+ }
1248
+ function givenName(values, what) {
1249
+ const name = given(values, what);
1250
+ if (typeof name !== "string") throw new Unapplicable(`${what} is text: pass it in \`value\``);
1251
+ return name;
1252
+ }
1253
+ var EVERY_MODE = ["empty", "literal", "variable", "expression", "wired"];
1254
+ async function pickInput({ canvas, pick }, modes) {
1255
+ const offered2 = (instance2) => instance2.inputs.filter((input2) => modes.includes(input2.mode));
1256
+ const instance = await pick(
1257
+ "instance",
1258
+ "instance",
1259
+ instanceOptions(canvas.instances.filter((each) => offered2(each).length > 0))
1260
+ );
1261
+ const input = await pick("input", "input", inputOptions(instance, offered2(instance)));
1262
+ return { instance, input };
1263
+ }
1264
+ function updateInput(instance, input, binding) {
1265
+ return {
1266
+ update_input: {
1267
+ scope: instance.scope,
1268
+ instance_id: instance.name,
1269
+ input_name: input.name,
1270
+ mode: binding.mode,
1271
+ value: binding.value,
1272
+ variable: binding.variable ?? "",
1273
+ expression: ""
427
1274
  }
428
- this.ruleState = advanceState(event, this.ruleState);
1275
+ };
1276
+ }
1277
+ var CATALOG_LIMIT = 500;
1278
+ var place = {
1279
+ id: "place",
1280
+ takesValue: false,
1281
+ async plan({ canvas, request, ports, signal, pick, note }) {
1282
+ const [query] = moduleReferences(request).map((reference) => reference.split("/").slice(-1)[0]);
1283
+ const listing = await cancellable(
1284
+ () => runCommand(
1285
+ ports.commands,
1286
+ "registry list",
1287
+ { axis: "module", limit: CATALOG_LIMIT, query },
1288
+ signal
1289
+ ),
1290
+ signal
1291
+ );
1292
+ if (listing.failed !== void 0) throw new Error(listing.failed.text);
1293
+ for (const document of listing.documents) {
1294
+ if (document.truncated) {
1295
+ note(
1296
+ `The registry listing was cut at ${CATALOG_LIMIT} modules, so the module meant may not have been a candidate. Name it as \`author/name\`, or find it with lace_search_module_registry.`
1297
+ );
1298
+ }
1299
+ }
1300
+ const rows = listing.documents.flatMap((document) => document.items);
1301
+ const row = await pick("module", "registry module", moduleOptions(rows));
1302
+ const placed = (result) => result.created.map((ref) => ref.id).join(", ");
1303
+ return {
1304
+ action: {
1305
+ place_module: { author: row.author, name: row.name, version: row.version }
1306
+ },
1307
+ summary: (result) => `placed ${moduleId(row)} ${row.version} as ${placed(result)}`,
1308
+ target: (result) => ({ scope: canvas.entry, instance: placed(result) }),
1309
+ before: null,
1310
+ after: (of, result) => result.created.map((ref) => presenceOf(of, ref.scope, ref.id)).find((presence) => presence !== null) ?? null
1311
+ };
429
1312
  }
430
1313
  };
431
-
432
- // src/system-prompt.ts
433
- function buildSystemPrompt(systems = ["aws", "azure", "google"]) {
434
- const systemList = systems.join("/");
435
- return PROMPT_TEMPLATE.replace("{{SYSTEMS}}", systemList);
1314
+ var connect = {
1315
+ id: "connect",
1316
+ takesValue: false,
1317
+ async plan({ canvas, ports, signal, pick }) {
1318
+ const source = await pick("instance", "source instance", sourceOptions(canvas.instances));
1319
+ const target = await pick(
1320
+ "instance",
1321
+ "target instance",
1322
+ targetOptions(canvas.instances, source)
1323
+ );
1324
+ const scored = await cancellable(
1325
+ () => ports.editor.wiringCandidates({
1326
+ scope: source.scope,
1327
+ source: source.name,
1328
+ target: target.name
1329
+ }),
1330
+ signal
1331
+ );
1332
+ const pair = await pick("connection", "connection", connectionOptions(source, target, scored));
1333
+ return {
1334
+ action: {
1335
+ connect: {
1336
+ scope: target.scope,
1337
+ source_scope: source.scope,
1338
+ source: source.name,
1339
+ target: target.name,
1340
+ source_output: pair.output,
1341
+ target_input: pair.input
1342
+ }
1343
+ },
1344
+ summary: () => `connected ${source.id}.${pair.output} \u2192 ${target.id}.${pair.input}`,
1345
+ ...inputEdit(canvas, target, pair.input)
1346
+ };
1347
+ }
1348
+ };
1349
+ var disconnect = {
1350
+ id: "disconnect",
1351
+ takesValue: false,
1352
+ async plan(resolving) {
1353
+ const { instance, input } = await pickInput(resolving, ["wired"]);
1354
+ return {
1355
+ action: {
1356
+ disconnect: { scope: instance.scope, target: instance.name, input_name: input.name }
1357
+ },
1358
+ summary: () => `disconnected ${instance.id}.${input.name}`,
1359
+ ...inputEdit(resolving.canvas, instance, input.name)
1360
+ };
1361
+ }
1362
+ };
1363
+ var set = {
1364
+ id: "set",
1365
+ takesValue: true,
1366
+ async plan(resolving) {
1367
+ const value = given(resolving.values, "the value the developer gave");
1368
+ const { instance, input } = await pickInput(resolving, EVERY_MODE);
1369
+ const shown = input.sensitive ? "(sensitive, value withheld)" : `= ${JSON.stringify(value)}`;
1370
+ return {
1371
+ action: updateInput(instance, input, { mode: InputMode.INPUT_MODE_LITERAL, value }),
1372
+ summary: () => `set ${instance.id}.${input.name} ${shown}`,
1373
+ ...inputEdit(resolving.canvas, instance, input.name)
1374
+ };
1375
+ }
1376
+ };
1377
+ var bind = {
1378
+ id: "bind",
1379
+ takesValue: true,
1380
+ async plan(resolving) {
1381
+ const variable = variableName(givenName(resolving.values, "the variable's name"));
1382
+ const { instance, input } = await pickInput(resolving, EVERY_MODE);
1383
+ return {
1384
+ action: updateInput(instance, input, { mode: InputMode.INPUT_MODE_VARIABLE, variable }),
1385
+ summary: () => `bound ${instance.id}.${input.name} to var.${variable}`,
1386
+ ...inputEdit(resolving.canvas, instance, input.name)
1387
+ };
1388
+ }
1389
+ };
1390
+ var clear = {
1391
+ id: "clear",
1392
+ takesValue: false,
1393
+ async plan(resolving) {
1394
+ const { instance, input } = await pickInput(resolving, ["literal", "variable", "expression"]);
1395
+ return {
1396
+ action: updateInput(instance, input, { mode: InputMode.INPUT_MODE_EMPTY }),
1397
+ summary: () => `cleared ${instance.id}.${input.name}`,
1398
+ ...inputEdit(resolving.canvas, instance, input.name)
1399
+ };
1400
+ }
1401
+ };
1402
+ var rename = {
1403
+ id: "rename",
1404
+ takesValue: true,
1405
+ async plan({ canvas, values, pick }) {
1406
+ const name = givenName(values, "the new name");
1407
+ const instance = await pick("instance", "instance", instanceOptions(canvas.instances));
1408
+ return {
1409
+ action: {
1410
+ rename_instance: { scope: instance.scope, old_id: instance.name, new_id: name }
1411
+ },
1412
+ summary: () => `renamed ${instance.id} to ${name}`,
1413
+ ...instanceEdit(canvas, instance, name)
1414
+ };
1415
+ }
1416
+ };
1417
+ var remove = {
1418
+ id: "delete",
1419
+ takesValue: false,
1420
+ async plan({ canvas, pick }) {
1421
+ const instance = await pick("instance", "instance", instanceOptions(canvas.instances));
1422
+ return {
1423
+ action: { delete_instance: { scope: instance.scope, instance_id: instance.name } },
1424
+ summary: () => `deleted ${instance.id}`,
1425
+ ...instanceEdit(canvas, instance, instance.name)
1426
+ };
1427
+ }
1428
+ };
1429
+ var ungroup = {
1430
+ id: "ungroup",
1431
+ takesValue: false,
1432
+ async plan({ canvas, pick }) {
1433
+ const groups = new Set(canvas.groups.map((group2) => group2.id));
1434
+ const group = await pick(
1435
+ "instance",
1436
+ "group",
1437
+ instanceOptions(canvas.instances.filter((instance) => groups.has(instance.id)))
1438
+ );
1439
+ return {
1440
+ action: { ungroup: { scope: group.scope, group_id: group.name } },
1441
+ summary: () => `ungrouped ${group.id}`,
1442
+ ...instanceEdit(canvas, group, group.name)
1443
+ };
1444
+ }
1445
+ };
1446
+ var OPERATIONS = [
1447
+ place,
1448
+ connect,
1449
+ disconnect,
1450
+ set,
1451
+ bind,
1452
+ clear,
1453
+ rename,
1454
+ remove,
1455
+ ungroup
1456
+ ];
1457
+ var CANCELLED = { kind: "cancelled" };
1458
+ var Fell = class extends Error {
1459
+ constructor(label) {
1460
+ super(`the ${label} fell to System Two`);
1461
+ this.label = label;
1462
+ }
1463
+ };
1464
+ function heldMore(decisions) {
1465
+ return decisions.some(
1466
+ (decision) => decision.others.length > 0 || decision.kind === "steps" && decision.option.value === "several"
1467
+ );
436
1468
  }
437
- var PROMPT_TEMPLATE = `You are Lace, an AI assistant that is the primary interface for composing Terraform infrastructure. Users describe what they need in natural language, and you compose it on a visual canvas. The canvas is an inspection and verification layer \u2014 you drive the composition.
438
-
439
- ## Canvas State
440
-
441
- Before each response, you receive a fresh snapshot of the current canvas (instances, connections, errors). This is your ground truth. Use it for instance IDs \u2014 never guess. The snapshot reflects all changes, including manual edits the user made on the canvas between messages.
442
-
443
- ## When the Engine Is Not Running
444
-
445
- Tell the user to start it with **Lace: Start Engine** from the Command Palette. Do not call any tools.
446
-
447
- ## When No Canvas Is Open
448
-
449
- Tell the user to open one with **Lace: Open Canvas** from the Command Palette. Do not call any write tools.
450
-
451
- ## Core Concepts
452
-
453
- **Instances**: When a module is added to the canvas it becomes an instance with a unique ID (e.g., "vpc", "subnet_1"). All write tools use instance IDs.
454
-
455
- **Input bindings** \u2014 each module input can be:
456
- - **empty** \u2014 not set (must be filled before generating)
457
- - **literal** \u2014 a hardcoded value: string, number, bool, object, or array
458
- - **variable** \u2014 a \`var.NAME\` reference, configurable at deploy time
459
- - **expression** \u2014 raw HCL: e.g., \`local.region\`, \`cidrsubnet(var.vpc_cidr, 8, 0)\`
460
- - **wired** \u2014 connected from another instance's output (via lace_connect or lace_auto_connect)
461
-
462
- ## Available Tools
463
-
464
- **Read tools** (gather information first):
465
- - lace_search_registry: Search the module registry by keyword, system ({{SYSTEMS}}), or category.
466
- - lace_inspect_module: Get full input/output schema for a registry module (before adding).
467
- - lace_describe_graph: Get the current canvas state \u2014 instances, connections, errors.
468
- - lace_validate_graph: Run validation \u2014 returns auto-resolvable vs. user-required errors.
469
- - lace_inspect_node: Get the live input bindings and outputs of a placed instance.
470
- - lace_get_settings: Read terraform block, providers, and locals.
471
- - lace_workspace_context: Analyze project files \u2014 returns a structured ProjectProfile + raw content.
472
-
473
- **Write tools** (modify the canvas):
474
- - lace_add_module: Add a module to the canvas.
475
- - lace_remove_module: Remove an instance.
476
- - lace_connect: Wire a source output to a target input.
477
- - lace_auto_connect: Best-effort wiring between two instances.
478
- - lace_disconnect: Remove a wire from a specific input.
479
- - lace_set_input: Set a literal value, variable reference, or HCL expression.
480
- - lace_rename_instance: Rename an instance (cascades to all references).
481
- - lace_set_variable: Add or update a canvas-level variable (var.NAME).
482
- - lace_set_local: Add or update a local value (literal or expression).
483
- - lace_create_group: Group instances visually on the canvas.
484
- - lace_ungroup: Remove a visual group (instances stay on canvas).
485
- - lace_undo: Undo the last canvas change.
486
- - lace_generate: Generate Terraform .tf files from the canvas.
487
-
488
- ## Workflow Rules
489
-
490
- 1. **Use the canvas snapshot** for instance IDs and error flags. Call lace_inspect_node for exact port names. Never guess port names.
491
- 2. **Search before adding**: lace_search_registry first, then lace_add_module. One search per module.
492
- 3. **Inspect before connecting**: lace_inspect_node on both source and target for exact output/input names.
493
- 4. **Auto-connect for common patterns**: lace_auto_connect first, fall back to lace_connect.
494
- 5. **Validate once at the end**: After all changes, call lace_validate_graph. Not after every step.
495
- 6. **Act on confirmation**: When the user says "yes", "go ahead", "do it" \u2014 execute immediately without re-asking.
496
- 7. **Never guess ambiguous values**: If a required input needs a value you cannot infer (DNS names, zone IDs, resource names, secrets), list the fields and ask. Never set placeholders.
497
- 8. **Respect version requests**: Pass the user's exact version to lace_add_module.
498
- 9. **Organize as you go**: After adding a batch of related modules, group them with lace_create_group. Keep the canvas readable without being asked.
499
-
500
- ## Starting a New Composition
501
-
502
- 1. Call lace_workspace_context to analyze the project.
503
- 2. Review the **ProjectProfile** (languages, frameworks, databases, cloud_hints). Ask 1-2 clarifying questions if needed:
504
- - If cloud provider is unclear: "Which cloud provider are you targeting?"
505
- - If project type is ambiguous: "Is this a web API, data pipeline, or static site?"
506
- - If they have a Dockerfile but no cloud hints: "How do you want to deploy \u2014 containers, serverless, or VMs?"
507
- 3. Based on answers + profile, suggest 2-3 module combinations. One sentence per suggestion.
508
- 4. Ask: "Want me to set these up?" \u2014 then STOP.
509
- 5. On confirmation, execute everything without re-asking.
510
-
511
- **CRITICAL: If the user confirmed in a previous message, do not ask again. Proceed immediately.**
512
-
513
- ## Understanding the Project
514
-
515
- When lace_workspace_context returns a ProjectProfile:
516
- - Match language + framework to infrastructure patterns (e.g., Express + Docker \u2192 ECS or Lambda)
517
- - Check cloud_hints for provider selection
518
- - Check existing_modules to avoid adding duplicates
519
- - Use databases array to suggest managed database services (postgres \u2192 RDS, mongodb \u2192 DocumentDB)
520
-
521
- ## Handling Validation Errors
522
-
523
- When the user mentions errors, says "fix it", "what's wrong", or "check for issues":
524
- 1. Call lace_validate_graph.
525
- 2. The response classifies errors as **auto-resolvable** vs. **requires user input**.
526
- 3. Fix all auto-resolvable errors (wire connections, set defaults) without asking.
527
- 4. For user-required values: list them clearly and ask. Never guess.
528
- 5. Summarize what you fixed and what you still need from the user.
529
-
530
- ## Input Value Guidance
531
-
532
- When setting inputs, use these heuristics for common types:
533
- - **CIDR blocks**: Suggest 10.0.0.0/16 for VPC. For subnets, use cidrsubnet(var.vpc_cidr, 8, N).
534
- - **Boolean flags**: Set sensible defaults (enable_dns_support=true, enable_dns_hostnames=true).
535
- - **Regions**: Ask the user, or use cloud_hints from ProjectProfile.
536
- - **Instance types**: Suggest cost-effective defaults (t3.medium, Standard_B2ms) but note the user can change them.
537
- - **Names, IDs, ARNs, passwords, secrets**: NEVER guess. Always ask.
538
-
539
- ## Using Locals and Per-Environment Values
540
-
541
- - Call lace_get_settings to see existing locals.
542
- - Use lace_set_local to create reusable values (e.g., local.region).
543
- - Reference locals in module inputs via expression: "local.NAME".
544
- - Per-environment values (staging vs production) are not part of the canvas \u2014 tell the user to pass them at plan time with \`lace stack preview|apply|destroy --var-file <file>\` or \`--var name=value\`. Values passed this way are baked into the plan, so they are not secret-safe; point the user to a provider data source for secrets instead.
545
-
546
- ## Canvas Organization
547
-
548
- Groups are visual containers that organize related instances on the canvas. They don't affect Terraform generation \u2014 they're purely for readability.
549
-
550
- **Proactive grouping:** As you build a composition, organize it into groups so the canvas stays readable. Group by logical function:
551
- - Networking: VPCs, subnets, route tables, NAT gateways, security groups
552
- - Compute: EC2 instances, ASGs, launch templates, load balancers
553
- - Data: RDS, DynamoDB, S3, ElastiCache
554
- - Identity: IAM roles, policies, instance profiles
555
- - Monitoring: CloudWatch alarms, log groups, dashboards
556
-
557
- **When to group:**
558
- - After adding 3+ related modules in a batch, group them immediately.
559
- - After the canvas exceeds ~8 instances, review and organize ungrouped nodes.
560
- - When the user asks to "add another X" to an existing cluster of related modules, add the new module and include it in the relevant group.
561
-
562
- **Naming:** Use short functional labels: "Network", "Compute", "Database", "Auth", "Monitoring". Not instance IDs or module names.
563
-
564
- ## Error Recovery
565
-
566
- - Tool returns "not found": call lace_describe_graph for current instance IDs.
567
- - Module not in registry: try broader search terms or remove the system filter.
568
- - Auto-connect finds no matches: it shows available ports \u2014 use lace_connect manually.
569
- - Wrong change: call lace_undo immediately.
570
-
571
- ## Conventions
572
-
573
- - Instance IDs are Terraform identifiers (e.g., "vpc", "subnet_1"), auto-generated on add.
574
- - Module names follow "system/name" (e.g., "aws/vpc", "azure/resource-group").
575
- - Each input has one binding. Setting a new one replaces the previous.
576
-
577
- ## Response Style
578
-
579
- - Be concise \u2014 one or two sentences to confirm what was done.
580
- - After changes, summarize the final state.
581
- - Execute all steps before responding. Do not narrate each step.
582
- - Only ask for clarification when genuinely ambiguous and not answerable from context or conversation history.
583
- - **Never ask the same question twice.** If answered in a prior turn, act on it.
584
- `;
585
-
586
- // src/tool-registry.ts
587
- function createToolRegistry() {
588
- const entries = /* @__PURE__ */ new Map();
1469
+ var twoSystems2 = (decision) => decision.composed !== null;
1470
+ var composedOf = (decisions) => decisions.flatMap((decision) => decision.composed === null ? [] : [decision.composed]);
1471
+ function movedText(operation, error) {
1472
+ return error instanceof Fell || error instanceof Undecided ? `the ${error.label} under Lace's ${operation} fell to your reading` : `Lace's ${operation} did not resolve: ${errorText(error)}`;
1473
+ }
1474
+ function statedFacts(names2, reading) {
1475
+ const fact = (slot, name) => slot === "operation" ? OPERATIONS.some((operation) => operation.id === name) : slot === "module" ? moduleReferences(name)[0] === name : names2.has(name);
1476
+ return Object.fromEntries(
1477
+ statedSlots(reading).flatMap((slot) => {
1478
+ const name = reading[slot];
1479
+ return name !== void 0 && fact(slot, name) ? [[slot, name]] : [];
1480
+ })
1481
+ );
1482
+ }
1483
+ var asItIs = (apply) => apply();
1484
+ async function resolveAndApply(ports, own, change, call, client, signal, trail, notApplied) {
1485
+ const canvas = readCanvas(await latest(ports.source));
1486
+ const names2 = canvasNames(canvas);
1487
+ const values = [...forms(change.values), ...unnamed(names2, call)];
1488
+ const statementOf = (reading) => withhold(renderReading(statedFacts(names2, reading)), values);
1489
+ const statement = statementOf(change.reading);
1490
+ const alternative = change.alternative === void 0 ? void 0 : { statement: statementOf(change.alternative), reading: change.alternative };
1491
+ const statements = [statement, ...alternative === void 0 ? [] : [alternative.statement]];
1492
+ const request = renderRequest(
1493
+ change.request,
1494
+ values,
1495
+ statements.reduce((longest, each) => each.length > longest.length ? each : longest)
1496
+ );
1497
+ const rankable = !holdsValue(withhold([request, ...statements].join(" "), [...names2]), values);
1498
+ const rank = client?.rank;
1499
+ const main = {
1500
+ request,
1501
+ terms: termsOf(request.split(VALUE_PLACEHOLDER).join(" ")),
1502
+ statement,
1503
+ reading: change.reading,
1504
+ ...rankable ? { rank } : {}
1505
+ };
1506
+ const ask = { ...main, ...alternative === void 0 ? {} : { alternative } };
1507
+ const decided2 = (on, kind, label, options, stated2) => {
1508
+ stopIfCancelled(signal);
1509
+ return decide(on, kind, label, options, stated2);
1510
+ };
1511
+ const resolvingInto = (into, trial) => ({
1512
+ canvas,
1513
+ request,
1514
+ values: change.values,
1515
+ ports,
1516
+ signal,
1517
+ async pick(kind, label, options) {
1518
+ const decision = await decided2(ask, kind, label, options);
1519
+ into.decisions.push(decision);
1520
+ if (trial && !moveStands(composedOf(into.decisions.slice(1)))) throw new Fell(label);
1521
+ return decision.option.value;
1522
+ },
1523
+ note: (line) => into.notes.push(line)
1524
+ });
1525
+ const planUnder = (decision, into, trial) => {
1526
+ into.decisions.push(decision);
1527
+ return decision.option.value.plan(resolvingInto(into, trial));
1528
+ };
1529
+ const first = await decided2(ask, "operation", "operation", operationOptions(OPERATIONS));
1530
+ const statedOperation = operationOptions(OPERATIONS).find(
1531
+ (each) => each.candidate.id === first.chat
1532
+ );
1533
+ const moveRule = async () => {
1534
+ if (first.how !== "clm" || statedOperation === void 0 || statedOperation.value === first.option.value) {
1535
+ return { operation: first.option.value, plan: await planUnder(first, trail, false) };
1536
+ }
1537
+ const trial = { decisions: [], notes: [] };
1538
+ try {
1539
+ const planned = await planUnder(first, trial, true);
1540
+ trail.decisions.push(...trial.decisions);
1541
+ trail.notes.push(...trial.notes);
1542
+ return { operation: first.option.value, plan: planned };
1543
+ } catch (error) {
1544
+ stopIfCancelled(signal);
1545
+ trail.moved = withhold(movedText(first.option.value.id, error), change.values);
1546
+ const standing = {
1547
+ ...first,
1548
+ option: statedOperation,
1549
+ how: "chat",
1550
+ composed: {
1551
+ took: "chat",
1552
+ taken: statedOperation.candidate.id,
1553
+ clm: first.composed?.clm ?? null,
1554
+ differed: false
1555
+ },
1556
+ alternative: first.alternative?.id === first.option.candidate.id ? null : first.alternative
1557
+ };
1558
+ return { operation: statedOperation.value, plan: await planUnder(standing, trail, false) };
1559
+ }
1560
+ };
1561
+ const { operation, plan } = await moveRule();
1562
+ const unread = trail.decisions.every((decision) => decision.others.length === 0);
1563
+ if (unread && main.rank !== void 0 && trail.decisions.some(twoSystems2)) {
1564
+ const steps = await decided2(main, "steps", "steps", stepsOptions(), "one");
1565
+ if (steps.ranking !== NOT_RANKED) trail.decisions.push(steps);
1566
+ }
1567
+ if (change.values.length > 0 && !operation.takesValue && !heldMore(trail.decisions)) {
1568
+ trail.notes.push(
1569
+ `The \`value\` sent with this change was not used: ${operation.id} takes none.`
1570
+ );
1571
+ }
1572
+ const lace = Object.assign({}, ...trail.decisions.map((each) => each.option.slots));
1573
+ const stated = statedSlots(change.reading);
1574
+ for (const slot of stated.filter(
1575
+ (slot2) => !trail.decisions.some(
1576
+ (decision) => decision.readings.some((each) => each[slot2] === change.reading[slot2])
1577
+ )
1578
+ )) {
1579
+ trail.notes.push(
1580
+ `Your reading's ${slot} ${change.reading[slot]} is not one of Lace's candidates${slot in lace ? `; Lace read ${lace[slot]}` : ""}.`
1581
+ );
1582
+ }
1583
+ const asked = trail.decisions.filter(
1584
+ (decision) => decision.alternative?.sure === true && decision.alternative.id !== decision.option.candidate.id
1585
+ );
1586
+ if (asked.length > 0) {
1587
+ return {
1588
+ kind: "asked",
1589
+ lace,
1590
+ alternative: Object.assign(
1591
+ {},
1592
+ ...trail.decisions.map(
1593
+ (decision) => asked.includes(decision) ? decision.alternative?.slots : decision.option.slots
1594
+ )
1595
+ )
1596
+ };
1597
+ }
1598
+ stopIfCancelled(signal);
1599
+ const result = await own(() => ports.editor.apply([plan.action]));
1600
+ if (!result.success) {
1601
+ const reasons = result.errors.map((error) => error.message).join("; ");
1602
+ return notApplied(`the engine refused it: ${reasons}`);
1603
+ }
1604
+ const after = readCanvas(await latest(ports.source));
1605
+ const record = {
1606
+ id: crypto.randomUUID(),
1607
+ target: plan.target(result),
1608
+ before: plan.before,
1609
+ after: plan.after(after, result),
1610
+ ...result.revision === void 0 ? {} : { revision: result.revision },
1611
+ questions: trail.decisions.map((decision) => ({
1612
+ kind: decision.kind,
1613
+ candidates: decision.candidates.map((candidate) => candidate.id)
1614
+ })),
1615
+ reported: false
1616
+ };
589
1617
  return {
590
- register(schema, handler) {
591
- entries.set(schema.name, { schema, handler });
1618
+ kind: "applied",
1619
+ summary: plan.summary(result),
1620
+ record,
1621
+ canvas: after,
1622
+ withheld: unnamed(names2, call)
1623
+ };
1624
+ }
1625
+ async function runChange(ports, own, change, call, client, signal, trail) {
1626
+ const notApplied = (why) => ({
1627
+ kind: "notApplied",
1628
+ why: withhold(why, change.values)
1629
+ });
1630
+ try {
1631
+ return await resolveAndApply(ports, own, change, call, client, signal, trail, notApplied);
1632
+ } catch (error) {
1633
+ if (error instanceof ApplyUnobservedError) {
1634
+ return { kind: "unobserved", end: withhold(endText(error.end), change.values) };
1635
+ }
1636
+ if (error instanceof Cancelled) return CANCELLED;
1637
+ if (error instanceof Undecided) {
1638
+ trail.undecided = error;
1639
+ const candidates = error.candidates.map((candidate) => candidate.id).join(", ");
1640
+ return notApplied(
1641
+ `the ${error.label} was not decided: ${rankingText(error.ranking)}, and your reading names none of its candidates: ${candidates}. Send this change again with \`modelReading\` naming one as the canvas lists it.`
1642
+ );
1643
+ }
1644
+ return notApplied(errorText(error));
1645
+ }
1646
+ }
1647
+ function rankingText(ranking2) {
1648
+ if (ranking2.ranked === null) return ranking2.failed;
1649
+ const [first] = ranking2.ranked.scores;
1650
+ const read2 = first?.id === NONE_CANDIDATE_ID ? `read ${NONE_OVER} first` : `ranked ${first?.id} first`;
1651
+ return `Lace was not sure, ${read2}`;
1652
+ }
1653
+ function decisionLine(decision, moved2) {
1654
+ const also = `the request also names ${decision.others.join(", ")}`;
1655
+ const named2 = {
1656
+ exact: ["named in the request"],
1657
+ unique: ["named in the request, ignoring case"],
1658
+ first: ["named in the request first", also],
1659
+ agreed: ["named in the request and in your reading", also]
1660
+ };
1661
+ const basis = decision.how === "clm" ? [
1662
+ `Lace's pick of ${decision.offered}`,
1663
+ ...decision.offered > decision.candidates.length ? [`ranked in parts, as ${decision.offered} candidates are more than one ranking holds`] : [],
1664
+ ...decision.over.map((candidate) => `over ${candidate}`),
1665
+ ...decision.composed?.differed ? [`your reading named ${decision.chat}`] : []
1666
+ ] : decision.how === "chat" ? [
1667
+ "your reading",
1668
+ moved2 !== void 0 && decision.kind === "operation" ? moved2 : decision.ranking === null ? "Lace did not rank" : rankingText(decision.ranking)
1669
+ ] : named2[decision.how];
1670
+ return ` ${decision.label}: ${decision.option.candidate.id} (${basis.join(", ")})`;
1671
+ }
1672
+ function outcomeLines(number, outcome, trail) {
1673
+ const head = `Change ${number}:`;
1674
+ const lines = trail.decisions.map((decision) => decisionLine(decision, trail.moved));
1675
+ switch (outcome.kind) {
1676
+ case "applied": {
1677
+ const moved2 = trail.moved === void 0 ? "" : " Lace's operation did not stand and yours did, marked below.";
1678
+ const unsure = trail.decisions.some(
1679
+ (decision) => decision.how === "chat" && (trail.moved === void 0 || decision.kind !== "operation")
1680
+ );
1681
+ const stood = unsure ? " Where Lace was not sure, your reading stood, marked below." : "";
1682
+ const differed = trail.decisions.some((decision) => decision.composed?.differed) ? " Lace's reading differed from yours and stood, marked below: tell the developer." : "";
1683
+ const others = trail.decisions.flatMap((decision) => decision.others);
1684
+ const unapplied = others.length > 0 ? `; nothing was applied for ${others.join(", ")}` : "";
1685
+ const more = heldMore(trail.decisions) ? ` This entry held more than one change and only this one was applied${unapplied}. Send the rest, one entry per change.` : "";
1686
+ return [`${head} applied. ${outcome.summary}.${more}${moved2}${stood}${differed}`, ...lines];
1687
+ }
1688
+ case "asked":
1689
+ return [
1690
+ `${head} not applied. Lace is sure your alternative reading means another change than the one it decided.`,
1691
+ ` Your reading: ${renderReading(outcome.lace)}`,
1692
+ ` Your alternative reading: ${renderReading(outcome.alternative)}`,
1693
+ " Ask the developer which is meant, then send that one."
1694
+ ];
1695
+ case "notApplied":
1696
+ return [`${head} not applied. Reason: ${outcome.why}`, ...lines];
1697
+ case "cancelled":
1698
+ return [`${head} not applied. The call was cancelled before it applied.`];
1699
+ case "unobserved":
1700
+ return [
1701
+ `${head} sent, and the engine answered it, but the session's stream ended (${outcome.end}) before the canvas showed it, so whether it applied cannot be read here. Do not send it again before the canvas is open again.`,
1702
+ ...lines
1703
+ ];
1704
+ }
1705
+ }
1706
+ function questionOf(decision) {
1707
+ const taken = decision.option.candidate.id;
1708
+ return {
1709
+ kind: decision.kind,
1710
+ capture_id: asAsked(decision.ranking)?.capture_id ?? null,
1711
+ chat: decision.chat,
1712
+ clm: decision.composed?.clm ?? null,
1713
+ took: decision.composed === null ? "named" : decision.composed.took,
1714
+ taken
1715
+ };
1716
+ }
1717
+ function undecidedOf(undecided) {
1718
+ const ranked = asAsked(undecided.ranking);
1719
+ const pick = ranked === null ? void 0 : pickOf(ranked.scores);
1720
+ return {
1721
+ kind: undecided.kind,
1722
+ capture_id: ranked?.capture_id ?? null,
1723
+ chat: null,
1724
+ clm: pick === void 0 ? null : { id: pick.id, rightness: pick.rightness },
1725
+ took: "chat",
1726
+ taken: null
1727
+ };
1728
+ }
1729
+ function reportOf(id, trail, applied, asked) {
1730
+ const questions = [
1731
+ ...trail.decisions.map(questionOf),
1732
+ ...trail.undecided === void 0 ? [] : [undecidedOf(trail.undecided)]
1733
+ ];
1734
+ return questions.some((question) => question.took !== "named") ? { id, surface: "canvas", questions, applied, asked } : void 0;
1735
+ }
1736
+ async function applyChanges(ports, changes, own = asItIs, signal) {
1737
+ const call = changes.flatMap((change) => change.values);
1738
+ const client = ports.transport === void 0 ? void 0 : rankingClient(ports.transport).changeCall(signal);
1739
+ const lines = [];
1740
+ let applied = [];
1741
+ const unapplied = [];
1742
+ let last;
1743
+ for (const [index, change] of changes.entries()) {
1744
+ const trail = { decisions: [], notes: [] };
1745
+ const outcome = signal?.aborted ? CANCELLED : await runChange(ports, own, change, call, client, signal, trail);
1746
+ lines.push(
1747
+ ...outcomeLines(index + 1, outcome, trail),
1748
+ ...outcome.kind === "cancelled" ? [] : trail.notes.map((line) => ` ${line}`)
1749
+ );
1750
+ if (outcome.kind === "applied") {
1751
+ const { canvas } = outcome;
1752
+ const before = last;
1753
+ applied = [
1754
+ ...before === void 0 ? [] : applied.map((each) => ({ ...each, record: follow(each.record, before, canvas) })),
1755
+ { record: outcome.record, withheld: outcome.withheld, trail }
1756
+ ];
1757
+ last = canvas;
1758
+ } else if (outcome.kind !== "unobserved" && outcome.kind !== "cancelled") {
1759
+ const report = reportOf(crypto.randomUUID(), trail, null, outcome.kind === "asked");
1760
+ if (report !== void 0) unapplied.push(report);
1761
+ }
1762
+ }
1763
+ const left = last;
1764
+ const settled = left === void 0 ? [] : applied.map(({ record, withheld, trail }) => {
1765
+ const standing = { ...record, after: targetState(left, record) };
1766
+ const report = reportOf(record.id, trail, appliedText(standing, withheld), false);
1767
+ return { record: standing, report };
1768
+ });
1769
+ const reports = [
1770
+ ...signal?.aborted ? [] : unapplied,
1771
+ ...settled.flatMap(({ report }) => report === void 0 ? [] : [report])
1772
+ ];
1773
+ const sent = client === void 0 ? [] : reports.map((report) => ({ report, ...client.decision(report) }));
1774
+ const made = new Set(sent.flatMap(({ report, made: made2 }) => made2 ? [report] : []));
1775
+ try {
1776
+ await untilCancelled(Promise.all(sent.map(({ settled: settled2 }) => settled2)), signal);
1777
+ } catch (error) {
1778
+ if (!(error instanceof Cancelled)) throw error;
1779
+ }
1780
+ const records = settled.map(({ record, report }) => ({
1781
+ ...record,
1782
+ reported: report !== void 0 && made.has(report)
1783
+ }));
1784
+ return { text: lines.join("\n"), applied: records };
1785
+ }
1786
+ function appliedText(record, withheld) {
1787
+ return withhold(
1788
+ `${renderTarget(record.target)}: ${renderState(record.before)} \u2192 ${renderState(record.after)}`,
1789
+ withheld
1790
+ );
1791
+ }
1792
+
1793
+ // src/surfaces/canvas/canvas-tools.ts
1794
+ var READING_PROPERTIES = {
1795
+ operation: {
1796
+ type: "string",
1797
+ enum: OPERATIONS.map((operation) => operation.id),
1798
+ description: OPERATIONS.map((operation) => OPERATION_TEXT[operation.id]).join("; ")
1799
+ },
1800
+ instance: {
1801
+ type: "string",
1802
+ description: "The instance a set, bind, clear, disconnect, rename or delete works on, or the group an ungroup dissolves."
1803
+ },
1804
+ input: {
1805
+ type: "string",
1806
+ description: "The input a set, bind, clear or disconnect works on, or a connect wires into."
1807
+ },
1808
+ sourceInstance: {
1809
+ type: "string",
1810
+ description: "The instance a connect wires from."
1811
+ },
1812
+ output: { type: "string", description: "The output a connect wires from." },
1813
+ targetInstance: {
1814
+ type: "string",
1815
+ description: "The instance a connect wires into."
1816
+ },
1817
+ module: {
1818
+ type: "string",
1819
+ description: "The registry module a place adds, as `author/name`."
1820
+ }
1821
+ };
1822
+ var READING = { type: "object", properties: READING_PROPERTIES, additionalProperties: false };
1823
+ var CHANGE = {
1824
+ name: "lace_change_module_canvas",
1825
+ title: "Change module canvas",
1826
+ description: [
1827
+ "Changes a Lace module canvas. Do not read the canvas before calling it. For each change pass the developer's own words in `request`, one entry per change: this tool resolves which operation, instances, inputs, outputs and registry modules are meant.",
1828
+ "`request` carries the words and never a literal value: pass each literal the developer gave (an input's value, an instance's new name, the name of the variable an input is bound to) in `value`, one change per entry, each with its own `value`. Lace withholds `value` from what it ranks and keeps, and keeps the words of `request` as written; the tool selects and never writes a value of its own.",
1829
+ "Every result of this tool carries the current canvas. On every call pass your own reading of each change in `modelReading`: always its `operation`, and any instance, input, output or registry module the developer named, as the canvas lists it once a result has shown you the canvas. Never put a value in `modelReading`. Where the words bear a second reading, pass it in `alternativeReading`.",
1830
+ "Lace reads the words too and applies its own reading where it is sure, yours otherwise; where the two differ the result says so: tell the developer. When Lace is also sure of your alternative reading, nothing is applied and the result shows both: ask the developer. A change neither reading settles is not applied, and the result names the part and its candidates: send it again naming one as the canvas lists it, with the developer's own words. Do not save or generate unless the developer asked."
1831
+ ].join(" "),
1832
+ inputSchema: {
1833
+ type: "object",
1834
+ properties: {
1835
+ changes: {
1836
+ type: "array",
1837
+ minItems: 1,
1838
+ description: "The changes, in order, one entry per change.",
1839
+ items: {
1840
+ type: "object",
1841
+ properties: {
1842
+ request: {
1843
+ type: "string",
1844
+ description: "One change, in the developer's own words, and never a literal value: that goes in `value`."
1845
+ },
1846
+ value: {
1847
+ description: "The literal the developer gave for this change: an input's value, an instance's new name, or the name of the variable an input is bound to (`var.<name>`). One value per entry: a change with a value of its own is an entry of its own."
1848
+ },
1849
+ modelReading: READING,
1850
+ alternativeReading: READING
1851
+ },
1852
+ required: ["request", "modelReading"],
1853
+ additionalProperties: false
1854
+ }
1855
+ }
592
1856
  },
593
- getHandler(name) {
594
- return entries.get(name)?.handler;
1857
+ required: ["changes"],
1858
+ additionalProperties: false
1859
+ }
1860
+ };
1861
+ var DESCRIBE = {
1862
+ name: "lace_describe_module_canvas",
1863
+ title: "Describe module canvas",
1864
+ description: "Describes a Lace module canvas (its module instances with their inputs and outputs, the wires between them, the groups, the diagnostics, and whether it holds unsaved or ungenerated edits) for answering questions about it. Not needed before making changes.",
1865
+ inputSchema: NO_INPUT
1866
+ };
1867
+ var SAVE = {
1868
+ name: "lace_save_module_canvas",
1869
+ title: "Save module canvas",
1870
+ description: "Saves a Lace module canvas. Call it only when the developer asks to save.",
1871
+ inputSchema: NO_INPUT
1872
+ };
1873
+ var GENERATE = {
1874
+ name: "lace_generate_module_terraform",
1875
+ title: "Generate module Terraform",
1876
+ description: "Writes the Terraform for a Lace module canvas: the saved canvas rendered to the module's .tf files. Returns the files written, or why Lace did not generate. Call it only when the developer asks to generate.",
1877
+ inputSchema: NO_INPUT
1878
+ };
1879
+ var canvasToolSchemas = [
1880
+ CHANGE,
1881
+ DESCRIBE,
1882
+ SAVE,
1883
+ GENERATE
1884
+ ];
1885
+ function generateSaid(event) {
1886
+ switch (event.type) {
1887
+ case "progress":
1888
+ return [];
1889
+ case "success":
1890
+ return [
1891
+ {
1892
+ text: [
1893
+ `Generated the Terraform. Files written: ${event.written.join(", ")}.`,
1894
+ `lace module validate on the written tree: ${JSON.stringify(trimValidate(event.validate))}`
1895
+ ].join("\n"),
1896
+ isError: false
1897
+ }
1898
+ ];
1899
+ case "error":
1900
+ return [
1901
+ {
1902
+ text: `Lace did not generate: ${event.message} (${reasonText(event.reason)}).`,
1903
+ isError: true
1904
+ }
1905
+ ];
1906
+ }
1907
+ }
1908
+ function unobserved(error) {
1909
+ if (!(error instanceof ApplyUnobservedError2)) throw error;
1910
+ return {
1911
+ text: `The session's stream ended (${endText(error.end)}) before the canvas showed this, so the canvas below is from before it.`,
1912
+ isError: false
1913
+ };
1914
+ }
1915
+ function cancelledSaid(operation, sent) {
1916
+ return {
1917
+ text: sent ? `The call was cancelled after the ${operation} was sent: it goes on in the engine, and the canvas below may be from before it ends.` : `The call was cancelled before the ${operation} was sent: nothing was done.`,
1918
+ isError: false
1919
+ };
1920
+ }
1921
+ var NO_RECORDS = { applied: [] };
1922
+ function canvasTools(ports) {
1923
+ const [change, describe, save, generate] = canvasToolSchemas;
1924
+ const observer = ports.transport === void 0 ? void 0 : outcomeObserver(ports.transport);
1925
+ const dispose = observer === void 0 ? () => {
1926
+ } : ports.source.subscribe(observer.frame, () => {
1927
+ });
1928
+ const attempt = (run) => run().catch((error) => [{ text: errorText(error), isError: true }]);
1929
+ const answer = async (said2) => ({
1930
+ content: [
1931
+ ...said2.map((each) => `${each.text}
1932
+ `),
1933
+ renderCanvas(await latest(ports.source))
1934
+ ].join("\n"),
1935
+ isError: said2.some((each) => each.isError)
1936
+ });
1937
+ const registrations = [
1938
+ registrationOf(
1939
+ change,
1940
+ async (input, signal) => {
1941
+ try {
1942
+ const { text: text2, applied } = await applyChanges(
1943
+ ports,
1944
+ parseChanges(input),
1945
+ observer?.own,
1946
+ signal
1947
+ );
1948
+ observer?.follow(applied);
1949
+ return { ...await answer([{ text: text2, isError: false }]), applied };
1950
+ } catch (error) {
1951
+ if (!(error instanceof InvalidInput)) throw error;
1952
+ return { ...await answer([{ text: errorText(error), isError: true }]), ...NO_RECORDS };
1953
+ }
1954
+ },
1955
+ (failure) => ({ ...failure, ...NO_RECORDS })
1956
+ ),
1957
+ registration(describe, () => answer([])),
1958
+ registration(
1959
+ save,
1960
+ async (_input, signal) => answer(
1961
+ await attempt(async () => {
1962
+ if (signal?.aborted) return [cancelledSaid("save", false)];
1963
+ const saved = { text: "Saved the canvas.", isError: false };
1964
+ try {
1965
+ await untilCancelled(ports.editor.save(), signal);
1966
+ return [saved];
1967
+ } catch (error) {
1968
+ if (error instanceof Cancelled) return [cancelledSaid("save", true)];
1969
+ return [saved, unobserved(error)];
1970
+ }
1971
+ })
1972
+ )
1973
+ ),
1974
+ registration(
1975
+ generate,
1976
+ async (_input, signal) => answer(
1977
+ await attempt(async () => {
1978
+ if (signal?.aborted) return [cancelledSaid("Generate", false)];
1979
+ const said2 = [];
1980
+ const events = ports.editor.generate()[Symbol.asyncIterator]();
1981
+ try {
1982
+ for (let next = await untilCancelled(events.next(), signal); next.done !== true; next = await untilCancelled(events.next(), signal)) {
1983
+ said2.push(...generateSaid(next.value));
1984
+ }
1985
+ } catch (error) {
1986
+ if (error instanceof Cancelled) return [...said2, cancelledSaid("Generate", true)];
1987
+ said2.push(unobserved(error));
1988
+ }
1989
+ return said2;
1990
+ })
1991
+ )
1992
+ )
1993
+ ];
1994
+ return Object.assign(registrations, { dispose });
1995
+ }
1996
+
1997
+ // src/surfaces/canvas/module-tools.ts
1998
+ var VALIDATE = {
1999
+ name: "lace_validate_module_terraform",
2000
+ title: "Validate module Terraform",
2001
+ description: "Runs `lace module validate` on a module's Terraform on disk, not on its canvas: canvas edits reach the Terraform after Save and Generate. Returns the verdict (whether the module is in Lace style) and the diagnostics.",
2002
+ inputSchema: NO_INPUT
2003
+ };
2004
+ var SEARCH = {
2005
+ name: "lace_search_module_registry",
2006
+ title: "Search module registry",
2007
+ description: "Searches the Lace module registry. Returns each published module as `author/name` with its latest version, its description, its system and its categories.",
2008
+ inputSchema: {
2009
+ type: "object",
2010
+ properties: {
2011
+ query: { type: "string", description: "Words to find in a module." },
2012
+ system: { type: "string", description: "The system a module is for, such as `aws`." },
2013
+ category: { type: "string", description: "A category a module is listed under." }
595
2014
  },
596
- listSchemas() {
597
- return [...entries.values()].map((e) => e.schema);
2015
+ additionalProperties: false
2016
+ }
2017
+ };
2018
+ var DESCRIBE2 = {
2019
+ name: "lace_describe_registry_module",
2020
+ title: "Describe registry module",
2021
+ description: "Describes one module of the Lace module registry before it is placed: every input with its type, default and whether it is required, every output, the version and the verdict of its certification.",
2022
+ inputSchema: {
2023
+ type: "object",
2024
+ properties: {
2025
+ module: { type: "string", description: "The module, as `author/name`." },
2026
+ version: { type: "string", description: "A published version. Left out: the latest." }
598
2027
  },
599
- listNames() {
600
- return [...entries.keys()];
601
- }
2028
+ required: ["module"],
2029
+ additionalProperties: false
2030
+ }
2031
+ };
2032
+ var moduleToolSchemas = [
2033
+ VALIDATE,
2034
+ SEARCH,
2035
+ DESCRIBE2
2036
+ ];
2037
+ function said(run, trim) {
2038
+ const failure = run.failed?.failure;
2039
+ return {
2040
+ content: commandText(run, trim),
2041
+ isError: run.failed !== void 0,
2042
+ ...failure === void 0 ? {} : { failure }
602
2043
  };
603
2044
  }
2045
+ function moduleTool(schema, run) {
2046
+ return registrationOf(schema, run, (failure) => failure);
2047
+ }
2048
+ function text(value) {
2049
+ return typeof value === "string" ? value : void 0;
2050
+ }
2051
+ function moduleTools({ commands }) {
2052
+ const [validate, search, describe] = moduleToolSchemas;
2053
+ return [
2054
+ moduleTool(
2055
+ validate,
2056
+ async (_input, signal) => said(await runCommand(commands, "module validate", {}, signal), trimValidate)
2057
+ ),
2058
+ moduleTool(
2059
+ search,
2060
+ async (input, signal) => said(
2061
+ await runCommand(
2062
+ commands,
2063
+ "registry list",
2064
+ {
2065
+ axis: "module",
2066
+ query: text(input.query),
2067
+ system: text(input.system),
2068
+ category: text(input.category)
2069
+ },
2070
+ signal
2071
+ ),
2072
+ trimRegistryList
2073
+ )
2074
+ ),
2075
+ moduleTool(describe, async (input, signal) => {
2076
+ const module = text(input.module);
2077
+ if (module === void 0) throw new InvalidInput("`module` is the module as `author/name`");
2078
+ return said(
2079
+ await runCommand(
2080
+ commands,
2081
+ "registry describe",
2082
+ { artifact: `module/${module}`, version: text(input.version) },
2083
+ signal
2084
+ ),
2085
+ trimRegistryDescribe
2086
+ );
2087
+ })
2088
+ ];
2089
+ }
604
2090
  export {
605
- AgentController,
606
- ProactivityWatcher,
607
- advanceState,
608
- buildSystemPrompt,
609
- capRecentMessages,
610
- createTelemetry,
2091
+ DECISION_KINDS,
2092
+ NONE_CANDIDATE_ID,
2093
+ VALUE_PLACEHOLDER,
2094
+ canvasToolSchemas,
2095
+ canvasTools,
2096
+ changeOutcomes,
2097
+ compose,
611
2098
  createToolRegistry,
612
- initialRuleState,
613
- matchAll,
614
- matchErrorsAppeared,
615
- matchGenerateError
2099
+ moduleToolSchemas,
2100
+ moduleTools,
2101
+ partOf,
2102
+ renderCandidate,
2103
+ renderCanvas,
2104
+ renderRequest,
2105
+ sure,
2106
+ trainingRows
616
2107
  };
617
2108
  //# sourceMappingURL=index.mjs.map