libretto 0.5.5 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/README.md +23 -10
  2. package/README.template.md +23 -10
  3. package/dist/cli/cli.js +10 -0
  4. package/dist/cli/commands/ai.js +77 -2
  5. package/dist/cli/commands/browser.js +98 -8
  6. package/dist/cli/commands/execution.js +152 -56
  7. package/dist/cli/commands/setup.js +390 -0
  8. package/dist/cli/commands/snapshot.js +2 -2
  9. package/dist/cli/commands/status.js +62 -0
  10. package/dist/cli/core/{snapshot-api-config.js → ai-model.js} +81 -7
  11. package/dist/cli/core/api-snapshot-analyzer.js +7 -5
  12. package/dist/cli/core/browser.js +202 -36
  13. package/dist/cli/core/{ai-config.js → config.js} +14 -79
  14. package/dist/cli/core/context.js +1 -25
  15. package/dist/cli/core/deploy-artifact.js +121 -61
  16. package/dist/cli/core/providers/browserbase.js +53 -0
  17. package/dist/cli/core/providers/index.js +48 -0
  18. package/dist/cli/core/providers/kernel.js +46 -0
  19. package/dist/cli/core/providers/libretto-cloud.js +58 -0
  20. package/dist/cli/core/readonly-exec.js +231 -0
  21. package/dist/{shared/llm/client.js → cli/core/resolve-model.js} +4 -68
  22. package/dist/cli/core/session.js +53 -0
  23. package/dist/cli/core/skill-version.js +73 -0
  24. package/dist/cli/core/telemetry.js +1 -54
  25. package/dist/cli/index.js +1 -7
  26. package/dist/cli/router.js +4 -4
  27. package/dist/cli/workers/run-integration-runtime.js +19 -13
  28. package/dist/cli/workers/run-integration-worker-protocol.js +5 -2
  29. package/dist/index.d.ts +2 -4
  30. package/dist/index.js +2 -2
  31. package/dist/runtime/extract/extract.d.ts +2 -2
  32. package/dist/runtime/extract/extract.js +4 -2
  33. package/dist/runtime/extract/index.d.ts +1 -1
  34. package/dist/runtime/recovery/agent.d.ts +2 -3
  35. package/dist/runtime/recovery/agent.js +5 -3
  36. package/dist/runtime/recovery/errors.d.ts +2 -3
  37. package/dist/runtime/recovery/errors.js +4 -2
  38. package/dist/runtime/recovery/index.d.ts +1 -2
  39. package/dist/runtime/recovery/recovery.d.ts +2 -3
  40. package/dist/runtime/recovery/recovery.js +3 -3
  41. package/dist/shared/debug/pause.js +4 -21
  42. package/dist/shared/run/api.d.ts +2 -0
  43. package/dist/shared/run/browser.d.ts +9 -1
  44. package/dist/shared/run/browser.js +43 -3
  45. package/dist/shared/state/index.d.ts +1 -1
  46. package/dist/shared/state/index.js +2 -0
  47. package/dist/shared/state/session-state.d.ts +20 -1
  48. package/dist/shared/state/session-state.js +12 -2
  49. package/dist/shared/workflow/workflow.d.ts +2 -1
  50. package/dist/shared/workflow/workflow.js +16 -9
  51. package/package.json +17 -16
  52. package/scripts/postinstall.mjs +13 -11
  53. package/scripts/skills-libretto.mjs +14 -4
  54. package/skills/AGENTS.md +11 -0
  55. package/skills/libretto/SKILL.md +30 -9
  56. package/skills/libretto/references/auth-profiles.md +1 -1
  57. package/skills/libretto/references/code-generation-rules.md +3 -3
  58. package/skills/libretto/references/configuration-file-reference.md +11 -6
  59. package/skills/libretto-readonly/SKILL.md +95 -0
  60. package/src/cli/cli.ts +10 -0
  61. package/src/cli/commands/ai.ts +111 -1
  62. package/src/cli/commands/browser.ts +111 -9
  63. package/src/cli/commands/execution.ts +181 -74
  64. package/src/cli/commands/setup.ts +516 -0
  65. package/src/cli/commands/snapshot.ts +2 -2
  66. package/src/cli/commands/status.ts +79 -0
  67. package/src/cli/core/{snapshot-api-config.ts → ai-model.ts} +154 -14
  68. package/src/cli/core/api-snapshot-analyzer.ts +7 -5
  69. package/src/cli/core/browser.ts +242 -35
  70. package/src/cli/core/{ai-config.ts → config.ts} +14 -108
  71. package/src/cli/core/context.ts +1 -45
  72. package/src/cli/core/deploy-artifact.ts +141 -71
  73. package/src/cli/core/providers/browserbase.ts +57 -0
  74. package/src/cli/core/providers/index.ts +62 -0
  75. package/src/cli/core/providers/kernel.ts +49 -0
  76. package/src/cli/core/providers/libretto-cloud.ts +61 -0
  77. package/src/cli/core/providers/types.ts +9 -0
  78. package/src/cli/core/readonly-exec.ts +284 -0
  79. package/src/{shared/llm/client.ts → cli/core/resolve-model.ts} +3 -85
  80. package/src/cli/core/session.ts +75 -2
  81. package/src/cli/core/skill-version.ts +93 -0
  82. package/src/cli/core/telemetry.ts +0 -52
  83. package/src/cli/index.ts +0 -6
  84. package/src/cli/router.ts +4 -4
  85. package/src/cli/workers/run-integration-runtime.ts +18 -16
  86. package/src/cli/workers/run-integration-worker-protocol.ts +4 -1
  87. package/src/index.ts +1 -7
  88. package/src/runtime/extract/extract.ts +6 -5
  89. package/src/runtime/recovery/agent.ts +5 -4
  90. package/src/runtime/recovery/errors.ts +4 -3
  91. package/src/runtime/recovery/recovery.ts +4 -4
  92. package/src/shared/debug/pause.ts +4 -23
  93. package/src/shared/run/browser.ts +50 -1
  94. package/src/shared/state/index.ts +2 -0
  95. package/src/shared/state/session-state.ts +10 -0
  96. package/src/shared/workflow/workflow.ts +24 -13
  97. package/dist/cli/commands/init.js +0 -286
  98. package/dist/cli/commands/logs.js +0 -117
  99. package/dist/shared/llm/ai-sdk-adapter.d.ts +0 -22
  100. package/dist/shared/llm/ai-sdk-adapter.js +0 -49
  101. package/dist/shared/llm/client.d.ts +0 -13
  102. package/dist/shared/llm/index.d.ts +0 -5
  103. package/dist/shared/llm/index.js +0 -6
  104. package/dist/shared/llm/types.d.ts +0 -67
  105. package/src/cli/commands/init.ts +0 -331
  106. package/src/cli/commands/logs.ts +0 -128
  107. package/src/shared/llm/ai-sdk-adapter.ts +0 -81
  108. package/src/shared/llm/index.ts +0 -3
  109. package/src/shared/llm/types.ts +0 -63
  110. /package/dist/{shared/llm → cli/core/providers}/types.js +0 -0
