@lace-cloud/chat-core 0.27.0 → 0.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -175,7 +175,7 @@ var NO_INPUT = { type: "object", properties: {}, additionalProperties: false };
175
175
 
176
176
  // src/surfaces/canvas/commands.ts
177
177
  function commandEnd(path, error) {
178
- const { message, failure } = (0, import_engine2.failureSays)(error, { kind: "read", path });
178
+ const { message, failure } = (0, import_engine2.failureSays)(error);
179
179
  const failed = (why, see = "") => `lace ${path} failed (reason ${why}): ${message}${see}`;
180
180
  if (failure !== void 0) {
181
181
  const see = failure.url === void 0 ? "" : `; see ${failure.url}`;
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/contract/tool-registry.ts","../src/surfaces/canvas/canvas-tools.ts","../src/contract/cancel.ts","../src/surfaces/canvas/change.ts","../src/surfaces/canvas/commands.ts","../src/surfaces/canvas/enumerate.ts","../src/surfaces/canvas/registration.ts","../src/surfaces/canvas/ports.ts","../src/surfaces/canvas/resolve.ts","../src/surfaces/canvas/stated.ts","../src/surfaces/canvas/withhold.ts","../src/surfaces/canvas/render.ts","../src/surfaces/canvas/module-tools.ts"],"sourcesContent":["// Public surface of @lace-cloud/chat-core: the tools a host's chat calls\n// Lace through, host-free. A host's model calls them through the tool\n// contract, and the tool sets work on a module's canvas and the registry\n// through the ports the host supplies. No model port, no loop and no UI live\n// here: a host adapts the tools to its own chat and supplies the ports.\n\n// ── The tool contract: the registry a host fills, and the handler and\n// registration it holds; a tool's schema and its result ──\nexport {\n createToolRegistry,\n type ToolHandler,\n type ToolRegistration,\n type ToolRegistry,\n} from './contract/tool-registry';\nexport type { ToolResult, ToolSchema } from './contract/types';\n// ── The canvas surface: its tool sets, each a function from the ports it\n// needs to its registrations, and their schemas as data; the canvas\n// renderer ──\nexport {\n type CanvasEditor,\n type CanvasToolPorts,\n type CanvasTools,\n canvasToolSchemas,\n canvasTools,\n type ModuleToolPorts,\n type ModuleToolResult,\n type ModuleTools,\n moduleToolSchemas,\n moduleTools,\n renderCanvas,\n} from './surfaces/canvas';\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\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. `signal` is the host's cancellation of the call, where its chat has\n// one: once it aborts, the tool starts nothing further and stops waiting, and\n// what it already sent stands.\nexport type ToolHandler<R extends ToolResult = ToolResult> = (\n input: Record<string, unknown>,\n signal?: AbortSignal,\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 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. Each registration is a name, a description that carries\n// the tool's guidance to any host, an input schema and a handler, and says\n// nothing about the host's editor.\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 { Cancelled, untilCancelled } from '../../contract/cancel';\nimport type { ToolRegistration } from '../../contract/tool-registry';\nimport type { ToolResult, ToolSchema } from '../../contract/types';\nimport { applyChanges, OPERATIONS, parseChanges } from './change';\nimport { trimValidate } from './commands';\nimport { type CanvasToolPorts, endText, latest } from './ports';\nimport { errorText, InvalidInput, NO_INPUT, reasonText, registration } from './registration';\nimport { renderCanvas } from './render';\nimport type { StatedSlot } from './stated';\n\n// What each slot of a change names, as the canvas or the registry lists it.\nconst STATED_PROPERTIES: Record<StatedSlot, Record<string, unknown>> = {\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: its canvas path (`group.child`) or its own id.',\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: { type: 'string', description: 'The instance a connect wires from.' },\n output: { type: 'string', description: 'The output a connect wires from.' },\n targetInstance: { type: 'string', description: 'The instance a connect wires into.' },\n module: {\n type: 'string',\n description:\n 'The registry module a place adds, as `author/name`, and `author/name@version` to place a version other than the one the registry lists.',\n },\n};\n\nconst CHANGE: ToolSchema = {\n name: 'lace_change_module_canvas',\n title: 'Change module canvas',\n description: [\n 'Changes a Lace module canvas: places registry modules, wires and unwires instances, sets, binds and clears inputs, and renames, deletes and ungroups instances.',\n 'State each change as the canvas lists it: its `operation`, and each instance, input, output and registry module it works on by the name the canvas gives it.',\n \"Pass each literal the developer gave (an input's value, an instance's new name, the variable an input is bound to) in `value`, one change per entry.\",\n 'A connect that names no `output` and no `input` wires the two instances as the canvas does when one is dragged onto the other.',\n 'A change that names nothing on the canvas, or a name that fits several things, is not applied, and the result lists its candidates: ask the developer which is meant, or send the change again naming one.',\n 'A place whose module the registry lists nothing for points to lace_search_module_registry.',\n 'Every result carries the current canvas. 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 operation: {\n type: 'string',\n enum: OPERATIONS.map((operation) => operation.id),\n description: OPERATIONS.map((operation) => operation.text).join('; '),\n },\n ...STATED_PROPERTIES,\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>`).\",\n },\n },\n required: ['operation'],\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. Read it before a change when you do not know the names the canvas gives its instances, inputs and outputs.',\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 success says of the files it wrote. With no saved edits\n// left to generate, a Generate writes nothing, and the engine still\n// validates the Terraform on disk.\nfunction writtenText(written: readonly string[]): string {\n return written.length === 0\n ? 'Generated the Terraform: nothing was written.'\n : `Generated the Terraform. Files written: ${written.join(', ')}.`;\n}\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 Terraform\n// on disk, 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 writtenText(event.written),\n `lace module validate on the Terraform on disk: ${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// What a Save or a Generate says of a call its host cancelled: nothing is\n// sent once the call is cancelled, and one already sent is the engine's, goes\n// on, and is not undone.\nfunction cancelledSaid(operation: 'save' | 'Generate', sent: boolean): Said {\n return {\n text: sent\n ? `The call was cancelled after the ${operation} was sent: it goes on in the engine, and the canvas below may be from before it ends.`\n : `The call was cancelled before the ${operation} was sent: nothing was done.`,\n isError: false,\n };\n}\n\n// The canvas tools in their order: change, describe, save, generate.\nexport type CanvasTools = readonly [\n ToolRegistration,\n ToolRegistration,\n ToolRegistration,\n ToolRegistration,\n];\n\nexport function canvasTools(ports: CanvasToolPorts): CanvasTools {\n const [change, describe, save, generate] = canvasToolSchemas;\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 return [\n registration(change, async (input, signal) => {\n try {\n const text = await applyChanges(ports, parseChanges(input), signal);\n return answer([{ text, isError: false }]);\n } catch (error) {\n if (!(error instanceof InvalidInput)) throw error;\n return answer([{ text: errorText(error), isError: true }]);\n }\n }),\n registration(describe, () => answer([])),\n registration(save, async (_input, signal) =>\n answer(\n await attempt(async () => {\n if (signal?.aborted) return [cancelledSaid('save', false)];\n const saved: Said = { text: 'Saved the canvas.', isError: false };\n try {\n await untilCancelled(ports.editor.save(), signal);\n return [saved];\n } catch (error) {\n if (error instanceof Cancelled) return [cancelledSaid('save', true)];\n return [saved, unobserved(error)];\n }\n }),\n ),\n ),\n registration(generate, async (_input, signal) =>\n answer(\n await attempt(async () => {\n if (signal?.aborted) return [cancelledSaid('Generate', false)];\n const said: Said[] = [];\n const events = ports.editor.generate()[Symbol.asyncIterator]();\n try {\n for (\n let next = await untilCancelled(events.next(), signal);\n next.done !== true;\n next = await untilCancelled(events.next(), signal)\n ) {\n said.push(...generateSaid(next.value));\n }\n } catch (error) {\n if (error instanceof Cancelled) return [...said, cancelledSaid('Generate', true)];\n said.push(unobserved(error));\n }\n return said;\n }),\n ),\n ),\n ];\n}\n","// The host's cancellation of a call (the `signal` a handler takes), read the\n// one way everywhere in the package: a step not yet started is not started,\n// and a wait in progress ends; what was already sent goes on.\n\n// The host cancelled the call before the step that would have run.\nexport class Cancelled extends Error {\n constructor() {\n super('the call was cancelled');\n }\n}\n\n// Stops a call its host cancelled, at a step boundary.\nexport function stopIfCancelled(signal: AbortSignal | undefined): void {\n if (signal?.aborted) throw new Cancelled();\n}\n\n// `work`, or `Cancelled` once the call's signal aborts first: the call stops\n// waiting, and what `work` stands for goes on. The listener ends with the\n// wait.\nexport function untilCancelled<T>(work: Promise<T>, signal: AbortSignal | undefined): Promise<T> {\n if (signal === undefined) return work;\n let stop = (): void => {};\n const cancelled = new Promise<never>((_, fail) => {\n stop = () => fail(new Cancelled());\n if (signal.aborted) stop();\n else signal.addEventListener('abort', stop, { once: true });\n });\n return Promise.race([work, cancelled]).finally(() => signal.removeEventListener('abort', stop));\n}\n\n// A step that waits on something: not started once the call is cancelled,\n// and otherwise waited on until it is.\nexport function cancellable<T>(\n start: () => Promise<T>,\n signal: AbortSignal | undefined,\n): Promise<T> {\n if (signal?.aborted) return Promise.reject(new Cancelled());\n return untilCancelled(start(), signal);\n}\n","// The change tool's work: each change, stated as the canvas lists it,\n// resolved slot by slot against the canvas as it stands when the change is\n// reached, then applied as one action.\n//\n// A slot resolves by name (resolve.ts): one option is the change's, and a\n// name that fits several options, fits none, or is not stated where the\n// operation needs it leaves the change unapplied, with the candidates the\n// canvas or the registry lists for the slot, so the model can ask the\n// developer or send the change again. A connect that names no pin is sent as\n// the canvas sends a drag of one instance onto another (`auto_connect`); one\n// that names both pins is a connect of those pins into any input of the\n// target, wired or not, as a pin drag is; one that names a single pin lists\n// the pairs the engine's matcher reads for it. The change's value is\n// withheld where text the package does not write enters a result: an\n// engine's refusal, a command's failure, a stream's end, and each name the\n// change stated that a result says back (withhold.ts).\nimport { type ApplyResult, ApplyUnobservedError, InputMode } from '@lace-cloud/canvas/engine';\nimport { Cancelled, cancellable, stopIfCancelled } from '../../contract/cancel';\nimport { runCommand } from './commands';\nimport {\n type CanvasInput,\n type CanvasInstance,\n type CanvasReading,\n connectionId,\n instanceOptions,\n moduleId,\n moduleOptions,\n type Option,\n pairListing,\n pinOptions,\n pinRef,\n readCanvas,\n} from './enumerate';\nimport { type CanvasEditor, type CanvasToolPorts, endText, latest } from './ports';\nimport { errorText, InvalidInput } from './registration';\nimport { resolve } from './resolve';\nimport { STATED_SLOTS, type Stated, type StatedSlot, slotsStated } from './stated';\nimport { withhold } from './withhold';\n\n// One entry of the tool's input: its operation, the names it states slot by\n// slot, and the literal the developer gave, undefined where it gave none.\nexport type Change = {\n readonly operation: Operation;\n readonly stated: Stated;\n readonly value: unknown;\n};\n\n// A change that cannot be applied as it was sent.\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\nexport function parseChanges(input: Record<string, unknown>): Change[] {\n const { changes } = input;\n if (!Array.isArray(changes) || changes.length === 0) {\n throw new InvalidInput('`changes` is a list of one or more changes');\n }\n return changes.map((entry: unknown, index) => {\n const which = `change ${index + 1}`;\n if (!isRecord(entry)) throw new InvalidInput(`${which} is an object`);\n const operation = OPERATIONS.find((each) => each.id === entry.operation);\n if (operation === undefined) {\n const ids = OPERATIONS.map((each) => each.id).join(', ');\n throw new InvalidInput(`${which} needs \\`operation\\`: one of ${ids}`);\n }\n // An empty name states nothing, as an absent one does.\n const names = STATED_SLOTS.flatMap((slot) => {\n const name = entry[slot];\n if (!present(name) || name === '') return [];\n if (typeof name !== 'string') {\n throw new InvalidInput(`${which}: \\`${slot}\\` is a name, as the canvas lists it`);\n }\n return [[slot, name]];\n });\n return {\n operation,\n stated: Object.fromEntries(names),\n value: present(entry.value) ? entry.value : undefined,\n };\n });\n}\n\n// The most candidates a reason lists.\nconst LISTED = 12;\n\n// Names as a reason lists them: the first `LISTED`, and how many more.\nfunction listed(names: readonly string[]): string {\n const kept = names.slice(0, LISTED);\n const more = names.length - kept.length;\n return [...kept, ...(more > 0 ? [`and ${more} more`] : [])].join(', ');\n}\n\nconst candidates = (names: readonly string[]): string => `Candidates: ${listed(names)}.`;\n\n// Where a slot's names come from: the registry for a module, the canvas for\n// every other slot.\nconst listedBy = (slot: StatedSlot): string => (slot === 'module' ? 'registry' : 'canvas');\n\n// What a slot names when it names no one option: nothing, for a slot the\n// change does not state; or the name it states, fitting no option or\n// several, as a result says it back (withheld against the change's value).\ntype Unresolved =\n | { readonly kind: 'missing' }\n | { readonly kind: 'none'; readonly stated: string }\n | { readonly kind: 'several'; readonly stated: string; readonly names: readonly string[] };\n\ntype Named<T> = { readonly kind: 'one'; readonly value: T } | Unresolved;\n\n// Why a slot names no one option, then `instead`: what the model can name.\n// `label` says what the slot offers (\"instance\", \"input of app\").\nfunction unresolvedText(\n slot: StatedSlot,\n label: string,\n unresolved: Unresolved,\n instead: string,\n): string {\n switch (unresolved.kind) {\n case 'missing':\n return `this change states no \\`${slot}\\`. ${instead}`;\n case 'none':\n return `no ${label} is named \\`${unresolved.stated}\\`. ${instead}`;\n case 'several':\n return `\\`${unresolved.stated}\\` names more than one ${label}: ${listed(unresolved.names)}. Name one as the ${listedBy(slot)} lists it.`;\n }\n}\n\nconst nothingOffered = (label: string): string => `the canvas offers no ${label} for this change.`;\n\n// Several reasons as one: each a sentence, in the order the slots stand.\nfunction reasons(each: readonly string[]): string {\n return each.map((why, i) => (i === 0 ? why : why[0].toUpperCase() + why.slice(1))).join(' ');\n}\n\n// What a slot names among the options the canvas offers it: its option's\n// value, or why the change cannot be applied, listing the options.\ntype Picked<T> = { readonly value: T } | { readonly why: string };\n\nconst whyOf = (picked: Picked<unknown>): string[] => ('why' in picked ? [picked.why] : []);\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// and the change in words once the engine applied it, read from the apply's\n// result and the canvas it produced.\ntype Plan = {\n readonly action: Action;\n readonly summary: (result: ApplyResult, after: CanvasReading) => string;\n};\n\ntype Resolving = {\n readonly canvas: CanvasReading;\n readonly change: Change;\n readonly ports: CanvasToolPorts;\n // The call's cancellation, for what the plan waits on.\n readonly signal: AbortSignal | undefined;\n // What the name `stated` names in `slot` among `options`.\n readonly name: <T>(\n slot: StatedSlot,\n stated: string | undefined,\n options: readonly Option<T>[],\n ) => Named<T>;\n // What `slot` names among the canvas's `options`.\n readonly choose: <T>(slot: StatedSlot, label: string, options: readonly Option<T>[]) => Picked<T>;\n // What `slot` names among the canvas's `options`, or the change cannot be\n // applied.\n readonly pick: <T>(slot: StatedSlot, label: string, options: readonly Option<T>[]) => 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, what it does in the words the tool's schema gives\n// the model, the slots it names things by, whether it writes the literal a\n// change carries in `value`, and how it resolves the rest of a change.\ntype Operation = {\n readonly id: string;\n readonly text: string;\n readonly slots: readonly StatedSlot[];\n readonly takesValue: boolean;\n readonly plan: (resolving: Resolving) => Promise<Plan>;\n};\n\n// The literal the developer gave: the tool writes no value of its own.\nfunction given(change: Change, what: string): unknown {\n if (change.value === undefined) {\n throw new Unapplicable(`this change needs ${what}: pass it in \\`value\\`.`);\n }\n return change.value;\n}\n\nfunction givenName(change: Change, what: string): string {\n const name = given(change, what);\n if (typeof name !== 'string') throw new Unapplicable(`${what} is text: pass it in \\`value\\`.`);\n return name;\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\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: the instance\n// among every instance, and the input among those of its inputs whose\n// binding is in one of `modes`, so an operation is offered only the inputs\n// it can act on. `offered` says what those inputs are, of an instance.\nfunction pickInput(\n { canvas, pick }: Resolving,\n modes: readonly BindingMode[],\n offered: (instance: CanvasInstance) => string,\n) {\n const instance = pick('instance', 'instance', instanceOptions(canvas.instances));\n const inputs = instance.inputs.filter((input) => modes.includes(input.mode));\n const input = pick('input', offered(instance), pinOptions(inputs));\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\n// What a place says where the listing does not settle the module.\nconst SEARCH = 'Find it with lace_search_module_registry and name it as `author/name`.';\n\n// A registry module as a change states it: `author/name`, or the name\n// alone, and after `@` the version to place where it names one. `query` is\n// the name part, which the registry listing is narrowed by. An `@` that\n// names no version is no module a place can add.\nfunction moduleRef(stated: string) {\n const at = stated.lastIndexOf('@');\n if (at < 1) return { ref: stated, query: stated.split('/').at(-1) ?? '' };\n const ref = stated.slice(0, at);\n const version = stated.slice(at + 1);\n if (version === '') {\n throw new Unapplicable(\n '`module` ends in `@` with no version after it. Name the version, as `author/name@version`, or leave out `@` to place the version the registry lists.',\n );\n }\n return { ref, query: ref.split('/').at(-1) ?? '', version };\n}\n\nconst place: Operation = {\n id: 'place',\n text: 'place: add a registry module to the canvas as a new instance',\n slots: ['module'],\n takesValue: false,\n async plan({ change, ports, signal, name, note }) {\n const stated = change.stated.module === undefined ? undefined : moduleRef(change.stated.module);\n const version = stated?.version;\n if (stated === undefined || stated.query === '') {\n throw new Unapplicable(\n unresolvedText('module', 'registry module', { kind: 'missing' }, SEARCH),\n );\n }\n const listing = await cancellable(\n () =>\n runCommand(\n ports.commands,\n 'registry list',\n { axis: 'module', limit: CATALOG_LIMIT, query: stated.query },\n signal,\n ),\n signal,\n );\n if (listing.failed !== undefined) throw new Error(listing.failed.text);\n if (listing.documents.some((document) => 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 const module = name(\n 'module',\n stated.ref,\n moduleOptions(listing.documents.flatMap((document) => document.items)),\n );\n if (module.kind !== 'one') {\n throw new Unapplicable(unresolvedText('module', 'registry module', module, SEARCH));\n }\n const row = module.value;\n return {\n action: {\n place_module: { author: row.author, name: row.name, version: version ?? row.version },\n },\n summary: (result) =>\n `placed ${moduleId(row)} ${version === undefined ? row.version : withhold(version, change.value)} as ${result.created.map((ref) => ref.id).join(', ')}`,\n };\n },\n};\n\n// A connect that names no pin: the engine's matcher wires the two\n// instances, as a drag of one onto the other does, and the pairs it leaves\n// tied come back for the developer to choose between. A connect that wired\n// nothing changed nothing.\nfunction autoConnect(\n canvas: CanvasReading,\n source: CanvasInstance,\n target: CanvasInstance,\n ends: { scope: string; source_scope: string; source: string; target: string },\n note: (line: string) => void,\n): Plan {\n const between = (reading: CanvasReading) =>\n reading.wires\n .filter((wire) => wire.source === source.id && wire.target === target.id)\n .map((wire) =>\n connectionId(\n pinRef(wire.source, wire.source_output),\n pinRef(wire.target, wire.target_input),\n ),\n );\n const before = new Set(between(canvas));\n return {\n action: { auto_connect: ends },\n summary(result, after) {\n const wired = between(after).filter((wire) => !before.has(wire));\n const ties = result.ties.map((pair) =>\n connectionId(pinRef(source.id, pair.output), pinRef(target.id, pair.input)),\n );\n const choose = 'Send it again naming the `output` and the `input` the developer means.';\n if (wired.length === 0) {\n throw new Unapplicable(\n ties.length > 0\n ? `more than one pair fits equally well, so nothing was wired: ${listed(ties)}. ${choose}`\n : `the engine wired nothing from ${source.id} into ${target.id}.`,\n );\n }\n if (ties.length > 0) {\n note(`Not connected, more than one pair fits equally well: ${listed(ties)}. ${choose}`);\n }\n return `connected ${source.id} to ${target.id}: ${wired.join(', ')}`;\n },\n };\n}\n\nconst connect: Operation = {\n id: 'connect',\n text: 'connect: wire an output of one instance into an input of another',\n slots: ['sourceInstance', 'output', 'targetInstance', 'input'],\n takesValue: false,\n async plan({ canvas, change, ports, signal, choose, note }) {\n const instances = instanceOptions(canvas.instances);\n const sourcePicked = choose('sourceInstance', 'instance', instances);\n const targetPicked = choose('targetInstance', 'instance', instances);\n if (!('value' in sourcePicked) || !('value' in targetPicked)) {\n throw new Unapplicable(reasons([...whyOf(sourcePicked), ...whyOf(targetPicked)]));\n }\n const [source, target] = [sourcePicked.value, targetPicked.value];\n if (source.id === target.id) {\n throw new Unapplicable(\n `\\`sourceInstance\\` and \\`targetInstance\\` both name ${source.id}: a connect wires one instance into another.`,\n );\n }\n const ends = {\n scope: target.scope,\n source_scope: source.scope,\n source: source.name,\n target: target.name,\n };\n const stated = { output: change.stated.output, input: change.stated.input };\n if (stated.output === undefined && stated.input === undefined) {\n return autoConnect(canvas, source, target, ends, note);\n }\n const output =\n stated.output === undefined\n ? undefined\n : choose('output', `output of ${source.id}`, pinOptions(source.outputs));\n const input =\n stated.input === undefined\n ? undefined\n : choose('input', `input of ${target.id}`, pinOptions(target.inputs));\n const whys = [...(output ? whyOf(output) : []), ...(input ? whyOf(input) : [])];\n // A connect naming one pin lists the pairs the engine's matcher gives\n // for it, from its own read of the two instances.\n if (output === undefined || input === undefined) {\n const [named, unnamed] = output === undefined ? ['input', 'output'] : ['output', 'input'];\n const scored = await cancellable(\n () =>\n ports.editor.wiringCandidates({\n scope: ends.scope,\n sourceScope: ends.source_scope,\n source: ends.source,\n target: ends.target,\n }),\n signal,\n );\n const pairs = pairListing(source, target, scored, {\n ...(output && 'value' in output ? { output: output.value.name } : {}),\n ...(input && 'value' in input ? { input: input.value.name } : {}),\n });\n whys.push(\n `this change states \\`${named}\\` and no \\`${unnamed}\\`: state both, or neither to wire the two instances as the canvas does. ${\n pairs.length > 0\n ? candidates(pairs)\n : `The engine's matcher pairs no output of ${source.id} with an input of ${target.id}.`\n }`,\n );\n throw new Unapplicable(reasons(whys));\n }\n if (!('value' in output) || !('value' in input)) throw new Unapplicable(reasons(whys));\n const [from, to] = [output.value.name, input.value.name];\n return {\n action: { connect: { ...ends, source_output: from, target_input: to } },\n summary: () => `connected ${connectionId(pinRef(source.id, from), pinRef(target.id, to))}`,\n };\n },\n};\n\nconst disconnect: Operation = {\n id: 'disconnect',\n text: \"disconnect: remove the wire into an instance's input\",\n slots: ['instance', 'input'],\n takesValue: false,\n async plan(resolving) {\n const { instance, input } = pickInput(resolving, ['wired'], (of) => `wired input of ${of.id}`);\n return {\n action: {\n disconnect: { scope: instance.scope, target: instance.name, input_name: input.name },\n },\n summary: () => `disconnected ${pinRef(instance.id, input.name)}`,\n };\n },\n};\n\nconst set: Operation = {\n id: 'set',\n text: 'set: give an input of an instance a literal value',\n slots: ['instance', 'input'],\n takesValue: true,\n async plan(resolving) {\n const value = given(resolving.change, 'the value the developer gave');\n const { instance, input } = pickInput(resolving, EVERY_MODE, (of) => `input of ${of.id}`);\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 ${pinRef(instance.id, input.name)} ${shown}`,\n };\n },\n};\n\nconst bind: Operation = {\n id: 'bind',\n text: \"bind: make an input of an instance take its value from a variable of the module (`var.<name>`), so the module's caller sets it\",\n slots: ['instance', 'input'],\n takesValue: true,\n async plan(resolving) {\n const variable = variableName(givenName(resolving.change, \"the variable's name\"));\n const { instance, input } = pickInput(resolving, EVERY_MODE, (of) => `input of ${of.id}`);\n return {\n action: updateInput(instance, input, { mode: InputMode.INPUT_MODE_VARIABLE, variable }),\n summary: () => `bound ${pinRef(instance.id, input.name)} to var.${variable}`,\n };\n },\n};\n\nconst clear: Operation = {\n id: 'clear',\n text: 'clear: unset an input of an instance, removing the value, variable or expression it holds',\n slots: ['instance', 'input'],\n takesValue: false,\n async plan(resolving) {\n const { instance, input } = pickInput(\n resolving,\n ['literal', 'variable', 'expression'],\n (of) => `input of ${of.id} that holds a value`,\n );\n return {\n action: updateInput(instance, input, { mode: InputMode.INPUT_MODE_EMPTY }),\n summary: () => `cleared ${pinRef(instance.id, input.name)}`,\n };\n },\n};\n\nconst rename: Operation = {\n id: 'rename',\n text: 'rename: give an instance a new name',\n slots: ['instance'],\n takesValue: true,\n async plan({ canvas, change, pick }) {\n const name = givenName(change, 'the new name');\n const instance = 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 };\n },\n};\n\nconst remove: Operation = {\n id: 'delete',\n text: 'delete: remove an instance from the canvas',\n slots: ['instance'],\n takesValue: false,\n async plan({ canvas, pick }) {\n const instance = 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 };\n },\n};\n\nconst ungroup: Operation = {\n id: 'ungroup',\n text: 'ungroup: dissolve a group, moving the instances inside it up beside it',\n slots: ['instance'],\n takesValue: false,\n async plan({ canvas, pick }) {\n const groups = new Set(canvas.groups.map((group) => group.id));\n const group = 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 };\n },\n};\n\n// The operations a change can be. Each is one row: its name, what it does,\n// what it names, and how it 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 | { readonly kind: 'applied'; readonly summary: string }\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 // The host cancelled the call before this change's apply was sent.\n | { readonly kind: 'cancelled' }\n // An earlier change's apply went unobserved: the stream it would be read\n // on had ended, so this change was not sent.\n | { readonly kind: 'notRun' };\n\nconst CANCELLED: Outcome = { kind: 'cancelled' };\nconst NOT_RUN: Outcome = { kind: 'notRun' };\n\n// The lines a change says before it is resolved: each slot it states that\n// its operation does not use, and a value an operation that takes none was\n// sent.\nfunction unusedLines({ operation, stated, value }: Change): string[] {\n const unused = slotsStated(stated).filter((slot) => !operation.slots.includes(slot));\n return [\n ...unused.map((slot) => `\\`${slot}\\` is not used by ${operation.id}.`),\n ...(value !== undefined && !operation.takesValue\n ? [`The \\`value\\` sent with this change was not used: ${operation.id} takes none.`]\n : []),\n ];\n}\n\nasync function resolveAndApply(\n ports: CanvasToolPorts,\n change: Change,\n signal: AbortSignal | undefined,\n note: (line: string) => void,\n): Promise<Outcome> {\n const canvas = readCanvas(await latest(ports.source));\n const name = <T>(\n slot: StatedSlot,\n stated: string | undefined,\n options: readonly Option<T>[],\n ): Named<T> => {\n if (stated === undefined) return { kind: 'missing' };\n const resolved = resolve(options, stated);\n // The name as a result says it back.\n const echoed = withhold(stated, change.value);\n switch (resolved.kind) {\n case 'one': {\n const [listedAs] = resolved.option.names;\n const where = slot === 'module' ? 'in the registry' : 'on the canvas';\n if (resolved.folded) note(`Your \\`${slot}\\` ${echoed} is \\`${listedAs}\\` ${where}.`);\n return { kind: 'one', value: resolved.option.value };\n }\n case 'several':\n return {\n kind: 'several',\n stated: echoed,\n names: resolved.options.map((each) => each.names[0]),\n };\n case 'none':\n return { kind: 'none', stated: echoed };\n }\n };\n const choose = <T>(slot: StatedSlot, label: string, options: readonly Option<T>[]): Picked<T> => {\n if (options.length === 0) return { why: nothingOffered(label) };\n const named = name(slot, change.stated[slot], options);\n if (named.kind === 'one') return { value: named.value };\n const offered = options.map((option) => option.names[0]);\n return { why: unresolvedText(slot, label, named, candidates(offered)) };\n };\n const resolving: Resolving = {\n canvas,\n change,\n ports,\n signal,\n name,\n choose,\n pick(slot, label, options) {\n const picked = choose(slot, label, options);\n if ('why' in picked) throw new Unapplicable(picked.why);\n return picked.value;\n },\n note,\n };\n for (const line of unusedLines(change)) note(line);\n const plan = await change.operation.plan(resolving);\n // Nothing is applied once the call is cancelled; an apply already sent is\n // the engine's, and stands.\n stopIfCancelled(signal);\n const result = await ports.editor.apply([plan.action]);\n if (!result.success) {\n const refusals = result.errors.map((error) => error.message).join('; ');\n return {\n kind: 'notApplied',\n why: `the engine refused it: ${withhold(refusals, change.value)}`,\n };\n }\n const after = readCanvas(await latest(ports.source));\n return { kind: 'applied', summary: plan.summary(result, after) };\n}\n\n// One change, whatever becomes of it: a failure of this change (a slot that\n// names nothing or several things, an engine that refused, a listing that\n// failed) is this change's outcome and stops no other, and so is an apply\n// the engine answered whose frame the session's stream ended before. A\n// reason the package wrote is said as it is; any other failure's text, and\n// the account of a stream's end, are withheld against the change's value.\nasync function runChange(\n ports: CanvasToolPorts,\n change: Change,\n signal: AbortSignal | undefined,\n note: (line: string) => void,\n): Promise<Outcome> {\n try {\n return await resolveAndApply(ports, change, signal, note);\n } catch (error) {\n if (error instanceof ApplyUnobservedError) {\n return { kind: 'unobserved', end: withhold(endText(error.end), change.value) };\n }\n // The host cancelled the call before this change's apply was sent (a\n // listing or a wiring read no longer waited on). Anything once the apply\n // was sent is the apply's own outcome.\n if (error instanceof Cancelled) return CANCELLED;\n if (error instanceof Unapplicable) return { kind: 'notApplied', why: error.message };\n return { kind: 'notApplied', why: withhold(errorText(error), change.value) };\n }\n}\n\nfunction outcomeLine(number: number, outcome: Outcome): string {\n const head = `Change ${number}:`;\n switch (outcome.kind) {\n case 'applied':\n return `${head} applied. ${outcome.summary}.`;\n case 'notApplied':\n return `${head} not applied. Reason: ${outcome.why}`;\n case 'cancelled':\n return `${head} not applied. The call was cancelled before it applied.`;\n case 'unobserved':\n return `${head} sent, and the engine answered it, but the session's stream ended (${outcome.end}) before the canvas showed it, so whether it applied cannot be read here. Do not send it again before the canvas is open again.`;\n case 'notRun':\n return `${head} not run. The session's stream ended before it, so it was not sent.`;\n }\n}\n\n// Applies the changes in order, each against the state the one before it\n// produced, and says per change what was applied or why nothing was, with\n// the lines it noted beneath it. A summary shows the value the operation\n// wrote unless the input is sensitive.\n//\n// `signal` is the host's cancellation of the call. Once it aborts, nothing\n// further is started: a listing or wiring read in progress is no longer\n// waited on, and the change in progress and every later one say the call\n// was cancelled before they applied. Once an apply goes unobserved (the\n// session's stream ended before its frame), no later change is sent: the\n// stream that would show it has ended.\nexport async function applyChanges(\n ports: CanvasToolPorts,\n changes: readonly Change[],\n signal?: AbortSignal,\n): Promise<string> {\n const lines: string[] = [];\n let ended = false;\n for (const [index, change] of changes.entries()) {\n const notes: string[] = [];\n const outcome: Outcome = ended\n ? NOT_RUN\n : signal?.aborted\n ? CANCELLED\n : await runChange(ports, change, signal, (line) => notes.push(line));\n ended = ended || outcome.kind === 'unobserved';\n lines.push(\n outcomeLine(index + 1, outcome),\n ...(outcome.kind === 'cancelled' || outcome.kind === 'notRun'\n ? []\n : notes.map((line) => ` ${line}`)),\n );\n }\n return lines.join('\\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 type CommandFailure,\n type CommandsPort,\n ConnectError,\n failureSays,\n type JsonOf,\n} from '@lace-cloud/canvas/engine';\nimport { moduleId } from './enumerate';\nimport { refusalReason } 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// Why a command ended, in the chat's words around what the failure says\n// (`failureSays`, the one reading every surface shows): the command's path,\n// and the reason the failure names as data — a failure document's, or a\n// refusal's when the engine refused the call before the command started —\n// by its wire spelling, or the API's own code when the API decided it, and\n// the page a document's reason points at when it names one. The chat's\n// commands are reads, so a stream that ended under one says to run it\n// again.\nfunction commandEnd(path: BoundPath, error: unknown): CommandEnd {\n const { message, failure } = failureSays(error, { kind: 'read', path });\n const failed = (why: string, see = '') => `lace ${path} failed (reason ${why}): ${message}${see}`;\n if (failure !== undefined) {\n const see = failure.url === undefined ? '' : `; see ${failure.url}`;\n return { text: failed(failure.apiCode ?? failure.reason, see), failure };\n }\n if (error instanceof ConnectError) return { text: failed(refusalReason(error)) };\n return { text: `lace ${path} did not finish cleanly (${message})` };\n}\n\n// `signal` is the tool call's cancellation, which the port reads as the\n// consumer no longer listening: the call stops waiting, and the command keeps\n// whatever it already did.\nexport async function runCommand<P extends BoundPath>(\n commands: CommandsPort,\n path: P,\n args: ArgsOf<P>,\n signal: AbortSignal = new AbortController().signal,\n): Promise<CommandOutput<P>> {\n const documents: JsonOf<P>[] = [];\n try {\n for await (const document of commands.invoke(path, args, 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 each slot a change names, and\n// the names it offers each by. `readCanvas` is the only fold over the Bundle\n// in this package, and it folds through proto's projection\n// (`projectCanvasView`), inspection (`deriveNodeConfig`), instance\n// resolution (`resolveInstance`) and diagnostic-to-node mapping\n// (`nodeIdForDiagnostic`) alone; every option 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.\nimport type { CanvasSource, JsonOf, WiringCandidate } from '@lace-cloud/canvas/engine';\nimport {\n type Diagnostic,\n deriveNodeConfig,\n nodeIdForDiagnostic,\n projectCanvasView,\n type RenderEdge,\n type RenderInput,\n type RenderOutput,\n resolveInstance,\n} from '@lace-cloud/proto';\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\n// One of the engine's diagnostics, with the canvas path of the instance it\n// is about where proto's one diagnostic-to-node mapping finds one.\nexport type CanvasDiagnostic = {\n readonly diagnostic: Diagnostic;\n readonly node: string | null;\n};\n\nexport type CanvasReading = {\n readonly module: string;\n readonly instances: readonly CanvasInstance[];\n readonly wires: readonly RenderEdge[];\n readonly groups: readonly CanvasGroup[];\n readonly diagnostics: readonly CanvasDiagnostic[];\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 instances,\n wires: view.edges,\n groups: view.groups.map((group) => ({ id: group.id, members: group.node_ids })),\n diagnostics: source.diagnostics.map((diagnostic) => ({\n diagnostic,\n node: nodeIdForDiagnostic(view, diagnostic),\n })),\n };\n}\n\n// One thing a slot can name: the names it is named by, the one the canvas\n// lists it by first, and the thing.\nexport type Option<T> = {\n readonly names: readonly [string, ...string[]];\n readonly value: T;\n};\n\n// An instance, named by its canvas path, then by its own id.\nexport function instanceOptions(instances: readonly CanvasInstance[]): Option<CanvasInstance>[] {\n return instances.map((instance) => ({ names: [instance.id, instance.name], value: instance }));\n}\n\n// A pin of an instance, named by its name.\nexport function pinOptions<P extends { readonly name: string }>(pins: readonly P[]): Option<P>[] {\n return pins.map((pin) => ({ names: [pin.name], value: pin }));\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\n// A registry module, named as `author/name`, then by its name.\nexport function moduleOptions(rows: readonly RegistryRow[]): Option<RegistryRow>[] {\n return rows.map((row) => ({ names: [moduleId(row), row.name], value: row }));\n}\n\n// A wire's end as the canvas lists it: an instance's canvas path and the\n// pin's name.\nexport function pinRef(instance: string, pin: string): string {\n return `${instance}.${pin}`;\n}\n\n// A wire as the canvas lists it.\nexport function connectionId(from: string, to: string): string {\n return `${from} → ${to}`;\n}\n\n// The engine matcher's pairs from source into target (`scored`, its read\n// for the two), as a connect lists them: in the matcher's order, best\n// first, each with its score, held to the one pin the change named.\nexport function pairListing(\n source: CanvasInstance,\n target: CanvasInstance,\n scored: readonly WiringCandidate[],\n pin: { readonly output?: string; readonly input?: string },\n): string[] {\n return scored\n .filter((pair) => pair.sourceInstance === source.name && pair.targetInstance === target.name)\n .filter((pair) => pin.output === undefined || pair.output === pin.output)\n .filter((pair) => pin.input === undefined || pair.input === pin.input)\n .map(\n (pair) =>\n `${connectionId(pinRef(source.id, pair.output), pinRef(target.id, pair.input))} (score ${pair.score})`,\n );\n}\n","import { 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// The reason a refused engine call names: the API's own code when the API\n// decided it, else the reason it carries, spelled as a failure document\n// spells it.\nexport function refusalReason(error: ConnectError): string {\n return error.apiCode ?? reasonWire(error.reason);\n}\n\n// A thrown error in words: its message, and for a refused engine call the\n// reason it names.\nexport function errorText(error: unknown): string {\n if (error instanceof ConnectError) return `${error.message} (reason ${refusalReason(error)})`;\n return error instanceof Error ? error.message : String(error);\n}\n\n// A tool's registration, whose handler always answers: a thrown error is\n// the call's result, said in the error's own words, never a rejection the\n// host's chat has to translate. A tool whose result carries data for its\n// host beside the text (`E`, each part optional) answers a failure with\n// none of it.\nexport function registration<E extends object = object>(\n schema: ToolSchema,\n run: ToolHandler<ToolResult & Partial<E>>,\n): ToolRegistration<ToolResult & Partial<E>> {\n const none: Partial<E> = {};\n return {\n schema,\n async handler(input, signal) {\n try {\n return await run(input, signal);\n } catch (error) {\n return { ...none, content: errorText(error), isError: true };\n }\n },\n };\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","// 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, and one with a\n// `commands` port alone constructs the module tools.\nimport type {\n ApplyUnobservedError,\n CanvasSource,\n CommandsPort,\n EditorPort,\n SourceEnd,\n SourcePort,\n} from '@lace-cloud/canvas/engine';\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};\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","// One slot's resolution: the name a change states, matched against the\n// names of each option the slot offers, in four steps: exactly on an\n// option's first name (an instance's canvas path, a module's `author/name`),\n// exactly on any of its names, then each again ignoring case. The first step\n// with any hit decides: one hit is the option, several are ambiguous, and a\n// later step is never reached. No hit at any step is unmatched. Both sides\n// are compared in one Unicode form (NFC), so a name typed decomposed finds\n// the name the canvas holds composed.\nimport type { Option } from './enumerate';\n\nexport type Resolved<T> =\n | { readonly kind: 'one'; readonly option: Option<T>; readonly folded: boolean }\n | { readonly kind: 'several'; readonly options: readonly Option<T>[] }\n | { readonly kind: 'none' };\n\ntype Step = {\n // Whether the step ignores case.\n readonly folded: boolean;\n readonly names: (option: Option<unknown>) => readonly string[];\n};\n\nconst first = (option: Option<unknown>) => option.names.slice(0, 1);\nconst every = (option: Option<unknown>) => option.names;\n\nconst STEPS: readonly Step[] = [\n { folded: false, names: first },\n { folded: false, names: every },\n { folded: true, names: first },\n { folded: true, names: every },\n];\n\nexport function resolve<T>(options: readonly Option<T>[], stated: string): Resolved<T> {\n const step = STEPS.map((each) => {\n const key = (name: string) => {\n const normal = name.normalize('NFC');\n return each.folded ? normal.toLowerCase() : normal;\n };\n const hits = options.filter((option) =>\n each.names(option).some((name) => key(name) === key(stated)),\n );\n return { folded: each.folded, hits };\n }).find((each) => each.hits.length > 0);\n if (step === undefined) return { kind: 'none' };\n return step.hits.length === 1\n ? { kind: 'one', option: step.hits[0], folded: step.folded }\n : { kind: 'several', options: step.hits };\n}\n","// The names one change states, each in its own slot, as the canvas or the\n// registry lists them: an instance by its canvas path or its own id, a pin\n// by its name, a registry module as `author/name` or by its name.\nexport const STATED_SLOTS = [\n 'instance',\n 'input',\n 'sourceInstance',\n 'output',\n 'targetInstance',\n 'module',\n] as const;\n\nexport type StatedSlot = (typeof STATED_SLOTS)[number];\n\nexport type Stated = Readonly<Partial<Record<StatedSlot, string>>>;\n\n// The slots a change states, in slot order.\nexport function slotsStated(stated: Stated): StatedSlot[] {\n return STATED_SLOTS.filter((slot) => stated[slot] !== undefined);\n}\n","// What a result withholds of the value a change carries. The value is\n// withheld only from text the package does not write itself and that could\n// carry it: an engine's refusal, a command's failure, the account of a\n// session's stream ending, and each name the model stated that a result\n// says back. The package's own words, and the names the canvas or the\n// registry lists, are never withheld: they are public, and the canvas the\n// result ends with prints them.\n\n// The one token that stands where a value was.\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\nconst GO_ESCAPES: Readonly<Record<string, string>> = {\n '\\x07': '\\\\a',\n '\\b': '\\\\b',\n '\\f': '\\\\f',\n '\\n': '\\\\n',\n '\\r': '\\\\r',\n '\\t': '\\\\t',\n '\\v': '\\\\v',\n '\"': '\\\\\"',\n '\\\\': '\\\\\\\\',\n};\n\n// What Go's strconv counts printable: a letter, mark, number, punctuation\n// or symbol, or the ASCII space.\nconst GO_PRINTABLE = /^[ \\p{L}\\p{M}\\p{N}\\p{P}\\p{S}]$/u;\n\n// One character as Go's `%q` writes it inside quotes.\nfunction goEscaped(char: string): string {\n const code = char.codePointAt(0) ?? 0;\n if (GO_ESCAPES[char] !== undefined) return GO_ESCAPES[char];\n if (GO_PRINTABLE.test(char)) return char;\n const [mark, width] = code < 0x80 ? ['x', 2] : code < 0x10000 ? ['u', 4] : ['U', 8];\n return `\\\\${mark}${code.toString(16).padStart(width, '0')}`;\n}\n\n// Every form a literal is written in: itself; quoted with JSON's escapes;\n// quoted as Go's `%q` writes it, which is how the engine quotes a value it\n// names; and each quoted form's escapes unquoted.\nfunction writtenForms(literal: string): string[] {\n const quoted = [JSON.stringify(literal), `\"${[...literal].map(goEscaped).join('')}\"`];\n return [literal, ...quoted, ...quoted.map((form) => form.slice(1, -1))];\n}\n\n// The forms of a value's literals, longest first, so one that holds another\n// is replaced whole.\nfunction forms(value: unknown): string[] {\n const all = literalTexts(value)\n .filter((literal) => literal !== '')\n .flatMap(writtenForms);\n return [...new Set(all)].sort((a, b) => b.length - a.length);\n}\n\n// `text` as a pattern that matches it literally.\nfunction escapeRegExp(text: string): string {\n return text.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\nconst NAME = /^[A-Za-z0-9_-]+$/;\n\n// Where a form stands in a text, in any case. One that could be a name\n// stands where it is a token of its own, delimited by anything that is not a\n// letter, a digit, an underscore or a hyphen; one that holds any other\n// character is never a name and stands wherever it occurs.\nfunction occurrences(form: string): RegExp {\n const text = escapeRegExp(form);\n return NAME.test(form)\n ? new RegExp(`(?<![A-Za-z0-9_-])${text}(?![A-Za-z0-9_-])`, 'gi')\n : new RegExp(text, 'gi');\n}\n\n// `text`, a text the package did not write, with every occurrence of the\n// value replaced by the placeholder.\nexport function withhold(text: string, value: unknown): string {\n return forms(value).reduce(\n (rest, form) => rest.replace(occurrences(form), VALUE_PLACEHOLDER),\n text,\n );\n}\n","// The canvas as a model reads it: a pure function of one frame. Every canvas\n// tool's result ends with `renderCanvas` of the session's latest frame, so\n// each call corrects the model's picture of the canvas.\nimport type { CanvasSource } from '@lace-cloud/canvas/engine';\nimport { callText } from '@lace-cloud/proto';\nimport {\n type CanvasDiagnostic,\n type CanvasInput,\n type CanvasInstance,\n connectionId,\n pinRef,\n readCanvas,\n} 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) => `- ${pinRef(instance.id, input.name)}`);\n}\n\n// A diagnostic names its instance by its canvas path, so a grouped\n// instance is never read as a top-level one of the same id; one whose\n// instance no node is found for names it with the module it was found in.\nfunction diagnosticLine({ diagnostic, node }: CanvasDiagnostic): string {\n const scoped =\n diagnostic.module_key === undefined\n ? diagnostic.instance_id\n : `${diagnostic.instance_id} in module ${diagnostic.module_key}`;\n const instance = node ?? (diagnostic.instance_id === undefined ? undefined : scoped);\n const where = [\n ['instance', instance],\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 `- ${connectionId(\n wire.source_output ? pinRef(wire.source, wire.source_output) : callText(wire.source),\n pinRef(wire.target, wire.target_input),\n )}`,\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', canvas.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","// 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 { ToolHandler, 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, registration } 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 & Partial<ModuleToolData>;\n\ntype ModuleToolData = { 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: ToolHandler<ModuleToolResult>,\n): ToolRegistration<ModuleToolResult> {\n return registration<ModuleToolData>(schema, run);\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 (_input, signal) =>\n said(await runCommand(commands, 'module validate', {}, signal), trimValidate),\n ),\n moduleTool(search, async (input, signal) =>\n said(\n await runCommand(\n commands,\n 'registry list',\n {\n axis: 'module',\n query: text(input.query),\n system: text(input.system),\n category: text(input.category),\n },\n signal,\n ),\n trimRegistryList,\n ),\n ),\n moduleTool(describe, async (input, signal) => {\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(\n commands,\n 'registry describe',\n { artifact: `module/${module}`, version: text(input.version) },\n signal,\n ),\n trimRegistryDescribe,\n );\n }),\n ];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAA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AQ;AAC7C;AAEO,SAAS,YAAY,EAAE,SAAS,GAAiC;AACtE,QAAM,CAAC,UAAU,QAAQ,QAAQ,IAAI;AACrC,SAAO;AAAA,IACL;AAAA,MAAW;AAAA,MAAU,OAAO,QAAQ,WAClC,KAAK,MAAM,WAAW,UAAU,mBAAmB,CAAC,GAAG,MAAM,GAAG,YAAY;AAAA,IAC9E;AAAA,IACA;AAAA,MAAW;AAAA,MAAQ,OAAO,OAAO,WAC/B;AAAA,QACE,MAAM;AAAA,UACJ;AAAA,UACA;AAAA,UACA;AAAA,YACE,MAAM;AAAA,YACN,OAAO,KAAK,MAAM,KAAK;AAAA,YACvB,QAAQ,KAAK,MAAM,MAAM;AAAA,YACzB,UAAU,KAAK,MAAM,QAAQ;AAAA,UAC/B;AAAA,UACA;AAAA,QACF;AAAA,QACA;AAAA,MACF;AAAA,IACF;AAAA,IACA,WAAW,UAAU,OAAO,OAAO,WAAW;AAC5C,YAAMC,UAAS,KAAK,MAAM,MAAM;AAChC,UAAIA,YAAW,OAAW,OAAM,IAAI,aAAa,yCAAyC;AAC1F,aAAO;AAAA,QACL,MAAM;AAAA,UACJ;AAAA,UACA;AAAA,UACA,EAAE,UAAU,UAAUA,OAAM,IAAI,SAAS,KAAK,MAAM,OAAO,EAAE;AAAA,UAC7D;AAAA,QACF;AAAA,QACA;AAAA,MACF;AAAA,IACF,CAAC;AAAA,EACH;AACF;","names":["import_engine","import_engine","import_engine","resolve","text","text","input","module","group","import_proto","said","text","SEARCH","DESCRIBE","module"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/contract/tool-registry.ts","../src/surfaces/canvas/canvas-tools.ts","../src/contract/cancel.ts","../src/surfaces/canvas/change.ts","../src/surfaces/canvas/commands.ts","../src/surfaces/canvas/enumerate.ts","../src/surfaces/canvas/registration.ts","../src/surfaces/canvas/ports.ts","../src/surfaces/canvas/resolve.ts","../src/surfaces/canvas/stated.ts","../src/surfaces/canvas/withhold.ts","../src/surfaces/canvas/render.ts","../src/surfaces/canvas/module-tools.ts"],"sourcesContent":["// Public surface of @lace-cloud/chat-core: the tools a host's chat calls\n// Lace through, host-free. A host's model calls them through the tool\n// contract, and the tool sets work on a module's canvas and the registry\n// through the ports the host supplies. No model port, no loop and no UI live\n// here: a host adapts the tools to its own chat and supplies the ports.\n\n// ── The tool contract: the registry a host fills, and the handler and\n// registration it holds; a tool's schema and its result ──\nexport {\n createToolRegistry,\n type ToolHandler,\n type ToolRegistration,\n type ToolRegistry,\n} from './contract/tool-registry';\nexport type { ToolResult, ToolSchema } from './contract/types';\n// ── The canvas surface: its tool sets, each a function from the ports it\n// needs to its registrations, and their schemas as data; the canvas\n// renderer ──\nexport {\n type CanvasEditor,\n type CanvasToolPorts,\n type CanvasTools,\n canvasToolSchemas,\n canvasTools,\n type ModuleToolPorts,\n type ModuleToolResult,\n type ModuleTools,\n moduleToolSchemas,\n moduleTools,\n renderCanvas,\n} from './surfaces/canvas';\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\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. `signal` is the host's cancellation of the call, where its chat has\n// one: once it aborts, the tool starts nothing further and stops waiting, and\n// what it already sent stands.\nexport type ToolHandler<R extends ToolResult = ToolResult> = (\n input: Record<string, unknown>,\n signal?: AbortSignal,\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 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. Each registration is a name, a description that carries\n// the tool's guidance to any host, an input schema and a handler, and says\n// nothing about the host's editor.\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 { Cancelled, untilCancelled } from '../../contract/cancel';\nimport type { ToolRegistration } from '../../contract/tool-registry';\nimport type { ToolResult, ToolSchema } from '../../contract/types';\nimport { applyChanges, OPERATIONS, parseChanges } from './change';\nimport { trimValidate } from './commands';\nimport { type CanvasToolPorts, endText, latest } from './ports';\nimport { errorText, InvalidInput, NO_INPUT, reasonText, registration } from './registration';\nimport { renderCanvas } from './render';\nimport type { StatedSlot } from './stated';\n\n// What each slot of a change names, as the canvas or the registry lists it.\nconst STATED_PROPERTIES: Record<StatedSlot, Record<string, unknown>> = {\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: its canvas path (`group.child`) or its own id.',\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: { type: 'string', description: 'The instance a connect wires from.' },\n output: { type: 'string', description: 'The output a connect wires from.' },\n targetInstance: { type: 'string', description: 'The instance a connect wires into.' },\n module: {\n type: 'string',\n description:\n 'The registry module a place adds, as `author/name`, and `author/name@version` to place a version other than the one the registry lists.',\n },\n};\n\nconst CHANGE: ToolSchema = {\n name: 'lace_change_module_canvas',\n title: 'Change module canvas',\n description: [\n 'Changes a Lace module canvas: places registry modules, wires and unwires instances, sets, binds and clears inputs, and renames, deletes and ungroups instances.',\n 'State each change as the canvas lists it: its `operation`, and each instance, input, output and registry module it works on by the name the canvas gives it.',\n \"Pass each literal the developer gave (an input's value, an instance's new name, the variable an input is bound to) in `value`, one change per entry.\",\n 'A connect that names no `output` and no `input` wires the two instances as the canvas does when one is dragged onto the other.',\n 'A change that names nothing on the canvas, or a name that fits several things, is not applied, and the result lists its candidates: ask the developer which is meant, or send the change again naming one.',\n 'A place whose module the registry lists nothing for points to lace_search_module_registry.',\n 'Every result carries the current canvas. 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 operation: {\n type: 'string',\n enum: OPERATIONS.map((operation) => operation.id),\n description: OPERATIONS.map((operation) => operation.text).join('; '),\n },\n ...STATED_PROPERTIES,\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>`).\",\n },\n },\n required: ['operation'],\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. Read it before a change when you do not know the names the canvas gives its instances, inputs and outputs.',\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 success says of the files it wrote. With no saved edits\n// left to generate, a Generate writes nothing, and the engine still\n// validates the Terraform on disk.\nfunction writtenText(written: readonly string[]): string {\n return written.length === 0\n ? 'Generated the Terraform: nothing was written.'\n : `Generated the Terraform. Files written: ${written.join(', ')}.`;\n}\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 Terraform\n// on disk, 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 writtenText(event.written),\n `lace module validate on the Terraform on disk: ${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// What a Save or a Generate says of a call its host cancelled: nothing is\n// sent once the call is cancelled, and one already sent is the engine's, goes\n// on, and is not undone.\nfunction cancelledSaid(operation: 'save' | 'Generate', sent: boolean): Said {\n return {\n text: sent\n ? `The call was cancelled after the ${operation} was sent: it goes on in the engine, and the canvas below may be from before it ends.`\n : `The call was cancelled before the ${operation} was sent: nothing was done.`,\n isError: false,\n };\n}\n\n// The canvas tools in their order: change, describe, save, generate.\nexport type CanvasTools = readonly [\n ToolRegistration,\n ToolRegistration,\n ToolRegistration,\n ToolRegistration,\n];\n\nexport function canvasTools(ports: CanvasToolPorts): CanvasTools {\n const [change, describe, save, generate] = canvasToolSchemas;\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 return [\n registration(change, async (input, signal) => {\n try {\n const text = await applyChanges(ports, parseChanges(input), signal);\n return answer([{ text, isError: false }]);\n } catch (error) {\n if (!(error instanceof InvalidInput)) throw error;\n return answer([{ text: errorText(error), isError: true }]);\n }\n }),\n registration(describe, () => answer([])),\n registration(save, async (_input, signal) =>\n answer(\n await attempt(async () => {\n if (signal?.aborted) return [cancelledSaid('save', false)];\n const saved: Said = { text: 'Saved the canvas.', isError: false };\n try {\n await untilCancelled(ports.editor.save(), signal);\n return [saved];\n } catch (error) {\n if (error instanceof Cancelled) return [cancelledSaid('save', true)];\n return [saved, unobserved(error)];\n }\n }),\n ),\n ),\n registration(generate, async (_input, signal) =>\n answer(\n await attempt(async () => {\n if (signal?.aborted) return [cancelledSaid('Generate', false)];\n const said: Said[] = [];\n const events = ports.editor.generate()[Symbol.asyncIterator]();\n try {\n for (\n let next = await untilCancelled(events.next(), signal);\n next.done !== true;\n next = await untilCancelled(events.next(), signal)\n ) {\n said.push(...generateSaid(next.value));\n }\n } catch (error) {\n if (error instanceof Cancelled) return [...said, cancelledSaid('Generate', true)];\n said.push(unobserved(error));\n }\n return said;\n }),\n ),\n ),\n ];\n}\n","// The host's cancellation of a call (the `signal` a handler takes), read the\n// one way everywhere in the package: a step not yet started is not started,\n// and a wait in progress ends; what was already sent goes on.\n\n// The host cancelled the call before the step that would have run.\nexport class Cancelled extends Error {\n constructor() {\n super('the call was cancelled');\n }\n}\n\n// Stops a call its host cancelled, at a step boundary.\nexport function stopIfCancelled(signal: AbortSignal | undefined): void {\n if (signal?.aborted) throw new Cancelled();\n}\n\n// `work`, or `Cancelled` once the call's signal aborts first: the call stops\n// waiting, and what `work` stands for goes on. The listener ends with the\n// wait.\nexport function untilCancelled<T>(work: Promise<T>, signal: AbortSignal | undefined): Promise<T> {\n if (signal === undefined) return work;\n let stop = (): void => {};\n const cancelled = new Promise<never>((_, fail) => {\n stop = () => fail(new Cancelled());\n if (signal.aborted) stop();\n else signal.addEventListener('abort', stop, { once: true });\n });\n return Promise.race([work, cancelled]).finally(() => signal.removeEventListener('abort', stop));\n}\n\n// A step that waits on something: not started once the call is cancelled,\n// and otherwise waited on until it is.\nexport function cancellable<T>(\n start: () => Promise<T>,\n signal: AbortSignal | undefined,\n): Promise<T> {\n if (signal?.aborted) return Promise.reject(new Cancelled());\n return untilCancelled(start(), signal);\n}\n","// The change tool's work: each change, stated as the canvas lists it,\n// resolved slot by slot against the canvas as it stands when the change is\n// reached, then applied as one action.\n//\n// A slot resolves by name (resolve.ts): one option is the change's, and a\n// name that fits several options, fits none, or is not stated where the\n// operation needs it leaves the change unapplied, with the candidates the\n// canvas or the registry lists for the slot, so the model can ask the\n// developer or send the change again. A connect that names no pin is sent as\n// the canvas sends a drag of one instance onto another (`auto_connect`); one\n// that names both pins is a connect of those pins into any input of the\n// target, wired or not, as a pin drag is; one that names a single pin lists\n// the pairs the engine's matcher reads for it. The change's value is\n// withheld where text the package does not write enters a result: an\n// engine's refusal, a command's failure, a stream's end, and each name the\n// change stated that a result says back (withhold.ts).\nimport { type ApplyResult, ApplyUnobservedError, InputMode } from '@lace-cloud/canvas/engine';\nimport { Cancelled, cancellable, stopIfCancelled } from '../../contract/cancel';\nimport { runCommand } from './commands';\nimport {\n type CanvasInput,\n type CanvasInstance,\n type CanvasReading,\n connectionId,\n instanceOptions,\n moduleId,\n moduleOptions,\n type Option,\n pairListing,\n pinOptions,\n pinRef,\n readCanvas,\n} from './enumerate';\nimport { type CanvasEditor, type CanvasToolPorts, endText, latest } from './ports';\nimport { errorText, InvalidInput } from './registration';\nimport { resolve } from './resolve';\nimport { STATED_SLOTS, type Stated, type StatedSlot, slotsStated } from './stated';\nimport { withhold } from './withhold';\n\n// One entry of the tool's input: its operation, the names it states slot by\n// slot, and the literal the developer gave, undefined where it gave none.\nexport type Change = {\n readonly operation: Operation;\n readonly stated: Stated;\n readonly value: unknown;\n};\n\n// A change that cannot be applied as it was sent.\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\nexport function parseChanges(input: Record<string, unknown>): Change[] {\n const { changes } = input;\n if (!Array.isArray(changes) || changes.length === 0) {\n throw new InvalidInput('`changes` is a list of one or more changes');\n }\n return changes.map((entry: unknown, index) => {\n const which = `change ${index + 1}`;\n if (!isRecord(entry)) throw new InvalidInput(`${which} is an object`);\n const operation = OPERATIONS.find((each) => each.id === entry.operation);\n if (operation === undefined) {\n const ids = OPERATIONS.map((each) => each.id).join(', ');\n throw new InvalidInput(`${which} needs \\`operation\\`: one of ${ids}`);\n }\n // An empty name states nothing, as an absent one does.\n const names = STATED_SLOTS.flatMap((slot) => {\n const name = entry[slot];\n if (!present(name) || name === '') return [];\n if (typeof name !== 'string') {\n throw new InvalidInput(`${which}: \\`${slot}\\` is a name, as the canvas lists it`);\n }\n return [[slot, name]];\n });\n return {\n operation,\n stated: Object.fromEntries(names),\n value: present(entry.value) ? entry.value : undefined,\n };\n });\n}\n\n// The most candidates a reason lists.\nconst LISTED = 12;\n\n// Names as a reason lists them: the first `LISTED`, and how many more.\nfunction listed(names: readonly string[]): string {\n const kept = names.slice(0, LISTED);\n const more = names.length - kept.length;\n return [...kept, ...(more > 0 ? [`and ${more} more`] : [])].join(', ');\n}\n\nconst candidates = (names: readonly string[]): string => `Candidates: ${listed(names)}.`;\n\n// Where a slot's names come from: the registry for a module, the canvas for\n// every other slot.\nconst listedBy = (slot: StatedSlot): string => (slot === 'module' ? 'registry' : 'canvas');\n\n// What a slot names when it names no one option: nothing, for a slot the\n// change does not state; or the name it states, fitting no option or\n// several, as a result says it back (withheld against the change's value).\ntype Unresolved =\n | { readonly kind: 'missing' }\n | { readonly kind: 'none'; readonly stated: string }\n | { readonly kind: 'several'; readonly stated: string; readonly names: readonly string[] };\n\ntype Named<T> = { readonly kind: 'one'; readonly value: T } | Unresolved;\n\n// Why a slot names no one option, then `instead`: what the model can name.\n// `label` says what the slot offers (\"instance\", \"input of app\").\nfunction unresolvedText(\n slot: StatedSlot,\n label: string,\n unresolved: Unresolved,\n instead: string,\n): string {\n switch (unresolved.kind) {\n case 'missing':\n return `this change states no \\`${slot}\\`. ${instead}`;\n case 'none':\n return `no ${label} is named \\`${unresolved.stated}\\`. ${instead}`;\n case 'several':\n return `\\`${unresolved.stated}\\` names more than one ${label}: ${listed(unresolved.names)}. Name one as the ${listedBy(slot)} lists it.`;\n }\n}\n\nconst nothingOffered = (label: string): string => `the canvas offers no ${label} for this change.`;\n\n// Several reasons as one: each a sentence, in the order the slots stand.\nfunction reasons(each: readonly string[]): string {\n return each.map((why, i) => (i === 0 ? why : why[0].toUpperCase() + why.slice(1))).join(' ');\n}\n\n// What a slot names among the options the canvas offers it: its option's\n// value, or why the change cannot be applied, listing the options.\ntype Picked<T> = { readonly value: T } | { readonly why: string };\n\nconst whyOf = (picked: Picked<unknown>): string[] => ('why' in picked ? [picked.why] : []);\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// and the change in words once the engine applied it, read from the apply's\n// result and the canvas it produced.\ntype Plan = {\n readonly action: Action;\n readonly summary: (result: ApplyResult, after: CanvasReading) => string;\n};\n\ntype Resolving = {\n readonly canvas: CanvasReading;\n readonly change: Change;\n readonly ports: CanvasToolPorts;\n // The call's cancellation, for what the plan waits on.\n readonly signal: AbortSignal | undefined;\n // What the name `stated` names in `slot` among `options`.\n readonly name: <T>(\n slot: StatedSlot,\n stated: string | undefined,\n options: readonly Option<T>[],\n ) => Named<T>;\n // What `slot` names among the canvas's `options`.\n readonly choose: <T>(slot: StatedSlot, label: string, options: readonly Option<T>[]) => Picked<T>;\n // What `slot` names among the canvas's `options`, or the change cannot be\n // applied.\n readonly pick: <T>(slot: StatedSlot, label: string, options: readonly Option<T>[]) => 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, what it does in the words the tool's schema gives\n// the model, the slots it names things by, whether it writes the literal a\n// change carries in `value`, and how it resolves the rest of a change.\ntype Operation = {\n readonly id: string;\n readonly text: string;\n readonly slots: readonly StatedSlot[];\n readonly takesValue: boolean;\n readonly plan: (resolving: Resolving) => Promise<Plan>;\n};\n\n// The literal the developer gave: the tool writes no value of its own.\nfunction given(change: Change, what: string): unknown {\n if (change.value === undefined) {\n throw new Unapplicable(`this change needs ${what}: pass it in \\`value\\`.`);\n }\n return change.value;\n}\n\nfunction givenName(change: Change, what: string): string {\n const name = given(change, what);\n if (typeof name !== 'string') throw new Unapplicable(`${what} is text: pass it in \\`value\\`.`);\n return name;\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\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: the instance\n// among every instance, and the input among those of its inputs whose\n// binding is in one of `modes`, so an operation is offered only the inputs\n// it can act on. `offered` says what those inputs are, of an instance.\nfunction pickInput(\n { canvas, pick }: Resolving,\n modes: readonly BindingMode[],\n offered: (instance: CanvasInstance) => string,\n) {\n const instance = pick('instance', 'instance', instanceOptions(canvas.instances));\n const inputs = instance.inputs.filter((input) => modes.includes(input.mode));\n const input = pick('input', offered(instance), pinOptions(inputs));\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\n// What a place says where the listing does not settle the module.\nconst SEARCH = 'Find it with lace_search_module_registry and name it as `author/name`.';\n\n// A registry module as a change states it: `author/name`, or the name\n// alone, and after `@` the version to place where it names one. `query` is\n// the name part, which the registry listing is narrowed by. An `@` that\n// names no version is no module a place can add.\nfunction moduleRef(stated: string) {\n const at = stated.lastIndexOf('@');\n if (at < 1) return { ref: stated, query: stated.split('/').at(-1) ?? '' };\n const ref = stated.slice(0, at);\n const version = stated.slice(at + 1);\n if (version === '') {\n throw new Unapplicable(\n '`module` ends in `@` with no version after it. Name the version, as `author/name@version`, or leave out `@` to place the version the registry lists.',\n );\n }\n return { ref, query: ref.split('/').at(-1) ?? '', version };\n}\n\nconst place: Operation = {\n id: 'place',\n text: 'place: add a registry module to the canvas as a new instance',\n slots: ['module'],\n takesValue: false,\n async plan({ change, ports, signal, name, note }) {\n const stated = change.stated.module === undefined ? undefined : moduleRef(change.stated.module);\n const version = stated?.version;\n if (stated === undefined || stated.query === '') {\n throw new Unapplicable(\n unresolvedText('module', 'registry module', { kind: 'missing' }, SEARCH),\n );\n }\n const listing = await cancellable(\n () =>\n runCommand(\n ports.commands,\n 'registry list',\n { axis: 'module', limit: CATALOG_LIMIT, query: stated.query },\n signal,\n ),\n signal,\n );\n if (listing.failed !== undefined) throw new Error(listing.failed.text);\n if (listing.documents.some((document) => 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 const module = name(\n 'module',\n stated.ref,\n moduleOptions(listing.documents.flatMap((document) => document.items)),\n );\n if (module.kind !== 'one') {\n throw new Unapplicable(unresolvedText('module', 'registry module', module, SEARCH));\n }\n const row = module.value;\n return {\n action: {\n place_module: { author: row.author, name: row.name, version: version ?? row.version },\n },\n summary: (result) =>\n `placed ${moduleId(row)} ${version === undefined ? row.version : withhold(version, change.value)} as ${result.created.map((ref) => ref.id).join(', ')}`,\n };\n },\n};\n\n// A connect that names no pin: the engine's matcher wires the two\n// instances, as a drag of one onto the other does, and the pairs it leaves\n// tied come back for the developer to choose between. A connect that wired\n// nothing changed nothing.\nfunction autoConnect(\n canvas: CanvasReading,\n source: CanvasInstance,\n target: CanvasInstance,\n ends: { scope: string; source_scope: string; source: string; target: string },\n note: (line: string) => void,\n): Plan {\n const between = (reading: CanvasReading) =>\n reading.wires\n .filter((wire) => wire.source === source.id && wire.target === target.id)\n .map((wire) =>\n connectionId(\n pinRef(wire.source, wire.source_output),\n pinRef(wire.target, wire.target_input),\n ),\n );\n const before = new Set(between(canvas));\n return {\n action: { auto_connect: ends },\n summary(result, after) {\n const wired = between(after).filter((wire) => !before.has(wire));\n const ties = result.ties.map((pair) =>\n connectionId(pinRef(source.id, pair.output), pinRef(target.id, pair.input)),\n );\n const choose = 'Send it again naming the `output` and the `input` the developer means.';\n if (wired.length === 0) {\n throw new Unapplicable(\n ties.length > 0\n ? `more than one pair fits equally well, so nothing was wired: ${listed(ties)}. ${choose}`\n : `the engine wired nothing from ${source.id} into ${target.id}.`,\n );\n }\n if (ties.length > 0) {\n note(`Not connected, more than one pair fits equally well: ${listed(ties)}. ${choose}`);\n }\n return `connected ${source.id} to ${target.id}: ${wired.join(', ')}`;\n },\n };\n}\n\nconst connect: Operation = {\n id: 'connect',\n text: 'connect: wire an output of one instance into an input of another',\n slots: ['sourceInstance', 'output', 'targetInstance', 'input'],\n takesValue: false,\n async plan({ canvas, change, ports, signal, choose, note }) {\n const instances = instanceOptions(canvas.instances);\n const sourcePicked = choose('sourceInstance', 'instance', instances);\n const targetPicked = choose('targetInstance', 'instance', instances);\n if (!('value' in sourcePicked) || !('value' in targetPicked)) {\n throw new Unapplicable(reasons([...whyOf(sourcePicked), ...whyOf(targetPicked)]));\n }\n const [source, target] = [sourcePicked.value, targetPicked.value];\n if (source.id === target.id) {\n throw new Unapplicable(\n `\\`sourceInstance\\` and \\`targetInstance\\` both name ${source.id}: a connect wires one instance into another.`,\n );\n }\n const ends = {\n scope: target.scope,\n source_scope: source.scope,\n source: source.name,\n target: target.name,\n };\n const stated = { output: change.stated.output, input: change.stated.input };\n if (stated.output === undefined && stated.input === undefined) {\n return autoConnect(canvas, source, target, ends, note);\n }\n const output =\n stated.output === undefined\n ? undefined\n : choose('output', `output of ${source.id}`, pinOptions(source.outputs));\n const input =\n stated.input === undefined\n ? undefined\n : choose('input', `input of ${target.id}`, pinOptions(target.inputs));\n const whys = [...(output ? whyOf(output) : []), ...(input ? whyOf(input) : [])];\n // A connect naming one pin lists the pairs the engine's matcher gives\n // for it, from its own read of the two instances.\n if (output === undefined || input === undefined) {\n const [named, unnamed] = output === undefined ? ['input', 'output'] : ['output', 'input'];\n const scored = await cancellable(\n () =>\n ports.editor.wiringCandidates({\n scope: ends.scope,\n sourceScope: ends.source_scope,\n source: ends.source,\n target: ends.target,\n }),\n signal,\n );\n const pairs = pairListing(source, target, scored, {\n ...(output && 'value' in output ? { output: output.value.name } : {}),\n ...(input && 'value' in input ? { input: input.value.name } : {}),\n });\n whys.push(\n `this change states \\`${named}\\` and no \\`${unnamed}\\`: state both, or neither to wire the two instances as the canvas does. ${\n pairs.length > 0\n ? candidates(pairs)\n : `The engine's matcher pairs no output of ${source.id} with an input of ${target.id}.`\n }`,\n );\n throw new Unapplicable(reasons(whys));\n }\n if (!('value' in output) || !('value' in input)) throw new Unapplicable(reasons(whys));\n const [from, to] = [output.value.name, input.value.name];\n return {\n action: { connect: { ...ends, source_output: from, target_input: to } },\n summary: () => `connected ${connectionId(pinRef(source.id, from), pinRef(target.id, to))}`,\n };\n },\n};\n\nconst disconnect: Operation = {\n id: 'disconnect',\n text: \"disconnect: remove the wire into an instance's input\",\n slots: ['instance', 'input'],\n takesValue: false,\n async plan(resolving) {\n const { instance, input } = pickInput(resolving, ['wired'], (of) => `wired input of ${of.id}`);\n return {\n action: {\n disconnect: { scope: instance.scope, target: instance.name, input_name: input.name },\n },\n summary: () => `disconnected ${pinRef(instance.id, input.name)}`,\n };\n },\n};\n\nconst set: Operation = {\n id: 'set',\n text: 'set: give an input of an instance a literal value',\n slots: ['instance', 'input'],\n takesValue: true,\n async plan(resolving) {\n const value = given(resolving.change, 'the value the developer gave');\n const { instance, input } = pickInput(resolving, EVERY_MODE, (of) => `input of ${of.id}`);\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 ${pinRef(instance.id, input.name)} ${shown}`,\n };\n },\n};\n\nconst bind: Operation = {\n id: 'bind',\n text: \"bind: make an input of an instance take its value from a variable of the module (`var.<name>`), so the module's caller sets it\",\n slots: ['instance', 'input'],\n takesValue: true,\n async plan(resolving) {\n const variable = variableName(givenName(resolving.change, \"the variable's name\"));\n const { instance, input } = pickInput(resolving, EVERY_MODE, (of) => `input of ${of.id}`);\n return {\n action: updateInput(instance, input, { mode: InputMode.INPUT_MODE_VARIABLE, variable }),\n summary: () => `bound ${pinRef(instance.id, input.name)} to var.${variable}`,\n };\n },\n};\n\nconst clear: Operation = {\n id: 'clear',\n text: 'clear: unset an input of an instance, removing the value, variable or expression it holds',\n slots: ['instance', 'input'],\n takesValue: false,\n async plan(resolving) {\n const { instance, input } = pickInput(\n resolving,\n ['literal', 'variable', 'expression'],\n (of) => `input of ${of.id} that holds a value`,\n );\n return {\n action: updateInput(instance, input, { mode: InputMode.INPUT_MODE_EMPTY }),\n summary: () => `cleared ${pinRef(instance.id, input.name)}`,\n };\n },\n};\n\nconst rename: Operation = {\n id: 'rename',\n text: 'rename: give an instance a new name',\n slots: ['instance'],\n takesValue: true,\n async plan({ canvas, change, pick }) {\n const name = givenName(change, 'the new name');\n const instance = 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 };\n },\n};\n\nconst remove: Operation = {\n id: 'delete',\n text: 'delete: remove an instance from the canvas',\n slots: ['instance'],\n takesValue: false,\n async plan({ canvas, pick }) {\n const instance = 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 };\n },\n};\n\nconst ungroup: Operation = {\n id: 'ungroup',\n text: 'ungroup: dissolve a group, moving the instances inside it up beside it',\n slots: ['instance'],\n takesValue: false,\n async plan({ canvas, pick }) {\n const groups = new Set(canvas.groups.map((group) => group.id));\n const group = 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 };\n },\n};\n\n// The operations a change can be. Each is one row: its name, what it does,\n// what it names, and how it 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 | { readonly kind: 'applied'; readonly summary: string }\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 // The host cancelled the call before this change's apply was sent.\n | { readonly kind: 'cancelled' }\n // An earlier change's apply went unobserved: the stream it would be read\n // on had ended, so this change was not sent.\n | { readonly kind: 'notRun' };\n\nconst CANCELLED: Outcome = { kind: 'cancelled' };\nconst NOT_RUN: Outcome = { kind: 'notRun' };\n\n// The lines a change says before it is resolved: each slot it states that\n// its operation does not use, and a value an operation that takes none was\n// sent.\nfunction unusedLines({ operation, stated, value }: Change): string[] {\n const unused = slotsStated(stated).filter((slot) => !operation.slots.includes(slot));\n return [\n ...unused.map((slot) => `\\`${slot}\\` is not used by ${operation.id}.`),\n ...(value !== undefined && !operation.takesValue\n ? [`The \\`value\\` sent with this change was not used: ${operation.id} takes none.`]\n : []),\n ];\n}\n\nasync function resolveAndApply(\n ports: CanvasToolPorts,\n change: Change,\n signal: AbortSignal | undefined,\n note: (line: string) => void,\n): Promise<Outcome> {\n const canvas = readCanvas(await latest(ports.source));\n const name = <T>(\n slot: StatedSlot,\n stated: string | undefined,\n options: readonly Option<T>[],\n ): Named<T> => {\n if (stated === undefined) return { kind: 'missing' };\n const resolved = resolve(options, stated);\n // The name as a result says it back.\n const echoed = withhold(stated, change.value);\n switch (resolved.kind) {\n case 'one': {\n const [listedAs] = resolved.option.names;\n const where = slot === 'module' ? 'in the registry' : 'on the canvas';\n if (resolved.folded) note(`Your \\`${slot}\\` ${echoed} is \\`${listedAs}\\` ${where}.`);\n return { kind: 'one', value: resolved.option.value };\n }\n case 'several':\n return {\n kind: 'several',\n stated: echoed,\n names: resolved.options.map((each) => each.names[0]),\n };\n case 'none':\n return { kind: 'none', stated: echoed };\n }\n };\n const choose = <T>(slot: StatedSlot, label: string, options: readonly Option<T>[]): Picked<T> => {\n if (options.length === 0) return { why: nothingOffered(label) };\n const named = name(slot, change.stated[slot], options);\n if (named.kind === 'one') return { value: named.value };\n const offered = options.map((option) => option.names[0]);\n return { why: unresolvedText(slot, label, named, candidates(offered)) };\n };\n const resolving: Resolving = {\n canvas,\n change,\n ports,\n signal,\n name,\n choose,\n pick(slot, label, options) {\n const picked = choose(slot, label, options);\n if ('why' in picked) throw new Unapplicable(picked.why);\n return picked.value;\n },\n note,\n };\n for (const line of unusedLines(change)) note(line);\n const plan = await change.operation.plan(resolving);\n // Nothing is applied once the call is cancelled; an apply already sent is\n // the engine's, and stands.\n stopIfCancelled(signal);\n const result = await ports.editor.apply([plan.action]);\n if (!result.success) {\n const refusals = result.errors.map((error) => error.message).join('; ');\n return {\n kind: 'notApplied',\n why: `the engine refused it: ${withhold(refusals, change.value)}`,\n };\n }\n const after = readCanvas(await latest(ports.source));\n return { kind: 'applied', summary: plan.summary(result, after) };\n}\n\n// One change, whatever becomes of it: a failure of this change (a slot that\n// names nothing or several things, an engine that refused, a listing that\n// failed) is this change's outcome and stops no other, and so is an apply\n// the engine answered whose frame the session's stream ended before. A\n// reason the package wrote is said as it is; any other failure's text, and\n// the account of a stream's end, are withheld against the change's value.\nasync function runChange(\n ports: CanvasToolPorts,\n change: Change,\n signal: AbortSignal | undefined,\n note: (line: string) => void,\n): Promise<Outcome> {\n try {\n return await resolveAndApply(ports, change, signal, note);\n } catch (error) {\n if (error instanceof ApplyUnobservedError) {\n return { kind: 'unobserved', end: withhold(endText(error.end), change.value) };\n }\n // The host cancelled the call before this change's apply was sent (a\n // listing or a wiring read no longer waited on). Anything once the apply\n // was sent is the apply's own outcome.\n if (error instanceof Cancelled) return CANCELLED;\n if (error instanceof Unapplicable) return { kind: 'notApplied', why: error.message };\n return { kind: 'notApplied', why: withhold(errorText(error), change.value) };\n }\n}\n\nfunction outcomeLine(number: number, outcome: Outcome): string {\n const head = `Change ${number}:`;\n switch (outcome.kind) {\n case 'applied':\n return `${head} applied. ${outcome.summary}.`;\n case 'notApplied':\n return `${head} not applied. Reason: ${outcome.why}`;\n case 'cancelled':\n return `${head} not applied. The call was cancelled before it applied.`;\n case 'unobserved':\n return `${head} sent, and the engine answered it, but the session's stream ended (${outcome.end}) before the canvas showed it, so whether it applied cannot be read here. Do not send it again before the canvas is open again.`;\n case 'notRun':\n return `${head} not run. The session's stream ended before it, so it was not sent.`;\n }\n}\n\n// Applies the changes in order, each against the state the one before it\n// produced, and says per change what was applied or why nothing was, with\n// the lines it noted beneath it. A summary shows the value the operation\n// wrote unless the input is sensitive.\n//\n// `signal` is the host's cancellation of the call. Once it aborts, nothing\n// further is started: a listing or wiring read in progress is no longer\n// waited on, and the change in progress and every later one say the call\n// was cancelled before they applied. Once an apply goes unobserved (the\n// session's stream ended before its frame), no later change is sent: the\n// stream that would show it has ended.\nexport async function applyChanges(\n ports: CanvasToolPorts,\n changes: readonly Change[],\n signal?: AbortSignal,\n): Promise<string> {\n const lines: string[] = [];\n let ended = false;\n for (const [index, change] of changes.entries()) {\n const notes: string[] = [];\n const outcome: Outcome = ended\n ? NOT_RUN\n : signal?.aborted\n ? CANCELLED\n : await runChange(ports, change, signal, (line) => notes.push(line));\n ended = ended || outcome.kind === 'unobserved';\n lines.push(\n outcomeLine(index + 1, outcome),\n ...(outcome.kind === 'cancelled' || outcome.kind === 'notRun'\n ? []\n : notes.map((line) => ` ${line}`)),\n );\n }\n return lines.join('\\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 type CommandFailure,\n type CommandsPort,\n ConnectError,\n failureSays,\n type JsonOf,\n} from '@lace-cloud/canvas/engine';\nimport { moduleId } from './enumerate';\nimport { refusalReason } 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// Why a command ended, in the chat's words around what the failure says\n// (`failureSays`, the one reading every surface shows): the command's path,\n// and the reason the failure names as data — a failure document's, or a\n// refusal's when the engine refused the call before the command started —\n// by its wire spelling, or the API's own code when the API decided it, and\n// the page a document's reason points at when it names one.\nfunction commandEnd(path: BoundPath, error: unknown): CommandEnd {\n const { message, failure } = failureSays(error);\n const failed = (why: string, see = '') => `lace ${path} failed (reason ${why}): ${message}${see}`;\n if (failure !== undefined) {\n const see = failure.url === undefined ? '' : `; see ${failure.url}`;\n return { text: failed(failure.apiCode ?? failure.reason, see), failure };\n }\n if (error instanceof ConnectError) return { text: failed(refusalReason(error)) };\n return { text: `lace ${path} did not finish cleanly (${message})` };\n}\n\n// `signal` is the tool call's cancellation, which the port reads as the\n// consumer no longer listening: the call stops waiting, and the command keeps\n// whatever it already did.\nexport async function runCommand<P extends BoundPath>(\n commands: CommandsPort,\n path: P,\n args: ArgsOf<P>,\n signal: AbortSignal = new AbortController().signal,\n): Promise<CommandOutput<P>> {\n const documents: JsonOf<P>[] = [];\n try {\n for await (const document of commands.invoke(path, args, 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 each slot a change names, and\n// the names it offers each by. `readCanvas` is the only fold over the Bundle\n// in this package, and it folds through proto's projection\n// (`projectCanvasView`), inspection (`deriveNodeConfig`), instance\n// resolution (`resolveInstance`) and diagnostic-to-node mapping\n// (`nodeIdForDiagnostic`) alone; every option 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.\nimport type { CanvasSource, JsonOf, WiringCandidate } from '@lace-cloud/canvas/engine';\nimport {\n type Diagnostic,\n deriveNodeConfig,\n nodeIdForDiagnostic,\n projectCanvasView,\n type RenderEdge,\n type RenderInput,\n type RenderOutput,\n resolveInstance,\n} from '@lace-cloud/proto';\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\n// One of the engine's diagnostics, with the canvas path of the instance it\n// is about where proto's one diagnostic-to-node mapping finds one.\nexport type CanvasDiagnostic = {\n readonly diagnostic: Diagnostic;\n readonly node: string | null;\n};\n\nexport type CanvasReading = {\n readonly module: string;\n readonly instances: readonly CanvasInstance[];\n readonly wires: readonly RenderEdge[];\n readonly groups: readonly CanvasGroup[];\n readonly diagnostics: readonly CanvasDiagnostic[];\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 instances,\n wires: view.edges,\n groups: view.groups.map((group) => ({ id: group.id, members: group.node_ids })),\n diagnostics: source.diagnostics.map((diagnostic) => ({\n diagnostic,\n node: nodeIdForDiagnostic(view, diagnostic),\n })),\n };\n}\n\n// One thing a slot can name: the names it is named by, the one the canvas\n// lists it by first, and the thing.\nexport type Option<T> = {\n readonly names: readonly [string, ...string[]];\n readonly value: T;\n};\n\n// An instance, named by its canvas path, then by its own id.\nexport function instanceOptions(instances: readonly CanvasInstance[]): Option<CanvasInstance>[] {\n return instances.map((instance) => ({ names: [instance.id, instance.name], value: instance }));\n}\n\n// A pin of an instance, named by its name.\nexport function pinOptions<P extends { readonly name: string }>(pins: readonly P[]): Option<P>[] {\n return pins.map((pin) => ({ names: [pin.name], value: pin }));\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\n// A registry module, named as `author/name`, then by its name.\nexport function moduleOptions(rows: readonly RegistryRow[]): Option<RegistryRow>[] {\n return rows.map((row) => ({ names: [moduleId(row), row.name], value: row }));\n}\n\n// A wire's end as the canvas lists it: an instance's canvas path and the\n// pin's name.\nexport function pinRef(instance: string, pin: string): string {\n return `${instance}.${pin}`;\n}\n\n// A wire as the canvas lists it.\nexport function connectionId(from: string, to: string): string {\n return `${from} → ${to}`;\n}\n\n// The engine matcher's pairs from source into target (`scored`, its read\n// for the two), as a connect lists them: in the matcher's order, best\n// first, each with its score, held to the one pin the change named.\nexport function pairListing(\n source: CanvasInstance,\n target: CanvasInstance,\n scored: readonly WiringCandidate[],\n pin: { readonly output?: string; readonly input?: string },\n): string[] {\n return scored\n .filter((pair) => pair.sourceInstance === source.name && pair.targetInstance === target.name)\n .filter((pair) => pin.output === undefined || pair.output === pin.output)\n .filter((pair) => pin.input === undefined || pair.input === pin.input)\n .map(\n (pair) =>\n `${connectionId(pinRef(source.id, pair.output), pinRef(target.id, pair.input))} (score ${pair.score})`,\n );\n}\n","import { 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// The reason a refused engine call names: the API's own code when the API\n// decided it, else the reason it carries, spelled as a failure document\n// spells it.\nexport function refusalReason(error: ConnectError): string {\n return error.apiCode ?? reasonWire(error.reason);\n}\n\n// A thrown error in words: its message, and for a refused engine call the\n// reason it names.\nexport function errorText(error: unknown): string {\n if (error instanceof ConnectError) return `${error.message} (reason ${refusalReason(error)})`;\n return error instanceof Error ? error.message : String(error);\n}\n\n// A tool's registration, whose handler always answers: a thrown error is\n// the call's result, said in the error's own words, never a rejection the\n// host's chat has to translate. A tool whose result carries data for its\n// host beside the text (`E`, each part optional) answers a failure with\n// none of it.\nexport function registration<E extends object = object>(\n schema: ToolSchema,\n run: ToolHandler<ToolResult & Partial<E>>,\n): ToolRegistration<ToolResult & Partial<E>> {\n const none: Partial<E> = {};\n return {\n schema,\n async handler(input, signal) {\n try {\n return await run(input, signal);\n } catch (error) {\n return { ...none, content: errorText(error), isError: true };\n }\n },\n };\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","// 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, and one with a\n// `commands` port alone constructs the module tools.\nimport type {\n ApplyUnobservedError,\n CanvasSource,\n CommandsPort,\n EditorPort,\n SourceEnd,\n SourcePort,\n} from '@lace-cloud/canvas/engine';\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};\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","// One slot's resolution: the name a change states, matched against the\n// names of each option the slot offers, in four steps: exactly on an\n// option's first name (an instance's canvas path, a module's `author/name`),\n// exactly on any of its names, then each again ignoring case. The first step\n// with any hit decides: one hit is the option, several are ambiguous, and a\n// later step is never reached. No hit at any step is unmatched. Both sides\n// are compared in one Unicode form (NFC), so a name typed decomposed finds\n// the name the canvas holds composed.\nimport type { Option } from './enumerate';\n\nexport type Resolved<T> =\n | { readonly kind: 'one'; readonly option: Option<T>; readonly folded: boolean }\n | { readonly kind: 'several'; readonly options: readonly Option<T>[] }\n | { readonly kind: 'none' };\n\ntype Step = {\n // Whether the step ignores case.\n readonly folded: boolean;\n readonly names: (option: Option<unknown>) => readonly string[];\n};\n\nconst first = (option: Option<unknown>) => option.names.slice(0, 1);\nconst every = (option: Option<unknown>) => option.names;\n\nconst STEPS: readonly Step[] = [\n { folded: false, names: first },\n { folded: false, names: every },\n { folded: true, names: first },\n { folded: true, names: every },\n];\n\nexport function resolve<T>(options: readonly Option<T>[], stated: string): Resolved<T> {\n const step = STEPS.map((each) => {\n const key = (name: string) => {\n const normal = name.normalize('NFC');\n return each.folded ? normal.toLowerCase() : normal;\n };\n const hits = options.filter((option) =>\n each.names(option).some((name) => key(name) === key(stated)),\n );\n return { folded: each.folded, hits };\n }).find((each) => each.hits.length > 0);\n if (step === undefined) return { kind: 'none' };\n return step.hits.length === 1\n ? { kind: 'one', option: step.hits[0], folded: step.folded }\n : { kind: 'several', options: step.hits };\n}\n","// The names one change states, each in its own slot, as the canvas or the\n// registry lists them: an instance by its canvas path or its own id, a pin\n// by its name, a registry module as `author/name` or by its name.\nexport const STATED_SLOTS = [\n 'instance',\n 'input',\n 'sourceInstance',\n 'output',\n 'targetInstance',\n 'module',\n] as const;\n\nexport type StatedSlot = (typeof STATED_SLOTS)[number];\n\nexport type Stated = Readonly<Partial<Record<StatedSlot, string>>>;\n\n// The slots a change states, in slot order.\nexport function slotsStated(stated: Stated): StatedSlot[] {\n return STATED_SLOTS.filter((slot) => stated[slot] !== undefined);\n}\n","// What a result withholds of the value a change carries. The value is\n// withheld only from text the package does not write itself and that could\n// carry it: an engine's refusal, a command's failure, the account of a\n// session's stream ending, and each name the model stated that a result\n// says back. The package's own words, and the names the canvas or the\n// registry lists, are never withheld: they are public, and the canvas the\n// result ends with prints them.\n\n// The one token that stands where a value was.\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\nconst GO_ESCAPES: Readonly<Record<string, string>> = {\n '\\x07': '\\\\a',\n '\\b': '\\\\b',\n '\\f': '\\\\f',\n '\\n': '\\\\n',\n '\\r': '\\\\r',\n '\\t': '\\\\t',\n '\\v': '\\\\v',\n '\"': '\\\\\"',\n '\\\\': '\\\\\\\\',\n};\n\n// What Go's strconv counts printable: a letter, mark, number, punctuation\n// or symbol, or the ASCII space.\nconst GO_PRINTABLE = /^[ \\p{L}\\p{M}\\p{N}\\p{P}\\p{S}]$/u;\n\n// One character as Go's `%q` writes it inside quotes.\nfunction goEscaped(char: string): string {\n const code = char.codePointAt(0) ?? 0;\n if (GO_ESCAPES[char] !== undefined) return GO_ESCAPES[char];\n if (GO_PRINTABLE.test(char)) return char;\n const [mark, width] = code < 0x80 ? ['x', 2] : code < 0x10000 ? ['u', 4] : ['U', 8];\n return `\\\\${mark}${code.toString(16).padStart(width, '0')}`;\n}\n\n// Every form a literal is written in: itself; quoted with JSON's escapes;\n// quoted as Go's `%q` writes it, which is how the engine quotes a value it\n// names; and each quoted form's escapes unquoted.\nfunction writtenForms(literal: string): string[] {\n const quoted = [JSON.stringify(literal), `\"${[...literal].map(goEscaped).join('')}\"`];\n return [literal, ...quoted, ...quoted.map((form) => form.slice(1, -1))];\n}\n\n// The forms of a value's literals, longest first, so one that holds another\n// is replaced whole.\nfunction forms(value: unknown): string[] {\n const all = literalTexts(value)\n .filter((literal) => literal !== '')\n .flatMap(writtenForms);\n return [...new Set(all)].sort((a, b) => b.length - a.length);\n}\n\n// `text` as a pattern that matches it literally.\nfunction escapeRegExp(text: string): string {\n return text.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\nconst NAME = /^[A-Za-z0-9_-]+$/;\n\n// Where a form stands in a text, in any case. One that could be a name\n// stands where it is a token of its own, delimited by anything that is not a\n// letter, a digit, an underscore or a hyphen; one that holds any other\n// character is never a name and stands wherever it occurs.\nfunction occurrences(form: string): RegExp {\n const text = escapeRegExp(form);\n return NAME.test(form)\n ? new RegExp(`(?<![A-Za-z0-9_-])${text}(?![A-Za-z0-9_-])`, 'gi')\n : new RegExp(text, 'gi');\n}\n\n// `text`, a text the package did not write, with every occurrence of the\n// value replaced by the placeholder.\nexport function withhold(text: string, value: unknown): string {\n return forms(value).reduce(\n (rest, form) => rest.replace(occurrences(form), VALUE_PLACEHOLDER),\n text,\n );\n}\n","// The canvas as a model reads it: a pure function of one frame. Every canvas\n// tool's result ends with `renderCanvas` of the session's latest frame, so\n// each call corrects the model's picture of the canvas.\nimport type { CanvasSource } from '@lace-cloud/canvas/engine';\nimport { callText } from '@lace-cloud/proto';\nimport {\n type CanvasDiagnostic,\n type CanvasInput,\n type CanvasInstance,\n connectionId,\n pinRef,\n readCanvas,\n} 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) => `- ${pinRef(instance.id, input.name)}`);\n}\n\n// A diagnostic names its instance by its canvas path, so a grouped\n// instance is never read as a top-level one of the same id; one whose\n// instance no node is found for names it with the module it was found in.\nfunction diagnosticLine({ diagnostic, node }: CanvasDiagnostic): string {\n const scoped =\n diagnostic.module_key === undefined\n ? diagnostic.instance_id\n : `${diagnostic.instance_id} in module ${diagnostic.module_key}`;\n const instance = node ?? (diagnostic.instance_id === undefined ? undefined : scoped);\n const where = [\n ['instance', instance],\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 `- ${connectionId(\n wire.source_output ? pinRef(wire.source, wire.source_output) : callText(wire.source),\n pinRef(wire.target, wire.target_input),\n )}`,\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', canvas.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","// 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 { ToolHandler, 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, registration } 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 & Partial<ModuleToolData>;\n\ntype ModuleToolData = { 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: ToolHandler<ModuleToolResult>,\n): ToolRegistration<ModuleToolResult> {\n return registration<ModuleToolData>(schema, run);\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 (_input, signal) =>\n said(await runCommand(commands, 'module validate', {}, signal), trimValidate),\n ),\n moduleTool(search, async (input, signal) =>\n said(\n await runCommand(\n commands,\n 'registry list',\n {\n axis: 'module',\n query: text(input.query),\n system: text(input.system),\n category: text(input.category),\n },\n signal,\n ),\n trimRegistryList,\n ),\n ),\n moduleTool(describe, async (input, signal) => {\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(\n commands,\n 'registry describe',\n { artifact: `module/${module}`, version: text(input.version) },\n signal,\n ),\n trimRegistryDescribe,\n );\n }),\n ];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACsCO,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;;;AChDA,IAAAA,iBAAyD;;;ACLlD,IAAM,YAAN,cAAwB,MAAM;AAAA,EACnC,cAAc;AACZ,UAAM,wBAAwB;AAAA,EAChC;AACF;AAGO,SAAS,gBAAgB,QAAuC;AACrE,MAAI,QAAQ,QAAS,OAAM,IAAI,UAAU;AAC3C;AAKO,SAAS,eAAkB,MAAkB,QAA6C;AAC/F,MAAI,WAAW,OAAW,QAAO;AACjC,MAAI,OAAO,MAAY;AAAA,EAAC;AACxB,QAAM,YAAY,IAAI,QAAe,CAAC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AAAA,MACF;AAAA,IACF,CAAC;AAAA,EACH;AACF;","names":["import_engine","import_engine","import_engine","resolve","text","text","input","module","group","import_proto","said","text","SEARCH","DESCRIBE","module"]}
package/dist/index.mjs CHANGED
@@ -152,7 +152,7 @@ var NO_INPUT = { type: "object", properties: {}, additionalProperties: false };
152
152
 
153
153
  // src/surfaces/canvas/commands.ts
154
154
  function commandEnd(path, error) {
155
- const { message, failure } = failureSays(error, { kind: "read", path });
155
+ const { message, failure } = failureSays(error);
156
156
  const failed = (why, see = "") => `lace ${path} failed (reason ${why}): ${message}${see}`;
157
157
  if (failure !== void 0) {
158
158
  const see = failure.url === void 0 ? "" : `; see ${failure.url}`;
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/contract/tool-registry.ts","../src/surfaces/canvas/canvas-tools.ts","../src/contract/cancel.ts","../src/surfaces/canvas/change.ts","../src/surfaces/canvas/commands.ts","../src/surfaces/canvas/enumerate.ts","../src/surfaces/canvas/registration.ts","../src/surfaces/canvas/ports.ts","../src/surfaces/canvas/resolve.ts","../src/surfaces/canvas/stated.ts","../src/surfaces/canvas/withhold.ts","../src/surfaces/canvas/render.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. `signal` is the host's cancellation of the call, where its chat has\n// one: once it aborts, the tool starts nothing further and stops waiting, and\n// what it already sent stands.\nexport type ToolHandler<R extends ToolResult = ToolResult> = (\n input: Record<string, unknown>,\n signal?: AbortSignal,\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 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. Each registration is a name, a description that carries\n// the tool's guidance to any host, an input schema and a handler, and says\n// nothing about the host's editor.\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 { Cancelled, untilCancelled } from '../../contract/cancel';\nimport type { ToolRegistration } from '../../contract/tool-registry';\nimport type { ToolResult, ToolSchema } from '../../contract/types';\nimport { applyChanges, OPERATIONS, parseChanges } from './change';\nimport { trimValidate } from './commands';\nimport { type CanvasToolPorts, endText, latest } from './ports';\nimport { errorText, InvalidInput, NO_INPUT, reasonText, registration } from './registration';\nimport { renderCanvas } from './render';\nimport type { StatedSlot } from './stated';\n\n// What each slot of a change names, as the canvas or the registry lists it.\nconst STATED_PROPERTIES: Record<StatedSlot, Record<string, unknown>> = {\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: its canvas path (`group.child`) or its own id.',\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: { type: 'string', description: 'The instance a connect wires from.' },\n output: { type: 'string', description: 'The output a connect wires from.' },\n targetInstance: { type: 'string', description: 'The instance a connect wires into.' },\n module: {\n type: 'string',\n description:\n 'The registry module a place adds, as `author/name`, and `author/name@version` to place a version other than the one the registry lists.',\n },\n};\n\nconst CHANGE: ToolSchema = {\n name: 'lace_change_module_canvas',\n title: 'Change module canvas',\n description: [\n 'Changes a Lace module canvas: places registry modules, wires and unwires instances, sets, binds and clears inputs, and renames, deletes and ungroups instances.',\n 'State each change as the canvas lists it: its `operation`, and each instance, input, output and registry module it works on by the name the canvas gives it.',\n \"Pass each literal the developer gave (an input's value, an instance's new name, the variable an input is bound to) in `value`, one change per entry.\",\n 'A connect that names no `output` and no `input` wires the two instances as the canvas does when one is dragged onto the other.',\n 'A change that names nothing on the canvas, or a name that fits several things, is not applied, and the result lists its candidates: ask the developer which is meant, or send the change again naming one.',\n 'A place whose module the registry lists nothing for points to lace_search_module_registry.',\n 'Every result carries the current canvas. 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 operation: {\n type: 'string',\n enum: OPERATIONS.map((operation) => operation.id),\n description: OPERATIONS.map((operation) => operation.text).join('; '),\n },\n ...STATED_PROPERTIES,\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>`).\",\n },\n },\n required: ['operation'],\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. Read it before a change when you do not know the names the canvas gives its instances, inputs and outputs.',\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 success says of the files it wrote. With no saved edits\n// left to generate, a Generate writes nothing, and the engine still\n// validates the Terraform on disk.\nfunction writtenText(written: readonly string[]): string {\n return written.length === 0\n ? 'Generated the Terraform: nothing was written.'\n : `Generated the Terraform. Files written: ${written.join(', ')}.`;\n}\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 Terraform\n// on disk, 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 writtenText(event.written),\n `lace module validate on the Terraform on disk: ${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// What a Save or a Generate says of a call its host cancelled: nothing is\n// sent once the call is cancelled, and one already sent is the engine's, goes\n// on, and is not undone.\nfunction cancelledSaid(operation: 'save' | 'Generate', sent: boolean): Said {\n return {\n text: sent\n ? `The call was cancelled after the ${operation} was sent: it goes on in the engine, and the canvas below may be from before it ends.`\n : `The call was cancelled before the ${operation} was sent: nothing was done.`,\n isError: false,\n };\n}\n\n// The canvas tools in their order: change, describe, save, generate.\nexport type CanvasTools = readonly [\n ToolRegistration,\n ToolRegistration,\n ToolRegistration,\n ToolRegistration,\n];\n\nexport function canvasTools(ports: CanvasToolPorts): CanvasTools {\n const [change, describe, save, generate] = canvasToolSchemas;\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 return [\n registration(change, async (input, signal) => {\n try {\n const text = await applyChanges(ports, parseChanges(input), signal);\n return answer([{ text, isError: false }]);\n } catch (error) {\n if (!(error instanceof InvalidInput)) throw error;\n return answer([{ text: errorText(error), isError: true }]);\n }\n }),\n registration(describe, () => answer([])),\n registration(save, async (_input, signal) =>\n answer(\n await attempt(async () => {\n if (signal?.aborted) return [cancelledSaid('save', false)];\n const saved: Said = { text: 'Saved the canvas.', isError: false };\n try {\n await untilCancelled(ports.editor.save(), signal);\n return [saved];\n } catch (error) {\n if (error instanceof Cancelled) return [cancelledSaid('save', true)];\n return [saved, unobserved(error)];\n }\n }),\n ),\n ),\n registration(generate, async (_input, signal) =>\n answer(\n await attempt(async () => {\n if (signal?.aborted) return [cancelledSaid('Generate', false)];\n const said: Said[] = [];\n const events = ports.editor.generate()[Symbol.asyncIterator]();\n try {\n for (\n let next = await untilCancelled(events.next(), signal);\n next.done !== true;\n next = await untilCancelled(events.next(), signal)\n ) {\n said.push(...generateSaid(next.value));\n }\n } catch (error) {\n if (error instanceof Cancelled) return [...said, cancelledSaid('Generate', true)];\n said.push(unobserved(error));\n }\n return said;\n }),\n ),\n ),\n ];\n}\n","// The host's cancellation of a call (the `signal` a handler takes), read the\n// one way everywhere in the package: a step not yet started is not started,\n// and a wait in progress ends; what was already sent goes on.\n\n// The host cancelled the call before the step that would have run.\nexport class Cancelled extends Error {\n constructor() {\n super('the call was cancelled');\n }\n}\n\n// Stops a call its host cancelled, at a step boundary.\nexport function stopIfCancelled(signal: AbortSignal | undefined): void {\n if (signal?.aborted) throw new Cancelled();\n}\n\n// `work`, or `Cancelled` once the call's signal aborts first: the call stops\n// waiting, and what `work` stands for goes on. The listener ends with the\n// wait.\nexport function untilCancelled<T>(work: Promise<T>, signal: AbortSignal | undefined): Promise<T> {\n if (signal === undefined) return work;\n let stop = (): void => {};\n const cancelled = new Promise<never>((_, fail) => {\n stop = () => fail(new Cancelled());\n if (signal.aborted) stop();\n else signal.addEventListener('abort', stop, { once: true });\n });\n return Promise.race([work, cancelled]).finally(() => signal.removeEventListener('abort', stop));\n}\n\n// A step that waits on something: not started once the call is cancelled,\n// and otherwise waited on until it is.\nexport function cancellable<T>(\n start: () => Promise<T>,\n signal: AbortSignal | undefined,\n): Promise<T> {\n if (signal?.aborted) return Promise.reject(new Cancelled());\n return untilCancelled(start(), signal);\n}\n","// The change tool's work: each change, stated as the canvas lists it,\n// resolved slot by slot against the canvas as it stands when the change is\n// reached, then applied as one action.\n//\n// A slot resolves by name (resolve.ts): one option is the change's, and a\n// name that fits several options, fits none, or is not stated where the\n// operation needs it leaves the change unapplied, with the candidates the\n// canvas or the registry lists for the slot, so the model can ask the\n// developer or send the change again. A connect that names no pin is sent as\n// the canvas sends a drag of one instance onto another (`auto_connect`); one\n// that names both pins is a connect of those pins into any input of the\n// target, wired or not, as a pin drag is; one that names a single pin lists\n// the pairs the engine's matcher reads for it. The change's value is\n// withheld where text the package does not write enters a result: an\n// engine's refusal, a command's failure, a stream's end, and each name the\n// change stated that a result says back (withhold.ts).\nimport { type ApplyResult, ApplyUnobservedError, InputMode } from '@lace-cloud/canvas/engine';\nimport { Cancelled, cancellable, stopIfCancelled } from '../../contract/cancel';\nimport { runCommand } from './commands';\nimport {\n type CanvasInput,\n type CanvasInstance,\n type CanvasReading,\n connectionId,\n instanceOptions,\n moduleId,\n moduleOptions,\n type Option,\n pairListing,\n pinOptions,\n pinRef,\n readCanvas,\n} from './enumerate';\nimport { type CanvasEditor, type CanvasToolPorts, endText, latest } from './ports';\nimport { errorText, InvalidInput } from './registration';\nimport { resolve } from './resolve';\nimport { STATED_SLOTS, type Stated, type StatedSlot, slotsStated } from './stated';\nimport { withhold } from './withhold';\n\n// One entry of the tool's input: its operation, the names it states slot by\n// slot, and the literal the developer gave, undefined where it gave none.\nexport type Change = {\n readonly operation: Operation;\n readonly stated: Stated;\n readonly value: unknown;\n};\n\n// A change that cannot be applied as it was sent.\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\nexport function parseChanges(input: Record<string, unknown>): Change[] {\n const { changes } = input;\n if (!Array.isArray(changes) || changes.length === 0) {\n throw new InvalidInput('`changes` is a list of one or more changes');\n }\n return changes.map((entry: unknown, index) => {\n const which = `change ${index + 1}`;\n if (!isRecord(entry)) throw new InvalidInput(`${which} is an object`);\n const operation = OPERATIONS.find((each) => each.id === entry.operation);\n if (operation === undefined) {\n const ids = OPERATIONS.map((each) => each.id).join(', ');\n throw new InvalidInput(`${which} needs \\`operation\\`: one of ${ids}`);\n }\n // An empty name states nothing, as an absent one does.\n const names = STATED_SLOTS.flatMap((slot) => {\n const name = entry[slot];\n if (!present(name) || name === '') return [];\n if (typeof name !== 'string') {\n throw new InvalidInput(`${which}: \\`${slot}\\` is a name, as the canvas lists it`);\n }\n return [[slot, name]];\n });\n return {\n operation,\n stated: Object.fromEntries(names),\n value: present(entry.value) ? entry.value : undefined,\n };\n });\n}\n\n// The most candidates a reason lists.\nconst LISTED = 12;\n\n// Names as a reason lists them: the first `LISTED`, and how many more.\nfunction listed(names: readonly string[]): string {\n const kept = names.slice(0, LISTED);\n const more = names.length - kept.length;\n return [...kept, ...(more > 0 ? [`and ${more} more`] : [])].join(', ');\n}\n\nconst candidates = (names: readonly string[]): string => `Candidates: ${listed(names)}.`;\n\n// Where a slot's names come from: the registry for a module, the canvas for\n// every other slot.\nconst listedBy = (slot: StatedSlot): string => (slot === 'module' ? 'registry' : 'canvas');\n\n// What a slot names when it names no one option: nothing, for a slot the\n// change does not state; or the name it states, fitting no option or\n// several, as a result says it back (withheld against the change's value).\ntype Unresolved =\n | { readonly kind: 'missing' }\n | { readonly kind: 'none'; readonly stated: string }\n | { readonly kind: 'several'; readonly stated: string; readonly names: readonly string[] };\n\ntype Named<T> = { readonly kind: 'one'; readonly value: T } | Unresolved;\n\n// Why a slot names no one option, then `instead`: what the model can name.\n// `label` says what the slot offers (\"instance\", \"input of app\").\nfunction unresolvedText(\n slot: StatedSlot,\n label: string,\n unresolved: Unresolved,\n instead: string,\n): string {\n switch (unresolved.kind) {\n case 'missing':\n return `this change states no \\`${slot}\\`. ${instead}`;\n case 'none':\n return `no ${label} is named \\`${unresolved.stated}\\`. ${instead}`;\n case 'several':\n return `\\`${unresolved.stated}\\` names more than one ${label}: ${listed(unresolved.names)}. Name one as the ${listedBy(slot)} lists it.`;\n }\n}\n\nconst nothingOffered = (label: string): string => `the canvas offers no ${label} for this change.`;\n\n// Several reasons as one: each a sentence, in the order the slots stand.\nfunction reasons(each: readonly string[]): string {\n return each.map((why, i) => (i === 0 ? why : why[0].toUpperCase() + why.slice(1))).join(' ');\n}\n\n// What a slot names among the options the canvas offers it: its option's\n// value, or why the change cannot be applied, listing the options.\ntype Picked<T> = { readonly value: T } | { readonly why: string };\n\nconst whyOf = (picked: Picked<unknown>): string[] => ('why' in picked ? [picked.why] : []);\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// and the change in words once the engine applied it, read from the apply's\n// result and the canvas it produced.\ntype Plan = {\n readonly action: Action;\n readonly summary: (result: ApplyResult, after: CanvasReading) => string;\n};\n\ntype Resolving = {\n readonly canvas: CanvasReading;\n readonly change: Change;\n readonly ports: CanvasToolPorts;\n // The call's cancellation, for what the plan waits on.\n readonly signal: AbortSignal | undefined;\n // What the name `stated` names in `slot` among `options`.\n readonly name: <T>(\n slot: StatedSlot,\n stated: string | undefined,\n options: readonly Option<T>[],\n ) => Named<T>;\n // What `slot` names among the canvas's `options`.\n readonly choose: <T>(slot: StatedSlot, label: string, options: readonly Option<T>[]) => Picked<T>;\n // What `slot` names among the canvas's `options`, or the change cannot be\n // applied.\n readonly pick: <T>(slot: StatedSlot, label: string, options: readonly Option<T>[]) => 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, what it does in the words the tool's schema gives\n// the model, the slots it names things by, whether it writes the literal a\n// change carries in `value`, and how it resolves the rest of a change.\ntype Operation = {\n readonly id: string;\n readonly text: string;\n readonly slots: readonly StatedSlot[];\n readonly takesValue: boolean;\n readonly plan: (resolving: Resolving) => Promise<Plan>;\n};\n\n// The literal the developer gave: the tool writes no value of its own.\nfunction given(change: Change, what: string): unknown {\n if (change.value === undefined) {\n throw new Unapplicable(`this change needs ${what}: pass it in \\`value\\`.`);\n }\n return change.value;\n}\n\nfunction givenName(change: Change, what: string): string {\n const name = given(change, what);\n if (typeof name !== 'string') throw new Unapplicable(`${what} is text: pass it in \\`value\\`.`);\n return name;\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\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: the instance\n// among every instance, and the input among those of its inputs whose\n// binding is in one of `modes`, so an operation is offered only the inputs\n// it can act on. `offered` says what those inputs are, of an instance.\nfunction pickInput(\n { canvas, pick }: Resolving,\n modes: readonly BindingMode[],\n offered: (instance: CanvasInstance) => string,\n) {\n const instance = pick('instance', 'instance', instanceOptions(canvas.instances));\n const inputs = instance.inputs.filter((input) => modes.includes(input.mode));\n const input = pick('input', offered(instance), pinOptions(inputs));\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\n// What a place says where the listing does not settle the module.\nconst SEARCH = 'Find it with lace_search_module_registry and name it as `author/name`.';\n\n// A registry module as a change states it: `author/name`, or the name\n// alone, and after `@` the version to place where it names one. `query` is\n// the name part, which the registry listing is narrowed by. An `@` that\n// names no version is no module a place can add.\nfunction moduleRef(stated: string) {\n const at = stated.lastIndexOf('@');\n if (at < 1) return { ref: stated, query: stated.split('/').at(-1) ?? '' };\n const ref = stated.slice(0, at);\n const version = stated.slice(at + 1);\n if (version === '') {\n throw new Unapplicable(\n '`module` ends in `@` with no version after it. Name the version, as `author/name@version`, or leave out `@` to place the version the registry lists.',\n );\n }\n return { ref, query: ref.split('/').at(-1) ?? '', version };\n}\n\nconst place: Operation = {\n id: 'place',\n text: 'place: add a registry module to the canvas as a new instance',\n slots: ['module'],\n takesValue: false,\n async plan({ change, ports, signal, name, note }) {\n const stated = change.stated.module === undefined ? undefined : moduleRef(change.stated.module);\n const version = stated?.version;\n if (stated === undefined || stated.query === '') {\n throw new Unapplicable(\n unresolvedText('module', 'registry module', { kind: 'missing' }, SEARCH),\n );\n }\n const listing = await cancellable(\n () =>\n runCommand(\n ports.commands,\n 'registry list',\n { axis: 'module', limit: CATALOG_LIMIT, query: stated.query },\n signal,\n ),\n signal,\n );\n if (listing.failed !== undefined) throw new Error(listing.failed.text);\n if (listing.documents.some((document) => 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 const module = name(\n 'module',\n stated.ref,\n moduleOptions(listing.documents.flatMap((document) => document.items)),\n );\n if (module.kind !== 'one') {\n throw new Unapplicable(unresolvedText('module', 'registry module', module, SEARCH));\n }\n const row = module.value;\n return {\n action: {\n place_module: { author: row.author, name: row.name, version: version ?? row.version },\n },\n summary: (result) =>\n `placed ${moduleId(row)} ${version === undefined ? row.version : withhold(version, change.value)} as ${result.created.map((ref) => ref.id).join(', ')}`,\n };\n },\n};\n\n// A connect that names no pin: the engine's matcher wires the two\n// instances, as a drag of one onto the other does, and the pairs it leaves\n// tied come back for the developer to choose between. A connect that wired\n// nothing changed nothing.\nfunction autoConnect(\n canvas: CanvasReading,\n source: CanvasInstance,\n target: CanvasInstance,\n ends: { scope: string; source_scope: string; source: string; target: string },\n note: (line: string) => void,\n): Plan {\n const between = (reading: CanvasReading) =>\n reading.wires\n .filter((wire) => wire.source === source.id && wire.target === target.id)\n .map((wire) =>\n connectionId(\n pinRef(wire.source, wire.source_output),\n pinRef(wire.target, wire.target_input),\n ),\n );\n const before = new Set(between(canvas));\n return {\n action: { auto_connect: ends },\n summary(result, after) {\n const wired = between(after).filter((wire) => !before.has(wire));\n const ties = result.ties.map((pair) =>\n connectionId(pinRef(source.id, pair.output), pinRef(target.id, pair.input)),\n );\n const choose = 'Send it again naming the `output` and the `input` the developer means.';\n if (wired.length === 0) {\n throw new Unapplicable(\n ties.length > 0\n ? `more than one pair fits equally well, so nothing was wired: ${listed(ties)}. ${choose}`\n : `the engine wired nothing from ${source.id} into ${target.id}.`,\n );\n }\n if (ties.length > 0) {\n note(`Not connected, more than one pair fits equally well: ${listed(ties)}. ${choose}`);\n }\n return `connected ${source.id} to ${target.id}: ${wired.join(', ')}`;\n },\n };\n}\n\nconst connect: Operation = {\n id: 'connect',\n text: 'connect: wire an output of one instance into an input of another',\n slots: ['sourceInstance', 'output', 'targetInstance', 'input'],\n takesValue: false,\n async plan({ canvas, change, ports, signal, choose, note }) {\n const instances = instanceOptions(canvas.instances);\n const sourcePicked = choose('sourceInstance', 'instance', instances);\n const targetPicked = choose('targetInstance', 'instance', instances);\n if (!('value' in sourcePicked) || !('value' in targetPicked)) {\n throw new Unapplicable(reasons([...whyOf(sourcePicked), ...whyOf(targetPicked)]));\n }\n const [source, target] = [sourcePicked.value, targetPicked.value];\n if (source.id === target.id) {\n throw new Unapplicable(\n `\\`sourceInstance\\` and \\`targetInstance\\` both name ${source.id}: a connect wires one instance into another.`,\n );\n }\n const ends = {\n scope: target.scope,\n source_scope: source.scope,\n source: source.name,\n target: target.name,\n };\n const stated = { output: change.stated.output, input: change.stated.input };\n if (stated.output === undefined && stated.input === undefined) {\n return autoConnect(canvas, source, target, ends, note);\n }\n const output =\n stated.output === undefined\n ? undefined\n : choose('output', `output of ${source.id}`, pinOptions(source.outputs));\n const input =\n stated.input === undefined\n ? undefined\n : choose('input', `input of ${target.id}`, pinOptions(target.inputs));\n const whys = [...(output ? whyOf(output) : []), ...(input ? whyOf(input) : [])];\n // A connect naming one pin lists the pairs the engine's matcher gives\n // for it, from its own read of the two instances.\n if (output === undefined || input === undefined) {\n const [named, unnamed] = output === undefined ? ['input', 'output'] : ['output', 'input'];\n const scored = await cancellable(\n () =>\n ports.editor.wiringCandidates({\n scope: ends.scope,\n sourceScope: ends.source_scope,\n source: ends.source,\n target: ends.target,\n }),\n signal,\n );\n const pairs = pairListing(source, target, scored, {\n ...(output && 'value' in output ? { output: output.value.name } : {}),\n ...(input && 'value' in input ? { input: input.value.name } : {}),\n });\n whys.push(\n `this change states \\`${named}\\` and no \\`${unnamed}\\`: state both, or neither to wire the two instances as the canvas does. ${\n pairs.length > 0\n ? candidates(pairs)\n : `The engine's matcher pairs no output of ${source.id} with an input of ${target.id}.`\n }`,\n );\n throw new Unapplicable(reasons(whys));\n }\n if (!('value' in output) || !('value' in input)) throw new Unapplicable(reasons(whys));\n const [from, to] = [output.value.name, input.value.name];\n return {\n action: { connect: { ...ends, source_output: from, target_input: to } },\n summary: () => `connected ${connectionId(pinRef(source.id, from), pinRef(target.id, to))}`,\n };\n },\n};\n\nconst disconnect: Operation = {\n id: 'disconnect',\n text: \"disconnect: remove the wire into an instance's input\",\n slots: ['instance', 'input'],\n takesValue: false,\n async plan(resolving) {\n const { instance, input } = pickInput(resolving, ['wired'], (of) => `wired input of ${of.id}`);\n return {\n action: {\n disconnect: { scope: instance.scope, target: instance.name, input_name: input.name },\n },\n summary: () => `disconnected ${pinRef(instance.id, input.name)}`,\n };\n },\n};\n\nconst set: Operation = {\n id: 'set',\n text: 'set: give an input of an instance a literal value',\n slots: ['instance', 'input'],\n takesValue: true,\n async plan(resolving) {\n const value = given(resolving.change, 'the value the developer gave');\n const { instance, input } = pickInput(resolving, EVERY_MODE, (of) => `input of ${of.id}`);\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 ${pinRef(instance.id, input.name)} ${shown}`,\n };\n },\n};\n\nconst bind: Operation = {\n id: 'bind',\n text: \"bind: make an input of an instance take its value from a variable of the module (`var.<name>`), so the module's caller sets it\",\n slots: ['instance', 'input'],\n takesValue: true,\n async plan(resolving) {\n const variable = variableName(givenName(resolving.change, \"the variable's name\"));\n const { instance, input } = pickInput(resolving, EVERY_MODE, (of) => `input of ${of.id}`);\n return {\n action: updateInput(instance, input, { mode: InputMode.INPUT_MODE_VARIABLE, variable }),\n summary: () => `bound ${pinRef(instance.id, input.name)} to var.${variable}`,\n };\n },\n};\n\nconst clear: Operation = {\n id: 'clear',\n text: 'clear: unset an input of an instance, removing the value, variable or expression it holds',\n slots: ['instance', 'input'],\n takesValue: false,\n async plan(resolving) {\n const { instance, input } = pickInput(\n resolving,\n ['literal', 'variable', 'expression'],\n (of) => `input of ${of.id} that holds a value`,\n );\n return {\n action: updateInput(instance, input, { mode: InputMode.INPUT_MODE_EMPTY }),\n summary: () => `cleared ${pinRef(instance.id, input.name)}`,\n };\n },\n};\n\nconst rename: Operation = {\n id: 'rename',\n text: 'rename: give an instance a new name',\n slots: ['instance'],\n takesValue: true,\n async plan({ canvas, change, pick }) {\n const name = givenName(change, 'the new name');\n const instance = 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 };\n },\n};\n\nconst remove: Operation = {\n id: 'delete',\n text: 'delete: remove an instance from the canvas',\n slots: ['instance'],\n takesValue: false,\n async plan({ canvas, pick }) {\n const instance = 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 };\n },\n};\n\nconst ungroup: Operation = {\n id: 'ungroup',\n text: 'ungroup: dissolve a group, moving the instances inside it up beside it',\n slots: ['instance'],\n takesValue: false,\n async plan({ canvas, pick }) {\n const groups = new Set(canvas.groups.map((group) => group.id));\n const group = 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 };\n },\n};\n\n// The operations a change can be. Each is one row: its name, what it does,\n// what it names, and how it 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 | { readonly kind: 'applied'; readonly summary: string }\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 // The host cancelled the call before this change's apply was sent.\n | { readonly kind: 'cancelled' }\n // An earlier change's apply went unobserved: the stream it would be read\n // on had ended, so this change was not sent.\n | { readonly kind: 'notRun' };\n\nconst CANCELLED: Outcome = { kind: 'cancelled' };\nconst NOT_RUN: Outcome = { kind: 'notRun' };\n\n// The lines a change says before it is resolved: each slot it states that\n// its operation does not use, and a value an operation that takes none was\n// sent.\nfunction unusedLines({ operation, stated, value }: Change): string[] {\n const unused = slotsStated(stated).filter((slot) => !operation.slots.includes(slot));\n return [\n ...unused.map((slot) => `\\`${slot}\\` is not used by ${operation.id}.`),\n ...(value !== undefined && !operation.takesValue\n ? [`The \\`value\\` sent with this change was not used: ${operation.id} takes none.`]\n : []),\n ];\n}\n\nasync function resolveAndApply(\n ports: CanvasToolPorts,\n change: Change,\n signal: AbortSignal | undefined,\n note: (line: string) => void,\n): Promise<Outcome> {\n const canvas = readCanvas(await latest(ports.source));\n const name = <T>(\n slot: StatedSlot,\n stated: string | undefined,\n options: readonly Option<T>[],\n ): Named<T> => {\n if (stated === undefined) return { kind: 'missing' };\n const resolved = resolve(options, stated);\n // The name as a result says it back.\n const echoed = withhold(stated, change.value);\n switch (resolved.kind) {\n case 'one': {\n const [listedAs] = resolved.option.names;\n const where = slot === 'module' ? 'in the registry' : 'on the canvas';\n if (resolved.folded) note(`Your \\`${slot}\\` ${echoed} is \\`${listedAs}\\` ${where}.`);\n return { kind: 'one', value: resolved.option.value };\n }\n case 'several':\n return {\n kind: 'several',\n stated: echoed,\n names: resolved.options.map((each) => each.names[0]),\n };\n case 'none':\n return { kind: 'none', stated: echoed };\n }\n };\n const choose = <T>(slot: StatedSlot, label: string, options: readonly Option<T>[]): Picked<T> => {\n if (options.length === 0) return { why: nothingOffered(label) };\n const named = name(slot, change.stated[slot], options);\n if (named.kind === 'one') return { value: named.value };\n const offered = options.map((option) => option.names[0]);\n return { why: unresolvedText(slot, label, named, candidates(offered)) };\n };\n const resolving: Resolving = {\n canvas,\n change,\n ports,\n signal,\n name,\n choose,\n pick(slot, label, options) {\n const picked = choose(slot, label, options);\n if ('why' in picked) throw new Unapplicable(picked.why);\n return picked.value;\n },\n note,\n };\n for (const line of unusedLines(change)) note(line);\n const plan = await change.operation.plan(resolving);\n // Nothing is applied once the call is cancelled; an apply already sent is\n // the engine's, and stands.\n stopIfCancelled(signal);\n const result = await ports.editor.apply([plan.action]);\n if (!result.success) {\n const refusals = result.errors.map((error) => error.message).join('; ');\n return {\n kind: 'notApplied',\n why: `the engine refused it: ${withhold(refusals, change.value)}`,\n };\n }\n const after = readCanvas(await latest(ports.source));\n return { kind: 'applied', summary: plan.summary(result, after) };\n}\n\n// One change, whatever becomes of it: a failure of this change (a slot that\n// names nothing or several things, an engine that refused, a listing that\n// failed) is this change's outcome and stops no other, and so is an apply\n// the engine answered whose frame the session's stream ended before. A\n// reason the package wrote is said as it is; any other failure's text, and\n// the account of a stream's end, are withheld against the change's value.\nasync function runChange(\n ports: CanvasToolPorts,\n change: Change,\n signal: AbortSignal | undefined,\n note: (line: string) => void,\n): Promise<Outcome> {\n try {\n return await resolveAndApply(ports, change, signal, note);\n } catch (error) {\n if (error instanceof ApplyUnobservedError) {\n return { kind: 'unobserved', end: withhold(endText(error.end), change.value) };\n }\n // The host cancelled the call before this change's apply was sent (a\n // listing or a wiring read no longer waited on). Anything once the apply\n // was sent is the apply's own outcome.\n if (error instanceof Cancelled) return CANCELLED;\n if (error instanceof Unapplicable) return { kind: 'notApplied', why: error.message };\n return { kind: 'notApplied', why: withhold(errorText(error), change.value) };\n }\n}\n\nfunction outcomeLine(number: number, outcome: Outcome): string {\n const head = `Change ${number}:`;\n switch (outcome.kind) {\n case 'applied':\n return `${head} applied. ${outcome.summary}.`;\n case 'notApplied':\n return `${head} not applied. Reason: ${outcome.why}`;\n case 'cancelled':\n return `${head} not applied. The call was cancelled before it applied.`;\n case 'unobserved':\n return `${head} sent, and the engine answered it, but the session's stream ended (${outcome.end}) before the canvas showed it, so whether it applied cannot be read here. Do not send it again before the canvas is open again.`;\n case 'notRun':\n return `${head} not run. The session's stream ended before it, so it was not sent.`;\n }\n}\n\n// Applies the changes in order, each against the state the one before it\n// produced, and says per change what was applied or why nothing was, with\n// the lines it noted beneath it. A summary shows the value the operation\n// wrote unless the input is sensitive.\n//\n// `signal` is the host's cancellation of the call. Once it aborts, nothing\n// further is started: a listing or wiring read in progress is no longer\n// waited on, and the change in progress and every later one say the call\n// was cancelled before they applied. Once an apply goes unobserved (the\n// session's stream ended before its frame), no later change is sent: the\n// stream that would show it has ended.\nexport async function applyChanges(\n ports: CanvasToolPorts,\n changes: readonly Change[],\n signal?: AbortSignal,\n): Promise<string> {\n const lines: string[] = [];\n let ended = false;\n for (const [index, change] of changes.entries()) {\n const notes: string[] = [];\n const outcome: Outcome = ended\n ? NOT_RUN\n : signal?.aborted\n ? CANCELLED\n : await runChange(ports, change, signal, (line) => notes.push(line));\n ended = ended || outcome.kind === 'unobserved';\n lines.push(\n outcomeLine(index + 1, outcome),\n ...(outcome.kind === 'cancelled' || outcome.kind === 'notRun'\n ? []\n : notes.map((line) => ` ${line}`)),\n );\n }\n return lines.join('\\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 type CommandFailure,\n type CommandsPort,\n ConnectError,\n failureSays,\n type JsonOf,\n} from '@lace-cloud/canvas/engine';\nimport { moduleId } from './enumerate';\nimport { refusalReason } 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// Why a command ended, in the chat's words around what the failure says\n// (`failureSays`, the one reading every surface shows): the command's path,\n// and the reason the failure names as data — a failure document's, or a\n// refusal's when the engine refused the call before the command started —\n// by its wire spelling, or the API's own code when the API decided it, and\n// the page a document's reason points at when it names one. The chat's\n// commands are reads, so a stream that ended under one says to run it\n// again.\nfunction commandEnd(path: BoundPath, error: unknown): CommandEnd {\n const { message, failure } = failureSays(error, { kind: 'read', path });\n const failed = (why: string, see = '') => `lace ${path} failed (reason ${why}): ${message}${see}`;\n if (failure !== undefined) {\n const see = failure.url === undefined ? '' : `; see ${failure.url}`;\n return { text: failed(failure.apiCode ?? failure.reason, see), failure };\n }\n if (error instanceof ConnectError) return { text: failed(refusalReason(error)) };\n return { text: `lace ${path} did not finish cleanly (${message})` };\n}\n\n// `signal` is the tool call's cancellation, which the port reads as the\n// consumer no longer listening: the call stops waiting, and the command keeps\n// whatever it already did.\nexport async function runCommand<P extends BoundPath>(\n commands: CommandsPort,\n path: P,\n args: ArgsOf<P>,\n signal: AbortSignal = new AbortController().signal,\n): Promise<CommandOutput<P>> {\n const documents: JsonOf<P>[] = [];\n try {\n for await (const document of commands.invoke(path, args, 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 each slot a change names, and\n// the names it offers each by. `readCanvas` is the only fold over the Bundle\n// in this package, and it folds through proto's projection\n// (`projectCanvasView`), inspection (`deriveNodeConfig`), instance\n// resolution (`resolveInstance`) and diagnostic-to-node mapping\n// (`nodeIdForDiagnostic`) alone; every option 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.\nimport type { CanvasSource, JsonOf, WiringCandidate } from '@lace-cloud/canvas/engine';\nimport {\n type Diagnostic,\n deriveNodeConfig,\n nodeIdForDiagnostic,\n projectCanvasView,\n type RenderEdge,\n type RenderInput,\n type RenderOutput,\n resolveInstance,\n} from '@lace-cloud/proto';\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\n// One of the engine's diagnostics, with the canvas path of the instance it\n// is about where proto's one diagnostic-to-node mapping finds one.\nexport type CanvasDiagnostic = {\n readonly diagnostic: Diagnostic;\n readonly node: string | null;\n};\n\nexport type CanvasReading = {\n readonly module: string;\n readonly instances: readonly CanvasInstance[];\n readonly wires: readonly RenderEdge[];\n readonly groups: readonly CanvasGroup[];\n readonly diagnostics: readonly CanvasDiagnostic[];\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 instances,\n wires: view.edges,\n groups: view.groups.map((group) => ({ id: group.id, members: group.node_ids })),\n diagnostics: source.diagnostics.map((diagnostic) => ({\n diagnostic,\n node: nodeIdForDiagnostic(view, diagnostic),\n })),\n };\n}\n\n// One thing a slot can name: the names it is named by, the one the canvas\n// lists it by first, and the thing.\nexport type Option<T> = {\n readonly names: readonly [string, ...string[]];\n readonly value: T;\n};\n\n// An instance, named by its canvas path, then by its own id.\nexport function instanceOptions(instances: readonly CanvasInstance[]): Option<CanvasInstance>[] {\n return instances.map((instance) => ({ names: [instance.id, instance.name], value: instance }));\n}\n\n// A pin of an instance, named by its name.\nexport function pinOptions<P extends { readonly name: string }>(pins: readonly P[]): Option<P>[] {\n return pins.map((pin) => ({ names: [pin.name], value: pin }));\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\n// A registry module, named as `author/name`, then by its name.\nexport function moduleOptions(rows: readonly RegistryRow[]): Option<RegistryRow>[] {\n return rows.map((row) => ({ names: [moduleId(row), row.name], value: row }));\n}\n\n// A wire's end as the canvas lists it: an instance's canvas path and the\n// pin's name.\nexport function pinRef(instance: string, pin: string): string {\n return `${instance}.${pin}`;\n}\n\n// A wire as the canvas lists it.\nexport function connectionId(from: string, to: string): string {\n return `${from} → ${to}`;\n}\n\n// The engine matcher's pairs from source into target (`scored`, its read\n// for the two), as a connect lists them: in the matcher's order, best\n// first, each with its score, held to the one pin the change named.\nexport function pairListing(\n source: CanvasInstance,\n target: CanvasInstance,\n scored: readonly WiringCandidate[],\n pin: { readonly output?: string; readonly input?: string },\n): string[] {\n return scored\n .filter((pair) => pair.sourceInstance === source.name && pair.targetInstance === target.name)\n .filter((pair) => pin.output === undefined || pair.output === pin.output)\n .filter((pair) => pin.input === undefined || pair.input === pin.input)\n .map(\n (pair) =>\n `${connectionId(pinRef(source.id, pair.output), pinRef(target.id, pair.input))} (score ${pair.score})`,\n );\n}\n","import { 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// The reason a refused engine call names: the API's own code when the API\n// decided it, else the reason it carries, spelled as a failure document\n// spells it.\nexport function refusalReason(error: ConnectError): string {\n return error.apiCode ?? reasonWire(error.reason);\n}\n\n// A thrown error in words: its message, and for a refused engine call the\n// reason it names.\nexport function errorText(error: unknown): string {\n if (error instanceof ConnectError) return `${error.message} (reason ${refusalReason(error)})`;\n return error instanceof Error ? error.message : String(error);\n}\n\n// A tool's registration, whose handler always answers: a thrown error is\n// the call's result, said in the error's own words, never a rejection the\n// host's chat has to translate. A tool whose result carries data for its\n// host beside the text (`E`, each part optional) answers a failure with\n// none of it.\nexport function registration<E extends object = object>(\n schema: ToolSchema,\n run: ToolHandler<ToolResult & Partial<E>>,\n): ToolRegistration<ToolResult & Partial<E>> {\n const none: Partial<E> = {};\n return {\n schema,\n async handler(input, signal) {\n try {\n return await run(input, signal);\n } catch (error) {\n return { ...none, content: errorText(error), isError: true };\n }\n },\n };\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","// 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, and one with a\n// `commands` port alone constructs the module tools.\nimport type {\n ApplyUnobservedError,\n CanvasSource,\n CommandsPort,\n EditorPort,\n SourceEnd,\n SourcePort,\n} from '@lace-cloud/canvas/engine';\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};\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","// One slot's resolution: the name a change states, matched against the\n// names of each option the slot offers, in four steps: exactly on an\n// option's first name (an instance's canvas path, a module's `author/name`),\n// exactly on any of its names, then each again ignoring case. The first step\n// with any hit decides: one hit is the option, several are ambiguous, and a\n// later step is never reached. No hit at any step is unmatched. Both sides\n// are compared in one Unicode form (NFC), so a name typed decomposed finds\n// the name the canvas holds composed.\nimport type { Option } from './enumerate';\n\nexport type Resolved<T> =\n | { readonly kind: 'one'; readonly option: Option<T>; readonly folded: boolean }\n | { readonly kind: 'several'; readonly options: readonly Option<T>[] }\n | { readonly kind: 'none' };\n\ntype Step = {\n // Whether the step ignores case.\n readonly folded: boolean;\n readonly names: (option: Option<unknown>) => readonly string[];\n};\n\nconst first = (option: Option<unknown>) => option.names.slice(0, 1);\nconst every = (option: Option<unknown>) => option.names;\n\nconst STEPS: readonly Step[] = [\n { folded: false, names: first },\n { folded: false, names: every },\n { folded: true, names: first },\n { folded: true, names: every },\n];\n\nexport function resolve<T>(options: readonly Option<T>[], stated: string): Resolved<T> {\n const step = STEPS.map((each) => {\n const key = (name: string) => {\n const normal = name.normalize('NFC');\n return each.folded ? normal.toLowerCase() : normal;\n };\n const hits = options.filter((option) =>\n each.names(option).some((name) => key(name) === key(stated)),\n );\n return { folded: each.folded, hits };\n }).find((each) => each.hits.length > 0);\n if (step === undefined) return { kind: 'none' };\n return step.hits.length === 1\n ? { kind: 'one', option: step.hits[0], folded: step.folded }\n : { kind: 'several', options: step.hits };\n}\n","// The names one change states, each in its own slot, as the canvas or the\n// registry lists them: an instance by its canvas path or its own id, a pin\n// by its name, a registry module as `author/name` or by its name.\nexport const STATED_SLOTS = [\n 'instance',\n 'input',\n 'sourceInstance',\n 'output',\n 'targetInstance',\n 'module',\n] as const;\n\nexport type StatedSlot = (typeof STATED_SLOTS)[number];\n\nexport type Stated = Readonly<Partial<Record<StatedSlot, string>>>;\n\n// The slots a change states, in slot order.\nexport function slotsStated(stated: Stated): StatedSlot[] {\n return STATED_SLOTS.filter((slot) => stated[slot] !== undefined);\n}\n","// What a result withholds of the value a change carries. The value is\n// withheld only from text the package does not write itself and that could\n// carry it: an engine's refusal, a command's failure, the account of a\n// session's stream ending, and each name the model stated that a result\n// says back. The package's own words, and the names the canvas or the\n// registry lists, are never withheld: they are public, and the canvas the\n// result ends with prints them.\n\n// The one token that stands where a value was.\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\nconst GO_ESCAPES: Readonly<Record<string, string>> = {\n '\\x07': '\\\\a',\n '\\b': '\\\\b',\n '\\f': '\\\\f',\n '\\n': '\\\\n',\n '\\r': '\\\\r',\n '\\t': '\\\\t',\n '\\v': '\\\\v',\n '\"': '\\\\\"',\n '\\\\': '\\\\\\\\',\n};\n\n// What Go's strconv counts printable: a letter, mark, number, punctuation\n// or symbol, or the ASCII space.\nconst GO_PRINTABLE = /^[ \\p{L}\\p{M}\\p{N}\\p{P}\\p{S}]$/u;\n\n// One character as Go's `%q` writes it inside quotes.\nfunction goEscaped(char: string): string {\n const code = char.codePointAt(0) ?? 0;\n if (GO_ESCAPES[char] !== undefined) return GO_ESCAPES[char];\n if (GO_PRINTABLE.test(char)) return char;\n const [mark, width] = code < 0x80 ? ['x', 2] : code < 0x10000 ? ['u', 4] : ['U', 8];\n return `\\\\${mark}${code.toString(16).padStart(width, '0')}`;\n}\n\n// Every form a literal is written in: itself; quoted with JSON's escapes;\n// quoted as Go's `%q` writes it, which is how the engine quotes a value it\n// names; and each quoted form's escapes unquoted.\nfunction writtenForms(literal: string): string[] {\n const quoted = [JSON.stringify(literal), `\"${[...literal].map(goEscaped).join('')}\"`];\n return [literal, ...quoted, ...quoted.map((form) => form.slice(1, -1))];\n}\n\n// The forms of a value's literals, longest first, so one that holds another\n// is replaced whole.\nfunction forms(value: unknown): string[] {\n const all = literalTexts(value)\n .filter((literal) => literal !== '')\n .flatMap(writtenForms);\n return [...new Set(all)].sort((a, b) => b.length - a.length);\n}\n\n// `text` as a pattern that matches it literally.\nfunction escapeRegExp(text: string): string {\n return text.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\nconst NAME = /^[A-Za-z0-9_-]+$/;\n\n// Where a form stands in a text, in any case. One that could be a name\n// stands where it is a token of its own, delimited by anything that is not a\n// letter, a digit, an underscore or a hyphen; one that holds any other\n// character is never a name and stands wherever it occurs.\nfunction occurrences(form: string): RegExp {\n const text = escapeRegExp(form);\n return NAME.test(form)\n ? new RegExp(`(?<![A-Za-z0-9_-])${text}(?![A-Za-z0-9_-])`, 'gi')\n : new RegExp(text, 'gi');\n}\n\n// `text`, a text the package did not write, with every occurrence of the\n// value replaced by the placeholder.\nexport function withhold(text: string, value: unknown): string {\n return forms(value).reduce(\n (rest, form) => rest.replace(occurrences(form), VALUE_PLACEHOLDER),\n text,\n );\n}\n","// The canvas as a model reads it: a pure function of one frame. Every canvas\n// tool's result ends with `renderCanvas` of the session's latest frame, so\n// each call corrects the model's picture of the canvas.\nimport type { CanvasSource } from '@lace-cloud/canvas/engine';\nimport { callText } from '@lace-cloud/proto';\nimport {\n type CanvasDiagnostic,\n type CanvasInput,\n type CanvasInstance,\n connectionId,\n pinRef,\n readCanvas,\n} 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) => `- ${pinRef(instance.id, input.name)}`);\n}\n\n// A diagnostic names its instance by its canvas path, so a grouped\n// instance is never read as a top-level one of the same id; one whose\n// instance no node is found for names it with the module it was found in.\nfunction diagnosticLine({ diagnostic, node }: CanvasDiagnostic): string {\n const scoped =\n diagnostic.module_key === undefined\n ? diagnostic.instance_id\n : `${diagnostic.instance_id} in module ${diagnostic.module_key}`;\n const instance = node ?? (diagnostic.instance_id === undefined ? undefined : scoped);\n const where = [\n ['instance', instance],\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 `- ${connectionId(\n wire.source_output ? pinRef(wire.source, wire.source_output) : callText(wire.source),\n pinRef(wire.target, wire.target_input),\n )}`,\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', canvas.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","// 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 { ToolHandler, 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, registration } 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 & Partial<ModuleToolData>;\n\ntype ModuleToolData = { 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: ToolHandler<ModuleToolResult>,\n): ToolRegistration<ModuleToolResult> {\n return registration<ModuleToolData>(schema, run);\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 (_input, signal) =>\n said(await runCommand(commands, 'module validate', {}, signal), trimValidate),\n ),\n moduleTool(search, async (input, signal) =>\n said(\n await runCommand(\n commands,\n 'registry list',\n {\n axis: 'module',\n query: text(input.query),\n system: text(input.system),\n category: text(input.category),\n },\n signal,\n ),\n trimRegistryList,\n ),\n ),\n moduleTool(describe, async (input, signal) => {\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(\n commands,\n 'registry describe',\n { artifact: `module/${module}`, version: text(input.version) },\n signal,\n ),\n trimRegistryDescribe,\n );\n }),\n ];\n}\n"],"mappings":";AAsCO,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;;;AChDA,SAAS,wBAAAA,6BAAgD;;;ACLlD,IAAM,YAAN,cAAwB,MAAM;AAAA,EACnC,cAAc;AACZ,UAAM,wBAAwB;AAAA,EAChC;AACF;AAGO,SAAS,gBAAgB,QAAuC;AACrE,MAAI,QAAQ,QAAS,OAAM,IAAI,UAAU;AAC3C;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W;AAC5C,YAAM,SAAS,KAAK,MAAM,MAAM;AAChC,UAAI,WAAW,OAAW,OAAM,IAAI,aAAa,yCAAyC;AAC1F,aAAO;AAAA,QACL,MAAM;AAAA,UACJ;AAAA,UACA;AAAA,UACA,EAAE,UAAU,UAAU,MAAM,IAAI,SAAS,KAAK,MAAM,OAAO,EAAE;AAAA,UAC7D;AAAA,QACF;AAAA,QACA;AAAA,MACF;AAAA,IACF,CAAC;AAAA,EACH;AACF;","names":["ApplyUnobservedError","ConnectError","ConnectError","resolve","text","text","input","group","ApplyUnobservedError","said","text","SEARCH","DESCRIBE"]}
1
+ {"version":3,"sources":["../src/contract/tool-registry.ts","../src/surfaces/canvas/canvas-tools.ts","../src/contract/cancel.ts","../src/surfaces/canvas/change.ts","../src/surfaces/canvas/commands.ts","../src/surfaces/canvas/enumerate.ts","../src/surfaces/canvas/registration.ts","../src/surfaces/canvas/ports.ts","../src/surfaces/canvas/resolve.ts","../src/surfaces/canvas/stated.ts","../src/surfaces/canvas/withhold.ts","../src/surfaces/canvas/render.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. `signal` is the host's cancellation of the call, where its chat has\n// one: once it aborts, the tool starts nothing further and stops waiting, and\n// what it already sent stands.\nexport type ToolHandler<R extends ToolResult = ToolResult> = (\n input: Record<string, unknown>,\n signal?: AbortSignal,\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 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. Each registration is a name, a description that carries\n// the tool's guidance to any host, an input schema and a handler, and says\n// nothing about the host's editor.\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 { Cancelled, untilCancelled } from '../../contract/cancel';\nimport type { ToolRegistration } from '../../contract/tool-registry';\nimport type { ToolResult, ToolSchema } from '../../contract/types';\nimport { applyChanges, OPERATIONS, parseChanges } from './change';\nimport { trimValidate } from './commands';\nimport { type CanvasToolPorts, endText, latest } from './ports';\nimport { errorText, InvalidInput, NO_INPUT, reasonText, registration } from './registration';\nimport { renderCanvas } from './render';\nimport type { StatedSlot } from './stated';\n\n// What each slot of a change names, as the canvas or the registry lists it.\nconst STATED_PROPERTIES: Record<StatedSlot, Record<string, unknown>> = {\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: its canvas path (`group.child`) or its own id.',\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: { type: 'string', description: 'The instance a connect wires from.' },\n output: { type: 'string', description: 'The output a connect wires from.' },\n targetInstance: { type: 'string', description: 'The instance a connect wires into.' },\n module: {\n type: 'string',\n description:\n 'The registry module a place adds, as `author/name`, and `author/name@version` to place a version other than the one the registry lists.',\n },\n};\n\nconst CHANGE: ToolSchema = {\n name: 'lace_change_module_canvas',\n title: 'Change module canvas',\n description: [\n 'Changes a Lace module canvas: places registry modules, wires and unwires instances, sets, binds and clears inputs, and renames, deletes and ungroups instances.',\n 'State each change as the canvas lists it: its `operation`, and each instance, input, output and registry module it works on by the name the canvas gives it.',\n \"Pass each literal the developer gave (an input's value, an instance's new name, the variable an input is bound to) in `value`, one change per entry.\",\n 'A connect that names no `output` and no `input` wires the two instances as the canvas does when one is dragged onto the other.',\n 'A change that names nothing on the canvas, or a name that fits several things, is not applied, and the result lists its candidates: ask the developer which is meant, or send the change again naming one.',\n 'A place whose module the registry lists nothing for points to lace_search_module_registry.',\n 'Every result carries the current canvas. 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 operation: {\n type: 'string',\n enum: OPERATIONS.map((operation) => operation.id),\n description: OPERATIONS.map((operation) => operation.text).join('; '),\n },\n ...STATED_PROPERTIES,\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>`).\",\n },\n },\n required: ['operation'],\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. Read it before a change when you do not know the names the canvas gives its instances, inputs and outputs.',\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 success says of the files it wrote. With no saved edits\n// left to generate, a Generate writes nothing, and the engine still\n// validates the Terraform on disk.\nfunction writtenText(written: readonly string[]): string {\n return written.length === 0\n ? 'Generated the Terraform: nothing was written.'\n : `Generated the Terraform. Files written: ${written.join(', ')}.`;\n}\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 Terraform\n// on disk, 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 writtenText(event.written),\n `lace module validate on the Terraform on disk: ${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// What a Save or a Generate says of a call its host cancelled: nothing is\n// sent once the call is cancelled, and one already sent is the engine's, goes\n// on, and is not undone.\nfunction cancelledSaid(operation: 'save' | 'Generate', sent: boolean): Said {\n return {\n text: sent\n ? `The call was cancelled after the ${operation} was sent: it goes on in the engine, and the canvas below may be from before it ends.`\n : `The call was cancelled before the ${operation} was sent: nothing was done.`,\n isError: false,\n };\n}\n\n// The canvas tools in their order: change, describe, save, generate.\nexport type CanvasTools = readonly [\n ToolRegistration,\n ToolRegistration,\n ToolRegistration,\n ToolRegistration,\n];\n\nexport function canvasTools(ports: CanvasToolPorts): CanvasTools {\n const [change, describe, save, generate] = canvasToolSchemas;\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 return [\n registration(change, async (input, signal) => {\n try {\n const text = await applyChanges(ports, parseChanges(input), signal);\n return answer([{ text, isError: false }]);\n } catch (error) {\n if (!(error instanceof InvalidInput)) throw error;\n return answer([{ text: errorText(error), isError: true }]);\n }\n }),\n registration(describe, () => answer([])),\n registration(save, async (_input, signal) =>\n answer(\n await attempt(async () => {\n if (signal?.aborted) return [cancelledSaid('save', false)];\n const saved: Said = { text: 'Saved the canvas.', isError: false };\n try {\n await untilCancelled(ports.editor.save(), signal);\n return [saved];\n } catch (error) {\n if (error instanceof Cancelled) return [cancelledSaid('save', true)];\n return [saved, unobserved(error)];\n }\n }),\n ),\n ),\n registration(generate, async (_input, signal) =>\n answer(\n await attempt(async () => {\n if (signal?.aborted) return [cancelledSaid('Generate', false)];\n const said: Said[] = [];\n const events = ports.editor.generate()[Symbol.asyncIterator]();\n try {\n for (\n let next = await untilCancelled(events.next(), signal);\n next.done !== true;\n next = await untilCancelled(events.next(), signal)\n ) {\n said.push(...generateSaid(next.value));\n }\n } catch (error) {\n if (error instanceof Cancelled) return [...said, cancelledSaid('Generate', true)];\n said.push(unobserved(error));\n }\n return said;\n }),\n ),\n ),\n ];\n}\n","// The host's cancellation of a call (the `signal` a handler takes), read the\n// one way everywhere in the package: a step not yet started is not started,\n// and a wait in progress ends; what was already sent goes on.\n\n// The host cancelled the call before the step that would have run.\nexport class Cancelled extends Error {\n constructor() {\n super('the call was cancelled');\n }\n}\n\n// Stops a call its host cancelled, at a step boundary.\nexport function stopIfCancelled(signal: AbortSignal | undefined): void {\n if (signal?.aborted) throw new Cancelled();\n}\n\n// `work`, or `Cancelled` once the call's signal aborts first: the call stops\n// waiting, and what `work` stands for goes on. The listener ends with the\n// wait.\nexport function untilCancelled<T>(work: Promise<T>, signal: AbortSignal | undefined): Promise<T> {\n if (signal === undefined) return work;\n let stop = (): void => {};\n const cancelled = new Promise<never>((_, fail) => {\n stop = () => fail(new Cancelled());\n if (signal.aborted) stop();\n else signal.addEventListener('abort', stop, { once: true });\n });\n return Promise.race([work, cancelled]).finally(() => signal.removeEventListener('abort', stop));\n}\n\n// A step that waits on something: not started once the call is cancelled,\n// and otherwise waited on until it is.\nexport function cancellable<T>(\n start: () => Promise<T>,\n signal: AbortSignal | undefined,\n): Promise<T> {\n if (signal?.aborted) return Promise.reject(new Cancelled());\n return untilCancelled(start(), signal);\n}\n","// The change tool's work: each change, stated as the canvas lists it,\n// resolved slot by slot against the canvas as it stands when the change is\n// reached, then applied as one action.\n//\n// A slot resolves by name (resolve.ts): one option is the change's, and a\n// name that fits several options, fits none, or is not stated where the\n// operation needs it leaves the change unapplied, with the candidates the\n// canvas or the registry lists for the slot, so the model can ask the\n// developer or send the change again. A connect that names no pin is sent as\n// the canvas sends a drag of one instance onto another (`auto_connect`); one\n// that names both pins is a connect of those pins into any input of the\n// target, wired or not, as a pin drag is; one that names a single pin lists\n// the pairs the engine's matcher reads for it. The change's value is\n// withheld where text the package does not write enters a result: an\n// engine's refusal, a command's failure, a stream's end, and each name the\n// change stated that a result says back (withhold.ts).\nimport { type ApplyResult, ApplyUnobservedError, InputMode } from '@lace-cloud/canvas/engine';\nimport { Cancelled, cancellable, stopIfCancelled } from '../../contract/cancel';\nimport { runCommand } from './commands';\nimport {\n type CanvasInput,\n type CanvasInstance,\n type CanvasReading,\n connectionId,\n instanceOptions,\n moduleId,\n moduleOptions,\n type Option,\n pairListing,\n pinOptions,\n pinRef,\n readCanvas,\n} from './enumerate';\nimport { type CanvasEditor, type CanvasToolPorts, endText, latest } from './ports';\nimport { errorText, InvalidInput } from './registration';\nimport { resolve } from './resolve';\nimport { STATED_SLOTS, type Stated, type StatedSlot, slotsStated } from './stated';\nimport { withhold } from './withhold';\n\n// One entry of the tool's input: its operation, the names it states slot by\n// slot, and the literal the developer gave, undefined where it gave none.\nexport type Change = {\n readonly operation: Operation;\n readonly stated: Stated;\n readonly value: unknown;\n};\n\n// A change that cannot be applied as it was sent.\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\nexport function parseChanges(input: Record<string, unknown>): Change[] {\n const { changes } = input;\n if (!Array.isArray(changes) || changes.length === 0) {\n throw new InvalidInput('`changes` is a list of one or more changes');\n }\n return changes.map((entry: unknown, index) => {\n const which = `change ${index + 1}`;\n if (!isRecord(entry)) throw new InvalidInput(`${which} is an object`);\n const operation = OPERATIONS.find((each) => each.id === entry.operation);\n if (operation === undefined) {\n const ids = OPERATIONS.map((each) => each.id).join(', ');\n throw new InvalidInput(`${which} needs \\`operation\\`: one of ${ids}`);\n }\n // An empty name states nothing, as an absent one does.\n const names = STATED_SLOTS.flatMap((slot) => {\n const name = entry[slot];\n if (!present(name) || name === '') return [];\n if (typeof name !== 'string') {\n throw new InvalidInput(`${which}: \\`${slot}\\` is a name, as the canvas lists it`);\n }\n return [[slot, name]];\n });\n return {\n operation,\n stated: Object.fromEntries(names),\n value: present(entry.value) ? entry.value : undefined,\n };\n });\n}\n\n// The most candidates a reason lists.\nconst LISTED = 12;\n\n// Names as a reason lists them: the first `LISTED`, and how many more.\nfunction listed(names: readonly string[]): string {\n const kept = names.slice(0, LISTED);\n const more = names.length - kept.length;\n return [...kept, ...(more > 0 ? [`and ${more} more`] : [])].join(', ');\n}\n\nconst candidates = (names: readonly string[]): string => `Candidates: ${listed(names)}.`;\n\n// Where a slot's names come from: the registry for a module, the canvas for\n// every other slot.\nconst listedBy = (slot: StatedSlot): string => (slot === 'module' ? 'registry' : 'canvas');\n\n// What a slot names when it names no one option: nothing, for a slot the\n// change does not state; or the name it states, fitting no option or\n// several, as a result says it back (withheld against the change's value).\ntype Unresolved =\n | { readonly kind: 'missing' }\n | { readonly kind: 'none'; readonly stated: string }\n | { readonly kind: 'several'; readonly stated: string; readonly names: readonly string[] };\n\ntype Named<T> = { readonly kind: 'one'; readonly value: T } | Unresolved;\n\n// Why a slot names no one option, then `instead`: what the model can name.\n// `label` says what the slot offers (\"instance\", \"input of app\").\nfunction unresolvedText(\n slot: StatedSlot,\n label: string,\n unresolved: Unresolved,\n instead: string,\n): string {\n switch (unresolved.kind) {\n case 'missing':\n return `this change states no \\`${slot}\\`. ${instead}`;\n case 'none':\n return `no ${label} is named \\`${unresolved.stated}\\`. ${instead}`;\n case 'several':\n return `\\`${unresolved.stated}\\` names more than one ${label}: ${listed(unresolved.names)}. Name one as the ${listedBy(slot)} lists it.`;\n }\n}\n\nconst nothingOffered = (label: string): string => `the canvas offers no ${label} for this change.`;\n\n// Several reasons as one: each a sentence, in the order the slots stand.\nfunction reasons(each: readonly string[]): string {\n return each.map((why, i) => (i === 0 ? why : why[0].toUpperCase() + why.slice(1))).join(' ');\n}\n\n// What a slot names among the options the canvas offers it: its option's\n// value, or why the change cannot be applied, listing the options.\ntype Picked<T> = { readonly value: T } | { readonly why: string };\n\nconst whyOf = (picked: Picked<unknown>): string[] => ('why' in picked ? [picked.why] : []);\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// and the change in words once the engine applied it, read from the apply's\n// result and the canvas it produced.\ntype Plan = {\n readonly action: Action;\n readonly summary: (result: ApplyResult, after: CanvasReading) => string;\n};\n\ntype Resolving = {\n readonly canvas: CanvasReading;\n readonly change: Change;\n readonly ports: CanvasToolPorts;\n // The call's cancellation, for what the plan waits on.\n readonly signal: AbortSignal | undefined;\n // What the name `stated` names in `slot` among `options`.\n readonly name: <T>(\n slot: StatedSlot,\n stated: string | undefined,\n options: readonly Option<T>[],\n ) => Named<T>;\n // What `slot` names among the canvas's `options`.\n readonly choose: <T>(slot: StatedSlot, label: string, options: readonly Option<T>[]) => Picked<T>;\n // What `slot` names among the canvas's `options`, or the change cannot be\n // applied.\n readonly pick: <T>(slot: StatedSlot, label: string, options: readonly Option<T>[]) => 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, what it does in the words the tool's schema gives\n// the model, the slots it names things by, whether it writes the literal a\n// change carries in `value`, and how it resolves the rest of a change.\ntype Operation = {\n readonly id: string;\n readonly text: string;\n readonly slots: readonly StatedSlot[];\n readonly takesValue: boolean;\n readonly plan: (resolving: Resolving) => Promise<Plan>;\n};\n\n// The literal the developer gave: the tool writes no value of its own.\nfunction given(change: Change, what: string): unknown {\n if (change.value === undefined) {\n throw new Unapplicable(`this change needs ${what}: pass it in \\`value\\`.`);\n }\n return change.value;\n}\n\nfunction givenName(change: Change, what: string): string {\n const name = given(change, what);\n if (typeof name !== 'string') throw new Unapplicable(`${what} is text: pass it in \\`value\\`.`);\n return name;\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\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: the instance\n// among every instance, and the input among those of its inputs whose\n// binding is in one of `modes`, so an operation is offered only the inputs\n// it can act on. `offered` says what those inputs are, of an instance.\nfunction pickInput(\n { canvas, pick }: Resolving,\n modes: readonly BindingMode[],\n offered: (instance: CanvasInstance) => string,\n) {\n const instance = pick('instance', 'instance', instanceOptions(canvas.instances));\n const inputs = instance.inputs.filter((input) => modes.includes(input.mode));\n const input = pick('input', offered(instance), pinOptions(inputs));\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\n// What a place says where the listing does not settle the module.\nconst SEARCH = 'Find it with lace_search_module_registry and name it as `author/name`.';\n\n// A registry module as a change states it: `author/name`, or the name\n// alone, and after `@` the version to place where it names one. `query` is\n// the name part, which the registry listing is narrowed by. An `@` that\n// names no version is no module a place can add.\nfunction moduleRef(stated: string) {\n const at = stated.lastIndexOf('@');\n if (at < 1) return { ref: stated, query: stated.split('/').at(-1) ?? '' };\n const ref = stated.slice(0, at);\n const version = stated.slice(at + 1);\n if (version === '') {\n throw new Unapplicable(\n '`module` ends in `@` with no version after it. Name the version, as `author/name@version`, or leave out `@` to place the version the registry lists.',\n );\n }\n return { ref, query: ref.split('/').at(-1) ?? '', version };\n}\n\nconst place: Operation = {\n id: 'place',\n text: 'place: add a registry module to the canvas as a new instance',\n slots: ['module'],\n takesValue: false,\n async plan({ change, ports, signal, name, note }) {\n const stated = change.stated.module === undefined ? undefined : moduleRef(change.stated.module);\n const version = stated?.version;\n if (stated === undefined || stated.query === '') {\n throw new Unapplicable(\n unresolvedText('module', 'registry module', { kind: 'missing' }, SEARCH),\n );\n }\n const listing = await cancellable(\n () =>\n runCommand(\n ports.commands,\n 'registry list',\n { axis: 'module', limit: CATALOG_LIMIT, query: stated.query },\n signal,\n ),\n signal,\n );\n if (listing.failed !== undefined) throw new Error(listing.failed.text);\n if (listing.documents.some((document) => 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 const module = name(\n 'module',\n stated.ref,\n moduleOptions(listing.documents.flatMap((document) => document.items)),\n );\n if (module.kind !== 'one') {\n throw new Unapplicable(unresolvedText('module', 'registry module', module, SEARCH));\n }\n const row = module.value;\n return {\n action: {\n place_module: { author: row.author, name: row.name, version: version ?? row.version },\n },\n summary: (result) =>\n `placed ${moduleId(row)} ${version === undefined ? row.version : withhold(version, change.value)} as ${result.created.map((ref) => ref.id).join(', ')}`,\n };\n },\n};\n\n// A connect that names no pin: the engine's matcher wires the two\n// instances, as a drag of one onto the other does, and the pairs it leaves\n// tied come back for the developer to choose between. A connect that wired\n// nothing changed nothing.\nfunction autoConnect(\n canvas: CanvasReading,\n source: CanvasInstance,\n target: CanvasInstance,\n ends: { scope: string; source_scope: string; source: string; target: string },\n note: (line: string) => void,\n): Plan {\n const between = (reading: CanvasReading) =>\n reading.wires\n .filter((wire) => wire.source === source.id && wire.target === target.id)\n .map((wire) =>\n connectionId(\n pinRef(wire.source, wire.source_output),\n pinRef(wire.target, wire.target_input),\n ),\n );\n const before = new Set(between(canvas));\n return {\n action: { auto_connect: ends },\n summary(result, after) {\n const wired = between(after).filter((wire) => !before.has(wire));\n const ties = result.ties.map((pair) =>\n connectionId(pinRef(source.id, pair.output), pinRef(target.id, pair.input)),\n );\n const choose = 'Send it again naming the `output` and the `input` the developer means.';\n if (wired.length === 0) {\n throw new Unapplicable(\n ties.length > 0\n ? `more than one pair fits equally well, so nothing was wired: ${listed(ties)}. ${choose}`\n : `the engine wired nothing from ${source.id} into ${target.id}.`,\n );\n }\n if (ties.length > 0) {\n note(`Not connected, more than one pair fits equally well: ${listed(ties)}. ${choose}`);\n }\n return `connected ${source.id} to ${target.id}: ${wired.join(', ')}`;\n },\n };\n}\n\nconst connect: Operation = {\n id: 'connect',\n text: 'connect: wire an output of one instance into an input of another',\n slots: ['sourceInstance', 'output', 'targetInstance', 'input'],\n takesValue: false,\n async plan({ canvas, change, ports, signal, choose, note }) {\n const instances = instanceOptions(canvas.instances);\n const sourcePicked = choose('sourceInstance', 'instance', instances);\n const targetPicked = choose('targetInstance', 'instance', instances);\n if (!('value' in sourcePicked) || !('value' in targetPicked)) {\n throw new Unapplicable(reasons([...whyOf(sourcePicked), ...whyOf(targetPicked)]));\n }\n const [source, target] = [sourcePicked.value, targetPicked.value];\n if (source.id === target.id) {\n throw new Unapplicable(\n `\\`sourceInstance\\` and \\`targetInstance\\` both name ${source.id}: a connect wires one instance into another.`,\n );\n }\n const ends = {\n scope: target.scope,\n source_scope: source.scope,\n source: source.name,\n target: target.name,\n };\n const stated = { output: change.stated.output, input: change.stated.input };\n if (stated.output === undefined && stated.input === undefined) {\n return autoConnect(canvas, source, target, ends, note);\n }\n const output =\n stated.output === undefined\n ? undefined\n : choose('output', `output of ${source.id}`, pinOptions(source.outputs));\n const input =\n stated.input === undefined\n ? undefined\n : choose('input', `input of ${target.id}`, pinOptions(target.inputs));\n const whys = [...(output ? whyOf(output) : []), ...(input ? whyOf(input) : [])];\n // A connect naming one pin lists the pairs the engine's matcher gives\n // for it, from its own read of the two instances.\n if (output === undefined || input === undefined) {\n const [named, unnamed] = output === undefined ? ['input', 'output'] : ['output', 'input'];\n const scored = await cancellable(\n () =>\n ports.editor.wiringCandidates({\n scope: ends.scope,\n sourceScope: ends.source_scope,\n source: ends.source,\n target: ends.target,\n }),\n signal,\n );\n const pairs = pairListing(source, target, scored, {\n ...(output && 'value' in output ? { output: output.value.name } : {}),\n ...(input && 'value' in input ? { input: input.value.name } : {}),\n });\n whys.push(\n `this change states \\`${named}\\` and no \\`${unnamed}\\`: state both, or neither to wire the two instances as the canvas does. ${\n pairs.length > 0\n ? candidates(pairs)\n : `The engine's matcher pairs no output of ${source.id} with an input of ${target.id}.`\n }`,\n );\n throw new Unapplicable(reasons(whys));\n }\n if (!('value' in output) || !('value' in input)) throw new Unapplicable(reasons(whys));\n const [from, to] = [output.value.name, input.value.name];\n return {\n action: { connect: { ...ends, source_output: from, target_input: to } },\n summary: () => `connected ${connectionId(pinRef(source.id, from), pinRef(target.id, to))}`,\n };\n },\n};\n\nconst disconnect: Operation = {\n id: 'disconnect',\n text: \"disconnect: remove the wire into an instance's input\",\n slots: ['instance', 'input'],\n takesValue: false,\n async plan(resolving) {\n const { instance, input } = pickInput(resolving, ['wired'], (of) => `wired input of ${of.id}`);\n return {\n action: {\n disconnect: { scope: instance.scope, target: instance.name, input_name: input.name },\n },\n summary: () => `disconnected ${pinRef(instance.id, input.name)}`,\n };\n },\n};\n\nconst set: Operation = {\n id: 'set',\n text: 'set: give an input of an instance a literal value',\n slots: ['instance', 'input'],\n takesValue: true,\n async plan(resolving) {\n const value = given(resolving.change, 'the value the developer gave');\n const { instance, input } = pickInput(resolving, EVERY_MODE, (of) => `input of ${of.id}`);\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 ${pinRef(instance.id, input.name)} ${shown}`,\n };\n },\n};\n\nconst bind: Operation = {\n id: 'bind',\n text: \"bind: make an input of an instance take its value from a variable of the module (`var.<name>`), so the module's caller sets it\",\n slots: ['instance', 'input'],\n takesValue: true,\n async plan(resolving) {\n const variable = variableName(givenName(resolving.change, \"the variable's name\"));\n const { instance, input } = pickInput(resolving, EVERY_MODE, (of) => `input of ${of.id}`);\n return {\n action: updateInput(instance, input, { mode: InputMode.INPUT_MODE_VARIABLE, variable }),\n summary: () => `bound ${pinRef(instance.id, input.name)} to var.${variable}`,\n };\n },\n};\n\nconst clear: Operation = {\n id: 'clear',\n text: 'clear: unset an input of an instance, removing the value, variable or expression it holds',\n slots: ['instance', 'input'],\n takesValue: false,\n async plan(resolving) {\n const { instance, input } = pickInput(\n resolving,\n ['literal', 'variable', 'expression'],\n (of) => `input of ${of.id} that holds a value`,\n );\n return {\n action: updateInput(instance, input, { mode: InputMode.INPUT_MODE_EMPTY }),\n summary: () => `cleared ${pinRef(instance.id, input.name)}`,\n };\n },\n};\n\nconst rename: Operation = {\n id: 'rename',\n text: 'rename: give an instance a new name',\n slots: ['instance'],\n takesValue: true,\n async plan({ canvas, change, pick }) {\n const name = givenName(change, 'the new name');\n const instance = 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 };\n },\n};\n\nconst remove: Operation = {\n id: 'delete',\n text: 'delete: remove an instance from the canvas',\n slots: ['instance'],\n takesValue: false,\n async plan({ canvas, pick }) {\n const instance = 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 };\n },\n};\n\nconst ungroup: Operation = {\n id: 'ungroup',\n text: 'ungroup: dissolve a group, moving the instances inside it up beside it',\n slots: ['instance'],\n takesValue: false,\n async plan({ canvas, pick }) {\n const groups = new Set(canvas.groups.map((group) => group.id));\n const group = 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 };\n },\n};\n\n// The operations a change can be. Each is one row: its name, what it does,\n// what it names, and how it 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 | { readonly kind: 'applied'; readonly summary: string }\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 // The host cancelled the call before this change's apply was sent.\n | { readonly kind: 'cancelled' }\n // An earlier change's apply went unobserved: the stream it would be read\n // on had ended, so this change was not sent.\n | { readonly kind: 'notRun' };\n\nconst CANCELLED: Outcome = { kind: 'cancelled' };\nconst NOT_RUN: Outcome = { kind: 'notRun' };\n\n// The lines a change says before it is resolved: each slot it states that\n// its operation does not use, and a value an operation that takes none was\n// sent.\nfunction unusedLines({ operation, stated, value }: Change): string[] {\n const unused = slotsStated(stated).filter((slot) => !operation.slots.includes(slot));\n return [\n ...unused.map((slot) => `\\`${slot}\\` is not used by ${operation.id}.`),\n ...(value !== undefined && !operation.takesValue\n ? [`The \\`value\\` sent with this change was not used: ${operation.id} takes none.`]\n : []),\n ];\n}\n\nasync function resolveAndApply(\n ports: CanvasToolPorts,\n change: Change,\n signal: AbortSignal | undefined,\n note: (line: string) => void,\n): Promise<Outcome> {\n const canvas = readCanvas(await latest(ports.source));\n const name = <T>(\n slot: StatedSlot,\n stated: string | undefined,\n options: readonly Option<T>[],\n ): Named<T> => {\n if (stated === undefined) return { kind: 'missing' };\n const resolved = resolve(options, stated);\n // The name as a result says it back.\n const echoed = withhold(stated, change.value);\n switch (resolved.kind) {\n case 'one': {\n const [listedAs] = resolved.option.names;\n const where = slot === 'module' ? 'in the registry' : 'on the canvas';\n if (resolved.folded) note(`Your \\`${slot}\\` ${echoed} is \\`${listedAs}\\` ${where}.`);\n return { kind: 'one', value: resolved.option.value };\n }\n case 'several':\n return {\n kind: 'several',\n stated: echoed,\n names: resolved.options.map((each) => each.names[0]),\n };\n case 'none':\n return { kind: 'none', stated: echoed };\n }\n };\n const choose = <T>(slot: StatedSlot, label: string, options: readonly Option<T>[]): Picked<T> => {\n if (options.length === 0) return { why: nothingOffered(label) };\n const named = name(slot, change.stated[slot], options);\n if (named.kind === 'one') return { value: named.value };\n const offered = options.map((option) => option.names[0]);\n return { why: unresolvedText(slot, label, named, candidates(offered)) };\n };\n const resolving: Resolving = {\n canvas,\n change,\n ports,\n signal,\n name,\n choose,\n pick(slot, label, options) {\n const picked = choose(slot, label, options);\n if ('why' in picked) throw new Unapplicable(picked.why);\n return picked.value;\n },\n note,\n };\n for (const line of unusedLines(change)) note(line);\n const plan = await change.operation.plan(resolving);\n // Nothing is applied once the call is cancelled; an apply already sent is\n // the engine's, and stands.\n stopIfCancelled(signal);\n const result = await ports.editor.apply([plan.action]);\n if (!result.success) {\n const refusals = result.errors.map((error) => error.message).join('; ');\n return {\n kind: 'notApplied',\n why: `the engine refused it: ${withhold(refusals, change.value)}`,\n };\n }\n const after = readCanvas(await latest(ports.source));\n return { kind: 'applied', summary: plan.summary(result, after) };\n}\n\n// One change, whatever becomes of it: a failure of this change (a slot that\n// names nothing or several things, an engine that refused, a listing that\n// failed) is this change's outcome and stops no other, and so is an apply\n// the engine answered whose frame the session's stream ended before. A\n// reason the package wrote is said as it is; any other failure's text, and\n// the account of a stream's end, are withheld against the change's value.\nasync function runChange(\n ports: CanvasToolPorts,\n change: Change,\n signal: AbortSignal | undefined,\n note: (line: string) => void,\n): Promise<Outcome> {\n try {\n return await resolveAndApply(ports, change, signal, note);\n } catch (error) {\n if (error instanceof ApplyUnobservedError) {\n return { kind: 'unobserved', end: withhold(endText(error.end), change.value) };\n }\n // The host cancelled the call before this change's apply was sent (a\n // listing or a wiring read no longer waited on). Anything once the apply\n // was sent is the apply's own outcome.\n if (error instanceof Cancelled) return CANCELLED;\n if (error instanceof Unapplicable) return { kind: 'notApplied', why: error.message };\n return { kind: 'notApplied', why: withhold(errorText(error), change.value) };\n }\n}\n\nfunction outcomeLine(number: number, outcome: Outcome): string {\n const head = `Change ${number}:`;\n switch (outcome.kind) {\n case 'applied':\n return `${head} applied. ${outcome.summary}.`;\n case 'notApplied':\n return `${head} not applied. Reason: ${outcome.why}`;\n case 'cancelled':\n return `${head} not applied. The call was cancelled before it applied.`;\n case 'unobserved':\n return `${head} sent, and the engine answered it, but the session's stream ended (${outcome.end}) before the canvas showed it, so whether it applied cannot be read here. Do not send it again before the canvas is open again.`;\n case 'notRun':\n return `${head} not run. The session's stream ended before it, so it was not sent.`;\n }\n}\n\n// Applies the changes in order, each against the state the one before it\n// produced, and says per change what was applied or why nothing was, with\n// the lines it noted beneath it. A summary shows the value the operation\n// wrote unless the input is sensitive.\n//\n// `signal` is the host's cancellation of the call. Once it aborts, nothing\n// further is started: a listing or wiring read in progress is no longer\n// waited on, and the change in progress and every later one say the call\n// was cancelled before they applied. Once an apply goes unobserved (the\n// session's stream ended before its frame), no later change is sent: the\n// stream that would show it has ended.\nexport async function applyChanges(\n ports: CanvasToolPorts,\n changes: readonly Change[],\n signal?: AbortSignal,\n): Promise<string> {\n const lines: string[] = [];\n let ended = false;\n for (const [index, change] of changes.entries()) {\n const notes: string[] = [];\n const outcome: Outcome = ended\n ? NOT_RUN\n : signal?.aborted\n ? CANCELLED\n : await runChange(ports, change, signal, (line) => notes.push(line));\n ended = ended || outcome.kind === 'unobserved';\n lines.push(\n outcomeLine(index + 1, outcome),\n ...(outcome.kind === 'cancelled' || outcome.kind === 'notRun'\n ? []\n : notes.map((line) => ` ${line}`)),\n );\n }\n return lines.join('\\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 type CommandFailure,\n type CommandsPort,\n ConnectError,\n failureSays,\n type JsonOf,\n} from '@lace-cloud/canvas/engine';\nimport { moduleId } from './enumerate';\nimport { refusalReason } 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// Why a command ended, in the chat's words around what the failure says\n// (`failureSays`, the one reading every surface shows): the command's path,\n// and the reason the failure names as data — a failure document's, or a\n// refusal's when the engine refused the call before the command started —\n// by its wire spelling, or the API's own code when the API decided it, and\n// the page a document's reason points at when it names one.\nfunction commandEnd(path: BoundPath, error: unknown): CommandEnd {\n const { message, failure } = failureSays(error);\n const failed = (why: string, see = '') => `lace ${path} failed (reason ${why}): ${message}${see}`;\n if (failure !== undefined) {\n const see = failure.url === undefined ? '' : `; see ${failure.url}`;\n return { text: failed(failure.apiCode ?? failure.reason, see), failure };\n }\n if (error instanceof ConnectError) return { text: failed(refusalReason(error)) };\n return { text: `lace ${path} did not finish cleanly (${message})` };\n}\n\n// `signal` is the tool call's cancellation, which the port reads as the\n// consumer no longer listening: the call stops waiting, and the command keeps\n// whatever it already did.\nexport async function runCommand<P extends BoundPath>(\n commands: CommandsPort,\n path: P,\n args: ArgsOf<P>,\n signal: AbortSignal = new AbortController().signal,\n): Promise<CommandOutput<P>> {\n const documents: JsonOf<P>[] = [];\n try {\n for await (const document of commands.invoke(path, args, 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 each slot a change names, and\n// the names it offers each by. `readCanvas` is the only fold over the Bundle\n// in this package, and it folds through proto's projection\n// (`projectCanvasView`), inspection (`deriveNodeConfig`), instance\n// resolution (`resolveInstance`) and diagnostic-to-node mapping\n// (`nodeIdForDiagnostic`) alone; every option 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.\nimport type { CanvasSource, JsonOf, WiringCandidate } from '@lace-cloud/canvas/engine';\nimport {\n type Diagnostic,\n deriveNodeConfig,\n nodeIdForDiagnostic,\n projectCanvasView,\n type RenderEdge,\n type RenderInput,\n type RenderOutput,\n resolveInstance,\n} from '@lace-cloud/proto';\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\n// One of the engine's diagnostics, with the canvas path of the instance it\n// is about where proto's one diagnostic-to-node mapping finds one.\nexport type CanvasDiagnostic = {\n readonly diagnostic: Diagnostic;\n readonly node: string | null;\n};\n\nexport type CanvasReading = {\n readonly module: string;\n readonly instances: readonly CanvasInstance[];\n readonly wires: readonly RenderEdge[];\n readonly groups: readonly CanvasGroup[];\n readonly diagnostics: readonly CanvasDiagnostic[];\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 instances,\n wires: view.edges,\n groups: view.groups.map((group) => ({ id: group.id, members: group.node_ids })),\n diagnostics: source.diagnostics.map((diagnostic) => ({\n diagnostic,\n node: nodeIdForDiagnostic(view, diagnostic),\n })),\n };\n}\n\n// One thing a slot can name: the names it is named by, the one the canvas\n// lists it by first, and the thing.\nexport type Option<T> = {\n readonly names: readonly [string, ...string[]];\n readonly value: T;\n};\n\n// An instance, named by its canvas path, then by its own id.\nexport function instanceOptions(instances: readonly CanvasInstance[]): Option<CanvasInstance>[] {\n return instances.map((instance) => ({ names: [instance.id, instance.name], value: instance }));\n}\n\n// A pin of an instance, named by its name.\nexport function pinOptions<P extends { readonly name: string }>(pins: readonly P[]): Option<P>[] {\n return pins.map((pin) => ({ names: [pin.name], value: pin }));\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\n// A registry module, named as `author/name`, then by its name.\nexport function moduleOptions(rows: readonly RegistryRow[]): Option<RegistryRow>[] {\n return rows.map((row) => ({ names: [moduleId(row), row.name], value: row }));\n}\n\n// A wire's end as the canvas lists it: an instance's canvas path and the\n// pin's name.\nexport function pinRef(instance: string, pin: string): string {\n return `${instance}.${pin}`;\n}\n\n// A wire as the canvas lists it.\nexport function connectionId(from: string, to: string): string {\n return `${from} → ${to}`;\n}\n\n// The engine matcher's pairs from source into target (`scored`, its read\n// for the two), as a connect lists them: in the matcher's order, best\n// first, each with its score, held to the one pin the change named.\nexport function pairListing(\n source: CanvasInstance,\n target: CanvasInstance,\n scored: readonly WiringCandidate[],\n pin: { readonly output?: string; readonly input?: string },\n): string[] {\n return scored\n .filter((pair) => pair.sourceInstance === source.name && pair.targetInstance === target.name)\n .filter((pair) => pin.output === undefined || pair.output === pin.output)\n .filter((pair) => pin.input === undefined || pair.input === pin.input)\n .map(\n (pair) =>\n `${connectionId(pinRef(source.id, pair.output), pinRef(target.id, pair.input))} (score ${pair.score})`,\n );\n}\n","import { 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// The reason a refused engine call names: the API's own code when the API\n// decided it, else the reason it carries, spelled as a failure document\n// spells it.\nexport function refusalReason(error: ConnectError): string {\n return error.apiCode ?? reasonWire(error.reason);\n}\n\n// A thrown error in words: its message, and for a refused engine call the\n// reason it names.\nexport function errorText(error: unknown): string {\n if (error instanceof ConnectError) return `${error.message} (reason ${refusalReason(error)})`;\n return error instanceof Error ? error.message : String(error);\n}\n\n// A tool's registration, whose handler always answers: a thrown error is\n// the call's result, said in the error's own words, never a rejection the\n// host's chat has to translate. A tool whose result carries data for its\n// host beside the text (`E`, each part optional) answers a failure with\n// none of it.\nexport function registration<E extends object = object>(\n schema: ToolSchema,\n run: ToolHandler<ToolResult & Partial<E>>,\n): ToolRegistration<ToolResult & Partial<E>> {\n const none: Partial<E> = {};\n return {\n schema,\n async handler(input, signal) {\n try {\n return await run(input, signal);\n } catch (error) {\n return { ...none, content: errorText(error), isError: true };\n }\n },\n };\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","// 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, and one with a\n// `commands` port alone constructs the module tools.\nimport type {\n ApplyUnobservedError,\n CanvasSource,\n CommandsPort,\n EditorPort,\n SourceEnd,\n SourcePort,\n} from '@lace-cloud/canvas/engine';\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};\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","// One slot's resolution: the name a change states, matched against the\n// names of each option the slot offers, in four steps: exactly on an\n// option's first name (an instance's canvas path, a module's `author/name`),\n// exactly on any of its names, then each again ignoring case. The first step\n// with any hit decides: one hit is the option, several are ambiguous, and a\n// later step is never reached. No hit at any step is unmatched. Both sides\n// are compared in one Unicode form (NFC), so a name typed decomposed finds\n// the name the canvas holds composed.\nimport type { Option } from './enumerate';\n\nexport type Resolved<T> =\n | { readonly kind: 'one'; readonly option: Option<T>; readonly folded: boolean }\n | { readonly kind: 'several'; readonly options: readonly Option<T>[] }\n | { readonly kind: 'none' };\n\ntype Step = {\n // Whether the step ignores case.\n readonly folded: boolean;\n readonly names: (option: Option<unknown>) => readonly string[];\n};\n\nconst first = (option: Option<unknown>) => option.names.slice(0, 1);\nconst every = (option: Option<unknown>) => option.names;\n\nconst STEPS: readonly Step[] = [\n { folded: false, names: first },\n { folded: false, names: every },\n { folded: true, names: first },\n { folded: true, names: every },\n];\n\nexport function resolve<T>(options: readonly Option<T>[], stated: string): Resolved<T> {\n const step = STEPS.map((each) => {\n const key = (name: string) => {\n const normal = name.normalize('NFC');\n return each.folded ? normal.toLowerCase() : normal;\n };\n const hits = options.filter((option) =>\n each.names(option).some((name) => key(name) === key(stated)),\n );\n return { folded: each.folded, hits };\n }).find((each) => each.hits.length > 0);\n if (step === undefined) return { kind: 'none' };\n return step.hits.length === 1\n ? { kind: 'one', option: step.hits[0], folded: step.folded }\n : { kind: 'several', options: step.hits };\n}\n","// The names one change states, each in its own slot, as the canvas or the\n// registry lists them: an instance by its canvas path or its own id, a pin\n// by its name, a registry module as `author/name` or by its name.\nexport const STATED_SLOTS = [\n 'instance',\n 'input',\n 'sourceInstance',\n 'output',\n 'targetInstance',\n 'module',\n] as const;\n\nexport type StatedSlot = (typeof STATED_SLOTS)[number];\n\nexport type Stated = Readonly<Partial<Record<StatedSlot, string>>>;\n\n// The slots a change states, in slot order.\nexport function slotsStated(stated: Stated): StatedSlot[] {\n return STATED_SLOTS.filter((slot) => stated[slot] !== undefined);\n}\n","// What a result withholds of the value a change carries. The value is\n// withheld only from text the package does not write itself and that could\n// carry it: an engine's refusal, a command's failure, the account of a\n// session's stream ending, and each name the model stated that a result\n// says back. The package's own words, and the names the canvas or the\n// registry lists, are never withheld: they are public, and the canvas the\n// result ends with prints them.\n\n// The one token that stands where a value was.\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\nconst GO_ESCAPES: Readonly<Record<string, string>> = {\n '\\x07': '\\\\a',\n '\\b': '\\\\b',\n '\\f': '\\\\f',\n '\\n': '\\\\n',\n '\\r': '\\\\r',\n '\\t': '\\\\t',\n '\\v': '\\\\v',\n '\"': '\\\\\"',\n '\\\\': '\\\\\\\\',\n};\n\n// What Go's strconv counts printable: a letter, mark, number, punctuation\n// or symbol, or the ASCII space.\nconst GO_PRINTABLE = /^[ \\p{L}\\p{M}\\p{N}\\p{P}\\p{S}]$/u;\n\n// One character as Go's `%q` writes it inside quotes.\nfunction goEscaped(char: string): string {\n const code = char.codePointAt(0) ?? 0;\n if (GO_ESCAPES[char] !== undefined) return GO_ESCAPES[char];\n if (GO_PRINTABLE.test(char)) return char;\n const [mark, width] = code < 0x80 ? ['x', 2] : code < 0x10000 ? ['u', 4] : ['U', 8];\n return `\\\\${mark}${code.toString(16).padStart(width, '0')}`;\n}\n\n// Every form a literal is written in: itself; quoted with JSON's escapes;\n// quoted as Go's `%q` writes it, which is how the engine quotes a value it\n// names; and each quoted form's escapes unquoted.\nfunction writtenForms(literal: string): string[] {\n const quoted = [JSON.stringify(literal), `\"${[...literal].map(goEscaped).join('')}\"`];\n return [literal, ...quoted, ...quoted.map((form) => form.slice(1, -1))];\n}\n\n// The forms of a value's literals, longest first, so one that holds another\n// is replaced whole.\nfunction forms(value: unknown): string[] {\n const all = literalTexts(value)\n .filter((literal) => literal !== '')\n .flatMap(writtenForms);\n return [...new Set(all)].sort((a, b) => b.length - a.length);\n}\n\n// `text` as a pattern that matches it literally.\nfunction escapeRegExp(text: string): string {\n return text.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\nconst NAME = /^[A-Za-z0-9_-]+$/;\n\n// Where a form stands in a text, in any case. One that could be a name\n// stands where it is a token of its own, delimited by anything that is not a\n// letter, a digit, an underscore or a hyphen; one that holds any other\n// character is never a name and stands wherever it occurs.\nfunction occurrences(form: string): RegExp {\n const text = escapeRegExp(form);\n return NAME.test(form)\n ? new RegExp(`(?<![A-Za-z0-9_-])${text}(?![A-Za-z0-9_-])`, 'gi')\n : new RegExp(text, 'gi');\n}\n\n// `text`, a text the package did not write, with every occurrence of the\n// value replaced by the placeholder.\nexport function withhold(text: string, value: unknown): string {\n return forms(value).reduce(\n (rest, form) => rest.replace(occurrences(form), VALUE_PLACEHOLDER),\n text,\n );\n}\n","// The canvas as a model reads it: a pure function of one frame. Every canvas\n// tool's result ends with `renderCanvas` of the session's latest frame, so\n// each call corrects the model's picture of the canvas.\nimport type { CanvasSource } from '@lace-cloud/canvas/engine';\nimport { callText } from '@lace-cloud/proto';\nimport {\n type CanvasDiagnostic,\n type CanvasInput,\n type CanvasInstance,\n connectionId,\n pinRef,\n readCanvas,\n} 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) => `- ${pinRef(instance.id, input.name)}`);\n}\n\n// A diagnostic names its instance by its canvas path, so a grouped\n// instance is never read as a top-level one of the same id; one whose\n// instance no node is found for names it with the module it was found in.\nfunction diagnosticLine({ diagnostic, node }: CanvasDiagnostic): string {\n const scoped =\n diagnostic.module_key === undefined\n ? diagnostic.instance_id\n : `${diagnostic.instance_id} in module ${diagnostic.module_key}`;\n const instance = node ?? (diagnostic.instance_id === undefined ? undefined : scoped);\n const where = [\n ['instance', instance],\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 `- ${connectionId(\n wire.source_output ? pinRef(wire.source, wire.source_output) : callText(wire.source),\n pinRef(wire.target, wire.target_input),\n )}`,\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', canvas.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","// 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 { ToolHandler, 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, registration } 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 & Partial<ModuleToolData>;\n\ntype ModuleToolData = { 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: ToolHandler<ModuleToolResult>,\n): ToolRegistration<ModuleToolResult> {\n return registration<ModuleToolData>(schema, run);\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 (_input, signal) =>\n said(await runCommand(commands, 'module validate', {}, signal), trimValidate),\n ),\n moduleTool(search, async (input, signal) =>\n said(\n await runCommand(\n commands,\n 'registry list',\n {\n axis: 'module',\n query: text(input.query),\n system: text(input.system),\n category: text(input.category),\n },\n signal,\n ),\n trimRegistryList,\n ),\n ),\n moduleTool(describe, async (input, signal) => {\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(\n commands,\n 'registry describe',\n { artifact: `module/${module}`, version: text(input.version) },\n signal,\n ),\n trimRegistryDescribe,\n );\n }),\n ];\n}\n"],"mappings":";AAsCO,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;;;AChDA,SAAS,wBAAAA,6BAAgD;;;ACLlD,IAAM,YAAN,cAAwB,MAAM;AAAA,EACnC,cAAc;AACZ,UAAM,wBAAwB;AAAA,EAChC;AACF;AAGO,SAAS,gBAAgB,QAAuC;AACrE,MAAI,QAAQ,QAAS,OAAM,IAAI,UAAU;AAC3C;AAKO,SAAS,eAAkB,MAAkB,QAA6C;AAC/F,MAAI,WAAW,OAAW,QAAO;AACjC,MAAI,OAAO,MAAY;AAAA,EAAC;AACxB,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,UACA;AAAA,UACA,EAAE,UAAU,UAAU,MAAM,IAAI,SAAS,KAAK,MAAM,OAAO,EAAE;AAAA,UAC7D;AAAA,QACF;AAAA,QACA;AAAA,MACF;AAAA,IACF,CAAC;AAAA,EACH;AACF;","names":["ApplyUnobservedError","ConnectError","ConnectError","resolve","text","text","input","group","ApplyUnobservedError","said","text","SEARCH","DESCRIBE"]}
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@lace-cloud/chat-core",
3
- "version": "0.27.0",
3
+ "version": "0.28.0",
4
4
  "license": "BUSL-1.1",
5
5
  "main": "./dist/index.cjs",
6
6
  "types": "./dist/index.d.ts",
7
7
  "dependencies": {
8
- "@lace-cloud/canvas": "0.27.0",
9
- "@lace-cloud/proto": "0.27.0"
8
+ "@lace-cloud/canvas": "0.28.0",
9
+ "@lace-cloud/proto": "0.28.0"
10
10
  },
11
11
  "devDependencies": {
12
12
  "tsup": "^8.5.0",