libretto 0.6.11 → 0.6.12

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.
Files changed (119) hide show
  1. package/README.md +4 -0
  2. package/README.template.md +4 -0
  3. package/dist/cli/cli.js +4 -3
  4. package/dist/cli/commands/ai.js +3 -2
  5. package/dist/cli/commands/browser.js +17 -17
  6. package/dist/cli/commands/execution.js +254 -234
  7. package/dist/cli/commands/experiments.js +100 -0
  8. package/dist/cli/commands/setup.js +20 -34
  9. package/dist/cli/commands/shared.js +10 -0
  10. package/dist/cli/commands/snapshot.js +81 -9
  11. package/dist/cli/commands/status.js +5 -4
  12. package/dist/cli/core/ai-model.js +6 -3
  13. package/dist/cli/core/browser.js +300 -121
  14. package/dist/cli/core/config.js +4 -2
  15. package/dist/cli/core/context.js +4 -0
  16. package/dist/cli/core/daemon/config.js +0 -6
  17. package/dist/cli/core/daemon/daemon.js +535 -89
  18. package/dist/cli/core/daemon/ipc.js +170 -129
  19. package/dist/cli/core/daemon/snapshot.js +72 -6
  20. package/dist/cli/core/experiments.js +66 -0
  21. package/dist/cli/core/session.js +5 -4
  22. package/dist/cli/core/skill-version.js +2 -1
  23. package/dist/cli/core/snapshot-analyzer.js +4 -3
  24. package/dist/cli/core/workflow-runner/runner.js +147 -0
  25. package/dist/cli/core/workflow-runtime.js +60 -0
  26. package/dist/cli/router.js +4 -1
  27. package/dist/shared/debug/pause-handler.d.ts +9 -0
  28. package/dist/shared/debug/pause-handler.js +15 -0
  29. package/dist/shared/debug/pause.d.ts +1 -2
  30. package/dist/shared/debug/pause.js +13 -36
  31. package/dist/shared/ipc/child-process-transport.d.ts +7 -0
  32. package/dist/shared/ipc/child-process-transport.js +60 -0
  33. package/dist/shared/ipc/child-process-transport.spec.d.ts +2 -0
  34. package/dist/shared/ipc/child-process-transport.spec.js +68 -0
  35. package/dist/shared/ipc/ipc.d.ts +46 -0
  36. package/dist/shared/ipc/ipc.js +165 -0
  37. package/dist/shared/ipc/ipc.spec.d.ts +2 -0
  38. package/dist/shared/ipc/ipc.spec.js +114 -0
  39. package/dist/shared/ipc/socket-transport.d.ts +9 -0
  40. package/dist/shared/ipc/socket-transport.js +143 -0
  41. package/dist/shared/ipc/socket-transport.spec.d.ts +2 -0
  42. package/dist/shared/ipc/socket-transport.spec.js +117 -0
  43. package/dist/shared/package-manager.d.ts +7 -0
  44. package/dist/shared/package-manager.js +60 -0
  45. package/dist/shared/paths/paths.d.ts +1 -8
  46. package/dist/shared/paths/paths.js +1 -49
  47. package/dist/shared/snapshot/capture-snapshot.d.ts +9 -0
  48. package/dist/shared/snapshot/capture-snapshot.js +463 -0
  49. package/dist/shared/snapshot/diff-snapshots.d.ts +72 -0
  50. package/dist/shared/snapshot/diff-snapshots.js +358 -0
  51. package/dist/shared/snapshot/render-snapshot.d.ts +39 -0
  52. package/dist/shared/snapshot/render-snapshot.js +651 -0
  53. package/dist/shared/snapshot/snapshot.spec.d.ts +2 -0
  54. package/dist/shared/snapshot/snapshot.spec.js +333 -0
  55. package/dist/shared/snapshot/types.d.ts +40 -0
  56. package/dist/shared/snapshot/types.js +0 -0
  57. package/dist/shared/snapshot/wait-for-page-stable.d.ts +17 -0
  58. package/dist/shared/snapshot/wait-for-page-stable.js +281 -0
  59. package/dist/shared/state/session-state.d.ts +1 -0
  60. package/dist/shared/state/session-state.js +1 -0
  61. package/docs/experiments.md +67 -0
  62. package/package.json +4 -2
  63. package/skills/libretto/SKILL.md +3 -1
  64. package/skills/libretto-readonly/SKILL.md +1 -1
  65. package/src/cli/AGENTS.md +7 -0
  66. package/src/cli/cli.ts +4 -3
  67. package/src/cli/commands/ai.ts +3 -2
  68. package/src/cli/commands/browser.ts +13 -11
  69. package/src/cli/commands/execution.ts +303 -271
  70. package/src/cli/commands/experiments.ts +120 -0
  71. package/src/cli/commands/setup.ts +18 -36
  72. package/src/cli/commands/shared.ts +20 -0
  73. package/src/cli/commands/snapshot.ts +99 -11
  74. package/src/cli/commands/status.ts +5 -4
  75. package/src/cli/core/ai-model.ts +6 -3
  76. package/src/cli/core/browser.ts +369 -147
  77. package/src/cli/core/config.ts +3 -1
  78. package/src/cli/core/context.ts +4 -0
  79. package/src/cli/core/daemon/config.ts +35 -19
  80. package/src/cli/core/daemon/daemon.ts +686 -106
  81. package/src/cli/core/daemon/ipc.ts +330 -214
  82. package/src/cli/core/daemon/snapshot.ts +106 -8
  83. package/src/cli/core/experiments.ts +85 -0
  84. package/src/cli/core/session.ts +5 -4
  85. package/src/cli/core/skill-version.ts +2 -1
  86. package/src/cli/core/snapshot-analyzer.ts +4 -3
  87. package/src/cli/core/workflow-runner/runner.ts +237 -0
  88. package/src/cli/core/workflow-runtime.ts +85 -0
  89. package/src/cli/router.ts +4 -1
  90. package/src/shared/debug/pause-handler.ts +20 -0
  91. package/src/shared/debug/pause.ts +14 -48
  92. package/src/shared/ipc/AGENTS.md +24 -0
  93. package/src/shared/ipc/child-process-transport.spec.ts +86 -0
  94. package/src/shared/ipc/child-process-transport.ts +96 -0
  95. package/src/shared/ipc/ipc.spec.ts +161 -0
  96. package/src/shared/ipc/ipc.ts +288 -0
  97. package/src/shared/ipc/socket-transport.spec.ts +141 -0
  98. package/src/shared/ipc/socket-transport.ts +189 -0
  99. package/src/shared/package-manager.ts +76 -0
  100. package/src/shared/paths/paths.ts +0 -72
  101. package/src/shared/snapshot/capture-snapshot.ts +615 -0
  102. package/src/shared/snapshot/diff-snapshots.ts +579 -0
  103. package/src/shared/snapshot/render-snapshot.ts +962 -0
  104. package/src/shared/snapshot/snapshot.spec.ts +388 -0
  105. package/src/shared/snapshot/types.ts +43 -0
  106. package/src/shared/snapshot/wait-for-page-stable.ts +425 -0
  107. package/src/shared/state/session-state.ts +1 -0
  108. package/dist/cli/core/daemon/index.js +0 -16
  109. package/dist/cli/core/daemon/spawn.js +0 -90
  110. package/dist/cli/core/pause-signals.js +0 -29
  111. package/dist/cli/workers/run-integration-runtime.js +0 -235
  112. package/dist/cli/workers/run-integration-worker-protocol.js +0 -17
  113. package/dist/cli/workers/run-integration-worker.js +0 -64
  114. package/src/cli/core/daemon/index.ts +0 -24
  115. package/src/cli/core/daemon/spawn.ts +0 -171
  116. package/src/cli/core/pause-signals.ts +0 -35
  117. package/src/cli/workers/run-integration-runtime.ts +0 -326
  118. package/src/cli/workers/run-integration-worker-protocol.ts +0 -19
  119. package/src/cli/workers/run-integration-worker.ts +0 -72