@@ -1,331 +0,0 @@
1
- import { createInterface } from "node:readline";
2
- import {
3
- appendFileSync,
4
- cpSync,
5
- existsSync,
6
- readdirSync,
7
- readFileSync,
8
- rmSync,
9
- writeFileSync,
10
- } from "node:fs";
11
- import { spawnSync } from "node:child_process";
12
- import { basename, dirname, join } from "node:path";
13
- import { fileURLToPath } from "node:url";
14
- import { readAiConfig } from "../core/ai-config.js";
15
- import { REPO_ROOT } from "../core/context.js";
16
- import {
17
- loadSnapshotEnv,
18
- resolveSnapshotApiModel,
19
- } from "../core/snapshot-api-config.js";
20
- import { hasProviderCredentials } from "../../shared/llm/client.js";
21
- import { SimpleCLI } from "../framework/simple-cli.js";
22
-
23
- type ProviderChoice = {
24
- key: string;
25
- label: string;
26
- envVar: string;
27
- envHint: string;
28
- };
29
-
30
- const PROVIDER_CHOICES: ProviderChoice[] = [
31
- {
32
- key: "1",
33
- label: "OpenAI",
34
- envVar: "OPENAI_API_KEY",
35
- envHint: "Get your key at https://platform.openai.com/api-keys",
36
- },
37
- {
38
- key: "2",
39
- label: "Anthropic",
40
- envVar: "ANTHROPIC_API_KEY",
41
- envHint: "Get your key at https://console.anthropic.com/settings/keys",
42
- },
43
- {
44
- key: "3",
45
- label: "Google Gemini",
46
- envVar: "GEMINI_API_KEY",
47
- envHint: "Get your key at https://aistudio.google.com/apikey",
48
- },
49
- {
50
- key: "4",
51
- label: "Google Vertex AI",
52
- envVar: "GOOGLE_CLOUD_PROJECT",
53
- envHint:
54
- "Requires gcloud auth application-default login and a GCP project ID",
55
- },
56
- ];
57
-
58
- function promptUser(
59
- rl: ReturnType<typeof createInterface>,
60
- question: string,
61
- ): Promise<string> {
62
- return new Promise((resolve) => {
63
- rl.question(question, (answer) => {
64
- resolve(answer.trim());
65
- });
66
- });
67
- }
68
-
69
- function safeReadAiConfig(): ReturnType<typeof readAiConfig> {
70
- try {
71
- return readAiConfig();
72
- } catch {
73
- return null;
74
- }
75
- }
76
-
77
- function printInvalidAiConfigWarning(): void {
78
- try {
79
- readAiConfig();
80
- } catch (error) {
81
- const message = error instanceof Error ? error.message : String(error);
82
- console.log(" ! Existing AI config is invalid:");
83
- for (const line of message.split("\n")) {
84
- console.log(` ${line}`);
85
- }
86
- }
87
- }
88
-
89
- function printSnapshotApiStatus(): void {
90
- const config = safeReadAiConfig();
91
- const selection = resolveSnapshotApiModel(config);
92
- const envPath = join(REPO_ROOT, ".env");
93
-
94
- console.log("\nSnapshot analysis:");
95
- console.log(
96
- " Libretto uses direct API calls for snapshot analysis when supported credentials are available.",
97
- );
98
- console.log(` Credentials are loaded from process env and ${envPath}.`);
99
- printInvalidAiConfigWarning();
100
-
101
- if (selection && hasProviderCredentials(selection.provider)) {
102
- console.log(` ✓ Ready: ${selection.model} (${selection.source})`);
103
- console.log(
104
- " Snapshot objectives will use the API analyzer by default.",
105
- );
106
- console.log(" No further action required.");
107
- return;
108
- }
109
-
110
- console.log(" ✗ No snapshot API credentials detected.");
111
- console.log(" Add one provider to .env:");
112
- console.log(" OPENAI_API_KEY=...");
113
- console.log(" ANTHROPIC_API_KEY=...");
114
- console.log(" GEMINI_API_KEY=... # or GOOGLE_GENERATIVE_AI_API_KEY");
115
- console.log(
116
- " GOOGLE_CLOUD_PROJECT=... # plus application default credentials for Vertex",
117
- );
118
- console.log(
119
- " Or run `npx libretto ai configure openai | anthropic | gemini | vertex` to set a specific model.",
120
- );
121
- console.log(
122
- " Run `npx libretto init` interactively to set up credentials.",
123
- );
124
- }
125
-
126
- async function runInteractiveApiSetup(): Promise<void> {
127
- const config = safeReadAiConfig();
128
- const selection = resolveSnapshotApiModel(config);
129
- const envPath = join(REPO_ROOT, ".env");
130
-
131
- console.log("\nSnapshot analysis setup:");
132
- console.log(" Libretto uses direct API calls for snapshot analysis.");
133
- console.log(` Credentials are loaded from process env and ${envPath}.`);
134
- printInvalidAiConfigWarning();
135
-
136
- if (selection && hasProviderCredentials(selection.provider)) {
137
- console.log(` ✓ Ready: ${selection.model} (${selection.source})`);
138
- console.log(
139
- " Snapshot objectives will use the API analyzer by default.",
140
- );
141
- return;
142
- }
143
-
144
- console.log(" ✗ No snapshot API credentials detected.\n");
145
-
146
- const rl = createInterface({
147
- input: process.stdin,
148
- output: process.stdout,
149
- });
150
-
151
- try {
152
- console.log(
153
- " Which API provider would you like to use for snapshot analysis?\n",
154
- );
155
- for (const choice of PROVIDER_CHOICES) {
156
- console.log(` ${choice.key}) ${choice.label}`);
157
- }
158
- console.log(" s) Skip for now\n");
159
-
160
- const answer = await promptUser(rl, " Choice: ");
161
-
162
- if (answer.toLowerCase() === "s" || !answer) {
163
- console.log(
164
- "\n Skipped. You can set up API credentials later by rerunning `npx libretto init`.",
165
- );
166
- console.log(" Or add credentials directly to your .env file:");
167
- console.log(" OPENAI_API_KEY=...");
168
- console.log(" ANTHROPIC_API_KEY=...");
169
- console.log(" GEMINI_API_KEY=...");
170
- console.log(
171
- " Or run `npx libretto ai configure openai | anthropic | gemini | vertex` to set a specific model.",
172
- );
173
- return;
174
- }
175
-
176
- const selected = PROVIDER_CHOICES.find((choice) => choice.key === answer);
177
- if (!selected) {
178
- console.log(`\n Unknown choice "${answer}". Skipping API setup.`);
179
- return;
180
- }
181
-
182
- console.log(`\n ${selected.label} selected.`);
183
- console.log(` ${selected.envHint}\n`);
184
-
185
- const apiKeyValue = await promptUser(
186
- rl,
187
- ` Enter your ${selected.envVar}: `,
188
- );
189
-
190
- if (!apiKeyValue) {
191
- console.log("\n No value entered. Skipping API key setup.");
192
- return;
193
- }
194
-
195
- let envContent = "";
196
- if (existsSync(envPath)) {
197
- envContent = readFileSync(envPath, "utf-8");
198
- }
199
-
200
- const envLine = `${selected.envVar}=${apiKeyValue}`;
201
- if (envContent.includes(`${selected.envVar}=`)) {
202
- const updated = envContent.replace(
203
- new RegExp(`^${selected.envVar}=.*$`, "m"),
204
- () => envLine,
205
- );
206
- writeFileSync(envPath, updated);
207
- console.log(`\n ✓ Updated ${selected.envVar} in ${envPath}`);
208
- } else {
209
- const separator = envContent && !envContent.endsWith("\n") ? "\n" : "";
210
- appendFileSync(envPath, `${separator}${envLine}\n`);
211
- console.log(`\n ✓ Added ${selected.envVar} to ${envPath}`);
212
- }
213
-
214
- loadSnapshotEnv();
215
- process.env[selected.envVar] = apiKeyValue;
216
- const newSelection = resolveSnapshotApiModel(safeReadAiConfig());
217
- if (newSelection && hasProviderCredentials(newSelection.provider)) {
218
- console.log(` ✓ Snapshot API ready: ${newSelection.model}`);
219
- }
220
- } finally {
221
- rl.close();
222
- }
223
- }
224
-
225
- function installBrowsers(): void {
226
- console.log("\nInstalling Playwright Chromium...");
227
- const result = spawnSync("npx", ["playwright", "install", "chromium"], {
228
- stdio: "inherit",
229
- shell: true,
230
- });
231
- if (result.status === 0) {
232
- console.log(" ✓ Playwright Chromium installed");
233
- } else {
234
- console.error(
235
- " ✗ Failed to install Playwright Chromium. Run manually: npx playwright install chromium",
236
- );
237
- }
238
- }
239
-
240
- function getPackageSkillsDir(): string {
241
- const thisFile = fileURLToPath(import.meta.url);
242
- // Walk up from dist/cli/commands/ to package root
243
- let dir = dirname(thisFile);
244
- while (dir !== dirname(dir)) {
245
- if (existsSync(join(dir, "skills", "libretto"))) {
246
- return join(dir, "skills", "libretto");
247
- }
248
- dir = dirname(dir);
249
- }
250
- throw new Error("Could not locate libretto skill files in package");
251
- }
252
-
253
- /**
254
- * Auto-detect .agents/ and .claude/ directories at a given root path.
255
- */
256
- function detectAgentDirs(root: string): string[] {
257
- const dirs: string[] = [];
258
- if (existsSync(join(root, ".agents"))) dirs.push(join(root, ".agents"));
259
- if (existsSync(join(root, ".claude"))) dirs.push(join(root, ".claude"));
260
- return dirs;
261
- }
262
-
263
- function copySkills(): void {
264
- const agentDirs = detectAgentDirs(REPO_ROOT);
265
-
266
- if (agentDirs.length === 0) {
267
- console.log(
268
- "\nSkills: No .agents/ or .claude/ directory found in repo root — skipping.",
269
- );
270
- return;
271
- }
272
-
273
- const destinations = agentDirs.map((d) => join(d, "skills", "libretto"));
274
-
275
- let sourceDir: string;
276
- try {
277
- sourceDir = getPackageSkillsDir();
278
- } catch (e) {
279
- console.error(` ✗ ${e instanceof Error ? e.message : String(e)}`);
280
- return;
281
- }
282
-
283
- for (let i = 0; i < agentDirs.length; i++) {
284
- const skillDest = destinations[i];
285
- const name = basename(agentDirs[i]);
286
- // Remove existing dir first so stale files from prior versions don't persist
287
- if (existsSync(skillDest)) {
288
- rmSync(skillDest, { recursive: true });
289
- }
290
- cpSync(sourceDir, skillDest, { recursive: true });
291
- const fileCount = readdirSync(skillDest).length;
292
- console.log(
293
- ` ✓ Copied ${fileCount} skill files to ${name}/skills/libretto/`,
294
- );
295
- }
296
- }
297
-
298
- export const initInput = SimpleCLI.input({
299
- positionals: [],
300
- named: {
301
- skipBrowsers: SimpleCLI.flag({
302
- name: "skip-browsers",
303
- help: "Skip Playwright Chromium installation",
304
- }),
305
- },
306
- });
307
-
308
- export const initCommand = SimpleCLI.command({
309
- description: "Initialize libretto in the current project",
310
- })
311
- .input(initInput)
312
- .handle(async ({ input }) => {
313
- console.log("Initializing libretto...\n");
314
-
315
- if (!input.skipBrowsers) {
316
- installBrowsers();
317
- } else {
318
- console.log("\nSkipping browser installation (--skip-browsers)");
319
- }
320
-
321
- copySkills();
322
-
323
- if (process.stdin.isTTY) {
324
- await runInteractiveApiSetup();
325
- } else {
326
- loadSnapshotEnv();
327
- printSnapshotApiStatus();
328
- }
329
-
330
- console.log("\n✓ libretto init complete");
331
- });
@@ -1,128 +0,0 @@
1
- import { z } from "zod";
2
- import { listOpenPages } from "../core/browser.js";
3
- import { withSessionLogger } from "../core/context.js";
4
- import {
5
- clearActionLog,
6
- clearNetworkLog,
7
- formatActionEntry,
8
- formatNetworkEntry,
9
- readActionLog,
10
- readNetworkLog,
11
- } from "../core/telemetry.js";
12
- import { SimpleCLI } from "../framework/simple-cli.js";
13
- import {
14
- integerOption,
15
- pageOption,
16
- sessionOption,
17
- withRequiredSession,
18
- } from "./shared.js";
19
-
20
- async function resolvePageId(
21
- session: string,
22
- pageId?: string,
23
- ): Promise<string | undefined> {
24
- if (!pageId) return undefined;
25
- const pages = await withSessionLogger(session, async (logger) =>
26
- listOpenPages(session, logger),
27
- );
28
- const foundPage = pages.find((page) => page.id === pageId);
29
- if (!foundPage) {
30
- throw new Error(
31
- `Page "${pageId}" was not found in session "${session}". Run "libretto pages --session ${session}" to list ids.`,
32
- );
33
- }
34
- return pageId;
35
- }
36
-
37
- export const networkInput = SimpleCLI.input({
38
- positionals: [],
39
- named: {
40
- session: sessionOption(),
41
- last: integerOption(),
42
- filter: SimpleCLI.option(z.string().optional()),
43
- method: SimpleCLI.option(z.string().optional()),
44
- page: pageOption(),
45
- clear: SimpleCLI.flag(),
46
- },
47
- });
48
-
49
- export const networkCommand = SimpleCLI.command({
50
- description: "View captured network requests",
51
- })
52
- .input(networkInput)
53
- .use(withRequiredSession())
54
- .handle(async ({ input, ctx }) => {
55
- if (input.clear) {
56
- clearNetworkLog(ctx.session);
57
- console.log("Network log cleared.");
58
- return;
59
- }
60
-
61
- const pageId = await resolvePageId(ctx.session, input.page);
62
- const entries = readNetworkLog(ctx.session, {
63
- last: input.last,
64
- filter: input.filter,
65
- method: input.method,
66
- pageId,
67
- });
68
-
69
- if (entries.length === 0) {
70
- console.log("No network requests captured.");
71
- return;
72
- }
73
-
74
- for (const entry of entries) {
75
- console.log(formatNetworkEntry(entry));
76
- }
77
- console.log(`\n${entries.length} request(s) shown.`);
78
- });
79
-
80
- export const actionsInput = SimpleCLI.input({
81
- positionals: [],
82
- named: {
83
- session: sessionOption(),
84
- last: integerOption(),
85
- filter: SimpleCLI.option(z.string().optional()),
86
- action: SimpleCLI.option(z.string().optional()),
87
- source: SimpleCLI.option(z.string().optional()),
88
- page: pageOption(),
89
- clear: SimpleCLI.flag(),
90
- },
91
- });
92
-
93
- export const actionsCommand = SimpleCLI.command({
94
- description: "View captured actions",
95
- })
96
- .input(actionsInput)
97
- .use(withRequiredSession())
98
- .handle(async ({ input, ctx }) => {
99
- if (input.clear) {
100
- clearActionLog(ctx.session);
101
- console.log("Action log cleared.");
102
- return;
103
- }
104
-
105
- const pageId = await resolvePageId(ctx.session, input.page);
106
- const entries = readActionLog(ctx.session, {
107
- last: input.last,
108
- filter: input.filter,
109
- action: input.action,
110
- source: input.source,
111
- pageId,
112
- });
113
-
114
- if (entries.length === 0) {
115
- console.log("No actions captured.");
116
- return;
117
- }
118
-
119
- for (const entry of entries) {
120
- console.log(formatActionEntry(entry));
121
- }
122
- console.log(`\n${entries.length} action(s) shown.`);
123
- });
124
-
125
- export const logCommands = {
126
- network: networkCommand,
127
- actions: actionsCommand,
128
- };
@@ -1,81 +0,0 @@
1
- import { generateObject, type LanguageModel } from "ai";
2
- import type { ZodType, output as ZodOutput } from "zod";
3
- import type { LLMClient, Message } from "./types.js";
4
-
5
- /**
6
- * Creates a libretto LLMClient from a Vercel AI SDK LanguageModel.
7
- *
8
- * This eliminates the need for consumers to write their own adapter
9
- * when using @ai-sdk/openai, @ai-sdk/anthropic, @ai-sdk/google-vertex,
10
- * or any other Vercel AI SDK-compatible provider.
11
- *
12
- * @example
13
- * ```typescript
14
- * import { createLLMClientFromModel } from "libretto/llm";
15
- * import { openai } from "@ai-sdk/openai";
16
- *
17
- * const llmClient = createLLMClientFromModel(openai("gpt-4o"));
18
- * ```
19
- */
20
- export function createLLMClientFromModel(model: LanguageModel): LLMClient {
21
- return {
22
- async generateObject<T extends ZodType>(opts: {
23
- prompt: string;
24
- schema: T;
25
- temperature?: number;
26
- }): Promise<ZodOutput<T>> {
27
- const { object } = await generateObject({
28
- model,
29
- schema: opts.schema,
30
- prompt: opts.prompt,
31
- temperature: opts.temperature ?? 0,
32
- });
33
- return object as ZodOutput<T>;
34
- },
35
-
36
- async generateObjectFromMessages<T extends ZodType>(opts: {
37
- messages: Message[];
38
- schema: T;
39
- temperature?: number;
40
- }): Promise<ZodOutput<T>> {
41
- // Convert libretto Message format to AI SDK message format
42
- const messages = opts.messages.map((msg) => {
43
- if (typeof msg.content === "string") {
44
- return { role: msg.role, content: msg.content };
45
- }
46
- if (msg.role === "assistant") {
47
- // AssistantContent only supports text parts (no images)
48
- return {
49
- role: "assistant" as const,
50
- content: msg.content
51
- .filter(
52
- (part): part is typeof part & { type: "text" } =>
53
- part.type === "text",
54
- )
55
- .map((part) => ({ type: "text" as const, text: part.text })),
56
- };
57
- }
58
- return {
59
- role: "user" as const,
60
- content: msg.content.map((part) =>
61
- part.type === "text"
62
- ? { type: "text" as const, text: part.text }
63
- : {
64
- type: "image" as const,
65
- image: part.image,
66
- ...(part.mediaType ? { mediaType: part.mediaType } : {}),
67
- },
68
- ),
69
- };
70
- });
71
-
72
- const { object } = await generateObject({
73
- model,
74
- schema: opts.schema,
75
- messages,
76
- temperature: opts.temperature ?? 0,
77
- });
78
- return object as ZodOutput<T>;
79
- },
80
- };
81
- }
@@ -1,3 +0,0 @@
1
- export type { LLMClient, Message, MessageContentPart } from "./types.js";
2
- export { createLLMClient } from "./client.js";
3
- export { createLLMClientFromModel } from "./ai-sdk-adapter.js";
@@ -1,63 +0,0 @@
1
- import type z from "zod";
2
-
3
- export type MessageContentPart =
4
- | { type: "text"; text: string }
5
- | { type: "image"; image: string | Uint8Array; mediaType?: string };
6
-
7
- export type Message = {
8
- role: "user" | "assistant";
9
- content: string | MessageContentPart[];
10
- };
11
-
12
- /**
13
- * Pluggable LLM client interface.
14
- *
15
- * Users provide their own implementation backed by any LLM provider
16
- * (OpenAI, Anthropic, etc.). Libretto uses this interface for AI extraction,
17
- * recovery agents, and error detection.
18
- *
19
- * **Error handling:** implementations should throw on failure rather than
20
- * returning sentinel values (e.g. `null` or `undefined`). Libretto relies
21
- * on exceptions to trigger retry/recovery logic.
22
- *
23
- * A ready-made adapter for the Vercel AI SDK is available via
24
- * {@link createLLMClientFromModel} in `libretto/llm`.
25
- */
26
- export interface LLMClient {
27
- /**
28
- * Generate a structured object from a single text prompt.
29
- *
30
- * The underlying model **must** support structured / JSON output so that
31
- * the response can be parsed and validated against the provided Zod schema.
32
- *
33
- * @param opts.prompt - The text prompt sent to the model.
34
- * @param opts.schema - A Zod schema describing the expected response shape.
35
- * @param opts.temperature - Sampling temperature (default chosen by implementation, typically 0).
36
- * @returns The parsed object matching the schema.
37
- * @throws On LLM or parsing failure.
38
- */
39
- generateObject<T extends z.ZodType>(opts: {
40
- prompt: string;
41
- schema: T;
42
- temperature?: number;
43
- }): Promise<z.output<T>>;
44
-
45
- /**
46
- * Generate a structured object from a conversation-style message array.
47
- *
48
- * Messages may contain **image content** (base64 data URIs via
49
- * {@link MessageContentPart}), so the backing model must support
50
- * vision / multimodal input when images are present.
51
- *
52
- * @param opts.messages - Ordered list of user/assistant messages, potentially multimodal.
53
- * @param opts.schema - A Zod schema describing the expected response shape.
54
- * @param opts.temperature - Sampling temperature (default chosen by implementation, typically 0).
55
- * @returns The parsed object matching the schema.
56
- * @throws On LLM or parsing failure.
57
- */
58
- generateObjectFromMessages<T extends z.ZodType>(opts: {
59
- messages: Message[];
60
- schema: T;
61
- temperature?: number;
62
- }): Promise<z.output<T>>;
63
- }