@enhance-eng/enhance 0.1.160 → 0.1.165

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/main.mjs CHANGED
@@ -1,25 +1,27 @@
1
1
  #!/usr/bin/env node
2
- import { $n as wholeCanvasDocumentOutputSchema, At as hasCanvasReferenceScope, En as canvasTextRunsOf, Et as assertCanvasReferenceNodes, Fn as canvasAgentActivityPhaseSchema$1, Ft as appErrorSchema$1, It as completeScreenOutputSchema, Lt as createScreenOutputSchema, Mt as PartialBatchError, Nt as CliError, Ot as canvasReferenceRenderTarget, Pn as beginCanvasActivityOutputSchema, Pr as canvasSchema$1, Qn as saveCanvasDocumentOutputSchema, Rt as appendRecordingChunkOutputSchema, Tt as canvasEditsSchema, Vt as startRecordingOutputSchema, _ as OPTION_DESCRIPTIONS, _r as canvasLayoutMainAxisOf, a as toSharedCapabilities, c as toFailurePayload, dt as canvasUpdateHtmlCapabilityInputSchema, er as canvasOperationSchema$1, f as ProcessExitError, fr as canvasReadableSceneDocumentSchema, gr as canvasAxisStyleProperties, h as createCapabilityPolicyAdapter, hr as canvasAuthoredStyleDeclarations, in as withFixtureScreen, j as operationStatusInputSchema, jt as parseCanvasReference, kt as fromCanvasReference, lt as canvasReadInputSchema, m as createRouterShapeAdapter, mr as canvasAuthoredLayoutValueOf, n as withCommandName, nt as canvasRenderScopedInputSchema, o as createMcpCapabilityDiscoveryAdapter, ot as canvasRemoveCapabilityInputSchema, p as createCapabilityCatalogAdapter, r as toCanvasAuthoringResult, rn as emptyFixtureDocument, s as toExitCode, sr as canvasWorldBoundsSchema$1, t as withCommandInFailure, tn as createOrganisationOutputSchema, u as toPublishedExitTable, vr as canvasLayoutPriorityDeclarations, vt as canvasFindInputSchema, y as PROCEDURE_DESCRIPTIONS, zt as completeRecordingOutputSchema } from "./cli-output-identity.lib-DrfKWcGw.mjs";
3
- import { C as canvasRadialGradientSvg, D as canvasAngularGradientSvg, E as canvasDiamondGradientSvg, O as canvasColorCss, S as createAuthUseCase, T as canvasFilterListCss, _ as assertCanvasReferenceOperations, b as createCanvasActivityComposite, d as createRenderFileAdapter, f as readCanvasReferenceScene, g as createEditCanvasComposite, h as fromCapabilityReference, k as compareCanvasSortKeys, n as createHttpRemoteAdapter, o as createOauthLoopbackAdapter, p as createWriteHtmlCanvasComposite, r as readCliEnvironment, s as createCapabilityInvocationAdapter, t as createMutationKeyAdapter, v as sceneAtVersion, w as canvasLinearGradientSvg, x as createRenderCanvasComposite, y as createApplyCanvasComposite } from "./mutation-key.adapter-DFjvJyX6.mjs";
2
+ import { An as emptyFixtureDocument, Ar as wholeCanvasDocumentOutputSchema, C as PROCEDURE_DESCRIPTIONS, Ct as ROOT_FIELD, Dt as objectFieldNames, Et as isInputRecord, Ft as canvasReadInputSchema, Gr as emptyCanvasSceneDocument$1, Gt as hasCanvasReferenceScope, Jr as canvasAuthoredLayoutValueOf, Kt as parseCanvasReference, Lt as canvasUpdateHtmlCapabilityInputSchema, On as createOrganisationOutputSchema, Ot as quotedValue, Qr as canvasLayoutMainAxisOf, Rr as canvasWorldBoundsSchema$1, St as canvasEditsSchema, Tt as inputProblemSummary, Ut as canvasReferenceRenderTarget, V as operationStatusInputSchema, Vt as assertCanvasReferenceNodes, Wt as fromCanvasReference, Xr as canvasAxisStyleProperties, Yr as canvasAuthoredStyleDeclarations, Zt as currentNodeIdStep, _ as CANVAS_UPDATE_HTML_INPUT_EXAMPLE, _i as canvasSchema$1, a as createRouterShapeAdapter, an as CliError, b as ProcessExitError, c as toKebabCase, cn as appErrorSchema$1, ct as canvasRemoveCapabilityInputSchema, d as createMcpCapabilityDiscoveryAdapter, dn as appendRecordingChunkOutputSchema, dr as canvasAgentActivityPhaseSchema$1, ei as canvasLayoutPriorityDeclarations, er as canvasTextRunsOf, f as toExitCode, fn as completeRecordingOutputSchema, h as toPublishedExitTable, i as createLazyCapabilityCatalogAdapter, in as PartialBatchError, it as canvasRenderScopedInputSchema, jn as withFixtureScreen, jr as canvasOperationSchema$1, kr as saveCanvasDocumentOutputSchema, ln as completeScreenOutputSchema, mn as startRecordingOutputSchema, n as withCommandName, p as toFailurePayload, pt as canvasFindInputSchema, qt as readStoredCanvasScene, r as toCanvasAuthoringResult, t as withCommandInFailure, u as toSharedCapabilities, un as createScreenOutputSchema, ur as beginCanvasActivityOutputSchema, v as CAPABILITY_UUID_EXAMPLE, wt as inputProblemFields, x as OPTION_DESCRIPTIONS, y as createCapabilityPolicyAdapter } from "./cli-output-identity.lib-Z9ISwnoo.mjs";
3
+ import { A as canvasAngularGradientSvg, C as assertCanvasReferenceOperations, D as canvasLinearGradientSvg, E as canvasRadialGradientSvg, M as compareCanvasSortKeys, O as canvasFilterListCss, S as createCanvasActivityComposite, T as createAuthUseCase, _ as readCanvasReferenceScene, b as createEditCanvasComposite, c as createOauthLoopbackAdapter, d as isJsonValued, f as createCapabilityInvocationAdapter, g as createRenderFileAdapter, i as readCliEnvironment, j as canvasColorCss, k as canvasDiamondGradientSvg, l as toInputHelp, n as createMutationKeyAdapter, r as createHttpRemoteAdapter, s as readToolMachine, t as installZodMessages, u as withCapabilityNames, v as createWriteHtmlCanvasComposite, w as createRenderCanvasComposite, x as sceneAtVersion } from "./zod-messages.lib-BrqCGdLn.mjs";
4
4
  import { t as toCapabilityInventory } from "./capability-inventory.mapper-DyYXyVBJ.mjs";
5
- import { t as createFileCredentialAdapter } from "./file-credential.adapter-C78gc9OK.mjs";
5
+ import { t as createFileCredentialAdapter } from "./file-credential.adapter-CShGZcd5.mjs";
6
6
  import process from "node:process";
7
- import { Command } from "commander";
7
+ import { Command, Help, Option } from "commander";
8
8
  import { createCli, parseRouter } from "trpc-cli";
9
9
  import { z } from "zod";
10
10
  import { z as z$1 } from "zod/mini";
