@lace-cloud/chat-core 0.19.0 → 0.21.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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/contract/tool-registry.ts","../src/questions/bounds.ts","../src/questions/types.ts","../src/questions/candidate.ts","../src/questions/reading.ts","../src/questions/render.ts","../src/examples/rows.ts","../src/ranking/client.ts","../src/hybrid/compose.ts","../src/surfaces/canvas/canvas-tools.ts","../src/surfaces/canvas/change.ts","../src/surfaces/canvas/commands.ts","../src/surfaces/canvas/enumerate.ts","../src/surfaces/canvas/registration.ts","../src/surfaces/canvas/outcome.ts","../src/surfaces/canvas/ports.ts","../src/surfaces/canvas/render.ts","../src/surfaces/canvas/resolve.ts","../src/surfaces/canvas/module-tools.ts"],"sourcesContent":["// Registry of tool schemas + handlers.\n//\n// Handlers are pure async functions: input object → ToolResult.\n// Schemas are plain data. The registry itself is a tiny in-memory\n// Map with no IDE coupling — every caller (VS Code adapter,\n// JetBrains adapter, unit tests) constructs one and registers the\n// tools their environment provides.\n//\n// Instance-per-session rather than a module singleton: a global\n// registry would leak tool handlers between adapters in any future\n// in-process multi-host scenario (e.g. testing), and buys nothing\n// over explicit construction.\n\nimport type { ToolResult, ToolSchema } from './types';\n\n// A handler answers with a `ToolResult`, or with one that carries more: a\n// tool whose result holds data for its host beside the text its model reads\n// states that result as `R`, and a host that holds the registration reads it\n// typed.\nexport type ToolHandler<R extends ToolResult = ToolResult> = (\n input: Record<string, unknown>,\n) => Promise<R>;\n\nexport type ToolRegistration<R extends ToolResult = ToolResult> = {\n schema: ToolSchema;\n handler: ToolHandler<R>;\n};\n\nexport interface ToolRegistry {\n register(schema: ToolSchema, handler: ToolHandler): void;\n getHandler(name: string): ToolHandler | undefined;\n listSchemas(): ToolSchema[];\n listNames(): string[];\n}\n\nexport function createToolRegistry(): ToolRegistry {\n const entries = new Map<string, ToolRegistration>();\n\n return {\n register(schema, handler) {\n entries.set(schema.name, { schema, handler });\n },\n\n getHandler(name) {\n return entries.get(name)?.handler;\n },\n\n listSchemas() {\n return [...entries.values()].map((e) => e.schema);\n },\n\n listNames() {\n return [...entries.keys()];\n },\n };\n}\n","// The bounds of what one rank call carries, each at most the ranking route's\n// own (the API's bounds parity test holds each of these at most the route's,\n// itself within the pod's). A question a capture records is held to them\n// too, so the rows rendered from it are rows the trainer reads.\n\n// The most candidates one rank call carries (the route's `CANDIDATES_MAX`).\nexport const RANK_CANDIDATES_MAX = 256;\n\n// The most characters of a rendered request and the statement appended to\n// it together (the route's `REQUEST_MAX_CHARS`).\nexport const RANK_REQUEST_MAX_CHARS = 4000;\n\n// The most characters of one candidate's prose (the route's\n// `CANDIDATE_TEXT_MAX_CHARS`).\nexport const RANK_CANDIDATE_TEXT_MAX_CHARS = 2000;\n","// The closed questions: the kind of decision a change asks, the candidates\n// it picks among, and the one that means none of them. Nothing here knows a\n// canvas, a network or a model.\n\n// The kinds of decision the hybrid makes inside the canvas tools. Each is a\n// closed set the tools enumerate from the session's IR and the registry: the\n// operation a change is, the instance it names, the input of an instance,\n// the registry module, the output → input pair a connect wires between two\n// instances, and whether an entry is one change or several. A threshold is\n// fitted per kind, so the kind is part of a candidate and the key of the\n// head's threshold set. This list is the one list: the API's\n// `DECISION_KINDS` and the ranking service's `kinds.py` restate it, and a\n// parity test beside each holds the copy to it.\nexport type DecisionKind = 'operation' | 'instance' | 'input' | 'module' | 'connection' | 'steps';\n\n// The kinds as a list, in the order a change asks them.\nexport const DECISION_KINDS: readonly DecisionKind[] = [\n 'operation',\n 'instance',\n 'input',\n 'module',\n 'connection',\n 'steps',\n];\n\n// The candidate every ranked set but a `steps` one carries last: none of the\n// others. It is ranked like any candidate and never applied; the pick is the\n// best of the others. No Terraform name, registry `author/name` or pair id\n// holds a parenthesis, so it is no real candidate's id. The API's\n// `NONE_CANDIDATE_ID` and the ranking service's `kinds.py` restate it, and a\n// parity test beside each holds the copy to it.\nexport const NONE_CANDIDATE_ID = '(none)';\n\n// One member of the closed set a decision picks from: its id, the prose the\n// ranking scores against the request, and the decision it belongs to.\nexport type Candidate = {\n readonly id: string;\n readonly kind: DecisionKind;\n readonly text: string;\n};\n","// The one candidate renderer. An option of a decision holds its facts (its\n// id, its kind, and the instance, input, output, module or pair it names,\n// as the canvas and the registry gave them), and `renderCandidate`, a pure\n// function of those facts, renders them to the prose the ranking scores.\n// The tools render every candidate a rank call receives through it at run\n// time. The API stores a call's candidates as they were sent (`{id, kind,\n// text}`) and a row carries them as captured, so a head trains on the words\n// the tools sent when the question was asked: a change to the wording\n// reaches the turns asked after it, never one asked before.\n//\n// The prose is held to the text bound of one rank call, and the same facts\n// are always cut the same way: names first. Prose is shortened before any\n// name is dropped, and a name is dropped whole, never cut.\nimport { RANK_CANDIDATE_TEXT_MAX_CHARS } from './bounds';\nimport { type Candidate, type DecisionKind, NONE_CANDIDATE_ID } from './types';\n\n// A wire's end as a request names it: an instance's canvas path and the\n// port's name.\nexport function pinRef(instance: string, pin: string): string {\n return `${instance}.${pin}`;\n}\n\n// The id of the connection candidate that wires `from` into `to`.\nexport function connectionId(from: string, to: string): string {\n return `${from} → ${to}`;\n}\n\n// What the operations are, in the words the ranking scores them by, keyed\n// by the operation's id.\nexport const OPERATION_TEXT: Readonly<Record<string, string>> = {\n place: 'place: add a registry module to the canvas as a new instance',\n connect: 'connect: wire an output of one instance into an input of another',\n disconnect: \"disconnect: remove the wire into an instance's input\",\n set: 'set: give an input of an instance a literal value',\n bind: \"bind: make an input of an instance take its value from a variable of the module (`var.<name>`), so the module's caller sets it\",\n clear:\n 'clear: unset an input of an instance, removing the value, variable or expression it holds',\n rename: 'rename: give an instance a new name',\n delete: 'delete: remove an instance from the canvas',\n ungroup: 'ungroup: dissolve a group, moving the instances inside it up beside it',\n};\n\n// Whether an entry is one change or several, in the words the ranking\n// scores it by, keyed by the reading's id.\nexport const STEPS_TEXT: Readonly<Record<string, string>> = {\n one: 'one change: the request asks for a single change to the canvas',\n several: 'several changes: the request asks for more than one change to the canvas',\n};\n\n// What `(none)` means in each kind of decision but `steps`, in the words the\n// ranking scores it by. `steps` has none: whether an entry is one change or\n// several is a two-way question, and an entry that asks for no change is\n// the operation's `(none)`.\nconst NONE_TEXT: Readonly<Record<Exclude<DecisionKind, 'steps'>, string>> = {\n operation: 'asks for no change these operations make',\n instance: 'means no instance on this canvas',\n input: 'means no input of this instance',\n module: 'means no module of this registry listing',\n connection: 'means no wire between these two instances',\n};\n\n// The `(none)` candidate of a kind of decision. It has no facts: its prose is\n// the kind's alone.\nexport function noneCandidate(kind: Exclude<DecisionKind, 'steps'>): Candidate {\n return { id: NONE_CANDIDATE_ID, kind, text: `none of these: the request ${NONE_TEXT[kind]}` };\n}\n\n// The candidates one rank call carries for a question of `kind`: its own,\n// then `(none)` last in every kind but `steps`. A training row carries the\n// same set, so what is trained is what is served.\nexport function rankCandidates(kind: DecisionKind, candidates: readonly Candidate[]): Candidate[] {\n return kind === 'steps' ? [...candidates] : [...candidates, noneCandidate(kind)];\n}\n\n// The role an instance plays in the question that offers it: the instance a\n// change addresses, the one a wire starts at, or the one it ends at. A\n// target's inputs are the ones a wire can end at: those no wire feeds.\nexport type InstanceRole = 'instance' | 'source' | 'target';\n\n// Whether an input holds anything, never what it holds.\nexport type InputState = 'not set' | 'set' | 'wired';\n\n// An instance's pin as its module declares it: its name and, where the\n// module says, what it is.\nexport type PinFacts = { readonly name: string; readonly description?: string };\n\n// One candidate as a capture stores it: its id, its kind, and the facts its\n// prose is written from. None of them is a value: an input says whether it\n// is set, never what to.\nexport type CandidateFacts =\n | { readonly id: string; readonly kind: 'operation' }\n | { readonly id: string; readonly kind: 'steps' }\n | {\n readonly id: string;\n readonly kind: 'instance';\n readonly role: InstanceRole;\n readonly module: string;\n readonly inputs: readonly PinFacts[];\n readonly outputs: readonly PinFacts[];\n }\n | {\n readonly id: string;\n readonly kind: 'input';\n readonly instance: string;\n readonly module: string;\n readonly type: string;\n readonly required: boolean;\n readonly state: InputState;\n readonly description?: string;\n }\n | {\n readonly id: string;\n readonly kind: 'module';\n readonly displayName: string;\n readonly description: string;\n readonly system: string;\n readonly categories: readonly string[];\n }\n | {\n readonly id: string;\n readonly kind: 'connection';\n readonly source: string;\n readonly output: string;\n readonly target: string;\n readonly input: string;\n readonly score?: number;\n };\n\n// The mark that stands where a text was cut.\nconst CUT_MARK = '…';\n\n// `text` cut to at most `limit` characters after its last whole word that\n// fits, the cut marked; `text` itself when it fits. A text whose first word\n// does not fit is cut to nothing.\nexport function shortened(text: string, limit: number): string {\n if (text.length <= limit) return text;\n const room = text.slice(0, Math.max(limit - CUT_MARK.length + 1, 0));\n const end = room.search(/\\s+\\S*$/);\n const kept = end === -1 ? '' : room.slice(0, end).trimEnd();\n return kept === '' ? '' : `${kept}${CUT_MARK}`;\n}\n\n// How far a candidate's prose is cut: each piece of what the module or the\n// registry says a thing is (a pin's, an input's or a module's description,\n// an input's type) to at most `prose` characters, and each list of names\n// to its first `names`.\ntype Cut = { readonly prose: number; readonly names: number };\n\nconst WHOLE: Cut = { prose: Number.POSITIVE_INFINITY, names: Number.POSITIVE_INFINITY };\n\n// A piece of prose as `cut` leaves it; none when nothing of it is left.\nfunction prose(text: string, cut: Cut): string | undefined {\n const kept = shortened(text, cut.prose);\n return kept === '' && text !== '' ? undefined : kept;\n}\n\n// The first `cut.names` items, each rendered by `render`, and how many more\n// there are.\nfunction listed<T>(items: readonly T[], cut: Cut, render: (item: T) => string): string {\n const kept = items.slice(0, cut.names).map(render);\n const more = items.length - kept.length;\n return [...kept, ...(more > 0 ? [`and ${more} more`] : [])].join(', ');\n}\n\nfunction worded(table: Readonly<Record<string, string>>, what: string, id: string): string {\n const text = table[id];\n if (text === undefined) throw new Error(`no ${what} is named ${id}`);\n return text;\n}\n\nconst about = (instance: string, module: string): string =>\n `instance ${instance} of module ${module}`;\n\ntype InstanceFacts = Extract<CandidateFacts, { readonly kind: 'instance' }>;\n\nconst names = (pins: readonly PinFacts[], cut: Cut): string => listed(pins, cut, (pin) => pin.name);\n\n// Pins with what the module says each is, where it says.\nconst described = (pins: readonly PinFacts[], cut: Cut): string =>\n listed(pins, cut, (pin) => {\n const description = pin.description === undefined ? undefined : prose(pin.description, cut);\n return description === undefined ? pin.name : `${pin.name} (${description})`;\n });\n\nconst INSTANCE_TEXT: Readonly<Record<InstanceRole, (facts: InstanceFacts, cut: Cut) => string>> = {\n instance: (f, cut) =>\n `${about(f.id, f.module)}; inputs: ${described(f.inputs, cut)}; outputs: ${described(f.outputs, cut)}`,\n source: (f, cut) =>\n `the wire starts at an output of ${about(f.id, f.module)}; its outputs: ${names(f.outputs, cut)}`,\n target: (f, cut) =>\n `the wire ends at an input of ${about(f.id, f.module)}; its inputs no wire feeds: ${names(f.inputs, cut)}`,\n};\n\nfunction textOf(facts: CandidateFacts, cut: Cut): string {\n switch (facts.kind) {\n case 'operation':\n return worded(OPERATION_TEXT, 'operation', facts.id);\n case 'steps':\n return worded(STEPS_TEXT, 'reading of the steps', facts.id);\n case 'instance':\n return INSTANCE_TEXT[facts.role](facts, cut);\n case 'input': {\n const type = prose(facts.type, cut);\n return [\n `input ${facts.id} of ${about(facts.instance, facts.module)}`,\n type === undefined ? undefined : `type ${type}`,\n facts.required ? 'required' : 'optional',\n facts.state,\n facts.description === undefined ? undefined : prose(facts.description, cut),\n ]\n .filter((part) => part !== undefined)\n .join('; ');\n }\n case 'module':\n return `registry module ${facts.id} (${facts.displayName}): ${prose(facts.description, cut) ?? ''}; system ${facts.system}; categories: ${listed(facts.categories, cut, (category) => category)}`;\n case 'connection': {\n const scored =\n facts.score === undefined\n ? \"the engine's matcher gives this pair no score\"\n : `the engine's matcher scores this pair ${facts.score}`;\n return `wire output ${pinRef(facts.source, facts.output)} into input ${pinRef(facts.target, facts.input)}; ${scored}`;\n }\n }\n}\n\n// The largest whole number up to `most` that `fits`, when `fits` holds of\n// 0; none when it does not.\nfunction largest(most: number, fits: (n: number) => boolean): number | undefined {\n if (!fits(0)) return undefined;\n let [low, high] = [0, most];\n while (low < high) {\n const middle = Math.ceil((low + high) / 2);\n if (fits(middle)) low = middle;\n else high = middle - 1;\n }\n return low;\n}\n\n// A candidate's prose within the text bound: whole when it fits; else with\n// its prose cut as little as fits; else, with no prose, its lists of names\n// cut to as many as fit; else the names-only prose cut at a word.\nfunction fitted(facts: CandidateFacts): string {\n const most = RANK_CANDIDATE_TEXT_MAX_CHARS;\n const fits = (cut: Cut) => textOf(facts, cut).length <= most;\n if (fits(WHOLE)) return textOf(facts, WHOLE);\n const proseCut = largest(most, (n) => fits({ prose: n, names: WHOLE.names }));\n if (proseCut !== undefined) return textOf(facts, { prose: proseCut, names: WHOLE.names });\n const namesCut = largest(most, (n) => fits({ prose: 0, names: n }));\n if (namesCut !== undefined) return textOf(facts, { prose: 0, names: namesCut });\n return shortened(textOf(facts, { prose: 0, names: 0 }), most);\n}\n\n// A candidate as the ranking reads it: its id and kind, and its prose\n// written from its facts within the text bound.\nexport function renderCandidate(facts: CandidateFacts): Candidate {\n return { id: facts.id, kind: facts.kind, text: fitted(facts) };\n}\n","// A reading of one change: the operation and the names it works on. The\n// tool's reading and the model's are the same shape, so they compare slot by\n// slot, and a candidate says which slots a reading names it by. An instance\n// is named by its canvas path, a module as `author/name`.\nexport const READING_SLOTS = [\n 'operation',\n 'instance',\n 'input',\n 'sourceInstance',\n 'output',\n 'targetInstance',\n 'module',\n] as const;\n\nexport type Slot = (typeof READING_SLOTS)[number];\n\nexport type Reading = Readonly<Partial<Record<Slot, string>>>;\n\n// The slots a reading states.\nexport function statedSlots(reading: Reading): Slot[] {\n return READING_SLOTS.filter((slot) => reading[slot] !== undefined);\n}\n\n// A reading in words, slot by slot: what a result shows of the tool's\n// reading and the model's, and what the ranking reads as the statement.\nexport function renderReading(reading: Reading): string {\n return statedSlots(reading)\n .map((slot) => `${slot}=${reading[slot]}`)\n .join(', ');\n}\n","// The one rendering of a request as the ranking reads it, and what is\n// withheld from it. Every function here is pure: the request a rank call\n// receives and a capture records is what was rendered here at run time.\nimport { RANK_REQUEST_MAX_CHARS } from './bounds';\nimport { shortened } from './candidate';\n\n// The one token that stands where a value was: in the request every rank\n// call for a change receives and a capture records, in each statement\n// beside it (the model's reading, and its alternative reading), in what a\n// decision reports as applied, and in a reason this package did not write.\nexport const VALUE_PLACEHOLDER = '<value>';\n\n// The texts a value holds: itself when it is text, a number or a boolean,\n// and every such leaf of a list or an object.\nfunction literalTexts(value: unknown): string[] {\n if (typeof value === 'string') return [value];\n if (typeof value === 'number' || typeof value === 'boolean') return [String(value)];\n if (typeof value === 'object' && value !== null)\n return Object.values(value).flatMap(literalTexts);\n return [];\n}\n\n// The literals of a change, longest first, so one that holds another is\n// replaced whole.\nfunction literals(values: readonly unknown[]): string[] {\n return values\n .flatMap(literalTexts)\n .filter((literal) => literal !== '')\n .sort((a, b) => b.length - a.length);\n}\n\n// A variable reference's name: `var.x` names the variable `x`, which is what\n// a binding writes.\nexport function variableName(text: string): string {\n return text.replace(/^var\\./, '');\n}\n\n// Every text values are written as: each literal, and a variable reference\n// also by the name of the variable it names.\nexport function forms(values: readonly unknown[]): string[] {\n return [...new Set(literals(values).flatMap((text) => [text, variableName(text)]))];\n}\n\n// What is withheld of another change's values against the names a canvas\n// holds: every form of them that is no name among `names`. A name on the\n// canvas is a canvas fact: the ranking sees it among the candidates.\nexport function unnamed(names: ReadonlySet<string>, values: readonly unknown[]): string[] {\n return forms(values).filter((text) => !names.has(text));\n}\n\n// `text` as a pattern that matches it literally.\nexport function escapeRegExp(text: string): string {\n return text.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\nconst NAME = /^[A-Za-z0-9_-]+$/;\n\n// Where a literal stands in a text. One that could be a name stands where\n// it is a token of its own, delimited by anything that is not a letter, a\n// digit, an underscore or a hyphen; one that holds any other character is\n// never a name and stands wherever it occurs.\nfunction occurrences(literal: string): RegExp {\n const text = escapeRegExp(literal);\n return NAME.test(literal)\n ? new RegExp(`(?<![A-Za-z0-9_-])${text}(?![A-Za-z0-9_-])`, 'g')\n : new RegExp(text, 'g');\n}\n\n// `text` with every occurrence of a literal replaced by the placeholder.\nexport function withhold(text: string, values: readonly unknown[]): string {\n return literals(values).reduce(\n (rest, literal) => rest.replace(occurrences(literal), VALUE_PLACEHOLDER),\n text,\n );\n}\n\n// Whether a rendered text still holds a literal: one `withhold` left where\n// it stood, inside a longer word. The change tool asks it of a change's\n// request and statements together, with every canvas name withheld, over\n// every withheld text of the call: a change that still holds one is never\n// sent to rank.\nexport function holdsValue(rendered: string, values: readonly unknown[]): boolean {\n return literals(values).some((literal) => rendered.includes(literal));\n}\n\n// A change's request as the ranking and a capture hold it: the developer's\n// words with each text in `values` replaced by the placeholder, cut at a\n// word so that it and `statement` (the longest a rank call for the change\n// carries) together are within the request bound of one rank call. It is\n// rendered once per change, and that one string is the request of every\n// rank call for the change and of every capture of it.\nexport function renderRequest(request: string, values: readonly unknown[], statement = ''): string {\n return shortened(withhold(request, values), RANK_REQUEST_MAX_CHARS - statement.length);\n}\n","// The row format, one definition: what a head trains on, is calibrated on\n// and is held out against. One row per question of a turn, holding exactly\n// what the rank call for the question carried (the request, the statement\n// and the candidates as rendered, `(none)` last in every kind but `steps`),\n// so what is trained is what was served. No row holds a value the tools\n// were given: the request and the statement are the strings the rank call\n// carried, every value the placeholder.\nimport type { Candidate, DecisionKind } from '../questions';\n\n// Which part of a corpus a turn's rows belong to: training, the calibration\n// the thresholds are fitted on, or the held-out part a threshold ships\n// against once. A turn is in the same part in every corpus.\nexport type Part = 'train' | 'calibration' | 'held_out';\n\n// Where a turn came from: a developer's call through the tools, or the\n// offline generator.\nexport type Origin = 'real' | 'synthetic';\n\n// One decision as a head learns it: the rendered request, the statement\n// beside it ('' when none was stated, and the pod scores the raw-words arm\n// by that), the closed set the question offered, the id of the right\n// candidate, the turn's part and origin, the turn's id (shared by every row\n// of the turn, so a turn counts once however many questions it asked), and\n// System Two's candidate for the question (null when it stated none), which\n// the fit's bar reads.\nexport type TrainingRow = {\n readonly request: string;\n readonly statement: string;\n readonly candidates: readonly Candidate[];\n readonly label: string;\n readonly part: Part;\n readonly origin: Origin;\n readonly turn: string;\n readonly chat: string | null;\n};\n\n// One question of a turn with its label: the candidates as the rank call\n// carried them, the id of the right one, and System Two's candidate for it.\nexport type LabelledQuestion = {\n readonly kind: DecisionKind;\n readonly candidates: readonly Candidate[];\n readonly label: string;\n readonly chat: string | null;\n};\n\n// A turn as rows are written from it: its id, the request and statement its\n// rank calls carried, its origin and its labelled questions.\nexport type LabelledTurn = {\n readonly id: string;\n readonly request: string;\n readonly statement: string;\n readonly origin: Origin;\n readonly questions: readonly LabelledQuestion[];\n};\n\n// A key as a fraction in [0, 1): its 32-bit FNV-1a hash, so the same key is\n// always at the same fraction, wherever it is read.\nexport function hashFraction(key: string): number {\n let hash = 0x811c9dc5;\n for (const char of key) {\n hash ^= char.codePointAt(0) ?? 0;\n hash = Math.imul(hash, 0x01000193) >>> 0;\n }\n return hash / 2 ** 32;\n}\n\n// The part of a key: 60% train, 20% calibration, 20% held out, the same key\n// in the same part in every corpus. A real turn's key is its account's\n// (the review export's `partKeyOf`), so every turn of one account, and with\n// them every turn that account made on each canvas, is in one part; a canvas\n// two accounts both edit can have turns in two parts, since no canvas\n// identity is collected.\nexport function partOf(key: string): Part {\n const at = hashFraction(key);\n return at < 0.6 ? 'train' : at < 0.8 ? 'calibration' : 'held_out';\n}\n\n// A turn's training rows in `part`, one per question, each labelled with its\n// right candidate. The part is the caller's: a real turn's is `partOf` its\n// account's key, a synthetic one's its side's. A relabelled question may be\n// labelled `(none)`: no candidate fitted.\nexport function trainingRows(turn: LabelledTurn, part: Part): TrainingRow[] {\n return turn.questions.map(({ candidates, label, chat }) => ({\n request: turn.request,\n statement: turn.statement,\n candidates,\n label,\n part,\n origin: turn.origin,\n turn: turn.id,\n chat,\n }));\n}\n","// The client of Lace's ranking service over a host's `Transport`: one rank\n// call per question, the composed decision once per change, and each\n// outcome once. Collection is the service's side effect of being asked, so\n// nothing here stores anything: the API captures the question at the rank\n// call and keys it to the caller.\nimport type { OutcomeReport } from '../examples/outcome';\nimport type { DecisionReport } from '../examples/record';\nimport { DECISION_KINDS, type DecisionKind } from '../questions';\nimport type { Rank, Ranked, Score, Thresholds, Transport } from './types';\n\nexport const RANK_PATH = '/api/v1/candidates/rank';\nexport const DECISIONS_PATH = '/api/v1/candidates/decisions';\n\n// The service gave no ranking: the API answered other than 200 (503\n// `ranking_unavailable` when the pod is down), the transport threw, or the\n// body is not a reply. The question is then System Two's alone.\nexport class RankingUnavailable extends Error {}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nconst isKind = (value: string): value is DecisionKind =>\n (DECISION_KINDS as readonly string[]).includes(value);\n\nfunction scoreOf(value: unknown): Score | undefined {\n if (!isRecord(value)) return undefined;\n const { id, score, rightness } = value;\n return typeof id === 'string' &&\n typeof score === 'number' &&\n typeof rightness === 'number' &&\n rightness >= 0 &&\n rightness <= 1\n ? { id, score, rightness }\n : undefined;\n}\n\nfunction thresholdsOf(value: unknown): Thresholds | undefined {\n if (!isRecord(value)) return undefined;\n const entries = Object.entries(value).map(([kind, threshold]) =>\n isKind(kind) && isRecord(threshold) && typeof threshold.from === 'number'\n ? [kind, { from: threshold.from }]\n : undefined,\n );\n return entries.every((entry) => entry !== undefined) ? Object.fromEntries(entries) : undefined;\n}\n\n// The reply as the API sends it, or none when the body is not one.\nexport function rankedOf(body: unknown): Ranked | undefined {\n if (!isRecord(body) || !Array.isArray(body.scores)) return undefined;\n const scores = body.scores.map(scoreOf);\n const thresholds = thresholdsOf(body.thresholds);\n return typeof body.capture_id === 'string' &&\n typeof body.head === 'string' &&\n scores.every((score) => score !== undefined) &&\n thresholds !== undefined\n ? { capture_id: body.capture_id, head: body.head, scores, thresholds }\n : undefined;\n}\n\nexport type RankingClient = {\n readonly rank: Rank;\n // Reports the composed decision of one change. A repeat is the same\n // answer; a report the API refuses or the transport drops is one failed\n // call, which nothing retries and nothing shows (decided: nothing in the\n // UI about what is sent).\n readonly decision: (report: DecisionReport) => Promise<void>;\n // Reports one outcome of a decision, by the decision's id.\n readonly outcome: (decision: string, outcome: OutcomeReport) => Promise<void>;\n};\n\nexport function rankingClient(transport: Transport): RankingClient {\n const post = (path: `/api/v1/candidates/${string}`, body: unknown) =>\n transport(path, { method: 'POST', body }).catch(() => ({ status: 0, body: undefined }));\n return {\n async rank(request) {\n const { status, body } = await post(RANK_PATH, request);\n const ranked = status === 200 ? rankedOf(body) : undefined;\n if (ranked === undefined) {\n throw new RankingUnavailable(\n status === 200 ? 'the ranking service answered with no ranking' : `status ${status}`,\n );\n }\n return ranked;\n },\n async decision(report) {\n await post(DECISIONS_PATH, report);\n },\n async outcome(decision, outcome) {\n await post(`${DECISIONS_PATH}/${encodeURIComponent(decision)}/outcomes`, outcome);\n },\n };\n}\n","// The composition of the two readings of one question. System Two\n// understands: the words, the statement and every typed value are its. System\n// One maps, where sure: its answer stands when its rightness clears the\n// head's threshold for the kind; otherwise the question is System Two's own\n// answer, the candidate its stated slot names, which may be none. Where the\n// two differ and System One is sure, System One's stands and the record says\n// both: the decision is graded later, not withheld.\nimport { type DecisionKind, NONE_CANDIDATE_ID } from '../questions';\nimport type { Ranked, Score } from '../ranking';\n\nconst real = (score: Score): boolean => score.id !== NONE_CANDIDATE_ID;\n\n// A ranking's pick: its best real candidate, in rank order. `(none)` is\n// ranked and never picked; a ranking of nothing else picks nothing.\nexport function pickOf(scores: readonly Score[]): Score | undefined {\n return scores.find(real);\n}\n\n// Whether System One is sure of its pick for a question of `kind`: the pick's\n// rightness reaches the threshold the reply carries for the kind. A reply\n// with no threshold for the kind is sure of nothing of that kind, and\n// `(none)` ranked first is never sure, whatever the rightness: the words may\n// mean nothing the set holds.\nexport function sure(ranked: Ranked, kind: DecisionKind): boolean {\n const from = ranked.thresholds[kind]?.from;\n const pick = pickOf(ranked.scores);\n return (\n from !== undefined &&\n pick !== undefined &&\n ranked.scores[0]?.id !== NONE_CANDIDATE_ID &&\n pick.rightness >= from\n );\n}\n\n// The two readings of one question. `chat` is System Two's candidate, null\n// when its statement names none; `ranked` is System One's reply, null when it\n// gave none (no transport, a failed call).\nexport type Readings = {\n readonly kind: DecisionKind;\n readonly chat: string | null;\n readonly ranked: Ranked | null;\n};\n\n// One question composed: whose answer was taken and which, System One's pick\n// with its rightness where it ranked, and whether the two readings differed\n// where System One's was taken.\nexport type Composed = {\n readonly took: 'chat' | 'clm';\n readonly taken: string | null;\n readonly clm: { readonly id: string; readonly rightness: number } | null;\n readonly differed: boolean;\n};\n\nexport function compose({ kind, chat, ranked }: Readings): Composed {\n const pick = ranked === null ? undefined : pickOf(ranked.scores);\n const clm = pick === undefined ? null : { id: pick.id, rightness: pick.rightness };\n if (ranked !== null && clm !== null && sure(ranked, kind)) {\n return { took: 'clm', taken: clm.id, clm, differed: chat !== null && chat !== clm.id };\n }\n return { took: 'chat', taken: chat, clm, differed: false };\n}\n\n// The move rule: System One's operation stands only when it was sure of the\n// operation and of every question asked under it. Where a question under it\n// fell to System Two, the operation is System Two's too, and the change is\n// resolved again under that operation.\nexport function moveStands(under: readonly Composed[]): boolean {\n return under.every((question) => question.took === 'clm');\n}\n","// The canvas tools: the tools that work on one authoring session. A host\n// constructs them from that session's ports; without a session they cannot\n// be constructed, and without a `transport` they compose System Two alone.\n// Each registration is a name, a description that carries the tool's\n// guidance to any host, an input schema and a handler, and says nothing\n// about the host's editor. With a `transport` the set also reads the\n// session's frames for what happened next to each reported change (the\n// outcome observer, composed here with the source it was given, every apply\n// of the change tool run through it), until the host disposes of the set.\n//\n// Every result ends with the current canvas, so each call corrects the\n// model's picture of it. Save and Generate run only when their own tool is\n// called, through the operations the canvas's own buttons run; no tool asks\n// for a confirmation and none reaches an operation the canvas confirms.\nimport { ApplyUnobservedError, type GenerateEvent } from '@lace-cloud/canvas/engine';\nimport type { ToolRegistration } from '../../contract/tool-registry';\nimport type { ToolResult, ToolSchema } from '../../contract/types';\nimport { OPERATION_TEXT, type Slot } from '../../questions';\nimport { applyChanges, type ChangeRecord, OPERATIONS, parseChanges } from './change';\nimport { trimValidate } from './commands';\nimport { outcomeObserver } from './outcome';\nimport { type CanvasToolPorts, endText, latest } from './ports';\nimport {\n errorText,\n InvalidInput,\n NO_INPUT,\n reasonText,\n registration,\n registrationOf,\n} from './registration';\nimport { renderCanvas } from './render';\n\n// What the model's reading states, slot by slot: one property per slot of\n// a reading, so the schema and the comparison name the same parts.\nconst READING_PROPERTIES: Record<Slot, Record<string, unknown>> = {\n operation: {\n type: 'string',\n enum: OPERATIONS.map((operation) => operation.id),\n description: OPERATIONS.map((operation) => OPERATION_TEXT[operation.id]).join('; '),\n },\n instance: {\n type: 'string',\n description:\n 'The instance a set, bind, clear, disconnect, rename or delete works on, or the group an ungroup dissolves.',\n },\n input: {\n type: 'string',\n description: 'The input a set, bind, clear or disconnect works on, or a connect wires into.',\n },\n sourceInstance: {\n type: 'string',\n description: 'The instance a connect wires from.',\n },\n output: { type: 'string', description: 'The output a connect wires from.' },\n targetInstance: {\n type: 'string',\n description: 'The instance a connect wires into.',\n },\n module: {\n type: 'string',\n description: 'The registry module a place adds, as `author/name`.',\n },\n};\n\nconst READING = { type: 'object', properties: READING_PROPERTIES, additionalProperties: false };\n\nconst CHANGE: ToolSchema = {\n name: 'lace_change_module_canvas',\n title: 'Change module canvas',\n description: [\n \"Changes a Lace module canvas. Do not read the canvas before calling it. For each change pass the developer's own words in `request`, one entry per change: this tool resolves which operation, instances, inputs, outputs and registry modules are meant.\",\n \"`request` carries the words and never a literal value: pass each literal the developer gave (an input's value, an instance's new name, the name of the variable an input is bound to) in `value`, one change per entry, each with its own `value`. Lace withholds `value` from what it ranks and keeps, and keeps the words of `request` as written; the tool selects and never writes a value of its own.\",\n 'Every result of this tool carries the current canvas. On every call pass your own reading of each change in `modelReading`: always its `operation`, and any instance, input, output or registry module the developer named, as the canvas lists it once a result has shown you the canvas. Never put a value in `modelReading`. Where the words bear a second reading, pass it in `alternativeReading`.',\n \"Lace reads the words too and applies its own reading where it is sure, yours otherwise; where the two differ the result says so: tell the developer. When Lace is also sure of your alternative reading, nothing is applied and the result shows both: ask the developer. A change neither reading settles is not applied, and the result names the part and its candidates: send it again naming one as the canvas lists it, with the developer's own words. Do not save or generate unless the developer asked.\",\n ].join(' '),\n inputSchema: {\n type: 'object',\n properties: {\n changes: {\n type: 'array',\n minItems: 1,\n description: 'The changes, in order, one entry per change.',\n items: {\n type: 'object',\n properties: {\n request: {\n type: 'string',\n description:\n \"One change, in the developer's own words, and never a literal value: that goes in `value`.\",\n },\n value: {\n description:\n \"The literal the developer gave for this change: an input's value, an instance's new name, or the name of the variable an input is bound to (`var.<name>`). One value per entry: a change with a value of its own is an entry of its own.\",\n },\n modelReading: READING,\n alternativeReading: READING,\n },\n required: ['request', 'modelReading'],\n additionalProperties: false,\n },\n },\n },\n required: ['changes'],\n additionalProperties: false,\n },\n};\n\nconst DESCRIBE: ToolSchema = {\n name: 'lace_describe_module_canvas',\n title: 'Describe module canvas',\n description:\n 'Describes a Lace module canvas (its module instances with their inputs and outputs, the wires between them, the groups, the diagnostics, and whether it holds unsaved or ungenerated edits) for answering questions about it. Not needed before making changes.',\n inputSchema: NO_INPUT,\n};\n\nconst SAVE: ToolSchema = {\n name: 'lace_save_module_canvas',\n title: 'Save module canvas',\n description: 'Saves a Lace module canvas. Call it only when the developer asks to save.',\n inputSchema: NO_INPUT,\n};\n\nconst GENERATE: ToolSchema = {\n name: 'lace_generate_module_terraform',\n title: 'Generate module Terraform',\n description:\n \"Writes the Terraform for a Lace module canvas: the saved canvas rendered to the module's .tf files. Returns the files written, or why Lace did not generate. Call it only when the developer asks to generate.\",\n inputSchema: NO_INPUT,\n};\n\n// The canvas tools' schemas as data, in the order `canvasTools` returns its\n// registrations: change, describe, save, generate. A host that generates a\n// manifest of the tools reads these without constructing the set, and the\n// set registers exactly these.\nexport const canvasToolSchemas: readonly [ToolSchema, ToolSchema, ToolSchema, ToolSchema] = [\n CHANGE,\n DESCRIBE,\n SAVE,\n GENERATE,\n];\n\ntype Said = { readonly text: string; readonly isError: boolean };\n\n// What a Generate's event says in a result. Its progress says nothing; it\n// closes with the files it wrote and the validate report of the written\n// tree, or with the engine's refusal by its reason.\nfunction generateSaid(event: GenerateEvent): Said[] {\n switch (event.type) {\n case 'progress':\n return [];\n case 'success':\n return [\n {\n text: [\n `Generated the Terraform. Files written: ${event.written.join(', ')}.`,\n `lace module validate on the written tree: ${JSON.stringify(trimValidate(event.validate))}`,\n ].join('\\n'),\n isError: false,\n },\n ];\n case 'error':\n return [\n {\n text: `Lace did not generate: ${event.message} (${reasonText(event.reason)}).`,\n isError: true,\n },\n ];\n }\n}\n\n// What a write the engine made says when the session's stream ended before\n// the frame that carries it: the canvas the result ends with cannot show it.\n// Any other failure is the call's own.\nfunction unobserved(error: unknown): Said {\n if (!(error instanceof ApplyUnobservedError)) throw error;\n return {\n text: `The session's stream ended (${endText(error.end)}) before the canvas showed this, so the canvas below is from before it.`,\n isError: false,\n };\n}\n\n// The change tool's result: the text its model reads, and beside it, for\n// the host, the record of each change that was applied, in order.\nexport type ChangeResult = ToolResult & {\n readonly applied: readonly ChangeRecord[];\n};\n\n// The canvas tools in their order: change, describe, save, generate, and\n// `dispose`, which ends the set's reading of the session's frames; a host\n// calls it when it drops the tools or the session closes.\nexport type CanvasTools = readonly [\n ToolRegistration<ChangeResult>,\n ToolRegistration,\n ToolRegistration,\n ToolRegistration,\n] & { readonly dispose: () => void };\n\nconst NO_RECORDS = { applied: [] } as const;\n\nexport function canvasTools(ports: CanvasToolPorts): CanvasTools {\n const [change, describe, save, generate] = canvasToolSchemas;\n const observer = ports.transport === undefined ? undefined : outcomeObserver(ports.transport);\n const dispose =\n observer === undefined ? () => {} : ports.source.subscribe(observer.frame, () => {});\n // What a call did; a call that threw says so the same way.\n const attempt = (run: () => Promise<readonly Said[]>): Promise<readonly Said[]> =>\n run().catch((error): Said[] => [{ text: errorText(error), isError: true }]);\n\n // What a call said, each part set off by a blank line, then the canvas as\n // it stands after the call.\n const answer = async (said: readonly Said[]): Promise<ToolResult> => ({\n content: [\n ...said.map((each) => `${each.text}\\n`),\n renderCanvas(await latest(ports.source)),\n ].join('\\n'),\n isError: said.some((each) => each.isError),\n });\n\n const registrations = [\n registrationOf<ChangeResult>(\n change,\n async (input) => {\n try {\n const { text, applied } = await applyChanges(ports, parseChanges(input), observer?.own);\n observer?.follow(applied);\n return { ...(await answer([{ text, isError: false }])), applied };\n } catch (error) {\n if (!(error instanceof InvalidInput)) throw error;\n return { ...(await answer([{ text: errorText(error), isError: true }])), ...NO_RECORDS };\n }\n },\n (failure) => ({ ...failure, ...NO_RECORDS }),\n ),\n registration(describe, () => answer([])),\n registration(save, async () =>\n answer(\n await attempt(async () => {\n const saved: Said = { text: 'Saved the canvas.', isError: false };\n try {\n await ports.editor.save();\n return [saved];\n } catch (error) {\n return [saved, unobserved(error)];\n }\n }),\n ),\n ),\n registration(generate, async () =>\n answer(\n await attempt(async () => {\n const said: Said[] = [];\n try {\n for await (const event of ports.editor.generate()) said.push(...generateSaid(event));\n } catch (error) {\n said.push(unobserved(error));\n }\n return said;\n }),\n ),\n ),\n ] as const;\n return Object.assign(registrations, { dispose });\n}\n","// The change tool's work: each change, in the developer's words, resolved\n// against the canvas as it is when that change is reached by the two\n// systems, then applied.\n//\n// System Two understands: the words, the reading it states with them\n// (`modelReading`, required on every call) and every typed value are its.\n// System One maps, where sure: a question's answer is its pick when the\n// pick's rightness clears the head's threshold for the kind, else System\n// Two's own answer, the candidate its stated slot names. The names a request\n// holds settle a question before either is asked. The operation is System\n// One's only when it was sure of it, of every question under it, and the\n// change resolves under it: the move rule is part of planning, and where it\n// fails the change is resolved again under System Two's operation, whose\n// outcome alone is the change's. Where System One is sure and the reading\n// named another candidate, System One's stands and the result says both:\n// the decision is graded by what the developer does next, not withheld. A\n// change neither system resolves is not applied, and the result says which\n// part and its candidates. Where the model gave an alternative reading and\n// System One is sure of a different answer under it, nothing is applied and\n// both decisions come back. `steps` (one change or several) is outside that\n// gate: System Two's answer is `one` by construction, System One's, read\n// under the model's reading alone, stands where sure, and it decides only\n// what the result says.\n//\n// What System One reads: the request rendered with every form of the\n// change's own value and every other value of the call the canvas does not\n// name withheld, and System Two's statements (its reading, and its\n// alternative reading where it gave one), each the stated slots that name a\n// fact (an operation, a name the canvas holds, a registry module as\n// `author/name`), withheld the same way. A change whose request or\n// statements still hold any withheld text of the call inside a word is not\n// ranked at all.\n//\n// A change leaves a record for the host: what it changed, the state before\n// and after, and the revision its apply produced. The composed decision is\n// reported to Lace's API once the call settles, with what was applied in\n// words, every value withheld.\nimport { type ApplyResult, ApplyUnobservedError, InputMode } from '@lace-cloud/canvas/engine';\nimport type { DecisionReport, Question } from '../../examples';\nimport { type Composed, moveStands, pickOf } from '../../hybrid';\nimport {\n type DecisionKind,\n forms,\n holdsValue,\n NONE_CANDIDATE_ID,\n READING_SLOTS,\n type Reading,\n renderReading,\n renderRequest,\n type Slot,\n statedSlots,\n unnamed,\n VALUE_PLACEHOLDER,\n variableName,\n withhold,\n} from '../../questions';\nimport { rankingClient } from '../../ranking';\nimport { runCommand } from './commands';\nimport {\n type CanvasInput,\n type CanvasInstance,\n type CanvasReading,\n canvasNames,\n connectionOptions,\n inputOptions,\n instanceOptions,\n moduleId,\n moduleOptions,\n type Option,\n operationOptions,\n readCanvas,\n sourceOptions,\n stepsOptions,\n targetOptions,\n} from './enumerate';\nimport { bindingOf, follow, presenceOf, targetState } from './outcome';\nimport { type CanvasEditor, type CanvasToolPorts, endText, latest } from './ports';\nimport { errorText, InvalidInput } from './registration';\nimport { renderState, renderTarget } from './render';\nimport {\n type Ask,\n asAsked,\n type Decision,\n decide,\n moduleReferences,\n NONE_OVER,\n type Ranking,\n termsOf,\n Undecided,\n} from './resolve';\n\n// One entry of the tool's input. `values` holds the literal the developer\n// gave: one item when the entry carries it and none when it does not.\n// `reading` is the model's own reading of the change and `alternative` its\n// other reading of the words, where it gave one.\nexport type Change = {\n readonly request: string;\n readonly values: readonly unknown[];\n readonly reading: Reading;\n readonly alternative?: Reading;\n};\n\n// What an applied change addressed: an instance of a scope (the module key\n// of the module that owns it), or one input of it.\nexport type ChangeTarget = {\n readonly scope: string;\n readonly instance: string;\n readonly input?: string;\n};\n\n// An input's binding: its mode and the content of that mode. A sensitive\n// input's binding is its mode alone.\nexport type InputBinding = {\n readonly mode: CanvasInput['mode'];\n readonly value?: unknown;\n readonly variable?: string;\n readonly expression?: string;\n readonly wiredSource?: string;\n};\n\n// An instance that is on the canvas: its name in its scope and its module.\nexport type InstancePresence = {\n readonly instance: string;\n readonly module: string;\n};\n\n// The state of what a change addressed, before it or after it: an input's\n// binding, an instance's presence, or `null` for an instance that is not on\n// the canvas.\nexport type ChangeState = InputBinding | InstancePresence | null;\n\n// One question of a decision as its record holds it: its kind and the ids of\n// its candidates, so an outcome can name the question and candidate a later\n// edit answers.\nexport type RecordQuestion = {\n readonly kind: DecisionKind;\n readonly candidates: readonly string[];\n};\n\n// The record of one applied change: what it addressed, that target's state\n// before and after, the revision of the frame its apply produced (absent\n// where the editor answered none), the decision's questions in the order\n// reported, and whether the decision was reported to Lace, so its outcomes\n// are. `id` is the decision's.\nexport type ChangeRecord = {\n readonly id: string;\n readonly target: ChangeTarget;\n readonly before: ChangeState;\n readonly after: ChangeState;\n readonly revision?: number;\n readonly questions: readonly RecordQuestion[];\n readonly reported: boolean;\n};\n\n// A change that cannot be applied as it was sent, whatever it resolves to.\nclass Unapplicable extends Error {}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nconst present = (value: unknown): boolean => value !== undefined && value !== null;\n\nfunction readingOf(index: number, name: string, stated: unknown): Reading {\n if (!isRecord(stated)) {\n throw new InvalidInput(`change ${index + 1}: \\`${name}\\` is an object of names`);\n }\n return Object.fromEntries(\n READING_SLOTS.flatMap((slot) => {\n const value = stated[slot];\n return typeof value === 'string' ? [[slot, value]] : [];\n }),\n );\n}\n\nexport function parseChanges(input: Record<string, unknown>): Change[] {\n const { changes } = input;\n if (!Array.isArray(changes)) throw new InvalidInput('`changes` is a list of changes');\n return changes.map((entry: unknown, index) => {\n if (!isRecord(entry) || typeof entry.request !== 'string') {\n throw new InvalidInput(`change ${index + 1} needs \\`request\\`: the developer's own words`);\n }\n if (!present(entry.modelReading)) {\n throw new InvalidInput(\n `change ${index + 1} needs \\`modelReading\\`: your own reading of the change, an object of the names you stated`,\n );\n }\n const alternative = present(entry.alternativeReading)\n ? { alternative: readingOf(index, 'alternativeReading', entry.alternativeReading) }\n : {};\n return {\n request: entry.request,\n values: [entry.value].filter(present),\n reading: readingOf(index, 'modelReading', entry.modelReading),\n ...alternative,\n };\n });\n}\n\n// One action of an `ApplyAction` batch, in the generated shape: an\n// instance-addressed action carries `scope`, the key of the module that\n// owns the instance, on its own sub-message, beside the instance's id there.\ntype Action = Parameters<CanvasEditor['apply']>[0][number];\n\n// What an operation resolves a change to: the one action that applies it,\n// the words for what it did, and what the record of it holds: the target,\n// its state on the canvas the change was resolved against, and how to read\n// its state from the canvas the apply produced.\ntype Plan = {\n readonly action: Action;\n readonly summary: (result: ApplyResult) => string;\n readonly target: (result: ApplyResult) => ChangeTarget;\n readonly before: ChangeState;\n readonly after: (canvas: CanvasReading, result: ApplyResult) => ChangeState;\n};\n\ntype Resolving = {\n readonly canvas: CanvasReading;\n // The request as rendered for the ranking.\n readonly request: string;\n readonly values: readonly unknown[];\n readonly ports: CanvasToolPorts;\n // Resolves one decision and records it for the result.\n readonly pick: <T>(\n kind: DecisionKind,\n label: string,\n options: readonly Option<T>[],\n ) => Promise<T>;\n // Records a line the result says beside the change's outcome.\n readonly note: (line: string) => void;\n};\n\n// One operation: its id (its prose is `OPERATION_TEXT[id]`, written where\n// every candidate's prose is) and how it resolves the rest of a change.\ntype Operation = {\n readonly id: string;\n // Whether the operation writes the literal a change carries in `value`.\n readonly takesValue: boolean;\n readonly plan: (resolving: Resolving) => Promise<Plan>;\n};\n\n// The record parts of an edit to one input of an instance.\nfunction inputEdit(canvas: CanvasReading, instance: CanvasInstance, inputName: string) {\n const state = (of: CanvasReading) => bindingOf(of, instance.scope, instance.name, inputName);\n return {\n target: () => ({ scope: instance.scope, instance: instance.name, input: inputName }),\n before: state(canvas),\n after: state,\n };\n}\n\n// The record parts of an edit to an instance itself, which is `nameAfter`\n// once the edit is applied.\nfunction instanceEdit(canvas: CanvasReading, instance: CanvasInstance, nameAfter: string) {\n return {\n target: () => ({ scope: instance.scope, instance: instance.name }),\n before: presenceOf(canvas, instance.scope, instance.name),\n after: (of: CanvasReading) => presenceOf(of, instance.scope, nameAfter),\n };\n}\n\n// System One selects and does not write: a value, a new name or a\n// variable's name is the literal the developer gave, carried in `value`.\nfunction given(values: readonly unknown[], what: string): unknown {\n if (values.length === 0) {\n throw new Unapplicable(`this change needs ${what}: pass it in \\`value\\``);\n }\n return values[0];\n}\n\nfunction givenName(values: readonly unknown[], what: string): string {\n const name = given(values, what);\n if (typeof name !== 'string') throw new Unapplicable(`${what} is text: pass it in \\`value\\``);\n return name;\n}\n\ntype BindingMode = CanvasInput['mode'];\n\nconst EVERY_MODE: readonly BindingMode[] = ['empty', 'literal', 'variable', 'expression', 'wired'];\n\n// The instance and the input an input operation works on, picked among the\n// inputs whose binding is in one of `modes`: an operation is offered only\n// the inputs it can act on.\nasync function pickInput({ canvas, pick }: Resolving, modes: readonly BindingMode[]) {\n const offered = (instance: CanvasInstance) =>\n instance.inputs.filter((input) => modes.includes(input.mode));\n const instance = await pick(\n 'instance',\n 'instance',\n instanceOptions(canvas.instances.filter((each) => offered(each).length > 0)),\n );\n const input = await pick('input', 'input', inputOptions(instance, offered(instance)));\n return { instance, input };\n}\n\n// The one `update_input` action: an input given a binding of one mode.\nfunction updateInput(\n instance: CanvasInstance,\n input: CanvasInput,\n binding: { mode: InputMode; value?: unknown; variable?: string },\n): Action {\n return {\n update_input: {\n scope: instance.scope,\n instance_id: instance.name,\n input_name: input.name,\n mode: binding.mode,\n value: binding.value,\n variable: binding.variable ?? '',\n expression: '',\n },\n };\n}\n\n// The most modules one registry listing returns.\nconst CATALOG_LIMIT = 500;\n\nconst place: Operation = {\n id: 'place',\n takesValue: false,\n async plan({ canvas, request, ports, pick, note }) {\n // A request that refers to a module as `author/name` narrows the listing\n // to modules of that name; any other request is resolved over the\n // catalog the listing returns.\n const [query] = moduleReferences(request).map((reference) => reference.split('/').slice(-1)[0]);\n const listing = await runCommand(ports.commands, 'registry list', {\n axis: 'module',\n limit: CATALOG_LIMIT,\n query,\n });\n if (listing.failed !== undefined) throw new Error(listing.failed.text);\n for (const document of listing.documents) {\n if (document.truncated) {\n note(\n `The registry listing was cut at ${CATALOG_LIMIT} modules, so the module meant may not have been a candidate. Name it as \\`author/name\\`, or find it with lace_search_module_registry.`,\n );\n }\n }\n const rows = listing.documents.flatMap((document) => document.items);\n const row = await pick('module', 'registry module', moduleOptions(rows));\n const placed = (result: ApplyResult) => result.created.map((ref) => ref.id).join(', ');\n return {\n action: {\n place_module: { author: row.author, name: row.name, version: row.version },\n },\n summary: (result) => `placed ${moduleId(row)} ${row.version} as ${placed(result)}`,\n target: (result) => ({ scope: canvas.entry, instance: placed(result) }),\n before: null,\n after: (of, result) =>\n result.created\n .map((ref) => presenceOf(of, ref.scope, ref.id))\n .find((presence) => presence !== null) ?? null,\n };\n },\n};\n\nconst connect: Operation = {\n id: 'connect',\n takesValue: false,\n async plan({ canvas, ports, pick }) {\n const source = await pick('instance', 'source instance', sourceOptions(canvas.instances));\n const target = await pick(\n 'instance',\n 'target instance',\n targetOptions(canvas.instances, source),\n );\n const scored = await ports.editor.wiringCandidates({\n scope: source.scope,\n source: source.name,\n target: target.name,\n });\n const pair = await pick('connection', 'connection', connectionOptions(source, target, scored));\n return {\n action: {\n connect: {\n scope: target.scope,\n source_scope: source.scope,\n source: source.name,\n target: target.name,\n source_output: pair.output,\n target_input: pair.input,\n },\n },\n summary: () => `connected ${source.id}.${pair.output} → ${target.id}.${pair.input}`,\n ...inputEdit(canvas, target, pair.input),\n };\n },\n};\n\nconst disconnect: Operation = {\n id: 'disconnect',\n takesValue: false,\n async plan(resolving) {\n const { instance, input } = await pickInput(resolving, ['wired']);\n return {\n action: {\n disconnect: { scope: instance.scope, target: instance.name, input_name: input.name },\n },\n summary: () => `disconnected ${instance.id}.${input.name}`,\n ...inputEdit(resolving.canvas, instance, input.name),\n };\n },\n};\n\nconst set: Operation = {\n id: 'set',\n takesValue: true,\n async plan(resolving) {\n const value = given(resolving.values, 'the value the developer gave');\n const { instance, input } = await pickInput(resolving, EVERY_MODE);\n const shown = input.sensitive ? '(sensitive, value withheld)' : `= ${JSON.stringify(value)}`;\n return {\n action: updateInput(instance, input, { mode: InputMode.INPUT_MODE_LITERAL, value }),\n summary: () => `set ${instance.id}.${input.name} ${shown}`,\n ...inputEdit(resolving.canvas, instance, input.name),\n };\n },\n};\n\nconst bind: Operation = {\n id: 'bind',\n takesValue: true,\n async plan(resolving) {\n const variable = variableName(givenName(resolving.values, \"the variable's name\"));\n const { instance, input } = await pickInput(resolving, EVERY_MODE);\n return {\n action: updateInput(instance, input, { mode: InputMode.INPUT_MODE_VARIABLE, variable }),\n summary: () => `bound ${instance.id}.${input.name} to var.${variable}`,\n ...inputEdit(resolving.canvas, instance, input.name),\n };\n },\n};\n\nconst clear: Operation = {\n id: 'clear',\n takesValue: false,\n async plan(resolving) {\n const { instance, input } = await pickInput(resolving, ['literal', 'variable', 'expression']);\n return {\n action: updateInput(instance, input, { mode: InputMode.INPUT_MODE_EMPTY }),\n summary: () => `cleared ${instance.id}.${input.name}`,\n ...inputEdit(resolving.canvas, instance, input.name),\n };\n },\n};\n\nconst rename: Operation = {\n id: 'rename',\n takesValue: true,\n async plan({ canvas, values, pick }) {\n const name = givenName(values, 'the new name');\n const instance = await pick('instance', 'instance', instanceOptions(canvas.instances));\n return {\n action: {\n rename_instance: { scope: instance.scope, old_id: instance.name, new_id: name },\n },\n summary: () => `renamed ${instance.id} to ${name}`,\n ...instanceEdit(canvas, instance, name),\n };\n },\n};\n\nconst remove: Operation = {\n id: 'delete',\n takesValue: false,\n async plan({ canvas, pick }) {\n const instance = await pick('instance', 'instance', instanceOptions(canvas.instances));\n return {\n action: { delete_instance: { scope: instance.scope, instance_id: instance.name } },\n summary: () => `deleted ${instance.id}`,\n ...instanceEdit(canvas, instance, instance.name),\n };\n },\n};\n\nconst ungroup: Operation = {\n id: 'ungroup',\n takesValue: false,\n async plan({ canvas, pick }) {\n const groups = new Set(canvas.groups.map((group) => group.id));\n const group = await pick(\n 'instance',\n 'group',\n instanceOptions(canvas.instances.filter((instance) => groups.has(instance.id))),\n );\n return {\n action: { ungroup: { scope: group.scope, group_id: group.name } },\n summary: () => `ungrouped ${group.id}`,\n ...instanceEdit(canvas, group, group.name),\n };\n },\n};\n\n// The operations a change can be. Each is one row: its name and how it\n// resolves the rest of the change.\nexport const OPERATIONS: readonly Operation[] = [\n place,\n connect,\n disconnect,\n set,\n bind,\n clear,\n rename,\n remove,\n ungroup,\n];\n\ntype Outcome =\n | {\n readonly kind: 'applied';\n readonly summary: string;\n readonly record: ChangeRecord;\n // The canvas the apply produced.\n readonly canvas: CanvasReading;\n // What the report of the change withholds beside its own value: every\n // value of the call the canvas did not name when the change was\n // ranked.\n readonly withheld: readonly unknown[];\n }\n // The ask rule fired: the model's two readings each map to a change\n // System One is sure of.\n | { readonly kind: 'asked'; readonly lace: Reading; readonly alternative: Reading }\n | { readonly kind: 'notApplied'; readonly why: string }\n // The engine answered the apply, and the session's stream ended before\n // the frame that carries it: what the canvas holds cannot be read.\n | { readonly kind: 'unobserved'; readonly end: string };\n\n// What resolving one change leaves beside its outcome: the decisions made,\n// the question neither system decided where there was one, the lines the\n// result says with it, and, where System One's operation did not stand (the\n// move rule), why, in the result's words.\ntype Trail = {\n readonly decisions: Decision<unknown>[];\n undecided?: Undecided;\n readonly notes: string[];\n moved?: string;\n};\n\n// A question under System One's operation fell to System Two while the move\n// was on trial: the operation does not stand.\nclass Fell extends Error {\n constructor(readonly label: string) {\n super(`the ${label} fell to System Two`);\n }\n}\n\n// Whether the tool read an entry as holding more than the one change it\n// applied: its words name other candidates for a decision, or System One\n// read it as several changes.\nfunction heldMore(decisions: readonly Decision<unknown>[]): boolean {\n return decisions.some(\n (decision) =>\n decision.others.length > 0 ||\n (decision.kind === 'steps' && decision.option.value === 'several'),\n );\n}\n\n// A decision the two systems read, as against one the names settled.\nconst twoSystems = (decision: Decision<unknown>) => decision.composed !== null;\n\n// What the two systems composed of the decisions they read.\nconst composedOf = (decisions: readonly Decision<unknown>[]): Composed[] =>\n decisions.flatMap((decision) => (decision.composed === null ? [] : [decision.composed]));\n\n// Why System One's operation did not stand, in the result's words: a\n// question under it fell to the model's reading, or the change did not\n// resolve under it.\nfunction movedText(operation: string, error: unknown): string {\n return error instanceof Fell || error instanceof Undecided\n ? `the ${error.label} under Lace's ${operation} fell to your reading`\n : `Lace's ${operation} did not resolve: ${errorText(error)}`;\n}\n\n// The slots of a reading that state a fact: the operation by its id, a name\n// the canvas holds, or a registry module as `author/name`. Any other slot is\n// no statement: a paraphrase, a stale name, or a value.\nfunction statedFacts(names: ReadonlySet<string>, reading: Reading): Reading {\n const fact = (slot: Slot, name: string): boolean =>\n slot === 'operation'\n ? OPERATIONS.some((operation) => operation.id === name)\n : slot === 'module'\n ? moduleReferences(name)[0] === name\n : names.has(name);\n return Object.fromEntries(\n statedSlots(reading).flatMap((slot) => {\n const name = reading[slot];\n return name !== undefined && fact(slot, name) ? [[slot, name]] : [];\n }),\n );\n}\n\n// How the tool runs one apply of its own: as it is, or through the outcome\n// observer, which holds the frames that arrive while the apply is in flight\n// and reads the one at the revision it returned as the package's own.\nexport type OwnApply = (apply: () => Promise<ApplyResult>) => Promise<ApplyResult>;\n\nconst asItIs: OwnApply = (apply) => apply();\n\nasync function resolveAndApply(\n ports: CanvasToolPorts,\n own: OwnApply,\n change: Change,\n call: readonly unknown[],\n trail: Trail,\n notApplied: (why: string) => Outcome,\n): Promise<Outcome> {\n const canvas = readCanvas(await latest(ports.source));\n const names = canvasNames(canvas);\n // Every form of the change's own value is the placeholder in the request\n // and the statements, a form the canvas names included: it is never read\n // as a name. Every other value of the call stands as the placeholder in\n // them unless the canvas names it.\n const values = [...forms(change.values), ...unnamed(names, call)];\n const statementOf = (reading: Reading) =>\n withhold(renderReading(statedFacts(names, reading)), values);\n const statement = statementOf(change.reading);\n const alternative =\n change.alternative === undefined\n ? undefined\n : { statement: statementOf(change.alternative), reading: change.alternative };\n const statements = [statement, ...(alternative === undefined ? [] : [alternative.statement])];\n // Rendered once, cut to the room the longest statement leaves: this one\n // string is every rank call's request for the change and the request its\n // captures carry. A name is read from the developer's words around the\n // placeholder, never from the token.\n const request = renderRequest(\n change.request,\n values,\n statements.reduce((longest, each) => (each.length > longest.length ? each : longest)),\n );\n // A withheld text of the call still inside a word that is no canvas name,\n // in the request or in either statement: no rank call is made for the\n // change (its decision is still reported, with no capture).\n const rankable = !holdsValue(withhold([request, ...statements].join(' '), [...names]), values);\n const rank = ports.transport === undefined ? undefined : rankingClient(ports.transport).rank;\n if (!rankable && rank !== undefined) {\n trail.notes.push(\n \"This change's words or reading hold a value of the call inside a word, so Lace did not rank it.\",\n );\n }\n // `steps` is read under the model's reading alone: it decides only what\n // the result says, so it is never ranked under the alternative reading and\n // never asks.\n const main: Ask = {\n request,\n terms: termsOf(request.split(VALUE_PLACEHOLDER).join(' ')),\n statement,\n reading: change.reading,\n ...(rankable ? { rank } : {}),\n };\n const ask: Ask = { ...main, ...(alternative === undefined ? {} : { alternative }) };\n // Resolving into `into`: each decision is recorded there, and on the move's\n // trial a question under System One's operation that is not System One's\n // ends the trial.\n const resolvingInto = (into: Trail, trial: boolean): Resolving => ({\n canvas,\n request,\n values: change.values,\n ports,\n async pick(kind, label, options) {\n const decision = await decide(ask, kind, label, options);\n into.decisions.push(decision);\n if (trial && !moveStands(composedOf(into.decisions.slice(1)))) throw new Fell(label);\n return decision.option.value;\n },\n note: (line) => into.notes.push(line),\n });\n const planUnder = (decision: Decision<Operation>, into: Trail, trial: boolean) => {\n into.decisions.push(decision);\n return decision.option.value.plan(resolvingInto(into, trial));\n };\n\n const first = await decide(ask, 'operation', 'operation', operationOptions(OPERATIONS));\n const statedOperation = operationOptions(OPERATIONS).find(\n (each) => each.candidate.id === first.chat,\n );\n // The move rule, as part of planning: where System One took the operation\n // and System Two stated another, System One's stands only when every\n // question under it is System One's too and the change resolves under it.\n // Otherwise the change is resolved again under System Two's operation, and\n // only what comes of that is the change's outcome.\n const moveRule = async (): Promise<{ operation: Operation; plan: Plan }> => {\n if (\n first.how !== 'clm' ||\n statedOperation === undefined ||\n statedOperation.value === first.option.value\n ) {\n return { operation: first.option.value, plan: await planUnder(first, trail, false) };\n }\n const trial: Trail = { decisions: [], notes: [] };\n try {\n const planned = await planUnder(first, trial, true);\n trail.decisions.push(...trial.decisions);\n trail.notes.push(...trial.notes);\n return { operation: first.option.value, plan: planned };\n } catch (error) {\n trail.moved = withhold(movedText(first.option.value.id, error), change.values);\n // The operation the move refused does not stand for this change, so\n // it is no alternative the ask rule can hand back either.\n const standing: Decision<Operation> = {\n ...first,\n option: statedOperation,\n how: 'chat',\n composed: {\n took: 'chat',\n taken: statedOperation.candidate.id,\n clm: first.composed?.clm ?? null,\n differed: false,\n },\n alternative: first.alternative?.id === first.option.candidate.id ? null : first.alternative,\n };\n return { operation: statedOperation.value, plan: await planUnder(standing, trail, false) };\n }\n };\n const { operation, plan } = await moveRule();\n // Whether the entry held more than this change: words that name more\n // candidates for a decision than it holds say so; where they do not and\n // the two systems read any decision, System One reads this too (System\n // Two's answer is `one` by construction). It decides only what the result\n // says, never whether the change applies.\n const unread = trail.decisions.every((decision) => decision.others.length === 0);\n if (unread && main.rank !== undefined && trail.decisions.some(twoSystems)) {\n await decide(main, 'steps', 'steps', stepsOptions(), 'one').then((decision) =>\n trail.decisions.push(decision),\n );\n }\n if (change.values.length > 0 && !operation.takesValue && !heldMore(trail.decisions)) {\n trail.notes.push(\n `The \\`value\\` sent with this change was not used: ${operation.id} takes none.`,\n );\n }\n // The tool's reading is what its decisions picked, slot by slot. A slot of\n // the model's reading that names none of the candidates offered for it is\n // no opinion, said in one line.\n const lace: Reading = Object.assign({}, ...trail.decisions.map((each) => each.option.slots));\n const stated = statedSlots(change.reading);\n for (const slot of stated.filter(\n (slot) =>\n !trail.decisions.some((decision) =>\n decision.readings.some((each) => each[slot] === change.reading[slot]),\n ),\n )) {\n trail.notes.push(\n `Your reading's ${slot} ${change.reading[slot]} is not one of Lace's candidates${slot in lace ? `; Lace read ${lace[slot]}` : ''}.`,\n );\n }\n // The ask rule: where System One is sure of a different answer under the\n // model's alternative reading, nothing is applied and both come back.\n const asked = trail.decisions.filter(\n (decision) =>\n decision.alternative?.sure === true &&\n decision.alternative.id !== decision.option.candidate.id,\n );\n if (asked.length > 0) {\n return {\n kind: 'asked',\n lace,\n alternative: Object.assign(\n {},\n ...trail.decisions.map((decision) =>\n asked.includes(decision) ? decision.alternative?.slots : decision.option.slots,\n ),\n ),\n };\n }\n\n const result = await own(() => ports.editor.apply([plan.action]));\n if (!result.success) {\n const reasons = result.errors.map((error) => error.message).join('; ');\n return notApplied(`the engine refused it: ${reasons}`);\n }\n const after = readCanvas(await latest(ports.source));\n const record: ChangeRecord = {\n id: crypto.randomUUID(),\n target: plan.target(result),\n before: plan.before,\n after: plan.after(after, result),\n ...(result.revision === undefined ? {} : { revision: result.revision }),\n questions: trail.decisions.map((decision) => ({\n kind: decision.kind,\n candidates: decision.candidates.map((candidate) => candidate.id),\n })),\n reported: false,\n };\n return {\n kind: 'applied',\n summary: plan.summary(result),\n record,\n canvas: after,\n withheld: unnamed(names, call),\n };\n}\n\n// One change, whatever becomes of it: a failure of this change (a question\n// neither system decided, an engine that refused, a change that names\n// nothing the canvas offers) is this change's outcome and stops no other,\n// and so is an apply the engine answered whose frame the session's stream\n// ended before. A reason is text this module did not write, so the literal\n// the change carries is withheld from it: the input it was meant for may be\n// one the module marks sensitive.\nasync function runChange(\n ports: CanvasToolPorts,\n own: OwnApply,\n change: Change,\n call: readonly unknown[],\n trail: Trail,\n): Promise<Outcome> {\n const notApplied = (why: string): Outcome => ({\n kind: 'notApplied',\n why: withhold(why, change.values),\n });\n try {\n return await resolveAndApply(ports, own, change, call, trail, notApplied);\n } catch (error) {\n if (error instanceof ApplyUnobservedError) {\n return { kind: 'unobserved', end: withhold(endText(error.end), change.values) };\n }\n if (error instanceof Undecided) {\n trail.undecided = error;\n const candidates = error.candidates.map((candidate) => candidate.id).join(', ');\n return notApplied(\n `the ${error.label} was not decided: ${rankingText(error.ranking)}, and your reading names none of its candidates: ${candidates}. Send this change again with \\`modelReading\\` naming one as the canvas lists it.`,\n );\n }\n return notApplied(errorText(error));\n }\n}\n\n// System One's reading in a result's words: not sure, with its pick, or why\n// it gave none.\nfunction rankingText(ranking: Ranking): string {\n if (ranking.ranked === null) return ranking.failed;\n const [first] = ranking.ranked.scores;\n const read =\n first?.id === NONE_CANDIDATE_ID ? `read ${NONE_OVER} first` : `ranked ${first?.id} first`;\n return `Lace was not sure, ${read}`;\n}\n\n// One decision in the result's words: what it holds and how. `moved` is\n// why System One's operation did not stand, said of the operation that did.\nfunction decisionLine(decision: Decision<unknown>, moved: string | undefined): string {\n const also = `the request also names ${decision.others.join(', ')}`;\n const named = {\n exact: ['named in the request'],\n unique: ['named in the request, ignoring case'],\n first: ['named in the request first', also],\n agreed: ['named in the request and in your reading', also],\n };\n const basis =\n decision.how === 'clm'\n ? [\n `Lace's pick of ${decision.offered}`,\n ...(decision.offered > decision.candidates.length\n ? [`ranked in parts, as ${decision.offered} candidates are more than one ranking holds`]\n : []),\n ...decision.over.map((candidate) => `over ${candidate}`),\n ...(decision.composed?.differed ? [`your reading named ${decision.chat}`] : []),\n ]\n : decision.how === 'chat'\n ? [\n 'your reading',\n moved !== undefined && decision.kind === 'operation'\n ? moved\n : decision.ranking === null\n ? 'Lace did not rank'\n : rankingText(decision.ranking),\n ]\n : named[decision.how];\n return ` ${decision.label}: ${decision.option.candidate.id} (${basis.join(', ')})`;\n}\n\nfunction outcomeLines(number: number, outcome: Outcome, trail: Trail): string[] {\n const head = `Change ${number}:`;\n const lines = trail.decisions.map((decision) => decisionLine(decision, trail.moved));\n switch (outcome.kind) {\n case 'applied': {\n const moved =\n trail.moved === undefined\n ? ''\n : \" Lace's operation did not stand and yours did, marked below.\";\n const unsure = trail.decisions.some(\n (decision) =>\n decision.how === 'chat' && (trail.moved === undefined || decision.kind !== 'operation'),\n );\n const stood = unsure ? ' Where Lace was not sure, your reading stood, marked below.' : '';\n const differed = trail.decisions.some((decision) => decision.composed?.differed)\n ? \" Lace's reading differed from yours and stood, marked below: tell the developer.\"\n : '';\n const others = trail.decisions.flatMap((decision) => decision.others);\n const unapplied = others.length > 0 ? `; nothing was applied for ${others.join(', ')}` : '';\n const more = heldMore(trail.decisions)\n ? ` This entry held more than one change and only this one was applied${unapplied}. Send the rest, one entry per change.`\n : '';\n return [`${head} applied. ${outcome.summary}.${more}${moved}${stood}${differed}`, ...lines];\n }\n case 'asked':\n return [\n `${head} not applied. Lace is sure your alternative reading means another change than the one it decided.`,\n ` Your reading: ${renderReading(outcome.lace)}`,\n ` Your alternative reading: ${renderReading(outcome.alternative)}`,\n ' Ask the developer which is meant, then send that one.',\n ];\n case 'notApplied':\n return [`${head} not applied. Reason: ${outcome.why}`, ...lines];\n case 'unobserved':\n return [\n `${head} sent, and the engine answered it, but the session's stream ended (${outcome.end}) before the canvas showed it, so whether it applied cannot be read here. Do not send it again before the canvas is open again.`,\n ...lines,\n ];\n }\n}\n\n// A decision as the report of its change holds it: the capture of the\n// question as asked, none where the ranking spanned parts (`asAsked`), so\n// every candidate a question names is one of the capture it names.\nfunction questionOf(decision: Decision<unknown>): Question {\n const taken = decision.option.candidate.id;\n return {\n kind: decision.kind,\n capture_id: asAsked(decision.ranking)?.capture_id ?? null,\n chat: decision.chat,\n clm: decision.composed?.clm ?? null,\n took: decision.composed === null ? 'named' : decision.composed.took,\n taken,\n };\n}\n\n// The question neither system decided, as the report holds it.\nfunction undecidedOf(undecided: Undecided): Question {\n const ranked = asAsked(undecided.ranking);\n const pick = ranked === null ? undefined : pickOf(ranked.scores);\n return {\n kind: undecided.kind,\n capture_id: ranked?.capture_id ?? null,\n chat: null,\n clm: pick === undefined ? null : { id: pick.id, rightness: pick.rightness },\n took: 'chat',\n taken: null,\n };\n}\n\n// The report of one change, or none where no question went to the two\n// systems: nothing was captured, and there is nothing to grade.\nfunction reportOf(id: string, trail: Trail, applied: string | null, asked: boolean) {\n const questions = [\n ...trail.decisions.map(questionOf),\n ...(trail.undecided === undefined ? [] : [undecidedOf(trail.undecided)]),\n ];\n return questions.some((question) => question.took !== 'named')\n ? { id, surface: 'canvas' as const, questions, applied, asked }\n : undefined;\n}\n\n// Applies the changes in order, each against the state the one before it\n// produced. `text` says per change what was applied or why nothing was, and\n// `applied` holds the record of each change that was applied, in order.\n//\n// One call is one request: a later change of the call is part of what the\n// developer asked for, not an outcome of an earlier one. So each earlier\n// record follows its instance through every later change, and every record's\n// `after` is read from the canvas the whole call left, which is the first\n// frame the outcome observer folds it over. The record keeps the names the\n// call left, so the fold can follow them; the report says them with every\n// value of the call the canvas did not name when the change was ranked\n// withheld. Each change's decision is reported once the call is done,\n// through the transport, where there is one. Every apply runs through `own`.\nexport async function applyChanges(\n ports: CanvasToolPorts,\n changes: readonly Change[],\n own: OwnApply = asItIs,\n): Promise<{ text: string; applied: ChangeRecord[] }> {\n const call = changes.flatMap((change) => change.values);\n const client = ports.transport === undefined ? undefined : rankingClient(ports.transport);\n const lines: string[] = [];\n let applied: { record: ChangeRecord; withheld: readonly unknown[]; trail: Trail }[] = [];\n const reports: DecisionReport[] = [];\n let last: CanvasReading | undefined;\n for (const [index, change] of changes.entries()) {\n const trail: Trail = { decisions: [], notes: [] };\n const outcome = await runChange(ports, own, change, call, trail);\n lines.push(\n ...outcomeLines(index + 1, outcome, trail),\n ...trail.notes.map((line) => ` ${line}`),\n );\n if (outcome.kind === 'applied') {\n const { canvas } = outcome;\n const before = last;\n applied = [\n ...(before === undefined\n ? []\n : applied.map((each) => ({ ...each, record: follow(each.record, before, canvas) }))),\n { record: outcome.record, withheld: outcome.withheld, trail },\n ];\n last = canvas;\n } else if (outcome.kind !== 'unobserved') {\n const report = reportOf(crypto.randomUUID(), trail, null, outcome.kind === 'asked');\n if (report !== undefined) reports.push(report);\n }\n }\n const left = last;\n const records =\n left === undefined\n ? []\n : applied.map(({ record, withheld, trail }) => {\n const settled = { ...record, after: targetState(left, record) };\n const report = reportOf(record.id, trail, appliedText(settled, withheld), false);\n if (report !== undefined) reports.push(report);\n return { ...settled, reported: report !== undefined && client !== undefined };\n });\n if (client !== undefined) await Promise.all(reports.map((report) => client.decision(report)));\n return { text: lines.join('\\n'), applied: records };\n}\n\n// What a change did, in the report's words: what it addressed and its state\n// before and after, with every value of the call the canvas did not name\n// when the change was ranked withheld.\nfunction appliedText(record: ChangeRecord, withheld: readonly unknown[]): string {\n return withhold(\n `${renderTarget(record.target)}: ${renderState(record.before)} → ${renderState(record.after)}`,\n withheld,\n );\n}\n","// One command run to its end through the `commands` port, and the documents\n// a model reads of the three commands the tools run: each trimmed to what a\n// model needs to answer the developer.\nimport {\n type ArgsOf,\n type BoundPath,\n CommandExitError,\n type CommandFailure,\n type CommandsPort,\n type JsonOf,\n} from '@lace-cloud/canvas/engine';\nimport { moduleId } from './enumerate';\nimport { errorText } from './registration';\n\n// Why a command did not exit cleanly: `text` says it to a model, and\n// `failure` is the command's failure document when it wrote one (its\n// `reason`, its `message` and the fields the reason carries), which a host\n// branches on. A command that printed its result and then exited non-zero,\n// and a transport that broke, carry no document.\nexport type CommandEnd = {\n readonly text: string;\n readonly failure?: CommandFailure;\n};\n\n// What a command wrote before it ended, and why it ended when it did not\n// exit cleanly. A command can do both: `module validate` prints its report\n// and exits non-zero on a tree that is not in Lace style.\nexport type CommandOutput<P extends BoundPath> = {\n readonly documents: readonly JsonOf<P>[];\n readonly failed?: CommandEnd;\n};\n\n// A failure document in words: the reason by its wire spelling, or the\n// API's own code when the API decided it (as errorText says a refused\n// engine call), the command's own message, and the page the reason points\n// at when it names one.\nfunction failureText(path: BoundPath, failure: CommandFailure): string {\n const see = failure.url === undefined ? '' : `; see ${failure.url}`;\n const why = failure.apiCode ?? failure.reason;\n return `lace ${path} failed (reason ${why}): ${failure.message}${see}`;\n}\n\nfunction commandEnd(path: BoundPath, error: unknown): CommandEnd {\n if (!(error instanceof CommandExitError)) {\n return { text: `lace ${path} did not finish cleanly (${errorText(error)})` };\n }\n if (error.failure !== undefined) {\n return { text: failureText(path, error.failure), failure: error.failure };\n }\n return {\n text: `lace ${path} did not finish cleanly (exit ${error.code}: ${error.stderrTail})`,\n };\n}\n\nexport async function runCommand<P extends BoundPath>(\n commands: CommandsPort,\n path: P,\n args: ArgsOf<P>,\n): Promise<CommandOutput<P>> {\n const documents: JsonOf<P>[] = [];\n try {\n for await (const document of commands.invoke(path, args, new AbortController().signal).events) {\n documents.push(document);\n }\n } catch (error) {\n return { documents, failed: commandEnd(path, error) };\n }\n return { documents };\n}\n\n// A run as a tool result's text: each document through its trim, then why\n// the command did not exit cleanly.\nexport function commandText<P extends BoundPath>(\n run: CommandOutput<P>,\n trim: (document: JsonOf<P>) => unknown,\n): string {\n return [\n ...run.documents.map((document) => JSON.stringify(trim(document))),\n ...(run.failed === undefined ? [] : [run.failed.text]),\n ].join('\\n');\n}\n\nexport function trimValidate(report: JsonOf<'module validate'>): unknown {\n return {\n verdict: report.verdict,\n exitClass: report.exitClass,\n diagnostics: report.diagnostics,\n residuals: report.residuals?.map(({ construct, subject, file, line, guidance }) => ({\n construct,\n subject,\n file,\n line,\n guidance,\n })),\n terraform: report.terraform,\n };\n}\n\nexport function trimRegistryList(list: JsonOf<'registry list'>): unknown {\n return {\n modules: list.items.map((row) => ({\n module: moduleId(row),\n version: row.version,\n name: row.displayName,\n description: row.description,\n system: row.system,\n categories: row.categories,\n })),\n truncated: list.truncated,\n };\n}\n\nexport function trimRegistryDescribe(described: JsonOf<'registry describe'>): unknown {\n return {\n module: moduleId(described),\n version: described.version,\n source: described.source,\n verdict: described.verdict,\n inputs: described.interface.inputs,\n outputs: described.interface.outputs,\n };\n}\n","// The one enumeration: what the canvas offers for each decision a change\n// needs. `readCanvas` is the only fold over the Bundle in this package, and\n// it folds through proto's projection (`projectCanvasView`), inspection\n// (`deriveNodeConfig`) and instance resolution (`resolveInstance`) alone; every candidate list below, and the canvas\n// renderer, read its result. Whether an input is sensitive is the callee's\n// own mark in the Bundle (`InputDef.sensitive` on its interface), read by\n// the module key the projection names. A candidate carries the prose the\n// ranking scores and the references a request can name it by.\nimport type { CanvasSource, JsonOf, WiringCandidate } from '@lace-cloud/canvas/engine';\nimport {\n deriveNodeConfig,\n projectCanvasView,\n type RenderEdge,\n type RenderInput,\n type RenderOutput,\n resolveInstance,\n} from '@lace-cloud/proto';\nimport {\n type Candidate,\n type CandidateFacts,\n connectionId,\n type InputState,\n type InstanceRole,\n type PinFacts,\n pinRef,\n type Reading,\n renderCandidate,\n} from '../../questions';\n\n// An instance's input as the inspection derives it (its binding's mode and\n// content), with the mark the callee's interface puts on it.\nexport type CanvasInput = RenderInput & { readonly sensitive: boolean };\n\n// One instance on the canvas: a module call, or a group (a call whose module\n// has calls of its own). `id` is its canvas path, unique on the canvas;\n// `name` is its id inside `scope`, the module key of the module that owns\n// it, which is how an action addresses it.\nexport type CanvasInstance = {\n readonly id: string;\n readonly name: string;\n readonly scope: string;\n readonly module: string;\n readonly inputs: readonly CanvasInput[];\n readonly outputs: readonly RenderOutput[];\n};\n\nexport type CanvasGroup = {\n readonly id: string;\n readonly members: readonly string[];\n};\n\nexport type CanvasReading = {\n readonly module: string;\n // The entry module's key: the scope a placed module lands in.\n readonly entry: string;\n readonly instances: readonly CanvasInstance[];\n readonly wires: readonly RenderEdge[];\n readonly groups: readonly CanvasGroup[];\n};\n\nexport function readCanvas(source: CanvasSource): CanvasReading {\n const { bundle } = source;\n const view = projectCanvasView(bundle, undefined, {\n canUndo: source.canUndo,\n canRedo: source.canRedo,\n unsaved: source.unsaved,\n });\n const calls = [...view.nodes, ...view.groups];\n const instances = calls.flatMap((call): CanvasInstance[] => {\n const owner = resolveInstance(bundle, call.id);\n const config = deriveNodeConfig(bundle, call.id);\n if (owner === null || config === null || call.module_key === undefined) return [];\n const declared = bundle.modules[call.module_key]?.interface?.inputs ?? [];\n const sensitive = new Set(declared.filter((def) => def.sensitive).map((def) => def.name));\n return [\n {\n id: call.id,\n name: owner.child.id,\n scope: owner.scopeKey,\n module: call.module_key,\n inputs: config.inputs.map((input) => ({ ...input, sensitive: sensitive.has(input.name) })),\n outputs: config.outputs,\n },\n ];\n });\n return {\n module: view.module_name,\n entry: bundle.entry,\n instances,\n wires: view.edges,\n groups: view.groups.map((group) => ({ id: group.id, members: group.node_ids })),\n };\n}\n\n// The names a canvas holds: each instance's canvas path and its name in its\n// scope, the keys of its module and of its scope, and its inputs' and\n// outputs' names. Every candidate the lists below build is named by these,\n// so a value equal to one is a canvas fact the ranking already sees.\nexport function canvasNames(canvas: CanvasReading): ReadonlySet<string> {\n return new Set(\n canvas.instances.flatMap((instance) => [\n instance.id,\n instance.name,\n instance.module,\n instance.scope,\n ...instance.inputs.map((input) => input.name),\n ...instance.outputs.map((output) => output.name),\n ]),\n );\n}\n\n// A reference names a candidate when every part of it is a term of the\n// request; a candidate is named when any of its references is.\nexport type Ref = readonly string[];\n\n// One member of a decision's closed set: its facts and the candidate the\n// ranking scores (rendered from them by `renderCandidate`), the references a\n// request names it by, the slots a reading names it by, and the thing it is.\nexport type Option<T> = {\n readonly facts: CandidateFacts;\n readonly candidate: Candidate;\n readonly refs: readonly Ref[];\n readonly slots: Reading;\n readonly value: T;\n};\n\n// An option whose candidate is its facts, rendered.\nfunction offered<T>(\n facts: CandidateFacts,\n rest: Omit<Option<T>, 'facts' | 'candidate'>,\n): Option<T> {\n return { facts, candidate: renderCandidate(facts), ...rest };\n}\n\n// A pin as an instance's facts hold it: its name, and what the module says\n// it is where it says.\nconst pinFacts = (pins: readonly { readonly name: string; readonly description?: string }[]) =>\n pins.map(\n (pin): PinFacts =>\n pin.description ? { name: pin.name, description: pin.description } : { name: pin.name },\n );\n\n// The inputs of an instance a wire can end at: those no wire feeds yet.\nfunction unwired(instance: CanvasInstance): CanvasInput[] {\n return instance.inputs.filter((input) => input.mode !== 'wired');\n}\n\n// An instance's facts in the role its question offers it in: a target's\n// inputs are those no wire feeds.\nfunction instanceFacts(instance: CanvasInstance, role: InstanceRole): CandidateFacts {\n return {\n id: instance.id,\n kind: 'instance',\n role,\n module: instance.module,\n inputs: pinFacts(role === 'target' ? unwired(instance) : instance.inputs),\n outputs: pinFacts(instance.outputs),\n };\n}\n\nexport function operationOptions<T extends { readonly id: string }>(\n operations: readonly T[],\n): Option<T>[] {\n return operations.map((operation) =>\n offered(\n { id: operation.id, kind: 'operation' },\n { refs: [[operation.id]], slots: { operation: operation.id }, value: operation },\n ),\n );\n}\n\n// The instance a change addresses, named by its canvas path or by its own id.\n// Its prose holds its inputs and outputs with what the module says each is.\nexport function instanceOptions(instances: readonly CanvasInstance[]): Option<CanvasInstance>[] {\n return instances.map((instance) =>\n offered(instanceFacts(instance, 'instance'), {\n refs: [[instance.id], [instance.name]],\n slots: { instance: instance.id },\n value: instance,\n }),\n );\n}\n\n// The instance a wire starts at. A request names it in that role by one of\n// its outputs (`net.id`); its bare name says nothing of the direction.\nexport function sourceOptions(instances: readonly CanvasInstance[]): Option<CanvasInstance>[] {\n return instances\n .filter((instance) => instance.outputs.length > 0)\n .map((instance) =>\n offered(instanceFacts(instance, 'source'), {\n refs: instance.outputs.map((output) => [pinRef(instance.id, output.name)]),\n slots: { sourceInstance: instance.id },\n value: instance,\n }),\n );\n}\n\n// The instance a wire ends at: another instance of the source's scope with\n// an input no wire feeds, named in that role by one of those inputs\n// (`app.subnet`).\nexport function targetOptions(\n instances: readonly CanvasInstance[],\n source: CanvasInstance,\n): Option<CanvasInstance>[] {\n return instances\n .filter((instance) => instance.scope === source.scope && instance.id !== source.id)\n .filter((instance) => unwired(instance).length > 0)\n .map((instance) =>\n offered(instanceFacts(instance, 'target'), {\n refs: unwired(instance).map((input) => [pinRef(instance.id, input.name)]),\n slots: { targetInstance: instance.id },\n value: instance,\n }),\n );\n}\n\nconst INPUT_STATE: Record<RenderInput['mode'], InputState> = {\n empty: 'not set',\n literal: 'set',\n variable: 'set',\n expression: 'set',\n wired: 'wired',\n};\n\n// An instance's inputs, the whole set or the part of it an operation works\n// on. The facts say whether an input is set and never what it is set to.\nexport function inputOptions(\n instance: CanvasInstance,\n inputs: readonly CanvasInput[],\n): Option<CanvasInput>[] {\n return inputs.map((input) =>\n offered(\n {\n id: input.name,\n kind: 'input',\n instance: instance.id,\n module: instance.module,\n type: input.type,\n required: input.required,\n state: INPUT_STATE[input.mode],\n ...(input.description === undefined ? {} : { description: input.description }),\n },\n { refs: [[input.name]], slots: { input: input.name }, value: input },\n ),\n );\n}\n\n// Whether an entry is one change or several. Nothing in a request names\n// either: System Two's answer is `one` by construction (the tool asks one\n// entry per change), and System One reads the words.\nexport type Steps = 'one' | 'several';\n\nconst STEPS: readonly Steps[] = ['one', 'several'];\n\nexport function stepsOptions(): Option<Steps>[] {\n return STEPS.map((id) => offered({ id, kind: 'steps' }, { refs: [], slots: {}, value: id }));\n}\n\nexport type RegistryRow = JsonOf<'registry list'>['items'][number];\n\nexport function moduleId(row: { readonly author: string; readonly name: string }): string {\n return `${row.author}/${row.name}`;\n}\n\nexport function moduleOptions(rows: readonly RegistryRow[]): Option<RegistryRow>[] {\n return rows.map((row) =>\n offered(\n {\n id: moduleId(row),\n kind: 'module',\n displayName: row.displayName,\n description: row.description,\n system: row.system,\n categories: row.categories,\n },\n { refs: [[moduleId(row)], [row.name]], slots: { module: moduleId(row) }, value: row },\n ),\n );\n}\n\n// The output and the input one wire joins.\nexport type Connection = { readonly output: string; readonly input: string };\n\n// The output → input pairs a connect can wire between two instances: every\n// output of the source into every input of the target no wire feeds. The\n// engine's matcher scores the pairs it would choose among (`scored`, read for\n// these two instances), and each candidate's facts carry that score; a pair\n// the matcher leaves out (an optional input, a score of 0) is a candidate\n// all the same, with no score. A request names a pair by\n// naming both of its ends.\nexport function connectionOptions(\n source: CanvasInstance,\n target: CanvasInstance,\n scored: readonly WiringCandidate[],\n): Option<Connection>[] {\n const between = scored.filter(\n (each) => each.sourceInstance === source.name && each.targetInstance === target.name,\n );\n return source.outputs.flatMap((output) =>\n unwired(target).map((input) => {\n const pair = { output: output.name, input: input.name };\n const from = pinRef(source.id, pair.output);\n const to = pinRef(target.id, pair.input);\n const match = between.find(\n (each) => each.output === pair.output && each.input === pair.input,\n );\n return offered(\n {\n id: connectionId(from, to),\n kind: 'connection',\n source: source.id,\n output: pair.output,\n target: target.id,\n input: pair.input,\n ...(match === undefined ? {} : { score: match.score }),\n },\n { refs: [[from, to]], slots: pair, value: pair },\n );\n }),\n );\n}\n","// A tool registration whose handler always answers: a thrown error is the\n// call's result, said in the error's own words, never a rejection the host's\n// chat has to translate.\nimport { ConnectError, type Reason, reasonWire } from '@lace-cloud/canvas/engine';\nimport type { ToolHandler, ToolRegistration } from '../../contract/tool-registry';\nimport type { ToolResult, ToolSchema } from '../../contract/types';\n\n// The input a model sent is not the shape the tool's schema states.\nexport class InvalidInput extends Error {}\n\n// A reason in a result's words, spelled as a failure document spells it.\nexport function reasonText(reason: Reason): string {\n return `reason ${reasonWire(reason)}`;\n}\n\n// A thrown error in words: its message, and for a refused engine call the\n// reason it carries, or the API's own code when the API decided it.\nexport function errorText(error: unknown): string {\n if (error instanceof ConnectError) {\n const reason =\n error.apiCode === undefined ? reasonText(error.reason) : `reason ${error.apiCode}`;\n return `${error.message} (${reason})`;\n }\n return error instanceof Error ? error.message : String(error);\n}\n\n// `failed` makes the tool's own result of a failure: a tool whose result\n// carries more than text states what that part is when the call threw.\nexport function registrationOf<R extends ToolResult>(\n schema: ToolSchema,\n run: ToolHandler<R>,\n failed: (failure: ToolResult) => R,\n): ToolRegistration<R> {\n return {\n schema,\n async handler(input) {\n try {\n return await run(input);\n } catch (error) {\n return failed({ content: errorText(error), isError: true });\n }\n },\n };\n}\n\nexport function registration(schema: ToolSchema, run: ToolHandler): ToolRegistration {\n return registrationOf(schema, run, (failure) => failure);\n}\n\n// A tool that takes no input of its own. A host adds what only it knows\n// (which module root the call is for) beside the properties a tool states.\nexport const NO_INPUT = { type: 'object', properties: {}, additionalProperties: false };\n","// What happened next to an applied change, read from the session's frames\n// after it. `changeOutcomes` is a pure function of a change's record, the\n// frames and the revisions this package's own applies produced; the observer\n// composes it with the session's frames and reports each outcome once\n// through the ranking client. Every outcome is a move of the session's\n// state, and every such move reaches a subscriber as a frame (a command that\n// writes the tree reaches it as the frame of the re-derived IR), so the\n// frames are all it reads.\nimport { type CanvasSource, deepEqual } from '@lace-cloud/canvas/engine';\nimport type { ChangeOutcome, OutcomeReport } from '../../examples';\nimport { connectionId, pinRef } from '../../questions';\nimport { rankingClient, type Transport } from '../../ranking';\nimport type { ChangeRecord, ChangeState, InputBinding, OwnApply } from './change';\nimport { type CanvasInstance, type CanvasReading, readCanvas } from './enumerate';\n\nfunction instanceAt(\n canvas: CanvasReading,\n scope: string,\n name: string,\n): CanvasInstance | undefined {\n return canvas.instances.find((instance) => instance.scope === scope && instance.name === name);\n}\n\nexport function presenceOf(canvas: CanvasReading, scope: string, name: string): ChangeState {\n const instance = instanceAt(canvas, scope, name);\n return instance === undefined ? null : { instance: instance.name, module: instance.module };\n}\n\nexport function bindingOf(\n canvas: CanvasReading,\n scope: string,\n name: string,\n inputName: string,\n): ChangeState {\n const input = instanceAt(canvas, scope, name)?.inputs.find((each) => each.name === inputName);\n if (input === undefined) return null;\n if (input.sensitive) return { mode: input.mode };\n return {\n mode: input.mode,\n value: input.value,\n variable: input.variable,\n expression: input.expression,\n wiredSource: input.wired_source,\n };\n}\n\n// The instance a record's change lives at: the name the change left it with\n// (a rename's new name, a placement's own), else the name it addressed.\nfunction at({ target, after }: ChangeRecord): string {\n return after !== null && 'instance' in after ? after.instance : target.instance;\n}\n\n// The state on a canvas of what a record's change addressed: an input's\n// binding, or an instance's presence.\nexport function targetState(canvas: CanvasReading, record: ChangeRecord): ChangeState {\n const { scope, input } = record.target;\n return input === undefined\n ? presenceOf(canvas, scope, at(record))\n : bindingOf(canvas, scope, at(record), input);\n}\n\n// A record carried from one frame to the next. Grouping, ungrouping and a\n// rename move an instance without changing it, so when the instance the\n// record lives at was in `previous` and is gone from `frame`, the record\n// follows it: (i) to the one instance of its name and module in a scope where\n// `previous` held no instance of that name (a group, or an ungroup with no\n// collision); else (ii) to the one instance of its module in its scope that\n// `previous` did not hold (a rename). Rule (i) first, so grouping two\n// siblings of one module follows each by its name. Otherwise it stays, and\n// reads as gone.\nexport function follow(\n record: ChangeRecord,\n previous: CanvasReading,\n frame: CanvasReading,\n): ChangeRecord {\n const name = at(record);\n const { scope } = record.target;\n const was = instanceAt(previous, scope, name);\n if (was === undefined || instanceAt(frame, scope, name) !== undefined) return record;\n const fresh = frame.instances.filter(\n (each) =>\n each.module === was.module && instanceAt(previous, each.scope, each.name) === undefined,\n );\n const one = (found: readonly CanvasInstance[]) => (found.length === 1 ? found[0] : undefined);\n const moved =\n one(fresh.filter((each) => each.name === name)) ??\n one(fresh.filter((each) => each.scope === scope));\n if (moved === undefined) return record;\n const { after } = record;\n return {\n ...record,\n target: { ...record.target, scope: moved.scope, instance: moved.name },\n after: after !== null && 'instance' in after ? { ...after, instance: moved.name } : after,\n };\n}\n\n// What a change decided of a state: the answers of its closed questions as\n// the canvas holds them. An input's mode (the operation that writes it), with\n// the wire's source when wired (the pair), or an instance's module; `null`\n// where the target is gone (its instance or input). A new literal, another\n// variable or a new name is the developer's own value, not another\n// candidate, so it decides nothing.\nconst decided = (state: ChangeState): unknown =>\n state === null ? null : 'mode' in state ? [state.mode, state.wiredSource] : state.module;\n\n// Whether the change no longer stands as applied: an input's binding moved\n// in any part (a new value in the same mode included), an instance in what\n// was decided of it, since its name is the developer's.\nconst moved = (state: ChangeState, from: ChangeState): boolean =>\n state !== null && 'mode' in state\n ? !deepEqual(state, from)\n : !deepEqual(decided(state), decided(from));\n\n// The operation that writes an input's binding of each mode.\nconst OPERATION_OF_MODE: Partial<Record<InputBinding['mode'], string>> = {\n literal: 'set',\n variable: 'bind',\n empty: 'clear',\n wired: 'connect',\n};\n\n// The question of the record's decision a later edit of the target answers,\n// and the candidate it names, when one of the decision's questions holds it:\n// a binding in another mode names the operation that writes that mode; a\n// wire from another source names the connection. A new value in the same\n// mode is the developer's own and names nothing.\nfunction answered(\n record: ChangeRecord,\n state: ChangeState,\n canvas: CanvasReading,\n): Pick<OutcomeReport, 'question' | 'candidate'> {\n if (state === null || !('mode' in state) || record.target.input === undefined) return {};\n const name = (kind: string, candidate: string | undefined) => {\n const question = record.questions.findIndex(\n (each) =>\n each.kind === kind && candidate !== undefined && each.candidates.includes(candidate),\n );\n return question === -1 || candidate === undefined ? {} : { question, candidate };\n };\n const after = record.after;\n if (after !== null && 'mode' in after && after.mode !== state.mode) {\n return name('operation', OPERATION_OF_MODE[state.mode]);\n }\n if (state.mode !== 'wired' || state.wiredSource === undefined) return {};\n const [, source, output] = /^module\\.([^.]+)\\.(.+)$/.exec(state.wiredSource) ?? [];\n const { scope } = record.target;\n const from = instanceAt(canvas, scope, source ?? '');\n const to = instanceAt(canvas, scope, at(record));\n return from === undefined || to === undefined || output === undefined\n ? {}\n : name('connection', connectionId(pinRef(from.id, output), pinRef(to.id, record.target.input)));\n}\n\n// The outcomes of one frame, read against the frame before it (none for\n// the first frame given), the target's state on that frame (`was`; the\n// record's `after` for the first) and the revisions this package's own\n// applies produced (`own`). A frame that changes what the change decided,\n// to another answer than the change's own, is a hand edit when the package\n// did not produce it, the strongest label, and a change again when it did;\n// either names the question and candidate the edit answers when the fold can\n// tell. A frame that moves the target and changes nothing decided (a new\n// value in the same mode), or puts back the change's own answer, reaches no\n// outcome, and the change no longer stands as applied. While it stands, a\n// save is a frame that is saved after one that was not, a Generate one that\n// is generated after one that was not.\nfunction frameOutcomes(\n record: ChangeRecord,\n was: ChangeState,\n previous: CanvasSource | undefined,\n frame: CanvasSource,\n canvas: CanvasReading,\n own: ReadonlySet<number>,\n): OutcomeReport[] {\n const state = targetState(canvas, record);\n if (deepEqual(state, record.before)) return [{ event: 'reverted' }];\n const changes = (from: ChangeState) => !deepEqual(decided(state), decided(from));\n if (changes(was) && changes(record.after)) {\n const event = own.has(frame.revision) ? 'changed_again' : 'hand_edited';\n return [{ event, ...answered(record, state, canvas) }];\n }\n if (moved(state, record.after)) return [];\n const saved: OutcomeReport[] =\n previous?.unsaved === true && !frame.unsaved ? [{ event: 'saved' }] : [];\n const generated: OutcomeReport[] =\n previous?.ungenerated === true && !frame.ungenerated ? [{ event: 'generated' }] : [];\n return [...saved, ...generated];\n}\n\n// The outcomes a change reached over `frames`, each kind of event once as\n// first reached, in that order, and its record carried to the last frame. `frames` runs\n// from a frame the session delivered once the change was applied (its own,\n// or a later one) to the latest; `own` is every revision this package's\n// applies produced, the record's own by default. A frame's outcomes depend\n// on it, the frame before it and the record carried to it alone, so an\n// observer folds a session frame by frame: each new frame with the one it\n// last read and the record the fold last returned.\nexport function changeOutcomes(\n record: ChangeRecord,\n frames: readonly CanvasSource[],\n own: ReadonlySet<number> = new Set(record.revision === undefined ? [] : [record.revision]),\n): { readonly record: ChangeRecord; readonly outcomes: OutcomeReport[] } {\n const canvases = frames.map(readCanvas);\n const reached = new Map<ChangeOutcome, OutcomeReport>();\n let carried = record;\n frames.forEach((frame, index) => {\n const was = index > 0 ? targetState(canvases[index - 1], carried) : record.after;\n if (index > 0) carried = follow(carried, canvases[index - 1], canvases[index]);\n for (const outcome of frameOutcomes(\n carried,\n was,\n frames[index - 1],\n frame,\n canvases[index],\n own,\n )) {\n if (!reached.has(outcome.event)) reached.set(outcome.event, outcome);\n }\n });\n return { record: carried, outcomes: [...reached.values()] };\n}\n\n// The observer the canvas tool set composes with its session where it has a\n// transport: it reads the session frame by frame, follows the records of\n// each change-tool result whose decision was reported, folds each record\n// through `changeOutcomes` and reports each outcome once per record through\n// the transport. It is the one owner of the package's own revisions: the\n// change tool runs every apply through `own`, frames that arrive while an\n// apply is in flight are held until it resolves, and a held frame at the\n// revision it returned is the package's own, whether or not that change\n// was reported; any other is read as usual.\nexport type OutcomeObserver = {\n // Runs one apply of the package's own.\n readonly own: OwnApply;\n // Follows the records of one change-tool result whose decision was\n // reported; the frame the call left is their reference state.\n readonly follow: (records: readonly ChangeRecord[]) => void;\n // Reads one frame of the session.\n readonly frame: (source: CanvasSource) => void;\n};\n\nexport function outcomeObserver(transport: Transport): OutcomeObserver {\n const client = rankingClient(transport);\n const followed = new Map<string, { record: ChangeRecord; reported: Set<ChangeOutcome> }>();\n const own = new Set<number>();\n let previous: CanvasSource | undefined;\n // The package's applies in flight, the revisions those that resolved\n // returned while another was still in flight, and the frames held meanwhile.\n let flying = 0;\n const returned = new Set<number>();\n let held: CanvasSource[] = [];\n // A report the API refuses or the transport drops is one failed call,\n // which nothing retries: the client's posts settle either way.\n const fold = (source: CanvasSource): void => {\n const frames = previous === undefined ? [source] : [previous, source];\n previous = source;\n for (const [id, each] of followed) {\n const { record, outcomes } = changeOutcomes(each.record, frames, own);\n followed.set(id, { record, reported: each.reported });\n for (const outcome of outcomes.filter(({ event }) => !each.reported.has(event))) {\n each.reported.add(outcome.event);\n void client.outcome(id, outcome);\n }\n }\n };\n const landed = (revision: number | undefined): void => {\n flying -= 1;\n if (revision !== undefined) returned.add(revision);\n if (flying > 0) return;\n const frames = held;\n held = [];\n for (const frame of frames) {\n if (returned.has(frame.revision)) own.add(frame.revision);\n fold(frame);\n }\n returned.clear();\n };\n return {\n async own(apply) {\n flying += 1;\n let revision: number | undefined;\n try {\n const result = await apply();\n revision = result.success ? result.revision : undefined;\n return result;\n } finally {\n landed(revision);\n }\n },\n follow(records) {\n for (const record of records.filter((each) => each.reported)) {\n followed.set(record.id, { record, reported: new Set() });\n }\n },\n frame(source) {\n if (flying > 0) held.push(source);\n else fold(source);\n },\n };\n}\n","// The ports the tool sets take. A tool set is a function from its ports to\n// its registrations, so its capability is which ports it was given: a host\n// with no session cannot construct the canvas tools, one with a `commands`\n// port alone constructs the module tools, and one with no `transport`\n// constructs canvas tools that compose System Two alone and report nothing.\nimport type {\n ApplyUnobservedError,\n CanvasSource,\n CommandsPort,\n EditorPort,\n SourceEnd,\n SourcePort,\n} from '@lace-cloud/canvas/engine';\nimport type { Transport } from '../../ranking';\n\n// What the canvas tools do to a session: the mapping's own editor, without\n// conflict resolution, which the tools cannot reach since the canvas\n// confirms it. `apply` resolves once the source has delivered the state its\n// batch produced, so a read of the source after it sees that batch, and\n// `wiringCandidates` reads the engine matcher's scored pairs, the one\n// matching rule a canvas drag uses too.\nexport type CanvasEditor = Pick<EditorPort, 'apply' | 'save' | 'generate' | 'wiringCandidates'>;\n\nexport type CanvasToolPorts = {\n readonly source: SourcePort;\n readonly editor: CanvasEditor;\n readonly commands: CommandsPort;\n readonly transport?: Transport;\n};\n\nexport type ModuleToolPorts = {\n readonly commands: CommandsPort;\n};\n\n// How a session's stream ended, in a result's words: its kind, and what\n// failed it when it failed.\nexport function endText(end: ApplyUnobservedError['end']): string {\n return end.kind === 'failed' ? `failed: ${end.error.message}` : end.kind;\n}\n\nfunction endError(end: SourceEnd): Error {\n return end.kind === 'failed' ? end.error : new Error('the authoring session is closed');\n}\n\n// The source's latest frame: a source replays it to a subscriber that joins\n// late, and replays its end the same way when it has no frame to give.\nexport function latest(source: SourcePort): Promise<CanvasSource> {\n let unsubscribe = (): void => {};\n const frame = new Promise<CanvasSource>((resolve, reject) => {\n unsubscribe = source.subscribe(resolve, (end) => reject(endError(end)));\n });\n return frame.finally(() => unsubscribe());\n}\n","// The canvas as a model reads it, and what a change addressed and its state\n// in words. Pure functions of their arguments: every tool's result ends with\n// `renderCanvas` of the session's latest frame, so each call corrects the\n// model's picture of the canvas.\nimport type { CanvasSource } from '@lace-cloud/canvas/engine';\nimport { callText, type Diagnostic } from '@lace-cloud/proto';\nimport { VALUE_PLACEHOLDER } from '../../questions';\nimport type { ChangeState, ChangeTarget } from './change';\nimport { type CanvasInput, type CanvasInstance, readCanvas } from './enumerate';\n\nfunction inputText(input: CanvasInput): string {\n if (input.mode === 'empty') {\n return `${input.name} (${input.required ? 'required, ' : ''}not set)`;\n }\n if (input.mode === 'wired') return `${input.name} (wired)`;\n if (input.sensitive) return `${input.name} (sensitive, value withheld)`;\n const shown = {\n literal: JSON.stringify(input.value),\n variable: `var.${input.variable}`,\n expression: `${input.expression}`,\n };\n return `${input.name} = ${shown[input.mode]}`;\n}\n\nfunction instanceLines(instance: CanvasInstance): string[] {\n return [\n `- ${instance.id}: module ${instance.module}`,\n ` inputs: [${instance.inputs.map(inputText).join('; ')}]`,\n ` outputs: [${instance.outputs.map((output) => output.name).join(', ')}]`,\n ];\n}\n\nfunction unsetRequired(instance: CanvasInstance): string[] {\n return instance.inputs\n .filter((input) => input.required && input.mode === 'empty')\n .map((input) => `- ${instance.id}.${input.name}`);\n}\n\nfunction diagnosticLine(diagnostic: Diagnostic): string {\n const where = [\n ['instance', diagnostic.instance_id],\n ['input', diagnostic.input_name],\n ['address', diagnostic.address],\n ['file', diagnostic.file],\n ['line', diagnostic.line],\n ]\n .filter(([, value]) => value !== undefined)\n .map(([label, value]) => `${label} ${value}`);\n return `- ${[`${diagnostic.severity}: ${diagnostic.message}`, ...where].join('; ')}`;\n}\n\nconst yesNo = (flag: boolean): string => (flag ? 'yes' : 'no');\n\nfunction section(title: string, lines: readonly string[]): string[] {\n return [`${title} (${lines.length}):`, ...lines];\n}\n\n// The canvas of one frame: every instance with its module, its inputs (a\n// sensitive input's value withheld) and its outputs; the wires; the required\n// inputs that are not set; the groups; the engine's diagnostics; and the\n// session's standing.\nexport function renderCanvas(source: CanvasSource): string {\n const canvas = readCanvas(source);\n return [\n `Canvas of module ${canvas.module}`,\n `Instances (${canvas.instances.length}):`,\n ...canvas.instances.flatMap(instanceLines),\n ...section(\n 'Wires',\n canvas.wires.map(\n (wire) =>\n `- ${wire.source_output ? `${wire.source}.${wire.source_output}` : callText(wire.source)} → ${wire.target}.${wire.target_input}`,\n ),\n ),\n ...section('Required inputs not set', canvas.instances.flatMap(unsetRequired)),\n ...section(\n 'Groups',\n canvas.groups.map((group) => `- ${group.id}: ${group.members.join(', ')}`),\n ),\n ...section('Diagnostics', source.diagnostics.map(diagnosticLine)),\n [\n `Standing: unsaved edits: ${yesNo(source.unsaved)}`,\n `saved edits not generated to Terraform: ${yesNo(source.ungenerated)}`,\n `conflict with the Terraform on disk: ${yesNo(source.conflict !== null)}`,\n `Terraform refused, canvas locked: ${yesNo(source.sourceRefused)}`,\n ].join('; '),\n ].join('\\n');\n}\n\n// What a change addressed, in words: the instance, or the input of it, and\n// the module that owns the instance.\nexport function renderTarget(target: ChangeTarget): string {\n const pin = target.input === undefined ? target.instance : `${target.instance}.${target.input}`;\n return `${pin} in ${target.scope}`;\n}\n\n// What a change addressed, before or after it, holding no value: an input's\n// binding by its mode, its literal, variable or expression standing as the\n// placeholder (a wire is named by the output it comes from, a name on the\n// canvas), and an instance by its module alone, since its name after a\n// rename is what the developer gave.\nexport function renderState(state: ChangeState): string {\n if (state === null) return 'absent';\n if (!('mode' in state)) return `an instance of module ${state.module}`;\n const shown = {\n empty: 'not set',\n literal: `literal ${VALUE_PLACEHOLDER}`,\n variable: `variable ${VALUE_PLACEHOLDER}`,\n expression: `expression ${VALUE_PLACEHOLDER}`,\n wired: `wired from ${state.wiredSource}`,\n };\n return shown[state.mode];\n}\n","// Resolution of one decision, in order: the one candidate the request names\n// exactly; the one candidate it names when case is ignored; otherwise the two\n// systems read it. System Two's answer is the candidate its stated slot\n// names; System One's is its ranking's pick with a rightness, sure or not;\n// `compose` says whose stands (hybrid/compose.ts).\n//\n// A decision fills one slot of one change, so words that name several of\n// its candidates, each by a name of its own, name more than one change: the\n// pick is the one the model's reading names among them, else the first the\n// words name, and the others are kept for the result to say. Where a name is\n// shared by two candidates, or one named candidate lies inside another, the\n// names cannot tell one change from several, and the two systems read it.\n\nimport { type Composed, compose, pickOf, sure } from '../../hybrid';\nimport {\n type Candidate,\n type CandidateFacts,\n type DecisionKind,\n NONE_CANDIDATE_ID,\n RANK_CANDIDATES_MAX,\n type Reading,\n rankCandidates,\n statedSlots,\n} from '../../questions';\nimport type { Rank, Ranked } from '../../ranking';\nimport type { Option } from './enumerate';\n\n// The names a request holds, each with where it first stands in the\n// request: its words, its dotted references with every run of their parts\n// (`data.db.name` names `data.db` and `db.name` too), and its slashed\n// references (`author/name`). `folded` is the same in lower case, and\n// `words` the request's words in order, in lower case.\nexport type Terms = {\n readonly exact: ReadonlyMap<string, number>;\n readonly folded: ReadonlyMap<string, number>;\n readonly words: readonly string[];\n};\n\nconst WORD = /[A-Za-z0-9_-]+/g;\nconst DOTTED = /[A-Za-z0-9_-]+(?:\\.[A-Za-z0-9_-]+)+/g;\nconst SLASHED = /[A-Za-z0-9_-]+(?:\\/[A-Za-z0-9_-]+)+/g;\n\n// A name and the offset it stands at in the request.\ntype Found = { readonly term: string; readonly at: number };\n\nfunction found(text: string, pattern: RegExp): Found[] {\n return [...text.matchAll(pattern)].map((match) => ({ term: match[0], at: match.index }));\n}\n\n// Every run of a dotted reference's parts, each at the offset of its first\n// part.\nfunction runs({ term, at }: Found): Found[] {\n const parts = term.split('.');\n const starts = parts.map((_, index) => at + parts.slice(0, index).join('.').length + index);\n return parts.flatMap((_, start) =>\n parts.slice(start).map((_, length) => ({\n term: parts.slice(start, start + length + 1).join('.'),\n at: starts[start],\n })),\n );\n}\n\n// The registry modules a request refers to by reference: its `author/name`\n// words.\nexport function moduleReferences(text: string): string[] {\n return found(text, SLASHED).map((each) => each.term);\n}\n\n// Each name keyed as `key` spells it, at the first offset it stands at.\nfunction firstAt(names: readonly Found[], key: (term: string) => string): Map<string, number> {\n return names.reduce(\n (at, { term, at: offset }) => at.set(key(term), Math.min(offset, at.get(key(term)) ?? offset)),\n new Map<string, number>(),\n );\n}\n\nexport function termsOf(text: string): Terms {\n const names = [\n ...found(text, WORD),\n ...found(text, DOTTED).flatMap(runs),\n ...found(text, SLASHED),\n ];\n return {\n exact: firstAt(names, (term) => term),\n folded: firstAt(names, (term) => term.toLowerCase()),\n words: found(text, WORD).map(({ term }) => term.toLowerCase()),\n };\n}\n\n// The words a candidate covers: those of its id, its prose and its\n// references, each whole and in the parts `_` and `-` divide it into, in\n// lower case.\nfunction vocabulary(option: Option<unknown>): ReadonlySet<string> {\n const text = [option.candidate.id, option.candidate.text, ...option.refs.flat()].join(' ');\n return new Set(\n found(text.toLowerCase(), WORD).flatMap(({ term }) => [term, ...term.split(/[_-]/)]),\n );\n}\n\n// Words that name nothing: articles, prepositions, conjunctions, pronouns,\n// determiners and auxiliaries. A run of words holds them whoever covers them,\n// and a span does not count them, so \"the\" and \"to\" in a description name\n// nothing a request says.\nconst FUNCTION_WORDS: ReadonlySet<string> = new Set(\n 'a about after all am an and any are as at be been but by can could did do does each every for from had has have he her his i if in into is it its may me might must my no nor not of off on onto or our out over per shall she should so some than that the their them then these they this those to up upon us via was we were will with would you your'.split(\n ' ',\n ),\n);\n\n// The span of the word at `index` that `covered` holds: how many words other\n// than function words stand in the longest run of consecutive words around\n// it that `covered` holds or that are function words; 0 when `covered` does\n// not hold the word.\nfunction span(words: readonly string[], index: number, covered: ReadonlySet<string>): number {\n if (!covered.has(words[index])) return 0;\n const outside = (word: string) => !covered.has(word) && !FUNCTION_WORDS.has(word);\n const before = words.slice(0, index).reverse().findIndex(outside);\n const after = words.slice(index + 1).findIndex(outside);\n return words\n .slice(before === -1 ? 0 : index - before, after === -1 ? words.length : index + 1 + after)\n .filter((word) => !FUNCTION_WORDS.has(word)).length;\n}\n\n// What a decision is resolved against: the request as the ranking reads it,\n// the names it holds, System Two's statement as words and its reading (no\n// slot stated when it gave none), its alternative reading where it gave one,\n// and the rank that asks System One, none where no transport ranks.\nexport type Ask = {\n readonly request: string;\n readonly terms: Terms;\n readonly statement: string;\n readonly reading: Reading;\n readonly alternative?: { readonly statement: string; readonly reading: Reading };\n readonly rank?: Rank;\n};\n\n// System One's reading of a question: its reply, or why it gave none.\nexport type Ranking =\n | { readonly ranked: Ranked; readonly parts: boolean }\n | { readonly ranked: null; readonly failed: string };\n\n// One resolved decision. `how` says which step resolved it: one name\n// (`exact`, `unique`), several names (`first`, the first the words name, or\n// `agreed`, the one the model's reading names among them), or the two\n// systems (`clm`, System One sure; `chat`, System Two's own answer).\n// `offered` is how many candidates it was picked from and `candidates` the\n// ones its question holds: all of them, or, for a set larger than one\n// ranking holds, the part that holds the pick. `others` are the candidates\n// the words also name for it, which this change did not use. `chat` is\n// System Two's candidate, `ranking` System One's reply (none where the names\n// settled it or nothing ranked), `composed` whose answer stands and whether\n// the two differed, `over` the candidates System One ranked next after its\n// pick (none of these first, when `(none)` outranked it), and `alternative`\n// System One's answer to the model's alternative reading, with whether it\n// was sure of it and the slots that name it. `readings` holds, for every\n// candidate offered, the slots a reading names it by.\nexport type Decision<T> = {\n readonly kind: DecisionKind;\n readonly label: string;\n readonly option: Option<T>;\n readonly how: 'exact' | 'unique' | 'first' | 'agreed' | 'clm' | 'chat';\n readonly offered: number;\n readonly candidates: readonly Candidate[];\n // The facts `candidates` were rendered from, in their order.\n readonly facts: readonly CandidateFacts[];\n readonly others: readonly string[];\n readonly chat: string | null;\n readonly ranking: Ranking | null;\n readonly composed: Composed | null;\n readonly over: readonly string[];\n readonly alternative: {\n readonly id: string;\n readonly sure: boolean;\n readonly slots: Reading;\n } | null;\n readonly readings: readonly Reading[];\n};\n\n// The canvas has nothing to pick from for a decision the change needs.\nexport class NothingOffered extends Error {\n constructor(readonly label: string) {\n super(`the canvas offers no ${label} for this change`);\n }\n}\n\n// Neither system resolved the decision: System One was not sure (or gave no\n// ranking) and the model's reading names no candidate of it. The candidates\n// are kept so the result can list them, and the ranking so the report holds\n// it.\nexport class Undecided extends Error {\n constructor(\n readonly kind: DecisionKind,\n readonly label: string,\n readonly candidates: readonly Candidate[],\n readonly ranking: Ranking,\n ) {\n super(`the ${label} was not decided`);\n }\n}\n\n// How many of the candidates ranked after the pick a result names.\nconst NAMED_ALTERNATIVES = 3;\n\n// How a result names `(none)` where it outranked the pick.\nexport const NONE_OVER = 'none of these';\n\n// A candidate the request names: the references that name it, and the\n// offset of the first of them in the request.\ntype Hit<T> = {\n readonly option: Option<T>;\n readonly refs: readonly (readonly string[])[];\n readonly at: number;\n};\n\n// The candidates a request names, in the order the request first names\n// them. The longest span of the words names. A dotted reference names each\n// run of its parts, so `data.cache` holds the words of three candidates: the\n// instance `data.cache`, the group `data`, and any other instance whose own\n// id is `cache`; the longer reference is the one the words spell, so a\n// candidate named only by single words that are each a segment of another\n// named candidate's dotted reference is not named. Likewise a single word\n// names nothing where, at each place it stands, another candidate's id,\n// prose or references cover a longer span of the request's words around it\n// than its own candidate's do, function words not counted: `admin` in \"the\n// orders database admin password\" is a word of the database's admin\n// password, not the instance `admin`, while `cluster` in \"upgrade the\n// cluster to Kubernetes\" names the instance `cluster`.\nfunction named<T>(\n options: readonly Option<T>[],\n { words }: Terms,\n terms: ReadonlyMap<string, number>,\n fold: (part: string) => string,\n): Hit<T>[] {\n const hits = options\n .map((option) => ({\n option,\n refs: option.refs\n .map((ref) => ref.map(fold))\n .filter((ref) => ref.every((part) => terms.has(part))),\n }))\n .filter((hit) => hit.refs.length > 0);\n const extended = (ref: readonly string[]): boolean =>\n ref.length === 1 &&\n hits.some((other) =>\n other.refs.some((longer) =>\n longer.some((part) => part !== ref[0] && part.split('.').includes(ref[0])),\n ),\n );\n const covers = new Map(options.map((option) => [option, vocabulary(option)]));\n const outspanned = (option: Option<T>, ref: readonly string[]): boolean => {\n const word = ref[0].toLowerCase();\n const places = words.flatMap((each, index) => (each === word ? [index] : []));\n const own = covers.get(option) ?? new Set<string>();\n return (\n ref.length === 1 &&\n !/[./]/.test(word) &&\n places.length > 0 &&\n places.every((index) =>\n options.some(\n (other) =>\n other !== option &&\n span(words, index, covers.get(other) ?? new Set()) > span(words, index, own),\n ),\n )\n );\n };\n const at = (ref: readonly string[]): number =>\n Math.min(...ref.map((part) => terms.get(part) ?? Number.POSITIVE_INFINITY));\n return hits\n .map((hit) => ({\n ...hit,\n refs: hit.refs.filter((ref) => !extended(ref) && !outspanned(hit.option, ref)),\n }))\n .filter((hit) => hit.refs.length > 0)\n .map((hit) => ({ ...hit, at: Math.min(...hit.refs.map(at)) }))\n .sort((a, b) => a.at - b.at);\n}\n\n// Whether the names tell the candidates they name apart, so each is a\n// candidate of its own: every one is named by a reference that names no\n// other, and none lies inside another (its id extends the other's by a\n// dotted part, as an instance's canvas path extends its group's).\nfunction apart<T>(hits: readonly Hit<T>[]): boolean {\n const key = (ref: readonly string[]) => ref.join(' ');\n return hits.every((hit) => {\n const others = hits.filter((other) => other !== hit);\n const own = hit.refs.some(\n (ref) => !others.some((other) => other.refs.some((each) => key(each) === key(ref))),\n );\n const inside = others.some((other) =>\n hit.option.candidate.id.startsWith(`${other.option.candidate.id}.`),\n );\n return own && !inside;\n });\n}\n\nconst NAME_STEPS = [\n {\n how: 'exact',\n hits: <T>(options: readonly Option<T>[], terms: Terms) =>\n named(options, terms, terms.exact, (part) => part),\n },\n {\n how: 'unique',\n hits: <T>(options: readonly Option<T>[], terms: Terms) =>\n named(options, terms, terms.folded, (part) => part.toLowerCase()),\n },\n] as const;\n\n// The candidates a reading names: those whose every slot the reading states\n// with the same name.\nexport function read<T>(options: readonly Option<T>[], reading: Reading): Option<T>[] {\n return options.filter((option) =>\n statedSlots(option.slots).every((slot) => reading[slot] === option.slots[slot]),\n );\n}\n\n// System Two's answer to a question: the one candidate its reading names,\n// or none.\nfunction answerOf<T>(options: readonly Option<T>[], reading: Reading): Option<T> | undefined {\n const named = read(options, reading);\n return named.length === 1 ? named[0] : undefined;\n}\n\n// The most real candidates one rank call carries: one place is `(none)`'s.\nconst PART = RANK_CANDIDATES_MAX - 1;\n\n// A set in parts of at most one ranking's worth of candidates, in its order.\nfunction partsOf<T>(items: readonly T[]): T[][] {\n return Array.from({ length: Math.ceil(items.length / PART) }, (_, n) =>\n items.slice(n * PART, (n + 1) * PART),\n );\n}\n\n// The part of a set that holds the candidate `id`.\nfunction partHolding(candidates: readonly Candidate[], id: string): readonly Candidate[] {\n return partsOf(candidates).find((part) => part.some((each) => each.id === id)) ?? [];\n}\n\n// The facts of the options a set of candidates was rendered from, in the\n// set's order.\nfunction factsOf<T>(options: readonly Option<T>[], part: readonly Candidate[]): CandidateFacts[] {\n const byId = new Map(options.map((option) => [option.candidate.id, option.facts]));\n return part.flatMap((candidate) => byId.get(candidate.id) ?? []);\n}\n\n// One ranking of a part: the candidates one rank call carried, its reply,\n// and the candidate it picked.\ntype PartRanking = {\n readonly part: readonly Candidate[];\n readonly ranked: Ranked;\n readonly pick: Candidate;\n};\n\n// One rank call over a part, with the statement given.\nasync function rankPart(\n rank: Rank,\n request: string,\n statement: string,\n kind: DecisionKind,\n part: readonly Candidate[],\n): Promise<PartRanking> {\n const ranked = await rank({ request, statement, candidates: rankCandidates(kind, part) });\n const pick = part.find((candidate) => candidate.id === pickOf(ranked.scores)?.id);\n if (pick === undefined) throw new Error('the ranking names no candidate of the set');\n return { part, ranked, pick };\n}\n\n// Ranks a set with calls of at most RANK_CANDIDATES_MAX candidates each. A\n// set within the bound is one call. A larger one is ranked part by part and\n// the parts' picks are ranked together, so no candidate is left out of the\n// ranking and no call carries more than the route admits; the answer is the\n// ranking of the part that holds the final pick.\nasync function rankWithin(\n rank: Rank,\n request: string,\n statement: string,\n kind: DecisionKind,\n candidates: readonly Candidate[],\n): Promise<PartRanking> {\n const parts = partsOf(candidates);\n if (parts.length === 1) return rankPart(rank, request, statement, kind, candidates);\n const rounds: PartRanking[] = [];\n for (const part of parts) rounds.push(await rankWithin(rank, request, statement, kind, part));\n const final = await rankWithin(\n rank,\n request,\n statement,\n kind,\n rounds.map((round) => round.pick),\n );\n const holding = rounds.find((round) => round.pick.id === final.pick.id);\n if (holding === undefined) throw new Error('the ranking names no candidate of the set');\n return holding;\n}\n\n// System One's reading of a question under `statement`: its reply over the\n// whole set, or why it gave none. A pick made across parts was never scored\n// against the whole set, so its ranking says so and is never sure.\nasync function ranking(\n ask: Ask,\n statement: string,\n kind: DecisionKind,\n candidates: readonly Candidate[],\n): Promise<{ readonly ranking: Ranking; readonly part: readonly Candidate[] }> {\n if (ask.rank === undefined) {\n return { ranking: { ranked: null, failed: 'Lace did not rank' }, part: candidates };\n }\n try {\n const { part, ranked } = await rankWithin(ask.rank, ask.request, statement, kind, candidates);\n return { ranking: { ranked, parts: part.length < candidates.length }, part };\n } catch (error) {\n const failed = `Lace could not rank: ${error instanceof Error ? error.message : String(error)}`;\n return { ranking: { ranked: null, failed }, part: candidates };\n }\n}\n\n// System One's reply to the question as asked: what `compose` reads and a\n// report holds. None where it gave none, and none where it ranked the set in\n// parts: a pick made across parts was never scored against the whole set, so\n// it is never sure, and no one capture holds every candidate of the\n// question, so no capture is the question's.\nexport const asAsked = (ranking: Ranking | null): Ranked | null =>\n ranking === null || ranking.ranked === null || ranking.parts ? null : ranking.ranked;\n\n// The two systems read a question the names left open. `stated` is System\n// Two's answer where the form states it (an entry is one change) rather\n// than its reading.\nasync function twoSystems<T>(\n ask: Ask,\n kind: DecisionKind,\n label: string,\n options: readonly Option<T>[],\n stated?: T,\n): Promise<Decision<T>> {\n const candidates = options.map((option) => option.candidate);\n const readings = options.map((option) => option.slots);\n const chat =\n stated === undefined\n ? answerOf(options, ask.reading)\n : options.find((option) => option.value === stated);\n const read = await ranking(ask, ask.statement, kind, candidates);\n const composed = compose({\n kind,\n chat: chat?.candidate.id ?? null,\n ranked: asAsked(read.ranking),\n });\n const option = options.find((each) => each.candidate.id === composed.taken);\n if (option === undefined) throw new Undecided(kind, label, candidates, read.ranking);\n const alternative =\n ask.alternative === undefined\n ? null\n : await ranking(ask, ask.alternative.statement, kind, candidates).then(({ ranking }) => {\n const ranked = asAsked(ranking);\n const pick = ranked === null ? undefined : pickOf(ranked.scores);\n const named = options.find((each) => each.candidate.id === pick?.id);\n return pick === undefined || ranked === null || named === undefined\n ? null\n : { id: pick.id, sure: sure(ranked, kind), slots: named.slots };\n });\n const ranked = read.ranking.ranked;\n const others =\n ranked === null ? [] : ranked.scores.filter((score) => score.id !== NONE_CANDIDATE_ID);\n const part = composed.took === 'clm' ? read.part : partHolding(candidates, option.candidate.id);\n return {\n kind,\n label,\n option,\n how: composed.took,\n offered: candidates.length,\n candidates: part,\n facts: factsOf(options, part),\n others: [],\n chat: chat?.candidate.id ?? null,\n ranking: read.ranking,\n composed,\n over: [\n ...(ranked?.scores[0]?.id === NONE_CANDIDATE_ID ? [NONE_OVER] : []),\n ...others.slice(1, NAMED_ALTERNATIVES + 1).map((score) => score.id),\n ],\n alternative,\n readings,\n };\n}\n\n// The decision the words settle, when they do: the first name step that\n// names any candidate decides. One candidate is the pick. Several, each a\n// candidate of its own, are more than the slot holds: the pick is the one\n// the model's reading names among them, else the first named, and the rest\n// are the decision's `others`. Names that do not tell their candidates\n// apart settle nothing.\nfunction byName<T>(\n ask: Ask,\n kind: DecisionKind,\n label: string,\n options: readonly Option<T>[],\n): Decision<T> | undefined {\n const settled = (option: Option<T>, how: Decision<T>['how'], hits: readonly Hit<T>[]) => ({\n kind,\n label,\n option,\n how,\n offered: options.length,\n candidates: options.map((each) => each.candidate),\n facts: options.map((each) => each.facts),\n others: hits.filter((hit) => hit.option !== option).map((hit) => hit.option.candidate.id),\n chat: answerOf(options, ask.reading)?.candidate.id ?? null,\n ranking: null,\n composed: null,\n over: [],\n alternative: null,\n readings: options.map((each) => each.slots),\n });\n const step = NAME_STEPS.map((each) => ({\n how: each.how,\n hits: each.hits(options, ask.terms),\n })).find((each) => each.hits.length > 0);\n if (step === undefined) return undefined;\n if (step.hits.length === 1) return settled(step.hits[0].option, step.how, step.hits);\n if (!apart(step.hits)) return undefined;\n const agreed = read(\n step.hits.map((hit) => hit.option),\n ask.reading,\n );\n return agreed.length === 1\n ? settled(agreed[0], 'agreed', step.hits)\n : settled(step.hits[0].option, 'first', step.hits);\n}\n\nexport async function decide<T>(\n ask: Ask,\n kind: DecisionKind,\n label: string,\n options: readonly Option<T>[],\n stated?: T,\n): Promise<Decision<T>> {\n if (options.length === 0) throw new NothingOffered(label);\n return byName(ask, kind, label, options) ?? twoSystems(ask, kind, label, options, stated);\n}\n","// The module tools: the tools that run one command and need no session. A\n// host constructs them from a `commands` port alone. Each runs exactly one\n// command and returns its document trimmed to what a model needs, or why\n// the command failed.\nimport type { BoundPath, CommandFailure, JsonOf } from '@lace-cloud/canvas/engine';\nimport type { ToolRegistration } from '../../contract/tool-registry';\nimport type { ToolResult, ToolSchema } from '../../contract/types';\nimport {\n type CommandOutput,\n commandText,\n runCommand,\n trimRegistryDescribe,\n trimRegistryList,\n trimValidate,\n} from './commands';\nimport type { ModuleToolPorts } from './ports';\nimport { InvalidInput, NO_INPUT, registrationOf } from './registration';\n\nconst VALIDATE: ToolSchema = {\n name: 'lace_validate_module_terraform',\n title: 'Validate module Terraform',\n description:\n \"Runs `lace module validate` on a module's Terraform on disk, not on its canvas: canvas edits reach the Terraform after Save and Generate. Returns the verdict (whether the module is in Lace style) and the diagnostics.\",\n inputSchema: NO_INPUT,\n};\n\nconst SEARCH: ToolSchema = {\n name: 'lace_search_module_registry',\n title: 'Search module registry',\n description:\n 'Searches the Lace module registry. Returns each published module as `author/name` with its latest version, its description, its system and its categories.',\n inputSchema: {\n type: 'object',\n properties: {\n query: { type: 'string', description: 'Words to find in a module.' },\n system: { type: 'string', description: 'The system a module is for, such as `aws`.' },\n category: { type: 'string', description: 'A category a module is listed under.' },\n },\n additionalProperties: false,\n },\n};\n\nconst DESCRIBE: ToolSchema = {\n name: 'lace_describe_registry_module',\n title: 'Describe registry module',\n description:\n 'Describes one module of the Lace module registry before it is placed: every input with its type, default and whether it is required, every output, the version and the verdict of its certification.',\n inputSchema: {\n type: 'object',\n properties: {\n module: { type: 'string', description: 'The module, as `author/name`.' },\n version: { type: 'string', description: 'A published version. Left out: the latest.' },\n },\n required: ['module'],\n additionalProperties: false,\n },\n};\n\n// The module tools' schemas as data, in the order `moduleTools` returns its\n// registrations: validate, registry search, registry describe. A host that\n// generates a manifest of the tools reads these without constructing the\n// set, and the set registers exactly these.\nexport const moduleToolSchemas: readonly [ToolSchema, ToolSchema, ToolSchema] = [\n VALIDATE,\n SEARCH,\n DESCRIBE,\n];\n\n// A module tool's result: the text its model reads, and beside it the\n// failure document of a command that failed and wrote one, for the host:\n// `failure.reason` is what a host branches on, never the text.\nexport type ModuleToolResult = ToolResult & { readonly failure?: CommandFailure };\n\n// The module tools in their order: validate, registry search, registry\n// describe.\nexport type ModuleTools = readonly [\n ToolRegistration<ModuleToolResult>,\n ToolRegistration<ModuleToolResult>,\n ToolRegistration<ModuleToolResult>,\n];\n\nfunction said<P extends BoundPath>(\n run: CommandOutput<P>,\n trim: (document: JsonOf<P>) => unknown,\n): ModuleToolResult {\n const failure = run.failed?.failure;\n return {\n content: commandText(run, trim),\n isError: run.failed !== undefined,\n ...(failure === undefined ? {} : { failure }),\n };\n}\n\n// A call that threw before its command ran wrote no failure document.\nfunction moduleTool(\n schema: ToolSchema,\n run: (input: Record<string, unknown>) => Promise<ModuleToolResult>,\n): ToolRegistration<ModuleToolResult> {\n return registrationOf<ModuleToolResult>(schema, run, (failure) => failure);\n}\n\n// A property a schema states as optional text: its text when the model sent\n// text, and otherwise not an argument of the command at all.\nfunction text(value: unknown): string | undefined {\n return typeof value === 'string' ? value : undefined;\n}\n\nexport function moduleTools({ commands }: ModuleToolPorts): ModuleTools {\n const [validate, search, describe] = moduleToolSchemas;\n return [\n moduleTool(validate, async () =>\n said(await runCommand(commands, 'module validate', {}), trimValidate),\n ),\n moduleTool(search, async (input) =>\n said(\n await runCommand(commands, 'registry list', {\n axis: 'module',\n query: text(input.query),\n system: text(input.system),\n category: text(input.category),\n }),\n trimRegistryList,\n ),\n ),\n moduleTool(describe, async (input) => {\n const module = text(input.module);\n if (module === undefined) throw new InvalidInput('`module` is the module as `author/name`');\n return said(\n await runCommand(commands, 'registry describe', {\n artifact: `module/${module}`,\n version: text(input.version),\n }),\n trimRegistryDescribe,\n );\n }),\n ];\n}\n"],"mappings":";AAmCO,SAAS,qBAAmC;AACjD,QAAM,UAAU,oBAAI,IAA8B;AAElD,SAAO;AAAA,IACL,SAAS,QAAQ,SAAS;AACxB,cAAQ,IAAI,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;;;ACjDO,IAAM,sBAAsB;AAI5B,IAAM,yBAAyB;AAI/B,IAAM,gCAAgC;;;ACEtC,IAAM,iBAA0C;AAAA,EACrD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAQO,IAAM,oBAAoB;;;ACb1B,SAAS,OAAO,UAAkB,KAAqB;AAC5D,SAAO,GAAG,QAAQ,IAAI,GAAG;AAC3B;AAGO,SAAS,aAAa,MAAc,IAAoB;AAC7D,SAAO,GAAG,IAAI,WAAM,EAAE;AACxB;AAIO,IAAM,iBAAmD;AAAA,EAC9D,OAAO;AAAA,EACP,SAAS;AAAA,EACT,YAAY;AAAA,EACZ,KAAK;AAAA,EACL,MAAM;AAAA,EACN,OACE;AAAA,EACF,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,SAAS;AACX;AAIO,IAAM,aAA+C;AAAA,EAC1D,KAAK;AAAA,EACL,SAAS;AACX;AAMA,IAAM,YAAsE;AAAA,EAC1E,WAAW;AAAA,EACX,U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,OAAO;AAC3E;AAIA,SAAS,KAAK,OAAoC;AAChD,SAAO,OAAO,UAAU,WAAW,QAAQ;AAC7C;AAEO,SAAS,YAAY,EAAE,SAAS,GAAiC;AACtE,QAAM,CAAC,UAAU,QAAQ,QAAQ,IAAI;AACrC,SAAO;AAAA,IACL;AAAA,MAAW;AAAA,MAAU,YACnB,KAAK,MAAM,WAAW,UAAU,mBAAmB,CAAC,CAAC,GAAG,YAAY;AAAA,IACtE;AAAA,IACA;AAAA,MAAW;AAAA,MAAQ,OAAO,UACxB;AAAA,QACE,MAAM,WAAW,UAAU,iBAAiB;AAAA,UAC1C,MAAM;AAAA,UACN,OAAO,KAAK,MAAM,KAAK;AAAA,UACvB,QAAQ,KAAK,MAAM,MAAM;AAAA,UACzB,UAAU,KAAK,MAAM,QAAQ;AAAA,QAC/B,CAAC;AAAA,QACD;AAAA,MACF;AAAA,IACF;AAAA,IACA,WAAW,UAAU,OAAO,UAAU;AACpC,YAAM,SAAS,KAAK,MAAM,MAAM;AAChC,UAAI,WAAW,OAAW,OAAM,IAAI,aAAa,yCAAyC;AAC1F,aAAO;AAAA,QACL,MAAM,WAAW,UAAU,qBAAqB;AAAA,UAC9C,UAAU,UAAU,MAAM;AAAA,UAC1B,SAAS,KAAK,MAAM,OAAO;AAAA,QAC7B,CAAC;AAAA,QACD;AAAA,MACF;AAAA,IACF,CAAC;AAAA,EACH;AACF;","names":["text","text","names","at","ApplyUnobservedError","described","found","moved","text","at","_","names","ranking","named","option","read","ranked","isRecord","offered","instance","input","group","twoSystems","names","slot","ranking","read","moved","named","ApplyUnobservedError","said","text","DESCRIBE"]}
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 event says in a result. Its progress says nothing; it\n// closes with the files it wrote and the validate report of the written\n// tree, or with the engine's refusal by its reason.\nfunction generateSaid(event: GenerateEvent): Said[] {\n switch (event.type) {\n case 'progress':\n return [];\n case 'success':\n return [\n {\n text: [\n `Generated the Terraform. Files written: ${event.written.join(', ')}.`,\n `lace module validate on the written tree: ${JSON.stringify(trimValidate(event.validate))}`,\n ].join('\\n'),\n isError: false,\n },\n ];\n case 'error':\n return [\n {\n text: `Lace did not generate: ${event.message} (${reasonText(event.reason)}).`,\n isError: true,\n },\n ];\n }\n}\n\n// What a write the engine made says when the session's stream ended before\n// the frame that carries it: the canvas the result ends with cannot show it.\n// Any other failure is the call's own.\nfunction unobserved(error: unknown): Said {\n if (!(error instanceof ApplyUnobservedError)) throw error;\n return {\n text: `The session's stream ended (${endText(error.end)}) before the canvas showed this, so the canvas below is from before it.`,\n isError: false,\n };\n}\n\n// 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 CommandExitError,\n type CommandFailure,\n type CommandsPort,\n type JsonOf,\n} from '@lace-cloud/canvas/engine';\nimport { moduleId } from './enumerate';\nimport { errorText } from './registration';\n\n// Why a command did not exit cleanly: `text` says it to a model, and\n// `failure` is the command's failure document when it wrote one (its\n// `reason`, its `message` and the fields the reason carries), which a host\n// branches on. A command that printed its result and then exited non-zero,\n// and a transport that broke, carry no document.\nexport type CommandEnd = {\n readonly text: string;\n readonly failure?: CommandFailure;\n};\n\n// What a command wrote before it ended, and why it ended when it did not\n// exit cleanly. A command can do both: `module validate` prints its report\n// and exits non-zero on a tree that is not in Lace style.\nexport type CommandOutput<P extends BoundPath> = {\n readonly documents: readonly JsonOf<P>[];\n readonly failed?: CommandEnd;\n};\n\n// A failure document in words: the reason by its wire spelling, or the\n// API's own code when the API decided it (as errorText says a refused\n// engine call), the command's own message, and the page the reason points\n// at when it names one.\nfunction failureText(path: BoundPath, failure: CommandFailure): string {\n const see = failure.url === undefined ? '' : `; see ${failure.url}`;\n const why = failure.apiCode ?? failure.reason;\n return `lace ${path} failed (reason ${why}): ${failure.message}${see}`;\n}\n\nfunction commandEnd(path: BoundPath, error: unknown): CommandEnd {\n if (!(error instanceof CommandExitError)) {\n return { text: `lace ${path} did not finish cleanly (${errorText(error)})` };\n }\n if (error.failure !== undefined) {\n return { text: failureText(path, error.failure), failure: error.failure };\n }\n return {\n text: `lace ${path} did not finish cleanly (exit ${error.code}: ${error.stderrTail})`,\n };\n}\n\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// A thrown error in words: its message, and for a refused engine call the\n// reason it carries, or the API's own code when the API decided it.\nexport function errorText(error: unknown): string {\n if (error instanceof ConnectError) {\n const reason =\n error.apiCode === undefined ? reasonText(error.reason) : `reason ${error.apiCode}`;\n return `${error.message} (${reason})`;\n }\n return error instanceof Error ? error.message : String(error);\n}\n\n// 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,M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