@lace-cloud/chat-core 0.0.1-bootstrap.0 → 0.6.4-next.25705814731

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,764 @@
1
+ // src/exhaustive.ts
2
+ function assertNever(value) {
3
+ throw new Error(`Unhandled closed-enum branch: ${JSON.stringify(value)}`);
4
+ }
5
+
6
+ // src/history.ts
7
+ var DEFAULT_TURN_CAP = 50;
8
+ function capRecentMessages(messages, turnCap = DEFAULT_TURN_CAP) {
9
+ const limit = turnCap * 2;
10
+ if (messages.length <= limit) return messages;
11
+ return messages.slice(messages.length - limit);
12
+ }
13
+
14
+ // src/telemetry.ts
15
+ var MAX_SESSIONS = 100;
16
+ function createTelemetry(log) {
17
+ const sessionBuffer = [];
18
+ let sessionCounter = 0;
19
+ function recordSession(session) {
20
+ if (sessionBuffer.length >= MAX_SESSIONS) sessionBuffer.shift();
21
+ sessionBuffer.push(session);
22
+ }
23
+ return {
24
+ startSession(prompt, command) {
25
+ sessionCounter += 1;
26
+ const session = {
27
+ sessionId: `s${sessionCounter}`,
28
+ prompt,
29
+ command,
30
+ toolCalls: [],
31
+ rounds: 0,
32
+ startTime: Date.now()
33
+ };
34
+ recordSession(session);
35
+ log("");
36
+ log(`[${ts()}] \u2500\u2500 session ${session.sessionId} \u2500\u2500`);
37
+ log(` prompt: "${truncate(prompt, 120)}"`);
38
+ if (command) log(` command: /${command}`);
39
+ return session;
40
+ },
41
+ logToolInvocation(session, name, params, result, durationMs) {
42
+ const maxPreview = result.isError ? 500 : 200;
43
+ const preview = truncate(result.content, maxPreview);
44
+ session.toolCalls.push({
45
+ name,
46
+ params,
47
+ durationMs,
48
+ isError: result.isError ?? false,
49
+ resultPreview: preview
50
+ });
51
+ const status = result.isError ? "ERR" : "OK";
52
+ log(`[${ts()}] [${session.sessionId}] tool ${name} (${durationMs}ms) ${status}`);
53
+ log(` params: ${JSON.stringify(params)}`);
54
+ log(result.isError ? ` error: ${preview}` : ` result: ${preview}`);
55
+ },
56
+ endSession(session, maxToolRounds) {
57
+ session.endTime = Date.now();
58
+ const totalMs = session.endTime - session.startTime;
59
+ const errorCount = session.toolCalls.filter((t) => t.isError).length;
60
+ const toolNames = session.toolCalls.map((t) => t.name);
61
+ const toolCounts = {};
62
+ for (const name of toolNames) {
63
+ toolCounts[name] = (toolCounts[name] ?? 0) + 1;
64
+ }
65
+ log(`[${ts()}] [${session.sessionId}] session end (${totalMs}ms)`);
66
+ log(` rounds: ${session.rounds}`);
67
+ log(` tools: ${session.toolCalls.length} call(s), ${errorCount} error(s)`);
68
+ if (Object.keys(toolCounts).length > 0) {
69
+ const breakdown = Object.entries(toolCounts).map(([n, c]) => `${n}\xD7${c}`).join(", ");
70
+ log(` breakdown: ${breakdown}`);
71
+ }
72
+ if (maxToolRounds !== void 0 && session.rounds >= maxToolRounds) {
73
+ log(
74
+ ` \u26A0 session hit maxToolRounds (${maxToolRounds}) \u2014 possible stuck loop. Tool sequence: ${toolNames.join(" \u2192 ")}`
75
+ );
76
+ }
77
+ if (session.toolCalls.length === 0 && session.prompt.trim().length > 10) {
78
+ log(` \u26A0 unmatched intent: no tools called for "${truncate(session.prompt, 100)}"`);
79
+ }
80
+ }
81
+ };
82
+ }
83
+ function ts() {
84
+ return (/* @__PURE__ */ new Date()).toISOString();
85
+ }
86
+ function truncate(s, max) {
87
+ return s.length > max ? `${s.slice(0, max)}...` : s;
88
+ }
89
+
90
+ // src/agent-controller.ts
91
+ var DEFAULT_MAX_TOOL_ROUNDS = 25;
92
+ var DEFAULT_COMPLETED_TURN_CAP = 50;
93
+ var AgentController = class {
94
+ constructor(opts) {
95
+ this.opts = opts;
96
+ this.history = [];
97
+ this.completedTurns = [];
98
+ this.activeTurn = null;
99
+ this.transportSubscription = null;
100
+ this.telemetry = createTelemetry((msg) => opts.adapter.log(msg));
101
+ }
102
+ /** Load persisted history and start listening for webview messages. */
103
+ async init() {
104
+ try {
105
+ this.history = await this.opts.adapter.loadHistory(this.opts.historyKey) ?? [];
106
+ } catch (err) {
107
+ this.opts.adapter.log(`[Chat] history load failed, starting fresh: ${String(err)}`);
108
+ this.history = [];
109
+ }
110
+ this.transportSubscription = this.opts.transport.onMessage(
111
+ (msg) => this.handleWebviewMessage(msg)
112
+ );
113
+ }
114
+ /** Cancel any active turn and unsubscribe from the webview. */
115
+ dispose() {
116
+ this.activeTurn?.abort();
117
+ this.activeTurn = null;
118
+ this.transportSubscription?.dispose();
119
+ this.transportSubscription = null;
120
+ }
121
+ /** Drop in-memory and persisted history. */
122
+ async clearHistory() {
123
+ this.history = [];
124
+ this.completedTurns = [];
125
+ await this.opts.adapter.saveHistory(this.opts.historyKey, []);
126
+ this.opts.transport.postMessage({ type: "history-cleared" });
127
+ }
128
+ /** Push a context-summary banner into the chat UI. */
129
+ postContextSummary(summary) {
130
+ this.opts.transport.postMessage({ type: "context-summary", summary });
131
+ }
132
+ /** Forward a proactive suggestion from the watcher to the chat UI. */
133
+ postProactiveSuggestion(suggestion) {
134
+ this.opts.transport.postMessage({ type: "proactive-suggestion", suggestion });
135
+ }
136
+ /** Notify the chat UI that the engine is unavailable for this session. */
137
+ postEngineUnavailable() {
138
+ this.opts.transport.postMessage({ type: "engine-unavailable" });
139
+ }
140
+ async handleWebviewMessage(msg) {
141
+ switch (msg.type) {
142
+ case "webview-ready":
143
+ this.opts.transport.postMessage({ type: "history", turns: this.completedTurns });
144
+ break;
145
+ case "user-turn":
146
+ await this.runTurn(msg.text);
147
+ break;
148
+ case "cancel-turn":
149
+ this.activeTurn?.abort();
150
+ break;
151
+ case "accept-proactive-suggestion":
152
+ this.opts.adapter.log(`[Chat] proactive suggestion accepted: ${msg.id}`);
153
+ break;
154
+ default:
155
+ assertNever(msg);
156
+ }
157
+ }
158
+ async runTurn(userText) {
159
+ const model = await this.opts.adapter.selectModel();
160
+ if (!model) {
161
+ this.opts.transport.postMessage({ type: "no-model" });
162
+ return;
163
+ }
164
+ this.activeTurn = new AbortController();
165
+ const signal = this.activeTurn.signal;
166
+ const session = this.telemetry.startSession(userText);
167
+ const systemPrompt = this.opts.buildSystemPrompt(this.opts.getAvailableSystems());
168
+ const canvasView = this.opts.getCanvasView();
169
+ const canvasContext = canvasView ? `Canvas: ${canvasView.nodes.length} node(s), ${canvasView.errors.length} error(s).` : "Canvas: (state not yet loaded)";
170
+ const messages = [
171
+ { role: "user", content: [{ kind: "text", value: systemPrompt }] },
172
+ {
173
+ role: "assistant",
174
+ content: [
175
+ {
176
+ kind: "text",
177
+ value: "Understood. I am Lace, your Terraform infrastructure assistant."
178
+ }
179
+ ]
180
+ },
181
+ ...this.history,
182
+ { role: "user", content: [{ kind: "text", value: `[Canvas state]
183
+ ${canvasContext}` }] },
184
+ { role: "assistant", content: [{ kind: "text", value: "Got it." }] },
185
+ { role: "user", content: [{ kind: "text", value: userText }] }
186
+ ];
187
+ this.history.push({ role: "user", content: [{ kind: "text", value: userText }] });
188
+ const turnToolCalls = [];
189
+ let assistantAccumulated = "";
190
+ const messageId = `msg-${Date.now()}`;
191
+ const failSignatureCount = /* @__PURE__ */ new Map();
192
+ const tools = this.opts.toolRegistry.listSchemas();
193
+ const maxRounds = this.opts.maxToolRounds ?? DEFAULT_MAX_TOOL_ROUNDS;
194
+ try {
195
+ for (let round = 0; round < maxRounds; round++) {
196
+ if (signal.aborted) break;
197
+ session.rounds = round + 1;
198
+ const textParts = [];
199
+ const toolCalls = [];
200
+ try {
201
+ for await (const event of this.opts.adapter.sendRequest(model, messages, tools, signal)) {
202
+ if (signal.aborted) break;
203
+ if (event.type === "text") {
204
+ textParts.push(event.value);
205
+ assistantAccumulated += event.value;
206
+ this.opts.transport.postMessage({ type: "token", text: event.value });
207
+ } else if (event.type === "tool-call") {
208
+ toolCalls.push({
209
+ name: event.name,
210
+ callId: event.callId,
211
+ input: event.input
212
+ });
213
+ }
214
+ }
215
+ } catch (err) {
216
+ const msg = err instanceof Error ? err.message : String(err);
217
+ this.opts.adapter.log(`[Chat] sendRequest failed: ${msg}`);
218
+ const line = `
219
+ _Model request failed: ${msg}_`;
220
+ this.opts.transport.postMessage({ type: "token", text: line });
221
+ assistantAccumulated += line;
222
+ break;
223
+ }
224
+ if (toolCalls.length === 0) break;
225
+ const assistantContent = [
226
+ ...textParts.map((t) => ({ kind: "text", value: t })),
227
+ ...toolCalls.map(
228
+ (tc) => ({
229
+ kind: "tool-call",
230
+ callId: tc.callId,
231
+ name: tc.name,
232
+ input: tc.input
233
+ })
234
+ )
235
+ ];
236
+ messages.push({ role: "assistant", content: assistantContent });
237
+ this.history.push({ role: "assistant", content: assistantContent });
238
+ const toolResultParts = [];
239
+ let allToolsErrored = true;
240
+ for (const tc of toolCalls) {
241
+ if (signal.aborted) break;
242
+ this.opts.transport.postMessage({
243
+ type: "tool-call",
244
+ callId: tc.callId,
245
+ name: tc.name,
246
+ input: tc.input
247
+ });
248
+ const handler = this.opts.toolRegistry.getHandler(tc.name);
249
+ const startedAt = Date.now();
250
+ let result;
251
+ if (!handler) {
252
+ result = { content: `Unknown tool: ${tc.name}`, isError: true };
253
+ } else {
254
+ try {
255
+ result = await handler(tc.input);
256
+ } catch (err) {
257
+ result = {
258
+ content: `Tool error: ${err instanceof Error ? err.message : String(err)}`,
259
+ isError: true
260
+ };
261
+ }
262
+ }
263
+ const durationMs = Date.now() - startedAt;
264
+ this.telemetry.logToolInvocation(session, tc.name, tc.input, result, durationMs);
265
+ turnToolCalls.push({
266
+ name: tc.name,
267
+ input: tc.input,
268
+ resultContent: result.content,
269
+ isError: result.isError
270
+ });
271
+ if (!result.isError) {
272
+ allToolsErrored = false;
273
+ failSignatureCount.delete(signatureFor(tc));
274
+ } else {
275
+ const sig = signatureFor(tc);
276
+ failSignatureCount.set(sig, (failSignatureCount.get(sig) ?? 0) + 1);
277
+ }
278
+ this.opts.transport.postMessage({
279
+ type: "tool-result",
280
+ callId: tc.callId,
281
+ name: tc.name,
282
+ content: result.content,
283
+ isError: result.isError
284
+ });
285
+ toolResultParts.push({
286
+ kind: "tool-result",
287
+ callId: tc.callId,
288
+ content: [
289
+ {
290
+ kind: "text",
291
+ value: result.isError ? `Tool [${tc.name}] failed: ${result.content}` : result.content
292
+ }
293
+ ],
294
+ isError: result.isError
295
+ });
296
+ }
297
+ messages.push({ role: "user", content: toolResultParts });
298
+ this.history.push({ role: "user", content: toolResultParts });
299
+ if (allToolsErrored && toolCalls.length > 0) {
300
+ const errorDetails = toolResultParts.flatMap((p) => p.content.map((c) => c.value)).filter(Boolean);
301
+ const msg = `
302
+ _All tool calls failed:
303
+ ${errorDetails.map((e) => `- ${e}`).join("\n")}_`;
304
+ this.opts.transport.postMessage({ type: "token", text: msg });
305
+ assistantAccumulated += msg;
306
+ break;
307
+ }
308
+ const stuck = [...failSignatureCount.entries()].find(([, count]) => count >= 2);
309
+ if (stuck) {
310
+ const msg = `
311
+ _I'm stuck \u2014 required fields cannot be inferred. Please provide the missing values._`;
312
+ this.opts.transport.postMessage({ type: "token", text: msg });
313
+ assistantAccumulated += msg;
314
+ break;
315
+ }
316
+ if (round === maxRounds - 1) {
317
+ const msg = `
318
+ _Reached operation limit (${maxRounds} rounds). Ask me to continue if needed._`;
319
+ this.opts.transport.postMessage({ type: "token", text: msg });
320
+ assistantAccumulated += msg;
321
+ }
322
+ }
323
+ } finally {
324
+ this.telemetry.endSession(session, maxRounds);
325
+ this.activeTurn = null;
326
+ if (signal.aborted) {
327
+ this.opts.transport.postMessage({ type: "turn-cancelled" });
328
+ } else {
329
+ this.completedTurns.push({
330
+ messageId,
331
+ userText,
332
+ assistantText: assistantAccumulated,
333
+ toolCalls: turnToolCalls
334
+ });
335
+ const cap = this.opts.completedTurnCap ?? DEFAULT_COMPLETED_TURN_CAP;
336
+ if (this.completedTurns.length > cap) {
337
+ this.completedTurns = this.completedTurns.slice(-cap);
338
+ }
339
+ await this.opts.adapter.saveHistory(this.opts.historyKey, capRecentMessages(this.history));
340
+ this.opts.transport.postMessage({ type: "turn-complete", messageId });
341
+ }
342
+ }
343
+ }
344
+ };
345
+ function signatureFor(tc) {
346
+ return `${tc.name}:${JSON.stringify(tc.input)}`;
347
+ }
348
+
349
+ // src/proactivity/index.ts
350
+ import { parseModuleKey, projectCanvasView } from "@lace-cloud/proto";
351
+
352
+ // src/proactivity/rules.ts
353
+ function initialRuleState() {
354
+ return { prevErrorCount: 0, prevNodeIds: /* @__PURE__ */ new Set() };
355
+ }
356
+ function matchUnwiredRequiredInput(event, state) {
357
+ const view = event.state_updated?.view;
358
+ if (!view) return null;
359
+ const newNodes = view.nodes.filter((n) => !state.prevNodeIds.has(n.id));
360
+ if (newNodes.length === 0) return null;
361
+ const newNode = newNodes[0];
362
+ const unwiredRequiredInput = findUnwiredRequiredInput(newNode);
363
+ if (!unwiredRequiredInput) return null;
364
+ const candidate = findSiblingOutputMatch(view, newNode, unwiredRequiredInput);
365
+ if (!candidate) return null;
366
+ return {
367
+ id: `unwired-${newNode.id}-${unwiredRequiredInput.name}`,
368
+ text: `The new \`${newNode.id}\` has an unwired required input \`${unwiredRequiredInput.name}\`. Want me to wire it to \`${candidate.instanceId}.${candidate.outputName}\`?`
369
+ };
370
+ }
371
+ function findUnwiredRequiredInput(node) {
372
+ for (const pin of node.inputs) {
373
+ if (pin.required && !pin.wired) return pin;
374
+ }
375
+ return null;
376
+ }
377
+ function findSiblingOutputMatch(view, target, targetInput) {
378
+ const family = targetInput.type_family;
379
+ if (!family) return null;
380
+ for (const node of view.nodes) {
381
+ if (node.id === target.id) continue;
382
+ for (const output of node.outputs) {
383
+ if (output.type_family === family) {
384
+ return { instanceId: node.id, outputName: output.name };
385
+ }
386
+ }
387
+ }
388
+ return null;
389
+ }
390
+ function matchGenerateError(event) {
391
+ const err = event.generate_error;
392
+ if (!err || err.diagnostics.length === 0) return null;
393
+ const first = err.diagnostics[0];
394
+ const location = first.instance_id ? `\`${first.instance_id}\`${first.address ? `.\`${first.address}\`` : ""}` : "";
395
+ const locSuffix = location ? ` at ${location}` : "";
396
+ return {
397
+ id: `gen-error-${Date.now()}`,
398
+ text: `Generation failed: ${first.message}${locSuffix}. Want me to look at it?`
399
+ };
400
+ }
401
+ function matchErrorsAppeared(event, state) {
402
+ const view = event.state_updated?.view;
403
+ if (!view) return null;
404
+ const curr = view.errors.length;
405
+ if (state.prevErrorCount !== 0 || curr === 0) return null;
406
+ const first = view.errors[0];
407
+ const summary = first.message + (view.errors.length > 1 ? ` (+${view.errors.length - 1} more)` : "");
408
+ return {
409
+ id: `errors-appeared-${Date.now()}`,
410
+ text: `${curr} validation error${curr === 1 ? "" : "s"} appeared \u2014 ${summary}. Investigate?`
411
+ };
412
+ }
413
+ function matchAll(event, state) {
414
+ return matchUnwiredRequiredInput(event, state) ?? matchGenerateError(event) ?? matchErrorsAppeared(event, state);
415
+ }
416
+ function advanceState(event, state) {
417
+ const view = event.state_updated?.view;
418
+ if (!view) return state;
419
+ return {
420
+ prevErrorCount: view.errors.length,
421
+ prevNodeIds: new Set(view.nodes.map((n) => n.id))
422
+ };
423
+ }
424
+
425
+ // src/proactivity/index.ts
426
+ var RETRY_DELAY_MS = 1e3;
427
+ var CONFIG_KEY = "proactivity";
428
+ var CONFIG_ENABLED_VALUE = "on";
429
+ var ProactivityWatcher = class {
430
+ constructor(opts) {
431
+ this.opts = opts;
432
+ this.stream = null;
433
+ this.ruleState = initialRuleState();
434
+ this.retried = false;
435
+ this.stopped = false;
436
+ }
437
+ start() {
438
+ if (this.stopped) return;
439
+ this.stream = this.opts.transport.subscribeStream(this.opts.sessionId);
440
+ this.stream.on("data", (event) => this.handleEvent(event));
441
+ this.stream.on("end", () => {
442
+ this.opts.adapter.log("[Proactivity] stream ended");
443
+ this.stream = null;
444
+ });
445
+ this.stream.on("error", (err) => {
446
+ this.opts.adapter.log(`[Proactivity] stream error: ${err.message}`);
447
+ this.stream = null;
448
+ if (!this.retried && !this.stopped) {
449
+ this.retried = true;
450
+ setTimeout(() => {
451
+ if (!this.stopped) this.start();
452
+ }, RETRY_DELAY_MS);
453
+ }
454
+ });
455
+ }
456
+ stop() {
457
+ this.stopped = true;
458
+ this.stream?.cancel();
459
+ this.stream = null;
460
+ }
461
+ handleEvent(event) {
462
+ const converted = toEngineEventLike(event);
463
+ const enabled = this.opts.adapter.getConfig(CONFIG_KEY, CONFIG_ENABLED_VALUE) === CONFIG_ENABLED_VALUE;
464
+ if (enabled) {
465
+ const suggestion = matchAll(converted, this.ruleState);
466
+ if (suggestion) this.opts.onSuggestion(suggestion);
467
+ }
468
+ this.ruleState = advanceState(converted, this.ruleState);
469
+ }
470
+ };
471
+ function toEngineEventLike(event) {
472
+ const result = {};
473
+ if (event.state?.bundle) {
474
+ const { id: moduleName } = parseModuleKey(event.state.bundle.entry);
475
+ const view = projectCanvasView(event.state.bundle, event.state.layouts ?? {}, {
476
+ moduleName,
477
+ canUndo: event.state.can_undo,
478
+ canRedo: event.state.can_redo,
479
+ isDirty: event.state.is_dirty
480
+ });
481
+ result.state_updated = { view };
482
+ }
483
+ if (event.generate_progress) {
484
+ result.generate_progress = {
485
+ stage: event.generate_progress.stage,
486
+ message: event.generate_progress.message
487
+ };
488
+ }
489
+ if (event.generate_success) {
490
+ result.generate_success = {
491
+ files_written: event.generate_success.files_written,
492
+ files: event.generate_success.files
493
+ };
494
+ }
495
+ if (event.generate_error) {
496
+ result.generate_error = {
497
+ message: event.generate_error.message,
498
+ diagnostics: event.generate_error.diagnostics.map((d) => ({ message: d.message }))
499
+ };
500
+ }
501
+ return result;
502
+ }
503
+
504
+ // src/system-prompt.ts
505
+ function buildSystemPrompt(systems = ["aws", "azure", "google"]) {
506
+ const systemList = systems.join("/");
507
+ return PROMPT_TEMPLATE.replace("{{SYSTEMS}}", systemList);
508
+ }
509
+ 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.
510
+
511
+ ## Canvas State
512
+
513
+ 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.
514
+
515
+ ## When the Engine Is Not Running
516
+
517
+ Tell the user to start it with **Lace: Start Engine** from the Command Palette. Do not call any tools.
518
+
519
+ ## When No Canvas Is Open
520
+
521
+ Tell the user to open one with **Lace: Open Canvas** from the Command Palette. Do not call any write tools.
522
+
523
+ ## Core Concepts
524
+
525
+ **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.
526
+
527
+ **Input bindings** \u2014 each module input can be:
528
+ - **empty** \u2014 not set (must be filled before generating)
529
+ - **literal** \u2014 a hardcoded value: string, number, bool, object, or array
530
+ - **variable** \u2014 a \`var.NAME\` reference, configurable at deploy time
531
+ - **expression** \u2014 raw HCL: e.g., \`local.region\`, \`cidrsubnet(var.vpc_cidr, 8, 0)\`
532
+ - **wired** \u2014 connected from another instance's output (via lace_connect or lace_auto_connect)
533
+
534
+ ## Available Tools
535
+
536
+ **Read tools** (gather information first):
537
+ - lace_search_registry: Search the module registry by keyword, system ({{SYSTEMS}}), or category.
538
+ - lace_inspect_module: Get full input/output schema for a registry module (before adding).
539
+ - lace_describe_graph: Get the current canvas state \u2014 instances, connections, errors.
540
+ - lace_validate_graph: Run validation \u2014 returns auto-resolvable vs. user-required errors.
541
+ - lace_inspect_node: Get the live input bindings and outputs of a placed instance.
542
+ - lace_get_settings: Read terraform block, providers, locals, and environments.
543
+ - lace_workspace_context: Analyze project files \u2014 returns a structured ProjectProfile + raw content.
544
+
545
+ **Write tools** (modify the canvas):
546
+ - lace_add_module: Add a module to the canvas.
547
+ - lace_remove_module: Remove an instance.
548
+ - lace_connect: Wire a source output to a target input.
549
+ - lace_auto_connect: Best-effort wiring between two instances.
550
+ - lace_disconnect: Remove a wire from a specific input.
551
+ - lace_set_input: Set a literal value, variable reference, or HCL expression.
552
+ - lace_rename_instance: Rename an instance (cascades to all references).
553
+ - lace_set_variable: Add or update a canvas-level variable (var.NAME).
554
+ - lace_set_local: Add or update a local value (literal or expression).
555
+ - lace_set_environment: Set environment-specific variable overrides.
556
+ - lace_create_group: Group instances visually on the canvas.
557
+ - lace_ungroup: Remove a visual group (instances stay on canvas).
558
+ - lace_undo: Undo the last canvas change.
559
+ - lace_generate: Generate Terraform .tf files from the canvas.
560
+
561
+ ## Workflow Rules
562
+
563
+ 1. **Use the canvas snapshot** for instance IDs and error flags. Call lace_inspect_node for exact port names. Never guess port names.
564
+ 2. **Search before adding**: lace_search_registry first, then lace_add_module. One search per module.
565
+ 3. **Inspect before connecting**: lace_inspect_node on both source and target for exact output/input names.
566
+ 4. **Auto-connect for common patterns**: lace_auto_connect first, fall back to lace_connect.
567
+ 5. **Validate once at the end**: After all changes, call lace_validate_graph. Not after every step.
568
+ 6. **Act on confirmation**: When the user says "yes", "go ahead", "do it" \u2014 execute immediately without re-asking.
569
+ 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.
570
+ 8. **Respect version requests**: Pass the user's exact version to lace_add_module.
571
+ 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.
572
+
573
+ ## Starting a New Composition
574
+
575
+ 1. Call lace_workspace_context to analyze the project.
576
+ 2. Review the **ProjectProfile** (languages, frameworks, databases, cloud_hints). Ask 1-2 clarifying questions if needed:
577
+ - If cloud provider is unclear: "Which cloud provider are you targeting?"
578
+ - If project type is ambiguous: "Is this a web API, data pipeline, or static site?"
579
+ - If they have a Dockerfile but no cloud hints: "How do you want to deploy \u2014 containers, serverless, or VMs?"
580
+ 3. Based on answers + profile, suggest 2-3 module combinations. One sentence per suggestion.
581
+ 4. Ask: "Want me to set these up?" \u2014 then STOP.
582
+ 5. On confirmation, execute everything without re-asking.
583
+
584
+ **CRITICAL: If the user confirmed in a previous message, do not ask again. Proceed immediately.**
585
+
586
+ ## Understanding the Project
587
+
588
+ When lace_workspace_context returns a ProjectProfile:
589
+ - Match language + framework to infrastructure patterns (e.g., Express + Docker \u2192 ECS or Lambda)
590
+ - Check cloud_hints for provider selection
591
+ - Check existing_modules to avoid adding duplicates
592
+ - Use databases array to suggest managed database services (postgres \u2192 RDS, mongodb \u2192 DocumentDB)
593
+
594
+ ## Handling Validation Errors
595
+
596
+ When the user mentions errors, says "fix it", "what's wrong", or "check for issues":
597
+ 1. Call lace_validate_graph.
598
+ 2. The response classifies errors as **auto-resolvable** vs. **requires user input**.
599
+ 3. Fix all auto-resolvable errors (wire connections, set defaults) without asking.
600
+ 4. For user-required values: list them clearly and ask. Never guess.
601
+ 5. Summarize what you fixed and what you still need from the user.
602
+
603
+ ## Input Value Guidance
604
+
605
+ When setting inputs, use these heuristics for common types:
606
+ - **CIDR blocks**: Suggest 10.0.0.0/16 for VPC. For subnets, use cidrsubnet(var.vpc_cidr, 8, N).
607
+ - **Boolean flags**: Set sensible defaults (enable_dns_support=true, enable_dns_hostnames=true).
608
+ - **Regions**: Ask the user, or use cloud_hints from ProjectProfile.
609
+ - **Instance types**: Suggest cost-effective defaults (t3.medium, Standard_B2ms) but note the user can change them.
610
+ - **Names, IDs, ARNs, passwords, secrets**: NEVER guess. Always ask.
611
+
612
+ ## Using Locals and Environment Variables
613
+
614
+ - Call lace_get_settings to see existing locals and environments.
615
+ - Use lace_set_local to create reusable values (e.g., local.region, local.environment).
616
+ - Use lace_set_environment to define per-environment overrides (staging vs production).
617
+ - Reference locals in module inputs via expression: "local.NAME".
618
+
619
+ ## Canvas Organization
620
+
621
+ Groups are visual containers that organize related instances on the canvas. They don't affect Terraform generation \u2014 they're purely for readability.
622
+
623
+ **Proactive grouping:** As you build a composition, organize it into groups so the canvas stays readable. Group by logical function:
624
+ - Networking: VPCs, subnets, route tables, NAT gateways, security groups
625
+ - Compute: EC2 instances, ASGs, launch templates, load balancers
626
+ - Data: RDS, DynamoDB, S3, ElastiCache
627
+ - Identity: IAM roles, policies, instance profiles
628
+ - Monitoring: CloudWatch alarms, log groups, dashboards
629
+
630
+ **When to group:**
631
+ - After adding 3+ related modules in a batch, group them immediately.
632
+ - After the canvas exceeds ~8 instances, review and organize ungrouped nodes.
633
+ - 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.
634
+
635
+ **Naming:** Use short functional labels: "Network", "Compute", "Database", "Auth", "Monitoring". Not instance IDs or module names.
636
+
637
+ ## Error Recovery
638
+
639
+ - Tool returns "not found": call lace_describe_graph for current instance IDs.
640
+ - Module not in registry: try broader search terms or remove the system filter.
641
+ - Auto-connect finds no matches: it shows available ports \u2014 use lace_connect manually.
642
+ - Wrong change: call lace_undo immediately.
643
+
644
+ ## Conventions
645
+
646
+ - Instance IDs are Terraform identifiers (e.g., "vpc", "subnet_1"), auto-generated on add.
647
+ - Module names follow "system/name" (e.g., "aws/vpc", "azure/resource-group").
648
+ - Each input has one binding. Setting a new one replaces the previous.
649
+
650
+ ## Response Style
651
+
652
+ - Be concise \u2014 one or two sentences to confirm what was done.
653
+ - After changes, summarize the final state.
654
+ - Execute all steps before responding. Do not narrate each step.
655
+ - Only ask for clarification when genuinely ambiguous and not answerable from context or conversation history.
656
+ - **Never ask the same question twice.** If answered in a prior turn, act on it.
657
+ `;
658
+
659
+ // src/tool-registry.ts
660
+ function createToolRegistry() {
661
+ const entries = /* @__PURE__ */ new Map();
662
+ return {
663
+ register(schema, handler) {
664
+ entries.set(schema.name, { schema, handler });
665
+ },
666
+ getHandler(name) {
667
+ return entries.get(name)?.handler;
668
+ },
669
+ listSchemas() {
670
+ return [...entries.values()].map((e) => e.schema);
671
+ },
672
+ listNames() {
673
+ return [...entries.keys()];
674
+ }
675
+ };
676
+ }
677
+
678
+ // src/utils/canvas-summary.ts
679
+ function formatCanvasState(view, opts = {}) {
680
+ if (!view) {
681
+ return "No canvas is open. Tell the user to open one with **Lace: Open Canvas** from the Command Palette before making any canvas changes.";
682
+ }
683
+ if (view.nodes.length === 0) {
684
+ return "Canvas is open but empty \u2014 no modules added yet.";
685
+ }
686
+ if (opts.compact) return formatCompact(view);
687
+ return formatDetailed(view);
688
+ }
689
+ function formatCompact(view) {
690
+ const groupCount = view.groups.length ?? 0;
691
+ const groupSuffix = groupCount > 0 ? `, ${groupCount} group(s)` : "";
692
+ const parts = [
693
+ `Canvas snapshot: ${view.nodes.length} instance(s), ${view.edges.length} connection(s)${groupSuffix}.`
694
+ ];
695
+ if (groupCount > 0) {
696
+ const groupList = view.groups.map((g) => {
697
+ const collapsed = g.collapsed ? " (collapsed)" : "";
698
+ return `${g.label} [${g.node_ids.join(", ")}]${collapsed}`;
699
+ }).join(", ");
700
+ parts.push(`Groups: ${groupList}`);
701
+ }
702
+ const nodeList = view.nodes.map((n) => `${n.id} (${n.label})${n.has_errors ? " \u26A0" : ""}`).join(", ");
703
+ parts.push(`Instances: ${nodeList}`);
704
+ if (view.edges.length > 0) {
705
+ const edgeList = view.edges.map((e) => `${e.source}.${e.source_output}\u2192${e.target}.${e.target_input}`).join(", ");
706
+ parts.push(`Connections: ${edgeList}`);
707
+ }
708
+ if (view.errors.length > 0) {
709
+ parts.push(`Errors: ${view.errors.length} validation error(s) present.`);
710
+ }
711
+ return parts.join("\n");
712
+ }
713
+ function formatDetailed(view) {
714
+ const lines = [];
715
+ lines.push(`**Canvas: ${view.nodes.length} instance(s), ${view.edges.length} connection(s)**`);
716
+ if (view.groups.length > 0) {
717
+ lines.push("");
718
+ lines.push("### Groups");
719
+ for (const g of view.groups) {
720
+ const collapsed = g.collapsed ? " (collapsed)" : "";
721
+ lines.push(`- **${g.label}** \u2014 ${g.node_ids.join(", ")}${collapsed}`);
722
+ }
723
+ }
724
+ lines.push("");
725
+ lines.push("### Instances");
726
+ for (const node of view.nodes) {
727
+ const errFlag = node.has_errors ? " \u26A0 has errors" : "";
728
+ lines.push(`- **${node.id}** (${node.label})${errFlag}`);
729
+ }
730
+ if (view.edges.length > 0) {
731
+ lines.push("");
732
+ lines.push("### Connections");
733
+ for (const edge of view.edges) {
734
+ lines.push(
735
+ `- ${edge.source}.${edge.source_output} \u2192 ${edge.target}.${edge.target_input}`
736
+ );
737
+ }
738
+ }
739
+ if (view.errors.length > 0) {
740
+ lines.push("");
741
+ lines.push("### Errors");
742
+ for (const err of view.errors) {
743
+ const loc = [err.instance_id, err.input_name].filter(Boolean).join(".");
744
+ lines.push(`- ${loc ? `[${loc}] ` : ""}${err.message}`);
745
+ }
746
+ }
747
+ return lines.join("\n");
748
+ }
749
+ export {
750
+ AgentController,
751
+ ProactivityWatcher,
752
+ advanceState,
753
+ buildSystemPrompt,
754
+ capRecentMessages,
755
+ createTelemetry,
756
+ createToolRegistry,
757
+ formatCanvasState,
758
+ initialRuleState,
759
+ matchAll,
760
+ matchErrorsAppeared,
761
+ matchGenerateError,
762
+ matchUnwiredRequiredInput
763
+ };
764
+ //# sourceMappingURL=index.mjs.map