@lace-cloud/chat-core 0.17.0 → 0.19.0

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