libretto 0.5.0 → 0.5.2

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 (122) hide show
  1. package/README.md +109 -35
  2. package/dist/cli/cli.js +22 -97
  3. package/dist/cli/commands/browser.js +86 -59
  4. package/dist/cli/commands/execution.js +199 -86
  5. package/dist/cli/commands/init.js +34 -29
  6. package/dist/cli/commands/logs.js +4 -5
  7. package/dist/cli/commands/shared.js +30 -29
  8. package/dist/cli/commands/snapshot.js +26 -39
  9. package/dist/cli/core/ai-config.js +21 -4
  10. package/dist/cli/core/api-snapshot-analyzer.js +15 -5
  11. package/dist/cli/core/browser.js +207 -37
  12. package/dist/cli/core/context.js +4 -1
  13. package/dist/cli/core/session-telemetry.js +434 -174
  14. package/dist/cli/core/session.js +21 -8
  15. package/dist/cli/core/snapshot-analyzer.js +14 -31
  16. package/dist/cli/core/snapshot-api-config.js +2 -6
  17. package/dist/cli/core/telemetry.js +20 -4
  18. package/dist/cli/framework/simple-cli.js +45 -25
  19. package/dist/cli/router.js +14 -21
  20. package/dist/cli/workers/run-integration-runtime.js +24 -5
  21. package/dist/cli/workers/run-integration-worker-protocol.js +3 -1
  22. package/dist/cli/workers/run-integration-worker.js +1 -4
  23. package/dist/index.d.ts +1 -2
  24. package/dist/index.js +7 -10
  25. package/dist/runtime/download/download.js +5 -1
  26. package/dist/runtime/extract/extract.js +11 -2
  27. package/dist/runtime/network/network.js +8 -1
  28. package/dist/runtime/recovery/agent.js +6 -2
  29. package/dist/runtime/recovery/errors.js +3 -1
  30. package/dist/runtime/recovery/recovery.js +3 -1
  31. package/dist/shared/condense-dom/condense-dom.js +17 -69
  32. package/dist/shared/config/config.d.ts +1 -9
  33. package/dist/shared/config/config.js +0 -18
  34. package/dist/shared/config/index.d.ts +2 -1
  35. package/dist/shared/config/index.js +0 -10
  36. package/dist/shared/debug/pause.js +9 -3
  37. package/dist/shared/dom-semantics.d.ts +8 -0
  38. package/dist/shared/dom-semantics.js +69 -0
  39. package/dist/shared/instrumentation/instrument.js +101 -5
  40. package/dist/shared/llm/ai-sdk-adapter.js +3 -1
  41. package/dist/shared/llm/client.js +3 -1
  42. package/dist/shared/logger/index.js +4 -1
  43. package/dist/shared/run/api.js +3 -1
  44. package/dist/shared/run/browser.js +47 -3
  45. package/dist/shared/state/session-state.d.ts +2 -1
  46. package/dist/shared/state/session-state.js +5 -2
  47. package/dist/shared/visualization/ghost-cursor.js +36 -14
  48. package/dist/shared/visualization/highlight.js +9 -6
  49. package/dist/shared/workflow/workflow.d.ts +4 -5
  50. package/dist/shared/workflow/workflow.js +3 -5
  51. package/package.json +6 -2
  52. package/scripts/check-skills-sync.mjs +25 -0
  53. package/scripts/compare-eval-summary.mjs +47 -0
  54. package/scripts/postinstall.mjs +15 -15
  55. package/scripts/prepare-release.sh +97 -0
  56. package/scripts/skills-libretto.mjs +103 -0
  57. package/scripts/summarize-evals.mjs +135 -0
  58. package/scripts/sync-skills.mjs +12 -0
  59. package/skills/libretto/SKILL.md +132 -54
  60. package/skills/libretto/references/action-logs.md +101 -0
  61. package/skills/libretto/references/auth-profiles.md +1 -2
  62. package/skills/libretto/references/code-generation-rules.md +210 -0
  63. package/skills/libretto/references/configuration-file-reference.md +53 -0
  64. package/skills/libretto/references/pages-and-page-targeting.md +1 -1
  65. package/skills/libretto/references/site-security-review.md +143 -0
  66. package/src/cli/cli.ts +23 -110
  67. package/src/cli/commands/browser.ts +94 -70
  68. package/src/cli/commands/execution.ts +233 -102
  69. package/src/cli/commands/init.ts +37 -33
  70. package/src/cli/commands/logs.ts +7 -7
  71. package/src/cli/commands/shared.ts +36 -37
  72. package/src/cli/commands/snapshot.ts +44 -59
  73. package/src/cli/core/ai-config.ts +24 -4
  74. package/src/cli/core/api-snapshot-analyzer.ts +17 -6
  75. package/src/cli/core/browser.ts +260 -49
  76. package/src/cli/core/context.ts +7 -2
  77. package/src/cli/core/session-telemetry.ts +449 -197
  78. package/src/cli/core/session.ts +21 -7
  79. package/src/cli/core/snapshot-analyzer.ts +26 -46
  80. package/src/cli/core/snapshot-api-config.ts +170 -175
  81. package/src/cli/core/telemetry.ts +39 -4
  82. package/src/cli/framework/simple-cli.ts +144 -77
  83. package/src/cli/router.ts +13 -21
  84. package/src/cli/workers/run-integration-runtime.ts +36 -9
  85. package/src/cli/workers/run-integration-worker-protocol.ts +2 -0
  86. package/src/cli/workers/run-integration-worker.ts +1 -4
  87. package/src/index.ts +73 -66
  88. package/src/runtime/download/download.ts +62 -58
  89. package/src/runtime/download/index.ts +5 -5
  90. package/src/runtime/extract/extract.ts +71 -61
  91. package/src/runtime/network/index.ts +3 -3
  92. package/src/runtime/network/network.ts +99 -93
  93. package/src/runtime/recovery/agent.ts +217 -212
  94. package/src/runtime/recovery/errors.ts +107 -104
  95. package/src/runtime/recovery/index.ts +3 -3
  96. package/src/runtime/recovery/recovery.ts +38 -35
  97. package/src/shared/condense-dom/condense-dom.ts +27 -82
  98. package/src/shared/config/config.ts +0 -19
  99. package/src/shared/config/index.ts +0 -5
  100. package/src/shared/debug/pause.ts +57 -51
  101. package/src/shared/dom-semantics.ts +68 -0
  102. package/src/shared/instrumentation/errors.ts +64 -62
  103. package/src/shared/instrumentation/index.ts +5 -5
  104. package/src/shared/instrumentation/instrument.ts +339 -209
  105. package/src/shared/llm/ai-sdk-adapter.ts +58 -55
  106. package/src/shared/llm/client.ts +181 -174
  107. package/src/shared/llm/types.ts +39 -39
  108. package/src/shared/logger/index.ts +11 -4
  109. package/src/shared/logger/logger.ts +312 -306
  110. package/src/shared/logger/sinks.ts +118 -114
  111. package/src/shared/paths/paths.ts +50 -49
  112. package/src/shared/paths/repo-root.ts +17 -17
  113. package/src/shared/run/api.ts +5 -1
  114. package/src/shared/run/browser.ts +65 -3
  115. package/src/shared/state/index.ts +9 -9
  116. package/src/shared/state/session-state.ts +46 -43
  117. package/src/shared/visualization/ghost-cursor.ts +180 -149
  118. package/src/shared/visualization/highlight.ts +89 -86
  119. package/src/shared/visualization/index.ts +13 -13
  120. package/src/shared/workflow/workflow.ts +19 -25
  121. package/skills/libretto/references/reverse-engineering-network-requests.md +0 -39
  122. package/skills/libretto/references/user-action-log.md +0 -31
