@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/README.md +354 -59
- package/dist/index.cjs +1948 -574
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.mts +227 -248
- package/dist/index.d.ts +227 -248
- package/dist/index.mjs +1939 -564
- package/dist/index.mjs.map +1 -1
- package/package.json +9 -2
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/exhaustive.ts","../src/history.ts","../src/telemetry.ts","../src/agent-controller.ts","../src/proactivity/rules.ts","../src/proactivity/index.ts","../src/system-prompt.ts","../src/tool-registry.ts"],"sourcesContent":["/** Compile-time exhaustiveness guard. See apps/api/src/lib/helpers.ts. */\nexport function assertNever(value: never): never {\n throw new Error(`Unhandled closed-enum branch: ${JSON.stringify(value)}`);\n}\n","// History helpers.\n//\n// `ChatMessage[]` is JSON-safe by construction — every `Part`\n// variant is plain data. There is deliberately no codec here: the\n// adapter persists whatever core gives it and loads it back\n// unchanged. The single concern is keeping persisted history\n// bounded so it doesn't grow without end.\n\nimport type { ChatMessage } from './types';\n\nconst DEFAULT_TURN_CAP = 50;\n\n/**\n * Trim message history to the most recent `turnCap` turns. A turn\n * is one user message followed by one assistant message (plus any\n * interleaved tool traffic the assistant emits). Keeping the last\n * `turnCap` turns is approximated by keeping `turnCap * 2` messages\n * — exact turn boundaries aren't worth tracking for a bounded cap.\n */\nexport function capRecentMessages(\n messages: ChatMessage[],\n turnCap = DEFAULT_TURN_CAP,\n): ChatMessage[] {\n const limit = turnCap * 2;\n if (messages.length <= limit) return messages;\n return messages.slice(messages.length - limit);\n}\n","// Structured telemetry for a chat session.\n//\n// Pure TS: session state is a plain object, formatting is deterministic,\n// log output is routed through a caller-supplied `log(msg)` function\n// (typically `ChatHostAdapter.log`). Nothing here imports vscode or\n// requires a specific log sink — unit tests can pass a buffer-backed\n// function and assert on the emitted lines.\n\nexport type ToolInvocationRecord = {\n name: string;\n params: unknown;\n durationMs: number;\n isError: boolean;\n resultPreview: string;\n};\n\nexport type SessionMetadata = {\n sessionId: string;\n prompt: string;\n command?: string;\n toolCalls: ToolInvocationRecord[];\n rounds: number;\n startTime: number;\n endTime?: number;\n};\n\nexport type Telemetry = {\n startSession(prompt: string, command?: string): SessionMetadata;\n logToolInvocation(\n session: SessionMetadata,\n name: string,\n params: unknown,\n result: { content: string; isError?: boolean },\n durationMs: number,\n ): void;\n endSession(session: SessionMetadata, maxToolRounds?: number): void;\n};\n\nconst MAX_SESSIONS = 100;\n\nexport function createTelemetry(log: (message: string) => void): Telemetry {\n const sessionBuffer: SessionMetadata[] = [];\n let sessionCounter = 0;\n\n function recordSession(session: SessionMetadata): void {\n if (sessionBuffer.length >= MAX_SESSIONS) sessionBuffer.shift();\n sessionBuffer.push(session);\n }\n\n return {\n startSession(prompt, command) {\n sessionCounter += 1;\n const session: SessionMetadata = {\n sessionId: `s${sessionCounter}`,\n prompt,\n command,\n toolCalls: [],\n rounds: 0,\n startTime: Date.now(),\n };\n recordSession(session);\n\n log('');\n log(`[${ts()}] ── session ${session.sessionId} ──`);\n log(` prompt: \"${truncate(prompt, 120)}\"`);\n if (command) log(` command: /${command}`);\n return session;\n },\n\n logToolInvocation(session, name, params, result, durationMs) {\n const maxPreview = result.isError ? 500 : 200;\n const preview = truncate(result.content, maxPreview);\n session.toolCalls.push({\n name,\n params,\n durationMs,\n isError: result.isError ?? false,\n resultPreview: preview,\n });\n\n const status = result.isError ? 'ERR' : 'OK';\n log(`[${ts()}] [${session.sessionId}] tool ${name} (${durationMs}ms) ${status}`);\n log(` params: ${JSON.stringify(params)}`);\n log(result.isError ? ` error: ${preview}` : ` result: ${preview}`);\n },\n\n endSession(session, maxToolRounds) {\n session.endTime = Date.now();\n const totalMs = session.endTime - session.startTime;\n const errorCount = session.toolCalls.filter((t) => t.isError).length;\n const toolNames = session.toolCalls.map((t) => t.name);\n\n const toolCounts: Record<string, number> = {};\n for (const name of toolNames) {\n toolCounts[name] = (toolCounts[name] ?? 0) + 1;\n }\n\n log(`[${ts()}] [${session.sessionId}] session end (${totalMs}ms)`);\n log(` rounds: ${session.rounds}`);\n log(` tools: ${session.toolCalls.length} call(s), ${errorCount} error(s)`);\n if (Object.keys(toolCounts).length > 0) {\n const breakdown = Object.entries(toolCounts)\n .map(([n, c]) => `${n}×${c}`)\n .join(', ');\n log(` breakdown: ${breakdown}`);\n }\n\n if (maxToolRounds !== undefined && session.rounds >= maxToolRounds) {\n log(\n ` ⚠ session hit maxToolRounds (${maxToolRounds}) — possible stuck loop. Tool sequence: ${toolNames.join(' → ')}`,\n );\n }\n\n if (session.toolCalls.length === 0 && session.prompt.trim().length > 10) {\n log(` ⚠ unmatched intent: no tools called for \"${truncate(session.prompt, 100)}\"`);\n }\n },\n };\n}\n\nfunction ts(): string {\n return new Date().toISOString();\n}\n\nfunction truncate(s: string, max: number): string {\n return s.length > max ? `${s.slice(0, max)}...` : s;\n}\n","// Agentic loop, IDE-agnostic.\n//\n// Owns: message history, completed-turn log, in-flight cancellation,\n// the send→stream→tool-call→tool-result→repeat cycle, and the\n// stuck/limit/error handlers that prevent runaway loops. Everything\n// IDE-specific is reached through the injected `ChatHostAdapter`,\n// `WebviewTransport`, and `ToolRegistry` — each of which has a\n// single well-defined shape defined elsewhere in this package.\n//\n// `runTurn` is the only non-trivial method. It's intentionally long\n// and linear: the agentic loop's control flow (break on no-tools,\n// break on stuck, break on all-errored, continue otherwise) is\n// easiest to read top-to-bottom without fragmenting into helpers\n// that would be called from exactly one place. Accumulated state\n// lives in clearly-scoped locals; the only things mutated outside\n// the function scope are `this.history`, `this.completedTurns`, and\n// the transport.\n\nimport { assertNever } from './exhaustive';\nimport { capRecentMessages } from './history';\nimport type { ChatHostAdapter } from './host-adapter';\nimport type { CompletedTurn, ContextSummary, ProactiveSuggestion, WebviewToHost } from './protocol';\nimport { createTelemetry, type Telemetry } from './telemetry';\nimport type { ToolRegistry } from './tool-registry';\nimport type {\n ChatMessage,\n Disposable,\n Part,\n TextPart,\n ToolCallPart,\n ToolResultPart,\n} from './types';\nimport type { WebviewTransport } from './webview-transport';\n\nexport type AgentControllerOptions = {\n adapter: ChatHostAdapter;\n transport: WebviewTransport;\n toolRegistry: ToolRegistry;\n buildSystemPrompt: (availableSystems: string[]) => string;\n getAvailableSystems: () => string[];\n /** Host-supplied counts of the current canvas; null before a state has loaded. */\n getCanvasFacts: () => { nodeCount: number; diagnosticCount: number } | null;\n historyKey: string;\n maxToolRounds?: number;\n completedTurnCap?: number;\n};\n\nconst DEFAULT_MAX_TOOL_ROUNDS = 25;\nconst DEFAULT_COMPLETED_TURN_CAP = 50;\n\nexport class AgentController {\n private history: ChatMessage[] = [];\n private completedTurns: CompletedTurn[] = [];\n private activeTurn: AbortController | null = null;\n private transportSubscription: Disposable | null = null;\n private readonly telemetry: Telemetry;\n\n constructor(private readonly opts: AgentControllerOptions) {\n this.telemetry = createTelemetry((msg) => opts.adapter.log(msg));\n }\n\n /** Load persisted history and start listening for webview messages. */\n async init(): Promise<void> {\n try {\n this.history = (await this.opts.adapter.loadHistory(this.opts.historyKey)) ?? [];\n } catch (err) {\n this.opts.adapter.log(`[Chat] history load failed, starting fresh: ${String(err)}`);\n this.history = [];\n }\n this.transportSubscription = this.opts.transport.onMessage((msg) =>\n this.handleWebviewMessage(msg),\n );\n }\n\n /** Cancel any active turn and unsubscribe from the webview. */\n dispose(): void {\n this.activeTurn?.abort();\n this.activeTurn = null;\n this.transportSubscription?.dispose();\n this.transportSubscription = null;\n }\n\n /** Drop in-memory and persisted history. */\n async clearHistory(): Promise<void> {\n this.history = [];\n this.completedTurns = [];\n await this.opts.adapter.saveHistory(this.opts.historyKey, []);\n this.opts.transport.postMessage({ type: 'history-cleared' });\n }\n\n /** Push a context-summary banner into the chat UI. */\n postContextSummary(summary: ContextSummary): void {\n this.opts.transport.postMessage({ type: 'context-summary', summary });\n }\n\n /** Forward a proactive suggestion from the watcher to the chat UI. */\n postProactiveSuggestion(suggestion: ProactiveSuggestion): void {\n this.opts.transport.postMessage({ type: 'proactive-suggestion', suggestion });\n }\n\n /** Notify the chat UI that the engine is unavailable for this session. */\n postEngineUnavailable(): void {\n this.opts.transport.postMessage({ type: 'engine-unavailable' });\n }\n\n private async handleWebviewMessage(msg: WebviewToHost): Promise<void> {\n switch (msg.type) {\n case 'webview-ready':\n this.opts.transport.postMessage({ type: 'history', turns: this.completedTurns });\n break;\n case 'user-turn':\n await this.runTurn(msg.text);\n break;\n case 'cancel-turn':\n this.activeTurn?.abort();\n break;\n case 'accept-proactive-suggestion':\n this.opts.adapter.log(`[Chat] proactive suggestion accepted: ${msg.id}`);\n break;\n default:\n assertNever(msg);\n }\n }\n\n private async runTurn(userText: string): Promise<void> {\n const model = await this.opts.adapter.selectModel();\n if (!model) {\n this.opts.transport.postMessage({ type: 'no-model' });\n return;\n }\n\n this.activeTurn = new AbortController();\n const signal = this.activeTurn.signal;\n const session = this.telemetry.startSession(userText);\n\n const systemPrompt = this.opts.buildSystemPrompt(this.opts.getAvailableSystems());\n const canvasFacts = this.opts.getCanvasFacts();\n const canvasContext = canvasFacts\n ? `Canvas: ${canvasFacts.nodeCount} node(s), ${canvasFacts.diagnosticCount} diagnostic(s).`\n : 'Canvas: (state not yet loaded)';\n\n const messages: ChatMessage[] = [\n { role: 'user', content: [{ kind: 'text', value: systemPrompt }] },\n {\n role: 'assistant',\n content: [\n {\n kind: 'text',\n value: 'Understood. I am Lace, your Terraform infrastructure assistant.',\n },\n ],\n },\n ...this.history,\n { role: 'user', content: [{ kind: 'text', value: `[Canvas state]\\n${canvasContext}` }] },\n { role: 'assistant', content: [{ kind: 'text', value: 'Got it.' }] },\n { role: 'user', content: [{ kind: 'text', value: userText }] },\n ];\n\n // Persist the user message in history right away so a cancel\n // preserves it rather than losing the turn outright.\n this.history.push({ role: 'user', content: [{ kind: 'text', value: userText }] });\n\n const turnToolCalls: CompletedTurn['toolCalls'] = [];\n let assistantAccumulated = '';\n const messageId = `msg-${Date.now()}`;\n const failSignatureCount = new Map<string, number>();\n const tools = this.opts.toolRegistry.listSchemas();\n const maxRounds = this.opts.maxToolRounds ?? DEFAULT_MAX_TOOL_ROUNDS;\n\n try {\n for (let round = 0; round < maxRounds; round++) {\n if (signal.aborted) break;\n session.rounds = round + 1;\n\n const textParts: string[] = [];\n const toolCalls: Array<{ name: string; callId: string; input: Record<string, unknown> }> =\n [];\n\n try {\n for await (const event of this.opts.adapter.sendRequest(model, messages, tools, signal)) {\n if (signal.aborted) break;\n if (event.type === 'text') {\n textParts.push(event.value);\n assistantAccumulated += event.value;\n this.opts.transport.postMessage({ type: 'token', text: event.value });\n } else if (event.type === 'tool-call') {\n toolCalls.push({\n name: event.name,\n callId: event.callId,\n input: event.input as Record<string, unknown>,\n });\n }\n }\n } catch (err: unknown) {\n const msg = err instanceof Error ? err.message : String(err);\n this.opts.adapter.log(`[Chat] sendRequest failed: ${msg}`);\n const line = `\\n_Model request failed: ${msg}_`;\n this.opts.transport.postMessage({ type: 'token', text: line });\n assistantAccumulated += line;\n break;\n }\n\n if (toolCalls.length === 0) break;\n\n const assistantContent: Part[] = [\n ...textParts.map((t): TextPart => ({ kind: 'text', value: t })),\n ...toolCalls.map(\n (tc): ToolCallPart => ({\n kind: 'tool-call',\n callId: tc.callId,\n name: tc.name,\n input: tc.input,\n }),\n ),\n ];\n messages.push({ role: 'assistant', content: assistantContent });\n this.history.push({ role: 'assistant', content: assistantContent });\n\n const toolResultParts: ToolResultPart[] = [];\n let allToolsErrored = true;\n\n for (const tc of toolCalls) {\n if (signal.aborted) break;\n\n this.opts.transport.postMessage({\n type: 'tool-call',\n callId: tc.callId,\n name: tc.name,\n input: tc.input,\n });\n\n const handler = this.opts.toolRegistry.getHandler(tc.name);\n const startedAt = Date.now();\n let result: { content: string; isError?: boolean };\n if (!handler) {\n result = { content: `Unknown tool: ${tc.name}`, isError: true };\n } else {\n try {\n result = await handler(tc.input);\n } catch (err: unknown) {\n result = {\n content: `Tool error: ${err instanceof Error ? err.message : String(err)}`,\n isError: true,\n };\n }\n }\n const durationMs = Date.now() - startedAt;\n this.telemetry.logToolInvocation(session, tc.name, tc.input, result, durationMs);\n\n turnToolCalls.push({\n name: tc.name,\n input: tc.input,\n resultContent: result.content,\n isError: result.isError,\n });\n\n if (!result.isError) {\n allToolsErrored = false;\n failSignatureCount.delete(signatureFor(tc));\n } else {\n const sig = signatureFor(tc);\n failSignatureCount.set(sig, (failSignatureCount.get(sig) ?? 0) + 1);\n }\n\n this.opts.transport.postMessage({\n type: 'tool-result',\n callId: tc.callId,\n name: tc.name,\n content: result.content,\n isError: result.isError,\n });\n\n toolResultParts.push({\n kind: 'tool-result',\n callId: tc.callId,\n content: [\n {\n kind: 'text',\n value: result.isError\n ? `Tool [${tc.name}] failed: ${result.content}`\n : result.content,\n },\n ],\n isError: result.isError,\n });\n }\n\n messages.push({ role: 'user', content: toolResultParts });\n this.history.push({ role: 'user', content: toolResultParts });\n\n if (allToolsErrored && toolCalls.length > 0) {\n const errorDetails = toolResultParts\n .flatMap((p) => p.content.map((c) => c.value))\n .filter(Boolean);\n const msg = `\\n_All tool calls failed:\\n${errorDetails.map((e) => `- ${e}`).join('\\n')}_`;\n this.opts.transport.postMessage({ type: 'token', text: msg });\n assistantAccumulated += msg;\n break;\n }\n\n const stuck = [...failSignatureCount.entries()].find(([, count]) => count >= 2);\n if (stuck) {\n const msg = `\\n_I'm stuck — required fields cannot be inferred. Please provide the missing values._`;\n this.opts.transport.postMessage({ type: 'token', text: msg });\n assistantAccumulated += msg;\n break;\n }\n\n if (round === maxRounds - 1) {\n const msg = `\\n_Reached operation limit (${maxRounds} rounds). Ask me to continue if needed._`;\n this.opts.transport.postMessage({ type: 'token', text: msg });\n assistantAccumulated += msg;\n }\n }\n } finally {\n this.telemetry.endSession(session, maxRounds);\n this.activeTurn = null;\n\n if (signal.aborted) {\n this.opts.transport.postMessage({ type: 'turn-cancelled' });\n } else {\n this.completedTurns.push({\n messageId,\n userText,\n assistantText: assistantAccumulated,\n toolCalls: turnToolCalls,\n });\n const cap = this.opts.completedTurnCap ?? DEFAULT_COMPLETED_TURN_CAP;\n if (this.completedTurns.length > cap) {\n this.completedTurns = this.completedTurns.slice(-cap);\n }\n await this.opts.adapter.saveHistory(this.opts.historyKey, capRecentMessages(this.history));\n this.opts.transport.postMessage({ type: 'turn-complete', messageId });\n }\n }\n }\n}\n\nfunction signatureFor(tc: { name: string; input: unknown }): string {\n return `${tc.name}:${JSON.stringify(tc.input)}`;\n}\n","// Pure rule functions for between-turn proactivity suggestions.\n// No vscode imports, no side effects — easy to unit test.\n//\n// Each rule: (event, prevState) => Suggestion | null\n// Returning null means \"nothing to suggest for this event.\"\n\nimport type { ChatEngineEvent } from '@lace-cloud/host';\nimport type { ProactiveSuggestion } from '../protocol';\n\ntype EngineDiagnostic = NonNullable<ChatEngineEvent['diagnostics']>[number];\n\nexport type RuleState = {\n prevDiagnosticErrorCount: number;\n};\n\nexport function initialRuleState(): RuleState {\n return { prevDiagnosticErrorCount: 0 };\n}\n\nfunction errorsOf(diagnostics: EngineDiagnostic[]): EngineDiagnostic[] {\n return diagnostics.filter((d) => d.severity === 'error');\n}\n\n// ── Rule 1: generation failed with diagnostics ──\n\nexport function matchGenerateError(event: ChatEngineEvent): ProactiveSuggestion | null {\n const err = event.generate_error;\n if (!err || err.diagnostics.length === 0) return null;\n\n const first = err.diagnostics[0];\n const location = first.instance_id\n ? `\\`${first.instance_id}\\`${first.address ? `.\\`${first.address}\\`` : ''}`\n : '';\n const locSuffix = location ? ` at ${location}` : '';\n return {\n id: `gen-error-${Date.now()}`,\n text: `Generation failed: ${first.message}${locSuffix}. Want me to look at it?`,\n };\n}\n\n// ── Rule 2: validation errors appeared (crossed 0 → N) ──\n//\n// Every session state carries the validator's findings, so the error\n// count of consecutive states is the whole signal.\n\nexport function matchErrorsAppeared(\n event: ChatEngineEvent,\n state: RuleState,\n): ProactiveSuggestion | null {\n if (!event.diagnostics) return null;\n\n const errors = errorsOf(event.diagnostics);\n const curr = errors.length;\n if (state.prevDiagnosticErrorCount !== 0 || curr === 0) return null;\n\n const summary = errors[0].message + (curr > 1 ? ` (+${curr - 1} more)` : '');\n return {\n id: `errors-appeared-${Date.now()}`,\n text: `${curr} validation error${curr === 1 ? '' : 's'} appeared — ${summary}. Investigate?`,\n };\n}\n\n// ── Dispatch ──\n\nexport function matchAll(event: ChatEngineEvent, state: RuleState): ProactiveSuggestion | null {\n return matchGenerateError(event) ?? matchErrorsAppeared(event, state);\n}\n\nexport function advanceState(event: ChatEngineEvent, state: RuleState): RuleState {\n if (!event.diagnostics) return state;\n return { prevDiagnosticErrorCount: errorsOf(event.diagnostics).length };\n}\n","// Engine-stream proactivity watcher.\n//\n// Subscribes to the session's engine facts and applies pure rule\n// functions (see `./rules`) to propose between-turn suggestions. The\n// only configurable surface is whether suggestions are emitted; even\n// when disabled we still advance internal state so transitions\n// aren't lost if the setting flips back on mid-session.\n//\n// All IDE-specific concerns (reading config, writing to the chat\n// webview) are reached through the `ChatHostAdapter` and a user-\n// supplied callback — nothing in this file imports vscode or any\n// other editor API.\n\nimport type { ChatEngineEvent, FactsSource, FactsStream } from '@lace-cloud/host';\nimport type { ChatHostAdapter } from '../host-adapter';\nimport type { ProactiveSuggestion } from '../protocol';\nimport { advanceState, initialRuleState, matchAll, type RuleState } from './rules';\n\nconst RETRY_DELAY_MS = 1000;\nconst CONFIG_KEY = 'proactivity';\nconst CONFIG_ENABLED_VALUE = 'on';\n\nexport type ProactivityWatcherOptions = {\n facts: FactsSource;\n sessionId: string;\n adapter: Pick<ChatHostAdapter, 'getConfig' | 'log'>;\n onSuggestion: (suggestion: ProactiveSuggestion) => void;\n};\n\nexport class ProactivityWatcher {\n private stream: FactsStream | null = null;\n private ruleState: RuleState = initialRuleState();\n private retried = false;\n private stopped = false;\n\n constructor(private readonly opts: ProactivityWatcherOptions) {}\n\n start(): void {\n if (this.stopped) return;\n this.stream = this.opts.facts.subscribeFacts(this.opts.sessionId);\n\n this.stream.on('data', (event) => this.handleEvent(event));\n this.stream.on('end', () => {\n this.opts.adapter.log('[Proactivity] stream ended');\n this.stream = null;\n });\n this.stream.on('error', (err: Error) => {\n this.opts.adapter.log(`[Proactivity] stream error: ${err.message}`);\n this.stream = null;\n if (!this.retried && !this.stopped) {\n this.retried = true;\n setTimeout(() => {\n if (!this.stopped) this.start();\n }, RETRY_DELAY_MS);\n }\n });\n }\n\n stop(): void {\n this.stopped = true;\n this.stream?.cancel();\n this.stream = null;\n }\n\n private handleEvent(event: ChatEngineEvent): void {\n const enabled =\n this.opts.adapter.getConfig(CONFIG_KEY, CONFIG_ENABLED_VALUE) === CONFIG_ENABLED_VALUE;\n\n if (enabled) {\n const suggestion = matchAll(event, this.ruleState);\n if (suggestion) this.opts.onSuggestion(suggestion);\n }\n this.ruleState = advanceState(event, this.ruleState);\n }\n}\n\nexport * from './rules';\n","// src/chat/system-prompt.ts\n//\n// System prompt factory for the Lace chat participant.\n// Dynamic context (canvas state, engine status) is injected per-request in participant.ts.\n\nexport function buildSystemPrompt(systems: string[] = ['aws', 'azure', 'google']): string {\n const systemList = systems.join('/');\n return PROMPT_TEMPLATE.replace('{{SYSTEMS}}', systemList);\n}\n\nconst 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 — you drive the composition.\n\n## Canvas State\n\nBefore each response, you receive a fresh snapshot of the current canvas (instances, connections, errors). This is your ground truth. Use it for instance IDs — never guess. The snapshot reflects all changes, including manual edits the user made on the canvas between messages.\n\n## When the Engine Is Not Running\n\nTell the user to start it with **Lace: Start Engine** from the Command Palette. Do not call any tools.\n\n## When No Canvas Is Open\n\nTell the user to open one with **Lace: Open Canvas** from the Command Palette. Do not call any write tools.\n\n## Core Concepts\n\n**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.\n\n**Input bindings** — each module input can be:\n- **empty** — not set (must be filled before generating)\n- **literal** — a hardcoded value: string, number, bool, object, or array\n- **variable** — a \\`var.NAME\\` reference, configurable at deploy time\n- **expression** — raw HCL: e.g., \\`local.region\\`, \\`cidrsubnet(var.vpc_cidr, 8, 0)\\`\n- **wired** — connected from another instance's output (via lace_connect or lace_auto_connect)\n\n## Available Tools\n\n**Read tools** (gather information first):\n- lace_search_registry: Search the module registry by keyword, system ({{SYSTEMS}}), or category.\n- lace_inspect_module: Get full input/output schema for a registry module (before adding).\n- lace_describe_graph: Get the current canvas state — instances, connections, errors.\n- lace_validate_graph: Run validation — returns auto-resolvable vs. user-required errors.\n- lace_inspect_node: Get the live input bindings and outputs of a placed instance.\n- lace_get_settings: Read terraform block, providers, and locals.\n- lace_workspace_context: Analyze project files — returns a structured ProjectProfile + raw content.\n\n**Write tools** (modify the canvas):\n- lace_add_module: Add a module to the canvas.\n- lace_remove_module: Remove an instance.\n- lace_connect: Wire a source output to a target input.\n- lace_auto_connect: Best-effort wiring between two instances.\n- lace_disconnect: Remove a wire from a specific input.\n- lace_set_input: Set a literal value, variable reference, or HCL expression.\n- lace_rename_instance: Rename an instance (cascades to all references).\n- lace_set_variable: Add or update a canvas-level variable (var.NAME).\n- lace_set_local: Add or update a local value (literal or expression).\n- lace_create_group: Group instances visually on the canvas.\n- lace_ungroup: Remove a visual group (instances stay on canvas).\n- lace_undo: Undo the last canvas change.\n- lace_generate: Generate Terraform .tf files from the canvas.\n\n## Workflow Rules\n\n1. **Use the canvas snapshot** for instance IDs and error flags. Call lace_inspect_node for exact port names. Never guess port names.\n2. **Search before adding**: lace_search_registry first, then lace_add_module. One search per module.\n3. **Inspect before connecting**: lace_inspect_node on both source and target for exact output/input names.\n4. **Auto-connect for common patterns**: lace_auto_connect first, fall back to lace_connect.\n5. **Validate once at the end**: After all changes, call lace_validate_graph. Not after every step.\n6. **Act on confirmation**: When the user says \"yes\", \"go ahead\", \"do it\" — execute immediately without re-asking.\n7. **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.\n8. **Respect version requests**: Pass the user's exact version to lace_add_module.\n9. **Organize as you go**: After adding a batch of related modules, group them with lace_create_group. Keep the canvas readable without being asked.\n\n## Starting a New Composition\n\n1. Call lace_workspace_context to analyze the project.\n2. Review the **ProjectProfile** (languages, frameworks, databases, cloud_hints). Ask 1-2 clarifying questions if needed:\n - If cloud provider is unclear: \"Which cloud provider are you targeting?\"\n - If project type is ambiguous: \"Is this a web API, data pipeline, or static site?\"\n - If they have a Dockerfile but no cloud hints: \"How do you want to deploy — containers, serverless, or VMs?\"\n3. Based on answers + profile, suggest 2-3 module combinations. One sentence per suggestion.\n4. Ask: \"Want me to set these up?\" — then STOP.\n5. On confirmation, execute everything without re-asking.\n\n**CRITICAL: If the user confirmed in a previous message, do not ask again. Proceed immediately.**\n\n## Understanding the Project\n\nWhen lace_workspace_context returns a ProjectProfile:\n- Match language + framework to infrastructure patterns (e.g., Express + Docker → ECS or Lambda)\n- Check cloud_hints for provider selection\n- Check existing_modules to avoid adding duplicates\n- Use databases array to suggest managed database services (postgres → RDS, mongodb → DocumentDB)\n\n## Handling Validation Errors\n\nWhen the user mentions errors, says \"fix it\", \"what's wrong\", or \"check for issues\":\n1. Call lace_validate_graph.\n2. The response classifies errors as **auto-resolvable** vs. **requires user input**.\n3. Fix all auto-resolvable errors (wire connections, set defaults) without asking.\n4. For user-required values: list them clearly and ask. Never guess.\n5. Summarize what you fixed and what you still need from the user.\n\n## Input Value Guidance\n\nWhen setting inputs, use these heuristics for common types:\n- **CIDR blocks**: Suggest 10.0.0.0/16 for VPC. For subnets, use cidrsubnet(var.vpc_cidr, 8, N).\n- **Boolean flags**: Set sensible defaults (enable_dns_support=true, enable_dns_hostnames=true).\n- **Regions**: Ask the user, or use cloud_hints from ProjectProfile.\n- **Instance types**: Suggest cost-effective defaults (t3.medium, Standard_B2ms) but note the user can change them.\n- **Names, IDs, ARNs, passwords, secrets**: NEVER guess. Always ask.\n\n## Using Locals and Per-Environment Values\n\n- Call lace_get_settings to see existing locals.\n- Use lace_set_local to create reusable values (e.g., local.region).\n- Reference locals in module inputs via expression: \"local.NAME\".\n- Per-environment values (staging vs production) are not part of the canvas — 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.\n\n## Canvas Organization\n\nGroups are visual containers that organize related instances on the canvas. They don't affect Terraform generation — they're purely for readability.\n\n**Proactive grouping:** As you build a composition, organize it into groups so the canvas stays readable. Group by logical function:\n- Networking: VPCs, subnets, route tables, NAT gateways, security groups\n- Compute: EC2 instances, ASGs, launch templates, load balancers\n- Data: RDS, DynamoDB, S3, ElastiCache\n- Identity: IAM roles, policies, instance profiles\n- Monitoring: CloudWatch alarms, log groups, dashboards\n\n**When to group:**\n- After adding 3+ related modules in a batch, group them immediately.\n- After the canvas exceeds ~8 instances, review and organize ungrouped nodes.\n- 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.\n\n**Naming:** Use short functional labels: \"Network\", \"Compute\", \"Database\", \"Auth\", \"Monitoring\". Not instance IDs or module names.\n\n## Error Recovery\n\n- Tool returns \"not found\": call lace_describe_graph for current instance IDs.\n- Module not in registry: try broader search terms or remove the system filter.\n- Auto-connect finds no matches: it shows available ports — use lace_connect manually.\n- Wrong change: call lace_undo immediately.\n\n## Conventions\n\n- Instance IDs are Terraform identifiers (e.g., \"vpc\", \"subnet_1\"), auto-generated on add.\n- Module names follow \"system/name\" (e.g., \"aws/vpc\", \"azure/resource-group\").\n- Each input has one binding. Setting a new one replaces the previous.\n\n## Response Style\n\n- Be concise — one or two sentences to confirm what was done.\n- After changes, summarize the final state.\n- Execute all steps before responding. Do not narrate each step.\n- Only ask for clarification when genuinely ambiguous and not answerable from context or conversation history.\n- **Never ask the same question twice.** If answered in a prior turn, act on it.\n`;\n","// Registry of tool schemas + handlers.\n//\n// Handlers are pure async functions: input object → ToolResult.\n// Schemas are plain data. The registry itself is a tiny in-memory\n// Map with no IDE coupling — every caller (VS Code adapter,\n// JetBrains adapter, unit tests) constructs one and registers the\n// tools their environment provides.\n//\n// Instance-per-session rather than a module singleton: a global\n// registry would leak tool handlers between adapters in any future\n// in-process multi-host scenario (e.g. testing), and buys nothing\n// over explicit construction.\n\nimport type { ToolResult, ToolSchema } from './types';\n\nexport type ToolHandler = (input: Record<string, unknown>) => Promise<ToolResult>;\n\nexport type ToolRegistration = {\n schema: ToolSchema;\n handler: ToolHandler;\n};\n\nexport interface ToolRegistry {\n register(schema: ToolSchema, handler: ToolHandler): void;\n getHandler(name: string): ToolHandler | undefined;\n listSchemas(): ToolSchema[];\n listNames(): string[];\n}\n\nexport function createToolRegistry(): ToolRegistry {\n const entries = new Map<string, ToolRegistration>();\n\n return {\n register(schema, handler) {\n entries.set(schema.name, { schema, handler });\n },\n\n getHandler(name) {\n return entries.get(name)?.handler;\n },\n\n listSchemas() {\n return [...entries.values()].map((e) => e.schema);\n },\n\n listNames() {\n return [...entries.keys()];\n },\n };\n}\n"],"mappings":";AACO,SAAS,YAAY,OAAqB;AAC/C,QAAM,IAAI,MAAM,iCAAiC,KAAK,UAAU,KAAK,CAAC,EAAE;AAC1E;;;ACOA,IAAM,mBAAmB;AASlB,SAAS,kBACd,UACA,UAAU,kBACK;AACf,QAAM,QAAQ,UAAU;AACxB,MAAI,SAAS,UAAU,MAAO,QAAO;AACrC,SAAO,SAAS,MAAM,SAAS,SAAS,KAAK;AAC/C;;;ACYA,IAAM,eAAe;AAEd,SAAS,gBAAgB,KAA2C;AACzE,QAAM,gBAAmC,CAAC;AAC1C,MAAI,iBAAiB;AAErB,WAAS,cAAc,SAAgC;AACrD,QAAI,cAAc,UAAU,aAAc,eAAc,MAAM;AAC9D,kBAAc,KAAK,OAAO;AAAA,EAC5B;AAEA,SAAO;AAAA,IACL,aAAa,QAAQ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AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACmBjB,SAAS,qBAAmC;AACjD,QAAM,UAAU,oBAAI,IAA8B;AAElD,SAAO;AAAA,IACL,SAAS,QAAQ,SAAS;AACxB,cAAQ,IAAI,OAAO,MAAM,EAAE,QAAQ,QAAQ,CAAC;AAAA,IAC9C;AAAA,IAEA,WAAW,MAAM;AACf,aAAO,QAAQ,IAAI,IAAI,GAAG;AAAA,IAC5B;AAAA,IAEA,cAAc;AACZ,aAAO,CAAC,GAAG,QAAQ,OAAO,CAAC,EAAE,IAAI,CAAC,MAAM,EAAE,MAAM;AAAA,IAClD;AAAA,IAEA,YAAY;AACV,aAAO,CAAC,GAAG,QAAQ,KAAK,CAAC;AAAA,IAC3B;AAAA,EACF;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/contract/tool-registry.ts","../src/questions/bounds.ts","../src/questions/types.ts","../src/questions/candidate.ts","../src/questions/reading.ts","../src/questions/render.ts","../src/examples/rows.ts","../src/ranking/client.ts","../src/hybrid/compose.ts","../src/surfaces/canvas/canvas-tools.ts","../src/surfaces/canvas/change.ts","../src/surfaces/canvas/commands.ts","../src/surfaces/canvas/enumerate.ts","../src/surfaces/canvas/registration.ts","../src/surfaces/canvas/outcome.ts","../src/surfaces/canvas/ports.ts","../src/surfaces/canvas/render.ts","../src/surfaces/canvas/resolve.ts","../src/surfaces/canvas/module-tools.ts"],"sourcesContent":["// Registry of tool schemas + handlers.\n//\n// Handlers are pure async functions: input object → ToolResult.\n// Schemas are plain data. The registry itself is a tiny in-memory\n// Map with no IDE coupling — every caller (VS Code adapter,\n// JetBrains adapter, unit tests) constructs one and registers the\n// tools their environment provides.\n//\n// Instance-per-session rather than a module singleton: a global\n// registry would leak tool handlers between adapters in any future\n// in-process multi-host scenario (e.g. testing), and buys nothing\n// over explicit construction.\n\nimport type { ToolResult, ToolSchema } from './types';\n\n// A handler answers with a `ToolResult`, or with one that carries more: a\n// tool whose result holds data for its host beside the text its model reads\n// states that result as `R`, and a host that holds the registration reads it\n// typed.\nexport type ToolHandler<R extends ToolResult = ToolResult> = (\n input: Record<string, unknown>,\n) => Promise<R>;\n\nexport type ToolRegistration<R extends ToolResult = ToolResult> = {\n schema: ToolSchema;\n handler: ToolHandler<R>;\n};\n\nexport interface ToolRegistry {\n register(schema: ToolSchema, handler: ToolHandler): void;\n getHandler(name: string): ToolHandler | undefined;\n listSchemas(): ToolSchema[];\n listNames(): string[];\n}\n\nexport function createToolRegistry(): ToolRegistry {\n const entries = new Map<string, ToolRegistration>();\n\n return {\n register(schema, handler) {\n entries.set(schema.name, { schema, handler });\n },\n\n getHandler(name) {\n return entries.get(name)?.handler;\n },\n\n listSchemas() {\n return [...entries.values()].map((e) => e.schema);\n },\n\n listNames() {\n return [...entries.keys()];\n },\n };\n}\n","// The bounds of what one rank call carries, each at most the ranking route's\n// own (the API's bounds parity test holds each of these at most the route's,\n// itself within the pod's). A question a capture records is held to them\n// too, so the rows rendered from it are rows the trainer reads.\n\n// The most candidates one rank call carries (the route's `CANDIDATES_MAX`).\nexport const RANK_CANDIDATES_MAX = 256;\n\n// The most characters of a rendered request and the statement appended to\n// it together (the route's `REQUEST_MAX_CHARS`).\nexport const RANK_REQUEST_MAX_CHARS = 4000;\n\n// The most characters of one candidate's prose (the route's\n// `CANDIDATE_TEXT_MAX_CHARS`).\nexport const RANK_CANDIDATE_TEXT_MAX_CHARS = 2000;\n","// The closed questions: the kind of decision a change asks, the candidates\n// it picks among, and the one that means none of them. Nothing here knows a\n// canvas, a network or a model.\n\n// The kinds of decision the hybrid makes inside the canvas tools. Each is a\n// closed set the tools enumerate from the session's IR and the registry: the\n// operation a change is, the instance it names, the input of an instance,\n// the registry module, the output → input pair a connect wires between two\n// instances, and whether an entry is one change or several. A threshold is\n// fitted per kind, so the kind is part of a candidate and the key of the\n// head's threshold set. This list is the one list: the API's\n// `DECISION_KINDS` and the ranking service's `kinds.py` restate it, and a\n// parity test beside each holds the copy to it.\nexport type DecisionKind = 'operation' | 'instance' | 'input' | 'module' | 'connection' | 'steps';\n\n// The kinds as a list, in the order a change asks them.\nexport const DECISION_KINDS: readonly DecisionKind[] = [\n 'operation',\n 'instance',\n 'input',\n 'module',\n 'connection',\n 'steps',\n];\n\n// The candidate every ranked set but a `steps` one carries last: none of the\n// others. It is ranked like any candidate and never applied; the pick is the\n// best of the others. No Terraform name, registry `author/name` or pair id\n// holds a parenthesis, so it is no real candidate's id. The API's\n// `NONE_CANDIDATE_ID` and the ranking service's `kinds.py` restate it, and a\n// parity test beside each holds the copy to it.\nexport const NONE_CANDIDATE_ID = '(none)';\n\n// One member of the closed set a decision picks from: its id, the prose the\n// ranking scores against the request, and the decision it belongs to.\nexport type Candidate = {\n readonly id: string;\n readonly kind: DecisionKind;\n readonly text: string;\n};\n","// The one candidate renderer. An option of a decision holds its facts (its\n// id, its kind, and the instance, input, output, module or pair it names,\n// as the canvas and the registry gave them), and `renderCandidate`, a pure\n// function of those facts, renders them to the prose the ranking scores.\n// The tools render every candidate a rank call receives through it at run\n// time. The API stores a call's candidates as they were sent (`{id, kind,\n// text}`) and a row carries them as captured, so a head trains on the words\n// the tools sent when the question was asked: a change to the wording\n// reaches the turns asked after it, never one asked before.\n//\n// The prose is held to the text bound of one rank call, and the same facts\n// are always cut the same way: names first. Prose is shortened before any\n// name is dropped, and a name is dropped whole, never cut.\nimport { RANK_CANDIDATE_TEXT_MAX_CHARS } from './bounds';\nimport { type Candidate, type DecisionKind, NONE_CANDIDATE_ID } from './types';\n\n// A wire's end as a request names it: an instance's canvas path and the\n// port's name.\nexport function pinRef(instance: string, pin: string): string {\n return `${instance}.${pin}`;\n}\n\n// The id of the connection candidate that wires `from` into `to`.\nexport function connectionId(from: string, to: string): string {\n return `${from} → ${to}`;\n}\n\n// What the operations are, in the words the ranking scores them by, keyed\n// by the operation's id.\nexport const OPERATION_TEXT: Readonly<Record<string, string>> = {\n place: 'place: add a registry module to the canvas as a new instance',\n connect: 'connect: wire an output of one instance into an input of another',\n disconnect: \"disconnect: remove the wire into an instance's input\",\n set: 'set: give an input of an instance a literal value',\n 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\",\n clear:\n 'clear: unset an input of an instance, removing the value, variable or expression it holds',\n rename: 'rename: give an instance a new name',\n delete: 'delete: remove an instance from the canvas',\n ungroup: 'ungroup: dissolve a group, moving the instances inside it up beside it',\n};\n\n// Whether an entry is one change or several, in the words the ranking\n// scores it by, keyed by the reading's id.\nexport const STEPS_TEXT: Readonly<Record<string, string>> = {\n one: 'one change: the request asks for a single change to the canvas',\n several: 'several changes: the request asks for more than one change to the canvas',\n};\n\n// What `(none)` means in each kind of decision but `steps`, in the words the\n// ranking scores it by. `steps` has none: whether an entry is one change or\n// several is a two-way question, and an entry that asks for no change is\n// the operation's `(none)`.\nconst NONE_TEXT: Readonly<Record<Exclude<DecisionKind, 'steps'>, string>> = {\n operation: 'asks for no change these operations make',\n instance: 'means no instance on this canvas',\n input: 'means no input of this instance',\n module: 'means no module of this registry listing',\n connection: 'means no wire between these two instances',\n};\n\n// The `(none)` candidate of a kind of decision. It has no facts: its prose is\n// the kind's alone.\nexport function noneCandidate(kind: Exclude<DecisionKind, 'steps'>): Candidate {\n return { id: NONE_CANDIDATE_ID, kind, text: `none of these: the request ${NONE_TEXT[kind]}` };\n}\n\n// The candidates one rank call carries for a question of `kind`: its own,\n// then `(none)` last in every kind but `steps`. A training row carries the\n// same set, so what is trained is what is served.\nexport function rankCandidates(kind: DecisionKind, candidates: readonly Candidate[]): Candidate[] {\n return kind === 'steps' ? [...candidates] : [...candidates, noneCandidate(kind)];\n}\n\n// The role an instance plays in the question that offers it: the instance a\n// change addresses, the one a wire starts at, or the one it ends at. A\n// target's inputs are the ones a wire can end at: those no wire feeds.\nexport type InstanceRole = 'instance' | 'source' | 'target';\n\n// Whether an input holds anything, never what it holds.\nexport type InputState = 'not set' | 'set' | 'wired';\n\n// An instance's pin as its module declares it: its name and, where the\n// module says, what it is.\nexport type PinFacts = { readonly name: string; readonly description?: string };\n\n// One candidate as a capture stores it: its id, its kind, and the facts its\n// prose is written from. None of them is a value: an input says whether it\n// is set, never what to.\nexport type CandidateFacts =\n | { readonly id: string; readonly kind: 'operation' }\n | { readonly id: string; readonly kind: 'steps' }\n | {\n readonly id: string;\n readonly kind: 'instance';\n readonly role: InstanceRole;\n readonly module: string;\n readonly inputs: readonly PinFacts[];\n readonly outputs: readonly PinFacts[];\n }\n | {\n readonly id: string;\n readonly kind: 'input';\n readonly instance: string;\n readonly module: string;\n readonly type: string;\n readonly required: boolean;\n readonly state: InputState;\n readonly description?: string;\n }\n | {\n readonly id: string;\n readonly kind: 'module';\n readonly displayName: string;\n readonly description: string;\n readonly system: string;\n readonly categories: readonly string[];\n }\n | {\n readonly id: string;\n readonly kind: 'connection';\n readonly source: string;\n readonly output: string;\n readonly target: string;\n readonly input: string;\n readonly score?: number;\n };\n\n// The mark that stands where a text was cut.\nconst CUT_MARK = '…';\n\n// `text` cut to at most `limit` characters after its last whole word that\n// fits, the cut marked; `text` itself when it fits. A text whose first word\n// does not fit is cut to nothing.\nexport function shortened(text: string, limit: number): string {\n if (text.length <= limit) return text;\n const room = text.slice(0, Math.max(limit - CUT_MARK.length + 1, 0));\n const end = room.search(/\\s+\\S*$/);\n const kept = end === -1 ? '' : room.slice(0, end).trimEnd();\n return kept === '' ? '' : `${kept}${CUT_MARK}`;\n}\n\n// How far a candidate's prose is cut: each piece of what the module or the\n// registry says a thing is (a pin's, an input's or a module's description,\n// an input's type) to at most `prose` characters, and each list of names\n// to its first `names`.\ntype Cut = { readonly prose: number; readonly names: number };\n\nconst WHOLE: Cut = { prose: Number.POSITIVE_INFINITY, names: Number.POSITIVE_INFINITY };\n\n// A piece of prose as `cut` leaves it; none when nothing of it is left.\nfunction prose(text: string, cut: Cut): string | undefined {\n const kept = shortened(text, cut.prose);\n return kept === '' && text !== '' ? undefined : kept;\n}\n\n// The first `cut.names` items, each rendered by `render`, and how many more\n// there are.\nfunction listed<T>(items: readonly T[], cut: Cut, render: (item: T) => string): string {\n const kept = items.slice(0, cut.names).map(render);\n const more = items.length - kept.length;\n return [...kept, ...(more > 0 ? [`and ${more} more`] : [])].join(', ');\n}\n\nfunction worded(table: Readonly<Record<string, string>>, what: string, id: string): string {\n const text = table[id];\n if (text === undefined) throw new Error(`no ${what} is named ${id}`);\n return text;\n}\n\nconst about = (instance: string, module: string): string =>\n `instance ${instance} of module ${module}`;\n\ntype InstanceFacts = Extract<CandidateFacts, { readonly kind: 'instance' }>;\n\nconst names = (pins: readonly PinFacts[], cut: Cut): string => listed(pins, cut, (pin) => pin.name);\n\n// Pins with what the module says each is, where it says.\nconst described = (pins: readonly PinFacts[], cut: Cut): string =>\n listed(pins, cut, (pin) => {\n const description = pin.description === undefined ? undefined : prose(pin.description, cut);\n return description === undefined ? pin.name : `${pin.name} (${description})`;\n });\n\nconst INSTANCE_TEXT: Readonly<Record<InstanceRole, (facts: InstanceFacts, cut: Cut) => string>> = {\n instance: (f, cut) =>\n `${about(f.id, f.module)}; inputs: ${described(f.inputs, cut)}; outputs: ${described(f.outputs, cut)}`,\n source: (f, cut) =>\n `the wire starts at an output of ${about(f.id, f.module)}; its outputs: ${names(f.outputs, cut)}`,\n target: (f, cut) =>\n `the wire ends at an input of ${about(f.id, f.module)}; its inputs no wire feeds: ${names(f.inputs, cut)}`,\n};\n\nfunction textOf(facts: CandidateFacts, cut: Cut): string {\n switch (facts.kind) {\n case 'operation':\n return worded(OPERATION_TEXT, 'operation', facts.id);\n case 'steps':\n return worded(STEPS_TEXT, 'reading of the steps', facts.id);\n case 'instance':\n return INSTANCE_TEXT[facts.role](facts, cut);\n case 'input': {\n const type = prose(facts.type, cut);\n return [\n `input ${facts.id} of ${about(facts.instance, facts.module)}`,\n type === undefined ? undefined : `type ${type}`,\n facts.required ? 'required' : 'optional',\n facts.state,\n facts.description === undefined ? undefined : prose(facts.description, cut),\n ]\n .filter((part) => part !== undefined)\n .join('; ');\n }\n case 'module':\n return `registry module ${facts.id} (${facts.displayName}): ${prose(facts.description, cut) ?? ''}; system ${facts.system}; categories: ${listed(facts.categories, cut, (category) => category)}`;\n case 'connection': {\n const scored =\n facts.score === undefined\n ? \"the engine's matcher gives this pair no score\"\n : `the engine's matcher scores this pair ${facts.score}`;\n return `wire output ${pinRef(facts.source, facts.output)} into input ${pinRef(facts.target, facts.input)}; ${scored}`;\n }\n }\n}\n\n// The largest whole number up to `most` that `fits`, when `fits` holds of\n// 0; none when it does not.\nfunction largest(most: number, fits: (n: number) => boolean): number | undefined {\n if (!fits(0)) return undefined;\n let [low, high] = [0, most];\n while (low < high) {\n const middle = Math.ceil((low + high) / 2);\n if (fits(middle)) low = middle;\n else high = middle - 1;\n }\n return low;\n}\n\n// A candidate's prose within the text bound: whole when it fits; else with\n// its prose cut as little as fits; else, with no prose, its lists of names\n// cut to as many as fit; else the names-only prose cut at a word.\nfunction fitted(facts: CandidateFacts): string {\n const most = RANK_CANDIDATE_TEXT_MAX_CHARS;\n const fits = (cut: Cut) => textOf(facts, cut).length <= most;\n if (fits(WHOLE)) return textOf(facts, WHOLE);\n const proseCut = largest(most, (n) => fits({ prose: n, names: WHOLE.names }));\n if (proseCut !== undefined) return textOf(facts, { prose: proseCut, names: WHOLE.names });\n const namesCut = largest(most, (n) => fits({ prose: 0, names: n }));\n if (namesCut !== undefined) return textOf(facts, { prose: 0, names: namesCut });\n return shortened(textOf(facts, { prose: 0, names: 0 }), most);\n}\n\n// A candidate as the ranking reads it: its id and kind, and its prose\n// written from its facts within the text bound.\nexport function renderCandidate(facts: CandidateFacts): Candidate {\n return { id: facts.id, kind: facts.kind, text: fitted(facts) };\n}\n","// A reading of one change: the operation and the names it works on. The\n// tool's reading and the model's are the same shape, so they compare slot by\n// slot, and a candidate says which slots a reading names it by. An instance\n// is named by its canvas path, a module as `author/name`.\nexport const READING_SLOTS = [\n 'operation',\n 'instance',\n 'input',\n 'sourceInstance',\n 'output',\n 'targetInstance',\n 'module',\n] as const;\n\nexport type Slot = (typeof READING_SLOTS)[number];\n\nexport type Reading = Readonly<Partial<Record<Slot, string>>>;\n\n// The slots a reading states.\nexport function statedSlots(reading: Reading): Slot[] {\n return READING_SLOTS.filter((slot) => reading[slot] !== undefined);\n}\n\n// A reading in words, slot by slot: what a result shows of the tool's\n// reading and the model's, and what the ranking reads as the statement.\nexport function renderReading(reading: Reading): string {\n return statedSlots(reading)\n .map((slot) => `${slot}=${reading[slot]}`)\n .join(', ');\n}\n","// The one rendering of a request as the ranking reads it, and what is\n// withheld from it. Every function here is pure: the request a rank call\n// receives and a capture records is what was rendered here at run time.\nimport { RANK_REQUEST_MAX_CHARS } from './bounds';\nimport { shortened } from './candidate';\n\n// The one token that stands where a value was: in the request every rank\n// call for a change receives and a capture records, in each statement\n// beside it (the model's reading, and its alternative reading), in what a\n// decision reports as applied, and in a reason this package did not write.\nexport const VALUE_PLACEHOLDER = '<value>';\n\n// The texts a value holds: itself when it is text, a number or a boolean,\n// and every such leaf of a list or an object.\nfunction literalTexts(value: unknown): string[] {\n if (typeof value === 'string') return [value];\n if (typeof value === 'number' || typeof value === 'boolean') return [String(value)];\n if (typeof value === 'object' && value !== null)\n return Object.values(value).flatMap(literalTexts);\n return [];\n}\n\n// The literals of a change, longest first, so one that holds another is\n// replaced whole.\nfunction literals(values: readonly unknown[]): string[] {\n return values\n .flatMap(literalTexts)\n .filter((literal) => literal !== '')\n .sort((a, b) => b.length - a.length);\n}\n\n// A variable reference's name: `var.x` names the variable `x`, which is what\n// a binding writes.\nexport function variableName(text: string): string {\n return text.replace(/^var\\./, '');\n}\n\n// Every text values are written as: each literal, and a variable reference\n// also by the name of the variable it names.\nexport function forms(values: readonly unknown[]): string[] {\n return [...new Set(literals(values).flatMap((text) => [text, variableName(text)]))];\n}\n\n// What is withheld of another change's values against the names a canvas\n// holds: every form of them that is no name among `names`. A name on the\n// canvas is a canvas fact: the ranking sees it among the candidates.\nexport function unnamed(names: ReadonlySet<string>, values: readonly unknown[]): string[] {\n return forms(values).filter((text) => !names.has(text));\n}\n\n// `text` as a pattern that matches it literally.\nexport function escapeRegExp(text: string): string {\n return text.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\nconst NAME = /^[A-Za-z0-9_-]+$/;\n\n// Where a literal stands in a text. One that could be a name stands where\n// it is a token of its own, delimited by anything that is not a letter, a\n// digit, an underscore or a hyphen; one that holds any other character is\n// never a name and stands wherever it occurs.\nfunction occurrences(literal: string): RegExp {\n const text = escapeRegExp(literal);\n return NAME.test(literal)\n ? new RegExp(`(?<![A-Za-z0-9_-])${text}(?![A-Za-z0-9_-])`, 'g')\n : new RegExp(text, 'g');\n}\n\n// `text` with every occurrence of a literal replaced by the placeholder.\nexport function withhold(text: string, values: readonly unknown[]): string {\n return literals(values).reduce(\n (rest, literal) => rest.replace(occurrences(literal), VALUE_PLACEHOLDER),\n text,\n );\n}\n\n// Whether a rendered text still holds a literal: one `withhold` left where\n// it stood, inside a longer word. The change tool asks it of a change's\n// request and statements together, with every canvas name withheld, over\n// every withheld text of the call: a change that still holds one is never\n// sent to rank.\nexport function holdsValue(rendered: string, values: readonly unknown[]): boolean {\n return literals(values).some((literal) => rendered.includes(literal));\n}\n\n// A change's request as the ranking and a capture hold it: the developer's\n// words with each text in `values` replaced by the placeholder, cut at a\n// word so that it and `statement` (the longest a rank call for the change\n// carries) together are within the request bound of one rank call. It is\n// rendered once per change, and that one string is the request of every\n// rank call for the change and of every capture of it.\nexport function renderRequest(request: string, values: readonly unknown[], statement = ''): string {\n return shortened(withhold(request, values), RANK_REQUEST_MAX_CHARS - statement.length);\n}\n","// The row format, one definition: what a head trains on, is calibrated on\n// and is held out against. One row per question of a turn, holding exactly\n// what the rank call for the question carried (the request, the statement\n// and the candidates as rendered, `(none)` last in every kind but `steps`),\n// so what is trained is what was served. No row holds a value the tools\n// were given: the request and the statement are the strings the rank call\n// carried, every value the placeholder.\nimport type { Candidate, DecisionKind } from '../questions';\n\n// Which part of a corpus a turn's rows belong to: training, the calibration\n// the thresholds are fitted on, or the held-out part a threshold ships\n// against once. A turn is in the same part in every corpus.\nexport type Part = 'train' | 'calibration' | 'held_out';\n\n// Where a turn came from: a developer's call through the tools, or the\n// offline generator.\nexport type Origin = 'real' | 'synthetic';\n\n// One decision as a head learns it: the rendered request, the statement\n// beside it ('' when none was stated, and the pod scores the raw-words arm\n// by that), the closed set the question offered, the id of the right\n// candidate, the turn's part and origin, the turn's id (shared by every row\n// of the turn, so a turn counts once however many questions it asked), and\n// System Two's candidate for the question (null when it stated none), which\n// the fit's bar reads.\nexport type TrainingRow = {\n readonly request: string;\n readonly statement: string;\n readonly candidates: readonly Candidate[];\n readonly label: string;\n readonly part: Part;\n readonly origin: Origin;\n readonly turn: string;\n readonly chat: string | null;\n};\n\n// One question of a turn with its label: the candidates as the rank call\n// carried them, the id of the right one, and System Two's candidate for it.\nexport type LabelledQuestion = {\n readonly kind: DecisionKind;\n readonly candidates: readonly Candidate[];\n readonly label: string;\n readonly chat: string | null;\n};\n\n// A turn as rows are written from it: its id, the request and statement its\n// rank calls carried, its origin and its labelled questions.\nexport type LabelledTurn = {\n readonly id: string;\n readonly request: string;\n readonly statement: string;\n readonly origin: Origin;\n readonly questions: readonly LabelledQuestion[];\n};\n\n// A key as a fraction in [0, 1): its 32-bit FNV-1a hash, so the same key is\n// always at the same fraction, wherever it is read.\nexport function hashFraction(key: string): number {\n let hash = 0x811c9dc5;\n for (const char of key) {\n hash ^= char.codePointAt(0) ?? 0;\n hash = Math.imul(hash, 0x01000193) >>> 0;\n }\n return hash / 2 ** 32;\n}\n\n// The part of a key: 60% train, 20% calibration, 20% held out, the same key\n// in the same part in every corpus. A real turn's key is its account's\n// (the review export's `partKeyOf`), so every turn of one account, and with\n// them every turn that account made on each canvas, is in one part; a canvas\n// two accounts both edit can have turns in two parts, since no canvas\n// identity is collected.\nexport function partOf(key: string): Part {\n const at = hashFraction(key);\n return at < 0.6 ? 'train' : at < 0.8 ? 'calibration' : 'held_out';\n}\n\n// A turn's training rows in `part`, one per question, each labelled with its\n// right candidate. The part is the caller's: a real turn's is `partOf` its\n// account's key, a synthetic one's its side's. A relabelled question may be\n// labelled `(none)`: no candidate fitted.\nexport function trainingRows(turn: LabelledTurn, part: Part): TrainingRow[] {\n return turn.questions.map(({ candidates, label, chat }) => ({\n request: turn.request,\n statement: turn.statement,\n candidates,\n label,\n part,\n origin: turn.origin,\n turn: turn.id,\n chat,\n }));\n}\n","// The client of Lace's ranking service over a host's `Transport`: one rank\n// call per question, the composed decision once per change, and each\n// outcome once. Collection is the service's side effect of being asked, so\n// nothing here stores anything: the API captures the question at the rank\n// call and keys it to the caller.\nimport type { OutcomeReport } from '../examples/outcome';\nimport type { DecisionReport } from '../examples/record';\nimport { DECISION_KINDS, type DecisionKind } from '../questions';\nimport type { Rank, Ranked, Score, Thresholds, Transport } from './types';\n\nexport const RANK_PATH = '/api/v1/candidates/rank';\nexport const DECISIONS_PATH = '/api/v1/candidates/decisions';\n\n// The service gave no ranking: the API answered other than 200 (503\n// `ranking_unavailable` when the pod is down), the transport threw, or the\n// body is not a reply. The question is then System Two's alone.\nexport class RankingUnavailable extends Error {}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nconst isKind = (value: string): value is DecisionKind =>\n (DECISION_KINDS as readonly string[]).includes(value);\n\nfunction scoreOf(value: unknown): Score | undefined {\n if (!isRecord(value)) return undefined;\n const { id, score, rightness } = value;\n return typeof id === 'string' &&\n typeof score === 'number' &&\n typeof rightness === 'number' &&\n rightness >= 0 &&\n rightness <= 1\n ? { id, score, rightness }\n : undefined;\n}\n\nfunction thresholdsOf(value: unknown): Thresholds | undefined {\n if (!isRecord(value)) return undefined;\n const entries = Object.entries(value).map(([kind, threshold]) =>\n isKind(kind) && isRecord(threshold) && typeof threshold.from === 'number'\n ? [kind, { from: threshold.from }]\n : undefined,\n );\n return entries.every((entry) => entry !== undefined) ? Object.fromEntries(entries) : undefined;\n}\n\n// The reply as the API sends it, or none when the body is not one.\nexport function rankedOf(body: unknown): Ranked | undefined {\n if (!isRecord(body) || !Array.isArray(body.scores)) return undefined;\n const scores = body.scores.map(scoreOf);\n const thresholds = thresholdsOf(body.thresholds);\n return typeof body.capture_id === 'string' &&\n typeof body.head === 'string' &&\n scores.every((score) => score !== undefined) &&\n thresholds !== undefined\n ? { capture_id: body.capture_id, head: body.head, scores, thresholds }\n : undefined;\n}\n\nexport type RankingClient = {\n readonly rank: Rank;\n // Reports the composed decision of one change. A repeat is the same\n // answer; a report the API refuses or the transport drops is one failed\n // call, which nothing retries and nothing shows (decided: nothing in the\n // UI about what is sent).\n readonly decision: (report: DecisionReport) => Promise<void>;\n // Reports one outcome of a decision, by the decision's id.\n readonly outcome: (decision: string, outcome: OutcomeReport) => Promise<void>;\n};\n\nexport function rankingClient(transport: Transport): RankingClient {\n const post = (path: `/api/v1/candidates/${string}`, body: unknown) =>\n transport(path, { method: 'POST', body }).catch(() => ({ status: 0, body: undefined }));\n return {\n async rank(request) {\n const { status, body } = await post(RANK_PATH, request);\n const ranked = status === 200 ? rankedOf(body) : undefined;\n if (ranked === undefined) {\n throw new RankingUnavailable(\n status === 200 ? 'the ranking service answered with no ranking' : `status ${status}`,\n );\n }\n return ranked;\n },\n async decision(report) {\n await post(DECISIONS_PATH, report);\n },\n async outcome(decision, outcome) {\n await post(`${DECISIONS_PATH}/${encodeURIComponent(decision)}/outcomes`, outcome);\n },\n };\n}\n","// The composition of the two readings of one question. System Two\n// understands: the words, the statement and every typed value are its. System\n// One maps, where sure: its answer stands when its rightness clears the\n// head's threshold for the kind; otherwise the question is System Two's own\n// answer, the candidate its stated slot names, which may be none. Where the\n// two differ and System One is sure, System One's stands and the record says\n// both: the decision is graded later, not withheld.\nimport { type DecisionKind, NONE_CANDIDATE_ID } from '../questions';\nimport type { Ranked, Score } from '../ranking';\n\nconst real = (score: Score): boolean => score.id !== NONE_CANDIDATE_ID;\n\n// A ranking's pick: its best real candidate, in rank order. `(none)` is\n// ranked and never picked; a ranking of nothing else picks nothing.\nexport function pickOf(scores: readonly Score[]): Score | undefined {\n return scores.find(real);\n}\n\n// Whether System One is sure of its pick for a question of `kind`: the pick's\n// rightness reaches the threshold the reply carries for the kind. A reply\n// with no threshold for the kind is sure of nothing of that kind, and\n// `(none)` ranked first is never sure, whatever the rightness: the words may\n// mean nothing the set holds.\nexport function sure(ranked: Ranked, kind: DecisionKind): boolean {\n const from = ranked.thresholds[kind]?.from;\n const pick = pickOf(ranked.scores);\n return (\n from !== undefined &&\n pick !== undefined &&\n ranked.scores[0]?.id !== NONE_CANDIDATE_ID &&\n pick.rightness >= from\n );\n}\n\n// The two readings of one question. `chat` is System Two's candidate, null\n// when its statement names none; `ranked` is System One's reply, null when it\n// gave none (no transport, a failed call).\nexport type Readings = {\n readonly kind: DecisionKind;\n readonly chat: string | null;\n readonly ranked: Ranked | null;\n};\n\n// One question composed: whose answer was taken and which, System One's pick\n// with its rightness where it ranked, and whether the two readings differed\n// where System One's was taken.\nexport type Composed = {\n readonly took: 'chat' | 'clm';\n readonly taken: string | null;\n readonly clm: { readonly id: string; readonly rightness: number } | null;\n readonly differed: boolean;\n};\n\nexport function compose({ kind, chat, ranked }: Readings): Composed {\n const pick = ranked === null ? undefined : pickOf(ranked.scores);\n const clm = pick === undefined ? null : { id: pick.id, rightness: pick.rightness };\n if (ranked !== null && clm !== null && sure(ranked, kind)) {\n return { took: 'clm', taken: clm.id, clm, differed: chat !== null && chat !== clm.id };\n }\n return { took: 'chat', taken: chat, clm, differed: false };\n}\n\n// The move rule: System One's operation stands only when it was sure of the\n// operation and of every question asked under it. Where a question under it\n// fell to System Two, the operation is System Two's too, and the change is\n// resolved again under that operation.\nexport function moveStands(under: readonly Composed[]): boolean {\n return under.every((question) => question.took === 'clm');\n}\n","// The canvas tools: the tools that work on one authoring session. A host\n// constructs them from that session's ports; without a session they cannot\n// be constructed, and without a `transport` they compose System Two alone.\n// Each registration is a name, a description that carries the tool's\n// guidance to any host, an input schema and a handler, and says nothing\n// about the host's editor. With a `transport` the set also reads the\n// session's frames for what happened next to each reported change (the\n// outcome observer, composed here with the source it was given, every apply\n// of the change tool run through it), until the host disposes of the set.\n//\n// Every result ends with the current canvas, so each call corrects the\n// model's picture of it. Save and Generate run only when their own tool is\n// called, through the operations the canvas's own buttons run; no tool asks\n// for a confirmation and none reaches an operation the canvas confirms.\nimport { ApplyUnobservedError, type GenerateEvent } from '@lace-cloud/canvas/engine';\nimport type { ToolRegistration } from '../../contract/tool-registry';\nimport type { ToolResult, ToolSchema } from '../../contract/types';\nimport { OPERATION_TEXT, type Slot } from '../../questions';\nimport { applyChanges, type ChangeRecord, OPERATIONS, parseChanges } from './change';\nimport { trimValidate } from './commands';\nimport { outcomeObserver } from './outcome';\nimport { type CanvasToolPorts, endText, latest } from './ports';\nimport {\n errorText,\n InvalidInput,\n NO_INPUT,\n reasonText,\n registration,\n registrationOf,\n} from './registration';\nimport { renderCanvas } from './render';\n\n// What the model's reading states, slot by slot: one property per slot of\n// a reading, so the schema and the comparison name the same parts.\nconst READING_PROPERTIES: Record<Slot, Record<string, unknown>> = {\n operation: {\n type: 'string',\n enum: OPERATIONS.map((operation) => operation.id),\n description: OPERATIONS.map((operation) => OPERATION_TEXT[operation.id]).join('; '),\n },\n instance: {\n type: 'string',\n description:\n 'The instance a set, bind, clear, disconnect, rename or delete works on, or the group an ungroup dissolves.',\n },\n input: {\n type: 'string',\n description: 'The input a set, bind, clear or disconnect works on, or a connect wires into.',\n },\n sourceInstance: {\n type: 'string',\n description: 'The instance a connect wires from.',\n },\n output: { type: 'string', description: 'The output a connect wires from.' },\n targetInstance: {\n type: 'string',\n description: 'The instance a connect wires into.',\n },\n module: {\n type: 'string',\n description: 'The registry module a place adds, as `author/name`.',\n },\n};\n\nconst READING = { type: 'object', properties: READING_PROPERTIES, additionalProperties: false };\n\nconst CHANGE: ToolSchema = {\n name: 'lace_change_module_canvas',\n title: 'Change module canvas',\n description: [\n \"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.\",\n \"`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.\",\n '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`.',\n \"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.\",\n ].join(' '),\n inputSchema: {\n type: 'object',\n properties: {\n changes: {\n type: 'array',\n minItems: 1,\n description: 'The changes, in order, one entry per change.',\n items: {\n type: 'object',\n properties: {\n request: {\n type: 'string',\n description:\n \"One change, in the developer's own words, and never a literal value: that goes in `value`.\",\n },\n value: {\n description:\n \"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.\",\n },\n modelReading: READING,\n alternativeReading: READING,\n },\n required: ['request', 'modelReading'],\n additionalProperties: false,\n },\n },\n },\n required: ['changes'],\n additionalProperties: false,\n },\n};\n\nconst DESCRIBE: ToolSchema = {\n name: 'lace_describe_module_canvas',\n title: 'Describe module canvas',\n description:\n '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.',\n inputSchema: NO_INPUT,\n};\n\nconst SAVE: ToolSchema = {\n name: 'lace_save_module_canvas',\n title: 'Save module canvas',\n description: 'Saves a Lace module canvas. Call it only when the developer asks to save.',\n inputSchema: NO_INPUT,\n};\n\nconst GENERATE: ToolSchema = {\n name: 'lace_generate_module_terraform',\n title: 'Generate module Terraform',\n description:\n \"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.\",\n inputSchema: NO_INPUT,\n};\n\n// The canvas tools' schemas as data, in the order `canvasTools` returns its\n// registrations: change, describe, save, generate. A host that generates a\n// manifest of the tools reads these without constructing the set, and the\n// set registers exactly these.\nexport const canvasToolSchemas: readonly [ToolSchema, ToolSchema, ToolSchema, ToolSchema] = [\n CHANGE,\n DESCRIBE,\n SAVE,\n GENERATE,\n];\n\ntype Said = { readonly text: string; readonly isError: boolean };\n\n// What a Generate's event says in a result. Its progress says nothing; it\n// closes with the files it wrote and the validate report of the written\n// tree, or with the engine's refusal by its reason.\nfunction generateSaid(event: GenerateEvent): Said[] {\n switch (event.type) {\n case 'progress':\n return [];\n case 'success':\n return [\n {\n text: [\n `Generated the Terraform. Files written: ${event.written.join(', ')}.`,\n `lace module validate on the written tree: ${JSON.stringify(trimValidate(event.validate))}`,\n ].join('\\n'),\n isError: false,\n },\n ];\n case 'error':\n return [\n {\n text: `Lace did not generate: ${event.message} (${reasonText(event.reason)}).`,\n isError: true,\n },\n ];\n }\n}\n\n// What a write the engine made says when the session's stream ended before\n// the frame that carries it: the canvas the result ends with cannot show it.\n// Any other failure is the call's own.\nfunction unobserved(error: unknown): Said {\n if (!(error instanceof ApplyUnobservedError)) throw error;\n return {\n text: `The session's stream ended (${endText(error.end)}) before the canvas showed this, so the canvas below is from before it.`,\n isError: false,\n };\n}\n\n// The change tool's result: the text its model reads, and beside it, for\n// the host, the record of each change that was applied, in order.\nexport type ChangeResult = ToolResult & {\n readonly applied: readonly ChangeRecord[];\n};\n\n// The canvas tools in their order: change, describe, save, generate, and\n// `dispose`, which ends the set's reading of the session's frames; a host\n// calls it when it drops the tools or the session closes.\nexport type CanvasTools = readonly [\n ToolRegistration<ChangeResult>,\n ToolRegistration,\n ToolRegistration,\n ToolRegistration,\n] & { readonly dispose: () => void };\n\nconst NO_RECORDS = { applied: [] } as const;\n\nexport function canvasTools(ports: CanvasToolPorts): CanvasTools {\n const [change, describe, save, generate] = canvasToolSchemas;\n const observer = ports.transport === undefined ? undefined : outcomeObserver(ports.transport);\n const dispose =\n observer === undefined ? () => {} : ports.source.subscribe(observer.frame, () => {});\n // What a call did; a call that threw says so the same way.\n const attempt = (run: () => Promise<readonly Said[]>): Promise<readonly Said[]> =>\n run().catch((error): Said[] => [{ text: errorText(error), isError: true }]);\n\n // What a call said, each part set off by a blank line, then the canvas as\n // it stands after the call.\n const answer = async (said: readonly Said[]): Promise<ToolResult> => ({\n content: [\n ...said.map((each) => `${each.text}\\n`),\n renderCanvas(await latest(ports.source)),\n ].join('\\n'),\n isError: said.some((each) => each.isError),\n });\n\n const registrations = [\n registrationOf<ChangeResult>(\n change,\n async (input) => {\n try {\n const { text, applied } = await applyChanges(ports, parseChanges(input), observer?.own);\n observer?.follow(applied);\n return { ...(await answer([{ text, isError: false }])), applied };\n } catch (error) {\n if (!(error instanceof InvalidInput)) throw error;\n return { ...(await answer([{ text: errorText(error), isError: true }])), ...NO_RECORDS };\n }\n },\n (failure) => ({ ...failure, ...NO_RECORDS }),\n ),\n registration(describe, () => answer([])),\n registration(save, async () =>\n answer(\n await attempt(async () => {\n const saved: Said = { text: 'Saved the canvas.', isError: false };\n try {\n await ports.editor.save();\n return [saved];\n } catch (error) {\n return [saved, unobserved(error)];\n }\n }),\n ),\n ),\n registration(generate, async () =>\n answer(\n await attempt(async () => {\n const said: Said[] = [];\n try {\n for await (const event of ports.editor.generate()) said.push(...generateSaid(event));\n } catch (error) {\n said.push(unobserved(error));\n }\n return said;\n }),\n ),\n ),\n ] as const;\n return Object.assign(registrations, { dispose });\n}\n","// The change tool's work: each change, in the developer's words, resolved\n// against the canvas as it is when that change is reached by the two\n// systems, then applied.\n//\n// System Two understands: the words, the reading it states with them\n// (`modelReading`, required on every call) and every typed value are its.\n// System One maps, where sure: a question's answer is its pick when the\n// pick's rightness clears the head's threshold for the kind, else System\n// Two's own answer, the candidate its stated slot names. The names a request\n// holds settle a question before either is asked. The operation is System\n// One's only when it was sure of it, of every question under it, and the\n// change resolves under it: the move rule is part of planning, and where it\n// fails the change is resolved again under System Two's operation, whose\n// outcome alone is the change's. Where System One is sure and the reading\n// named another candidate, System One's stands and the result says both:\n// the decision is graded by what the developer does next, not withheld. A\n// change neither system resolves is not applied, and the result says which\n// part and its candidates. Where the model gave an alternative reading and\n// System One is sure of a different answer under it, nothing is applied and\n// both decisions come back. `steps` (one change or several) is outside that\n// gate: System Two's answer is `one` by construction, System One's, read\n// under the model's reading alone, stands where sure, and it decides only\n// what the result says.\n//\n// What System One reads: the request rendered with every form of the\n// change's own value and every other value of the call the canvas does not\n// name withheld, and System Two's statements (its reading, and its\n// alternative reading where it gave one), each the stated slots that name a\n// fact (an operation, a name the canvas holds, a registry module as\n// `author/name`), withheld the same way. A change whose request or\n// statements still hold any withheld text of the call inside a word is not\n// ranked at all.\n//\n// A change leaves a record for the host: what it changed, the state before\n// and after, and the revision its apply produced. The composed decision is\n// reported to Lace's API once the call settles, with what was applied in\n// words, every value withheld.\nimport { type ApplyResult, ApplyUnobservedError, InputMode } from '@lace-cloud/canvas/engine';\nimport type { DecisionReport, Question } from '../../examples';\nimport { type Composed, moveStands, pickOf } from '../../hybrid';\nimport {\n type DecisionKind,\n forms,\n holdsValue,\n NONE_CANDIDATE_ID,\n READING_SLOTS,\n type Reading,\n renderReading,\n renderRequest,\n type Slot,\n statedSlots,\n unnamed,\n VALUE_PLACEHOLDER,\n variableName,\n withhold,\n} from '../../questions';\nimport { rankingClient } from '../../ranking';\nimport { runCommand } from './commands';\nimport {\n type CanvasInput,\n type CanvasInstance,\n type CanvasReading,\n canvasNames,\n connectionOptions,\n inputOptions,\n instanceOptions,\n moduleId,\n moduleOptions,\n type Option,\n operationOptions,\n readCanvas,\n sourceOptions,\n stepsOptions,\n targetOptions,\n} from './enumerate';\nimport { bindingOf, follow, presenceOf, targetState } from './outcome';\nimport { type CanvasEditor, type CanvasToolPorts, endText, latest } from './ports';\nimport { errorText, InvalidInput } from './registration';\nimport { renderState, renderTarget } from './render';\nimport {\n type Ask,\n asAsked,\n type Decision,\n decide,\n moduleReferences,\n NONE_OVER,\n type Ranking,\n termsOf,\n Undecided,\n} from './resolve';\n\n// One entry of the tool's input. `values` holds the literal the developer\n// gave: one item when the entry carries it and none when it does not.\n// `reading` is the model's own reading of the change and `alternative` its\n// other reading of the words, where it gave one.\nexport type Change = {\n readonly request: string;\n readonly values: readonly unknown[];\n readonly reading: Reading;\n readonly alternative?: Reading;\n};\n\n// What an applied change addressed: an instance of a scope (the module key\n// of the module that owns it), or one input of it.\nexport type ChangeTarget = {\n readonly scope: string;\n readonly instance: string;\n readonly input?: string;\n};\n\n// An input's binding: its mode and the content of that mode. A sensitive\n// input's binding is its mode alone.\nexport type InputBinding = {\n readonly mode: CanvasInput['mode'];\n readonly value?: unknown;\n readonly variable?: string;\n readonly expression?: string;\n readonly wiredSource?: string;\n};\n\n// An instance that is on the canvas: its name in its scope and its module.\nexport type InstancePresence = {\n readonly instance: string;\n readonly module: string;\n};\n\n// The state of what a change addressed, before it or after it: an input's\n// binding, an instance's presence, or `null` for an instance that is not on\n// the canvas.\nexport type ChangeState = InputBinding | InstancePresence | null;\n\n// One question of a decision as its record holds it: its kind and the ids of\n// its candidates, so an outcome can name the question and candidate a later\n// edit answers.\nexport type RecordQuestion = {\n readonly kind: DecisionKind;\n readonly candidates: readonly string[];\n};\n\n// The record of one applied change: what it addressed, that target's state\n// before and after, the revision of the frame its apply produced (absent\n// where the editor answered none), the decision's questions in the order\n// reported, and whether the decision was reported to Lace, so its outcomes\n// are. `id` is the decision's.\nexport type ChangeRecord = {\n readonly id: string;\n readonly target: ChangeTarget;\n readonly before: ChangeState;\n readonly after: ChangeState;\n readonly revision?: number;\n readonly questions: readonly RecordQuestion[];\n readonly reported: boolean;\n};\n\n// A change that cannot be applied as it was sent, whatever it resolves to.\nclass Unapplicable extends Error {}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nconst present = (value: unknown): boolean => value !== undefined && value !== null;\n\nfunction readingOf(index: number, name: string, stated: unknown): Reading {\n if (!isRecord(stated)) {\n throw new InvalidInput(`change ${index + 1}: \\`${name}\\` is an object of names`);\n }\n return Object.fromEntries(\n READING_SLOTS.flatMap((slot) => {\n const value = stated[slot];\n return typeof value === 'string' ? [[slot, value]] : [];\n }),\n );\n}\n\nexport function parseChanges(input: Record<string, unknown>): Change[] {\n const { changes } = input;\n if (!Array.isArray(changes)) throw new InvalidInput('`changes` is a list of changes');\n return changes.map((entry: unknown, index) => {\n if (!isRecord(entry) || typeof entry.request !== 'string') {\n throw new InvalidInput(`change ${index + 1} needs \\`request\\`: the developer's own words`);\n }\n if (!present(entry.modelReading)) {\n throw new InvalidInput(\n `change ${index + 1} needs \\`modelReading\\`: your own reading of the change, an object of the names you stated`,\n );\n }\n const alternative = present(entry.alternativeReading)\n ? { alternative: readingOf(index, 'alternativeReading', entry.alternativeReading) }\n : {};\n return {\n request: entry.request,\n values: [entry.value].filter(present),\n reading: readingOf(index, 'modelReading', entry.modelReading),\n ...alternative,\n };\n });\n}\n\n// One action of an `ApplyAction` batch, in the generated shape: an\n// instance-addressed action carries `scope`, the key of the module that\n// owns the instance, on its own sub-message, beside the instance's id there.\ntype Action = Parameters<CanvasEditor['apply']>[0][number];\n\n// What an operation resolves a change to: the one action that applies it,\n// the words for what it did, and what the record of it holds: the target,\n// its state on the canvas the change was resolved against, and how to read\n// its state from the canvas the apply produced.\ntype Plan = {\n readonly action: Action;\n readonly summary: (result: ApplyResult) => string;\n readonly target: (result: ApplyResult) => ChangeTarget;\n readonly before: ChangeState;\n readonly after: (canvas: CanvasReading, result: ApplyResult) => ChangeState;\n};\n\ntype Resolving = {\n readonly canvas: CanvasReading;\n // The request as rendered for the ranking.\n readonly request: string;\n readonly values: readonly unknown[];\n readonly ports: CanvasToolPorts;\n // Resolves one decision and records it for the result.\n readonly pick: <T>(\n kind: DecisionKind,\n label: string,\n options: readonly Option<T>[],\n ) => Promise<T>;\n // Records a line the result says beside the change's outcome.\n readonly note: (line: string) => void;\n};\n\n// One operation: its id (its prose is `OPERATION_TEXT[id]`, written where\n// every candidate's prose is) and how it resolves the rest of a change.\ntype Operation = {\n readonly id: string;\n // Whether the operation writes the literal a change carries in `value`.\n readonly takesValue: boolean;\n readonly plan: (resolving: Resolving) => Promise<Plan>;\n};\n\n// The record parts of an edit to one input of an instance.\nfunction inputEdit(canvas: CanvasReading, instance: CanvasInstance, inputName: string) {\n const state = (of: CanvasReading) => bindingOf(of, instance.scope, instance.name, inputName);\n return {\n target: () => ({ scope: instance.scope, instance: instance.name, input: inputName }),\n before: state(canvas),\n after: state,\n };\n}\n\n// The record parts of an edit to an instance itself, which is `nameAfter`\n// once the edit is applied.\nfunction instanceEdit(canvas: CanvasReading, instance: CanvasInstance, nameAfter: string) {\n return {\n target: () => ({ scope: instance.scope, instance: instance.name }),\n before: presenceOf(canvas, instance.scope, instance.name),\n after: (of: CanvasReading) => presenceOf(of, instance.scope, nameAfter),\n };\n}\n\n// System One selects and does not write: a value, a new name or a\n// variable's name is the literal the developer gave, carried in `value`.\nfunction given(values: readonly unknown[], what: string): unknown {\n if (values.length === 0) {\n throw new Unapplicable(`this change needs ${what}: pass it in \\`value\\``);\n }\n return values[0];\n}\n\nfunction givenName(values: readonly unknown[], what: string): string {\n const name = given(values, what);\n if (typeof name !== 'string') throw new Unapplicable(`${what} is text: pass it in \\`value\\``);\n return name;\n}\n\ntype BindingMode = CanvasInput['mode'];\n\nconst EVERY_MODE: readonly BindingMode[] = ['empty', 'literal', 'variable', 'expression', 'wired'];\n\n// The instance and the input an input operation works on, picked among the\n// inputs whose binding is in one of `modes`: an operation is offered only\n// the inputs it can act on.\nasync function pickInput({ canvas, pick }: Resolving, modes: readonly BindingMode[]) {\n const offered = (instance: CanvasInstance) =>\n instance.inputs.filter((input) => modes.includes(input.mode));\n const instance = await pick(\n 'instance',\n 'instance',\n instanceOptions(canvas.instances.filter((each) => offered(each).length > 0)),\n );\n const input = await pick('input', 'input', inputOptions(instance, offered(instance)));\n return { instance, input };\n}\n\n// The one `update_input` action: an input given a binding of one mode.\nfunction updateInput(\n instance: CanvasInstance,\n input: CanvasInput,\n binding: { mode: InputMode; value?: unknown; variable?: string },\n): Action {\n return {\n update_input: {\n scope: instance.scope,\n instance_id: instance.name,\n input_name: input.name,\n mode: binding.mode,\n value: binding.value,\n variable: binding.variable ?? '',\n expression: '',\n },\n };\n}\n\n// The most modules one registry listing returns.\nconst CATALOG_LIMIT = 500;\n\nconst place: Operation = {\n id: 'place',\n takesValue: false,\n async plan({ canvas, request, ports, pick, note }) {\n // A request that refers to a module as `author/name` narrows the listing\n // to modules of that name; any other request is resolved over the\n // catalog the listing returns.\n const [query] = moduleReferences(request).map((reference) => reference.split('/').slice(-1)[0]);\n const listing = await runCommand(ports.commands, 'registry list', {\n axis: 'module',\n limit: CATALOG_LIMIT,\n query,\n });\n if (listing.failed !== undefined) throw new Error(listing.failed.text);\n for (const document of listing.documents) {\n if (document.truncated) {\n note(\n `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.`,\n );\n }\n }\n const rows = listing.documents.flatMap((document) => document.items);\n const row = await pick('module', 'registry module', moduleOptions(rows));\n const placed = (result: ApplyResult) => result.created.map((ref) => ref.id).join(', ');\n return {\n action: {\n place_module: { author: row.author, name: row.name, version: row.version },\n },\n summary: (result) => `placed ${moduleId(row)} ${row.version} as ${placed(result)}`,\n target: (result) => ({ scope: canvas.entry, instance: placed(result) }),\n before: null,\n after: (of, result) =>\n result.created\n .map((ref) => presenceOf(of, ref.scope, ref.id))\n .find((presence) => presence !== null) ?? null,\n };\n },\n};\n\nconst connect: Operation = {\n id: 'connect',\n takesValue: false,\n async plan({ canvas, ports, pick }) {\n const source = await pick('instance', 'source instance', sourceOptions(canvas.instances));\n const target = await pick(\n 'instance',\n 'target instance',\n targetOptions(canvas.instances, source),\n );\n const scored = await ports.editor.wiringCandidates({\n scope: source.scope,\n source: source.name,\n target: target.name,\n });\n const pair = await pick('connection', 'connection', connectionOptions(source, target, scored));\n return {\n action: {\n connect: {\n scope: target.scope,\n source_scope: source.scope,\n source: source.name,\n target: target.name,\n source_output: pair.output,\n target_input: pair.input,\n },\n },\n summary: () => `connected ${source.id}.${pair.output} → ${target.id}.${pair.input}`,\n ...inputEdit(canvas, target, pair.input),\n };\n },\n};\n\nconst disconnect: Operation = {\n id: 'disconnect',\n takesValue: false,\n async plan(resolving) {\n const { instance, input } = await pickInput(resolving, ['wired']);\n return {\n action: {\n disconnect: { scope: instance.scope, target: instance.name, input_name: input.name },\n },\n summary: () => `disconnected ${instance.id}.${input.name}`,\n ...inputEdit(resolving.canvas, instance, input.name),\n };\n },\n};\n\nconst set: Operation = {\n id: 'set',\n takesValue: true,\n async plan(resolving) {\n const value = given(resolving.values, 'the value the developer gave');\n const { instance, input } = await pickInput(resolving, EVERY_MODE);\n const shown = input.sensitive ? '(sensitive, value withheld)' : `= ${JSON.stringify(value)}`;\n return {\n action: updateInput(instance, input, { mode: InputMode.INPUT_MODE_LITERAL, value }),\n summary: () => `set ${instance.id}.${input.name} ${shown}`,\n ...inputEdit(resolving.canvas, instance, input.name),\n };\n },\n};\n\nconst bind: Operation = {\n id: 'bind',\n takesValue: true,\n async plan(resolving) {\n const variable = variableName(givenName(resolving.values, \"the variable's name\"));\n const { instance, input } = await pickInput(resolving, EVERY_MODE);\n return {\n action: updateInput(instance, input, { mode: InputMode.INPUT_MODE_VARIABLE, variable }),\n summary: () => `bound ${instance.id}.${input.name} to var.${variable}`,\n ...inputEdit(resolving.canvas, instance, input.name),\n };\n },\n};\n\nconst clear: Operation = {\n id: 'clear',\n takesValue: false,\n async plan(resolving) {\n const { instance, input } = await pickInput(resolving, ['literal', 'variable', 'expression']);\n return {\n action: updateInput(instance, input, { mode: InputMode.INPUT_MODE_EMPTY }),\n summary: () => `cleared ${instance.id}.${input.name}`,\n ...inputEdit(resolving.canvas, instance, input.name),\n };\n },\n};\n\nconst rename: Operation = {\n id: 'rename',\n takesValue: true,\n async plan({ canvas, values, pick }) {\n const name = givenName(values, 'the new name');\n const instance = await pick('instance', 'instance', instanceOptions(canvas.instances));\n return {\n action: {\n rename_instance: { scope: instance.scope, old_id: instance.name, new_id: name },\n },\n summary: () => `renamed ${instance.id} to ${name}`,\n ...instanceEdit(canvas, instance, name),\n };\n },\n};\n\nconst remove: Operation = {\n id: 'delete',\n takesValue: false,\n async plan({ canvas, pick }) {\n const instance = await pick('instance', 'instance', instanceOptions(canvas.instances));\n return {\n action: { delete_instance: { scope: instance.scope, instance_id: instance.name } },\n summary: () => `deleted ${instance.id}`,\n ...instanceEdit(canvas, instance, instance.name),\n };\n },\n};\n\nconst ungroup: Operation = {\n id: 'ungroup',\n takesValue: false,\n async plan({ canvas, pick }) {\n const groups = new Set(canvas.groups.map((group) => group.id));\n const group = await pick(\n 'instance',\n 'group',\n instanceOptions(canvas.instances.filter((instance) => groups.has(instance.id))),\n );\n return {\n action: { ungroup: { scope: group.scope, group_id: group.name } },\n summary: () => `ungrouped ${group.id}`,\n ...instanceEdit(canvas, group, group.name),\n };\n },\n};\n\n// The operations a change can be. Each is one row: its name and how it\n// resolves the rest of the change.\nexport const OPERATIONS: readonly Operation[] = [\n place,\n connect,\n disconnect,\n set,\n bind,\n clear,\n rename,\n remove,\n ungroup,\n];\n\ntype Outcome =\n | {\n readonly kind: 'applied';\n readonly summary: string;\n readonly record: ChangeRecord;\n // The canvas the apply produced.\n readonly canvas: CanvasReading;\n // What the report of the change withholds beside its own value: every\n // value of the call the canvas did not name when the change was\n // ranked.\n readonly withheld: readonly unknown[];\n }\n // The ask rule fired: the model's two readings each map to a change\n // System One is sure of.\n | { readonly kind: 'asked'; readonly lace: Reading; readonly alternative: Reading }\n | { readonly kind: 'notApplied'; readonly why: string }\n // The engine answered the apply, and the session's stream ended before\n // the frame that carries it: what the canvas holds cannot be read.\n | { readonly kind: 'unobserved'; readonly end: string };\n\n// What resolving one change leaves beside its outcome: the decisions made,\n// the question neither system decided where there was one, the lines the\n// result says with it, and, where System One's operation did not stand (the\n// move rule), why, in the result's words.\ntype Trail = {\n readonly decisions: Decision<unknown>[];\n undecided?: Undecided;\n readonly notes: string[];\n moved?: string;\n};\n\n// A question under System One's operation fell to System Two while the move\n// was on trial: the operation does not stand.\nclass Fell extends Error {\n constructor(readonly label: string) {\n super(`the ${label} fell to System Two`);\n }\n}\n\n// Whether the tool read an entry as holding more than the one change it\n// applied: its words name other candidates for a decision, or System One\n// read it as several changes.\nfunction heldMore(decisions: readonly Decision<unknown>[]): boolean {\n return decisions.some(\n (decision) =>\n decision.others.length > 0 ||\n (decision.kind === 'steps' && decision.option.value === 'several'),\n );\n}\n\n// A decision the two systems read, as against one the names settled.\nconst twoSystems = (decision: Decision<unknown>) => decision.composed !== null;\n\n// What the two systems composed of the decisions they read.\nconst composedOf = (decisions: readonly Decision<unknown>[]): Composed[] =>\n decisions.flatMap((decision) => (decision.composed === null ? [] : [decision.composed]));\n\n// Why System One's operation did not stand, in the result's words: a\n// question under it fell to the model's reading, or the change did not\n// resolve under it.\nfunction movedText(operation: string, error: unknown): string {\n return error instanceof Fell || error instanceof Undecided\n ? `the ${error.label} under Lace's ${operation} fell to your reading`\n : `Lace's ${operation} did not resolve: ${errorText(error)}`;\n}\n\n// The slots of a reading that state a fact: the operation by its id, a name\n// the canvas holds, or a registry module as `author/name`. Any other slot is\n// no statement: a paraphrase, a stale name, or a value.\nfunction statedFacts(names: ReadonlySet<string>, reading: Reading): Reading {\n const fact = (slot: Slot, name: string): boolean =>\n slot === 'operation'\n ? OPERATIONS.some((operation) => operation.id === name)\n : slot === 'module'\n ? moduleReferences(name)[0] === name\n : names.has(name);\n return Object.fromEntries(\n statedSlots(reading).flatMap((slot) => {\n const name = reading[slot];\n return name !== undefined && fact(slot, name) ? [[slot, name]] : [];\n }),\n );\n}\n\n// How the tool runs one apply of its own: as it is, or through the outcome\n// observer, which holds the frames that arrive while the apply is in flight\n// and reads the one at the revision it returned as the package's own.\nexport type OwnApply = (apply: () => Promise<ApplyResult>) => Promise<ApplyResult>;\n\nconst asItIs: OwnApply = (apply) => apply();\n\nasync function resolveAndApply(\n ports: CanvasToolPorts,\n own: OwnApply,\n change: Change,\n call: readonly unknown[],\n trail: Trail,\n notApplied: (why: string) => Outcome,\n): Promise<Outcome> {\n const canvas = readCanvas(await latest(ports.source));\n const names = canvasNames(canvas);\n // Every form of the change's own value is the placeholder in the request\n // and the statements, a form the canvas names included: it is never read\n // as a name. Every other value of the call stands as the placeholder in\n // them unless the canvas names it.\n const values = [...forms(change.values), ...unnamed(names, call)];\n const statementOf = (reading: Reading) =>\n withhold(renderReading(statedFacts(names, reading)), values);\n const statement = statementOf(change.reading);\n const alternative =\n change.alternative === undefined\n ? undefined\n : { statement: statementOf(change.alternative), reading: change.alternative };\n const statements = [statement, ...(alternative === undefined ? [] : [alternative.statement])];\n // Rendered once, cut to the room the longest statement leaves: this one\n // string is every rank call's request for the change and the request its\n // captures carry. A name is read from the developer's words around the\n // placeholder, never from the token.\n const request = renderRequest(\n change.request,\n values,\n statements.reduce((longest, each) => (each.length > longest.length ? each : longest)),\n );\n // A withheld text of the call still inside a word that is no canvas name,\n // in the request or in either statement: no rank call is made for the\n // change (its decision is still reported, with no capture).\n const rankable = !holdsValue(withhold([request, ...statements].join(' '), [...names]), values);\n const rank = ports.transport === undefined ? undefined : rankingClient(ports.transport).rank;\n if (!rankable && rank !== undefined) {\n trail.notes.push(\n \"This change's words or reading hold a value of the call inside a word, so Lace did not rank it.\",\n );\n }\n // `steps` is read under the model's reading alone: it decides only what\n // the result says, so it is never ranked under the alternative reading and\n // never asks.\n const main: Ask = {\n request,\n terms: termsOf(request.split(VALUE_PLACEHOLDER).join(' ')),\n statement,\n reading: change.reading,\n ...(rankable ? { rank } : {}),\n };\n const ask: Ask = { ...main, ...(alternative === undefined ? {} : { alternative }) };\n // Resolving into `into`: each decision is recorded there, and on the move's\n // trial a question under System One's operation that is not System One's\n // ends the trial.\n const resolvingInto = (into: Trail, trial: boolean): Resolving => ({\n canvas,\n request,\n values: change.values,\n ports,\n async pick(kind, label, options) {\n const decision = await decide(ask, kind, label, options);\n into.decisions.push(decision);\n if (trial && !moveStands(composedOf(into.decisions.slice(1)))) throw new Fell(label);\n return decision.option.value;\n },\n note: (line) => into.notes.push(line),\n });\n const planUnder = (decision: Decision<Operation>, into: Trail, trial: boolean) => {\n into.decisions.push(decision);\n return decision.option.value.plan(resolvingInto(into, trial));\n };\n\n const first = await decide(ask, 'operation', 'operation', operationOptions(OPERATIONS));\n const statedOperation = operationOptions(OPERATIONS).find(\n (each) => each.candidate.id === first.chat,\n );\n // The move rule, as part of planning: where System One took the operation\n // and System Two stated another, System One's stands only when every\n // question under it is System One's too and the change resolves under it.\n // Otherwise the change is resolved again under System Two's operation, and\n // only what comes of that is the change's outcome.\n const moveRule = async (): Promise<{ operation: Operation; plan: Plan }> => {\n if (\n first.how !== 'clm' ||\n statedOperation === undefined ||\n statedOperation.value === first.option.value\n ) {\n return { operation: first.option.value, plan: await planUnder(first, trail, false) };\n }\n const trial: Trail = { decisions: [], notes: [] };\n try {\n const planned = await planUnder(first, trial, true);\n trail.decisions.push(...trial.decisions);\n trail.notes.push(...trial.notes);\n return { operation: first.option.value, plan: planned };\n } catch (error) {\n trail.moved = withhold(movedText(first.option.value.id, error), change.values);\n // The operation the move refused does not stand for this change, so\n // it is no alternative the ask rule can hand back either.\n const standing: Decision<Operation> = {\n ...first,\n option: statedOperation,\n how: 'chat',\n composed: {\n took: 'chat',\n taken: statedOperation.candidate.id,\n clm: first.composed?.clm ?? null,\n differed: false,\n },\n alternative: first.alternative?.id === first.option.candidate.id ? null : first.alternative,\n };\n return { operation: statedOperation.value, plan: await planUnder(standing, trail, false) };\n }\n };\n const { operation, plan } = await moveRule();\n // Whether the entry held more than this change: words that name more\n // candidates for a decision than it holds say so; where they do not and\n // the two systems read any decision, System One reads this too (System\n // Two's answer is `one` by construction). It decides only what the result\n // says, never whether the change applies.\n const unread = trail.decisions.every((decision) => decision.others.length === 0);\n if (unread && main.rank !== undefined && trail.decisions.some(twoSystems)) {\n await decide(main, 'steps', 'steps', stepsOptions(), 'one').then((decision) =>\n trail.decisions.push(decision),\n );\n }\n if (change.values.length > 0 && !operation.takesValue && !heldMore(trail.decisions)) {\n trail.notes.push(\n `The \\`value\\` sent with this change was not used: ${operation.id} takes none.`,\n );\n }\n // The tool's reading is what its decisions picked, slot by slot. A slot of\n // the model's reading that names none of the candidates offered for it is\n // no opinion, said in one line.\n const lace: Reading = Object.assign({}, ...trail.decisions.map((each) => each.option.slots));\n const stated = statedSlots(change.reading);\n for (const slot of stated.filter(\n (slot) =>\n !trail.decisions.some((decision) =>\n decision.readings.some((each) => each[slot] === change.reading[slot]),\n ),\n )) {\n trail.notes.push(\n `Your reading's ${slot} ${change.reading[slot]} is not one of Lace's candidates${slot in lace ? `; Lace read ${lace[slot]}` : ''}.`,\n );\n }\n // The ask rule: where System One is sure of a different answer under the\n // model's alternative reading, nothing is applied and both come back.\n const asked = trail.decisions.filter(\n (decision) =>\n decision.alternative?.sure === true &&\n decision.alternative.id !== decision.option.candidate.id,\n );\n if (asked.length > 0) {\n return {\n kind: 'asked',\n lace,\n alternative: Object.assign(\n {},\n ...trail.decisions.map((decision) =>\n asked.includes(decision) ? decision.alternative?.slots : decision.option.slots,\n ),\n ),\n };\n }\n\n const result = await own(() => ports.editor.apply([plan.action]));\n if (!result.success) {\n const reasons = result.errors.map((error) => error.message).join('; ');\n return notApplied(`the engine refused it: ${reasons}`);\n }\n const after = readCanvas(await latest(ports.source));\n const record: ChangeRecord = {\n id: crypto.randomUUID(),\n target: plan.target(result),\n before: plan.before,\n after: plan.after(after, result),\n ...(result.revision === undefined ? {} : { revision: result.revision }),\n questions: trail.decisions.map((decision) => ({\n kind: decision.kind,\n candidates: decision.candidates.map((candidate) => candidate.id),\n })),\n reported: false,\n };\n return {\n kind: 'applied',\n summary: plan.summary(result),\n record,\n canvas: after,\n withheld: unnamed(names, call),\n };\n}\n\n// One change, whatever becomes of it: a failure of this change (a question\n// neither system decided, an engine that refused, a change that names\n// nothing the canvas offers) is this change's outcome and stops no other,\n// and so is an apply the engine answered whose frame the session's stream\n// ended before. A reason is text this module did not write, so the literal\n// the change carries is withheld from it: the input it was meant for may be\n// one the module marks sensitive.\nasync function runChange(\n ports: CanvasToolPorts,\n own: OwnApply,\n change: Change,\n call: readonly unknown[],\n trail: Trail,\n): Promise<Outcome> {\n const notApplied = (why: string): Outcome => ({\n kind: 'notApplied',\n why: withhold(why, change.values),\n });\n try {\n return await resolveAndApply(ports, own, change, call, trail, notApplied);\n } catch (error) {\n if (error instanceof ApplyUnobservedError) {\n return { kind: 'unobserved', end: withhold(endText(error.end), change.values) };\n }\n if (error instanceof Undecided) {\n trail.undecided = error;\n const candidates = error.candidates.map((candidate) => candidate.id).join(', ');\n return notApplied(\n `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.`,\n );\n }\n return notApplied(errorText(error));\n }\n}\n\n// System One's reading in a result's words: not sure, with its pick, or why\n// it gave none.\nfunction rankingText(ranking: Ranking): string {\n if (ranking.ranked === null) return ranking.failed;\n const [first] = ranking.ranked.scores;\n const read =\n first?.id === NONE_CANDIDATE_ID ? `read ${NONE_OVER} first` : `ranked ${first?.id} first`;\n return `Lace was not sure, ${read}`;\n}\n\n// One decision in the result's words: what it holds and how. `moved` is\n// why System One's operation did not stand, said of the operation that did.\nfunction decisionLine(decision: Decision<unknown>, moved: string | undefined): string {\n const also = `the request also names ${decision.others.join(', ')}`;\n const named = {\n exact: ['named in the request'],\n unique: ['named in the request, ignoring case'],\n first: ['named in the request first', also],\n agreed: ['named in the request and in your reading', also],\n };\n const basis =\n decision.how === 'clm'\n ? [\n `Lace's pick of ${decision.offered}`,\n ...(decision.offered > decision.candidates.length\n ? [`ranked in parts, as ${decision.offered} candidates are more than one ranking holds`]\n : []),\n ...decision.over.map((candidate) => `over ${candidate}`),\n ...(decision.composed?.differed ? [`your reading named ${decision.chat}`] : []),\n ]\n : decision.how === 'chat'\n ? [\n 'your reading',\n moved !== undefined && decision.kind === 'operation'\n ? moved\n : decision.ranking === null\n ? 'Lace did not rank'\n : rankingText(decision.ranking),\n ]\n : named[decision.how];\n return ` ${decision.label}: ${decision.option.candidate.id} (${basis.join(', ')})`;\n}\n\nfunction outcomeLines(number: number, outcome: Outcome, trail: Trail): string[] {\n const head = `Change ${number}:`;\n const lines = trail.decisions.map((decision) => decisionLine(decision, trail.moved));\n switch (outcome.kind) {\n case 'applied': {\n const moved =\n trail.moved === undefined\n ? ''\n : \" Lace's operation did not stand and yours did, marked below.\";\n const unsure = trail.decisions.some(\n (decision) =>\n decision.how === 'chat' && (trail.moved === undefined || decision.kind !== 'operation'),\n );\n const stood = unsure ? ' Where Lace was not sure, your reading stood, marked below.' : '';\n const differed = trail.decisions.some((decision) => decision.composed?.differed)\n ? \" Lace's reading differed from yours and stood, marked below: tell the developer.\"\n : '';\n const others = trail.decisions.flatMap((decision) => decision.others);\n const unapplied = others.length > 0 ? `; nothing was applied for ${others.join(', ')}` : '';\n const more = heldMore(trail.decisions)\n ? ` This entry held more than one change and only this one was applied${unapplied}. Send the rest, one entry per change.`\n : '';\n return [`${head} applied. ${outcome.summary}.${more}${moved}${stood}${differed}`, ...lines];\n }\n case 'asked':\n return [\n `${head} not applied. Lace is sure your alternative reading means another change than the one it decided.`,\n ` Your reading: ${renderReading(outcome.lace)}`,\n ` Your alternative reading: ${renderReading(outcome.alternative)}`,\n ' Ask the developer which is meant, then send that one.',\n ];\n case 'notApplied':\n return [`${head} not applied. Reason: ${outcome.why}`, ...lines];\n case 'unobserved':\n return [\n `${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.`,\n ...lines,\n ];\n }\n}\n\n// A decision as the report of its change holds it: the capture of the\n// question as asked, none where the ranking spanned parts (`asAsked`), so\n// every candidate a question names is one of the capture it names.\nfunction questionOf(decision: Decision<unknown>): Question {\n const taken = decision.option.candidate.id;\n return {\n kind: decision.kind,\n capture_id: asAsked(decision.ranking)?.capture_id ?? null,\n chat: decision.chat,\n clm: decision.composed?.clm ?? null,\n took: decision.composed === null ? 'named' : decision.composed.took,\n taken,\n };\n}\n\n// The question neither system decided, as the report holds it.\nfunction undecidedOf(undecided: Undecided): Question {\n const ranked = asAsked(undecided.ranking);\n const pick = ranked === null ? undefined : pickOf(ranked.scores);\n return {\n kind: undecided.kind,\n capture_id: ranked?.capture_id ?? null,\n chat: null,\n clm: pick === undefined ? null : { id: pick.id, rightness: pick.rightness },\n took: 'chat',\n taken: null,\n };\n}\n\n// The report of one change, or none where no question went to the two\n// systems: nothing was captured, and there is nothing to grade.\nfunction reportOf(id: string, trail: Trail, applied: string | null, asked: boolean) {\n const questions = [\n ...trail.decisions.map(questionOf),\n ...(trail.undecided === undefined ? [] : [undecidedOf(trail.undecided)]),\n ];\n return questions.some((question) => question.took !== 'named')\n ? { id, surface: 'canvas' as const, questions, applied, asked }\n : undefined;\n}\n\n// Applies the changes in order, each against the state the one before it\n// produced. `text` says per change what was applied or why nothing was, and\n// `applied` holds the record of each change that was applied, in order.\n//\n// One call is one request: a later change of the call is part of what the\n// developer asked for, not an outcome of an earlier one. So each earlier\n// record follows its instance through every later change, and every record's\n// `after` is read from the canvas the whole call left, which is the first\n// frame the outcome observer folds it over. The record keeps the names the\n// call left, so the fold can follow them; the report says them with every\n// value of the call the canvas did not name when the change was ranked\n// withheld. Each change's decision is reported once the call is done,\n// through the transport, where there is one. Every apply runs through `own`.\nexport async function applyChanges(\n ports: CanvasToolPorts,\n changes: readonly Change[],\n own: OwnApply = asItIs,\n): Promise<{ text: string; applied: ChangeRecord[] }> {\n const call = changes.flatMap((change) => change.values);\n const client = ports.transport === undefined ? undefined : rankingClient(ports.transport);\n const lines: string[] = [];\n let applied: { record: ChangeRecord; withheld: readonly unknown[]; trail: Trail }[] = [];\n const reports: DecisionReport[] = [];\n let last: CanvasReading | undefined;\n for (const [index, change] of changes.entries()) {\n const trail: Trail = { decisions: [], notes: [] };\n const outcome = await runChange(ports, own, change, call, trail);\n lines.push(\n ...outcomeLines(index + 1, outcome, trail),\n ...trail.notes.map((line) => ` ${line}`),\n );\n if (outcome.kind === 'applied') {\n const { canvas } = outcome;\n const before = last;\n applied = [\n ...(before === undefined\n ? []\n : applied.map((each) => ({ ...each, record: follow(each.record, before, canvas) }))),\n { record: outcome.record, withheld: outcome.withheld, trail },\n ];\n last = canvas;\n } else if (outcome.kind !== 'unobserved') {\n const report = reportOf(crypto.randomUUID(), trail, null, outcome.kind === 'asked');\n if (report !== undefined) reports.push(report);\n }\n }\n const left = last;\n const records =\n left === undefined\n ? []\n : applied.map(({ record, withheld, trail }) => {\n const settled = { ...record, after: targetState(left, record) };\n const report = reportOf(record.id, trail, appliedText(settled, withheld), false);\n if (report !== undefined) reports.push(report);\n return { ...settled, reported: report !== undefined && client !== undefined };\n });\n if (client !== undefined) await Promise.all(reports.map((report) => client.decision(report)));\n return { text: lines.join('\\n'), applied: records };\n}\n\n// What a change did, in the report's words: what it addressed and its state\n// before and after, with every value of the call the canvas did not name\n// when the change was ranked withheld.\nfunction appliedText(record: ChangeRecord, withheld: readonly unknown[]): string {\n return withhold(\n `${renderTarget(record.target)}: ${renderState(record.before)} → ${renderState(record.after)}`,\n withheld,\n );\n}\n","// One command run to its end through the `commands` port, and the documents\n// a model reads of the three commands the tools run: each trimmed to what a\n// model needs to answer the developer.\nimport {\n type ArgsOf,\n type BoundPath,\n CommandExitError,\n type CommandFailure,\n type CommandsPort,\n type JsonOf,\n} from '@lace-cloud/canvas/engine';\nimport { moduleId } from './enumerate';\nimport { errorText } from './registration';\n\n// Why a command did not exit cleanly: `text` says it to a model, and\n// `failure` is the command's failure document when it wrote one (its\n// `reason`, its `message` and the fields the reason carries), which a host\n// branches on. A command that printed its result and then exited non-zero,\n// and a transport that broke, carry no document.\nexport type CommandEnd = {\n readonly text: string;\n readonly failure?: CommandFailure;\n};\n\n// What a command wrote before it ended, and why it ended when it did not\n// exit cleanly. A command can do both: `module validate` prints its report\n// and exits non-zero on a tree that is not in Lace style.\nexport type CommandOutput<P extends BoundPath> = {\n readonly documents: readonly JsonOf<P>[];\n readonly failed?: CommandEnd;\n};\n\n// A failure document in words: the reason by its wire spelling, or the\n// API's own code when the API decided it (as errorText says a refused\n// engine call), the command's own message, and the page the reason points\n// at when it names one.\nfunction failureText(path: BoundPath, failure: CommandFailure): string {\n const see = failure.url === undefined ? '' : `; see ${failure.url}`;\n const why = failure.apiCode ?? failure.reason;\n return `lace ${path} failed (reason ${why}): ${failure.message}${see}`;\n}\n\nfunction commandEnd(path: BoundPath, error: unknown): CommandEnd {\n if (!(error instanceof CommandExitError)) {\n return { text: `lace ${path} did not finish cleanly (${errorText(error)})` };\n }\n if (error.failure !== undefined) {\n return { text: failureText(path, error.failure), failure: error.failure };\n }\n return {\n text: `lace ${path} did not finish cleanly (exit ${error.code}: ${error.stderrTail})`,\n };\n}\n\nexport async function runCommand<P extends BoundPath>(\n commands: CommandsPort,\n path: P,\n args: ArgsOf<P>,\n): Promise<CommandOutput<P>> {\n const documents: JsonOf<P>[] = [];\n try {\n for await (const document of commands.invoke(path, args, new AbortController().signal).events) {\n documents.push(document);\n }\n } catch (error) {\n return { documents, failed: commandEnd(path, error) };\n }\n return { documents };\n}\n\n// A run as a tool result's text: each document through its trim, then why\n// the command did not exit cleanly.\nexport function commandText<P extends BoundPath>(\n run: CommandOutput<P>,\n trim: (document: JsonOf<P>) => unknown,\n): string {\n return [\n ...run.documents.map((document) => JSON.stringify(trim(document))),\n ...(run.failed === undefined ? [] : [run.failed.text]),\n ].join('\\n');\n}\n\nexport function trimValidate(report: JsonOf<'module validate'>): unknown {\n return {\n verdict: report.verdict,\n exitClass: report.exitClass,\n diagnostics: report.diagnostics,\n residuals: report.residuals?.map(({ construct, subject, file, line, guidance }) => ({\n construct,\n subject,\n file,\n line,\n guidance,\n })),\n terraform: report.terraform,\n };\n}\n\nexport function trimRegistryList(list: JsonOf<'registry list'>): unknown {\n return {\n modules: list.items.map((row) => ({\n module: moduleId(row),\n version: row.version,\n name: row.displayName,\n description: row.description,\n system: row.system,\n categories: row.categories,\n })),\n truncated: list.truncated,\n };\n}\n\nexport function trimRegistryDescribe(described: JsonOf<'registry describe'>): unknown {\n return {\n module: moduleId(described),\n version: described.version,\n source: described.source,\n verdict: described.verdict,\n inputs: described.interface.inputs,\n outputs: described.interface.outputs,\n };\n}\n","// The one enumeration: what the canvas offers for each decision a change\n// needs. `readCanvas` is the only fold over the Bundle in this package, and\n// it folds through proto's projection (`projectCanvasView`), inspection\n// (`deriveNodeConfig`) and instance resolution (`resolveInstance`) alone; every candidate list below, and the canvas\n// renderer, read its result. Whether an input is sensitive is the callee's\n// own mark in the Bundle (`InputDef.sensitive` on its interface), read by\n// the module key the projection names. A candidate carries the prose the\n// ranking scores and the references a request can name it by.\nimport type { CanvasSource, JsonOf, WiringCandidate } from '@lace-cloud/canvas/engine';\nimport {\n deriveNodeConfig,\n projectCanvasView,\n type RenderEdge,\n type RenderInput,\n type RenderOutput,\n resolveInstance,\n} from '@lace-cloud/proto';\nimport {\n type Candidate,\n type CandidateFacts,\n connectionId,\n type InputState,\n type InstanceRole,\n type PinFacts,\n pinRef,\n type Reading,\n renderCandidate,\n} from '../../questions';\n\n// An instance's input as the inspection derives it (its binding's mode and\n// content), with the mark the callee's interface puts on it.\nexport type CanvasInput = RenderInput & { readonly sensitive: boolean };\n\n// One instance on the canvas: a module call, or a group (a call whose module\n// has calls of its own). `id` is its canvas path, unique on the canvas;\n// `name` is its id inside `scope`, the module key of the module that owns\n// it, which is how an action addresses it.\nexport type CanvasInstance = {\n readonly id: string;\n readonly name: string;\n readonly scope: string;\n readonly module: string;\n readonly inputs: readonly CanvasInput[];\n readonly outputs: readonly RenderOutput[];\n};\n\nexport type CanvasGroup = {\n readonly id: string;\n readonly members: readonly string[];\n};\n\nexport type CanvasReading = {\n readonly module: string;\n // The entry module's key: the scope a placed module lands in.\n readonly entry: string;\n readonly instances: readonly CanvasInstance[];\n readonly wires: readonly RenderEdge[];\n readonly groups: readonly CanvasGroup[];\n};\n\nexport function readCanvas(source: CanvasSource): CanvasReading {\n const { bundle } = source;\n const view = projectCanvasView(bundle, undefined, {\n canUndo: source.canUndo,\n canRedo: source.canRedo,\n unsaved: source.unsaved,\n });\n const calls = [...view.nodes, ...view.groups];\n const instances = calls.flatMap((call): CanvasInstance[] => {\n const owner = resolveInstance(bundle, call.id);\n const config = deriveNodeConfig(bundle, call.id);\n if (owner === null || config === null || call.module_key === undefined) return [];\n const declared = bundle.modules[call.module_key]?.interface?.inputs ?? [];\n const sensitive = new Set(declared.filter((def) => def.sensitive).map((def) => def.name));\n return [\n {\n id: call.id,\n name: owner.child.id,\n scope: owner.scopeKey,\n module: call.module_key,\n inputs: config.inputs.map((input) => ({ ...input, sensitive: sensitive.has(input.name) })),\n outputs: config.outputs,\n },\n ];\n });\n return {\n module: view.module_name,\n entry: bundle.entry,\n instances,\n wires: view.edges,\n groups: view.groups.map((group) => ({ id: group.id, members: group.node_ids })),\n };\n}\n\n// The names a canvas holds: each instance's canvas path and its name in its\n// scope, the keys of its module and of its scope, and its inputs' and\n// outputs' names. Every candidate the lists below build is named by these,\n// so a value equal to one is a canvas fact the ranking already sees.\nexport function canvasNames(canvas: CanvasReading): ReadonlySet<string> {\n return new Set(\n canvas.instances.flatMap((instance) => [\n instance.id,\n instance.name,\n instance.module,\n instance.scope,\n ...instance.inputs.map((input) => input.name),\n ...instance.outputs.map((output) => output.name),\n ]),\n );\n}\n\n// A reference names a candidate when every part of it is a term of the\n// request; a candidate is named when any of its references is.\nexport type Ref = readonly string[];\n\n// One member of a decision's closed set: its facts and the candidate the\n// ranking scores (rendered from them by `renderCandidate`), the references a\n// request names it by, the slots a reading names it by, and the thing it is.\nexport type Option<T> = {\n readonly facts: CandidateFacts;\n readonly candidate: Candidate;\n readonly refs: readonly Ref[];\n readonly slots: Reading;\n readonly value: T;\n};\n\n// An option whose candidate is its facts, rendered.\nfunction offered<T>(\n facts: CandidateFacts,\n rest: Omit<Option<T>, 'facts' | 'candidate'>,\n): Option<T> {\n return { facts, candidate: renderCandidate(facts), ...rest };\n}\n\n// A pin as an instance's facts hold it: its name, and what the module says\n// it is where it says.\nconst pinFacts = (pins: readonly { readonly name: string; readonly description?: string }[]) =>\n pins.map(\n (pin): PinFacts =>\n pin.description ? { name: pin.name, description: pin.description } : { name: pin.name },\n );\n\n// The inputs of an instance a wire can end at: those no wire feeds yet.\nfunction unwired(instance: CanvasInstance): CanvasInput[] {\n return instance.inputs.filter((input) => input.mode !== 'wired');\n}\n\n// An instance's facts in the role its question offers it in: a target's\n// inputs are those no wire feeds.\nfunction instanceFacts(instance: CanvasInstance, role: InstanceRole): CandidateFacts {\n return {\n id: instance.id,\n kind: 'instance',\n role,\n module: instance.module,\n inputs: pinFacts(role === 'target' ? unwired(instance) : instance.inputs),\n outputs: pinFacts(instance.outputs),\n };\n}\n\nexport function operationOptions<T extends { readonly id: string }>(\n operations: readonly T[],\n): Option<T>[] {\n return operations.map((operation) =>\n offered(\n { id: operation.id, kind: 'operation' },\n { refs: [[operation.id]], slots: { operation: operation.id }, value: operation },\n ),\n );\n}\n\n// The instance a change addresses, named by its canvas path or by its own id.\n// Its prose holds its inputs and outputs with what the module says each is.\nexport function instanceOptions(instances: readonly CanvasInstance[]): Option<CanvasInstance>[] {\n return instances.map((instance) =>\n offered(instanceFacts(instance, 'instance'), {\n refs: [[instance.id], [instance.name]],\n slots: { instance: instance.id },\n value: instance,\n }),\n );\n}\n\n// The instance a wire starts at. A request names it in that role by one of\n// its outputs (`net.id`); its bare name says nothing of the direction.\nexport function sourceOptions(instances: readonly CanvasInstance[]): Option<CanvasInstance>[] {\n return instances\n .filter((instance) => instance.outputs.length > 0)\n .map((instance) =>\n offered(instanceFacts(instance, 'source'), {\n refs: instance.outputs.map((output) => [pinRef(instance.id, output.name)]),\n slots: { sourceInstance: instance.id },\n value: instance,\n }),\n );\n}\n\n// The instance a wire ends at: another instance of the source's scope with\n// an input no wire feeds, named in that role by one of those inputs\n// (`app.subnet`).\nexport function targetOptions(\n instances: readonly CanvasInstance[],\n source: CanvasInstance,\n): Option<CanvasInstance>[] {\n return instances\n .filter((instance) => instance.scope === source.scope && instance.id !== source.id)\n .filter((instance) => unwired(instance).length > 0)\n .map((instance) =>\n offered(instanceFacts(instance, 'target'), {\n refs: unwired(instance).map((input) => [pinRef(instance.id, input.name)]),\n slots: { targetInstance: instance.id },\n value: instance,\n }),\n );\n}\n\nconst INPUT_STATE: Record<RenderInput['mode'], InputState> = {\n empty: 'not set',\n literal: 'set',\n variable: 'set',\n expression: 'set',\n wired: 'wired',\n};\n\n// An instance's inputs, the whole set or the part of it an operation works\n// on. The facts say whether an input is set and never what it is set to.\nexport function inputOptions(\n instance: CanvasInstance,\n inputs: readonly CanvasInput[],\n): Option<CanvasInput>[] {\n return inputs.map((input) =>\n offered(\n {\n id: input.name,\n kind: 'input',\n instance: instance.id,\n module: instance.module,\n type: input.type,\n required: input.required,\n state: INPUT_STATE[input.mode],\n ...(input.description === undefined ? {} : { description: input.description }),\n },\n { refs: [[input.name]], slots: { input: input.name }, value: input },\n ),\n );\n}\n\n// Whether an entry is one change or several. Nothing in a request names\n// either: System Two's answer is `one` by construction (the tool asks one\n// entry per change), and System One reads the words.\nexport type Steps = 'one' | 'several';\n\nconst STEPS: readonly Steps[] = ['one', 'several'];\n\nexport function stepsOptions(): Option<Steps>[] {\n return STEPS.map((id) => offered({ id, kind: 'steps' }, { refs: [], slots: {}, value: id }));\n}\n\nexport type RegistryRow = JsonOf<'registry list'>['items'][number];\n\nexport function moduleId(row: { readonly author: string; readonly name: string }): string {\n return `${row.author}/${row.name}`;\n}\n\nexport function moduleOptions(rows: readonly RegistryRow[]): Option<RegistryRow>[] {\n return rows.map((row) =>\n offered(\n {\n id: moduleId(row),\n kind: 'module',\n displayName: row.displayName,\n description: row.description,\n system: row.system,\n categories: row.categories,\n },\n { refs: [[moduleId(row)], [row.name]], slots: { module: moduleId(row) }, value: row },\n ),\n );\n}\n\n// The output and the input one wire joins.\nexport type Connection = { readonly output: string; readonly input: string };\n\n// The output → input pairs a connect can wire between two instances: every\n// output of the source into every input of the target no wire feeds. The\n// engine's matcher scores the pairs it would choose among (`scored`, read for\n// these two instances), and each candidate's facts carry that score; a pair\n// the matcher leaves out (an optional input, a score of 0) is a candidate\n// all the same, with no score. A request names a pair by\n// naming both of its ends.\nexport function connectionOptions(\n source: CanvasInstance,\n target: CanvasInstance,\n scored: readonly WiringCandidate[],\n): Option<Connection>[] {\n const between = scored.filter(\n (each) => each.sourceInstance === source.name && each.targetInstance === target.name,\n );\n return source.outputs.flatMap((output) =>\n unwired(target).map((input) => {\n const pair = { output: output.name, input: input.name };\n const from = pinRef(source.id, pair.output);\n const to = pinRef(target.id, pair.input);\n const match = between.find(\n (each) => each.output === pair.output && each.input === pair.input,\n );\n return offered(\n {\n id: connectionId(from, to),\n kind: 'connection',\n source: source.id,\n output: pair.output,\n target: target.id,\n input: pair.input,\n ...(match === undefined ? {} : { score: match.score }),\n },\n { refs: [[from, to]], slots: pair, value: pair },\n );\n }),\n );\n}\n","// A tool registration whose handler always answers: a thrown error is the\n// call's result, said in the error's own words, never a rejection the host's\n// chat has to translate.\nimport { ConnectError, type Reason, reasonWire } from '@lace-cloud/canvas/engine';\nimport type { ToolHandler, ToolRegistration } from '../../contract/tool-registry';\nimport type { ToolResult, ToolSchema } from '../../contract/types';\n\n// The input a model sent is not the shape the tool's schema states.\nexport class InvalidInput extends Error {}\n\n// A reason in a result's words, spelled as a failure document spells it.\nexport function reasonText(reason: Reason): string {\n return `reason ${reasonWire(reason)}`;\n}\n\n// A thrown error in words: its message, and for a refused engine call the\n// reason it carries, or the API's own code when the API decided it.\nexport function errorText(error: unknown): string {\n if (error instanceof ConnectError) {\n const reason =\n error.apiCode === undefined ? reasonText(error.reason) : `reason ${error.apiCode}`;\n return `${error.message} (${reason})`;\n }\n return error instanceof Error ? error.message : String(error);\n}\n\n// `failed` makes the tool's own result of a failure: a tool whose result\n// carries more than text states what that part is when the call threw.\nexport function registrationOf<R extends ToolResult>(\n schema: ToolSchema,\n run: ToolHandler<R>,\n failed: (failure: ToolResult) => R,\n): ToolRegistration<R> {\n return {\n schema,\n async handler(input) {\n try {\n return await run(input);\n } catch (error) {\n return failed({ content: errorText(error), isError: true });\n }\n },\n };\n}\n\nexport function registration(schema: ToolSchema, run: ToolHandler): ToolRegistration {\n return registrationOf(schema, run, (failure) => failure);\n}\n\n// A tool that takes no input of its own. A host adds what only it knows\n// (which module root the call is for) beside the properties a tool states.\nexport const NO_INPUT = { type: 'object', properties: {}, additionalProperties: false };\n","// What happened next to an applied change, read from the session's frames\n// after it. `changeOutcomes` is a pure function of a change's record, the\n// frames and the revisions this package's own applies produced; the observer\n// composes it with the session's frames and reports each outcome once\n// through the ranking client. Every outcome is a move of the session's\n// state, and every such move reaches a subscriber as a frame (a command that\n// writes the tree reaches it as the frame of the re-derived IR), so the\n// frames are all it reads.\nimport { type CanvasSource, deepEqual } from '@lace-cloud/canvas/engine';\nimport type { ChangeOutcome, OutcomeReport } from '../../examples';\nimport { connectionId, pinRef } from '../../questions';\nimport { rankingClient, type Transport } from '../../ranking';\nimport type { ChangeRecord, ChangeState, InputBinding, OwnApply } from './change';\nimport { type CanvasInstance, type CanvasReading, readCanvas } from './enumerate';\n\nfunction instanceAt(\n canvas: CanvasReading,\n scope: string,\n name: string,\n): CanvasInstance | undefined {\n return canvas.instances.find((instance) => instance.scope === scope && instance.name === name);\n}\n\nexport function presenceOf(canvas: CanvasReading, scope: string, name: string): ChangeState {\n const instance = instanceAt(canvas, scope, name);\n return instance === undefined ? null : { instance: instance.name, module: instance.module };\n}\n\nexport function bindingOf(\n canvas: CanvasReading,\n scope: string,\n name: string,\n inputName: string,\n): ChangeState {\n const input = instanceAt(canvas, scope, name)?.inputs.find((each) => each.name === inputName);\n if (input === undefined) return null;\n if (input.sensitive) return { mode: input.mode };\n return {\n mode: input.mode,\n value: input.value,\n variable: input.variable,\n expression: input.expression,\n wiredSource: input.wired_source,\n };\n}\n\n// The instance a record's change lives at: the name the change left it with\n// (a rename's new name, a placement's own), else the name it addressed.\nfunction at({ target, after }: ChangeRecord): string {\n return after !== null && 'instance' in after ? after.instance : target.instance;\n}\n\n// The state on a canvas of what a record's change addressed: an input's\n// binding, or an instance's presence.\nexport function targetState(canvas: CanvasReading, record: ChangeRecord): ChangeState {\n const { scope, input } = record.target;\n return input === undefined\n ? presenceOf(canvas, scope, at(record))\n : bindingOf(canvas, scope, at(record), input);\n}\n\n// A record carried from one frame to the next. Grouping, ungrouping and a\n// rename move an instance without changing it, so when the instance the\n// record lives at was in `previous` and is gone from `frame`, the record\n// follows it: (i) to the one instance of its name and module in a scope where\n// `previous` held no instance of that name (a group, or an ungroup with no\n// collision); else (ii) to the one instance of its module in its scope that\n// `previous` did not hold (a rename). Rule (i) first, so grouping two\n// siblings of one module follows each by its name. Otherwise it stays, and\n// reads as gone.\nexport function follow(\n record: ChangeRecord,\n previous: CanvasReading,\n frame: CanvasReading,\n): ChangeRecord {\n const name = at(record);\n const { scope } = record.target;\n const was = instanceAt(previous, scope, name);\n if (was === undefined || instanceAt(frame, scope, name) !== undefined) return record;\n const fresh = frame.instances.filter(\n (each) =>\n each.module === was.module && instanceAt(previous, each.scope, each.name) === undefined,\n );\n const one = (found: readonly CanvasInstance[]) => (found.length === 1 ? found[0] : undefined);\n const moved =\n one(fresh.filter((each) => each.name === name)) ??\n one(fresh.filter((each) => each.scope === scope));\n if (moved === undefined) return record;\n const { after } = record;\n return {\n ...record,\n target: { ...record.target, scope: moved.scope, instance: moved.name },\n after: after !== null && 'instance' in after ? { ...after, instance: moved.name } : after,\n };\n}\n\n// What a change decided of a state: the answers of its closed questions as\n// the canvas holds them. An input's mode (the operation that writes it), with\n// the wire's source when wired (the pair), or an instance's module; `null`\n// where the target is gone (its instance or input). A new literal, another\n// variable or a new name is the developer's own value, not another\n// candidate, so it decides nothing.\nconst decided = (state: ChangeState): unknown =>\n state === null ? null : 'mode' in state ? [state.mode, state.wiredSource] : state.module;\n\n// Whether the change no longer stands as applied: an input's binding moved\n// in any part (a new value in the same mode included), an instance in what\n// was decided of it, since its name is the developer's.\nconst moved = (state: ChangeState, from: ChangeState): boolean =>\n state !== null && 'mode' in state\n ? !deepEqual(state, from)\n : !deepEqual(decided(state), decided(from));\n\n// The operation that writes an input's binding of each mode.\nconst OPERATION_OF_MODE: Partial<Record<InputBinding['mode'], string>> = {\n literal: 'set',\n variable: 'bind',\n empty: 'clear',\n wired: 'connect',\n};\n\n// The question of the record's decision a later edit of the target answers,\n// and the candidate it names, when one of the decision's questions holds it:\n// a binding in another mode names the operation that writes that mode; a\n// wire from another source names the connection. A new value in the same\n// mode is the developer's own and names nothing.\nfunction answered(\n record: ChangeRecord,\n state: ChangeState,\n canvas: CanvasReading,\n): Pick<OutcomeReport, 'question' | 'candidate'> {\n if (state === null || !('mode' in state) || record.target.input === undefined) return {};\n const name = (kind: string, candidate: string | undefined) => {\n const question = record.questions.findIndex(\n (each) =>\n each.kind === kind && candidate !== undefined && each.candidates.includes(candidate),\n );\n return question === -1 || candidate === undefined ? {} : { question, candidate };\n };\n const after = record.after;\n if (after !== null && 'mode' in after && after.mode !== state.mode) {\n return name('operation', OPERATION_OF_MODE[state.mode]);\n }\n if (state.mode !== 'wired' || state.wiredSource === undefined) return {};\n const [, source, output] = /^module\\.([^.]+)\\.(.+)$/.exec(state.wiredSource) ?? [];\n const { scope } = record.target;\n const from = instanceAt(canvas, scope, source ?? '');\n const to = instanceAt(canvas, scope, at(record));\n return from === undefined || to === undefined || output === undefined\n ? {}\n : name('connection', connectionId(pinRef(from.id, output), pinRef(to.id, record.target.input)));\n}\n\n// The outcomes of one frame, read against the frame before it (none for\n// the first frame given), the target's state on that frame (`was`; the\n// record's `after` for the first) and the revisions this package's own\n// applies produced (`own`). A frame that changes what the change decided,\n// to another answer than the change's own, is a hand edit when the package\n// did not produce it, the strongest label, and a change again when it did;\n// either names the question and candidate the edit answers when the fold can\n// tell. A frame that moves the target and changes nothing decided (a new\n// value in the same mode), or puts back the change's own answer, reaches no\n// outcome, and the change no longer stands as applied. While it stands, a\n// save is a frame that is saved after one that was not, a Generate one that\n// is generated after one that was not.\nfunction frameOutcomes(\n record: ChangeRecord,\n was: ChangeState,\n previous: CanvasSource | undefined,\n frame: CanvasSource,\n canvas: CanvasReading,\n own: ReadonlySet<number>,\n): OutcomeReport[] {\n const state = targetState(canvas, record);\n if (deepEqual(state, record.before)) return [{ event: 'reverted' }];\n const changes = (from: ChangeState) => !deepEqual(decided(state), decided(from));\n if (changes(was) && changes(record.after)) {\n const event = own.has(frame.revision) ? 'changed_again' : 'hand_edited';\n return [{ event, ...answered(record, state, canvas) }];\n }\n if (moved(state, record.after)) return [];\n const saved: OutcomeReport[] =\n previous?.unsaved === true && !frame.unsaved ? [{ event: 'saved' }] : [];\n const generated: OutcomeReport[] =\n previous?.ungenerated === true && !frame.ungenerated ? [{ event: 'generated' }] : [];\n return [...saved, ...generated];\n}\n\n// The outcomes a change reached over `frames`, each kind of event once as\n// first reached, in that order, and its record carried to the last frame. `frames` runs\n// from a frame the session delivered once the change was applied (its own,\n// or a later one) to the latest; `own` is every revision this package's\n// applies produced, the record's own by default. A frame's outcomes depend\n// on it, the frame before it and the record carried to it alone, so an\n// observer folds a session frame by frame: each new frame with the one it\n// last read and the record the fold last returned.\nexport function changeOutcomes(\n record: ChangeRecord,\n frames: readonly CanvasSource[],\n own: ReadonlySet<number> = new Set(record.revision === undefined ? [] : [record.revision]),\n): { readonly record: ChangeRecord; readonly outcomes: OutcomeReport[] } {\n const canvases = frames.map(readCanvas);\n const reached = new Map<ChangeOutcome, OutcomeReport>();\n let carried = record;\n frames.forEach((frame, index) => {\n const was = index > 0 ? targetState(canvases[index - 1], carried) : record.after;\n if (index > 0) carried = follow(carried, canvases[index - 1], canvases[index]);\n for (const outcome of frameOutcomes(\n carried,\n was,\n frames[index - 1],\n frame,\n canvases[index],\n own,\n )) {\n if (!reached.has(outcome.event)) reached.set(outcome.event, outcome);\n }\n });\n return { record: carried, outcomes: [...reached.values()] };\n}\n\n// The observer the canvas tool set composes with its session where it has a\n// transport: it reads the session frame by frame, follows the records of\n// each change-tool result whose decision was reported, folds each record\n// through `changeOutcomes` and reports each outcome once per record through\n// the transport. It is the one owner of the package's own revisions: the\n// change tool runs every apply through `own`, frames that arrive while an\n// apply is in flight are held until it resolves, and a held frame at the\n// revision it returned is the package's own, whether or not that change\n// was reported; any other is read as usual.\nexport type OutcomeObserver = {\n // Runs one apply of the package's own.\n readonly own: OwnApply;\n // Follows the records of one change-tool result whose decision was\n // reported; the frame the call left is their reference state.\n readonly follow: (records: readonly ChangeRecord[]) => void;\n // Reads one frame of the session.\n readonly frame: (source: CanvasSource) => void;\n};\n\nexport function outcomeObserver(transport: Transport): OutcomeObserver {\n const client = rankingClient(transport);\n const followed = new Map<string, { record: ChangeRecord; reported: Set<ChangeOutcome> }>();\n const own = new Set<number>();\n let previous: CanvasSource | undefined;\n // The package's applies in flight, the revisions those that resolved\n // returned while another was still in flight, and the frames held meanwhile.\n let flying = 0;\n const returned = new Set<number>();\n let held: CanvasSource[] = [];\n // A report the API refuses or the transport drops is one failed call,\n // which nothing retries: the client's posts settle either way.\n const fold = (source: CanvasSource): void => {\n const frames = previous === undefined ? [source] : [previous, source];\n previous = source;\n for (const [id, each] of followed) {\n const { record, outcomes } = changeOutcomes(each.record, frames, own);\n followed.set(id, { record, reported: each.reported });\n for (const outcome of outcomes.filter(({ event }) => !each.reported.has(event))) {\n each.reported.add(outcome.event);\n void client.outcome(id, outcome);\n }\n }\n };\n const landed = (revision: number | undefined): void => {\n flying -= 1;\n if (revision !== undefined) returned.add(revision);\n if (flying > 0) return;\n const frames = held;\n held = [];\n for (const frame of frames) {\n if (returned.has(frame.revision)) own.add(frame.revision);\n fold(frame);\n }\n returned.clear();\n };\n return {\n async own(apply) {\n flying += 1;\n let revision: number | undefined;\n try {\n const result = await apply();\n revision = result.success ? result.revision : undefined;\n return result;\n } finally {\n landed(revision);\n }\n },\n follow(records) {\n for (const record of records.filter((each) => each.reported)) {\n followed.set(record.id, { record, reported: new Set() });\n }\n },\n frame(source) {\n if (flying > 0) held.push(source);\n else fold(source);\n },\n };\n}\n","// The ports the tool sets take. A tool set is a function from its ports to\n// its registrations, so its capability is which ports it was given: a host\n// with no session cannot construct the canvas tools, one with a `commands`\n// port alone constructs the module tools, and one with no `transport`\n// constructs canvas tools that compose System Two alone and report nothing.\nimport type {\n ApplyUnobservedError,\n CanvasSource,\n CommandsPort,\n EditorPort,\n SourceEnd,\n SourcePort,\n} from '@lace-cloud/canvas/engine';\nimport type { Transport } from '../../ranking';\n\n// What the canvas tools do to a session: the mapping's own editor, without\n// conflict resolution, which the tools cannot reach since the canvas\n// confirms it. `apply` resolves once the source has delivered the state its\n// batch produced, so a read of the source after it sees that batch, and\n// `wiringCandidates` reads the engine matcher's scored pairs, the one\n// matching rule a canvas drag uses too.\nexport type CanvasEditor = Pick<EditorPort, 'apply' | 'save' | 'generate' | 'wiringCandidates'>;\n\nexport type CanvasToolPorts = {\n readonly source: SourcePort;\n readonly editor: CanvasEditor;\n readonly commands: CommandsPort;\n readonly transport?: Transport;\n};\n\nexport type ModuleToolPorts = {\n readonly commands: CommandsPort;\n};\n\n// How a session's stream ended, in a result's words: its kind, and what\n// failed it when it failed.\nexport function endText(end: ApplyUnobservedError['end']): string {\n return end.kind === 'failed' ? `failed: ${end.error.message}` : end.kind;\n}\n\nfunction endError(end: SourceEnd): Error {\n return end.kind === 'failed' ? end.error : new Error('the authoring session is closed');\n}\n\n// The source's latest frame: a source replays it to a subscriber that joins\n// late, and replays its end the same way when it has no frame to give.\nexport function latest(source: SourcePort): Promise<CanvasSource> {\n let unsubscribe = (): void => {};\n const frame = new Promise<CanvasSource>((resolve, reject) => {\n unsubscribe = source.subscribe(resolve, (end) => reject(endError(end)));\n });\n return frame.finally(() => unsubscribe());\n}\n","// The canvas as a model reads it, and what a change addressed and its state\n// in words. Pure functions of their arguments: every tool's result ends with\n// `renderCanvas` of the session's latest frame, so each call corrects the\n// model's picture of the canvas.\nimport type { CanvasSource } from '@lace-cloud/canvas/engine';\nimport { callText, type Diagnostic } from '@lace-cloud/proto';\nimport { VALUE_PLACEHOLDER } from '../../questions';\nimport type { ChangeState, ChangeTarget } from './change';\nimport { type CanvasInput, type CanvasInstance, readCanvas } from './enumerate';\n\nfunction inputText(input: CanvasInput): string {\n if (input.mode === 'empty') {\n return `${input.name} (${input.required ? 'required, ' : ''}not set)`;\n }\n if (input.mode === 'wired') return `${input.name} (wired)`;\n if (input.sensitive) return `${input.name} (sensitive, value withheld)`;\n const shown = {\n literal: JSON.stringify(input.value),\n variable: `var.${input.variable}`,\n expression: `${input.expression}`,\n };\n return `${input.name} = ${shown[input.mode]}`;\n}\n\nfunction instanceLines(instance: CanvasInstance): string[] {\n return [\n `- ${instance.id}: module ${instance.module}`,\n ` inputs: [${instance.inputs.map(inputText).join('; ')}]`,\n ` outputs: [${instance.outputs.map((output) => output.name).join(', ')}]`,\n ];\n}\n\nfunction unsetRequired(instance: CanvasInstance): string[] {\n return instance.inputs\n .filter((input) => input.required && input.mode === 'empty')\n .map((input) => `- ${instance.id}.${input.name}`);\n}\n\nfunction diagnosticLine(diagnostic: Diagnostic): string {\n const where = [\n ['instance', diagnostic.instance_id],\n ['input', diagnostic.input_name],\n ['address', diagnostic.address],\n ['file', diagnostic.file],\n ['line', diagnostic.line],\n ]\n .filter(([, value]) => value !== undefined)\n .map(([label, value]) => `${label} ${value}`);\n return `- ${[`${diagnostic.severity}: ${diagnostic.message}`, ...where].join('; ')}`;\n}\n\nconst yesNo = (flag: boolean): string => (flag ? 'yes' : 'no');\n\nfunction section(title: string, lines: readonly string[]): string[] {\n return [`${title} (${lines.length}):`, ...lines];\n}\n\n// The canvas of one frame: every instance with its module, its inputs (a\n// sensitive input's value withheld) and its outputs; the wires; the required\n// inputs that are not set; the groups; the engine's diagnostics; and the\n// session's standing.\nexport function renderCanvas(source: CanvasSource): string {\n const canvas = readCanvas(source);\n return [\n `Canvas of module ${canvas.module}`,\n `Instances (${canvas.instances.length}):`,\n ...canvas.instances.flatMap(instanceLines),\n ...section(\n 'Wires',\n canvas.wires.map(\n (wire) =>\n `- ${wire.source_output ? `${wire.source}.${wire.source_output}` : callText(wire.source)} → ${wire.target}.${wire.target_input}`,\n ),\n ),\n ...section('Required inputs not set', canvas.instances.flatMap(unsetRequired)),\n ...section(\n 'Groups',\n canvas.groups.map((group) => `- ${group.id}: ${group.members.join(', ')}`),\n ),\n ...section('Diagnostics', source.diagnostics.map(diagnosticLine)),\n [\n `Standing: unsaved edits: ${yesNo(source.unsaved)}`,\n `saved edits not generated to Terraform: ${yesNo(source.ungenerated)}`,\n `conflict with the Terraform on disk: ${yesNo(source.conflict !== null)}`,\n `Terraform refused, canvas locked: ${yesNo(source.sourceRefused)}`,\n ].join('; '),\n ].join('\\n');\n}\n\n// What a change addressed, in words: the instance, or the input of it, and\n// the module that owns the instance.\nexport function renderTarget(target: ChangeTarget): string {\n const pin = target.input === undefined ? target.instance : `${target.instance}.${target.input}`;\n return `${pin} in ${target.scope}`;\n}\n\n// What a change addressed, before or after it, holding no value: an input's\n// binding by its mode, its literal, variable or expression standing as the\n// placeholder (a wire is named by the output it comes from, a name on the\n// canvas), and an instance by its module alone, since its name after a\n// rename is what the developer gave.\nexport function renderState(state: ChangeState): string {\n if (state === null) return 'absent';\n if (!('mode' in state)) return `an instance of module ${state.module}`;\n const shown = {\n empty: 'not set',\n literal: `literal ${VALUE_PLACEHOLDER}`,\n variable: `variable ${VALUE_PLACEHOLDER}`,\n expression: `expression ${VALUE_PLACEHOLDER}`,\n wired: `wired from ${state.wiredSource}`,\n };\n return shown[state.mode];\n}\n","// Resolution of one decision, in order: the one candidate the request names\n// exactly; the one candidate it names when case is ignored; otherwise the two\n// systems read it. System Two's answer is the candidate its stated slot\n// names; System One's is its ranking's pick with a rightness, sure or not;\n// `compose` says whose stands (hybrid/compose.ts).\n//\n// A decision fills one slot of one change, so words that name several of\n// its candidates, each by a name of its own, name more than one change: the\n// pick is the one the model's reading names among them, else the first the\n// words name, and the others are kept for the result to say. Where a name is\n// shared by two candidates, or one named candidate lies inside another, the\n// names cannot tell one change from several, and the two systems read it.\n\nimport { type Composed, compose, pickOf, sure } from '../../hybrid';\nimport {\n type Candidate,\n type CandidateFacts,\n type DecisionKind,\n NONE_CANDIDATE_ID,\n RANK_CANDIDATES_MAX,\n type Reading,\n rankCandidates,\n statedSlots,\n} from '../../questions';\nimport type { Rank, Ranked } from '../../ranking';\nimport type { Option } from './enumerate';\n\n// The names a request holds, each with where it first stands in the\n// request: its words, its dotted references with every run of their parts\n// (`data.db.name` names `data.db` and `db.name` too), and its slashed\n// references (`author/name`). `folded` is the same in lower case, and\n// `words` the request's words in order, in lower case.\nexport type Terms = {\n readonly exact: ReadonlyMap<string, number>;\n readonly folded: ReadonlyMap<string, number>;\n readonly words: readonly string[];\n};\n\nconst WORD = /[A-Za-z0-9_-]+/g;\nconst DOTTED = /[A-Za-z0-9_-]+(?:\\.[A-Za-z0-9_-]+)+/g;\nconst SLASHED = /[A-Za-z0-9_-]+(?:\\/[A-Za-z0-9_-]+)+/g;\n\n// A name and the offset it stands at in the request.\ntype Found = { readonly term: string; readonly at: number };\n\nfunction found(text: string, pattern: RegExp): Found[] {\n return [...text.matchAll(pattern)].map((match) => ({ term: match[0], at: match.index }));\n}\n\n// Every run of a dotted reference's parts, each at the offset of its first\n// part.\nfunction runs({ term, at }: Found): Found[] {\n const parts = term.split('.');\n const starts = parts.map((_, index) => at + parts.slice(0, index).join('.').length + index);\n return parts.flatMap((_, start) =>\n parts.slice(start).map((_, length) => ({\n term: parts.slice(start, start + length + 1).join('.'),\n at: starts[start],\n })),\n );\n}\n\n// The registry modules a request refers to by reference: its `author/name`\n// words.\nexport function moduleReferences(text: string): string[] {\n return found(text, SLASHED).map((each) => each.term);\n}\n\n// Each name keyed as `key` spells it, at the first offset it stands at.\nfunction firstAt(names: readonly Found[], key: (term: string) => string): Map<string, number> {\n return names.reduce(\n (at, { term, at: offset }) => at.set(key(term), Math.min(offset, at.get(key(term)) ?? offset)),\n new Map<string, number>(),\n );\n}\n\nexport function termsOf(text: string): Terms {\n const names = [\n ...found(text, WORD),\n ...found(text, DOTTED).flatMap(runs),\n ...found(text, SLASHED),\n ];\n return {\n exact: firstAt(names, (term) => term),\n folded: firstAt(names, (term) => term.toLowerCase()),\n words: found(text, WORD).map(({ term }) => term.toLowerCase()),\n };\n}\n\n// The words a candidate covers: those of its id, its prose and its\n// references, each whole and in the parts `_` and `-` divide it into, in\n// lower case.\nfunction vocabulary(option: Option<unknown>): ReadonlySet<string> {\n const text = [option.candidate.id, option.candidate.text, ...option.refs.flat()].join(' ');\n return new Set(\n found(text.toLowerCase(), WORD).flatMap(({ term }) => [term, ...term.split(/[_-]/)]),\n );\n}\n\n// Words that name nothing: articles, prepositions, conjunctions, pronouns,\n// determiners and auxiliaries. A run of words holds them whoever covers them,\n// and a span does not count them, so \"the\" and \"to\" in a description name\n// nothing a request says.\nconst FUNCTION_WORDS: ReadonlySet<string> = new Set(\n '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(\n ' ',\n ),\n);\n\n// The span of the word at `index` that `covered` holds: how many words other\n// than function words stand in the longest run of consecutive words around\n// it that `covered` holds or that are function words; 0 when `covered` does\n// not hold the word.\nfunction span(words: readonly string[], index: number, covered: ReadonlySet<string>): number {\n if (!covered.has(words[index])) return 0;\n const outside = (word: string) => !covered.has(word) && !FUNCTION_WORDS.has(word);\n const before = words.slice(0, index).reverse().findIndex(outside);\n const after = words.slice(index + 1).findIndex(outside);\n return words\n .slice(before === -1 ? 0 : index - before, after === -1 ? words.length : index + 1 + after)\n .filter((word) => !FUNCTION_WORDS.has(word)).length;\n}\n\n// What a decision is resolved against: the request as the ranking reads it,\n// the names it holds, System Two's statement as words and its reading (no\n// slot stated when it gave none), its alternative reading where it gave one,\n// and the rank that asks System One, none where no transport ranks.\nexport type Ask = {\n readonly request: string;\n readonly terms: Terms;\n readonly statement: string;\n readonly reading: Reading;\n readonly alternative?: { readonly statement: string; readonly reading: Reading };\n readonly rank?: Rank;\n};\n\n// System One's reading of a question: its reply, or why it gave none.\nexport type Ranking =\n | { readonly ranked: Ranked; readonly parts: boolean }\n | { readonly ranked: null; readonly failed: string };\n\n// One resolved decision. `how` says which step resolved it: one name\n// (`exact`, `unique`), several names (`first`, the first the words name, or\n// `agreed`, the one the model's reading names among them), or the two\n// systems (`clm`, System One sure; `chat`, System Two's own answer).\n// `offered` is how many candidates it was picked from and `candidates` the\n// ones its question holds: all of them, or, for a set larger than one\n// ranking holds, the part that holds the pick. `others` are the candidates\n// the words also name for it, which this change did not use. `chat` is\n// System Two's candidate, `ranking` System One's reply (none where the names\n// settled it or nothing ranked), `composed` whose answer stands and whether\n// the two differed, `over` the candidates System One ranked next after its\n// pick (none of these first, when `(none)` outranked it), and `alternative`\n// System One's answer to the model's alternative reading, with whether it\n// was sure of it and the slots that name it. `readings` holds, for every\n// candidate offered, the slots a reading names it by.\nexport type Decision<T> = {\n readonly kind: DecisionKind;\n readonly label: string;\n readonly option: Option<T>;\n readonly how: 'exact' | 'unique' | 'first' | 'agreed' | 'clm' | 'chat';\n readonly offered: number;\n readonly candidates: readonly Candidate[];\n // The facts `candidates` were rendered from, in their order.\n readonly facts: readonly CandidateFacts[];\n readonly others: readonly string[];\n readonly chat: string | null;\n readonly ranking: Ranking | null;\n readonly composed: Composed | null;\n readonly over: readonly string[];\n readonly alternative: {\n readonly id: string;\n readonly sure: boolean;\n readonly slots: Reading;\n } | null;\n readonly readings: readonly Reading[];\n};\n\n// The canvas has nothing to pick from for a decision the change needs.\nexport class NothingOffered extends Error {\n constructor(readonly label: string) {\n super(`the canvas offers no ${label} for this change`);\n }\n}\n\n// Neither system resolved the decision: System One was not sure (or gave no\n// ranking) and the model's reading names no candidate of it. The candidates\n// are kept so the result can list them, and the ranking so the report holds\n// it.\nexport class Undecided extends Error {\n constructor(\n readonly kind: DecisionKind,\n readonly label: string,\n readonly candidates: readonly Candidate[],\n readonly ranking: Ranking,\n ) {\n super(`the ${label} was not decided`);\n }\n}\n\n// How many of the candidates ranked after the pick a result names.\nconst NAMED_ALTERNATIVES = 3;\n\n// How a result names `(none)` where it outranked the pick.\nexport const NONE_OVER = 'none of these';\n\n// A candidate the request names: the references that name it, and the\n// offset of the first of them in the request.\ntype Hit<T> = {\n readonly option: Option<T>;\n readonly refs: readonly (readonly string[])[];\n readonly at: number;\n};\n\n// The candidates a request names, in the order the request first names\n// them. The longest span of the words names. A dotted reference names each\n// run of its parts, so `data.cache` holds the words of three candidates: the\n// instance `data.cache`, the group `data`, and any other instance whose own\n// id is `cache`; the longer reference is the one the words spell, so a\n// candidate named only by single words that are each a segment of another\n// named candidate's dotted reference is not named. Likewise a single word\n// names nothing where, at each place it stands, another candidate's id,\n// prose or references cover a longer span of the request's words around it\n// than its own candidate's do, function words not counted: `admin` in \"the\n// orders database admin password\" is a word of the database's admin\n// password, not the instance `admin`, while `cluster` in \"upgrade the\n// cluster to Kubernetes\" names the instance `cluster`.\nfunction named<T>(\n options: readonly Option<T>[],\n { words }: Terms,\n terms: ReadonlyMap<string, number>,\n fold: (part: string) => string,\n): Hit<T>[] {\n const hits = options\n .map((option) => ({\n option,\n refs: option.refs\n .map((ref) => ref.map(fold))\n .filter((ref) => ref.every((part) => terms.has(part))),\n }))\n .filter((hit) => hit.refs.length > 0);\n const extended = (ref: readonly string[]): boolean =>\n ref.length === 1 &&\n hits.some((other) =>\n other.refs.some((longer) =>\n longer.some((part) => part !== ref[0] && part.split('.').includes(ref[0])),\n ),\n );\n const covers = new Map(options.map((option) => [option, vocabulary(option)]));\n const outspanned = (option: Option<T>, ref: readonly string[]): boolean => {\n const word = ref[0].toLowerCase();\n const places = words.flatMap((each, index) => (each === word ? [index] : []));\n const own = covers.get(option) ?? new Set<string>();\n return (\n ref.length === 1 &&\n !/[./]/.test(word) &&\n places.length > 0 &&\n places.every((index) =>\n options.some(\n (other) =>\n other !== option &&\n span(words, index, covers.get(other) ?? new Set()) > span(words, index, own),\n ),\n )\n );\n };\n const at = (ref: readonly string[]): number =>\n Math.min(...ref.map((part) => terms.get(part) ?? Number.POSITIVE_INFINITY));\n return hits\n .map((hit) => ({\n ...hit,\n refs: hit.refs.filter((ref) => !extended(ref) && !outspanned(hit.option, ref)),\n }))\n .filter((hit) => hit.refs.length > 0)\n .map((hit) => ({ ...hit, at: Math.min(...hit.refs.map(at)) }))\n .sort((a, b) => a.at - b.at);\n}\n\n// Whether the names tell the candidates they name apart, so each is a\n// candidate of its own: every one is named by a reference that names no\n// other, and none lies inside another (its id extends the other's by a\n// dotted part, as an instance's canvas path extends its group's).\nfunction apart<T>(hits: readonly Hit<T>[]): boolean {\n const key = (ref: readonly string[]) => ref.join(' ');\n return hits.every((hit) => {\n const others = hits.filter((other) => other !== hit);\n const own = hit.refs.some(\n (ref) => !others.some((other) => other.refs.some((each) => key(each) === key(ref))),\n );\n const inside = others.some((other) =>\n hit.option.candidate.id.startsWith(`${other.option.candidate.id}.`),\n );\n return own && !inside;\n });\n}\n\nconst NAME_STEPS = [\n {\n how: 'exact',\n hits: <T>(options: readonly Option<T>[], terms: Terms) =>\n named(options, terms, terms.exact, (part) => part),\n },\n {\n how: 'unique',\n hits: <T>(options: readonly Option<T>[], terms: Terms) =>\n named(options, terms, terms.folded, (part) => part.toLowerCase()),\n },\n] as const;\n\n// The candidates a reading names: those whose every slot the reading states\n// with the same name.\nexport function read<T>(options: readonly Option<T>[], reading: Reading): Option<T>[] {\n return options.filter((option) =>\n statedSlots(option.slots).every((slot) => reading[slot] === option.slots[slot]),\n );\n}\n\n// System Two's answer to a question: the one candidate its reading names,\n// or none.\nfunction answerOf<T>(options: readonly Option<T>[], reading: Reading): Option<T> | undefined {\n const named = read(options, reading);\n return named.length === 1 ? named[0] : undefined;\n}\n\n// The most real candidates one rank call carries: one place is `(none)`'s.\nconst PART = RANK_CANDIDATES_MAX - 1;\n\n// A set in parts of at most one ranking's worth of candidates, in its order.\nfunction partsOf<T>(items: readonly T[]): T[][] {\n return Array.from({ length: Math.ceil(items.length / PART) }, (_, n) =>\n items.slice(n * PART, (n + 1) * PART),\n );\n}\n\n// The part of a set that holds the candidate `id`.\nfunction partHolding(candidates: readonly Candidate[], id: string): readonly Candidate[] {\n return partsOf(candidates).find((part) => part.some((each) => each.id === id)) ?? [];\n}\n\n// The facts of the options a set of candidates was rendered from, in the\n// set's order.\nfunction factsOf<T>(options: readonly Option<T>[], part: readonly Candidate[]): CandidateFacts[] {\n const byId = new Map(options.map((option) => [option.candidate.id, option.facts]));\n return part.flatMap((candidate) => byId.get(candidate.id) ?? []);\n}\n\n// One ranking of a part: the candidates one rank call carried, its reply,\n// and the candidate it picked.\ntype PartRanking = {\n readonly part: readonly Candidate[];\n readonly ranked: Ranked;\n readonly pick: Candidate;\n};\n\n// One rank call over a part, with the statement given.\nasync function rankPart(\n rank: Rank,\n request: string,\n statement: string,\n kind: DecisionKind,\n part: readonly Candidate[],\n): Promise<PartRanking> {\n const ranked = await rank({ request, statement, candidates: rankCandidates(kind, part) });\n const pick = part.find((candidate) => candidate.id === pickOf(ranked.scores)?.id);\n if (pick === undefined) throw new Error('the ranking names no candidate of the set');\n return { part, ranked, pick };\n}\n\n// Ranks a set with calls of at most RANK_CANDIDATES_MAX candidates each. A\n// set within the bound is one call. A larger one is ranked part by part and\n// the parts' picks are ranked together, so no candidate is left out of the\n// ranking and no call carries more than the route admits; the answer is the\n// ranking of the part that holds the final pick.\nasync function rankWithin(\n rank: Rank,\n request: string,\n statement: string,\n kind: DecisionKind,\n candidates: readonly Candidate[],\n): Promise<PartRanking> {\n const parts = partsOf(candidates);\n if (parts.length === 1) return rankPart(rank, request, statement, kind, candidates);\n const rounds: PartRanking[] = [];\n for (const part of parts) rounds.push(await rankWithin(rank, request, statement, kind, part));\n const final = await rankWithin(\n rank,\n request,\n statement,\n kind,\n rounds.map((round) => round.pick),\n );\n const holding = rounds.find((round) => round.pick.id === final.pick.id);\n if (holding === undefined) throw new Error('the ranking names no candidate of the set');\n return holding;\n}\n\n// System One's reading of a question under `statement`: its reply over the\n// whole set, or why it gave none. A pick made across parts was never scored\n// against the whole set, so its ranking says so and is never sure.\nasync function ranking(\n ask: Ask,\n statement: string,\n kind: DecisionKind,\n candidates: readonly Candidate[],\n): Promise<{ readonly ranking: Ranking; readonly part: readonly Candidate[] }> {\n if (ask.rank === undefined) {\n return { ranking: { ranked: null, failed: 'Lace did not rank' }, part: candidates };\n }\n try {\n const { part, ranked } = await rankWithin(ask.rank, ask.request, statement, kind, candidates);\n return { ranking: { ranked, parts: part.length < candidates.length }, part };\n } catch (error) {\n const failed = `Lace could not rank: ${error instanceof Error ? error.message : String(error)}`;\n return { ranking: { ranked: null, failed }, part: candidates };\n }\n}\n\n// System One's reply to the question as asked: what `compose` reads and a\n// report holds. None where it gave none, and none where it ranked the set in\n// parts: a pick made across parts was never scored against the whole set, so\n// it is never sure, and no one capture holds every candidate of the\n// question, so no capture is the question's.\nexport const asAsked = (ranking: Ranking | null): Ranked | null =>\n ranking === null || ranking.ranked === null || ranking.parts ? null : ranking.ranked;\n\n// The two systems read a question the names left open. `stated` is System\n// Two's answer where the form states it (an entry is one change) rather\n// than its reading.\nasync function twoSystems<T>(\n ask: Ask,\n kind: DecisionKind,\n label: string,\n options: readonly Option<T>[],\n stated?: T,\n): Promise<Decision<T>> {\n const candidates = options.map((option) => option.candidate);\n const readings = options.map((option) => option.slots);\n const chat =\n stated === undefined\n ? answerOf(options, ask.reading)\n : options.find((option) => option.value === stated);\n const read = await ranking(ask, ask.statement, kind, candidates);\n const composed = compose({\n kind,\n chat: chat?.candidate.id ?? null,\n ranked: asAsked(read.ranking),\n });\n const option = options.find((each) => each.candidate.id === composed.taken);\n if (option === undefined) throw new Undecided(kind, label, candidates, read.ranking);\n const alternative =\n ask.alternative === undefined\n ? null\n : await ranking(ask, ask.alternative.statement, kind, candidates).then(({ ranking }) => {\n const ranked = asAsked(ranking);\n const pick = ranked === null ? undefined : pickOf(ranked.scores);\n const named = options.find((each) => each.candidate.id === pick?.id);\n return pick === undefined || ranked === null || named === undefined\n ? null\n : { id: pick.id, sure: sure(ranked, kind), slots: named.slots };\n });\n const ranked = read.ranking.ranked;\n const others =\n ranked === null ? [] : ranked.scores.filter((score) => score.id !== NONE_CANDIDATE_ID);\n const part = composed.took === 'clm' ? read.part : partHolding(candidates, option.candidate.id);\n return {\n kind,\n label,\n option,\n how: composed.took,\n offered: candidates.length,\n candidates: part,\n facts: factsOf(options, part),\n others: [],\n chat: chat?.candidate.id ?? null,\n ranking: read.ranking,\n composed,\n over: [\n ...(ranked?.scores[0]?.id === NONE_CANDIDATE_ID ? [NONE_OVER] : []),\n ...others.slice(1, NAMED_ALTERNATIVES + 1).map((score) => score.id),\n ],\n alternative,\n readings,\n };\n}\n\n// The decision the words settle, when they do: the first name step that\n// names any candidate decides. One candidate is the pick. Several, each a\n// candidate of its own, are more than the slot holds: the pick is the one\n// the model's reading names among them, else the first named, and the rest\n// are the decision's `others`. Names that do not tell their candidates\n// apart settle nothing.\nfunction byName<T>(\n ask: Ask,\n kind: DecisionKind,\n label: string,\n options: readonly Option<T>[],\n): Decision<T> | undefined {\n const settled = (option: Option<T>, how: Decision<T>['how'], hits: readonly Hit<T>[]) => ({\n kind,\n label,\n option,\n how,\n offered: options.length,\n candidates: options.map((each) => each.candidate),\n facts: options.map((each) => each.facts),\n others: hits.filter((hit) => hit.option !== option).map((hit) => hit.option.candidate.id),\n chat: answerOf(options, ask.reading)?.candidate.id ?? null,\n ranking: null,\n composed: null,\n over: [],\n alternative: null,\n readings: options.map((each) => each.slots),\n });\n const step = NAME_STEPS.map((each) => ({\n how: each.how,\n hits: each.hits(options, ask.terms),\n })).find((each) => each.hits.length > 0);\n if (step === undefined) return undefined;\n if (step.hits.length === 1) return settled(step.hits[0].option, step.how, step.hits);\n if (!apart(step.hits)) return undefined;\n const agreed = read(\n step.hits.map((hit) => hit.option),\n ask.reading,\n );\n return agreed.length === 1\n ? settled(agreed[0], 'agreed', step.hits)\n : settled(step.hits[0].option, 'first', step.hits);\n}\n\nexport async function decide<T>(\n ask: Ask,\n kind: DecisionKind,\n label: string,\n options: readonly Option<T>[],\n stated?: T,\n): Promise<Decision<T>> {\n if (options.length === 0) throw new NothingOffered(label);\n return byName(ask, kind, label, options) ?? twoSystems(ask, kind, label, options, stated);\n}\n","// The module tools: the tools that run one command and need no session. A\n// host constructs them from a `commands` port alone. Each runs exactly one\n// command and returns its document trimmed to what a model needs, or why\n// the command failed.\nimport type { BoundPath, CommandFailure, JsonOf } from '@lace-cloud/canvas/engine';\nimport type { ToolRegistration } from '../../contract/tool-registry';\nimport type { ToolResult, ToolSchema } from '../../contract/types';\nimport {\n type CommandOutput,\n commandText,\n runCommand,\n trimRegistryDescribe,\n trimRegistryList,\n trimValidate,\n} from './commands';\nimport type { ModuleToolPorts } from './ports';\nimport { InvalidInput, NO_INPUT, registrationOf } from './registration';\n\nconst VALIDATE: ToolSchema = {\n name: 'lace_validate_module_terraform',\n title: 'Validate module Terraform',\n description:\n \"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.\",\n inputSchema: NO_INPUT,\n};\n\nconst SEARCH: ToolSchema = {\n name: 'lace_search_module_registry',\n title: 'Search module registry',\n description:\n 'Searches the Lace module registry. Returns each published module as `author/name` with its latest version, its description, its system and its categories.',\n inputSchema: {\n type: 'object',\n properties: {\n query: { type: 'string', description: 'Words to find in a module.' },\n system: { type: 'string', description: 'The system a module is for, such as `aws`.' },\n category: { type: 'string', description: 'A category a module is listed under.' },\n },\n additionalProperties: false,\n },\n};\n\nconst DESCRIBE: ToolSchema = {\n name: 'lace_describe_registry_module',\n title: 'Describe registry module',\n description:\n '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.',\n inputSchema: {\n type: 'object',\n properties: {\n module: { type: 'string', description: 'The module, as `author/name`.' },\n version: { type: 'string', description: 'A published version. Left out: the latest.' },\n },\n required: ['module'],\n additionalProperties: false,\n },\n};\n\n// The module tools' schemas as data, in the order `moduleTools` returns its\n// registrations: validate, registry search, registry describe. A host that\n// generates a manifest of the tools reads these without constructing the\n// set, and the set registers exactly these.\nexport const moduleToolSchemas: readonly [ToolSchema, ToolSchema, ToolSchema] = [\n VALIDATE,\n SEARCH,\n DESCRIBE,\n];\n\n// A module tool's result: the text its model reads, and beside it the\n// failure document of a command that failed and wrote one, for the host:\n// `failure.reason` is what a host branches on, never the text.\nexport type ModuleToolResult = ToolResult & { readonly failure?: CommandFailure };\n\n// The module tools in their order: validate, registry search, registry\n// describe.\nexport type ModuleTools = readonly [\n ToolRegistration<ModuleToolResult>,\n ToolRegistration<ModuleToolResult>,\n ToolRegistration<ModuleToolResult>,\n];\n\nfunction said<P extends BoundPath>(\n run: CommandOutput<P>,\n trim: (document: JsonOf<P>) => unknown,\n): ModuleToolResult {\n const failure = run.failed?.failure;\n return {\n content: commandText(run, trim),\n isError: run.failed !== undefined,\n ...(failure === undefined ? {} : { failure }),\n };\n}\n\n// A call that threw before its command ran wrote no failure document.\nfunction moduleTool(\n schema: ToolSchema,\n run: (input: Record<string, unknown>) => Promise<ModuleToolResult>,\n): ToolRegistration<ModuleToolResult> {\n return registrationOf<ModuleToolResult>(schema, run, (failure) => failure);\n}\n\n// A property a schema states as optional text: its text when the model sent\n// text, and otherwise not an argument of the command at all.\nfunction text(value: unknown): string | undefined {\n return typeof value === 'string' ? value : undefined;\n}\n\nexport function moduleTools({ commands }: ModuleToolPorts): ModuleTools {\n const [validate, search, describe] = moduleToolSchemas;\n return [\n moduleTool(validate, async () =>\n said(await runCommand(commands, 'module validate', {}), trimValidate),\n ),\n moduleTool(search, async (input) =>\n said(\n await runCommand(commands, 'registry list', {\n axis: 'module',\n query: text(input.query),\n system: text(input.system),\n category: text(input.category),\n }),\n trimRegistryList,\n ),\n ),\n moduleTool(describe, async (input) => {\n const module = text(input.module);\n if (module === undefined) throw new InvalidInput('`module` is the module as `author/name`');\n return said(\n await runCommand(commands, 'registry describe', {\n artifact: `module/${module}`,\n version: text(input.version),\n }),\n trimRegistryDescribe,\n );\n }),\n ];\n}\n"],"mappings":";AAmCO,SAAS,qBAAmC;AACjD,QAAM,UAAU,oBAAI,IAA8B;AAElD,SAAO;AAAA,IACL,SAAS,QAAQ,SAAS;AACxB,cAAQ,IAAI,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AAA,IACtE;AAAA,IACA;AAAA,MAAW;AAAA,MAAQ,OAAO,UACxB;AAAA,QACE,MAAM,WAAW,UAAU,iBAAiB;AAAA,UAC1C,MAAM;AAAA,UACN,OAAO,KAAK,MAAM,KAAK;AAAA,UACvB,QAAQ,KAAK,MAAM,MAAM;AAAA,UACzB,UAAU,KAAK,MAAM,QAAQ;AAAA,QAC/B,CAAC;AAAA,QACD;AAAA,MACF;AAAA,IACF;AAAA,IACA,WAAW,UAAU,OAAO,UAAU;AACpC,YAAM,SAAS,KAAK,MAAM,MAAM;AAChC,UAAI,WAAW,OAAW,OAAM,IAAI,aAAa,yCAAyC;AAC1F,aAAO;AAAA,QACL,MAAM,WAAW,UAAU,qBAAqB;AAAA,UAC9C,UAAU,UAAU,MAAM;AAAA,UAC1B,SAAS,KAAK,MAAM,OAAO;AAAA,QAC7B,CAAC;AAAA,QACD;AAAA,MACF;AAAA,IACF,CAAC;AAAA,EACH;AACF;","names":["text","text","names","at","ApplyUnobservedError","described","found","moved","text","at","_","names","ranking","named","option","read","ranked","isRecord","offered","instance","input","group","twoSystems","names","slot","ranking","read","moved","named","ApplyUnobservedError","said","text","DESCRIBE"]}
|