11
+ import { link, mkdir, open, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
12
+ import path from "node:path";
11
13
  import { hostname, tmpdir } from "node:os";
12
14
  import { createInterface } from "node:readline";
13
- import { chmodSync, createReadStream, existsSync, lstatSync, mkdirSync, openAsBlob, readFileSync, readdirSync, statSync, unlinkSync, writeFileSync } from "node:fs";
14
- import path from "node:path";
15
15
  import { createHash, randomUUID } from "node:crypto";
16
- import { link, mkdir, open, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
16
+ import { chmodSync, createReadStream, existsSync, lstatSync, mkdirSync, openAsBlob, readFileSync, readdirSync, realpathSync, statSync, unlinkSync, writeFileSync } from "node:fs";
17
17
  import { pipeline } from "node:stream/promises";
18
18
  import { channel } from "node:diagnostics_channel";
19
19
  import { proxify } from "trpc-cli/dist/proxify.js";
20
20
 
21
21
  //#region ../../packages/contract/src/canvas/canvas-font-family.lib.ts
22
22
  const GENERIC_FAMILIES = /* @__PURE__ */ new Set([
23
+ "-apple-system",
24
+ "blinkmacsystemfont",
23
25
  "cursive",
24
26
  "emoji",
25
27
  "fantasy",
@@ -65,10 +67,14 @@ const canvasTextDirectionDeclarations = (direction) => direction === void 0 ? {}
65
67
  ...direction !== "auto" && { direction },
66
68
  "unicode-bidi": direction === "auto" ? "plaintext" : "isolate"
67
69
  };
70
+ /** The fonts the canvas ships, by the plain name people write and the name of the bundled face. */
71
+ const CANVAS_BUNDLED_FONT_FAMILIES = {
72
+ Inter: "Inter Variable",
73
+ "JetBrains Mono": "JetBrains Mono Variable"
74
+ };
68
75
  const canvasTypographyFontFamily = (typography) => [.../* @__PURE__ */ new Set([
69
76
  typography.family,
70
- ...typography.family === "Inter" ? ["Inter Variable"] : [],
71
- ...typography.family === "JetBrains Mono" ? ["JetBrains Mono Variable"] : [],
77
+ ...Object.hasOwn(CANVAS_BUNDLED_FONT_FAMILIES, typography.family) ? [CANVAS_BUNDLED_FONT_FAMILIES[typography.family] ?? typography.family] : [],
72
78
  ...typography.fallbackFamilies
73
79
  ])].map((family) => canvasFontFamilyCss(family)).join(", ");
74
80
  /** Weight is the sole wght owner; the remaining axes never shadow the visible weight field. */
@@ -267,6 +273,65 @@ const createScreenFixtureComposite = (remote) => async (input) => {
267
273
  }
268
274
  };
269
275
 
276
+ //#endregion
277
+ //#region src/application/setup.use-case.ts
278
+ const nextOf = (input) => [
279
+ ...input.isSignedIn ? [] : ["The sign-in is not done. Run enhance auth login, then enhance setup again."],
280
+ ...input.notWritten.map(({ agent, file }) => `The skill for ${agent} could not be written to ${file}.`),
281
+ ...input.shared === null ? [] : [`No coding agent was found on this machine, so the skill is in ${input.shared.file}, which several agents read.`],
282
+ `Open your coding agent in your project and run the ${input.skill} skill.`
283
+ ];
284
+ const createSetupUseCase = (dependencies) => ({ run: async (input) => {
285
+ const { auth, skills } = dependencies;
286
+ const signIn = async () => {
287
+ if (input.token !== null) return auth.loginWithToken(input.token);
288
+ try {
289
+ return await auth.status();
290
+ } catch (error) {
291
+ if (!(error instanceof CliError) || error.code !== "UNAUTHORIZED") throw error;
292
+ }
293
+ return auth.loginWithBrowser({
294
+ label: input.label,
295
+ openBrowser: input.openBrowser,
296
+ onReady: input.onReady
297
+ });
298
+ };
299
+ const signed = await (async () => {
300
+ try {
301
+ return {
302
+ person: await signIn(),
303
+ problem: null
304
+ };
305
+ } catch (error) {
306
+ return {
307
+ person: null,
308
+ problem: error instanceof Error ? error.message : String(error)
309
+ };
310
+ }
311
+ })();
312
+ const skill = dependencies.skill();
313
+ const copied = await skills.write(skill);
314
+ return {
315
+ status: signed.person !== null && copied.notWritten.length === 0 ? "ready" : "incomplete",
316
+ signedIn: signed.person === null ? null : {
317
+ personId: signed.person.personId,
318
+ displayName: signed.person.displayName
319
+ },
320
+ signInProblem: signed.problem,
321
+ skill: {
322
+ name: skill.name,
323
+ written: copied.written,
324
+ notWritten: copied.notWritten
325
+ },
326
+ next: nextOf({
327
+ skill: skill.name,
328
+ isSignedIn: signed.person !== null,
329
+ shared: copied.isShared ? copied.written[0] ?? null : null,
330
+ notWritten: copied.notWritten
331
+ })
332
+ };
333
+ } });
334
+
270
335
  //#endregion
271
336
  //#region src/application/world-fixture.composite.ts
272
337
  const WORLD_FIXTURE_PROCEDURES = [
@@ -322,6 +387,83 @@ const createWorldFixtureComposite = (remote, createScreen) => async (input) => {
322
387
  }
323
388
  };
324
389
 
390
+ //#endregion
391
+ //#region src/infrastructure/agent-skill-folders.adapter.ts
392
+ /** Each coding agent's own folder in the home folder, and where it reads personal skills from. */
393
+ const AGENTS = [
394
+ {
395
+ agent: "Claude Code",
396
+ home: ".claude",
397
+ skills: ".claude/skills"
398
+ },
399
+ {
400
+ agent: "Codex",
401
+ home: ".codex",
402
+ skills: ".codex/skills"
403
+ },
404
+ {
405
+ agent: "Cursor",
406
+ home: ".cursor",
407
+ skills: ".cursor/skills"
408
+ },
409
+ {
410
+ agent: "OpenCode",
411
+ home: ".config/opencode",
412
+ skills: ".config/opencode/skills"
413
+ },
414
+ {
415
+ agent: "Gemini",
416
+ home: ".gemini",
417
+ skills: ".gemini/skills"
418
+ }
419
+ ];
420
+ /** The folder several agents read, used when none of the agents above is installed. */
421
+ const SHARED = {
422
+ agent: "the shared skills folder",
423
+ skills: ".agents/skills"
424
+ };
425
+ const isFolder = async (folder) => {
426
+ try {
427
+ return (await stat(folder)).isDirectory();
428
+ } catch {
429
+ return false;
430
+ }
431
+ };
432
+ const createAgentSkillFoldersAdapter = (homeDirectory) => ({ write: async (skill) => {
433
+ const found = (await Promise.all(AGENTS.map(async (entry) => await isFolder(path.join(homeDirectory, entry.home)) ? entry : null))).filter((entry) => entry !== null);
434
+ const targets = found.length === 0 ? [SHARED] : found;
435
+ const outcomes = await Promise.all(targets.map(async ({ agent, skills }) => {
436
+ const file = path.join(homeDirectory, skills, skill.name, "SKILL.md");
437
+ try {
438
+ await mkdir(path.dirname(file), { recursive: true });
439
+ await writeFile(file, skill.text);
440
+ return {
441
+ agent,
442
+ file,
443
+ reason: null
444
+ };
445
+ } catch (error) {
446
+ return {
447
+ agent,
448
+ file,
449
+ reason: error instanceof Error ? error.message : String(error)
450
+ };
451
+ }
452
+ }));
453
+ return {
454
+ written: outcomes.flatMap(({ agent, file, reason }) => reason === null ? [{
455
+ agent,
456
+ file
457
+ }] : []),
458
+ notWritten: outcomes.flatMap(({ agent, file, reason }) => reason === null ? [] : [{
459
+ agent,
460
+ file,
461
+ reason
462
+ }]),
463
+ isShared: found.length === 0
464
+ };
465
+ } });
466
+
325
467
  //#endregion
326
468
  //#region src/infrastructure/stdin-token.lib.ts
327
469
  const readToken = async (offered, command) => {
@@ -356,7 +498,9 @@ const readOptionalToken = async (offered) => {
356
498
 
357
499
  //#endregion
358
500
  //#region src/infrastructure/auth.program.ts
359
- const MAX_TOKEN_LABEL_CHARACTERS = 120;
501
+ const MAX_TOKEN_LABEL_CHARACTERS$1 = 120;
502
+ /** What a person, or an agent relaying to one, is told while the browser sign-in is open. */
503
+ const WAITING_FOR_BROWSER = "Sign in or sign up in the browser. This command carries on when you finish, however long that takes; Ctrl-C stops it.";
360
504
  const registerAuthProgram = (program, auth, output) => {
361
505
  const command = program.command("auth").description("Store and inspect the agent credential.");
362
506
  command.command("login").description("Authenticate in a browser, then store a revocable agent credential.").option("--token <token>", "Use an existing agent token instead of browser authentication.").option("--no-open", "Print the authorization URL without opening the browser.").action(async (options) => {
@@ -366,12 +510,13 @@ const registerAuthProgram = (program, auth, output) => {
366
510
  return;
367
511
  }
368
512
  output.result(await auth.loginWithBrowser({
369
- label: `CLI on ${hostname()}`.slice(0, MAX_TOKEN_LABEL_CHARACTERS),
513
+ label: `CLI on ${hostname()}`.slice(0, MAX_TOKEN_LABEL_CHARACTERS$1),
370
514
  openBrowser: options.open,
371
515
  onReady: (url) => {
372
516
  output.result({
373
517
  status: "waiting_for_browser",
374
- url
518
+ url,
519
+ waiting: WAITING_FOR_BROWSER
375
520
  });
376
521
  }
377
522
  }));
@@ -447,14 +592,11 @@ const selectAuthoringToken = (input, value, isComposite) => {
447
592
  const authoringMutationId = (input, purpose) => input.mutationKey.current("canvas.applyOperations", { purpose });
448
593
  const applyAuthoringOperations = async (input, options, purpose, operations) => {
449
594
  selectAuthoringToken(input, options.clientToken, false);
450
- const reference = parseCanvasReference(options.canvas);
451
- const baseVersion = authoringBaseVersion(options.baseVersion);
452
- if (hasCanvasReferenceScope(reference)) assertCanvasReferenceOperations(reference, await sceneAtVersion(input, reference.canvasId, baseVersion), operations);
453
- return createApplyCanvasComposite(input.remote).execute({
454
- canvasId: reference.canvasId,
595
+ return createEditCanvasComposite(input.remote).apply({
596
+ ...parseCanvasReference(options.canvas),
597
+ baseVersion: authoringBaseVersion(options.baseVersion),
455
598
  mutationId: authoringMutationId(input, purpose),
456
- baseVersion,
457
- operations: [...operations]
599
+ operations
458
600
  });
459
601
  };
460
602
  const applyAuthoringEdits = async (input, options, edits, idPrefix) => {
@@ -469,6 +611,54 @@ const applyAuthoringEdits = async (input, options, edits, idPrefix) => {
469
611
  });
470
612
  };
471
613
 
614
+ //#endregion
615
+ //#region src/application/input-refusal.use-case.ts
616
+ const MAX_NAMED_PATHS = 3;
617
+ const namedPaths = (fields) => {
618
+ const paths = Object.keys(fields).filter((field) => field !== ROOT_FIELD);
619
+ const roots = paths.filter((path) => paths.every((other) => !path.startsWith(`${other}.`)));
620
+ if (roots.length === 0) return "";
621
+ const shown = roots.slice(0, MAX_NAMED_PATHS).join(", ");
622
+ return roots.length <= MAX_NAMED_PATHS ? ` at ${shown}` : ` at ${shown} and ${String(roots.length - MAX_NAMED_PATHS)} more`;
623
+ };
624
+ /**
625
+ * The refusal of an input that failed its check: every problem with its field, what was expected
626
+ * and what was given.
627
+ */
628
+ const inputRefusal = (input) => {
629
+ const fields = inputProblemFields(input.error, input.checked);
630
+ return new CliError("BAD_REQUEST", `${input.subject} is invalid${namedPaths(fields)}.`, `${inputProblemSummary(fields)} ${input.help}`, fields);
631
+ };
632
+ const SPELLINGS = [
633
+ ["canvasRef", "canvasId"],
634
+ ["canvasId", "canvasRef"],
635
+ ["baseVersion", "expectedVersion"],
636
+ ["expectedVersion", "baseVersion"]
637
+ ];
638
+ const readAs = (given, name, other, subject) => {
639
+ const hasName = Object.hasOwn(given, name);
640
+ if (hasName && JSON.stringify(given[name]) !== JSON.stringify(given[other])) throw new CliError("BAD_REQUEST", `${subject} gives ${name} and ${other} different values.`, `Give ${name} alone; ${other} is another name for it.`, {
641
+ [name]: quotedValue(given[name]),
642
+ [other]: quotedValue(given[other])
643
+ });
644
+ return Object.fromEntries(Object.entries(given).flatMap(([key, held]) => {
645
+ if (key !== other) return [[key, held]];
646
+ return hasName ? [] : [[name, held]];
647
+ }));
648
+ };
649
+ /**
650
+ * Reads the other spelling of a canvas and of the version a write expects, where the command has
651
+ * one name and not the other. The schemas are strict and shared with hosted assistants, so the
652
+ * key is renamed here and the schema stays as it is.
653
+ */
654
+ const withAcceptedSpellings = (schema, value, subject) => {
655
+ const shapes = objectFieldNames(schema);
656
+ if (shapes === null || shapes.length === 0 || !isInputRecord(value) || Array.isArray(value)) return value;
657
+ let read = { ...value };
658
+ for (const [name, other] of SPELLINGS) if (shapes.every((names) => names.includes(name) && !names.includes(other)) && Object.hasOwn(read, other)) read = readAs(read, name, other, subject);
659
+ return read;
660
+ };
661
+
472
662
  //#endregion
473
663
  //#region src/infrastructure/canvas-authoring-input.lib.ts
474
664
  const canvasAuthoringInput = (value, option) => {
@@ -498,10 +688,15 @@ const decodedFrom = (value) => {
498
688
  const createCanvasOperationInputAdapter = (value) => {
499
689
  const decoded = decodedFrom(value);
500
690
  const parsed = operationBatchSchema.safeParse(decoded);
501
- if (!parsed.success) {
502
- const issue = parsed.error.issues[0];
503
- throw new CliError("BAD_REQUEST", `The canvas operation batch is invalid${issue === void 0 || issue.path.length === 0 ? "" : ` at ${issue.path.join(".")}`}.`, "Correct the named operation; run 'enhance canvas apply --help' for the supported vocabulary.");
504
- }
691
+ if (!parsed.success) throw inputRefusal({
692
+ subject: "The canvas operation batch",
693
+ error: parsed.error,
694
+ checked: {
695
+ schema: operationBatchSchema,
696
+ value: decoded
697
+ },
698
+ help: "Run 'enhance canvas apply --help' for the supported vocabulary."
699
+ });
505
700
  return parsed.data;
506
701
  };
507
702
 
@@ -523,17 +718,15 @@ const configureCanvasApply = (canvas, input) => {
523
718
  canvas.command("apply").description("Apply an atomic canvas edit batch and return its affected bounds.").summary("Apply edits and return affected bounds.").requiredOption("--canvas <url-or-id>", "Canvas URL or UUID to edit.").requiredOption("--base-version <integer>", "Exact version returned by canvas inspect or tree.").requiredOption("--operations <json-or-@path>", "JSON operation array inline, or @path to a JSON file.").option("--client-token <uuid>", "Stable UUID to reuse only when retrying this exact batch.").addHelpText("after", [
524
719
  "",
525
720
  "Supported operations: insertNode, insertText, insertPrototype, setText, editText, setBox, setLabel, setVisibility, setLocked, setConstraints, setStyles, setAppearance, setLayout, patchTypography, setTypography, patchAdditionalStyles, setAdditionalStyles, setProps, setParentage, move, remove.",
526
- "Use editText for revision-aware character or range changes. setText replaces the whole text and is rejected if it conflicts with a newer text edit.",
527
- "Example:",
528
- ` enhance canvas apply --canvas <url-or-id> --base-version 3 --operations '[{"op":"insertText","nodeId":"txt_summary","parentId":"root","text":"Checkout needs an address.","box":{"x":120,"y":594,"width":720,"height":80},"styles":{"font-size":24}}]'`
721
+ "Use editText for revision-aware character or range changes. setText replaces the whole text and is rejected if it conflicts with a newer text edit."
529
722
  ].join("\n")).action(async (options) => {
530
723
  selectMutationToken(input, options.clientToken);
531
724
  const reference = parseCanvasReference(options.canvas);
532
725
  const baseVersion = baseVersionFrom(options.baseVersion);
533
726
  const operations = createCanvasOperationInputAdapter(options.operations);
534
- if (hasCanvasReferenceScope(reference)) assertCanvasReferenceOperations(reference, await sceneAtVersion(input, reference.canvasId, baseVersion), operations);
727
+ if (hasCanvasReferenceScope(reference)) assertCanvasReferenceOperations(reference, await sceneAtVersion(input, reference.canvasId, baseVersion, "flag"), operations);
535
728
  const result = await input.invocation.invoke({
536
- capability: fromCapabilityReference(input.catalog(), "canvas.apply"),
729
+ capability: input.catalog.one("canvas.apply"),
537
730
  arguments: {
538
731
  canvasId: reference.canvasId,
539
732
  baseVersion,
@@ -609,18 +802,25 @@ const configureCanvasAuthoringActivity = (canvas, input) => {
609
802
  //#endregion
610
803
  //#region src/infrastructure/canvas-json-input.adapter.ts
611
804
  const createCanvasJsonInputAdapter = (value, schema, option) => {
612
- const decoded = (() => {
805
+ const read = withAcceptedSpellings(schema, (() => {
613
806
  try {
614
807
  return JSON.parse(canvasAuthoringInput(value, option));
615
808
  } catch (error) {
616
809
  if (error instanceof CliError) throw error;
617
810
  throw new CliError("BAD_REQUEST", `${option} must be valid JSON.`, `Pass inline JSON or @/absolute/path/to/input.json; run the command with --help.`);
618
811
  }
619
- })();
620
- const parsed = schema.safeParse(decoded);
812
+ })(), option);
813
+ const parsed = schema.safeParse(read);
621
814
  if (parsed.success) return parsed.data;
622
- const issue = parsed.error.issues[0];
623
- throw new CliError("BAD_REQUEST", `${option} is invalid${issue === void 0 || issue.path.length === 0 ? "" : ` at ${issue.path.join(".")}`}.`, issue?.message ?? "Correct the JSON shape and retry.");
815
+ throw inputRefusal({
816
+ subject: option,
817
+ error: parsed.error,
818
+ checked: {
819
+ schema,
820
+ value: read
821
+ },
822
+ help: "Run the command with --help for the whole input."
823
+ });
624
824
  };
625
825
 
626
826
  //#endregion
@@ -1018,7 +1218,7 @@ const computedCanvasNodeCss = (node, document) => ({
1018
1218
  const childrenOf = (document, parentId) => Object.entries(document.relationships).filter(([, relationship]) => relationship.parentId === parentId).toSorted(([leftId, left], [rightId, right]) => left.sortKey === right.sortKey ? leftId.localeCompare(rightId) : compareCanvasSortKeys(left.sortKey, right.sortKey)).map(([nodeId]) => nodeId);
1019
1219
  const requireNode = (document, nodeId) => {
1020
1220
  const node = document.nodes[nodeId];
1021
- if (node === void 0) throw new CliError("NOT_FOUND", `Canvas node ${nodeId} does not exist.`, "Run canvas tree and use a current stable node id.");
1221
+ if (node === void 0) throw new CliError("NOT_FOUND", `Canvas node ${nodeId} does not exist.`, currentNodeIdStep());
1022
1222
  return node;
1023
1223
  };
1024
1224
  const stringProperty = (node, property) => {
@@ -1139,7 +1339,7 @@ const canvasScene = async (input, canvasId) => {
1139
1339
  const held = wholeCanvasDocumentOutputSchema.parse(await input.remote.query("canvas.document.get", { canvasId }));
1140
1340
  return {
1141
1341
  held,
1142
- document: canvasReadableSceneDocumentSchema.parse(held.document)
1342
+ document: readStoredCanvasScene(held.document)
1143
1343
  };
1144
1344
  };
1145
1345
  const configureCanvasAuthoringSource = (canvas, input) => {
@@ -1174,12 +1374,62 @@ const configureCanvasAuthoringSource = (canvas, input) => {
1174
1374
  });
1175
1375
  };
1176
1376
 
1377
+ //#endregion
1378
+ //#region src/application/client-token.use-case.ts
1379
+ const REPEATABLE_CODES = /* @__PURE__ */ new Set(["INTERNAL", "RATE_LIMITED"]);
1380
+ const SAYS_SAME_TOKEN = /same (?:--client-token|clientToken)/u;
1381
+ const isRecord$3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1382
+ /**
1383
+ * Whether the same call may be made again after this refusal. A wrong input, a missing canvas and
1384
+ * a canvas that moved on would only be refused again, and the changed call needs a new token.
1385
+ */
1386
+ const isRepeatable = (error) => REPEATABLE_CODES.has(error.code) || error.fields?.["outcome"] === "not_confirmed" || SAYS_SAME_TOKEN.test(error.remediation);
1387
+ const repeatWith = (clientToken) => `To repeat this call, give it --client-token ${clientToken}: a write that landed is found, not made twice.`;
1388
+ const refusalWith = (error, clientToken) => {
1389
+ if (!(error instanceof CliError)) return new CliError("INTERNAL", "The command failed before its answer arrived, so a write may or may not have landed.", repeatWith(clientToken), { clientToken });
1390
+ if (!isRepeatable(error)) return error;
1391
+ const remediation = `${error.remediation} ${repeatWith(clientToken)}`;
1392
+ const fields = {
1393
+ ...error.fields,
1394
+ clientToken
1395
+ };
1396
+ return error instanceof PartialBatchError ? new PartialBatchError(error.message, remediation, {
1397
+ code: error.code,
1398
+ fields
1399
+ }) : new CliError(error.code, error.message, remediation, fields);
1400
+ };
1401
+ /**
1402
+ * Runs a write with the caller's client token, or with one made here when the caller gave none.
1403
+ * A token made here is the only way to repeat the call as the same call, so it is put in the
1404
+ * answer and in every refusal after which the call may be repeated.
1405
+ */
1406
+ const runWithClientToken = async (given, run) => {
1407
+ if (given !== null) return run(given);
1408
+ const clientToken = randomUUID();
1409
+ try {
1410
+ const answer = await run(clientToken);
1411
+ return isRecord$3(answer) ? {
1412
+ ...answer,
1413
+ clientToken
1414
+ } : answer;
1415
+ } catch (error) {
1416
+ throw refusalWith(error, clientToken);
1417
+ }
1418
+ };
1419
+
1177
1420
  //#endregion
1178
1421
  //#region src/infrastructure/client-token-input.lib.ts
1179
- const clientTokenForInput = (clientToken) => {
1180
- if (clientToken === void 0) throw new CliError("BAD_REQUEST", "--client-token is required with --input.", "Mint one UUID for this request and reuse it only when retrying the same --input.");
1181
- return z.uuid().parse(clientToken);
1422
+ /** The client token a flag gave, or null when the flag was left out for the tool to make one. */
1423
+ const clientTokenFrom = (offered) => {
1424
+ if (offered === void 0) return null;
1425
+ const parsed = z.uuid().safeParse(offered);
1426
+ if (parsed.success) return parsed.data;
1427
+ throw new CliError("BAD_REQUEST", "--client-token must be a UUID.", "Give a UUID, or leave --client-token out: the command makes one and prints it as clientToken.");
1182
1428
  };
1429
+ const invokeWithClientToken = async (invocation, request, offered) => runWithClientToken(clientTokenFrom(offered), async (clientToken) => invocation.invoke({
1430
+ ...request,
1431
+ clientToken
1432
+ }));
1183
1433
 
1184
1434
  //#endregion
1185
1435
  //#region src/infrastructure/canvas-authoring-structure.program.ts
@@ -1190,13 +1440,12 @@ const executeDuplicate = async (input, options) => {
1190
1440
  options.baseVersion,
1191
1441
  options.nodes,
1192
1442
  options.idPrefix
1193
- ].some((value) => value !== void 0)) throw new CliError("BAD_REQUEST", "Choose --input or the individual duplicate options.", "Use --input with --client-token for native measured duplication.");
1194
- const capability = fromCapabilityReference(input.catalog(), "canvas.duplicateNodes");
1195
- input.output.result(await input.invocation.invoke({
1443
+ ].some((value) => value !== void 0)) throw new CliError("BAD_REQUEST", "Choose --input or the individual duplicate options.", "Use --input alone for native measured duplication.");
1444
+ const capability = input.catalog.one("canvas.duplicateNodes");
1445
+ input.output.result(await invokeWithClientToken(input.invocation, {
1196
1446
  capability,
1197
- arguments: createCanvasJsonInputAdapter(options.input, capability.inputSchema, "--input"),
1198
- clientToken: clientTokenForInput(options.clientToken)
1199
- }));
1447
+ arguments: createCanvasJsonInputAdapter(options.input, capability.inputSchema, "--input")
1448
+ }, options.clientToken));
1200
1449
  return;
1201
1450
  }
1202
1451
  if (options.canvas === void 0 || options.baseVersion === void 0 || options.nodes === void 0) throw new TypeError("The required-option check let duplicate-nodes run without --canvas, --base-version or --nodes.");
@@ -1218,7 +1467,7 @@ const executeDuplicate = async (input, options) => {
1218
1467
  });
1219
1468
  };
1220
1469
  const configureDuplicate = (canvas, input) => {
1221
- canvas.command("duplicate-nodes").description("Deep-clone node subtrees; --input uses native measured layout and durable copy receipts.").option("--input <json-or-@path>", "Scoped native duplication request; requires --client-token.").option("--canvas <url-or-id>", "Canvas URL or UUID to edit.").option("--base-version <integer>", "Exact current canvas version.").option("--nodes <json-or-@path>", "Array of {id,parentId?} requests.").option("--id-prefix <prefix>", "Stable namespace for cloned ids.").option("--client-token <uuid>", "Stable UUID for retrying this exact batch.").action(async (options) => executeDuplicate(input, options));
1470
+ canvas.command("duplicate-nodes").description("Deep-clone node subtrees; --input uses native measured layout and durable copy receipts.").option("--input <json-or-@path>", "Scoped native duplication request.").option("--canvas <url-or-id>", "Canvas URL or UUID to edit.").option("--base-version <integer>", "Exact current canvas version.").option("--nodes <json-or-@path>", "Array of {id,parentId?} requests.").option("--id-prefix <prefix>", "Stable namespace for cloned ids.").option("--client-token <uuid>", "Stable UUID for retrying this exact batch.").action(async (options) => executeDuplicate(input, options));
1222
1471
  };
1223
1472
  const configureMove = (canvas, input) => {
1224
1473
  canvas.command("move-nodes").description("Reorder or reparent nodes.").requiredOption("--canvas <url-or-id>", "Canvas URL or UUID to edit.").requiredOption("--base-version <integer>", "Exact current canvas version.").requiredOption("--moves <json-or-@path>", "Sequential before, after, or parent/index moves.").option("--client-token <uuid>", "Stable UUID for retrying this exact batch.").action(async (options) => {
@@ -1275,7 +1524,7 @@ const writeHtml = async (input, options) => {
1275
1524
  const reference = parseCanvasReference(options.canvas);
1276
1525
  const baseVersion = authoringBaseVersion(options.baseVersion);
1277
1526
  input.output.result(await input.invocation.invoke({
1278
- capability: fromCapabilityReference(input.catalog(), "canvas.writeHtml"),
1527
+ capability: input.catalog.one("canvas.writeHtml"),
1279
1528
  arguments: {
1280
1529
  canvasId: reference.canvasId,
1281
1530
  ...reference.pageId !== void 0 && { pageId: reference.pageId },
@@ -1311,7 +1560,7 @@ const configureCreateArtboard = (canvas, input) => {
1311
1560
  selectAuthoringToken(input, options.clientToken, true);
1312
1561
  const canvasId = fromCanvasReference(options.canvas);
1313
1562
  const baseVersion = authoringBaseVersion(options.baseVersion);
1314
- const scene = await sceneAtVersion(input, canvasId, baseVersion);
1563
+ const scene = await sceneAtVersion(input, canvasId, baseVersion, "flag");
1315
1564
  const rootBoxes = Object.entries(scene.relationships).flatMap(([nodeId, relationship]) => {
1316
1565
  const box = scene.nodes[nodeId]?.box;
1317
1566
  return box !== void 0 && relationship.parentId === "root" ? [box] : [];
@@ -1352,16 +1601,16 @@ const configureCanvasConversions = (canvas, input) => {
1352
1601
  "canvas.insertHtml",
1353
1602
  "canvas.makeEditable",
1354
1603
  "canvas.capture",
1604
+ "canvas.capturePage",
1355
1605
  "canvas.arrange"
1356
1606
  ]) {
1357
- const capability = fromCapabilityReference(input.catalog(), id);
1358
- const name = id === "canvas.insertHtml" ? "insert-html" : id === "canvas.makeEditable" ? "make-editable" : id.slice(7);
1359
- canvas.command(name).description(capability.guide.summary).requiredOption("--input <json-or-@path>", "Canvas reference, base version and explicit native authoring request.").requiredOption("--client-token <uuid>", "Stable intent ID; reuse unchanged after an uncertain outcome.").action(async (options) => {
1360
- input.output.result(await input.invocation.invoke({
1607
+ const name = id === "canvas.insertHtml" ? "insert-html" : id === "canvas.makeEditable" ? "make-editable" : id === "canvas.capturePage" ? "capture-page" : id.slice(7);
1608
+ canvas.command(name).description(input.catalog.summary(id)).requiredOption("--input <json-or-@path>", "Canvas reference, base version and explicit native authoring request.").option("--client-token <uuid>", "Stable intent ID; reuse unchanged after an uncertain outcome. Made and printed as clientToken when left out.").action(async (options) => {
1609
+ const capability = input.catalog.one(id);
1610
+ input.output.result(await invokeWithClientToken(input.invocation, {
1361
1611
  capability,
1362
- arguments: createCanvasJsonInputAdapter(options.input, capability.inputSchema, "--input"),
1363
- clientToken: z.uuid().parse(options.clientToken)
1364
- }));
1612
+ arguments: createCanvasJsonInputAdapter(options.input, capability.inputSchema, "--input")
1613
+ }, options.clientToken));
1365
1614
  });
1366
1615
  }
1367
1616
  };
@@ -1369,12 +1618,11 @@ const configureCanvasConversions = (canvas, input) => {
1369
1618
  //#endregion
1370
1619
  //#region src/infrastructure/canvas-exchange.program.ts
1371
1620
  const configureRemove = (canvas, input) => {
1372
- canvas.command("remove").description("Remove explicitly named canvas subtrees with scope, lock and revision checks.").requiredOption("--input <json-or-@path>", "Request containing canvasRef, baseVersion and rootNodeIds.").requiredOption("--client-token <uuid>", "Stable intent ID; reuse unchanged after an uncertain outcome.").action(async (options) => {
1373
- input.output.result(await input.invocation.invoke({
1374
- capability: fromCapabilityReference(input.catalog(), "canvas.remove"),
1375
- arguments: createCanvasJsonInputAdapter(options.input, canvasRemoveCapabilityInputSchema, "--input"),
1376
- clientToken: z.uuid().parse(options.clientToken)
1377
- }));
1621
+ canvas.command("remove").description("Remove explicitly named canvas subtrees with scope, lock and revision checks.").requiredOption("--input <json-or-@path>", "Request containing canvasRef, baseVersion and rootNodeIds.").option("--client-token <uuid>", "Stable intent ID; reuse unchanged after an uncertain outcome. Made and printed as clientToken when left out.").action(async (options) => {
1622
+ input.output.result(await invokeWithClientToken(input.invocation, {
1623
+ capability: input.catalog.one("canvas.remove"),
1624
+ arguments: createCanvasJsonInputAdapter(options.input, canvasRemoveCapabilityInputSchema, "--input")
1625
+ }, options.clientToken));
1378
1626
  });
1379
1627
  };
1380
1628
  const configureRead = (canvas, input) => {
@@ -1385,7 +1633,7 @@ const configureRead = (canvas, input) => {
1385
1633
  ...options.nodeId !== void 0 && { nodeId: options.nodeId }
1386
1634
  } : createCanvasJsonInputAdapter(options.input, canvasReadInputSchema, "--input");
1387
1635
  input.output.result(await input.invocation.invoke({
1388
- capability: fromCapabilityReference(input.catalog(), "canvas.read"),
1636
+ capability: input.catalog.one("canvas.read"),
1389
1637
  arguments: request,
1390
1638
  clientToken: null
1391
1639
  }));
@@ -1394,46 +1642,43 @@ const configureRead = (canvas, input) => {
1394
1642
  const configureCanvasExchange = (canvas, input) => {
1395
1643
  canvas.command("find").description("Find accessible canvases and existing creation destinations with bounded results.").option("--input <json-or-@path>", "Search title, collection, limit and continuation cursor.", "{}").action(async (options) => {
1396
1644
  input.output.result(await input.invocation.invoke({
1397
- capability: fromCapabilityReference(input.catalog(), "canvas.find"),
1645
+ capability: input.catalog.one("canvas.find"),
1398
1646
  arguments: createCanvasJsonInputAdapter(options.input, canvasFindInputSchema, "--input"),
1399
1647
  clientToken: null
1400
1648
  }));
1401
1649
  });
1402
1650
  configureRemove(canvas, input);
1403
1651
  configureRead(canvas, input);
1404
- canvas.command("update-html").description("Apply an identity-preserving edit from a complete HTML snapshot.").requiredOption("--input <json-or-@path>", "Request containing canvasRef, snapshotToken, html and removeNodeIds.").requiredOption("--client-token <uuid>", "Stable intent ID; reuse unchanged after an uncertain outcome.").action(async (options) => {
1652
+ canvas.command("update-html").description("Apply an identity-preserving edit from a complete HTML snapshot.").requiredOption("--input <json-or-@path>", "Request containing canvasRef, snapshotToken, html and removeNodeIds.").option("--client-token <uuid>", "Stable intent ID; reuse unchanged after an uncertain outcome. Made and printed as clientToken when left out.").action(async (options) => {
1405
1653
  const request = createCanvasJsonInputAdapter(options.input, canvasUpdateHtmlCapabilityInputSchema, "--input");
1406
- input.output.result(await input.invocation.invoke({
1407
- capability: fromCapabilityReference(input.catalog(), "canvas.updateHtml"),
1408
- arguments: request,
1409
- clientToken: z.uuid().parse(options.clientToken)
1410
- }));
1654
+ input.output.result(await invokeWithClientToken(input.invocation, {
1655
+ capability: input.catalog.one("canvas.updateHtml"),
1656
+ arguments: request
1657
+ }, options.clientToken));
1411
1658
  });
1412
1659
  };
1413
1660
 
1414
1661
  //#endregion
1415
1662
  //#region src/infrastructure/canvas-prototype.program.ts
1416
1663
  const configureCanvasPrototype = (canvas, input) => {
1417
- const capability = fromCapabilityReference(input.catalog(), "prototype.publishCanvas");
1418
- canvas.command("publish-prototype").description(capability.guide.summary).requiredOption("--input <json-or-@path>", "Complete canvas reference, baseVersion, unpacked build directory or existing deployment, and bounded waitMs.").requiredOption("--client-token <uuid>", "Stable attachment intent; reuse the same arguments after uncertainty, use a new token after replanning.").action(async (options) => {
1419
- input.output.result(await input.invocation.invoke({
1664
+ canvas.command("publish-prototype").description(input.catalog.summary("prototype.publishCanvas")).requiredOption("--input <json-or-@path>", "Complete canvas reference, baseVersion, unpacked build directory or existing deployment, and bounded waitMs.").option("--client-token <uuid>", "Stable attachment intent; reuse the same arguments after uncertainty, use a new token after replanning. Made and printed as clientToken when left out.").action(async (options) => {
1665
+ const capability = input.catalog.one("prototype.publishCanvas");
1666
+ input.output.result(await invokeWithClientToken(input.invocation, {
1420
1667
  capability,
1421
- arguments: createCanvasJsonInputAdapter(options.input, capability.inputSchema, "--input"),
1422
- clientToken: z.uuid().parse(options.clientToken)
1423
- }));
1668
+ arguments: createCanvasJsonInputAdapter(options.input, capability.inputSchema, "--input")
1669
+ }, options.clientToken));
1424
1670
  });
1425
1671
  };
1426
1672
 
1427
1673
  //#endregion
1428
1674
  //#region src/infrastructure/canvas-asset.program.ts
1429
1675
  const configureCanvasAsset = (canvas, input) => {
1430
- const capability = fromCapabilityReference(input.catalog(), "canvas.importAsset");
1431
- canvas.command("import-asset").description(capability.guide.summary).requiredOption("--input <json-or-@path>", "Canvas reference and selected local file source.").requiredOption("--client-token <uuid>", "Stable import intent; reuse after uncertainty.").action(async (options) => {
1432
- input.output.result(await input.invocation.invoke({
1676
+ canvas.command("import-asset").description(input.catalog.summary("canvas.importAsset")).requiredOption("--input <json-or-@path>", "Canvas reference and selected local file source.").option("--client-token <uuid>", "Stable import intent; reuse after uncertainty. Made and printed as clientToken when left out.").action(async (options) => {
1677
+ const capability = input.catalog.one("canvas.importAsset");
1678
+ input.output.result(await invokeWithClientToken(input.invocation, {
1433
1679
  capability,
1434
- arguments: createCanvasJsonInputAdapter(options.input, capability.inputSchema, "--input"),
1435
- clientToken: z.uuid().parse(options.clientToken)
1436
- }));
1680
+ arguments: createCanvasJsonInputAdapter(options.input, capability.inputSchema, "--input")
1681
+ }, options.clientToken));
1437
1682
  });
1438
1683
  };
1439
1684
 
@@ -1454,11 +1699,8 @@ const configureCanvasAuthoring = (canvas, input) => {
1454
1699
  //#endregion
1455
1700
  //#region src/infrastructure/canvas-inspection.program.ts
1456
1701
  const referenceFor = (command) => {
1457
- const reference = command.getOptionValue("canvas");
1458
- const legacy = command.getOptionValue("canvasId");
1459
- if (reference !== void 0 && legacy !== void 0) throw new CliError("BAD_REQUEST", "--canvas and --canvas-id cannot be combined.", "Pass the pasted URL or UUID through --canvas.");
1460
- const selected = reference ?? legacy;
1461
- if (typeof selected !== "string") throw new TypeError(`The required-option check let canvas ${command.name()} run without --canvas.`);
1702
+ const selected = command.getOptionValue("canvas");
1703
+ if (typeof selected !== "string") throw new TypeError(`The spelling check let canvas ${command.name()} run without --canvas.`);
1462
1704
  return {
1463
1705
  reference: parseCanvasReference(selected),
1464
1706
  url: selected
@@ -1482,6 +1724,10 @@ const readLinkedSelection = async (command, input, reference, url) => {
1482
1724
  node: nodes.find((node) => node.id === nodeId)
1483
1725
  };
1484
1726
  };
1727
+ /**
1728
+ * Lets the four read commands follow a link to a page or a selection. They take `--canvas` as
1729
+ * their own, so the link reaches them whole and `--canvas-id` is read into it.
1730
+ */
1485
1731
  const configureCanvasInspection = (canvas, input) => {
1486
1732
  for (const name of [
1487
1733
  "inspect",
@@ -1492,7 +1738,6 @@ const configureCanvasInspection = (canvas, input) => {
1492
1738
  const command = canvas.commands.find((candidate) => candidate.name() === name);
1493
1739
  const canvasId = command?.options.find((option) => option.long === "--canvas-id");
1494
1740
  if (command === void 0 || canvasId === void 0) continue;
1495
- canvasId.makeOptionMandatory(false);
1496
1741
  command.options.find((option) => option.long === "--node-id")?.makeOptionMandatory(false);
1497
1742
  command.option("--canvas <url-or-id>", "Pasted canvas URL or UUID. Selection links limit reads and edits to the linked subtree.");
1498
1743
  command.action(async () => {
@@ -1511,18 +1756,9 @@ const configureCanvasInspection = (canvas, input) => {
1511
1756
  const createCanvasRenderInputAdapter = (options) => {
1512
1757
  if (options.input === void 0) return null;
1513
1758
  if (options.canvas !== void 0 || options.nodeId !== void 0 || options.bounds !== void 0 || options.expectedVersion !== void 0 || options.atMs !== void 0 || options.output !== void 0 || options.force === true || options.scale !== "1" || options.timeoutMs !== "120000") throw new CliError("BAD_REQUEST", "The bounded --input request cannot be combined with individual render options.", "Put the entire scoped render request in --input.");
1514
- return {
1515
- arguments: createCanvasJsonInputAdapter(options.input, canvasRenderScopedInputSchema, "--input"),
1516
- clientToken: clientTokenForInput(options.clientToken)
1517
- };
1759
+ return { arguments: createCanvasJsonInputAdapter(options.input, canvasRenderScopedInputSchema, "--input") };
1518
1760
  };
1519
1761
 
1520
- //#endregion
1521
- //#region src/infrastructure/command-examples.consts.ts
1522
- const CANVAS_RENDER_EXAMPLE = "canvas render --canvas 0b9f4c1e-5d2a-4e8b-9c3f-7a6d1e2b4c50";
1523
- /** A command line, after the binary name, that each listed command accepts exactly as written. */
1524
- const COMMAND_EXAMPLES = { "canvas render": CANVAS_RENDER_EXAMPLE };
1525
-
1526
1762
  //#endregion
1527
1763
  //#region src/infrastructure/canvas.program.ts
1528
1764
  const positiveInteger$2 = z.coerce.number().int().positive();
@@ -1574,7 +1810,7 @@ const selectedRenderTarget = async (options, input) => {
1574
1810
  const held = wholeCanvasDocumentOutputSchema.parse(await input.remote.query("canvas.document.get", { canvasId: reference.canvasId }));
1575
1811
  if (expectedVersion !== null && expectedVersion !== held.version) throw new CliError("CONFLICT", "The canvas changed before rendering.", "Read the linked page or selection and render its current version.");
1576
1812
  return {
1577
- target: canvasReferenceRenderTarget(reference, canvasReadableSceneDocumentSchema.parse(held.document), target),
1813
+ target: canvasReferenceRenderTarget(reference, readStoredCanvasScene(held.document), target),
1578
1814
  expectedVersion: held.version
1579
1815
  };
1580
1816
  };
@@ -1588,7 +1824,7 @@ const executeRender = async (options, input) => {
1588
1824
  if (recordingId === void 0 && options.atMs !== void 0) throw new CliError("BAD_REQUEST", "--at-ms requires a stable recording node id such as rec_<recording-uuid>.", "Run `enhance canvas tree --canvas <url-or-id>` and choose a recording node.");
1589
1825
  selectClientToken(input, options.clientToken);
1590
1826
  const result = await input.invocation.invoke({
1591
- capability: fromCapabilityReference(input.catalog(), "canvas.render"),
1827
+ capability: input.catalog.one("canvas.render"),
1592
1828
  arguments: {
1593
1829
  canvasId: parseCanvasReference(options.canvas).canvasId,
1594
1830
  ...resolved,
@@ -1606,15 +1842,14 @@ const executeRender = async (options, input) => {
1606
1842
  });
1607
1843
  input.output.result(result);
1608
1844
  };
1609
- const rootOf = (command) => command.parent === null ? command : rootOf(command.parent);
1610
1845
  const configureRender = (render, input) => {
1611
- render.option("--input <json-or-@path>", "Bounded scoped render request; requires --client-token.").option("--canvas <url-or-id>", "Canvas URL or UUID to render.").option("--node-id <id>", "Render one stable canvas node instead of all authored content.").option("--bounds <json>", "Render an explicit rectangle in canvas world coordinates.").option("--expected-version <integer>", "Refuse pixels from any other document version.").option("--at-ms <integer>", "Pause a recording node at this millisecond; inspect the PNG before snapshotting it.").option("--scale <number>", "Output pixels per canvas unit, from 0.1 to 4.", "1").option("--output <path>", "Write the PNG to this path instead of a protected temporary file.").option("--force", "Replace an existing --output file deliberately.", false).option("--timeout-ms <integer>", "Local polling deadline in milliseconds.", "120000").option("--client-token <uuid>", "Stable UUID to reuse only when retrying this render request.").addHelpText("after", () => `\nExample:\n ${rootOf(render).name()} ${CANVAS_RENDER_EXAMPLE}\n\nFor transcript-led selection, inspect nearby --at-ms renders and reject transitions or duplicate states before running recording snapshot.\n`).action(async (options) => {
1846
+ render.option("--input <json-or-@path>", "Bounded scoped render request.").option("--canvas <url-or-id>", "Canvas URL or UUID to render.").option("--node-id <id>", "Render one stable canvas node instead of all authored content.").option("--bounds <json>", "Render an explicit rectangle in canvas world coordinates.").option("--expected-version <integer>", "Refuse pixels from any other document version.").option("--at-ms <integer>", "Pause a recording node at this millisecond; inspect the PNG before snapshotting it.").option("--scale <number>", "Output pixels per canvas unit, from 0.1 to 4.", "1").option("--output <path>", "Write the PNG to this path instead of a protected temporary file.").option("--force", "Replace an existing --output file deliberately.", false).option("--timeout-ms <integer>", "Local polling deadline in milliseconds.", "120000").option("--client-token <uuid>", "Stable UUID to reuse only when retrying this render request.").addHelpText("after", "\nFor transcript-led selection, inspect nearby --at-ms renders and reject transitions or duplicate states before running recording snapshot.").action(async (options) => {
1612
1847
  const bounded = createCanvasRenderInputAdapter(options);
1613
1848
  if (bounded === null) return executeRender(options, input);
1614
- input.output.result(await input.invocation.invoke({
1615
- capability: fromCapabilityReference(input.catalog(), "canvas.render"),
1849
+ input.output.result(await invokeWithClientToken(input.invocation, {
1850
+ capability: input.catalog.one("canvas.render"),
1616
1851
  ...bounded
1617
- }));
1852
+ }, options.clientToken));
1618
1853
  });
1619
1854
  };
1620
1855
  const registerCanvasProgram = (program, input) => {
@@ -1634,7 +1869,42 @@ const registerCanvasProgram = (program, input) => {
1634
1869
  };
1635
1870
 
1636
1871
  //#endregion
1637
- //#region ../../packages/sdk/dist/stall-watch.lib-qRMMj0yg.mjs
1872
+ //#region src/infrastructure/capture-skill.lib.ts
1873
+ /**
1874
+ * The skill `setup` copies to each coding agent. Its description says when it applies, and its body
1875
+ * names the commands; the tool's own help teaches the rest. A line is added only when measured
1876
+ * runs are worse without it; `skill-evaluation` holds the cases and what the last runs found.
1877
+ */
1878
+ const skillText = (skill, command) => `---
1879
+ name: ${skill}
1880
+ description: Put the screens a thread is changing onto an Enhance canvas as editable frames and return the link. Use when asked to capture, share or review screens, or to put work on a canvas. Also applies whenever a thread has changed how a screen looks: when that work is done, offer once, in one line, to put the changed screens on an Enhance canvas for review, and capture only on a yes.
1881
+ ---
1882
+
1883
+ # Capture screens to Enhance
1884
+
1885
+ Put each screen this thread is changing onto one Enhance canvas as an editable frame, and return the canvas link.
1886
+
1887
+ ## Commands
1888
+
1889
+ - \`${command} canvas create --title "<what this thread is changing>"\` makes the canvas and answers with its id and its link.
1890
+ - \`${command} canvas capture-page --help\` shows the two calls one capture takes, with an example. Read it before the first capture.
1891
+ - \`${command} auth status\` says who is signed in. If nobody is, ask the person to run \`${command} setup\`.
1892
+ `;
1893
+ /**
1894
+ * The skill's name and file. `command` is how an agent's shell reaches the tool: its command name
1895
+ * when that is on the PATH, or its full path. Each release names its skill after its own command,
1896
+ * so the production and development tools never overwrite one another's.
1897
+ */
1898
+ const captureSkillOf = (input) => {
1899
+ const name = `${input.commandName}-capture`;
1900
+ return {
1901
+ name,
1902
+ text: skillText(name, input.command)
1903
+ };
1904
+ };
1905
+
1906
+ //#endregion
1907
+ //#region ../../packages/sdk/dist/stall-watch.lib-JRTp4jPK.mjs
1638
1908
  const CAPTURE_METADATA_LENGTH = 200;
1639
1909
  const CAPTURE_FAILURE_LENGTH = 1e3;
1640
1910
  const CAPTURE_UPLOAD_BATCH_SIZE = 400;
@@ -2379,9 +2649,24 @@ const writeCaptureJson = async (path, value) => {
2379
2649
  await writeFile(temporary, JSON.stringify(value), { mode: 384 });
2380
2650
  await rename(temporary, path);
2381
2651
  };
2652
+ const manifestJson = (path, content) => {
2653
+ try {
2654
+ return JSON.parse(content);
2655
+ } catch (error) {
2656
+ throw captureError("artifact", `The capture manifest ${path} is not JSON: ${error instanceof Error ? error.message : "it could not be parsed"}.`);
2657
+ }
2658
+ };
2659
+ /**
2660
+ * The manifest at `path`. One that is not JSON, or not a capture manifest, throws an artifact
2661
+ * error naming the file and the first problem in it, which a caller can report as bad input.
2662
+ */
2382
2663
  const readCaptureManifest = async (path) => {
2383
- const raw = JSON.parse(await readFile(path, "utf8"));
2384
- return lenientCaptureManifestSchema.parse(raw);
2664
+ const content = await readFile(path, "utf8");
2665
+ const parsed = lenientCaptureManifestSchema.safeParse(manifestJson(path, content));
2666
+ if (parsed.success) return parsed.data;
2667
+ const [problem] = parsed.error.issues;
2668
+ const field = problem?.path.join(".") ?? "";
2669
+ throw captureError("artifact", `The capture manifest ${path} is not valid: ${field === "" ? "" : `${field}: `}${problem?.message ?? "it is not a capture manifest"}`);
2385
2670
  };
2386
2671
  /** Historical formats stay pinned; an ordinary writer always uses CANVAS_SCENE_VERSION. */
2387
2672
  const LEGACY_CANVAS_FORMATS = {
@@ -2417,8 +2702,10 @@ const LEGACY_CANVAS_ADAPTATIONS = {
2417
2702
  [LEGACY_CANVAS_FORMATS.v13]: "format-number",
2418
2703
  [LEGACY_CANVAS_FORMATS.v14]: "format-number"
2419
2704
  };
2420
- /** Why the API refused an operation, as a fixed value. Never the words of the refusal. */
2705
+ /** Why the API refused a request or one of its operations, as a fixed value. Never its words. */
2421
2706
  const CANVAS_REFUSAL_CODES = [
2707
+ "input-invalid",
2708
+ "request-too-large",
2422
2709
  "appearance-unsupported-component",
2423
2710
  "styles-unsupported-component",
2424
2711
  "text-shadow-blend-unsupported",
@@ -2721,6 +3008,96 @@ const adaptCanvasDocumentFormat = (document) => {
2721
3008
  if (document["version"] === LEGACY_CANVAS_FORMATS.v13 || document["version"] === LEGACY_CANVAS_FORMATS.v14) return adapted;
2722
3009
  return withoutTextShadowBlends(document["version"] === LEGACY_CANVAS_FORMATS.v12 ? adapted : adaptCanvasCss(adapted));
2723
3010
  };
3011
+ const isSafeInteger = (value) => Number.isSafeInteger(value);
3012
+ /** A format below 1 names no adaptation, so the walk below refuses it. */
3013
+ const canvasWriterFormat = (version) => {
3014
+ if (!isSafeInteger(version)) return "refused";
3015
+ if (version > 15) return "ahead";
3016
+ if (version === 15) return "current";
3017
+ const adaptations = new Map(Object.entries(LEGACY_CANVAS_ADAPTATIONS).map(([format, kind]) => [Number(format), kind]));
3018
+ for (let format = version; format < 15; format += 1) if (adaptations.get(format) !== "format-number") return "refused";
3019
+ return "number-only";
3020
+ };
3021
+ const objectPictureSizeSchema = z.enum(["quarter", "sixteenth"]);
3022
+ /** One stored picture of one top layer. */
3023
+ const canvasObjectPictureSchema = z.strictObject({
3024
+ objectId: z.string().min(1),
3025
+ size: objectPictureSizeSchema,
3026
+ /** Where the picture's bytes are; what it answers with never changes. */
3027
+ url: z.string().min(1),
3028
+ width: z.number().int().positive(),
3029
+ height: z.number().int().positive(),
3030
+ /** The canvas version the picture was drawn at. */
3031
+ drawnVersion: z.number().int().nonnegative(),
3032
+ /** Whether the top layer is unchanged since the picture was drawn. */
3033
+ isCurrent: z.boolean(),
3034
+ /**
3035
+ * The font size, in pixels, that set the most characters of the top layer's texts when it was
3036
+ * drawn; left out where it held no text, or for a picture drawn before sizes were kept.
3037
+ */
3038
+ textSize: z.number().positive().optional()
3039
+ });
3040
+ z.strictObject({
3041
+ canvasId: z.uuid(),
3042
+ /** Only pictures drawn after this version; every picture when left out. */
3043
+ sinceVersion: z.number().int().nonnegative().optional()
3044
+ });
3045
+ z.object({ pictures: z.array(canvasObjectPictureSchema) });
3046
+ z.strictObject({
3047
+ canvasId: z.uuid(),
3048
+ objectIds: z.array(z.string().min(1)).min(1).max(200)
3049
+ });
3050
+ z.object({ scheduled: z.number().int().nonnegative() });
3051
+ const MAX_PICTURE_STORAGE_KEY_LENGTH = 500;
3052
+ const MAX_PICTURE_FAILURE_LENGTH = 500;
3053
+ /** One top layer a picture job is to draw, with when it was last put on the list. */
3054
+ const objectPictureWorkObjectSchema = z.object({
3055
+ objectId: z.string().min(1),
3056
+ wantedAt: z.iso.datetime()
3057
+ });
3058
+ /** One picture a job drew and uploaded, in pixels of the stored picture. */
3059
+ const drawnObjectPictureSchema = z.object({
3060
+ size: objectPictureSizeSchema,
3061
+ width: z.number().int().positive(),
3062
+ height: z.number().int().positive(),
3063
+ bytes: z.number().int().positive(),
3064
+ storageKey: z.string().min(1).max(MAX_PICTURE_STORAGE_KEY_LENGTH),
3065
+ /** The text size of the top layer the page drew, as the list of pictures gives it. */
3066
+ textSize: z.number().positive().optional()
3067
+ });
3068
+ z.object({
3069
+ jobId: z.uuid(),
3070
+ loadedVersion: z.number().int().positive(),
3071
+ drawn: z.array(objectPictureWorkObjectSchema.extend({ pictures: z.array(drawnObjectPictureSchema).length(2) })).max(20),
3072
+ failed: z.array(z.object({
3073
+ objectId: z.string().min(1),
3074
+ message: z.string().min(1).max(MAX_PICTURE_FAILURE_LENGTH)
3075
+ })).max(20)
3076
+ });
3077
+ const coordinate$1 = z.number();
3078
+ const extent = z.number().nonnegative();
3079
+ /** A box in page coordinates. */
3080
+ const canvasOutlineBoxSchema = z.strictObject({
3081
+ x: coordinate$1,
3082
+ y: coordinate$1,
3083
+ width: extent,
3084
+ height: extent
3085
+ });
3086
+ /** What a browser measured of one top layer: its own box, and how far its descendants paint. */
3087
+ const canvasOutlineMeasurementSchema = z.strictObject({
3088
+ objectId: z.string().min(1),
3089
+ box: canvasOutlineBoxSchema,
3090
+ reach: canvasOutlineBoxSchema
3091
+ });
3092
+ z.strictObject({
3093
+ canvasId: z.uuid(),
3094
+ /** The revision of the document the browser had laid out when it measured. */
3095
+ version: z.number().int().positive(),
3096
+ measurements: z.array(canvasOutlineMeasurementSchema).min(1).max(200)
3097
+ });
3098
+ z.object({ stored: z.number().int().nonnegative() });
3099
+ z.strictObject({ canvasId: z.uuid() });
3100
+ z.object({ measurements: z.array(canvasOutlineMeasurementSchema.extend({ measuredVersion: z.number().int().nonnegative() })) });
2724
3101
  z.strictObject({});
2725
3102
  z.object({ firstAgentWorkAt: z.iso.datetime().nullable() });
2726
3103
  /** Cursor pagination, defined once so no endpoint invents its own page shape. */
@@ -2827,13 +3204,18 @@ const canvasSchema = z.object({
2827
3204
  createdAt: z.iso.datetime(),
2828
3205
  lastActivityAt: z.iso.datetime()
2829
3206
  });
3207
+ /**
3208
+ * A canvas with its full web address, which only the API can write: it is built from the web
3209
+ * address of the API's own environment, so a reader never joins an id to a host.
3210
+ */
3211
+ const linkedCanvasSchema = canvasSchema.extend({ url: z.url() });
2830
3212
  z.object({
2831
3213
  title: z.string().trim().min(1),
2832
3214
  /** The team to file it under, or null for the maker's own. Refused for one you are not on. */
2833
3215
  organisationId: z.uuid().nullable().default(null),
2834
3216
  sourceUrl: z.string().nullable().default(null)
2835
3217
  });
2836
- canvasSchema.extend({ version: z.number().int().positive() });
3218
+ linkedCanvasSchema.extend({ version: z.number().int().positive() });
2837
3219
  z.object({ canvasId: z.uuid() });
2838
3220
  /**
2839
3221
  * Which collection to draw: your own, a team's by id, or everything you can reach. One field
@@ -2857,7 +3239,7 @@ z.object({
2857
3239
  ]).default("all"),
2858
3240
  hasUnresolved: z.boolean().default(false)
2859
3241
  });
2860
- const canvasCardBaseSchema = canvasSchema.extend({
3242
+ const canvasCardBaseSchema = linkedCanvasSchema.extend({
2861
3243
  screenCount: z.number().int().min(0),
2862
3244
  hasRecording: z.boolean(),
2863
3245
  /** When the person listing last opened it in the web app; `null` if they never have. */
@@ -3289,6 +3671,11 @@ const canvasNodeLayoutSchema = z.object({
3289
3671
  clipContent: z.boolean().optional(),
3290
3672
  baselineSource: canvasBaselineSourceSchema.optional(),
3291
3673
  scrollbarGutter: canvasScrollbarGutterSchema.optional(),
3674
+ /**
3675
+ * The frame holds an embedded document. Chromium sizes that document's viewport in whole
3676
+ * pixels, rounding the frame's content box up, so what the frame holds resolves against that.
3677
+ */
3678
+ embeddedDocument: z.literal(true).optional(),
3292
3679
  container: canvasFlexLayoutSchema.partial().extend({ padding: canvasFlexPaddingSchema.partial().optional() }).optional()
3293
3680
  }).strict();
3294
3681
  const boundedNumber = canvasNumberSchema;
@@ -3357,7 +3744,9 @@ const canvasOutlineSchema = z.object({
3357
3744
  ]),
3358
3745
  paints: z.array(canvasPaintSchema),
3359
3746
  dashPattern: canvasDashPatternSchema.optional(),
3360
- dashCap: canvasDashCapSchema.optional()
3747
+ dashCap: canvasDashCapSchema.optional(),
3748
+ /** Captured CSS dashes, which the browser draws, as for a border. */
3749
+ dashOrigin: z.literal("css").optional()
3361
3750
  });
3362
3751
  const canvasShadowSchema = z.object({
3363
3752
  id: itemId,
@@ -3816,13 +4205,13 @@ z.strictObject({
3816
4205
  state: z.enum(["awaiting_upload", "ready"]),
3817
4206
  metadata: canvasAssetMetadataSchema.nullable()
3818
4207
  }).refine((asset) => asset.state === "ready" === (asset.metadata !== null), "Readiness must match verified metadata.").refine((asset) => asset.metadata === null || asset.metadata.kind === asset.kind, "Metadata must describe the reserved asset kind.").refine((asset) => isStoredContentType(asset.kind, asset.contentType), "Content type must match the asset kind.").refine((asset) => asset.path === (asset.kind === "image" ? canvasImageAssetPath(asset.canvasId, asset.assetId) : canvasFontAssetPath(asset.canvasId, asset.sha256)), "The resource path must match its native identity.").safeExtend({ upload: signedUploadSchema.nullable() }).refine((asset) => asset.state === "awaiting_upload" === (asset.upload !== null), "Only pending uploads receive upload access.");
3819
- const SIDES = [
4208
+ const SIDES$1 = [
3820
4209
  "top",
3821
4210
  "right",
3822
4211
  "bottom",
3823
4212
  "left"
3824
4213
  ];
3825
- SIDES.map((side) => `padding-${side}`), SIDES.map((side) => `margin-${side}`);
4214
+ SIDES$1.map((side) => `padding-${side}`), SIDES$1.map((side) => `margin-${side}`);
3826
4215
  const format = z.enum(["png", "jpeg"]);
3827
4216
  const scale = z.number().positive();
3828
4217
  const canvasExportSettingsSchema = z.strictObject({
@@ -3895,7 +4284,34 @@ const canvasGeometrySchema = z.discriminatedUnion("kind", [
3895
4284
  canvasBooleanGeometrySchema
3896
4285
  ]);
3897
4286
  const CANVAS_COMPOSITING_RETIRED = "Update Enhance: compositing is no longer supported. Use the isolation style or a mask group.";
3898
- const canvasDocumentFormatSchema = z.literal(15, { error: "This editor uses an unsupported document format. Update the editor before changing this canvas." });
4287
+ const CANVAS_FORMAT_UPDATE_REQUIRED = "This change needs a newer version of Enhance. Refresh the editor, or update the Enhance plugin or command-line tool, then try again.";
4288
+ const CANVAS_FORMAT_SERVER_UPDATING = "Enhance is being updated. Try again in a minute.";
4289
+ /** Marks an issue whose message was written for whoever sent the request, so the API keeps it. */
4290
+ const FOR_CALLER = { forCaller: true };
4291
+ /**
4292
+ * The format a writer was built for, as a plain whole number so tool schemas can describe it. Which
4293
+ * writes that format may make is `refuseUnsafeWriterFormat`'s call.
4294
+ */
4295
+ const canvasDocumentFormatSchema = z.number({ error: CANVAS_FORMAT_UPDATE_REQUIRED }).int({ error: CANVAS_FORMAT_UPDATE_REQUIRED }).positive({ error: CANVAS_FORMAT_UPDATE_REQUIRED }).meta({
4296
+ description: `The document format this client writes. The current format is ${String(15)}.`,
4297
+ examples: [15]
4298
+ });
4299
+ /**
4300
+ * Refuses a write its client's format could get wrong. A client whose format differs from the
4301
+ * current one only in its number may still name changes, but a whole value it sends may lack
4302
+ * fields added since, so that needs the current format.
4303
+ */
4304
+ const refuseUnsafeWriterFormat = (documentFormatVersion, writes, context) => {
4305
+ const writer = canvasWriterFormat(documentFormatVersion);
4306
+ if (writer === "current" || writer === "number-only" && writes === "names") return;
4307
+ context.addIssue({
4308
+ code: "custom",
4309
+ path: ["documentFormatVersion"],
4310
+ message: writer === "ahead" ? CANVAS_FORMAT_SERVER_UPDATING : CANVAS_FORMAT_UPDATE_REQUIRED,
4311
+ params: FOR_CALLER,
4312
+ input: documentFormatVersion
4313
+ });
4314
+ };
3899
4315
  z.object({
3900
4316
  signature: z.string().regex(/^[a-f0-9]{16}$/u),
3901
4317
  /** The captured picture of the page's text, inline as written or as its canvas image store path. */
@@ -4010,7 +4426,8 @@ const canvasUnsupportedFeatureSchema = z.enum([
4010
4426
  "image-shadows",
4011
4427
  "effect-noise",
4012
4428
  "effect-texture",
4013
- "effect-glass"
4429
+ "effect-glass",
4430
+ "mask-source"
4014
4431
  ]);
4015
4432
  const canvasConversionReportSchema = z.object({
4016
4433
  nodeCount: z.number().int().positive(),
@@ -4052,13 +4469,27 @@ const canvasSubtreeDraftSchema = z.object({
4052
4469
  nodeCount: draft.nodes.length
4053
4470
  }
4054
4471
  }));
4055
- z.object({
4472
+ /** A capture that lands as a new editable frame on a page, with no screen layer. */
4473
+ const editableFrameCaptureSchema = z.object({
4474
+ screenId: z.string().min(1),
4475
+ pageId: z.string().min(1),
4476
+ pictureNodeId: z.string().min(1).optional().describe("The capture's picture, which the frame replaces in place and whose id it keeps. Refused as capture-already-landed once the picture is a frame.")
4477
+ });
4478
+ const editableFrameInputBase = {
4056
4479
  canvasId: z.uuid(),
4057
4480
  documentFormatVersion: canvasDocumentFormatSchema,
4058
4481
  mutationId: z.uuid(),
4059
4482
  baseVersion: z.number().int().positive(),
4060
- screenNodeId: z.string().min(1),
4061
4483
  draft: canvasSubtreeDraftSchema
4484
+ };
4485
+ z.union([z.strictObject({
4486
+ ...editableFrameInputBase,
4487
+ screenNodeId: z.string().min(1).describe("The screen layer to convert beside itself.")
4488
+ }), z.strictObject({
4489
+ ...editableFrameInputBase,
4490
+ capture: editableFrameCaptureSchema.describe("The stored page a new capture lands from, and the page its frame goes on.")
4491
+ })]).superRefine((input, context) => {
4492
+ refuseUnsafeWriterFormat(input.documentFormatVersion, "whole", context);
4062
4493
  });
4063
4494
  const createEditableFrameResultSchema = z.object({
4064
4495
  canvasId: z.uuid(),
@@ -4120,7 +4551,8 @@ const RENDER_WARNING_CODES = [
4120
4551
  "LOCAL_FONT_FALLBACK",
4121
4552
  "SOURCE_FALLBACK",
4122
4553
  "SCALE_REDUCED",
4123
- "LAYOUT_FALLBACK"
4554
+ "LAYOUT_FALLBACK",
4555
+ "DRAWN_APPROXIMATELY"
4124
4556
  ];
4125
4557
  const MAX_RENDER_MESSAGE_LENGTH$1 = 500;
4126
4558
  const canvasRenderPixelLimitSchema = z.number().int().positive();
@@ -4160,7 +4592,10 @@ const canvasRenderSnapshotResultSchema = z.object({
4160
4592
  recordingId: z.uuid(),
4161
4593
  atMs: z.number().int().nonnegative(),
4162
4594
  screenId: z.uuid(),
4163
- screenNodeId: z.string().min(1),
4595
+ /** Null when the snapshot asked for a place only, so no screen layer was added. */
4596
+ screenNodeId: z.string().min(1).nullable(),
4597
+ /** The page the place is on. */
4598
+ pageId: z.string().min(1).optional(),
4164
4599
  viewport: z.object({
4165
4600
  width: z.number().int().positive(),
4166
4601
  height: z.number().int().positive()
@@ -4325,7 +4760,11 @@ const canvasSnapshotRequestSchema = z.strictObject({
4325
4760
  pageId: z.string().min(1).optional(),
4326
4761
  nodeIds: z.array(z.string().min(1))
4327
4762
  }),
4328
- placement: z.strictObject({ kind: z.literal("below-source") })
4763
+ /**
4764
+ * Below the walkthrough: as a screen layer, which installed CLIs ask for, or as a place only,
4765
+ * where the agent's CLI lands an editable frame.
4766
+ */
4767
+ placement: z.strictObject({ kind: z.enum(["below-source", "editable-below-source"]) })
4329
4768
  });
4330
4769
  z.object({
4331
4770
  canvasId: z.uuid(),
@@ -4350,7 +4789,12 @@ const canvasConversionDestinationSchema = z.discriminatedUnion("kind", [
4350
4789
  }),
4351
4790
  z.object({
4352
4791
  kind: z.literal("replace"),
4353
- targetNodeId: z.string().min(1)
4792
+ targetNodeId: z.string().min(1),
4793
+ /**
4794
+ * A capture's swap: the target must still be the capture's picture. When another browser has
4795
+ * already made it editable, the swap is refused as `capture-already-landed`.
4796
+ */
4797
+ onlyPicture: z.literal(true).optional()
4354
4798
  })
4355
4799
  ]);
4356
4800
  const canvasConversionSourceSchema = z.discriminatedUnion("kind", [z.object({
@@ -4582,6 +5026,21 @@ const canvasTextStylesSchema = z.strictObject({
4582
5026
  "text-align": textStyleValues["text-align"].optional(),
4583
5027
  "white-space": textStyleValues["white-space"].optional()
4584
5028
  });
5029
+ /** Every alignment a browser computes, which conversion stores and Undo must be able to put back. */
5030
+ const storedTextAlignSchema = z.enum([
5031
+ "start",
5032
+ "end",
5033
+ "left",
5034
+ "right",
5035
+ "center",
5036
+ "justify",
5037
+ "justify-all",
5038
+ "match-parent",
5039
+ "-webkit-left",
5040
+ "-webkit-right",
5041
+ "-webkit-center"
5042
+ ]);
5043
+ const storedFontStyleSchema = z.union([textStyleValues["font-style"], z.string().regex(/^oblique -?(?:\d+(?:\.\d+)?|\.\d+)deg$/u)]);
4585
5044
  const restorableTextStyleValue = z.union([canvasAdditionalStyleSchema.shape.value, canvasNumberSchema]).nullable().optional();
4586
5045
  const canvasTextStylePatchSchema = z.strictObject({
4587
5046
  "text-decoration": restorableTextStyleValue,
@@ -4604,7 +5063,7 @@ const canvasTextStylePatchSchema = z.strictObject({
4604
5063
  "text-box": canvasAdditionalStyleSchema.shape.value.nullable().optional(),
4605
5064
  "text-box-trim": canvasAdditionalStyleSchema.shape.value.nullable().optional(),
4606
5065
  "text-box-edge": canvasAdditionalStyleSchema.shape.value.nullable().optional(),
4607
- "font-style": textStyleValues["font-style"].nullable().optional(),
5066
+ "font-style": storedFontStyleSchema.nullable().optional(),
4608
5067
  "font-stretch": z.union([z.enum([
4609
5068
  "normal",
4610
5069
  "ultra-condensed",
@@ -4622,14 +5081,22 @@ const canvasTextStylePatchSchema = z.strictObject({
4622
5081
  z.literal("normal")
4623
5082
  ]).nullable().optional(),
4624
5083
  "line-height": textStyleValues["line-height"].nullable().optional(),
4625
- "text-align": textStyleValues["text-align"].nullable().optional(),
5084
+ "text-align": storedTextAlignSchema.nullable().optional(),
4626
5085
  "text-indent": z.union([canvasNumberSchema, signedPixelLengthSchema]).nullable().optional(),
4627
5086
  "white-space": textStyleValues["white-space"].nullable().optional(),
4628
5087
  "word-spacing": z.union([
4629
5088
  canvasNumberSchema,
4630
5089
  signedPixelLengthSchema,
4631
5090
  z.literal("normal")
4632
- ]).nullable().optional()
5091
+ ]).nullable().optional(),
5092
+ direction: restorableTextStyleValue,
5093
+ "unicode-bidi": restorableTextStyleValue,
5094
+ "hanging-punctuation": restorableTextStyleValue,
5095
+ "text-transform": restorableTextStyleValue,
5096
+ "-webkit-text-stroke": restorableTextStyleValue,
5097
+ "-webkit-text-stroke-width": restorableTextStyleValue,
5098
+ "-webkit-text-stroke-color": restorableTextStyleValue,
5099
+ "paint-order": restorableTextStyleValue
4633
5100
  });
4634
5101
  const overflowStyleValue = canvasAdditionalStyleSchema.shape.value;
4635
5102
  const dimensionalStyleValue = z.union([z.string(), canvasNumberSchema]);
@@ -5050,7 +5517,7 @@ const currentCanvasOperationSchema = z.discriminatedUnion("op", [
5050
5517
  removedText: z.record(nodeIdSchema$3, canvasSceneNodeSchema.pick({ props: true })).optional()
5051
5518
  })
5052
5519
  ]);
5053
- /** An older client's compositing write is refused with the CSS that replaces it. */
5520
+ currentCanvasOperationSchema.options;
5054
5521
  /** Each operation's name, for records that may state which kind failed and nothing else. */
5055
5522
  const CANVAS_OPERATION_NAMES = currentCanvasOperationSchema.options.map((option) => option.shape.op.value);
5056
5523
  const canvasOperationSchema = z.preprocess((value, context) => {
@@ -5109,6 +5576,8 @@ const canvasMutationRevisionSchema = z.object({
5109
5576
  operations: z.array(canvasOperationSchema)
5110
5577
  });
5111
5578
  z.object({
5579
+ /** The canvas's web address. An API older than the field answers without it. */
5580
+ url: z.url().optional(),
5112
5581
  mutations: z.array(canvasMutationRevisionSchema).optional(),
5113
5582
  version: z.number().int().min(1),
5114
5583
  /**
@@ -5140,6 +5609,119 @@ z.discriminatedUnion("outcome", [z.object({
5140
5609
  version: z.number().int().min(1),
5141
5610
  document: canvasDocumentBlobSchema
5142
5611
  })]);
5612
+ /** One answer stops taking top layers once it holds this many layers, unless it is asked for more. */
5613
+ const CANVAS_PART_LAYER_LIMIT = 5e3;
5614
+ /** The most layers a read of parts may ask one answer to hold before it stops. */
5615
+ const CANVAS_PART_LAYER_LIMIT_MAX = 1e5;
5616
+ /** The most identifiers one read of parts may name in each list. */
5617
+ const CANVAS_PART_NAMED_LIMIT = 2e3;
5618
+ z.strictObject({ canvasId: z.uuid() });
5619
+ /** The font files a layer inside a top layer declares, without the rest of the layer. */
5620
+ const canvasFontDeclarationSchema = z.object({
5621
+ layerId: z.string(),
5622
+ /** The child of the root that holds the layer. */
5623
+ topLayerId: z.string(),
5624
+ fontFaces: z.array(z.unknown())
5625
+ });
5626
+ z.object({
5627
+ version: z.number().int().min(1),
5628
+ restoreFenceVersion: z.number().int().positive().optional(),
5629
+ /** The root and each child of the root, pages among them, and every removed-layer id. */
5630
+ document: canvasDocumentBlobSchema,
5631
+ screens: z.array(documentScreenSchema),
5632
+ /** Whether the canvas holds more than `LARGE_PAGE_LAYERS` layers, every page counted. */
5633
+ isLarge: z.boolean(),
5634
+ fontDeclarations: z.array(canvasFontDeclarationSchema)
5635
+ });
5636
+ const namedIds = z.array(z.string().min(1)).max(CANVAS_PART_NAMED_LIMIT);
5637
+ z.strictObject({
5638
+ canvasId: z.uuid(),
5639
+ /** Children of the root, answered in this order. */
5640
+ topLayerIds: namedIds.optional(),
5641
+ /** Layers anywhere; each is answered with the whole top layer that holds it. */
5642
+ layerIds: namedIds.optional(),
5643
+ /**
5644
+ * The layers after which the answer takes no further top layer. An editor raises it on a very
5645
+ * large canvas, so the whole canvas arrives in a bounded number of answers.
5646
+ */
5647
+ maxLayers: z.number().int().min(CANVAS_PART_LAYER_LIMIT).max(CANVAS_PART_LAYER_LIMIT_MAX).default(CANVAS_PART_LAYER_LIMIT)
5648
+ }).refine(({ topLayerIds = [], layerIds = [] }) => topLayerIds.length + layerIds.length > 0, "A read of parts names at least one layer.");
5649
+ z.object({
5650
+ /** The revision every layer of the answer was read at. */
5651
+ version: z.number().int().min(1),
5652
+ /** Each answered top layer's own record and every layer inside it: no root, no removed ids. */
5653
+ document: canvasDocumentBlobSchema,
5654
+ /** The top layers answered, in the order asked. */
5655
+ read: z.array(z.string()),
5656
+ /** The top layers left out because the answer was full, in the order asked. */
5657
+ notReached: z.array(z.string()),
5658
+ /** The named identifiers that are no top layer of the canvas, or are inside none. */
5659
+ absent: z.array(z.string())
5660
+ });
5661
+ /** Custom CSS on a text layer that styles its first letter, one declaration per property. */
5662
+ const CANVAS_FIRST_LETTER_PREFIX = "--canvas-first-letter-";
5663
+ const SIDES = [
5664
+ "top",
5665
+ "right",
5666
+ "bottom",
5667
+ "left"
5668
+ ];
5669
+ /**
5670
+ * The properties a first letter takes (CSS Pseudo-Elements 4, `::first-letter`), each with the
5671
+ * value it has when a layer does not declare it: its block's for a property that inherits, the
5672
+ * initial value for one that does not.
5673
+ */
5674
+ const CANVAS_FIRST_LETTER_PROPERTIES = {
5675
+ ...Object.fromEntries([
5676
+ "color",
5677
+ "font-family",
5678
+ "font-size",
5679
+ "font-stretch",
5680
+ "font-style",
5681
+ "font-weight",
5682
+ "font-variant-caps",
5683
+ "font-variant-ligatures",
5684
+ "font-variant-numeric",
5685
+ "font-feature-settings",
5686
+ "font-variation-settings",
5687
+ "font-kerning",
5688
+ "letter-spacing",
5689
+ "line-height",
5690
+ "text-shadow",
5691
+ "text-transform",
5692
+ "word-spacing",
5693
+ "-webkit-text-fill-color",
5694
+ "-webkit-text-stroke-color",
5695
+ "-webkit-text-stroke-width"
5696
+ ].map((property) => [property, "inherit"])),
5697
+ ...Object.fromEntries([
5698
+ "float",
5699
+ "vertical-align",
5700
+ "initial-letter",
5701
+ "opacity",
5702
+ "background-color",
5703
+ "background-image",
5704
+ "box-shadow",
5705
+ "text-decoration-line",
5706
+ "text-decoration-style",
5707
+ "text-decoration-color",
5708
+ "text-decoration-thickness",
5709
+ ...SIDES.flatMap((side) => [
5710
+ `margin-${side}`,
5711
+ `padding-${side}`,
5712
+ `border-${side}-style`,
5713
+ `border-${side}-width`,
5714
+ `border-${side}-color`
5715
+ ]),
5716
+ ...[
5717
+ "top-left",
5718
+ "top-right",
5719
+ "bottom-right",
5720
+ "bottom-left"
5721
+ ].map((corner) => `border-${corner}-radius`)
5722
+ ].map((property) => [property, "initial"]))
5723
+ };
5724
+ `${Object.entries(CANVAS_FIRST_LETTER_PROPERTIES).map(([property, fallback]) => `${property}:var(${CANVAS_FIRST_LETTER_PREFIX}${property},${fallback})`).join(";")}`;
5143
5725
  const textLinkSchema = z.object({
5144
5726
  start: z.number().int().nonnegative(),
5145
5727
  end: z.number().int().positive(),
@@ -5170,13 +5752,28 @@ const canvasPropertySectionSchema = z.enum([
5170
5752
  "export",
5171
5753
  "source"
5172
5754
  ]);
5755
+ const MAX_RENDER_MESSAGE_LENGTH = 500;
5756
+ const MAX_RENDER_KIND_LENGTH = 100;
5757
+ /**
5758
+ * What a layer's box is: `placed` where the canvas draws the layer, `placed-before-transform` where
5759
+ * it draws the layer before the layer's own transform, `recorded` a size kept from when the layer
5760
+ * was made, for a layer the browser lays out.
5761
+ */
5762
+ const canvasBoxSourceSchema = z.enum([
5763
+ "placed",
5764
+ "placed-before-transform",
5765
+ "recorded"
5766
+ ]);
5767
+ /** Present only on a read that holds a `recorded` box. */
5768
+ const boxNoteSchema = z.string().min(1).optional();
5173
5769
  const canvasInspectNodeSummarySchema = z.object({
5174
5770
  id: z.string().min(1),
5175
- label: z.string().max(500),
5176
- kind: z.string().min(1).max(100),
5771
+ label: z.string().max(MAX_RENDER_MESSAGE_LENGTH),
5772
+ kind: z.string().min(1).max(MAX_RENDER_KIND_LENGTH),
5177
5773
  parentId: z.string().min(1).nullable(),
5178
5774
  childCount: z.number().int().min(0),
5179
5775
  box: canvasSceneBoxSchema.nullable(),
5776
+ boxSource: canvasBoxSourceSchema.optional(),
5180
5777
  propertySections: z.array(canvasPropertySectionSchema)
5181
5778
  });
5182
5779
  z.object({ canvasId: z.uuid() });
@@ -5189,13 +5786,15 @@ z.object({
5189
5786
  rootChildCount: z.number().int().min(0),
5190
5787
  bounds: canvasSceneBoxSchema.nullable(),
5191
5788
  kinds: z.record(z.string(), z.number().int().min(0)),
5789
+ boxNote: boxNoteSchema,
5192
5790
  next: z.array(z.string().min(1))
5193
5791
  });
5194
5792
  z.object({ canvasId: z.uuid() });
5195
5793
  z.object({
5196
5794
  canvasId: z.uuid(),
5197
5795
  version: z.number().int().positive(),
5198
- nodes: z.array(canvasInspectNodeSummarySchema)
5796
+ nodes: z.array(canvasInspectNodeSummarySchema),
5797
+ boxNote: boxNoteSchema
5199
5798
  });
5200
5799
  z.object({
5201
5800
  canvasId: z.uuid(),
@@ -5214,14 +5813,54 @@ z.object({
5214
5813
  props: z.record(z.string(), z.unknown()),
5215
5814
  children: z.array(z.string().min(1))
5216
5815
  }),
5816
+ boxNote: boxNoteSchema,
5217
5817
  next: z.array(z.string().min(1))
5218
5818
  });
5819
+ /**
5820
+ * What each operation writes. `names` sets one plain value, places, removes, or merges a patch, so
5821
+ * values its client never knew stay as stored. `whole` brings a whole layer or replaces a whole
5822
+ * group of values, which a client that read the canvas in an older format may have stripped.
5823
+ */
5824
+ const CANVAS_OPERATION_WRITES = {
5825
+ insertConvertedSubtree: "whole",
5826
+ insertNode: "whole",
5827
+ insertText: "names",
5828
+ insertPrototype: "names",
5829
+ setPrototypeDeployment: "names",
5830
+ editText: "names",
5831
+ setText: "names",
5832
+ setBox: "names",
5833
+ setLabel: "names",
5834
+ setContainerKind: "names",
5835
+ setVisibility: "names",
5836
+ setLocked: "names",
5837
+ setConstraints: "names",
5838
+ setStyles: "names",
5839
+ patchExportSettings: "names",
5840
+ setAppearance: "names",
5841
+ setLayout: "whole",
5842
+ patchTypography: "names",
5843
+ setTypography: "whole",
5844
+ patchAdditionalStyles: "names",
5845
+ setAdditionalStyles: "whole",
5846
+ setArtworkColor: "whole",
5847
+ setTextStyleLibrary: "whole",
5848
+ patchFontLibrary: "names",
5849
+ setTextStyle: "whole",
5850
+ setGeometry: "whole",
5851
+ setProps: "whole",
5852
+ setParentage: "names",
5853
+ move: "names",
5854
+ remove: "names"
5855
+ };
5219
5856
  const nodeIdSchema$2 = canvasSceneNodeSchema.shape.id;
5220
5857
  const writableBoxSchema = canvasSceneBoxSchema.extend({
5221
5858
  width: z.number().positive(),
5222
5859
  height: z.number().positive()
5223
5860
  });
5224
5861
  const copiedNodeIdsSchema = z.record(nodeIdSchema$2, nodeIdSchema$2);
5862
+ /** A receipt stored before boxes said what they are holds none, so the source stays optional. */
5863
+ const canvasReceiptBoxSchema = canvasSceneBoxSchema.extend({ boxSource: canvasBoxSourceSchema.optional() });
5225
5864
  const canvasMutationRequestContextSchema = z.strictObject({
5226
5865
  fingerprint: z.string().regex(/^[a-f0-9]{64}$/u),
5227
5866
  revisionPolicy: z.enum(["strict", "rebase"]),
@@ -5235,6 +5874,8 @@ z.object({
5235
5874
  operations: z.array(canvasOperationSchema).min(1),
5236
5875
  requestContext: canvasMutationRequestContextSchema.optional(),
5237
5876
  writeScope: canvasWriteScopeSchema.optional()
5877
+ }).superRefine((input, context) => {
5878
+ refuseUnsafeWriterFormat(input.documentFormatVersion, input.operations.every((operation) => CANVAS_OPERATION_WRITES[operation.op] === "names") ? "names" : "whole", context);
5238
5879
  });
5239
5880
  const applyCanvasOperationsOutputSchema = z.object({
5240
5881
  canvasId: z.uuid(),
@@ -5245,7 +5886,7 @@ const applyCanvasOperationsOutputSchema = z.object({
5245
5886
  insertedNodeIds: z.array(nodeIdSchema$2),
5246
5887
  changedNodeIds: z.array(nodeIdSchema$2),
5247
5888
  removedNodeIds: z.array(nodeIdSchema$2),
5248
- boxes: z.record(nodeIdSchema$2, canvasSceneBoxSchema),
5889
+ boxes: z.record(nodeIdSchema$2, canvasReceiptBoxSchema),
5249
5890
  affectedBounds: writableBoxSchema.nullable(),
5250
5891
  copiedNodeIds: copiedNodeIdsSchema.optional(),
5251
5892
  next: z.array(z.string().min(1))
@@ -5257,7 +5898,8 @@ z.strictObject({
5257
5898
  });
5258
5899
  z.discriminatedUnion("state", [z.strictObject({ state: z.literal("not-found") }), z.strictObject({
5259
5900
  state: z.literal("committed"),
5260
- result: applyCanvasOperationsOutputSchema
5901
+ /** `url` is the canvas's web address. An API older than the field answers without it. */
5902
+ result: applyCanvasOperationsOutputSchema.extend({ url: z.url().optional() })
5261
5903
  })]);
5262
5904
  const LIMITS = {
5263
5905
  nodes: 1e3,
@@ -5654,8 +6296,10 @@ const canvasPreparationRequestSchema = z.discriminatedUnion("kind", [
5654
6296
  sources: z.array(z.strictObject({
5655
6297
  screenId: z.uuid(),
5656
6298
  captureId: z.uuid(),
5657
- label: z.string().min(1)
5658
- })).min(1)
6299
+ /** What the frame is called. Absent, the frame takes the stored page's own title. */
6300
+ label: z.string().min(1).optional()
6301
+ })).min(1),
6302
+ landing: z.literal("editable-frame").optional().describe("Lands the page as an ordinary editable frame. Without it, the layers belong to a capture run.")
5659
6303
  }),
5660
6304
  canvasArrangePreparationSchema,
5661
6305
  canvasDuplicatePreparationSchema,
@@ -5736,7 +6380,11 @@ const canvasPreparationJobSchema = z.discriminatedUnion("state", [
5736
6380
  job.extend({
5737
6381
  state: z.literal("succeeded"),
5738
6382
  phase: z.literal("complete"),
5739
- result: canvasPreparationPlanSchema.extend({ loadedVersion: z.number().int().positive() }),
6383
+ result: canvasPreparationPlanSchema.extend({
6384
+ loadedVersion: z.number().int().positive(),
6385
+ /** Where a screen compile fell back, such as a font it replaced; absent when it had none. */
6386
+ warnings: z.array(canvasRenderWarningSchema).optional()
6387
+ }),
5740
6388
  failure: z.null()
5741
6389
  }),
5742
6390
  job.extend({
@@ -6121,7 +6769,8 @@ z.discriminatedUnion("purpose", [
6121
6769
  "inspection",
6122
6770
  "snapshot",
6123
6771
  "thumbnail",
6124
- "export"
6772
+ "export",
6773
+ "object-pictures"
6125
6774
  ]),
6126
6775
  scale: z.number().positive(),
6127
6776
  maxOutputPixels: canvasRenderPixelLimitSchema.optional(),
@@ -6190,6 +6839,16 @@ z.discriminatedUnion("purpose", [
6190
6839
  sourceState: z.undefined().optional(),
6191
6840
  conversion: canvasConversionRequestSchema,
6192
6841
  scale: z.literal(1)
6842
+ }),
6843
+ claimRenderWorkBaseSchema.extend({
6844
+ purpose: z.literal("object-pictures"),
6845
+ target: canvasRenderTargetSchema,
6846
+ sourceState: z.undefined().optional(),
6847
+ scale: z.number().positive(),
6848
+ maxOutputPixels: canvasRenderPixelLimitSchema.optional(),
6849
+ /** The top layers to draw, in order; each picture is stored under the prefix. */
6850
+ objects: z.array(objectPictureWorkObjectSchema).max(20),
6851
+ outputPrefix: z.string().min(1).max(MAX_STORAGE_KEY_LENGTH)
6193
6852
  })
6194
6853
  ]);
6195
6854
  z.object({
@@ -6334,12 +6993,24 @@ z.object({
6334
6993
  nodes: z.array(canvasInspectNodeSummarySchema),
6335
6994
  contextRootId: nodeIdSchema.nullable(),
6336
6995
  visibleWorldBox: canvasWorldBoundsSchema.nullable(),
6996
+ boxNote: z.string().min(1).optional(),
6337
6997
  next: z.array(z.string().min(1)).max(MAX_SELECTION_COMMANDS)
6338
6998
  });
6339
6999
  const canvasCaptureProvenanceSchema = z.discriminatedUnion("kind", [z.object({
6340
7000
  kind: z.literal("recording"),
6341
7001
  recordingId: z.string()
6342
7002
  })]);
7003
+ /**
7004
+ * The mark on a captured page's picture while it becomes editable. Every capture lands as this
7005
+ * picture first; whoever converts it replaces the same layer with the editable frame, through the
7006
+ * one swap (`insertConvertedSubtree` with destination `replace` and `onlyPicture`). A conversion
7007
+ * that fails writes `failed` with a short reason, so every viewer sees the failure rather than a
7008
+ * spinner that never ends; Try again writes `converting` again.
7009
+ */
7010
+ const captureLandingSchema = z.discriminatedUnion("state", [z.object({ state: z.literal("converting") }), z.object({
7011
+ state: z.literal("failed"),
7012
+ reason: z.string().min(1).max(200)
7013
+ })]);
6343
7014
  z.object({
6344
7015
  html: z.string().optional(),
6345
7016
  viewport: z.object({
@@ -6349,7 +7020,8 @@ z.object({
6349
7020
  atMs: z.number(),
6350
7021
  screenId: z.string().nullable().default(null),
6351
7022
  sourceNodeId: z.string().optional(),
6352
- provenance: canvasCaptureProvenanceSchema.optional()
7023
+ provenance: canvasCaptureProvenanceSchema.optional(),
7024
+ landing: captureLandingSchema.optional()
6353
7025
  });
6354
7026
  z.object({
6355
7027
  provenance: canvasCaptureProvenanceSchema.optional(),
@@ -6473,12 +7145,16 @@ z.object({
6473
7145
  versionId: z.uuid()
6474
7146
  });
6475
7147
  z.object({ entry: canvasVersionEntrySchema });
7148
+ /** A restore or a duplicate copies a version the API holds, so it only names what to change. */
7149
+ const refuseUnsafeVersionCopy = (input, context) => {
7150
+ refuseUnsafeWriterFormat(input.documentFormatVersion, "names", context);
7151
+ };
6476
7152
  z.object({
6477
7153
  canvasId: z.uuid(),
6478
7154
  documentFormatVersion: canvasDocumentFormatSchema,
6479
7155
  versionId: z.uuid(),
6480
7156
  expectedVersion: z.number().int().positive()
6481
- });
7157
+ }).superRefine(refuseUnsafeVersionCopy);
6482
7158
  z.object({
6483
7159
  canvasId: z.uuid(),
6484
7160
  version: z.number().int().positive(),
@@ -6492,7 +7168,7 @@ z.object({
6492
7168
  versionId: z.uuid(),
6493
7169
  organisationId: z.union([z.uuid(), z.literal("personal")]),
6494
7170
  title: z.string().trim().min(1).optional()
6495
- });
7171
+ }).superRefine(refuseUnsafeVersionCopy);
6496
7172
  z.object({
6497
7173
  canvasId: z.uuid(),
6498
7174
  title: z.string().min(1),
@@ -6675,6 +7351,16 @@ const setReviewStateInputSchema = z.object({
6675
7351
  ])
6676
7352
  });
6677
7353
  z.object({ reviewState: setReviewStateInputSchema.shape.reviewState.nullable() });
7354
+ z.object({ canvasId: z.uuid() });
7355
+ z.object({
7356
+ /** The only credential a page receives: it stores captures and does nothing else. */
7357
+ pass: z.string().min(1),
7358
+ expiresAt: z.iso.datetime(),
7359
+ /** Where the capture script is published, for the snippet to load. */
7360
+ scriptUrl: z.url(),
7361
+ /** Where the page stores its capture: the API as the page reaches it. */
7362
+ apiUrl: z.url()
7363
+ });
6678
7364
  /** How many replies a thread hands back in one go before `hasMoreMessages` takes over. */
6679
7365
  const MAX_MESSAGES_PER_THREAD = 50;
6680
7366
  const MAX_MESSAGES_PER_PAGE = 100;
@@ -7956,6 +8642,12 @@ z.object({
7956
8642
  version: z.number().int().positive()
7957
8643
  })]).optional()
7958
8644
  });
8645
+ z.object({ bytes: z.number().int().positive().max(Number.MAX_SAFE_INTEGER) });
8646
+ z.object({
8647
+ id: z.uuid(),
8648
+ upload: signedUploadSchema
8649
+ });
8650
+ z.object({ id: z.uuid() });
7959
8651
  const MAX_PROTOTYPE_CONTENT_TYPE_LENGTH = 200;
7960
8652
  const prototypePathSchema = z.string().min(1).refine((value) => !value.startsWith("/") && !value.endsWith("/") && !value.includes("\\") && !value.includes("\0") && value.split("/").every((part) => part !== "" && part !== "." && part !== ".."), { message: "prototype paths must be portable relative file paths" });
7961
8653
  const prototypeFileSchema = z.object({
@@ -8093,6 +8785,7 @@ z$1.extend(prototypeBridgeConnectRequestSchema, {
8093
8785
  capabilities: z$1.array(z$1.string()),
8094
8786
  release: z$1.string().check(z$1.minLength(1))
8095
8787
  });
8788
+ z$1.extend(prototypeBridgeConnectRequestSchema, { type: z$1.literal("enhance.prototype.capture-blocked") });
8096
8789
  z$1.object({
8097
8790
  protocol: z$1.literal(1),
8098
8791
  type: z$1.literal("enhance.prototype.unloading"),
@@ -8345,6 +9038,21 @@ const HASH_SEEDS = [
8345
9038
  FNV_OFFSET_BASIS ^ MURMUR_HASH_2,
8346
9039
  FNV_OFFSET_BASIS ^ MURMUR_HASH_3
8347
9040
  ];
9041
+ [`[data-enhance-unsupported]:not([data-enhance-unsupported-hidden]):not([style*="display: none"]) {
9042
+ align-items: center !important;
9043
+ background-color: #f7f7f8 !important;
9044
+ background-image: linear-gradient(to top right, transparent calc(50% - 1px), #a8a8b0 50%, transparent calc(50% + 1px)), linear-gradient(to bottom right, transparent calc(50% - 1px), #a8a8b0 50%, transparent calc(50% + 1px)) !important;
9045
+ border: 1px solid #c7c7cc !important;
9046
+ box-sizing: border-box !important;
9047
+ color: #4f4f55 !important;
9048
+ display: flex !important;
9049
+ font: 500 14px/1.4 Inter, ui-sans-serif, system-ui, sans-serif !important;
9050
+ justify-content: center !important;
9051
+ overflow: hidden !important;
9052
+ text-align: center !important;
9053
+ }`, `[data-enhance-unsupported-hidden], [data-enhance-unsupported][style*="display: none"] {
9054
+ display: none !important;
9055
+ }`].join("\n");
8348
9056
  const viewportSchema = z.object({
8349
9057
  width: z.number().int().positive(),
8350
9058
  height: z.number().int().positive()
@@ -8609,21 +9317,6 @@ z.object({
8609
9317
  /** Screens survive with their provenance nulled. That is what makes iteration safe. */
8610
9318
  detachedScreenCount: z.number().int().min(0)
8611
9319
  });
8612
- [`[data-enhance-unsupported]:not([data-enhance-unsupported-hidden]):not([style*="display: none"]) {
8613
- align-items: center !important;
8614
- background-color: #f7f7f8 !important;
8615
- background-image: linear-gradient(to top right, transparent calc(50% - 1px), #a8a8b0 50%, transparent calc(50% + 1px)), linear-gradient(to bottom right, transparent calc(50% - 1px), #a8a8b0 50%, transparent calc(50% + 1px)) !important;
8616
- border: 1px solid #c7c7cc !important;
8617
- box-sizing: border-box !important;
8618
- color: #4f4f55 !important;
8619
- display: flex !important;
8620
- font: 500 14px/1.4 Inter, ui-sans-serif, system-ui, sans-serif !important;
8621
- justify-content: center !important;
8622
- overflow: hidden !important;
8623
- text-align: center !important;
8624
- }`, `[data-enhance-unsupported-hidden], [data-enhance-unsupported][style*="display: none"] {
8625
- display: none !important;
8626
- }`].join("\n");
8627
9320
  z.object({
8628
9321
  /**
8629
9322
  * Client-minted, once per capture attempt. A retry is the same screen; a re-capture at the
@@ -8647,6 +9340,8 @@ z.object({
8647
9340
  });
8648
9341
  z.object({
8649
9342
  screenId: z.uuid(),
9343
+ /** Where the screen's files are stored; a capture names its stored copies by it. */
9344
+ assetBundleId: z.uuid().nullable(),
8650
9345
  /** Re-issued on every call, because the usual reason for a retry is an expired presign. */
8651
9346
  upload: signedUploadSchema,
8652
9347
  alreadyExists: z.boolean(),
@@ -8928,7 +9623,9 @@ const clientRenderFailureDetailsSchema = z.strictObject({
8928
9623
  "clipboard-unavailable",
8929
9624
  "clipboard-image-pending",
8930
9625
  "clipboard-image-unavailable",
9626
+ "paste-content-refused",
8931
9627
  "edit-target-unsupported",
9628
+ "edit-result-invalid",
8932
9629
  "react-hook-order",
8933
9630
  "menu-rows-unsupported"
8934
9631
  ]),
@@ -8964,6 +9661,7 @@ const clientRenderFailureDetailsSchema = z.strictObject({
8964
9661
  subsystem: z.enum([
8965
9662
  "menu",
8966
9663
  "menu-picture",
9664
+ "arrival-cue",
8967
9665
  "unknown"
8968
9666
  ]).optional(),
8969
9667
  repeats: count$1.optional(),
@@ -9034,7 +9732,18 @@ const CANVAS_SYNC_REPORTS = [
9034
9732
  "whole-value-text",
9035
9733
  "retrying",
9036
9734
  "recovery",
9037
- "trace"
9735
+ "trace",
9736
+ "update-required"
9737
+ ];
9738
+ /** How a failed document read was answered, on the report of one worth a look. */
9739
+ const CANVAS_SYNC_READ_OUTCOMES = [
9740
+ "transient",
9741
+ "no-edit-access",
9742
+ "restored",
9743
+ "replan",
9744
+ "refused",
9745
+ "update-required",
9746
+ "fault"
9038
9747
  ];
9039
9748
  const CANVAS_SYNC_DETAILS = [
9040
9749
  ...CLIENT_SAVE_ISSUES,
@@ -9071,7 +9780,8 @@ const CANVAS_SYNC_REPORT_STATUSES = [
9071
9780
  "view-only",
9072
9781
  "sign-in",
9073
9782
  "gone",
9074
- "restored"
9783
+ "restored",
9784
+ "update-required"
9075
9785
  ];
9076
9786
  /** Whether a recovery state began in this visit or was reopened from the browser copy. */
9077
9787
  const CANVAS_SYNC_EPISODES = ["new", "reopened"];
@@ -9113,6 +9823,7 @@ const CANVAS_SAVE_NOTICE_CAUSES = [
9113
9823
  "refused",
9114
9824
  "copy-refused",
9115
9825
  "copy-preview",
9826
+ "update-required",
9116
9827
  "unknown"
9117
9828
  ];
9118
9829
  const CANVAS_SAVE_SEVERITIES = [
@@ -9136,7 +9847,8 @@ const CANVAS_SAVE_ACTIONS = [
9136
9847
  "retry-upload",
9137
9848
  "choose-file",
9138
9849
  "remove-screen",
9139
- "go-to-canvases"
9850
+ "go-to-canvases",
9851
+ "reload"
9140
9852
  ];
9141
9853
  const CANVAS_SAVE_OUTCOMES = [
9142
9854
  "saved",
@@ -9230,6 +9942,7 @@ z.strictObject({
9230
9942
  durationMs: z.number().int().nonnegative(),
9231
9943
  pendingChanges: z.number().int().nonnegative(),
9232
9944
  reason: z.enum(CANVAS_SYNC_DETAILS).optional(),
9945
+ readOutcome: z.enum(CANVAS_SYNC_READ_OUTCOMES).optional(),
9233
9946
  status: z.enum(CANVAS_SYNC_REPORT_STATUSES).optional(),
9234
9947
  episode: z.enum(CANVAS_SYNC_EPISODES).optional(),
9235
9948
  trace: canvasSaveTraceSchema.optional()
@@ -9240,7 +9953,8 @@ z.object({
9240
9953
  "delivered",
9241
9954
  "failed",
9242
9955
  "disabled",
9243
- "no-identity"
9956
+ "no-identity",
9957
+ "expired"
9244
9958
  ]).optional()
9245
9959
  });
9246
9960
  z.discriminatedUnion("type", [z.object({ type: z.literal("enhance3:extension-probe") }).strict(), z.object({ type: z.literal("enhance3:extension-present") }).strict()]);
@@ -9445,8 +10159,8 @@ z.discriminatedUnion("name", [
9445
10159
  z.object({ accepted: z.literal(true) });
9446
10160
  const listed = (allowed, value) => typeof value === "string" && allowed.includes(value) ? value : null;
9447
10161
  const refusalOf = (error) => {
9448
- const { refusalCode, operation, component } = error.fields ?? {};
9449
- if (refusalCode === void 0 && operation === void 0 && component === void 0) return void 0;
10162
+ const { refusalCode, operation, component, operationIndex } = error.fields ?? {};
10163
+ if (refusalCode === void 0 && operation === void 0 && component === void 0 && operationIndex === void 0) return void 0;
9450
10164
  const code = CANVAS_SAVE_REFUSAL_CODES.find((value) => value === refusalCode);
9451
10165
  return {
9452
10166
  refusalCode: refusalCode === void 0 ? "unclassified" : code ?? "unknown",
@@ -9458,6 +10172,15 @@ const refusalOf = (error) => {
9458
10172
  const MUTATION_ID_REUSED = "mutation-id-reused";
9459
10173
  /** `fields.reason` on a 413, whether the server's envelope or a proxy's bare status says so. */
9460
10174
  const REQUEST_TOO_LARGE = "request-too-large";
10175
+ const tooLarge = {
10176
+ kind: "refused",
10177
+ reason: REQUEST_TOO_LARGE,
10178
+ refusal: {
10179
+ refusalCode: REQUEST_TOO_LARGE,
10180
+ operation: "unknown",
10181
+ component: "unknown"
10182
+ }
10183
+ };
9461
10184
  const HTTP_UNAUTHORIZED = 401;
9462
10185
  const HTTP_FORBIDDEN$1 = 403;
9463
10186
  const HTTP_NOT_FOUND = 404;
@@ -9492,17 +10215,15 @@ const conflictOutcome = (error) => {
9492
10215
  reason: error.message
9493
10216
  };
9494
10217
  };
9495
- /** The server names the two refusals a client must tell apart; any other is the message. */
10218
+ /** The server names the refusals a client must tell apart; any other is the message. */
9496
10219
  const badRequestOutcome = (error) => {
9497
10220
  const reason = error.fields?.["reason"];
9498
10221
  if (reason === "mutation-id-reused") return {
9499
10222
  kind: "fault",
9500
10223
  detail: MUTATION_ID_REUSED
9501
10224
  };
9502
- if (reason === "request-too-large") return {
9503
- kind: "refused",
9504
- reason: REQUEST_TOO_LARGE
9505
- };
10225
+ if (reason === "request-too-large") return tooLarge;
10226
+ if (error.fields?.["documentFormatVersion"] === "This change needs a newer version of Enhance. Refresh the editor, or update the Enhance plugin or command-line tool, then try again.") return { kind: "update-required" };
9506
10227
  const refusal = refusalOf(error);
9507
10228
  return {
9508
10229
  kind: "refused",
@@ -9534,10 +10255,7 @@ const statusOutcome = (status, retryAfterMs) => {
9534
10255
  };
9535
10256
  if (status === HTTP_FORBIDDEN$1) return { kind: "no-edit-access" };
9536
10257
  if (status === HTTP_NOT_FOUND) return { kind: "gone" };
9537
- if (status === HTTP_TOO_LARGE) return {
9538
- kind: "refused",
9539
- reason: REQUEST_TOO_LARGE
9540
- };
10258
+ if (status === HTTP_TOO_LARGE) return tooLarge;
9541
10259
  if (status === HTTP_TIMEOUT || status === HTTP_TOO_MANY_REQUESTS || status === HTTP_CLIENT_CLOSED || status >= HTTP_SERVER_ERROR) return {
9542
10260
  kind: "transient",
9543
10261
  retryAfterMs
@@ -9744,7 +10462,7 @@ const startStallWatch = (caller, idleMs = STALL_MS) => {
9744
10462
  };
9745
10463
 
9746
10464
  //#endregion
9747
- //#region ../../packages/sdk/dist/capture-client.client-Dztj8uko.mjs
10465
+ //#region ../../packages/sdk/dist/capture-client.client-C_8yINru.mjs
9748
10466
  const line = (text) => `Enhance: ${text}\n`;
9749
10467
  /** A left-out capture by its journey and step, or by its test when it could not be read at all. */
9750
10468
  const leftOutName = (leftOut, attempts) => {
@@ -10256,7 +10974,7 @@ const createEnhance = (options) => {
10256
10974
  //#region src/infrastructure/captures.program.ts
10257
10975
  const publicationError = (error, manifest) => {
10258
10976
  const code = error instanceof Error ? Reflect.get(error, "code") : void 0;
10259
- return new CliError(code === "authorization" ? "UNAUTHORIZED" : code === "conflict" ? "CONFLICT" : ["configuration", "artifact"].includes(String(code)) ? "BAD_REQUEST" : "INTERNAL", error instanceof Error ? error.message : "Capture publication was not confirmed.", `Retry enhance captures publish with the same manifest: ${manifest}`);
10977
+ return new CliError(code === "authorization" ? "UNAUTHORIZED" : code === "conflict" ? "CONFLICT" : ["configuration", "artifact"].includes(String(code)) ? "BAD_REQUEST" : "INTERNAL", error instanceof Error ? error.message : "Capture publication was not confirmed.", code === "artifact" ? "The manifest or a capture file beside it cannot be published as it is. Correct what the message names, or capture again and publish the new manifest." : `Retry enhance captures publish with the same manifest: ${manifest}`);
10260
10978
  };
10261
10979
  const registerCapturesProgram = (program, dependencies) => {
10262
10980
  program.command("captures").description("Publish SDK captures as editable canvas journeys.").command("publish <manifest>").description("Publish or resume a reserved capture manifest and print its durable receipt.").action(async (manifest) => {
@@ -10278,8 +10996,6 @@ const registerCapturesProgram = (program, dependencies) => {
10278
10996
  //#region src/infrastructure/command-summaries.consts.ts
10279
10997
  const COMMAND_SUMMARIES = {
10280
10998
  "captureRun.review": "Read product review for a run canvas.",
10281
- "canvas chats": "Chat history.",
10282
- "canvas.createEditableFrame": "Make a screen editable.",
10283
10999
  "canvas.create": "Create a canvas.",
10284
11000
  "canvas.get": "Read a canvas and access.",
10285
11001
  "canvas.setAccess": "Change canvas link access.",
@@ -10296,8 +11012,6 @@ const COMMAND_SUMMARIES = {
10296
11012
  "canvas.tree": "Read the node hierarchy.",
10297
11013
  "canvas.node": "Read a node and children.",
10298
11014
  "canvas.selection": "Read the live selection.",
10299
- "canvas asset": "Manage uploaded assets.",
10300
- "canvas mutation": "Read mutation receipts.",
10301
11015
  "canvas apply": "Apply canvas operations.",
10302
11016
  "canvas find": "Find accessible canvases.",
10303
11017
  "canvas remove": "Remove scoped subtrees.",
@@ -10308,6 +11022,7 @@ const COMMAND_SUMMARIES = {
10308
11022
  "canvas insert-html": "Insert compiled HTML.",
10309
11023
  "canvas make-editable": "Convert a captured screen.",
10310
11024
  "canvas capture": "Capture a recording moment.",
11025
+ "canvas capture-page": "Capture a page you opened.",
10311
11026
  "canvas arrange": "Arrange canvas objects.",
10312
11027
  "canvas duplicate-nodes": "Duplicate node subtrees.",
10313
11028
  "canvas text-style-library": "Manage text styles.",
@@ -10319,6 +11034,104 @@ const COMMAND_SUMMARIES = {
10319
11034
  "canvas invites": "Invite people to a canvas."
10320
11035
  };
10321
11036
 
11037
+ //#endregion
11038
+ //#region src/infrastructure/input-spellings.lib.ts
11039
+ const CANVAS = "--canvas";
11040
+ const CANVAS_ID = "--canvas-id";
11041
+ const VERSION_SPELLINGS = ["--base-version", "--expected-version"];
11042
+ /** Options a command cannot run without, which the tool checks once either spelling is read. */
11043
+ const REQUIRED_SPELLINGS = /* @__PURE__ */ new WeakSet();
11044
+ /** Whether the command needs this option or the other spelling of it. */
11045
+ const isRequiredSpelling = (option) => REQUIRED_SPELLINGS.has(option);
11046
+ const optionOf = (command, long) => command.options.find((option) => option.long === long);
11047
+ const isGiven = (command, option) => command.getOptionValueSource(option.attributeName()) === "cli";
11048
+ /** Hands one spelling's value to the option the command's action reads, and forgets the first. */
11049
+ const moveValue = (command, from, to, value) => {
11050
+ command.setOptionValueWithSource(to.attributeName(), value, "cli");
11051
+ Reflect.deleteProperty(command.opts(), from.attributeName());
11052
+ };
11053
+ /** Puts `second` straight after `first` in help, wherever each was added. */
11054
+ const placeTogether = (command, first, second) => {
11055
+ const others = command.options.filter((option) => option !== first && option !== second);
11056
+ const at = Math.min(...[first, second].map((option) => command.options.indexOf(option)).filter((i) => i >= 0));
11057
+ Reflect.set(command, "options", [
11058
+ ...others.slice(0, at),
11059
+ first,
11060
+ second,
11061
+ ...others.slice(at)
11062
+ ]);
11063
+ };
11064
+ /**
11065
+ * Commander refuses a missing mandatory option before any hook runs, so an option with a second
11066
+ * spelling is checked here instead, after either spelling has had its chance.
11067
+ */
11068
+ const requireEither = (shown, other) => {
11069
+ const wasMandatory = shown.mandatory || other.mandatory;
11070
+ shown.makeOptionMandatory(false);
11071
+ other.makeOptionMandatory(false);
11072
+ if (wasMandatory) REQUIRED_SPELLINGS.add(shown);
11073
+ };
11074
+ const refuseMissing = (command, shown, other) => {
11075
+ if (!isRequiredSpelling(shown) || isGiven(command, shown) || isGiven(command, other)) return;
11076
+ if (command.getOptionValueSource("json") === "cli") return;
11077
+ throw new CliError("BAD_REQUEST", `${String(shown.long)} is required.`, `Pass ${String(shown.long)}, or ${String(other.long)} in its place.`);
11078
+ };
11079
+ /** Runs `read` before the command's own action, and never for a subcommand of it. */
11080
+ const beforeAction = (command, read) => {
11081
+ command.hook("preAction", (_hooked, actionCommand) => {
11082
+ if (actionCommand === command) read();
11083
+ });
11084
+ };
11085
+ const acceptCanvasSpellings = (command) => {
11086
+ const ownCanvas = optionOf(command, CANVAS);
11087
+ const ownCanvasId = optionOf(command, CANVAS_ID);
11088
+ if (ownCanvas === void 0 && ownCanvasId === void 0) return;
11089
+ const canvas = ownCanvas ?? new Option(`${CANVAS} <url-or-id>`, "Canvas URL, the `/c/<id>` path `enhance canvas find` returns, or canvas id.");
11090
+ const canvasId = ownCanvasId ?? new Option(`${CANVAS_ID} <id>`, `Canvas id alone. Accepted in place of ${CANVAS}.`);
11091
+ if (ownCanvas === void 0) command.addOption(canvas);
11092
+ if (ownCanvasId === void 0) command.addOption(canvasId);
11093
+ else canvasId.description = `${canvasId.description} Accepted in place of ${CANVAS}.`.trim();
11094
+ placeTogether(command, canvas, canvasId);
11095
+ requireEither(canvas, canvasId);
11096
+ beforeAction(command, () => {
11097
+ if (isGiven(command, canvas) && isGiven(command, canvasId)) throw new CliError("BAD_REQUEST", `${CANVAS} and ${CANVAS_ID} cannot be combined.`, `Pass the canvas once, through ${CANVAS}.`);
11098
+ refuseMissing(command, canvas, canvasId);
11099
+ if (ownCanvas !== void 0) {
11100
+ if (isGiven(command, canvasId)) moveValue(command, canvasId, canvas, command.getOptionValue(canvasId.attributeName()));
11101
+ return;
11102
+ }
11103
+ const reference = command.getOptionValue(canvas.attributeName());
11104
+ if (typeof reference === "string") moveValue(command, canvas, canvasId, fromCanvasReference(reference));
11105
+ });
11106
+ };
11107
+ const acceptVersionSpellings = (command) => {
11108
+ const [base, expected] = VERSION_SPELLINGS.map((long) => optionOf(command, long));
11109
+ const own = base ?? expected;
11110
+ if (own?.long === void 0 || base !== void 0 && expected !== void 0) return;
11111
+ const otherLong = VERSION_SPELLINGS.find((long) => long !== own.long) ?? own.long;
11112
+ const other = new Option(`${otherLong} ${own.flags.split(" ").slice(1).join(" ")}`, `Accepted in place of ${own.long}.`);
11113
+ if (own.parseArg !== void 0) other.argParser(own.parseArg);
11114
+ command.addOption(other);
11115
+ placeTogether(command, own, other);
11116
+ requireEither(own, other);
11117
+ beforeAction(command, () => {
11118
+ refuseMissing(command, own, other);
11119
+ if (!isGiven(command, other)) return;
11120
+ const given = command.getOptionValue(other.attributeName());
11121
+ if (isGiven(command, own) && String(command.getOptionValue(own.attributeName())) !== String(given)) throw new CliError("BAD_REQUEST", `${own.long ?? ""} and ${otherLong} name the same version and were given different values.`, "Pass the version once.");
11122
+ moveValue(command, other, own, given);
11123
+ });
11124
+ };
11125
+ /**
11126
+ * Gives a command the second spelling of each input it takes under one: a canvas as `--canvas`
11127
+ * and `--canvas-id`, and the version it expects as `--base-version` and `--expected-version`. The
11128
+ * command's action still reads the option it was written with.
11129
+ */
11130
+ const acceptInputSpellings = (command) => {
11131
+ acceptCanvasSpellings(command);
11132
+ acceptVersionSpellings(command);
11133
+ };
11134
+
10322
11135
  //#endregion
10323
11136
  //#region src/infrastructure/option-string.mapper.ts
10324
11137
  const toBareStringOption = (option, canAcceptNull = false) => {
@@ -10357,11 +11170,14 @@ const REQUIRED_OPTIONS = /* @__PURE__ */ new Map([
10357
11170
  ["screen.create --provenance", null],
10358
11171
  ["screen.create --route", null],
10359
11172
  ["screen.create --viewport", null],
11173
+ ["canvas.duplicate --organisation-id", null],
11174
+ ["canvas.move --organisation-id", null],
11175
+ ["canvas.version.name --target", null],
11176
+ ["canvas.document.save --document", null],
11177
+ ["canvas.copyWalkthroughs --recording-ids", null],
11178
+ ["comment.start --anchor", null],
11179
+ ["comment.move --anchor", null],
10360
11180
  ["canvas render --canvas", "--input"],
10361
- ["canvas.inspect --canvas", "--canvas-id"],
10362
- ["canvas.tree --canvas", "--canvas-id"],
10363
- ["canvas.node --canvas", "--canvas-id"],
10364
- ["canvas.selection --canvas", "--canvas-id"],
10365
11181
  ["canvas read --canvas", "--input"],
10366
11182
  ["canvas duplicate-nodes --canvas", "--input"],
10367
11183
  ["canvas duplicate-nodes --base-version", "--input"],
@@ -10391,13 +11207,20 @@ const refusalFor = ({ option, replacement }) => {
10391
11207
  return replacement === null ? new CliError("BAD_REQUEST", `${flag} is required unless --json supplies the complete input.`, `Pass ${flag} explicitly, including false or null when that is the intended value.`) : new CliError("BAD_REQUEST", `${flag} is required unless ${replacement.long ?? replacement.flags} is given.`, `Pass ${flag}, or use ${replacement.long ?? replacement.flags} instead.`);
10392
11208
  };
10393
11209
  /**
10394
- * States each replaceable requirement in the option's help, and refuses a command that has neither
10395
- * the option nor its replacement on the command line.
11210
+ * The API's commands print a value that is one of several kinds, or an object, as optional:
11211
+ * `[value]`, `[json]`, `[values...]`. Help shows a required one as every other required flag.
11212
+ */
11213
+ const shownAsRequired = (flags) => flags.replace(/\[([^\]]+)\]$/u, (_whole, name) => `<${name}>`);
11214
+ /**
11215
+ * Shows each requirement in the option's help: a replaceable one in its description, and one that
11216
+ * nothing replaces in its flags. Refuses a command that has neither the option nor its replacement
11217
+ * on the command line.
10396
11218
  */
10397
11219
  const requireOptions = (command, scope) => {
10398
11220
  const required = requiredOptionsOf(command, scope);
10399
11221
  if (required.length === 0) return;
10400
- for (const { option, replacement } of required) if (replacement !== null) option.description = `${option.description} Required unless ${replacement.long ?? replacement.flags} is given.`;
11222
+ for (const { option, replacement } of required) if (replacement === null) option.flags = shownAsRequired(option.flags);
11223
+ else option.description = `${option.description} Required unless ${replacement.long ?? replacement.flags} is given.`;
10401
11224
  command.hook("preAction", (_hookedCommand, actionCommand) => {
10402
11225
  if (actionCommand !== command) return;
10403
11226
  if (actionCommand.getOptionValueSource("json") === "cli") return;
@@ -10411,13 +11234,15 @@ const requireOptions = (command, scope) => {
10411
11234
  //#region src/infrastructure/cli-polish.lib.ts
10412
11235
  const NAMESPACES = {
10413
11236
  "canvas text-style-library": "Find, read, and publish reusable text styles across canvases.",
10414
- "canvas chats": "Inspect and manage authorized canvas chat history.",
10415
11237
  canvas: "Create, find, share and manage canvases.",
10416
11238
  "canvas render": "Render production-faithful canvas pixels after inspecting exact structure and geometry.",
10417
11239
  "canvas version": "Inspect and name retained canvas history.",
10418
11240
  "canvas document": "Read or replace the opaque document stored on a canvas.",
10419
11241
  "canvas invites": "Invite people to a canvas and manage pending invitations.",
10420
11242
  "canvas participants": "List and change the people who can reach a canvas.",
11243
+ "canvas realtime": "Tell the people on a canvas that an agent is at work on it.",
11244
+ "canvas realtime activity": "Begin, renew and end the indicator that an agent is working on a canvas.",
11245
+ "capture-run": "Review what a capture run changed against its baseline.",
10421
11246
  comment: "Comment threads and replies anchored to canvas content.",
10422
11247
  organisation: "Teams the authenticated person belongs to or creates.",
10423
11248
  "organisation invites": "Invite people to a team and manage pending invitations.",
@@ -10426,8 +11251,24 @@ const NAMESPACES = {
10426
11251
  "person recipients": "People available when choosing sharing recipients.",
10427
11252
  recording: "Recorded walkthroughs, chunks, recovery, and completion.",
10428
11253
  "recording-asset": "External page assets mirrored for durable replay.",
10429
- screen: "Captured pages uploaded for placement on a canvas."
10430
- };
11254
+ screen: "Captured pages uploaded for placement on a canvas.",
11255
+ transcript: "Read what was said in a recorded walkthrough, and retry a failed transcription."
11256
+ };
11257
+ /** Commands that do one job from different inputs, each with the sentence that names the other. */
11258
+ const TWINS = {
11259
+ "canvas delete-nodes": "`enhance canvas remove` does the same with a JSON input.",
11260
+ "canvas remove": "`enhance canvas delete-nodes` does the same with flags.",
11261
+ "prototype publish": "`enhance canvas publish-prototype` does the same with a JSON input.",
11262
+ "canvas publish-prototype": "`enhance prototype publish` does the same with flags.",
11263
+ "canvas work begin": "`enhance canvas realtime activity begin` does the same.",
11264
+ "canvas work update": "`enhance canvas realtime activity renew` does the same.",
11265
+ "canvas finish-working-on-nodes": "`enhance canvas realtime activity end` does the same.",
11266
+ "canvas realtime activity begin": "`enhance canvas work begin` does the same.",
11267
+ "canvas realtime activity renew": "`enhance canvas work update` does the same.",
11268
+ "canvas realtime activity end": "`enhance canvas finish-working-on-nodes` does the same."
11269
+ };
11270
+ const DEFAULT_HELP_WIDTH = 80;
11271
+ const LONG_ANSWER_NOTE = "An answer with a line over 2,000 characters, or over 25,000 in all, is written to a file. The tool prints the path of that file with its characters and records in its place: read the file.";
10431
11272
  const STDIN_TOKEN_PROCEDURES = /* @__PURE__ */ new Set([
10432
11273
  "canvas.invites.accept",
10433
11274
  "canvas.invites.preview",
@@ -10444,16 +11285,18 @@ const NULL_LITERAL_OPTIONS = /* @__PURE__ */ new Set([
10444
11285
  "screen.create --route"
10445
11286
  ]);
10446
11287
  const asRecord$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? Object.fromEntries(Object.entries(value)) : null;
10447
- const procedurePathOf$2 = (command) => {
11288
+ const procedurePathOf$3 = (command) => {
10448
11289
  const details = asRecord$1(Reflect.get(command, "__trpcCli"));
10449
11290
  const path = details === null ? void 0 : details["path"];
10450
11291
  return typeof path === "string" ? path : null;
10451
11292
  };
10452
11293
  const optionDescription = (command, option, generated, commandPath) => {
10453
11294
  const longName = option.long;
10454
- const scope = procedurePathOf$2(command) ?? commandPath.join(" ");
11295
+ const procedurePath = procedurePathOf$3(command);
11296
+ const scope = procedurePath ?? commandPath.join(" ");
10455
11297
  const specific = scope === "" || longName === void 0 ? void 0 : OPTION_DESCRIPTIONS[`${scope} ${longName}`];
10456
11298
  if (specific !== void 0) return specific;
11299
+ if (procedurePath === null && generated.trim() !== "") return generated;
10457
11300
  if (longName !== void 0 && OPTION_DESCRIPTIONS[longName] !== void 0) return OPTION_DESCRIPTIONS[longName];
10458
11301
  const useful = (generated.split(/Any of:|One of:/u, 1)[0]?.trim() ?? "").split(";").map((part) => part.trim()).filter((part) => part !== "" && [
10459
11302
  "Format:",
@@ -10472,7 +11315,7 @@ const configureCommand = (command, input, commandPath) => {
10472
11315
  });
10473
11316
  command.showHelpAfterError(false).showSuggestionAfterError(false);
10474
11317
  const explicitNulls = [];
10475
- const scope = procedurePathOf$2(command) ?? commandPath.join(" ");
11318
+ const scope = procedurePathOf$3(command) ?? commandPath.join(" ");
10476
11319
  for (const option of command.options) {
10477
11320
  option.description = optionDescription(command, option, option.description, commandPath);
10478
11321
  const canAcceptNull = NULL_LITERAL_OPTIONS.has(`${scope} ${option.long ?? ""}`);
@@ -10485,6 +11328,7 @@ const configureCommand = (command, input, commandPath) => {
10485
11328
  if (explicitNulls.length > 0) command.hook("preAction", (actionCommand) => {
10486
11329
  for (const explicitNull of explicitNulls) if (explicitNull.matches(actionCommand.getOptionValue(explicitNull.name))) actionCommand.setOptionValueWithSource(explicitNull.name, null, "cli");
10487
11330
  });
11331
+ acceptInputSpellings(command);
10488
11332
  requireOptions(command, scope);
10489
11333
  };
10490
11334
  const prepareMutation = (command, commandPath, procedurePath, input) => {
@@ -10513,12 +11357,21 @@ const describe = (command, commandPath, procedurePath, descriptions) => {
10513
11357
  else if (procedurePath !== null) command.description(PROCEDURE_DESCRIPTIONS[procedurePath] ?? descriptions.get(procedurePath) ?? `Run the ${procedurePath} API operation.`);
10514
11358
  const summary = COMMAND_SUMMARIES[commandPath.join(" ")] ?? (procedurePath === null ? void 0 : COMMAND_SUMMARIES[procedurePath]);
10515
11359
  if (summary !== void 0) command.summary(summary);
11360
+ const twin = TWINS[commandPath.join(" ")];
11361
+ if (twin === void 0) return;
11362
+ if (command.summary() === "") command.summary(command.description());
11363
+ command.description(`${command.description()} ${twin}`);
11364
+ };
11365
+ /** Says once, in the tool's own help, where a long answer goes. */
11366
+ const noteLongAnswers = (program) => {
11367
+ program.configureHelp({ formatHelp: (command, helper) => `${Help.prototype.formatHelp.call(helper, command, helper)}\n${helper.boxWrap(LONG_ANSWER_NOTE, helper.helpWidth ?? DEFAULT_HELP_WIDTH)}\n` });
10516
11368
  };
10517
11369
  const polishCli = (command, input, path = []) => {
10518
11370
  configureCommand(command, input, path);
11371
+ if (path.length === 0) noteLongAnswers(command);
10519
11372
  for (const child of command.commands) {
10520
11373
  const commandPath = [...path, child.name()];
10521
- const procedurePath = procedurePathOf$2(child);
11374
+ const procedurePath = procedurePathOf$3(child);
10522
11375
  prepareMutation(child, commandPath, procedurePath, input);
10523
11376
  describe(child, commandPath, procedurePath, input.descriptions);
10524
11377
  prepareStdinToken(child, commandPath, procedurePath);
@@ -10529,30 +11382,128 @@ const polishCli = (command, input, path = []) => {
10529
11382
  //#endregion
10530
11383
  //#region src/infrastructure/cli-surface.lib.ts
10531
11384
  const CLI_EXCLUDED_PROCEDURES = createCapabilityPolicyAdapter().excludedProcedures;
10532
- const CLI_EXCLUDED_NAMESPACES = /* @__PURE__ */ new Set([
10533
- "canvas thumbnail",
10534
- "canvas font-catalog",
10535
- "telemetry"
10536
- ]);
10537
- const procedurePathOf$1 = (command) => {
11385
+ /** The list trpc-cli writes into a group's description when it builds the group. */
11386
+ const SUBCOMMAND_LIST = /Available subcommands: .*$/u;
11387
+ const procedurePathOf$2 = (command) => {
10538
11388
  const details = Reflect.get(command, "__trpcCli");
10539
11389
  if (typeof details !== "object" || details === null) return null;
10540
11390
  const path = Reflect.get(details, "path");
10541
11391
  return typeof path === "string" ? path : null;
10542
11392
  };
10543
- const removeExcludedProcedures = (command, path = []) => {
10544
- const visible = command.commands.filter((child) => {
10545
- const procedure = procedurePathOf$1(child);
10546
- const commandPath = [...path, child.name()].join(" ");
10547
- return !CLI_EXCLUDED_NAMESPACES.has(commandPath) && (procedure === null || !CLI_EXCLUDED_PROCEDURES.has(procedure));
11393
+ /**
11394
+ * Leaves only what an agent can run: removes each command whose procedure is not offered, then
11395
+ * each group that is left with no command, so a group is never a command that does nothing.
11396
+ */
11397
+ const removeExcludedProcedures = (command) => {
11398
+ const offered = command.commands.filter((child) => {
11399
+ const procedure = procedurePathOf$2(child);
11400
+ if (procedure !== null) return !CLI_EXCLUDED_PROCEDURES.has(procedure);
11401
+ const isGroup = child.commands.length > 0;
11402
+ removeExcludedProcedures(child);
11403
+ return !isGroup || child.commands.length > 0;
10548
11404
  });
10549
- Reflect.set(command, "commands", visible);
10550
- for (const child of visible) removeExcludedProcedures(child, [...path, child.name()]);
11405
+ Reflect.set(command, "commands", offered);
11406
+ const names = offered.map((child) => child.name()).join(", ");
11407
+ command.description(command.description().replace(SUBCOMMAND_LIST, () => `Available subcommands: ${names}`));
11408
+ };
11409
+
11410
+ //#endregion
11411
+ //#region src/infrastructure/command-examples.consts.ts
11412
+ const CANVAS_RENDER_EXAMPLE = "canvas render --canvas 0b9f4c1e-5d2a-4e8b-9c3f-7a6d1e2b4c50";
11413
+ /**
11414
+ * A command line, after the binary name, that each listed command accepts exactly as written. Help,
11415
+ * the command listing and the docs page of a command all show this one line.
11416
+ */
11417
+ const COMMAND_EXAMPLES = {
11418
+ "canvas apply": `canvas apply --canvas 00000000-0000-4000-8000-000000000010 --base-version 1 --operations '[{"op":"setText","nodeId":"text_title","text":"Ready"}]'`,
11419
+ "canvas edit": `canvas edit --canvas 00000000-0000-4000-8000-000000000010 --base-version 1 --edits '[{"kind":"set_text","nodeId":"text_title","text":"Today"}]'`,
11420
+ "canvas set-text-content": `canvas set-text-content --canvas 00000000-0000-4000-8000-000000000010 --base-version 1 --updates '[{"nodeId":"text_title","textContent":"Today"}]'`,
11421
+ "canvas rename-nodes": `canvas rename-nodes --canvas 00000000-0000-4000-8000-000000000010 --base-version 1 --updates '[{"nodeId":"card","name":"Task"}]'`,
11422
+ "canvas update-styles": `canvas update-styles --canvas 00000000-0000-4000-8000-000000000010 --base-version 1 --updates '[{"nodeIds":["button"],"styles":{"background":"#0f766e"}}]'`,
11423
+ "canvas delete-nodes": `canvas delete-nodes --canvas 00000000-0000-4000-8000-000000000010 --base-version 1 --node-ids '["obsolete"]'`,
11424
+ "canvas get-computed-styles": `canvas get-computed-styles --canvas 00000000-0000-4000-8000-000000000010 --node-ids '["button"]'`,
11425
+ "canvas duplicate-nodes": `canvas duplicate-nodes --input '{"canvasRef":"00000000-0000-4000-8000-000000000010","baseVersion":1,"nodeIds":["screen"],"destination":{"kind":"native"}}'`,
11426
+ "canvas move-nodes": `canvas move-nodes --canvas 00000000-0000-4000-8000-000000000010 --base-version 1 --moves '[{"nodeId":"card","before":"other"}]'`,
11427
+ "canvas create-artboard": `canvas create-artboard --canvas 00000000-0000-4000-8000-000000000010 --base-version 1 --name Home --styles '{"width":"1440px","height":"900px"}'`,
11428
+ "canvas render": CANVAS_RENDER_EXAMPLE,
11429
+ "canvas work begin": `canvas work begin --canvas 00000000-0000-4000-8000-000000000010 --phase creating --bounds '{"x":0,"y":0,"width":1440,"height":900}'`,
11430
+ "canvas work update": `canvas work update --canvas 00000000-0000-4000-8000-000000000010 --activity-id 00000000-0000-4000-8000-000000000010 --phase writing --bounds '{"x":0,"y":0,"width":1440,"height":900}'`,
11431
+ "canvas find": `canvas find --input '{"collection":"everything","includeDestinations":true,"limit":25}'`,
11432
+ "canvas read": `canvas read --input '{"canvasRef":"00000000-0000-4000-8000-000000000010","view":"outline","depth":2,"limit":50}'`,
11433
+ "canvas remove": `canvas remove --input '{"canvasRef":"00000000-0000-4000-8000-000000000010","baseVersion":1,"rootNodeIds":["obsolete"]}'`,
11434
+ "canvas update-html": `canvas update-html --input '${JSON.stringify(CANVAS_UPDATE_HTML_INPUT_EXAMPLE)}'`,
11435
+ "canvas publish-prototype": `canvas publish-prototype --input '{"canvasRef":"00000000-0000-4000-8000-000000000010","baseVersion":1,"source":{"kind":"deployment","deploymentId":"00000000-0000-4000-8000-000000000010"},"waitMs":1500}'`,
11436
+ "canvas import-asset": `canvas import-asset --input '{"canvasRef":"00000000-0000-4000-8000-000000000010","source":{"kind":"file","path":"/project/logo.png"}}'`,
11437
+ "canvas insert-html": String.raw`canvas insert-html --input '{"canvasRef":"00000000-0000-4000-8000-000000000010","baseVersion":1,"destination":{"parentNodeId":"root"},"html":"<div style=\"width:400px;height:200px\">Hello</div>","waitMs":1500}'`,
11438
+ "canvas make-editable": `canvas make-editable --input '{"canvasRef":"00000000-0000-4000-8000-000000000010","baseVersion":1,"sourceNodeId":"screen","placement":{"kind":"adjacent"},"waitMs":1500}'`,
11439
+ "canvas capture": `canvas capture --input '{"canvasRef":"00000000-0000-4000-8000-000000000010","baseVersion":1,"source":{"kind":"recording","recordingId":"00000000-0000-4000-8000-000000000010","atMs":500},"previewJobId":"00000000-0000-4000-8000-000000000010","placement":{"kind":"editable-below-source"},"waitMs":1500}'`,
11440
+ "canvas capture-page": `canvas capture-page --input '{"canvasRef":"00000000-0000-4000-8000-000000000010"}'`,
11441
+ "canvas arrange": `canvas arrange --input '{"canvasRef":"00000000-0000-4000-8000-000000000010","baseVersion":1,"changes":[{"kind":"position","nodeId":"screen","parentPosition":{"x":40,"y":40}}]}'`,
11442
+ "operation status": `operation status --input '{"operation":{"kind":"canvas-mutation","canvasId":"00000000-0000-4000-8000-000000000010","mutationId":"00000000-0000-4000-8000-000000000010","fingerprint":"5bf58a8bb75a9cf7b4718822d018a70aa3a06113c5eea973eb908ada9000766f"}}'`,
11443
+ "canvas document save": `canvas document save --json '${JSON.stringify({
11444
+ canvasId: CAPABILITY_UUID_EXAMPLE,
11445
+ baseVersion: 1,
11446
+ document: emptyCanvasSceneDocument$1(),
11447
+ screenIds: []
11448
+ })}'`,
11449
+ "canvas text-style-library list": `canvas text-style-library list --json '{"search":"Brand","limit":20}'`,
11450
+ "canvas realtime activity begin": `canvas realtime activity begin --json '{"canvasId":"00000000-0000-4000-8000-000000000010","phase":"creating","bounds":{"x":0,"y":0,"width":1440,"height":900}}'`,
11451
+ "canvas realtime activity renew": `canvas realtime activity renew --json '{"canvasId":"00000000-0000-4000-8000-000000000010","activityId":"00000000-0000-4000-8000-000000000010","phase":"writing","bounds":{"x":0,"y":0,"width":1440,"height":900}}'`,
11452
+ "canvas version name": `canvas version name --json '{"canvasId":"00000000-0000-4000-8000-000000000010","target":{"kind":"current","expectedVersion":1},"title":"Checkout review"}'`,
11453
+ "comment list": `comment list --json '{"canvasId":"00000000-0000-4000-8000-000000000010","page":{"limit":20}}'`,
11454
+ "comment get": `comment get --json '{"canvasId":"00000000-0000-4000-8000-000000000010","threadId":"00000000-0000-4000-8000-000000000010"}'`,
11455
+ "comment start": `comment start --json '{"canvasId":"00000000-0000-4000-8000-000000000010","clientThreadId":"00000000-0000-4000-8000-000000000010","anchor":{"on":"canvas","point":{"x":120,"y":160}},"body":"Check this spacing."}'`,
11456
+ "comment resolve": `comment resolve --json '{"canvasId":"00000000-0000-4000-8000-000000000010","threadId":"00000000-0000-4000-8000-000000000010","resolved":true}'`,
11457
+ "comment reply": `comment reply --json '{"canvasId":"00000000-0000-4000-8000-000000000010","threadId":"00000000-0000-4000-8000-000000000010","clientMessageId":"00000000-0000-4000-8000-000000000010","body":"Fixed."}'`,
11458
+ "comment move": `comment move --json '{"canvasId":"00000000-0000-4000-8000-000000000010","threadId":"00000000-0000-4000-8000-000000000010","anchor":{"on":"canvas","point":{"x":120,"y":160}}}'`,
11459
+ "recording start": `recording start --json '{"sourceUrl":"https://example.test/checkout","viewport":{"width":1280,"height":800},"pageTitle":"Checkout"}'`,
11460
+ "recording complete": `recording complete --json '{"recordingId":"00000000-0000-4000-8000-000000000010","durationMs":1000,"viewport":{"width":1280,"height":800},"sourceUrl":"https://example.test/checkout"}'`,
11461
+ "screen create": `screen create --json '{"clientToken":"00000000-0000-4000-8000-000000000010","provenance":null,"route":"/checkout","pageTitle":"Checkout","viewport":{"width":1280,"height":800},"bytes":1024}'`
11462
+ };
11463
+ /** The line under a command's example that says which of its values stand for the caller's own. */
11464
+ const COMMAND_EXAMPLE_PLACEHOLDERS = {
11465
+ "canvas apply": "Replace with your own: the canvas id, the version, the layer id \"text_title\".",
11466
+ "canvas edit": "Replace with your own: the canvas id, the version, the layer id \"text_title\".",
11467
+ "canvas set-text-content": "Replace with your own: the canvas id, the version, the layer id \"text_title\".",
11468
+ "canvas rename-nodes": "Replace with your own: the canvas id, the version, the layer id \"card\".",
11469
+ "canvas update-styles": "Replace with your own: the canvas id, the version, the layer id \"button\".",
11470
+ "canvas delete-nodes": "Replace with your own: the canvas id, the version, the layer id \"obsolete\".",
11471
+ "canvas get-computed-styles": "Replace with your own: the canvas id, the layer id \"button\".",
11472
+ "canvas duplicate-nodes": "Replace with your own: the canvas id, the version, the layer id \"screen\".",
11473
+ "canvas move-nodes": "Replace with your own: the canvas id, the version, the layer ids \"card\" and \"other\".",
11474
+ "canvas create-artboard": "Replace with your own: the canvas id, the version.",
11475
+ "canvas render": "Replace with your own: the canvas id.",
11476
+ "canvas work begin": "Replace with your own: the canvas id.",
11477
+ "canvas work update": "Replace with your own: the canvas id, the activity id.",
11478
+ "canvas read": "Replace with your own: the canvas id.",
11479
+ "canvas remove": "Replace with your own: the canvas id, the version, the layer id \"obsolete\".",
11480
+ "canvas update-html": "Replace with your own: the canvas id, the snapshot token, the HTML.",
11481
+ "canvas publish-prototype": "Replace with your own: the canvas id, the version, the deployment id.",
11482
+ "canvas import-asset": "Replace with your own: the canvas id, the file path.",
11483
+ "canvas insert-html": "Replace with your own: the canvas id, the version.",
11484
+ "canvas make-editable": "Replace with your own: the canvas id, the version, the layer id \"screen\".",
11485
+ "canvas capture": "Replace with your own: the canvas id, the version, the recording id, the time, the preview job id.",
11486
+ "canvas capture-page": "Replace with your own: the canvas id.",
11487
+ "canvas arrange": "Replace with your own: the canvas id, the version, the layer id \"screen\".",
11488
+ "operation status": "Replace with your own: the whole operation, copied from the answer of a write.",
11489
+ "canvas document save": "Replace with your own: the canvas id, the version, the document.",
11490
+ "canvas realtime activity begin": "Replace with your own: the canvas id.",
11491
+ "canvas realtime activity renew": "Replace with your own: the canvas id, the activity id.",
11492
+ "canvas version name": "Replace with your own: the canvas id, the version.",
11493
+ "comment list": "Replace with your own: the canvas id.",
11494
+ "comment get": "Replace with your own: the canvas id, the thread id.",
11495
+ "comment start": "Replace with your own: the canvas id, the thread id, a UUID you make.",
11496
+ "comment resolve": "Replace with your own: the canvas id, the thread id.",
11497
+ "comment reply": "Replace with your own: the canvas id, the thread id, the message id, a UUID you make.",
11498
+ "comment move": "Replace with your own: the canvas id, the thread id.",
11499
+ "recording start": "Replace with your own: the address, the page title.",
11500
+ "recording complete": "Replace with your own: the recording id, the address.",
11501
+ "screen create": "Replace with your own: the client token, a UUID you make, the route, the page title, the size in bytes."
10551
11502
  };
10552
11503
 
10553
11504
  //#endregion
10554
11505
  //#region src/infrastructure/commands.program.ts
10555
- const procedurePathOf = (command) => {
11506
+ const procedurePathOf$1 = (command) => {
10556
11507
  const details = Reflect.get(command, "__trpcCli");
10557
11508
  if (typeof details !== "object" || details === null) return null;
10558
11509
  const path = Reflect.get(details, "path");
@@ -10567,7 +11518,7 @@ const listedCommands = (command, path = []) => command.commands.filter((child) =
10567
11518
  });
10568
11519
  const recordsFrom = (command, path = []) => command.commands.filter((child) => child.name() !== "help").flatMap((child) => {
10569
11520
  const childPath = [...path, child.name()];
10570
- const procedure = procedurePathOf(child);
11521
+ const procedure = procedurePathOf$1(child);
10571
11522
  return [{
10572
11523
  path: childPath.join(" "),
10573
11524
  procedure,
@@ -10584,12 +11535,19 @@ const toReferenceRecord = (capability, discovery) => ({
10584
11535
  }),
10585
11536
  exampleOutput: capability.guide.examples[0]?.output ?? null
10586
11537
  });
10587
- const commandRecords = (program, catalog) => {
10588
- const capabilities = catalog();
11538
+ /** Whether a command path is the namespace or below it; every path is, when none is asked for. */
11539
+ const withinNamespace = (namespace) => (path) => {
11540
+ const prefix = namespace?.trim();
11541
+ if (prefix === void 0) return true;
11542
+ return path === prefix || path?.startsWith(`${prefix} `) === true;
11543
+ };
11544
+ const commandRecords = (program, catalog, isListed) => {
11545
+ const capabilities = catalog.all();
10589
11546
  const discovery = createMcpCapabilityDiscoveryAdapter(capabilities);
10590
11547
  const exitCodes = toPublishedExitTable();
10591
11548
  return listedCommands(program).flatMap(({ command, path }) => {
10592
- const procedure = procedurePathOf(command);
11549
+ if (!isListed(path)) return [];
11550
+ const procedure = procedurePathOf$1(command);
10593
11551
  const capability = capabilities.find(({ cli }) => cli?.path === path);
10594
11552
  if (capability === void 0 && procedure === null && command.commands.length > 0) return [];
10595
11553
  return [{
@@ -10607,7 +11565,7 @@ const commandRecords = (program, catalog) => {
10607
11565
  return {
10608
11566
  flags: option.flags,
10609
11567
  description: option.description,
10610
- required: requirement !== void 0 || option.mandatory,
11568
+ required: requirement !== void 0 || option.mandatory || isRequiredSpelling(option),
10611
11569
  ...typeof requirement === "string" && { requiredUnless: requirement },
10612
11570
  ...option.defaultValue !== void 0 && { defaultValue: option.defaultValue }
10613
11571
  };
@@ -10619,9 +11577,10 @@ const commandRecords = (program, catalog) => {
10619
11577
  });
10620
11578
  };
10621
11579
  const registerCommandsProgram = (program, output, catalog) => {
10622
- program.command("commands").description("Emit the command inventory as NDJSON without walking the help tree.").option("--namespace <path>", "Keep commands at or below this space-separated path.").option("--capabilities", "Emit the transport-neutral capability inventory.", false).option("--reference", "Emit complete shared capability contracts for documentation.", false).option("--records", "Emit the complete contract of each listed command for documentation.", false).action((options) => {
11580
+ program.command("commands").description("Emit the command inventory as NDJSON without walking the help tree.").option("--namespace <path>", "Keep commands at or below this space-separated path, in every mode.").option("--capabilities", "Emit the transport-neutral capability inventory.", false).option("--reference", "Emit complete shared capability contracts for documentation.", false).option("--records", "Emit the complete contract of each listed command for documentation.", false).action((options) => {
11581
+ const isListed = withinNamespace(options.namespace);
10623
11582
  if (options.reference) {
10624
- const shared = toSharedCapabilities(catalog());
11583
+ const shared = toSharedCapabilities(catalog.all()).filter(({ cli }) => isListed(cli?.path));
10625
11584
  const discovery = createMcpCapabilityDiscoveryAdapter(shared);
10626
11585
  output.result({
10627
11586
  items: shared.map((capability) => toReferenceRecord(capability, discovery)),
@@ -10631,20 +11590,20 @@ const registerCommandsProgram = (program, output, catalog) => {
10631
11590
  }
10632
11591
  if (options.records) {
10633
11592
  output.result({
10634
- items: commandRecords(program, catalog),
11593
+ items: commandRecords(program, catalog, isListed),
10635
11594
  truncated: false
10636
11595
  });
10637
11596
  return;
10638
11597
  }
10639
11598
  if (options.capabilities) {
11599
+ const listed = catalog.all().filter(({ cli }) => isListed(cli?.path));
10640
11600
  output.result({
10641
- items: toCapabilityInventory(catalog()),
11601
+ items: toCapabilityInventory(listed),
10642
11602
  truncated: false
10643
11603
  });
10644
11604
  return;
10645
11605
  }
10646
- const prefix = options.namespace?.trim();
10647
- const records = recordsFrom(program).filter((record) => prefix === void 0 || record.path === prefix || record.path.startsWith(`${prefix} `));
11606
+ const records = recordsFrom(program).filter((record) => isListed(record.path));
10648
11607
  output.result({
10649
11608
  items: records,
10650
11609
  truncated: false
@@ -10654,12 +11613,19 @@ const registerCommandsProgram = (program, output, catalog) => {
10654
11613
 
10655
11614
  //#endregion
10656
11615
  //#region src/infrastructure/comment.program.ts
11616
+ const canvasGiven = (argument, option) => {
11617
+ if (argument !== void 0 && option !== void 0) throw new CliError("BAD_REQUEST", "The canvas was given twice: as the argument and as --canvas.", "Pass the canvas once.");
11618
+ const reference = argument ?? option;
11619
+ if (reference === void 0) throw new CliError("BAD_REQUEST", "--canvas is required.", "Pass --canvas with a canvas URL or id, or --canvas-id with the id alone.");
11620
+ return reference;
11621
+ };
10657
11622
  const registerCommentProgram = (program, invocation, catalog, output) => {
10658
11623
  const comment = program.commands.find((command) => command.name() === "comment");
10659
11624
  if (comment === void 0) throw new TypeError("derived comment namespace is missing");
10660
- comment.command("attention").description("List every open comment needing attention; source metadata is included when a capture has it.").argument("<canvas-url-or-id>", "A pasted Enhance canvas URL shaped /c/<UUID>, or a bare canvas UUID.").action(async (reference) => {
11625
+ comment.command("attention").description("List every open comment needing attention; source metadata is included when a capture has it.").argument("[canvas-url-or-id]", "A pasted Enhance canvas URL shaped /c/<UUID>, or a bare canvas UUID. --canvas is also accepted.").option("--canvas <url-or-id>", "Canvas URL or UUID, in place of the argument.").action(async (argument, options) => {
11626
+ const reference = canvasGiven(argument, options.canvas);
10661
11627
  output.result(await invocation.invoke({
10662
- capability: fromCapabilityReference(catalog(), "comment.attention"),
11628
+ capability: catalog.one("comment.attention"),
10663
11629
  arguments: { canvasId: fromCanvasReference(reference) },
10664
11630
  clientToken: null
10665
11631
  }));
@@ -10670,12 +11636,13 @@ const registerCommentProgram = (program, invocation, catalog, output) => {
10670
11636
  //#region src/infrastructure/doctor.program.ts
10671
11637
  const registerDoctorProgram = (program, dependencies) => {
10672
11638
  const { version, credentials, remote, output } = dependencies;
10673
- program.command("doctor").description("Check the installed binary, API reachability, and credential file without changes.").action(async () => {
11639
+ program.command("doctor").description("Check the installed binary, its Node, API reachability, and credential file without changes.").action(async () => {
10674
11640
  const [health, token] = await Promise.all([remote.health(), credentials.read()]);
10675
11641
  output.result({
10676
11642
  status: token !== null && health.reachable ? "ok" : "degraded",
10677
11643
  binary: process.argv[1] ?? "enhance",
10678
11644
  version,
11645
+ node: process.versions.node,
10679
11646
  api: health,
10680
11647
  credential: {
10681
11648
  path: credentials.path,
@@ -10761,12 +11728,264 @@ const registerFixtureProgram = (program, composites, output) => {
10761
11728
  registerWorldFixture(fixture, composites.world, output);
10762
11729
  };
10763
11730
 
11731
+ //#endregion
11732
+ //#region src/infrastructure/input-help.program.ts
11733
+ /** The longest help a command made from an API procedure may print, and any other command. */
11734
+ const PROCEDURE_HELP_LIMIT = 2500;
11735
+ const UTILITY_HELP_LIMIT = 3200;
11736
+ const BOUNDS = {
11737
+ flag: "--bounds",
11738
+ schema: canvasWorldBoundsSchema$1
11739
+ };
11740
+ /** The JSON flags of each hand-written command. A command made from a procedure needs no row. */
11741
+ const JSON_FLAGS = {
11742
+ "canvas apply": [{
11743
+ flag: "--operations",
11744
+ capability: "canvas.apply",
11745
+ field: "operations"
11746
+ }],
11747
+ "canvas edit": [{
11748
+ flag: "--edits",
11749
+ capability: "canvas.edit",
11750
+ field: "edits"
11751
+ }],
11752
+ "canvas set-text-content": [{
11753
+ flag: "--updates",
11754
+ schema: textUpdatesSchema
11755
+ }],
11756
+ "canvas rename-nodes": [{
11757
+ flag: "--updates",
11758
+ schema: renameUpdatesSchema
11759
+ }],
11760
+ "canvas update-styles": [{
11761
+ flag: "--updates",
11762
+ schema: styleUpdatesSchema
11763
+ }],
11764
+ "canvas delete-nodes": [{
11765
+ flag: "--node-ids",
11766
+ schema: nodeIdsSchema
11767
+ }],
11768
+ "canvas get-computed-styles": [{
11769
+ flag: "--node-ids",
11770
+ schema: nodeIdsSchema
11771
+ }],
11772
+ "canvas duplicate-nodes": [{
11773
+ flag: "--input",
11774
+ capability: "canvas.duplicateNodes"
11775
+ }, {
11776
+ flag: "--nodes",
11777
+ schema: duplicateInputsSchema
11778
+ }],
11779
+ "canvas move-nodes": [{
11780
+ flag: "--moves",
11781
+ schema: moveInputsSchema
11782
+ }],
11783
+ "canvas create-artboard": [{
11784
+ flag: "--styles",
11785
+ schema: styleObjectSchema
11786
+ }],
11787
+ "canvas render": [{
11788
+ flag: "--input",
11789
+ schema: canvasRenderScopedInputSchema,
11790
+ capability: "canvas.render"
11791
+ }, BOUNDS],
11792
+ "canvas work begin": [BOUNDS],
11793
+ "canvas work update": [BOUNDS],
11794
+ "canvas find": [{
11795
+ flag: "--input",
11796
+ capability: "canvas.find"
11797
+ }],
11798
+ "canvas read": [{
11799
+ flag: "--input",
11800
+ schema: canvasReadInputSchema,
11801
+ capability: "canvas.read"
11802
+ }],
11803
+ "canvas remove": [{
11804
+ flag: "--input",
11805
+ capability: "canvas.remove"
11806
+ }],
11807
+ "canvas update-html": [{
11808
+ flag: "--input",
11809
+ capability: "canvas.updateHtml"
11810
+ }],
11811
+ "canvas publish-prototype": [{
11812
+ flag: "--input",
11813
+ capability: "prototype.publishCanvas"
11814
+ }],
11815
+ "canvas import-asset": [{
11816
+ flag: "--input",
11817
+ capability: "canvas.importAsset"
11818
+ }],
11819
+ "canvas insert-html": [{
11820
+ flag: "--input",
11821
+ capability: "canvas.insertHtml"
11822
+ }],
11823
+ "canvas make-editable": [{
11824
+ flag: "--input",
11825
+ capability: "canvas.makeEditable"
11826
+ }],
11827
+ "canvas capture": [{
11828
+ flag: "--input",
11829
+ capability: "canvas.capture"
11830
+ }],
11831
+ "canvas capture-page": [{
11832
+ flag: "--input",
11833
+ capability: "canvas.capturePage"
11834
+ }],
11835
+ "canvas arrange": [{
11836
+ flag: "--input",
11837
+ capability: "canvas.arrange"
11838
+ }],
11839
+ "operation status": [{
11840
+ flag: "--input",
11841
+ capability: "operation.status"
11842
+ }]
11843
+ };
11844
+ const capabilityOf = (find, id) => {
11845
+ const capability = find(id);
11846
+ if (capability === void 0) throw new TypeError(`${id} is missing from the capability catalogue`);
11847
+ return capability;
11848
+ };
11849
+ const jsonSchemaOf = (schema) => z.toJSONSchema(schema, {
11850
+ unrepresentable: "any",
11851
+ io: "input"
11852
+ });
11853
+ /** The schema a hand-written command checks the value of one JSON flag against. */
11854
+ const jsonFlagSchemaOf = (source, find) => {
11855
+ if ("schema" in source) return source.schema;
11856
+ const input = capabilityOf(find, source.capability).inputSchema;
11857
+ if (source.field === void 0) return input;
11858
+ const field = input instanceof z.ZodObject ? input.shape[source.field] : void 0;
11859
+ if (!(field instanceof z.ZodType)) throw new TypeError(`${source.capability} has no input field ${source.field}`);
11860
+ return field;
11861
+ };
11862
+ /** One field's schema, still able to follow a reference into the input it was taken from. */
11863
+ const fieldSchemaOf = (input, field) => {
11864
+ const properties = input["properties"];
11865
+ const held = typeof properties === "object" && properties !== null ? Reflect.get(properties, field) : void 0;
11866
+ return typeof held === "object" && held !== null ? {
11867
+ ...held,
11868
+ $defs: input["$defs"]
11869
+ } : held;
11870
+ };
11871
+ const describedFlag = (source, find) => ({
11872
+ flag: source.flag,
11873
+ schema: jsonSchemaOf(jsonFlagSchemaOf(source, find)),
11874
+ fields: "schema" in source || source.field !== void 0 ? [] : capabilityOf(find, source.capability).guide.input
11875
+ });
11876
+ const procedurePathOf = (command) => {
11877
+ const details = Reflect.get(command, "__trpcCli");
11878
+ const path = typeof details === "object" && details !== null ? Reflect.get(details, "path") : void 0;
11879
+ return typeof path === "string" ? path : null;
11880
+ };
11881
+ /** The flags of a command made from a procedure whose value is a JSON object or a list of them. */
11882
+ const procedureFlags = (command, capability) => {
11883
+ const input = jsonSchemaOf(capability.inputSchema);
11884
+ const properties = input["properties"];
11885
+ if (typeof properties !== "object" || properties === null) return [];
11886
+ return Object.keys(properties).flatMap((name) => {
11887
+ const flag = `--${toKebabCase(name)}`;
11888
+ const schema = fieldSchemaOf(input, name);
11889
+ return command.options.some((option) => option.long === flag) && isJsonValued(schema) ? [{
11890
+ flag,
11891
+ schema,
11892
+ fields: []
11893
+ }] : [];
11894
+ });
11895
+ };
11896
+ const inputOf = (command, path, find) => {
11897
+ const sources = JSON_FLAGS[path];
11898
+ if (sources !== void 0) {
11899
+ const owner = sources.find((source) => source.capability !== void 0)?.capability;
11900
+ return {
11901
+ flags: sources.map((source) => describedFlag(source, find)),
11902
+ capability: owner === void 0 ? null : capabilityOf(find, owner)
11903
+ };
11904
+ }
11905
+ const procedure = procedurePathOf(command);
11906
+ const capability = procedure === null ? void 0 : find(procedure);
11907
+ if (capability === void 0) return null;
11908
+ const flags = procedureFlags(command, capability);
11909
+ return flags.length === 0 ? null : {
11910
+ flags,
11911
+ capability
11912
+ };
11913
+ };
11914
+ const rootOf = (command) => command.parent === null ? command : rootOf(command.parent);
11915
+ /**
11916
+ * The writers of the help texts already added after a command's options. Commander keeps each as
11917
+ * a listener on the command, which is an event emitter its types do not show.
11918
+ */
11919
+ const helpWritersOf = (command) => {
11920
+ const listeners = Reflect.get(command, "listeners");
11921
+ if (typeof listeners !== "function") return [];
11922
+ const held = Reflect.apply(listeners, command, ["afterHelp"]);
11923
+ return Array.isArray(held) ? held.filter((writer) => typeof writer === "function") : [];
11924
+ };
11925
+ /** What those writers print, to count its length against the help limit. */
11926
+ const textAfterOptions = (command, writers) => {
11927
+ const parts = [];
11928
+ const context = {
11929
+ error: false,
11930
+ command,
11931
+ write: (part) => {
11932
+ parts.push(part);
11933
+ }
11934
+ };
11935
+ for (const write of writers) write(context);
11936
+ return parts.join("");
11937
+ };
11938
+ /** Every command of a program with its path, groups included. */
11939
+ const commandsOf = (command, path = []) => command.commands.flatMap((child) => {
11940
+ const childPath = [...path, child.name()];
11941
+ return [{
11942
+ command: child,
11943
+ path: childPath.join(" ")
11944
+ }, ...commandsOf(child, childPath)];
11945
+ });
11946
+ const inputHelpOf = (target, find) => {
11947
+ const { command, path, others } = target;
11948
+ const input = inputOf(command, path, find);
11949
+ if (input === null) return "";
11950
+ const binary = rootOf(command).name();
11951
+ const example = COMMAND_EXAMPLES[path];
11952
+ const cap = procedurePathOf(command) === null ? UTILITY_HELP_LIMIT : PROCEDURE_HELP_LIMIT;
11953
+ const commandOf = (id) => {
11954
+ const cliPath = find(id)?.cli?.path;
11955
+ return cliPath === void 0 ? id : `${binary} ${cliPath}`;
11956
+ };
11957
+ return toInputHelp({
11958
+ flags: input.flags,
11959
+ earlier: (input.capability?.earlierAnswers ?? []).map((sentence) => withCapabilityNames(sentence, commandOf)),
11960
+ example: example === void 0 ? null : `${binary} ${example}`,
11961
+ placeholders: COMMAND_EXAMPLE_PLACEHOLDERS[path] ?? null,
11962
+ limit: cap - command.helpInformation().length - textAfterOptions(command, others).length - 1,
11963
+ rest: `${binary} commands --records --namespace "${path}"`
11964
+ });
11965
+ };
11966
+ /**
11967
+ * Adds, after the options of each command that takes JSON in a flag, the fields of that JSON, the
11968
+ * call that gives an input an earlier answer supplies, and one example. The text is made when
11969
+ * help is asked for, from the command's capability record.
11970
+ */
11971
+ const attachInputHelp = (program, catalog) => {
11972
+ for (const { command, path } of commandsOf(program)) {
11973
+ if (!(JSON_FLAGS[path] !== void 0 || procedurePathOf(command) !== null)) continue;
11974
+ const others = helpWritersOf(command);
11975
+ command.addHelpText("after", () => inputHelpOf({
11976
+ command,
11977
+ path,
11978
+ others
11979
+ }, catalog.find));
11980
+ }
11981
+ };
11982
+
10764
11983
  //#endregion
10765
11984
  //#region src/infrastructure/operation.program.ts
10766
11985
  const registerOperationProgram = (program, input) => {
10767
11986
  program.command("operation").description("Read existing domain-owned operation outcomes.").command("status").description("Recover an existing outcome without creating or resuming work.").requiredOption("--input <json-or-@path>", "Operation reference and optional detail offset/limit.").action(async (options) => {
10768
11987
  input.output.result(await input.invocation.invoke({
10769
- capability: fromCapabilityReference(input.catalog(), "operation.status"),
11988
+ capability: input.catalog.one("operation.status"),
10770
11989
  arguments: createCanvasJsonInputAdapter(options.input, operationStatusInputSchema, "--input"),
10771
11990
  clientToken: null
10772
11991
  }));
@@ -10785,7 +12004,7 @@ const registerPrototypeProgram = (program, invocation, catalog, output) => {
10785
12004
  (program.commands.find((command) => command.name() === "prototype") ?? program.command("prototype").description("Publish static frontend prototypes.")).command("publish").description("Package and publish an unpacked static build directory. The CLI creates the upload artifact. To update a prototype, publish to its owner node: pass --prototype-id and that node as --node-id. Any other node that shows it forks into its own prototype. An update keeps the title the node shows; --title only names a new node.").requiredOption("--canvas-id <uuid>", "Canvas that receives the prototype.").requiredOption("--directory <path>", "Unpacked static build directory; do not pass a ZIP file.").requiredOption("--title <title>", "Label above the prototype frame.").requiredOption("--base-version <number>", "Current canvas document version.", positiveInteger).option("--prototype-id <uuid>", "Existing prototype identity to publish a new deployment.").option("--client-token <uuid>", "Stable retry token for this exact build.").option("--node-id <id>", "Exact canvas node to create, update, or fork when it is a copy.").option("--entry <path>", "HTML entry relative to the uploaded directory.", "index.html").option("--x <pixels>", "Canvas x coordinate.", finiteNumber, DEFAULT_POSITION).option("--y <pixels>", "Canvas y coordinate.", finiteNumber, DEFAULT_POSITION).option("--width <pixels>", "Prototype viewport width.", positiveNumber, DEFAULT_WIDTH).option("--height <pixels>", "Prototype viewport height.", positiveNumber, DEFAULT_HEIGHT).action(async (options) => {
10786
12005
  const clientToken = options.clientToken ?? randomUUID();
10787
12006
  output.result(await invocation.invoke({
10788
- capability: fromCapabilityReference(catalog(), "prototype.publish"),
12007
+ capability: catalog.one("prototype.publish"),
10789
12008
  arguments: {
10790
12009
  canvasId: options.canvasId,
10791
12010
  prototypeId: options.prototypeId ?? null,
@@ -10822,7 +12041,7 @@ const registerRecordingProgram = (program, input) => {
10822
12041
  const recordingId = z.uuid().safeParse(options.recordingId);
10823
12042
  if (!token.success || !recordingId.success) throw new CliError("BAD_REQUEST", "The recording id or client token is not a UUID.", "Use the recording id from `recording list`; mint one client token per accepted moment.");
10824
12043
  input.output.result(await input.invocation.invoke({
10825
- capability: fromCapabilityReference(input.catalog(), "recording.snapshot"),
12044
+ capability: input.catalog.one("recording.snapshot"),
10826
12045
  arguments: {
10827
12046
  canvasId: fromCanvasReference(options.canvas),
10828
12047
  recordingId: recordingId.data,
@@ -10840,10 +12059,87 @@ const refuseDocumentConflict = (path, input, result) => {
10840
12059
  if (path !== "canvas.document.save" || typeof result !== "object" || result === null || !("outcome" in result) || result.outcome !== "conflict") return result;
10841
12060
  throw new CliError("CONFLICT", "The canvas document changed before this save landed.", `Run 'enhance canvas document get --canvas-id ${typeof input === "object" && input !== null && "canvasId" in input && typeof input.canvasId === "string" ? input.canvasId : "<canvas-id>"}', merge your change into that document, then retry with its version.`);
10842
12061
  };
10843
- const createRemoteRouterAdapter = (source, remote) => proxify(source, (path) => ({ [path]: {
10844
- query: async (input) => remote.query(path, input),
10845
- mutate: async (input) => refuseDocumentConflict(path, input, await remote.mutate(path, input))
10846
- } }));
12062
+ const INPUT_SUBJECT = "The input";
12063
+ /**
12064
+ * Checks a generated command's input with the schema the API checks it with, so every problem is
12065
+ * named before anything is sent. The input goes on as it was given: the API applies its own
12066
+ * defaults. A schema that cannot be checked here is left to the API.
12067
+ */
12068
+ const checkedInput = (schema, input) => {
12069
+ if (!(schema instanceof z.ZodType)) return input;
12070
+ const read = withAcceptedSpellings(schema, input, INPUT_SUBJECT);
12071
+ const parsed = (() => {
12072
+ try {
12073
+ return schema.safeParse(read);
12074
+ } catch {
12075
+ return null;
12076
+ }
12077
+ })();
12078
+ if (parsed === null || parsed.success) return read;
12079
+ const refusal = inputRefusal({
12080
+ subject: INPUT_SUBJECT,
12081
+ error: parsed.error,
12082
+ checked: {
12083
+ schema,
12084
+ value: read
12085
+ },
12086
+ help: "Run the command with --help for every flag."
12087
+ });
12088
+ const flags = Object.keys(refusal.fields ?? {}).map((field) => field.split(".", 1)[0] ?? "").filter((field, index, all) => field !== "input" && all.indexOf(field) === index).map((field) => `--${toKebabCase(field)}`);
12089
+ throw new CliError(refusal.code, refusal.message, flags.length === 0 ? refusal.remediation : `${refusal.remediation} These are the flags ${flags.join(", ")}.`, refusal.fields);
12090
+ };
12091
+ const createRemoteRouterAdapter = (source, remote) => {
12092
+ const schemas = new Map(source.map(([path, info]) => [path, info.originalInputSchema]));
12093
+ return proxify(source, (path) => ({ [path]: {
12094
+ query: async (input) => remote.query(path, checkedInput(schemas.get(path), input)),
12095
+ mutate: async (input) => {
12096
+ const checked = checkedInput(schemas.get(path), input);
12097
+ return refuseDocumentConflict(path, checked, await remote.mutate(path, checked));
12098
+ }
12099
+ } }));
12100
+ };
12101
+
12102
+ //#endregion
12103
+ //#region src/infrastructure/setup.program.ts
12104
+ const MAX_TOKEN_LABEL_CHARACTERS = 120;
12105
+ const registerSetupProgram = (program, setup, output) => {
12106
+ program.command("setup").description("Sign in if nobody is, give each coding agent on this machine the Enhance skill, and say what to do next.").option("--token <token>", "Sign in with an existing agent token instead of the browser.").option("--no-open", "Print the sign-in address without opening the browser.").action(async (options) => {
12107
+ const answer = await setup.run({
12108
+ token: await readOptionalToken(options.token),
12109
+ label: `CLI on ${hostname()}`.slice(0, MAX_TOKEN_LABEL_CHARACTERS),
12110
+ openBrowser: options.open,
12111
+ onReady: (url) => {
12112
+ output.result({
12113
+ status: "waiting_for_browser",
12114
+ url,
12115
+ waiting: WAITING_FOR_BROWSER
12116
+ });
12117
+ }
12118
+ });
12119
+ output.result(answer);
12120
+ if (answer.status === "ready") return;
12121
+ throw answer.signedIn === null ? new CliError("UNAUTHORIZED", `Setup is not finished: ${answer.signInProblem ?? "nobody is signed in."}`, "Run 'enhance auth login', then 'enhance setup' again.") : new CliError("INTERNAL", `Setup is not finished: the skill could not be written to ${answer.skill.notWritten.map(({ file }) => file).join(", ")}.`, "Make that folder writable, then run 'enhance setup' again.");
12122
+ });
12123
+ };
12124
+
12125
+ //#endregion
12126
+ //#region src/infrastructure/skill-command.lib.ts
12127
+ const realFileOf = (file) => {
12128
+ try {
12129
+ return realpathSync(file);
12130
+ } catch {
12131
+ return null;
12132
+ }
12133
+ };
12134
+ /**
12135
+ * How a skill should name the tool so an agent's shell can run it: the bare command when the PATH
12136
+ * leads to this tool, and this tool's full path when it leads nowhere or to another install.
12137
+ */
12138
+ const skillCommandOf = (commandName, machine) => {
12139
+ if (machine.entry === void 0) return commandName;
12140
+ const found = machine.searchPath.split(path.delimiter).filter((folder) => folder !== "").map((folder) => realFileOf(path.join(folder, commandName))).find((file) => file !== null);
12141
+ return found !== void 0 && found === realFileOf(machine.entry) ? commandName : machine.entry;
12142
+ };
10847
12143
 
10848
12144
  //#endregion
10849
12145
  //#region src/infrastructure/transcript.program.ts
@@ -10854,7 +12150,7 @@ const registerTranscriptProgram = (program, input) => {
10854
12150
  const recordingId = z.uuid().safeParse(options.recordingId);
10855
12151
  if (!recordingId.success) throw new CliError("BAD_REQUEST", "--recording-id must be a UUID.", "Use the recording id returned by `enhance recording list`.");
10856
12152
  input.output.result(await input.invocation.invoke({
10857
- capability: fromCapabilityReference(input.catalog(), "transcript.read"),
12153
+ capability: input.catalog.one("transcript.read"),
10858
12154
  arguments: {
10859
12155
  canvasId: fromCanvasReference(options.canvas),
10860
12156
  recordingId: recordingId.data
@@ -10901,12 +12197,18 @@ const cliMetadataFrom = (procedures) => {
10901
12197
  mutationPaths: new Set(procedures.flatMap(([path, info]) => info.type === "mutation" ? [path] : []))
10902
12198
  };
10903
12199
  };
10904
- const createLazyCapabilityCatalog = () => {
10905
- let catalog = null;
10906
- return () => {
10907
- catalog ??= createCapabilityCatalogAdapter();
10908
- return catalog;
10909
- };
12200
+ /** Signing in, and the setup that signs in and gives each coding agent the skill. */
12201
+ const registerSignInPrograms = (program, input) => {
12202
+ const auth = createAuthUseCase(input.credentials, input.remote, createOauthLoopbackAdapter(input.remote));
12203
+ registerAuthProgram(program, auth, input.output);
12204
+ registerSetupProgram(program, createSetupUseCase({
12205
+ auth,
12206
+ skills: createAgentSkillFoldersAdapter(input.machine.homeDirectory),
12207
+ skill: () => captureSkillOf({
12208
+ commandName: input.commandName,
12209
+ command: skillCommandOf(input.commandName, input.machine)
12210
+ })
12211
+ }), input.output);
10910
12212
  };
10911
12213
  const registerUtilityPrograms = (program, input, catalog) => {
10912
12214
  const screen = createScreenFixtureComposite(input.remote);
@@ -10917,7 +12219,7 @@ const registerUtilityPrograms = (program, input, catalog) => {
10917
12219
  now: () => /* @__PURE__ */ new Date(),
10918
12220
  progress: input.output.result
10919
12221
  });
10920
- registerAuthProgram(program, createAuthUseCase(input.credentials, input.remote, createOauthLoopbackAdapter(input.remote)), input.output);
12222
+ registerSignInPrograms(program, input);
10921
12223
  registerCommentProgram(program, invocation, catalog, input.output);
10922
12224
  registerCapturesProgram(program, input);
10923
12225
  registerOperationProgram(program, {
@@ -10958,9 +12260,20 @@ const registerUtilityPrograms = (program, input, catalog) => {
10958
12260
  output: input.output
10959
12261
  });
10960
12262
  };
12263
+ /**
12264
+ * Whether the command that ran answered with nothing. trpc-cli prints no line for such an answer
12265
+ * and keeps it on the command, so the tool prints the `null` itself.
12266
+ */
12267
+ const ranWithNoAnswer = (program) => {
12268
+ const ran = Reflect.get(program, "__ran");
12269
+ const last = Array.isArray(ran) ? ran.at(-1) : void 0;
12270
+ if (typeof last !== "object" || last === null) return false;
12271
+ const answer = Reflect.get(last, "__result");
12272
+ return answer === null || answer === void 0;
12273
+ };
10961
12274
  const createCliProgram = (input) => {
10962
12275
  const procedures = parseRouter({ router: createRouterShapeAdapter() });
10963
- const catalog = createLazyCapabilityCatalog();
12276
+ const catalog = createLazyCapabilityCatalogAdapter();
10964
12277
  const { descriptions, mutationPaths } = cliMetadataFrom(procedures);
10965
12278
  const cli = createCli({
10966
12279
  router: createRemoteRouterAdapter(procedures, input.remote),
@@ -10981,6 +12294,7 @@ const createCliProgram = (input) => {
10981
12294
  output: input.output
10982
12295
  });
10983
12296
  built.description("Operate Enhance as the authenticated person.");
12297
+ attachInputHelp(built, catalog);
10984
12298
  const failureState = input.state;
10985
12299
  return {
10986
12300
  program: built,
@@ -10989,6 +12303,7 @@ const createCliProgram = (input) => {
10989
12303
  await cli.run(runParams, built);
10990
12304
  } catch (error) {
10991
12305
  if (!(error instanceof ProcessExitError)) throw error;
12306
+ if (error.requestedCode === 0 && ranWithNoAnswer(built)) input.output.result(null);
10992
12307
  if (error.requestedCode !== 0 && failureState.pendingParserMessage !== null) {
10993
12308
  const failure = toFailurePayload(error, failureState.pendingParserMessage);
10994
12309
  failureState.exitCode = toExitCode(failure, true);
@@ -11005,17 +12320,48 @@ const createCliProgram = (input) => {
11005
12320
  //#region src/infrastructure/exit-process.lib.ts
11006
12321
  const exitProcess = (code) => process.exit(code);
11007
12322
 
12323
+ //#endregion
12324
+ //#region src/infrastructure/sensitive-file.lib.ts
12325
+ const SENSITIVE_FILE_TTL_MS = 36e5;
12326
+ const DIRECTORY_MODE = 448;
12327
+ const FILE_MODE = 384;
12328
+ const prepareSensitiveDirectory = (directory) => {
12329
+ mkdirSync(directory, {
12330
+ recursive: true,
12331
+ mode: DIRECTORY_MODE
12332
+ });
12333
+ chmodSync(directory, DIRECTORY_MODE);
12334
+ };
12335
+ const sensitiveReference = (fields) => ({
12336
+ ...fields,
12337
+ sensitive: true,
12338
+ cleanup: "unlink-after-use",
12339
+ deleteAfter: new Date(Date.now() + SENSITIVE_FILE_TTL_MS).toISOString()
12340
+ });
12341
+ /** Writes one record to a protected file of its own, and answers with what names that file. */
12342
+ const sensitiveRecordFile = (directory, record) => {
12343
+ prepareSensitiveDirectory(directory);
12344
+ const outputPath = path.join(directory, `result-${randomUUID()}.ndjson`);
12345
+ const body = `${JSON.stringify(record)}\n`;
12346
+ writeFileSync(outputPath, body, {
12347
+ mode: 384,
12348
+ flag: "wx"
12349
+ });
12350
+ return sensitiveReference({
12351
+ path: outputPath,
12352
+ characters: body.length,
12353
+ records: 1
12354
+ });
12355
+ };
12356
+
11008
12357
  //#endregion
11009
12358
  //#region src/infrastructure/ndjson.logger.ts
11010
12359
  const MAX_INLINE_CHARACTERS = 25e3;
11011
12360
  const MAX_LINE_CHARACTERS = 2e3;
11012
12361
  const DIGEST_CHARACTERS = 16;
11013
- const SENSITIVE_FILE_TTL_MS = 36e5;
11014
- const DIRECTORY_MODE = 448;
11015
- const FILE_MODE = 384;
11016
12362
  const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
11017
12363
  const linesFor = (value) => {
11018
- if (Array.isArray(value)) return value.map((entry) => JSON.stringify(entry));
12364
+ if (Array.isArray(value)) return value.length === 0 ? ["[]"] : value.map((entry) => JSON.stringify(entry));
11019
12365
  if (!isObject(value) || !Array.isArray(value["items"])) return [JSON.stringify(value)];
11020
12366
  if ("nextCursor" in value) return [JSON.stringify(value)];
11021
12367
  const items = value["items"];
@@ -11037,7 +12383,7 @@ const writeLines = (lines) => {
11037
12383
  }
11038
12384
  const reference = createHash("sha256").update(body).digest("hex").slice(0, DIGEST_CHARACTERS);
11039
12385
  const outputPath = path.join(tmpdir(), `enhance-${reference}.ndjson`);
11040
- writeFileSync(outputPath, body, { mode: FILE_MODE });
12386
+ writeFileSync(outputPath, body, { mode: 384 });
11041
12387
  process.stdout.write(`${JSON.stringify({
11042
12388
  path: outputPath,
11043
12389
  characters: body.length,
@@ -11060,13 +12406,6 @@ const hasSignedUrl = (value) => {
11060
12406
  if (!isObject(value)) return false;
11061
12407
  return Object.values(value).some((entry) => hasSignedUrl(entry));
11062
12408
  };
11063
- const prepareSensitiveDirectory = (directory) => {
11064
- mkdirSync(directory, {
11065
- recursive: true,
11066
- mode: DIRECTORY_MODE
11067
- });
11068
- chmodSync(directory, DIRECTORY_MODE);
11069
- };
11070
12409
  const sweepExpiredSensitiveFiles = (directory) => {
11071
12410
  if (!existsSync(directory)) return;
11072
12411
  const staleBefore = Date.now() - SENSITIVE_FILE_TTL_MS;
@@ -11077,19 +12416,13 @@ const sweepExpiredSensitiveFiles = (directory) => {
11077
12416
  if (lstatSync(candidate).mtimeMs < staleBefore) unlinkSync(candidate);
11078
12417
  }
11079
12418
  };
11080
- const sensitiveReference = (fields) => ({
11081
- ...fields,
11082
- sensitive: true,
11083
- cleanup: "unlink-after-use",
11084
- deleteAfter: new Date(Date.now() + SENSITIVE_FILE_TTL_MS).toISOString()
11085
- });
11086
12419
  const writeSignedUrlResult = (value, sensitiveDirectory) => {
11087
12420
  const lines = linesFor(value);
11088
12421
  const body = `${lines.join("\n")}\n`;
11089
12422
  prepareSensitiveDirectory(sensitiveDirectory);
11090
12423
  const outputPath = path.join(sensitiveDirectory, `result-${randomUUID()}.ndjson`);
11091
12424
  writeFileSync(outputPath, body, {
11092
- mode: FILE_MODE,
12425
+ mode: 384,
11093
12426
  flag: "wx"
11094
12427
  });
11095
12428
  process.stdout.write(`${JSON.stringify(sensitiveReference({
@@ -11116,7 +12449,7 @@ const writeSensitiveResult = (value, secret, sensitiveDirectory) => {
11116
12449
  prepareSensitiveDirectory(sensitiveDirectory);
11117
12450
  const outputPath = path.join(sensitiveDirectory, `result-${randomUUID()}.token`);
11118
12451
  writeFileSync(outputPath, body, {
11119
- mode: FILE_MODE,
12452
+ mode: 384,
11120
12453
  flag: "wx"
11121
12454
  });
11122
12455
  const safe = Object.fromEntries(Object.entries(value).filter(([field]) => field !== secret.field));
@@ -11129,6 +12462,24 @@ const writeSensitiveResult = (value, secret, sensitiveDirectory) => {
11129
12462
  })
11130
12463
  })}\n`);
11131
12464
  };
12465
+ /** The source a render answered with, when the answer is a rendered picture that carries one. */
12466
+ const renderSourceOf = (value) => {
12467
+ if (!isObject(value) || value["contentType"] !== "image/png") return null;
12468
+ if (typeof value["picture"] !== "string") return null;
12469
+ const source = value["source"];
12470
+ return isObject(source) && source["status"] === "available" ? source : null;
12471
+ };
12472
+ /**
12473
+ * A render's answer names its picture; the layer's source, which is long, goes to a file of its own
12474
+ * that the answer names as `source`. Printed whole, the source pushed the answer into a file and
12475
+ * the picture's path out of sight.
12476
+ */
12477
+ const writeRenderResult = (value, source, sensitiveDirectory) => {
12478
+ writeLines([JSON.stringify({
12479
+ ...value,
12480
+ source: sensitiveRecordFile(sensitiveDirectory, source)
12481
+ })]);
12482
+ };
11132
12483
  const isHelpText = (value) => value.includes("Usage:") || value.includes("Options:") || value.includes("Commands:");
11133
12484
  const failureSchema = appErrorSchema$1.omit({ fields: true }).extend({
11134
12485
  remediation: z.string(),
@@ -11168,27 +12519,18 @@ const writeResult = (value, sensitiveDirectory) => {
11168
12519
  }
11169
12520
  const authoring = toCanvasAuthoringResult(value);
11170
12521
  if (authoring !== null) {
11171
- let detail = null;
11172
- if (authoring.detail !== null) {
11173
- prepareSensitiveDirectory(sensitiveDirectory);
11174
- const outputPath = path.join(sensitiveDirectory, `result-${randomUUID()}.ndjson`);
11175
- const body = `${JSON.stringify(authoring.detail)}\n`;
11176
- writeFileSync(outputPath, body, {
11177
- mode: FILE_MODE,
11178
- flag: "wx"
11179
- });
11180
- detail = sensitiveReference({
11181
- path: outputPath,
11182
- characters: body.length,
11183
- records: 1
11184
- });
11185
- }
12522
+ const detail = authoring.detail === null ? null : sensitiveRecordFile(sensitiveDirectory, authoring.detail);
11186
12523
  process.stdout.write(`${JSON.stringify({
11187
12524
  ...authoring.value,
11188
12525
  ...detail !== null && { detail }
11189
12526
  })}\n`);
11190
12527
  return;
11191
12528
  }
12529
+ const renderSource = renderSourceOf(value);
12530
+ if (renderSource !== null && isObject(value)) {
12531
+ writeRenderResult(value, renderSource, sensitiveDirectory);
12532
+ return;
12533
+ }
11192
12534
  writeLines(linesFor(value));
11193
12535
  };
11194
12536
  const writeFailure = (value) => {
@@ -11198,6 +12540,7 @@ const createNdjsonLoggerAdapter = (state, configDirectory, commandName = "enhanc
11198
12540
  const failureState = state;
11199
12541
  const sensitiveDirectory = path.join(configDirectory, "sensitive");
11200
12542
  sweepExpiredSensitiveFiles(sensitiveDirectory);
12543
+ let hasPrintedHelp = false;
11201
12544
  return {
11202
12545
  result: (value) => {
11203
12546
  writeResult(withCommandName(value, commandName), sensitiveDirectory);
@@ -11207,7 +12550,10 @@ const createNdjsonLoggerAdapter = (state, configDirectory, commandName = "enhanc
11207
12550
  },
11208
12551
  logger: {
11209
12552
  info: (...args) => {
11210
- writeResult(withCommandName(args.length === 1 ? args[0] : args, commandName), sensitiveDirectory);
12553
+ const value = withCommandName(args.length === 1 ? args[0] : args, commandName);
12554
+ hasPrintedHelp ||= typeof value === "string" && isHelpText(value);
12555
+ if (hasPrintedHelp && typeof value === "string") process.stdout.write(value);
12556
+ else writeResult(value, sensitiveDirectory);
11211
12557
  },
11212
12558
  error: (...args) => {
11213
12559
  const message = String(withCommandName(args.map(String).join(""), commandName));
@@ -11221,6 +12567,7 @@ const createNdjsonLoggerAdapter = (state, configDirectory, commandName = "enhanc
11221
12567
 
11222
12568
  //#endregion
11223
12569
  //#region src/main.ts
12570
+ installZodMessages();
11224
12571
  const main = async () => {
11225
12572
  const config = readCliEnvironment();
11226
12573
  const state = {
@@ -11228,19 +12575,20 @@ const main = async () => {
11228
12575
  pendingParserMessage: null
11229
12576
  };
11230
12577
  const output = createNdjsonLoggerAdapter(state, config.configDirectory, config.commandName);
11231
- const credentials = createFileCredentialAdapter(config.configDirectory);
12578
+ const credentials = createFileCredentialAdapter(config.configDirectory, config.earlierConfigDirectory);
11232
12579
  const mutationKey = createMutationKeyAdapter();
11233
12580
  const remote = createHttpRemoteAdapter(config.apiUrl, credentials, mutationKey);
11234
12581
  const cli = createCliProgram({
11235
12582
  apiUrl: config.apiUrl,
11236
- version: "0.1.160",
12583
+ version: "0.1.165",
11237
12584
  credentials,
11238
12585
  remote,
11239
12586
  mutationKey,
11240
12587
  output,
11241
12588
  state,
11242
12589
  configDirectory: config.configDirectory,
11243
- commandName: config.commandName
12590
+ commandName: config.commandName,
12591
+ machine: readToolMachine()
11244
12592
  });
11245
12593
  try {
11246
12594
  await cli.run();