package/README.md CHANGED
@@ -1,70 +1,134 @@
1
1
  # Libretto
2
2
 
3
- Libretto gives your coding agent superpowers for building, debugging, and maintaining browser RPA integrations.
3
+ [![npm version](https://img.shields.io/npm/v/libretto)](https://www.npmjs.com/package/libretto)
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
5
+ [![GitHub Discussions](https://img.shields.io/github/discussions/saffron-health/libretto)](https://github.com/saffron-health/libretto/discussions)
4
6
 
5
- It is designed for engineering teams that automate workflows in web apps and want to move from brittle browser-only scripts to faster, more reliable network-first integrations.
7
+ Libretto is a toolkit for building robust web integrations. It gives your coding agent a live browser and a token-efficient CLI to:
6
8
 
7
- ## Installation
9
+ - Inspect live pages with minimal context overhead
10
+ - Capture network traffic to reverse-engineer site APIs
11
+ - Record user actions and replay them as automation scripts
12
+ - Debug broken workflows interactively against the real site
8
13
 
9
- ```bash
10
- npm install --save-dev libretto
11
- ```
14
+ We at [Saffron Health](https://saffron.health) built Libretto to help us maintain our browser integrations to common healthcare software. We're open-sourcing it so other teams have an easier time doing the same thing.
12
15
 
13
- Chromium is downloaded automatically via a `postinstall` script. If postinstall scripts are disabled (e.g. `--ignore-scripts`, common in monorepos), run init manually:
16
+ https://github.com/user-attachments/assets/9b9a0ab3-5133-4b20-b3be-459943349d18
17
+
18
+ ## Installation
14
19
 
15
20
  ```bash
21
+ npm install libretto
22
+
23
+ # Install skill, download Chromium if not already installed, configure snapshot analysis
16
24
  npx libretto init
17
- ```
18
25
 
19
- This installs the Chromium browser binary and optionally configures an AI subagent (Gemini, Claude, or Codex) that can analyze page snapshots without consuming the coding agent's context window.
26
+ # Configure or change the snapshot analysis model (see Configuration section below). `npx libretto init` sets this up the first time.
27
+ npx libretto ai configure <openai | anthropic | gemini | vertex>
28
+ ```
20
29
 
21
- ## Usage
30
+ ## Use cases
22
31
 
23
- Libretto is usually used through prompts with the Libretto skill.
32
+ Libretto is designed to be used as a skill through your coding agent. Here are some example prompts:
24
33
 
25
34
  ### One-shot script generation
26
35
 
27
- ```text
28
- Use the Libretto skill. Go on LinkedIn and scrape the first 10 posts for content, who posted it, the number of reactions, the first 25 comments, and the first 25 reposts.
29
- ```
36
+ > Use the Libretto skill. Go on LinkedIn and scrape the first 10 posts for content, who posted it, the number of reactions, the first 25 comments, and the first 25 reposts.
37
+
38
+ Your coding agent will open a window for you to log into LinkedIn, and then automatically start exploring.
30
39
 
31
40
  ### Interactive script building
32
41
 
33
- ```text
34
- Use the Libretto skill. Let's interactively build a script to scrape scheduling info from the eClinicalWorks EHR.
35
- ```
42
+ > I'm gonna show you a workflow in the eclinicalworks EHR to get a patient's primary insurance ID. Use libretto skill to turn it into a playwright script that takes patient name and dob as input to get back the insurance ID. URL is ...
43
+
44
+ Libretto can read your actions you perform in the browser, so you can perform a workflow, then ask it to use your actions to rebuild the workflow.
36
45
 
37
46
  ### Convert browser automation to network requests
38
47
 
39
- ```text
40
- We have a browser script at ./integration.ts that automates going to Hacker News and getting the first 10 posts. Convert it to direct network scripts instead. Use the Libretto skill.
41
- ```
48
+ > We have a browser script at ./integration.ts that automates going to Hacker News and getting the first 10 posts. Convert it to direct network scripts instead. Use the Libretto skill.
49
+
50
+ Libretto can read network requests from the browser, which it can use to reverse engineer the API and create a script that directly calls those requests. Directly making API calls is faster, and more reliable, than UI automation. You can also ask Libretto to conduct a security analysis which analyzes the requests for common security cookies, so you can understand whether a network request approach will be safe.
42
51
 
43
52
  ### Fix broken integrations
44
53
 
45
- ```text
46
- We have a browser script at ./integration.ts that is supposed to go to Availity and perform an eligibility check for a patient. But I'm getting a broken selector error when I run it. Fix it. Use the Libretto skill.
54
+ > We have a browser script at ./integration.ts that is supposed to go to Availity and perform an eligibility check for a patient. But I'm getting a broken selector error when I run it. Fix it. Use the Libretto skill.
55
+
56
+ Agents can use Libretto to reproduce the failure, pause the workflow at any point, inspect the live page, and fix issues, all autonomously.
57
+
58
+ ### CLI usage
59
+
60
+ You can also use Libretto directly from the command line. All commands accept `--session <name>` to target a specific session.
61
+
62
+ ```bash
63
+ npx libretto init # interactive; run yourself, not through an agent
64
+ npx libretto open <url> # launch browser and open a URL (headed by default)
65
+ npx libretto snapshot --objective "..." --context "..." # capture PNG + HTML and analyze with an LLM
66
+ npx libretto exec "<code>" # execute Playwright TypeScript against the open page
67
+ npx libretto run <file> <export> # run an exported workflow from a file
68
+ npx libretto resume # resume a paused workflow
69
+ npx libretto network # view captured network requests
70
+ npx libretto actions # view captured user/agent actions
71
+ npx libretto pages # list open pages in the session
72
+ npx libretto save <domain> # save browser session (cookies, localStorage) for reuse
73
+ npx libretto close # close the browser
74
+ npx libretto ai configure <provider> # configure snapshot analysis model
47
75
  ```
48
76
 
49
- You can also run workflows directly from the CLI:
77
+ ## Configuration
78
+
79
+ All Libretto state lives in a `.libretto/` directory at your project root. Configuration is stored in `.libretto/config.json`.
80
+
81
+ ### Config file
82
+
83
+ `.libretto/config.json` controls snapshot analysis and viewport settings:
84
+
85
+ ```json
86
+ {
87
+ "version": 1,
88
+ "ai": {
89
+ "model": "openai/gpt-5.4",
90
+ "updatedAt": "2026-01-01T00:00:00.000Z"
91
+ },
92
+ "viewport": { "width": 1280, "height": 800 }
93
+ }
94
+ ```
95
+
96
+ The `ai` field configures which model Libretto uses for snapshot analysis — extracting selectors, identifying interactive elements, or diagnosing why a step failed. This keeps heavy visual context out of your coding agent's context window. Snapshot analysis is required.
97
+
98
+ The easiest way to set the model is through the CLI:
50
99
 
51
100
  ```bash
52
- npx libretto help
53
- npx libretto run ./integration.ts main
101
+ npx libretto ai configure <openai | anthropic | gemini | vertex>
54
102
  ```
55
103
 
56
- ## The `.libretto/` directory
104
+ Provider credentials are read from environment variables or a `.env` file at your project root: `OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, `GEMINI_API_KEY` / `GOOGLE_GENERATIVE_AI_API_KEY`, or `GOOGLE_CLOUD_PROJECT` for Vertex.
105
+
106
+ The `viewport` field sets the default browser viewport size. Both fields are optional.
107
+
108
+ ### Sessions
57
109
 
58
- Libretto stores local runtime state in a `.libretto/` directory at your project root. Sensitive directories (`sessions/` and `profiles/`) are automatically git-ignored via `.libretto/.gitignore`.
110
+ Each Libretto session gets its own directory under `.libretto/sessions/<name>/` containing runtime state. Sessions are git-ignored.
59
111
 
60
- - **`profiles/<domain>.json`**Saved browser sessions (cookies, localStorage) for authenticated sites. Created via `npx libretto save <domain>`. Machine-local and never committed.
61
- - **`sessions/<name>/`**Per-session runtime state:
62
- - `state.json` — Session metadata (debug port, PID, status)
63
- - `logs.jsonl` — Structured session logs
64
- - `network.jsonl`Captured network requests (URLs, methods, headers, response status)
65
- - `actions.jsonl` — Recorded user actions (clicks, fills, navigations)
66
- - `snapshots/` — Screenshot PNGs and HTML snapshots captured via `npx libretto snapshot`
67
- - **`ai.json`** — AI runtime configuration set via `npx libretto ai configure`.
112
+ - `state.json`session metadata (debug port, PID, status)
113
+ - `logs.jsonl`structured session logs
114
+ - `network.jsonl` — captured network requests
115
+ - `actions.jsonl` — recorded user actions
116
+ - `snapshots/`screenshot PNGs and HTML snapshots
117
+
118
+ ### Profiles
119
+
120
+ Profiles save browser sessions (cookies, localStorage) so you can reuse authenticated state across runs. They are stored in `.libretto/profiles/<domain>.json`, created via `npx libretto save <domain>`. Profiles are machine-local and git-ignored.
121
+
122
+ ## Community
123
+
124
+ Have a question, idea, or want to share what you've built? Join the conversation on [GitHub Discussions](https://github.com/saffron-health/libretto/discussions).
125
+
126
+ - **[Q&A](https://github.com/saffron-health/libretto/discussions/categories/q-a)** — Ask questions and get help
127
+ - **[Ideas](https://github.com/saffron-health/libretto/discussions/categories/ideas)** — Suggest new features or improvements
128
+ - **[Show and tell](https://github.com/saffron-health/libretto/discussions/categories/show-and-tell)** — Share your workflows and automations
129
+ - **[General](https://github.com/saffron-health/libretto/discussions/categories/general)** — Chat about anything Libretto-related
130
+
131
+ Found a bug? Please [open an issue](https://github.com/saffron-health/libretto/issues/new).
68
132
 
69
133
  ## Authors
70
134
 
@@ -80,3 +144,13 @@ pnpm build
80
144
  pnpm type-check
81
145
  pnpm test
82
146
  ```
147
+
148
+ Source layout:
149
+
150
+ - `src/cli/` — CLI commands
151
+ - `src/runtime/` — browser runtime (network, recovery, downloads, extraction)
152
+ - `src/shared/` — shared utilities (config, LLM client, logging, state)
153
+ - `test/` — test files (`*.spec.ts`)
154
+ - `skills/libretto/` — source of truth for the Libretto skill; mirrors are synced on `pnpm i`
155
+
156
+ To check that skill mirrors are in sync without fixing them, run `pnpm check:skills`. To release, run `pnpm prepare-release`.
package/dist/cli/cli.js CHANGED
@@ -1,19 +1,10 @@
1
- import {
2
- closeLogger,
3
- createLoggerForSession,
4
- ensureLibrettoSetup
5
- } from "./core/context.js";
6
- import {
7
- SESSION_DEFAULT,
8
- validateSessionName
9
- } from "./core/session.js";
1
+ import { ensureLibrettoSetup } from "./core/context.js";
10
2
  import { createCLIApp } from "./router.js";
11
3
  function renderUsage(app) {
12
4
  return `${app.renderHelp()}
13
5
 
14
6
  Options:
15
- --session <name> Use a named session (default: "default")
16
- Built-in sessions: default, dev-server, browser-agent
7
+ --session <name> Use a named session (auto-generated for open/run if omitted)
17
8
 
18
9
  Examples:
19
10
  libretto open https://linkedin.com
@@ -31,7 +22,7 @@ Examples:
31
22
  libretto ai configure openai/gpt-4o
32
23
  libretto snapshot
33
24
  libretto snapshot --objective "Find the submit button" --context "Submitting a referral form, already filled in patient details"
34
- libretto resume --session default
25
+ libretto resume --session my-session
35
26
  libretto close
36
27
  libretto close --all
37
28
  libretto close --all --force
@@ -56,67 +47,6 @@ Sessions:
56
47
  Each session runs an isolated browser instance on a dynamic port.
57
48
  `;
58
49
  }
59
- function readSessionArgBeforePassthrough(rawArgs) {
60
- for (let index = 0; index < rawArgs.length; index += 1) {
61
- const token = rawArgs[index];
62
- if (token === "--") return void 0;
63
- if (token === "--session") {
64
- const value2 = rawArgs[index + 1];
65
- if (!value2 || value2 === "--" || value2.startsWith("--")) {
66
- return null;
67
- }
68
- return value2;
69
- }
70
- if (!token.startsWith("--session=")) continue;
71
- const value = token.slice("--session=".length);
72
- if (value.length === 0 || value === "--" || value.startsWith("--")) {
73
- return null;
74
- }
75
- return value;
76
- }
77
- return void 0;
78
- }
79
- function parseSessionForLog(rawArgs) {
80
- const value = readSessionArgBeforePassthrough(rawArgs);
81
- if (value === void 0 || value === null) {
82
- return SESSION_DEFAULT;
83
- }
84
- try {
85
- validateSessionName(value);
86
- return value;
87
- } catch {
88
- return SESSION_DEFAULT;
89
- }
90
- }
91
- function validateLegacySessionArg(rawArgs) {
92
- const value = readSessionArgBeforePassthrough(rawArgs);
93
- if (value === void 0) return;
94
- if (value === null) {
95
- throw new Error(
96
- `Usage: libretto <command> [--session <name>]
97
- Missing or invalid --session value.`
98
- );
99
- }
100
- validateSessionName(value);
101
- }
102
- function initializeLogger(rawArgs) {
103
- const sessionForLog = parseSessionForLog(rawArgs);
104
- const logger = createLoggerForSession(sessionForLog);
105
- logger.info("cli-start", {
106
- args: rawArgs,
107
- cwd: process.cwd(),
108
- session: sessionForLog
109
- });
110
- return logger;
111
- }
112
- async function withCliLogger(rawArgs, run) {
113
- const logger = initializeLogger(rawArgs);
114
- try {
115
- return await run(logger);
116
- } finally {
117
- await closeLogger(logger);
118
- }
119
- }
120
50
  function isRootHelpRequest(rawArgs) {
121
51
  if (rawArgs.length === 0) return true;
122
52
  if (rawArgs[0] === "--help" || rawArgs[0] === "-h") return true;
@@ -126,32 +56,27 @@ async function runLibrettoCLI() {
126
56
  const rawArgs = process.argv.slice(2);
127
57
  let exitCode = 0;
128
58
  ensureLibrettoSetup();
129
- await withCliLogger(rawArgs, async (logger) => {
130
- const app = createCLIApp(logger);
131
- try {
132
- validateLegacySessionArg(rawArgs);
133
- if (isRootHelpRequest(rawArgs)) {
134
- console.log(renderUsage(app));
135
- return;
136
- }
137
- logger.info("cli-command", { args: rawArgs });
138
- const result = await app.run(rawArgs);
139
- if (typeof result === "string") {
140
- console.log(result);
141
- }
142
- } catch (err) {
143
- logger.error("cli-error", { error: err, args: rawArgs });
144
- const message = err instanceof Error ? err.message : String(err);
145
- if (message.startsWith("Unknown command: ")) {
146
- console.error(`${message}
59
+ const app = createCLIApp();
60
+ try {
61
+ if (isRootHelpRequest(rawArgs)) {
62
+ console.log(renderUsage(app));
63
+ return;
64
+ }
65
+ const result = await app.run(rawArgs);
66
+ if (typeof result === "string") {
67
+ console.log(result);
68
+ }
69
+ } catch (err) {
70
+ const message = err instanceof Error ? err.message : String(err);
71
+ if (message.startsWith("Unknown command: ")) {
72
+ console.error(`${message}
147
73
  `);
148
- console.log(renderUsage(app));
149
- } else {
150
- console.error(message);
151
- }
152
- exitCode = 1;
74
+ console.log(renderUsage(app));
75
+ } else {
76
+ console.error(message);
153
77
  }
154
- });
78
+ exitCode = 1;
79
+ }
155
80
  process.exit(exitCode);
156
81
  }
157
82
  export {
@@ -2,17 +2,21 @@ import { z } from "zod";
2
2
  import {
3
3
  runClose as runCloseWithLogger,
4
4
  runCloseAll as runCloseAllWithLogger,
5
+ runConnect as runConnectWithLogger,
5
6
  runOpen,
6
7
  runPages,
7
8
  runSave
8
9
  } from "../core/browser.js";
9
- import { withSessionLogger } from "../core/context.js";
10
- import { assertSessionAvailableForStart } from "../core/session.js";
10
+ import { createLoggerForSession, withSessionLogger } from "../core/context.js";
11
+ import {
12
+ assertSessionAvailableForStart,
13
+ validateSessionName
14
+ } from "../core/session.js";
11
15
  import { SimpleCLI } from "../framework/simple-cli.js";
12
16
  import {
13
- loadSessionStateMiddleware,
14
- resolveSessionMiddleware,
15
- sessionOption
17
+ sessionOption,
18
+ withAutoSession,
19
+ withRequiredSession
16
20
  } from "./shared.js";
17
21
  function parseViewportArg(viewportArg) {
18
22
  if (!viewportArg) return void 0;
@@ -52,16 +56,32 @@ const openInput = SimpleCLI.input({
52
56
  (input) => !(input.headed && input.headless),
53
57
  "Cannot pass both --headed and --headless."
54
58
  );
55
- function createOpenCommand(logger) {
56
- return SimpleCLI.command({
57
- description: "Launch browser and open URL (headed by default)"
58
- }).input(openInput).use(resolveSessionMiddleware).handle(async ({ input, ctx }) => {
59
- assertSessionAvailableForStart(ctx.session, logger);
60
- const headed = input.headed || !input.headless;
61
- const viewport = parseViewportArg(input.viewport);
62
- await runOpen(input.url, headed, ctx.session, logger, { viewport });
63
- });
64
- }
59
+ const openCommand = SimpleCLI.command({
60
+ description: "Launch browser and open URL (headed by default)"
61
+ }).input(openInput).use(withAutoSession()).handle(async ({ input, ctx }) => {
62
+ assertSessionAvailableForStart(ctx.session, ctx.logger);
63
+ const headed = input.headed || !input.headless;
64
+ const viewport = parseViewportArg(input.viewport);
65
+ await runOpen(input.url, headed, ctx.session, ctx.logger, { viewport });
66
+ });
67
+ const connectInput = SimpleCLI.input({
68
+ positionals: [
69
+ SimpleCLI.positional("cdpUrl", z.string().optional(), {
70
+ help: "CDP endpoint URL (e.g. http://127.0.0.1:9222)"
71
+ })
72
+ ],
73
+ named: {
74
+ session: sessionOption()
75
+ }
76
+ }).refine(
77
+ (input) => Boolean(input.cdpUrl),
78
+ `Usage: libretto connect <cdp-url> --session <name>`
79
+ );
80
+ const connectCommand = SimpleCLI.command({
81
+ description: "Connect to an existing Chrome DevTools Protocol (CDP) endpoint"
82
+ }).input(connectInput).use(withAutoSession()).handle(async ({ input, ctx }) => {
83
+ await runConnectWithLogger(input.cdpUrl, ctx.session, ctx.logger);
84
+ });
65
85
  const saveInput = SimpleCLI.input({
66
86
  positionals: [
67
87
  SimpleCLI.positional("urlOrDomain", z.string().optional(), {
@@ -73,72 +93,79 @@ const saveInput = SimpleCLI.input({
73
93
  }
74
94
  }).refine(
75
95
  (input) => Boolean(input.urlOrDomain),
76
- `Usage: libretto save <url|domain> [--session <name>]`
96
+ `Usage: libretto save <url|domain> --session <name>`
77
97
  );
78
- function createSaveCommand(logger) {
79
- return SimpleCLI.command({
80
- description: "Save current browser session"
81
- }).input(saveInput).use(resolveSessionMiddleware).use(loadSessionStateMiddleware).handle(async ({ input, ctx }) => {
82
- await runSave(input.urlOrDomain, ctx.session, logger);
83
- });
84
- }
98
+ const saveCommand = SimpleCLI.command({
99
+ description: "Save current browser session"
100
+ }).input(saveInput).use(withRequiredSession()).handle(async ({ input, ctx }) => {
101
+ await runSave(input.urlOrDomain, ctx.session, ctx.logger);
102
+ });
85
103
  const pagesInput = SimpleCLI.input({
86
104
  positionals: [],
87
105
  named: {
88
106
  session: sessionOption()
89
107
  }
90
108
  });
91
- function createPagesCommand(logger) {
92
- return SimpleCLI.command({
93
- description: "List open pages in the session"
94
- }).input(pagesInput).use(resolveSessionMiddleware).use(loadSessionStateMiddleware).handle(async ({ ctx }) => {
95
- await runPages(ctx.session, logger);
96
- });
97
- }
109
+ const pagesCommand = SimpleCLI.command({
110
+ description: "List open pages in the session"
111
+ }).input(pagesInput).use(withRequiredSession()).handle(async ({ ctx }) => {
112
+ await runPages(ctx.session, ctx.logger);
113
+ });
98
114
  const closeInput = SimpleCLI.input({
99
115
  positionals: [],
100
116
  named: {
101
117
  session: sessionOption(),
102
- all: SimpleCLI.flag({ help: "Close all tracked sessions in this workspace" }),
103
- force: SimpleCLI.flag({ help: "Force kill sessions that ignore SIGTERM (requires --all)" })
118
+ all: SimpleCLI.flag({
119
+ help: "Close all tracked sessions in this workspace"
120
+ }),
121
+ force: SimpleCLI.flag({
122
+ help: "Force kill sessions that ignore SIGTERM (requires --all)"
123
+ })
124
+ }
125
+ }).refine(
126
+ (input) => input.all || input.session,
127
+ `Usage: libretto close --session <name>
128
+ Usage: libretto close --all [--force]`
129
+ );
130
+ const closeCommand = SimpleCLI.command({
131
+ description: "Close the browser"
132
+ }).input(closeInput).handle(async ({ input }) => {
133
+ if (input.force && !input.all) {
134
+ throw new Error(`Usage: libretto close --all [--force]`);
104
135
  }
136
+ if (input.all) {
137
+ const logger2 = createLoggerForSession("cli");
138
+ await runCloseAllWithLogger(logger2, { force: input.force });
139
+ return;
140
+ }
141
+ validateSessionName(input.session);
142
+ const logger = createLoggerForSession(input.session);
143
+ await runCloseWithLogger(input.session, logger);
105
144
  });
106
- function createCloseCommand(logger) {
107
- return SimpleCLI.command({
108
- description: "Close the browser"
109
- }).input(closeInput).use(resolveSessionMiddleware).handle(async ({ input, ctx }) => {
110
- if (input.force && !input.all) {
111
- throw new Error(`Usage: libretto close --all [--force]`);
112
- }
113
- if (input.all) {
114
- await runCloseAllWithLogger(logger, { force: input.force });
115
- return;
116
- }
117
- await runCloseWithLogger(ctx.session, logger);
118
- });
119
- }
120
- function createBrowserCommands(logger) {
121
- return {
122
- open: createOpenCommand(logger),
123
- save: createSaveCommand(logger),
124
- pages: createPagesCommand(logger),
125
- close: createCloseCommand(logger)
126
- };
127
- }
145
+ const browserCommands = {
146
+ open: openCommand,
147
+ connect: connectCommand,
148
+ save: saveCommand,
149
+ pages: pagesCommand,
150
+ close: closeCommand
151
+ };
128
152
  async function runClose(session) {
129
153
  await withSessionLogger(session, async (logger) => {
130
154
  await runCloseWithLogger(session, logger);
131
155
  });
132
156
  }
133
157
  export {
158
+ browserCommands,
159
+ closeCommand,
134
160
  closeInput,
135
- createBrowserCommands,
136
- createCloseCommand,
137
- createOpenCommand,
138
- createPagesCommand,
139
- createSaveCommand,
161
+ connectCommand,
162
+ connectInput,
163
+ openCommand,
140
164
  openInput,
165
+ pagesCommand,
141
166
  pagesInput,
167
+ parseViewportArg,
142
168
  runClose,
169
+ saveCommand,
143
170
  saveInput
144
171
  };