@@ -1,7 +1,21 @@
1
1
  import { createHash } from "node:crypto";
2
- import { createServer, connect as netConnect } from "node:net";
3
- import { unlink } from "node:fs/promises";
2
+ import { spawn } from "node:child_process";
3
+ import { openSync, closeSync } from "node:fs";
4
+ import { createRequire } from "node:module";
5
+ import { fileURLToPath } from "node:url";
6
+ import { createIpcPeer } from "../../../shared/ipc/ipc.js";
7
+ import { connectToIpcSocket } from "../../../shared/ipc/socket-transport.js";
4
8
  import { REPO_ROOT } from "../context.js";
9
+ function createNoopDaemonToCliHandlers() {
10
+ return {
11
+ workflowOutput: () => {
12
+ },
13
+ workflowPaused: () => {
14
+ },
15
+ workflowFinished: () => {
16
+ }
17
+ };
18
+ }
5
19
  class DaemonClientError extends Error {
6
20
  constructor(message, output) {
7
21
  super(message);
@@ -9,163 +23,190 @@ class DaemonClientError extends Error {
9
23
  this.name = "DaemonClientError";
10
24
  }
11
25
  }
26
+ function isDaemonReadyMessage(message) {
27
+ if (typeof message !== "object" || message === null) return false;
28
+ const candidate = message;
29
+ return candidate.type === "ready" && typeof candidate.socketPath === "string";
30
+ }
31
+ function isDaemonStartupErrorMessage(message) {
32
+ if (typeof message !== "object" || message === null) return false;
33
+ const candidate = message;
34
+ return candidate.type === "startup-error" && typeof candidate.message === "string";
35
+ }
12
36
  function getDaemonSocketPath(session) {
13
37
  const hash = createHash("sha256").update(`${REPO_ROOT}:${session}`).digest("hex").slice(0, 12);
14
38
  return `/tmp/libretto-${process.getuid()}-${hash}.sock`;
15
39
  }
16
- class DaemonServer {
17
- constructor(socketPath, handler) {
18
- this.socketPath = socketPath;
19
- this.handler = handler;
40
+ class DaemonClient {
41
+ constructor(ipc) {
42
+ this.ipc = ipc;
20
43
  }
21
- server = null;
22
- async listen() {
23
- try {
24
- await unlink(this.socketPath);
25
- } catch (err) {
26
- if (err.code !== "ENOENT") throw err;
27
- }
28
- const server = createServer((socket) => {
29
- let buffer = "";
30
- socket.on("data", (chunk) => {
31
- buffer += chunk.toString();
32
- const newlineIndex = buffer.indexOf("\n");
33
- if (newlineIndex === -1) return;
34
- const line = buffer.slice(0, newlineIndex);
35
- buffer = buffer.slice(newlineIndex + 1);
36
- void (async () => {
37
- let response;
38
- try {
39
- const request = JSON.parse(line);
40
- const data = await this.handler(request);
41
- response = { id: request.id, type: "result", data };
42
- } catch (err) {
43
- const id = (() => {
44
- try {
45
- return JSON.parse(line).id ?? "unknown";
46
- } catch {
47
- return "unknown";
48
- }
49
- })();
50
- response = {
51
- id,
52
- type: "error",
53
- message: err instanceof Error ? err.message : String(err),
54
- output: err instanceof Error ? err.output : void 0
55
- };
56
- }
57
- socket.end(JSON.stringify(response) + "\n");
58
- })();
59
- });
60
- });
61
- this.server = server;
62
- await new Promise((resolve, reject) => {
63
- server.on("error", reject);
64
- server.listen(this.socketPath, () => resolve());
65
- });
44
+ static async connect(socketPath, handlers = createNoopDaemonToCliHandlers()) {
45
+ const transport = await connectToIpcSocket(socketPath);
46
+ return new DaemonClient(
47
+ createIpcPeer(transport, handlers)
48
+ );
66
49
  }
67
- async close() {
68
- const server = this.server;
69
- if (!server) return;
70
- this.server = null;
71
- await new Promise((resolve, reject) => {
72
- server.close((err) => err ? reject(err) : resolve());
50
+ static async spawn(options) {
51
+ const { config, logger, logPath, startupTimeoutMs, handlers, onFailure } = options;
52
+ const { session } = config;
53
+ const daemonEntryPath = fileURLToPath(
54
+ new URL("./daemon.js", import.meta.url)
55
+ );
56
+ const require2 = createRequire(import.meta.url);
57
+ const tsxCliPath = require2.resolve("tsx/cli");
58
+ const childStderrFd = openSync(logPath, "a");
59
+ const child = spawn(
60
+ process.execPath,
61
+ [
62
+ tsxCliPath,
63
+ ...config.workflow?.tsconfigPath ? ["--tsconfig", config.workflow.tsconfigPath] : [],
64
+ daemonEntryPath,
65
+ JSON.stringify(config)
66
+ ],
67
+ {
68
+ detached: true,
69
+ stdio: ["ignore", "ignore", childStderrFd, "ipc"]
70
+ }
71
+ );
72
+ closeSync(childStderrFd);
73
+ const pid = child.pid;
74
+ logger.info("daemon-spawned", { pid, session });
75
+ const readyMessage = await DaemonClient.waitForReadyMessage({
76
+ child,
77
+ timeoutMs: startupTimeoutMs,
78
+ formatTimeoutError: () => new Error(
79
+ `Daemon failed to start within ${Math.ceil(startupTimeoutMs / 1e3)}s. Check logs: ${logPath}`
80
+ ),
81
+ formatSpawnError: (error) => {
82
+ const errWithCode = error;
83
+ const hint = errWithCode.code === "ENOENT" ? " Ensure Node.js is available in PATH for child processes." : "";
84
+ return new Error(
85
+ `Failed to spawn daemon: ${error.message}.${hint} Check logs: ${logPath}`
86
+ );
87
+ },
88
+ formatExitError: (code, signal) => {
89
+ const status = code ?? signal ?? "unknown";
90
+ return new Error(
91
+ `Daemon exited before startup (status: ${status}). Check logs: ${logPath}`
92
+ );
93
+ },
94
+ onReady: (message) => {
95
+ logger.info("daemon-ready", {
96
+ session,
97
+ socketPath: message.socketPath,
98
+ pid
99
+ });
100
+ child.disconnect();
101
+ child.unref();
102
+ },
103
+ onSpawnError: (error) => {
104
+ logger.error("daemon-spawn-error", { error, session });
105
+ },
106
+ onExit: (code, signal, ready) => {
107
+ logger.warn("daemon-exit", { code, signal, session, pid, ready });
108
+ }
109
+ }).catch(async (error) => {
110
+ try {
111
+ process.kill(pid, "SIGTERM");
112
+ } catch {
113
+ }
114
+ await onFailure?.();
115
+ throw error;
73
116
  });
74
- try {
75
- await unlink(this.socketPath);
76
- } catch (err) {
77
- if (err.code !== "ENOENT") throw err;
78
- }
79
- }
80
- }
81
- class DaemonClient {
82
- constructor(socketPath) {
83
- this.socketPath = socketPath;
117
+ const client = await DaemonClient.connect(
118
+ readyMessage.socketPath,
119
+ handlers
120
+ );
121
+ const socketPath = readyMessage.socketPath;
122
+ logger.info("daemon-ipc-ready", { session, socketPath });
123
+ return { pid, socketPath, provider: readyMessage.provider, client };
84
124
  }
85
- async send(request) {
125
+ static async waitForReadyMessage(args) {
126
+ const {
127
+ child,
128
+ timeoutMs,
129
+ formatTimeoutError,
130
+ formatSpawnError,
131
+ formatExitError,
132
+ onReady,
133
+ onSpawnError,
134
+ onExit
135
+ } = args;
86
136
  return new Promise((resolve, reject) => {
87
- const socket = netConnect(this.socketPath);
88
- let buffer = "";
89
- socket.on("connect", () => {
90
- socket.write(JSON.stringify(request) + "\n");
91
- });
92
- socket.on("data", (chunk) => {
93
- buffer += chunk.toString();
94
- });
95
- socket.on("end", () => {
96
- try {
97
- const response = JSON.parse(buffer.trim());
98
- resolve(response);
99
- } catch (err) {
100
- reject(
101
- new Error(
102
- `Failed to parse daemon response: ${err instanceof Error ? err.message : String(err)}`
103
- )
104
- );
137
+ let ready = false;
138
+ let timeout;
139
+ const cleanup = () => {
140
+ clearTimeout(timeout);
141
+ child.off("message", onMessage);
142
+ child.off("error", onError);
143
+ child.off("exit", onChildExit);
144
+ };
145
+ const fail = (error) => {
146
+ cleanup();
147
+ reject(error);
148
+ };
149
+ timeout = setTimeout(() => fail(formatTimeoutError()), timeoutMs);
150
+ const onMessage = (message) => {
151
+ if (isDaemonStartupErrorMessage(message)) {
152
+ fail(new Error(message.message));
153
+ return;
105
154
  }
106
- });
107
- socket.on("error", (err) => {
108
- reject(err);
109
- });
110
- });
111
- }
112
- generateId() {
113
- return Math.random().toString(36).slice(2, 10);
114
- }
115
- async sendOrThrow(request) {
116
- const response = await this.send(request);
117
- if (response.type === "error") {
118
- throw new DaemonClientError(response.message, response.output);
119
- }
120
- return response.data;
121
- }
122
- async sendResult(request) {
123
- const response = await this.send(request);
124
- if (response.type === "error") {
125
- return {
126
- ok: false,
127
- message: response.message,
128
- output: response.output
155
+ if (!isDaemonReadyMessage(message)) return;
156
+ ready = true;
157
+ cleanup();
158
+ onReady?.(message);
159
+ resolve(message);
129
160
  };
130
- }
131
- return { ok: true, data: response.data };
161
+ const onError = (error) => {
162
+ onSpawnError?.(error);
163
+ fail(formatSpawnError(error));
164
+ };
165
+ const onChildExit = (code, signal) => {
166
+ onExit?.(code, signal, ready);
167
+ if (ready) return;
168
+ fail(formatExitError(code, signal));
169
+ };
170
+ child.on("message", onMessage);
171
+ child.on("error", onError);
172
+ child.on("exit", onChildExit);
173
+ });
132
174
  }
133
175
  async ping() {
134
176
  try {
135
- await this.sendOrThrow({ id: this.generateId(), command: "ping" });
177
+ await this.ipc.call.ping();
136
178
  return true;
137
179
  } catch {
138
180
  return false;
139
181
  }
140
182
  }
141
183
  async pages() {
142
- return this.sendOrThrow({ id: this.generateId(), command: "pages" });
184
+ return this.ipc.call.pages();
143
185
  }
144
186
  async exec(args) {
145
- return this.sendResult({
146
- id: this.generateId(),
147
- command: "exec",
148
- ...args
149
- });
187
+ return this.ipc.call.exec(args);
150
188
  }
151
189
  async readonlyExec(args) {
152
- return this.sendResult({
153
- id: this.generateId(),
154
- command: "readonly-exec",
155
- ...args
156
- });
190
+ return this.ipc.call.readonlyExec(args);
157
191
  }
158
192
  async snapshot(args = {}) {
159
- return this.sendOrThrow({
160
- id: this.generateId(),
161
- command: "snapshot",
162
- ...args
163
- });
193
+ return this.ipc.call.snapshot(args);
194
+ }
195
+ async getWorkflowStatus() {
196
+ return this.ipc.call.getWorkflowStatus();
197
+ }
198
+ async resumeWorkflow() {
199
+ await this.ipc.call.resumeWorkflow();
200
+ }
201
+ async close() {
202
+ return this.ipc.call.close();
203
+ }
204
+ destroy() {
205
+ this.ipc.destroy();
164
206
  }
165
207
  }
166
208
  export {
167
209
  DaemonClient,
168
210
  DaemonClientError,
169
- DaemonServer,
170
211
  getDaemonSocketPath
171
212
  };
@@ -1,5 +1,10 @@
1
1
  import { mkdirSync, writeFileSync } from "node:fs";
2
2
  import { getSessionSnapshotRunDir } from "../context.js";
3
+ import {
4
+ snapshot
5
+ } from "../../../shared/snapshot/capture-snapshot.js";
6
+ import { waitForPageStable } from "../../../shared/snapshot/wait-for-page-stable.js";
7
+ import { librettoCommand } from "../../../shared/package-manager.js";
3
8
  import {
4
9
  resolveSnapshotViewport,
5
10
  readSnapshotViewportMetrics,
@@ -9,6 +14,71 @@ import {
9
14
  } from "../../commands/snapshot.js";
10
15
  const RENDER_SETTLE_TIMEOUT_MS = 1e4;
11
16
  async function handleSnapshot(targetPage, session, logger, pageId) {
17
+ const screenshot = await captureSnapshotScreenshot(
18
+ targetPage,
19
+ session,
20
+ logger,
21
+ pageId
22
+ );
23
+ const htmlPath = `${getSessionSnapshotRunDir(
24
+ session,
25
+ screenshot.snapshotRunId
26
+ )}/page.html`;
27
+ const htmlContent = await targetPage.content();
28
+ writeFileSync(htmlPath, htmlContent);
29
+ logger.info("screenshot-success", {
30
+ session,
31
+ pageUrl: screenshot.pageUrl,
32
+ title: screenshot.title,
33
+ pngPath: screenshot.pngPath,
34
+ htmlPath,
35
+ snapshotRunId: screenshot.snapshotRunId
36
+ });
37
+ return {
38
+ ...screenshot,
39
+ htmlPath
40
+ };
41
+ }
42
+ async function handleCompactSnapshot(targetPage, session, logger, options = {}) {
43
+ if (options.useCachedSnapshot) {
44
+ if (!options.cachedSnapshot) {
45
+ throw new Error(
46
+ `No compact snapshot is cached for session "${session}". Run ${librettoCommand(`snapshot --session ${session}`)} first.`
47
+ );
48
+ }
49
+ const screenshot2 = await captureSnapshotScreenshot(
50
+ targetPage,
51
+ session,
52
+ logger,
53
+ options.pageId
54
+ );
55
+ return {
56
+ mode: "compact",
57
+ pngPath: screenshot2.pngPath,
58
+ snapshot: options.cachedSnapshot
59
+ };
60
+ }
61
+ const waitResult = await waitForPageStable(targetPage);
62
+ if (!waitResult.ok) {
63
+ logger.warn("compact-snapshot-stability-wait-incomplete", {
64
+ session,
65
+ pageId: options.pageId,
66
+ diagnostics: waitResult.diagnostics
67
+ });
68
+ }
69
+ const screenshot = await captureSnapshotScreenshot(
70
+ targetPage,
71
+ session,
72
+ logger,
73
+ options.pageId
74
+ );
75
+ return {
76
+ mode: "compact",
77
+ pngPath: screenshot.pngPath,
78
+ snapshot: await snapshot(targetPage)
79
+ };
80
+ }
81
+ async function captureSnapshotScreenshot(targetPage, session, logger, pageId) {
12
82
  const snapshotRunId = `snapshot-${Date.now()}`;
13
83
  const snapshotRunDir = getSessionSnapshotRunDir(session, snapshotRunId);
14
84
  mkdirSync(snapshotRunDir, { recursive: true });
@@ -25,7 +95,6 @@ async function handleSnapshot(targetPage, session, logger, pageId) {
25
95
  logger.warn("screenshot-url-read-failed", { session, pageId, error });
26
96
  }
27
97
  const pngPath = `${snapshotRunDir}/page.png`;
28
- const htmlPath = `${snapshotRunDir}/page.html`;
29
98
  await Promise.race([
30
99
  targetPage.waitForLoadState("networkidle").catch(() => {
31
100
  }),
@@ -63,24 +132,21 @@ async function handleSnapshot(targetPage, session, logger, pageId) {
63
132
  );
64
133
  await targetPage.screenshot({ path: pngPath });
65
134
  }
66
- const htmlContent = await targetPage.content();
67
- writeFileSync(htmlPath, htmlContent);
68
- logger.info("screenshot-success", {
135
+ logger.info("screenshot-captured", {
69
136
  session,
70
137
  pageUrl,
71
138
  title,
72
139
  pngPath,
73
- htmlPath,
74
140
  snapshotRunId
75
141
  });
76
142
  return {
77
143
  pngPath,
78
- htmlPath,
79
144
  snapshotRunId,
80
145
  pageUrl: pageUrl ?? "",
81
146
  title: title ?? ""
82
147
  };
83
148
  }
84
149
  export {
150
+ handleCompactSnapshot,
85
151
  handleSnapshot
86
152
  };
@@ -0,0 +1,66 @@
1
+ import {
2
+ readLibrettoConfig,
3
+ writeLibrettoConfig
4
+ } from "./config.js";
5
+ const EXPERIMENTS = {
6
+ "compact-snapshot-format": {
7
+ title: "Compact snapshot format",
8
+ oneSentenceDescription: "Use compact accessibility snapshots and exec page-change diffs without an AI sub-agent.",
9
+ docs: [
10
+ "Compact snapshot format changes how agents should use snapshot and exec after the experiment is enabled.",
11
+ "",
12
+ "Compared with the skill's documented behavior:",
13
+ " - Run libretto snapshot --session <name> without --objective or --context.",
14
+ " - Snapshot output is a screenshot path plus a compact accessibility tree; it does not use the PNG + HTML + AI analysis path.",
15
+ " - Run libretto snapshot <ref> --session <name> to inspect a subtree from the latest full compact snapshot.",
16
+ " - Run libretto exec normally; after successful mutations, Libretto prints page-change diffs from compact snapshots without AI analysis.",
17
+ " - If a session was already open before enabling the experiment, close and reopen it before relying on this behavior.",
18
+ "",
19
+ "Full compact snapshot:",
20
+ " libretto snapshot --session <name>",
21
+ "",
22
+ "Cached subtree snapshot:",
23
+ " libretto snapshot <ref> --session <name>",
24
+ "",
25
+ "Run an unscoped snapshot before using refs. Subtree snapshots capture a fresh screenshot but reuse the latest cached tree.",
26
+ "",
27
+ "Notes:",
28
+ " - Use ref forms printed in the tree, such as l16. Numeric-suffix aliases such as e16 also match l16."
29
+ ].join("\n"),
30
+ defaultValue: false
31
+ }
32
+ };
33
+ function isExperimentName(name) {
34
+ return Object.hasOwn(EXPERIMENTS, name);
35
+ }
36
+ function resolveExperiments(config = readLibrettoConfig()) {
37
+ return Object.fromEntries(
38
+ Object.entries(EXPERIMENTS).map(([name, metadata]) => [
39
+ name,
40
+ config.experiments?.[name] ?? metadata.defaultValue
41
+ ])
42
+ );
43
+ }
44
+ function setExperimentEnabled(name, enabled, configPath) {
45
+ if (!isExperimentName(name)) {
46
+ throw new Error(`Unknown experiment "${name}".`);
47
+ }
48
+ const config = readLibrettoConfig(configPath);
49
+ const writtenConfig = writeLibrettoConfig(
50
+ {
51
+ ...config,
52
+ experiments: {
53
+ ...config.experiments,
54
+ [name]: enabled
55
+ }
56
+ },
57
+ configPath
58
+ );
59
+ return resolveExperiments(writtenConfig);
60
+ }
61
+ export {
62
+ EXPERIMENTS,
63
+ isExperimentName,
64
+ resolveExperiments,
65
+ setExperimentEnabled
66
+ };
@@ -18,6 +18,7 @@ import {
18
18
  parseSessionStateContent,
19
19
  serializeSessionState
20
20
  } from "../../shared/state/index.js";
21
+ import { librettoCommand } from "../../shared/package-manager.js";
21
22
  const SESSION_NAME_PATTERN = /^[a-zA-Z0-9._-]+$/;
22
23
  const SESSION_DEV_SERVER = "dev-server";
23
24
  const SESSION_BROWSER_AGENT = "browser-agent";
@@ -119,7 +120,7 @@ function throwSessionNotFoundError(session) {
119
120
  }
120
121
  lines.push("");
121
122
  lines.push("Start one with:");
122
- lines.push(` libretto open <url> --session ${session}`);
123
+ lines.push(` ${librettoCommand(`open <url> --session ${session}`)}`);
123
124
  throw new Error(lines.join("\n"));
124
125
  }
125
126
  function assertSessionStateExistsOrThrow(session) {
@@ -176,7 +177,7 @@ function assertSessionAllowsCommand(state, commandName, allowedModes) {
176
177
  }
177
178
  const supportedModes = [...allowedModes].join(", ");
178
179
  throw new Error(
179
- `Command "${commandName}" is blocked for session "${state.session}" because it is in ${mode} mode. Allowed modes for this command: ${supportedModes}. Run \`libretto session-mode write-access --session ${state.session}\` to unlock the session.`
180
+ `Command "${commandName}" is blocked for session "${state.session}" because it is in ${mode} mode. Allowed modes for this command: ${supportedModes}. Run \`${librettoCommand(`session-mode write-access --session ${state.session}`)}\` to unlock the session.`
180
181
  );
181
182
  }
182
183
  function clearSessionState(session, logger) {
@@ -213,7 +214,7 @@ function assertSessionAvailableForStart(session, logger) {
213
214
  if (!existingState) return;
214
215
  if (existingState.provider && existingState.cdpEndpoint) {
215
216
  throw new Error(
216
- `Session "${session}" is already open via ${existingState.provider.name} provider. Close it first with: libretto close --session ${session}`
217
+ `Session "${session}" is already open via ${existingState.provider.name} provider. Close it first with: ${librettoCommand(`close --session ${session}`)}`
217
218
  );
218
219
  }
219
220
  if (existingState.pid == null || !isPidRunning(existingState.pid)) {
@@ -222,7 +223,7 @@ function assertSessionAvailableForStart(session, logger) {
222
223
  }
223
224
  const endpoint = `http://127.0.0.1:${existingState.port}`;
224
225
  throw new Error(
225
- `Session "${session}" is already open and connected to ${endpoint} (pid ${existingState.pid}). Create a new session or close the current one with: libretto close --session ${session}`
226
+ `Session "${session}" is already open and connected to ${endpoint} (pid ${existingState.pid}). Create a new session or close the current one with: ${librettoCommand(`close --session ${session}`)}`
226
227
  );
227
228
  }
228
229
  export {
@@ -2,6 +2,7 @@ import { existsSync, readFileSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  import { fileURLToPath } from "node:url";
4
4
  import { REPO_ROOT } from "./context.js";
5
+ import { librettoCommand } from "../../shared/package-manager.js";
5
6
  const INSTALLED_SKILL_PATHS = [
6
7
  [".agents", "skills", "libretto", "SKILL.md"],
7
8
  [".claude", "skills", "libretto", "SKILL.md"]
@@ -63,7 +64,7 @@ function warnIfInstalledSkillOutOfDate() {
63
64
  return;
64
65
  }
65
66
  console.error(
66
- `Warning: Your agent skill (${mismatch.installedVersion}) is out of date with your Libretto CLI (${mismatch.cliVersion}). Please run \`npx libretto setup\` to update your skills to the correct version.`
67
+ `Warning: Your agent skill (${mismatch.installedVersion}) is out of date with your Libretto CLI (${mismatch.cliVersion}). Please run \`${librettoCommand("setup")}\` to update your skills to the correct version.`
67
68
  );
68
69
  } catch {
69
70
  }
@@ -3,6 +3,7 @@ import { extname, isAbsolute, join, resolve } from "node:path";
3
3
  import { spawn } from "node:child_process";
4
4
  import { tmpdir } from "node:os";
5
5
  import { z } from "zod";
6
+ import { librettoCommand } from "../../shared/package-manager.js";
6
7
  const InterpretResultSchema = z.object({
7
8
  answer: z.string(),
8
9
  selectors: z.array(
@@ -171,7 +172,7 @@ async function runExternalCommand(command, args, logger, stdinText) {
171
172
  if (error.code === "ENOENT") {
172
173
  reject(
173
174
  new Error(
174
- `Command not found: ${command}. Configure AI with 'libretto ai configure'.`
175
+ `Command not found: ${command}. Configure AI with '${librettoCommand("ai configure")}'.`
175
176
  )
176
177
  );
177
178
  return;
@@ -645,12 +646,12 @@ async function runInterpret(args, logger) {
645
646
  const configuredAgent = UserCodingAgent.getConfigured();
646
647
  if (!configuredAgent) {
647
648
  throw new Error(
648
- "No AI config set. Run 'npx libretto ai configure codex' (or claude/gemini), or set API credentials in your .env file for direct API analysis."
649
+ `No AI config set. Run '${librettoCommand("ai configure codex")}' (or claude/gemini), or set API credentials in your .env file for direct API analysis.`
649
650
  );
650
651
  }
651
652
  const configuredAnalyzer = configuredAgent.snapshotAnalyzerConfig;
652
653
  throw new Error(
653
- "The CLI-agent snapshot analysis path is not active. Update your config to the current format with `npx libretto ai configure <provider>`, or set API credentials in .env for direct API analysis."
654
+ `The CLI-agent snapshot analysis path is not active. Update your config to the current format with \`${librettoCommand("ai configure <provider>")}\`, or set API credentials in .env for direct API analysis.`
654
655
  );
655
656
  }
656
657
  function canAnalyzeSnapshots() {