@engenty/local-models 0.0.0-stage → 0.20.6

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.
@@ -0,0 +1,211 @@
1
+ import { spawn as spawnDetached } from "node:child_process";
2
+ // cross-spawn: on Windows a command from npm is a .cmd file, which only cmd.exe starts, with
3
+ // its arguments quoted the way cmd.exe reads them. Elsewhere it is child_process.spawn.
4
+ import spawn from "cross-spawn";
5
+ /**
6
+ * Runs a file and gives what it printed, like execFile: it rejects when the file is not there,
7
+ * ends with another code than 0, or takes longer than `timeout` (then with `killed` and `signal`
8
+ * set, as execFile does).
9
+ */
10
+ export function run(file, args, options = {}) {
11
+ return new Promise((resolve, reject) => {
12
+ const child = spawn(file, args, {
13
+ env: options.env,
14
+ cwd: options.cwd,
15
+ stdio: ["ignore", "pipe", "pipe"],
16
+ timeout: options.timeout,
17
+ });
18
+ let stdout = "";
19
+ let stderr = "";
20
+ child.stdout?.on("data", (chunk) => {
21
+ stdout += chunk.toString("utf8");
22
+ });
23
+ child.stderr?.on("data", (chunk) => {
24
+ stderr += chunk.toString("utf8");
25
+ });
26
+ child.on("error", reject);
27
+ child.on("close", (code, signal) => {
28
+ if (code === 0) {
29
+ resolve({ stdout, stderr });
30
+ }
31
+ else {
32
+ reject(Object.assign(new Error(`${file} ended with ${signal ?? code}`), {
33
+ code,
34
+ signal,
35
+ killed: child.killed,
36
+ stdout,
37
+ stderr,
38
+ }));
39
+ }
40
+ });
41
+ });
42
+ }
43
+ /** A version probe that could not finish: the machine is busy, the client may well be there. */
44
+ export class ProbeUndecided extends Error {
45
+ }
46
+ /** Spawn failures that say the machine is short of something, not that the client is missing. */
47
+ const BUSY_CODES = new Set(["EAGAIN", "EMFILE", "ENFILE", "ENOMEM"]);
48
+ /**
49
+ * `<bin> --version`, read by `pick`. Null: the client is not there or does not answer. A probe
50
+ * that ran out of time or could not start for want of resources throws ProbeUndecided: a client
51
+ * that starts slowly while another one is busy is still installed.
52
+ */
53
+ export async function probeVersion(bin, env, pick) {
54
+ try {
55
+ const { stdout } = await run(bin, ["--version"], { timeout: 15_000, env });
56
+ return pick(stdout);
57
+ }
58
+ catch (err) {
59
+ const { killed, code } = err;
60
+ if (killed || (typeof code === "string" && BUSY_CODES.has(code))) {
61
+ throw new ProbeUndecided(`${bin} --version did not finish`, { cause: err });
62
+ }
63
+ return null;
64
+ }
65
+ }
66
+ let shellEnv = null;
67
+ /** The person's login shell, asked once: a desktop app and a bare dev server start without its variables. */
68
+ export function loginShellEnv() {
69
+ shellEnv ??= new Promise((done) => {
70
+ // Windows has no login shell to ask: the process's own environment is the person's.
71
+ if (process.platform === "win32") {
72
+ done({});
73
+ return;
74
+ }
75
+ const shell = process.env.SHELL || "/bin/zsh";
76
+ // In a session of its own, away from the terminal this process runs in: an interactive
77
+ // shell takes over that terminal for its job control and keeps it when it ends, and Ctrl-C
78
+ // then reaches nobody. (execFile cannot do this: it drops `detached`.)
79
+ const child = spawnDetached(shell, ["-l", "-i", "-c", "env"], {
80
+ detached: true,
81
+ stdio: ["ignore", "pipe", "ignore"],
82
+ timeout: 10_000,
83
+ env: {
84
+ HOME: process.env.HOME,
85
+ USER: process.env.USER,
86
+ PATH: process.env.PATH,
87
+ TERM: "dumb",
88
+ },
89
+ });
90
+ let stdout = "";
91
+ child.stdout.setEncoding("utf8");
92
+ child.stdout.on("data", (chunk) => {
93
+ stdout += chunk;
94
+ });
95
+ child.on("error", () => done({}));
96
+ child.on("close", (code) => {
97
+ const out = {};
98
+ for (const line of code === 0 ? stdout.split("\n") : []) {
99
+ const at = line.indexOf("=");
100
+ if (at > 0) {
101
+ out[line.slice(0, at)] = line.slice(at + 1);
102
+ }
103
+ }
104
+ done(out);
105
+ });
106
+ });
107
+ return shellEnv;
108
+ }
109
+ /**
110
+ * What a Windows program needs of the environment to start at all: the system's folders, the
111
+ * user's folders, and how commands are found and run (a .cmd needs ComSpec).
112
+ */
113
+ const WINDOWS_BASE = /^(SystemRoot|SystemDrive|windir|ComSpec|PATHEXT|TEMP|TMP|USERPROFILE|USERNAME|USERDOMAIN|HOMEDRIVE|HOMEPATH|APPDATA|LOCALAPPDATA|ProgramData|ProgramFiles|ProgramFiles\(x86\)|ProgramW6432|CommonProgramFiles|CommonProgramFiles\(x86\)|CommonProgramW6432|COMPUTERNAME|OS|PROCESSOR_ARCHITECTURE|NUMBER_OF_PROCESSORS)$/i;
114
+ /**
115
+ * The environment a client gets: its sign-in as the login shell sets it (else as this process
116
+ * has it), PATH as the shell has it so the client is found from a GUI app too, and nothing else —
117
+ * no key of the host's, no session of a parent client.
118
+ */
119
+ export function clientEnv(shell, own, passThrough,
120
+ /** Folders before the shell's PATH: the clients the host installed. */
121
+ first = [], platform = process.platform) {
122
+ const picked = {};
123
+ const source = Object.keys(shell).length ? shell : own;
124
+ for (const [key, value] of Object.entries(source)) {
125
+ if (passThrough.test(key) && value) {
126
+ picked[key] = value;
127
+ }
128
+ }
129
+ const windows = platform === "win32";
130
+ if (windows) {
131
+ for (const [key, value] of Object.entries(own)) {
132
+ if (WINDOWS_BASE.test(key) && value) {
133
+ picked[key] = value;
134
+ }
135
+ }
136
+ }
137
+ const sep = windows ? ";" : ":";
138
+ const ownPath = own.PATH ?? own.Path ?? "";
139
+ const path = [...first, ...(shell.PATH ?? "").split(sep), ...ownPath.split(sep)].filter(Boolean);
140
+ return {
141
+ ...picked,
142
+ PATH: [...new Set(path)].join(sep),
143
+ HOME: own.HOME,
144
+ USER: own.USER,
145
+ LANG: "en_US.UTF-8",
146
+ TERM: "dumb",
147
+ };
148
+ }
149
+ /** The environment without the named keys. */
150
+ export function stripKeys(env, keyVars) {
151
+ const bare = { ...env };
152
+ for (const key of keyVars) {
153
+ delete bare[key];
154
+ }
155
+ return bare;
156
+ }
157
+ let folders = () => [];
158
+ /**
159
+ * Where the host installs clients, searched before the shell's PATH: a setup that installs a
160
+ * client into a folder of its own names the folder here, once, before any client runs.
161
+ */
162
+ export function setClientFolders(list) {
163
+ folders = list;
164
+ }
165
+ const resolved = new Map();
166
+ /**
167
+ * The environment a client runs in, decided once: the subscription sign-in comes first — it is
168
+ * what the person installed the client for — so a key the shell sets is held back while the
169
+ * client is signed in without it, and used only where it is the one way in.
170
+ */
171
+ export function resolveEnv(spec) {
172
+ let pending = resolved.get(spec.id);
173
+ if (!pending) {
174
+ pending = (async () => {
175
+ const withKey = clientEnv(await loginShellEnv(), process.env, spec.passThrough, folders());
176
+ const bare = stripKeys(withKey, spec.keyVars);
177
+ const own = await spec.auth(bare);
178
+ if (own !== "none") {
179
+ return { env: bare, auth: own };
180
+ }
181
+ if (spec.keyVars.some((key) => withKey[key])) {
182
+ const keyed = await spec.auth(withKey);
183
+ if (keyed !== "none") {
184
+ return { env: withKey, auth: "api_key" };
185
+ }
186
+ }
187
+ return { env: bare, auth: "none" };
188
+ })();
189
+ resolved.set(spec.id, pending);
190
+ }
191
+ return pending;
192
+ }
193
+ /** The environment of a sign-in: the client on its own, without a key of the shell, in a real terminal. */
194
+ export async function loginEnv(spec) {
195
+ const bare = stripKeys(clientEnv(await loginShellEnv(), process.env, spec.passThrough, folders()), spec.keyVars);
196
+ return { ...bare, TERM: "xterm-256color", COLORTERM: "truecolor" };
197
+ }
198
+ /** The client's sign-in right now, on its own: asked again and again while the person signs in. */
199
+ export async function freshAuth(spec) {
200
+ return spec.auth(await loginEnv(spec));
201
+ }
202
+ /** Forgets what was decided: the person may just have signed in or changed their shell. */
203
+ export function forgetEnv(id) {
204
+ shellEnv = null;
205
+ if (id) {
206
+ resolved.delete(id);
207
+ }
208
+ else {
209
+ resolved.clear();
210
+ }
211
+ }
@@ -0,0 +1,26 @@
1
+ /** Who answers, as a failure names it. */
2
+ export interface ClientMeta {
3
+ id: string;
4
+ /** The product name, as the person knows it. */
5
+ name: string;
6
+ }
7
+ /**
8
+ * Why a client did not answer: its account cannot pay (`exhausted`), the vendor no longer serves
9
+ * that account with this client (`not_served`), it is not signed in (`signed_out`), it is not
10
+ * installed (`not_installed`), or anything else (`failed`). Each host words them itself.
11
+ */
12
+ export type FailureCode = "exhausted" | "not_served" | "signed_out" | "not_installed" | "failed";
13
+ /** A client's failure, with what the client itself said. */
14
+ export declare class ClientFailure extends Error {
15
+ readonly code: FailureCode;
16
+ readonly client: ClientMeta;
17
+ /** What the client said, as it said it. */
18
+ readonly detail: string;
19
+ /** The client's whole last output, where it says more than `detail`. */
20
+ readonly raw?: string;
21
+ constructor(code: FailureCode, client: ClientMeta, detail: string, raw?: string);
22
+ }
23
+ /** The kind of failure a client's own words describe. */
24
+ export declare function failureCode(detail: string): FailureCode;
25
+ /** The failure a client reports, sorted by what it says. */
26
+ export declare function clientFailure(client: ClientMeta, detail: string, raw?: string): ClientFailure;
@@ -0,0 +1,35 @@
1
+ /** A client's failure, with what the client itself said. */
2
+ export class ClientFailure extends Error {
3
+ code;
4
+ client;
5
+ /** What the client said, as it said it. */
6
+ detail;
7
+ /** The client's whole last output, where it says more than `detail`. */
8
+ raw;
9
+ constructor(code, client, detail, raw) {
10
+ super(`${client.name}: ${detail}`.slice(0, 500));
11
+ this.code = code;
12
+ this.client = client;
13
+ this.detail = detail;
14
+ this.raw = raw;
15
+ }
16
+ }
17
+ /** The kind of failure a client's own words describe. */
18
+ export function failureCode(detail) {
19
+ if (/credit balance|billing|too low|usage limit|quota|insufficient|rate.?limit|\b429\b/i.test(detail)) {
20
+ return "exhausted";
21
+ }
22
+ // Signed in, but the vendor no longer serves that account with this client: signing in again
23
+ // with the same account changes nothing.
24
+ if (/IneligibleTier|no longer supported|UNSUPPORTED_CLIENT|not eligible/i.test(detail)) {
25
+ return "not_served";
26
+ }
27
+ if (/authenticat|log ?in|logged in|oauth|credential|unauthori[sz]ed|\b401\b|api key/i.test(detail)) {
28
+ return "signed_out";
29
+ }
30
+ return "failed";
31
+ }
32
+ /** The failure a client reports, sorted by what it says. */
33
+ export function clientFailure(client, detail, raw) {
34
+ return new ClientFailure(failureCode(detail), client, detail, raw);
35
+ }
@@ -0,0 +1,14 @@
1
+ import type { Client, ClientId } from "./client.js";
2
+ export { type ChatCall, type ChatClient, type ChatEvent, type ChatMcp, issuesIn, } from "./chat.js";
3
+ export { CLAUDE_BIN, type ClaudeResult, claude, claudeAnswer } from "./claude.js";
4
+ export { CLIENT_IDS, type Client, type ClientId } from "./client.js";
5
+ export { CODEX_BIN, type CodexEvent, codex, codexAnswer, codexExecArgs } from "./codex.js";
6
+ export { CURSOR_BIN, type CursorResult, cursor, cursorWorkspace } from "./cursor.js";
7
+ export { type ClientStatus, type Detectable, detectClient } from "./detect.js";
8
+ export { type ClientAuth, clientEnv, type EnvSpec, forgetEnv, freshAuth, loginEnv, loginShellEnv, ProbeUndecided, probeVersion, type ResolvedEnv, resolveEnv, run, setClientFolders, stripKeys, } from "./env.js";
9
+ export { ClientFailure, type ClientMeta, clientFailure, type FailureCode, failureCode, } from "./failure.js";
10
+ export { type Bridge, type BridgeTool, type ClientAnswer, type ClientCall, type ClientImageCall, ClientImageModel, ClientModel, type ClientModelOptions, type Effort, } from "./model.js";
11
+ export { DEFAULT_WORDS, extensionOf, jsonInstruction, type PromptWords, parseJsonAnswer, renderPrompt, } from "./prompt.js";
12
+ export { type ClientOutput, lastJson, runClient } from "./run.js";
13
+ /** The clients, by id. */
14
+ export declare const CLIENTS: Record<ClientId, Client>;
@@ -0,0 +1,16 @@
1
+ import { claude } from "./claude.js";
2
+ import { codex } from "./codex.js";
3
+ import { cursor } from "./cursor.js";
4
+ export { issuesIn, } from "./chat.js";
5
+ export { CLAUDE_BIN, claude, claudeAnswer } from "./claude.js";
6
+ export { CLIENT_IDS } from "./client.js";
7
+ export { CODEX_BIN, codex, codexAnswer, codexExecArgs } from "./codex.js";
8
+ export { CURSOR_BIN, cursor, cursorWorkspace } from "./cursor.js";
9
+ export { detectClient } from "./detect.js";
10
+ export { clientEnv, forgetEnv, freshAuth, loginEnv, loginShellEnv, ProbeUndecided, probeVersion, resolveEnv, run, setClientFolders, stripKeys, } from "./env.js";
11
+ export { ClientFailure, clientFailure, failureCode, } from "./failure.js";
12
+ export { ClientImageModel, ClientModel, } from "./model.js";
13
+ export { DEFAULT_WORDS, extensionOf, jsonInstruction, parseJsonAnswer, renderPrompt, } from "./prompt.js";
14
+ export { lastJson, runClient } from "./run.js";
15
+ /** The clients, by id. */
16
+ export const CLIENTS = { claude, codex, cursor };
@@ -0,0 +1,126 @@
1
+ import type { ImageModel, LanguageModel } from "ai";
2
+ import { ClientFailure, type ClientMeta } from "./failure.js";
3
+ import { type PromptWords } from "./prompt.js";
4
+ /**
5
+ * An installed AI client as a model: every call runs the client once, headless, on the person's
6
+ * own sign-in. A call with tools hands them to the client over MCP (the host's `bridge`) and lets
7
+ * it work through them itself; a call that wants structured output has the client validate it
8
+ * against the schema where it can, else asks for JSON and parses it. A client that makes images
9
+ * on the sign-in is an image model as well (ClientImageModel).
10
+ */
11
+ type V3 = Extract<LanguageModel, {
12
+ specificationVersion: "v3";
13
+ }>;
14
+ type ImageV3 = Extract<ImageModel, {
15
+ specificationVersion: "v3";
16
+ }>;
17
+ type ImageCallOptions = Parameters<ImageV3["doGenerate"]>[0];
18
+ type ImageResult = Awaited<ReturnType<ImageV3["doGenerate"]>>;
19
+ type CallOptions = Parameters<V3["doGenerate"]>[0];
20
+ type GenerateResult = Awaited<ReturnType<V3["doGenerate"]>>;
21
+ type StreamResult = Awaited<ReturnType<V3["doStream"]>>;
22
+ /** How hard the client works on a call, where it takes a hint. */
23
+ export type Effort = "low" | "medium" | "high";
24
+ /** A tool of the call, served to the client over MCP while it answers. */
25
+ export interface BridgeTool {
26
+ name: string;
27
+ description?: string;
28
+ /** JSON Schema of the input, as the model call declares it. */
29
+ inputSchema: Record<string, unknown>;
30
+ execute(input: unknown): Promise<unknown>;
31
+ /** What the model gets to see of a result where a tool shapes it (a screenshot, say). */
32
+ toModelOutput?: (output: unknown) => unknown;
33
+ }
34
+ /** Serves a call's tools over MCP at `url` until `close`. */
35
+ export type Bridge = (tools: BridgeTool[]) => {
36
+ url: string;
37
+ close(): void;
38
+ };
39
+ export interface ClientModelOptions {
40
+ effort?: Effort;
41
+ /** Where each call gets a folder of its own, deleted afterwards. Default: the system's temp folder. */
42
+ workDir?: string;
43
+ /** Serves a call's tools to the client; without it a call's tools are left out, with a warning. */
44
+ bridge?: Bridge;
45
+ /** The sentences the client reads besides the call's messages. */
46
+ words?: PromptWords;
47
+ /** What a client's failure becomes for the host, such as an error that names it in the person's language. */
48
+ error?: (failure: ClientFailure) => Error;
49
+ }
50
+ /** One call, as the client is asked for it. */
51
+ export interface ClientCall {
52
+ /** A folder of this call alone: attachments, config files; deleted afterwards. */
53
+ dir: string;
54
+ system: string;
55
+ prompt: string;
56
+ files: string[];
57
+ /** The MCP server holding this call's tools, when it has any. */
58
+ bridgeUrl: string | null;
59
+ /** The schema the answer must match — only for a client that validates it itself. */
60
+ schema: unknown | null;
61
+ webSearch: boolean;
62
+ effort?: Effort;
63
+ signal?: AbortSignal;
64
+ }
65
+ export interface ClientAnswer {
66
+ text: string;
67
+ usage?: {
68
+ input?: number;
69
+ cacheRead?: number;
70
+ cacheWrite?: number;
71
+ output?: number;
72
+ };
73
+ meta?: Record<string, string | number | boolean | null>;
74
+ sessionId?: string;
75
+ stopReason?: string;
76
+ }
77
+ export declare abstract class ClientModel implements V3 {
78
+ readonly specificationVersion: "v3";
79
+ abstract readonly provider: string;
80
+ readonly modelId: string;
81
+ readonly supportedUrls: {};
82
+ /** Whether the client validates structured output against the schema itself. */
83
+ protected readonly nativeSchema: boolean;
84
+ /** Whether the client runs a call's tools (over the bridge); else they are left out, with a warning. */
85
+ protected readonly usesTools: boolean;
86
+ /** The same, for whoever builds the call: a caller tells such a client no tools exist. */
87
+ get takesTools(): boolean;
88
+ /** Whether the client searches the web with a tool of its own, tools of the call or not. */
89
+ protected readonly searchesWeb: boolean;
90
+ protected readonly effort?: Effort;
91
+ protected readonly client: ClientMeta;
92
+ protected readonly options: ClientModelOptions;
93
+ private readonly executors;
94
+ constructor(client: ClientMeta, alias: string, options?: ClientModelOptions);
95
+ /** The tools a call may name, by the names the agent gives them: the client runs them over the bridge. */
96
+ attach(tools: Record<string, unknown>): void;
97
+ /** Runs the client once for this call. */
98
+ protected abstract invoke(call: ClientCall): Promise<ClientAnswer>;
99
+ doGenerate(options: CallOptions): Promise<GenerateResult>;
100
+ /** The answer as one piece: the client prints it when it is done. */
101
+ doStream(options: CallOptions): Promise<StreamResult>;
102
+ }
103
+ /** One image call, as the client is asked for it. */
104
+ export interface ClientImageCall {
105
+ /** A folder of this call alone, with the reference images in it; deleted afterwards. */
106
+ dir: string;
107
+ prompt: string;
108
+ /** The reference images, as paths in `dir`. */
109
+ files: string[];
110
+ aspectRatio?: string;
111
+ signal?: AbortSignal;
112
+ }
113
+ /** A client that makes images on the person's sign-in: one client run per image. */
114
+ export declare abstract class ClientImageModel implements ImageV3 {
115
+ readonly specificationVersion: "v3";
116
+ abstract readonly provider: string;
117
+ readonly modelId: string;
118
+ readonly maxImagesPerCall = 1;
119
+ protected readonly client: ClientMeta;
120
+ protected readonly options: ClientModelOptions;
121
+ constructor(client: ClientMeta, alias: string, options?: ClientModelOptions);
122
+ /** Runs the client once and hands back the image it made. */
123
+ protected abstract invoke(call: ClientImageCall): Promise<Uint8Array>;
124
+ doGenerate(options: ImageCallOptions): Promise<ImageResult>;
125
+ }
126
+ export {};
@@ -0,0 +1,225 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { mkdirSync, rmSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { ClientFailure } from "./failure.js";
6
+ import { DEFAULT_WORDS, extensionOf, jsonInstruction, parseJsonAnswer, renderPrompt, } from "./prompt.js";
7
+ const callDir = (workDir) => join(workDir ?? join(tmpdir(), "engenty-local-models"), randomBytes(8).toString("hex"));
8
+ /** A failure as the host wants it: ENOENT is a client that is not installed. */
9
+ function hostError(err, client, error) {
10
+ const failure = err?.code === "ENOENT" && !(err instanceof ClientFailure)
11
+ ? new ClientFailure("not_installed", client, err.message)
12
+ : err;
13
+ return failure instanceof ClientFailure && error ? error(failure) : failure;
14
+ }
15
+ export class ClientModel {
16
+ specificationVersion = "v3";
17
+ modelId;
18
+ supportedUrls = {};
19
+ /** Whether the client validates structured output against the schema itself. */
20
+ nativeSchema = false;
21
+ /** Whether the client runs a call's tools (over the bridge); else they are left out, with a warning. */
22
+ usesTools = true;
23
+ /** The same, for whoever builds the call: a caller tells such a client no tools exist. */
24
+ get takesTools() {
25
+ return this.usesTools;
26
+ }
27
+ /** Whether the client searches the web with a tool of its own, tools of the call or not. */
28
+ searchesWeb = true;
29
+ effort;
30
+ client;
31
+ options;
32
+ executors = new Map();
33
+ constructor(client, alias, options = {}) {
34
+ this.client = client;
35
+ this.modelId = alias;
36
+ this.effort = options.effort;
37
+ this.options = options;
38
+ }
39
+ /** The tools a call may name, by the names the agent gives them: the client runs them over the bridge. */
40
+ attach(tools) {
41
+ for (const [name, tool] of Object.entries(tools)) {
42
+ const t = tool;
43
+ if (typeof t?.execute === "function") {
44
+ this.executors.set(name, t);
45
+ if (t.id) {
46
+ this.executors.set(t.id, t);
47
+ }
48
+ }
49
+ }
50
+ }
51
+ async doGenerate(options) {
52
+ const dir = callDir(this.options.workDir);
53
+ mkdirSync(dir, { recursive: true });
54
+ const words = this.options.words ?? DEFAULT_WORDS;
55
+ const { system, prompt, files, warnings } = renderPrompt(options.prompt, dir, words);
56
+ const bridged = [];
57
+ let webSearch = false;
58
+ for (const tool of options.tools ?? []) {
59
+ // The client searches with its own tool; naming `web_search` is what switches it on.
60
+ if (tool.type === "function" && tool.name === "web_search" && this.searchesWeb) {
61
+ webSearch = true;
62
+ continue;
63
+ }
64
+ if (tool.type !== "function" || !this.usesTools || !this.options.bridge) {
65
+ warnings.push({ type: "unsupported", feature: `tool ${tool.name}` });
66
+ continue;
67
+ }
68
+ const executor = this.executors.get(tool.name);
69
+ if (!executor?.execute) {
70
+ warnings.push({
71
+ type: "unsupported",
72
+ feature: `tool ${tool.name}`,
73
+ details: "no executor",
74
+ });
75
+ continue;
76
+ }
77
+ bridged.push({
78
+ name: tool.name,
79
+ description: tool.description,
80
+ inputSchema: tool.inputSchema,
81
+ execute: (input) => executor.execute(input),
82
+ toModelOutput: executor.toModelOutput,
83
+ });
84
+ }
85
+ for (const key of ["temperature", "topP", "topK", "seed", "stopSequences"]) {
86
+ if (options[key] !== undefined) {
87
+ warnings.push({ type: "unsupported", feature: key });
88
+ }
89
+ }
90
+ const structured = options.responseFormat?.type === "json";
91
+ const schema = structured && options.responseFormat?.type === "json"
92
+ ? (options.responseFormat.schema ?? null)
93
+ : null;
94
+ const bridge = bridged.length && this.options.bridge ? this.options.bridge(bridged) : null;
95
+ try {
96
+ const answer = await this.invoke({
97
+ dir,
98
+ system: structured && !this.nativeSchema
99
+ ? [system, jsonInstruction(schema, words)].filter(Boolean).join("\n\n")
100
+ : system,
101
+ prompt,
102
+ files,
103
+ bridgeUrl: bridge?.url ?? null,
104
+ schema: this.nativeSchema ? schema : null,
105
+ webSearch,
106
+ effort: this.effort,
107
+ signal: options.abortSignal,
108
+ });
109
+ const u = answer.usage ?? {};
110
+ const cacheRead = u.cacheRead ?? 0;
111
+ const cacheWrite = u.cacheWrite ?? 0;
112
+ const input = u.input ?? 0;
113
+ return {
114
+ content: [
115
+ {
116
+ type: "text",
117
+ text: structured ? JSON.stringify(parseJsonAnswer(answer.text)) : answer.text,
118
+ },
119
+ ],
120
+ finishReason: { unified: "stop", raw: answer.stopReason },
121
+ usage: {
122
+ inputTokens: {
123
+ total: input,
124
+ noCache: Math.max(0, input - cacheRead - cacheWrite),
125
+ cacheRead,
126
+ cacheWrite,
127
+ },
128
+ outputTokens: { total: u.output ?? 0, text: u.output ?? 0, reasoning: undefined },
129
+ raw: u,
130
+ },
131
+ providerMetadata: { [this.provider]: answer.meta ?? {} },
132
+ response: { id: answer.sessionId, modelId: this.modelId },
133
+ warnings,
134
+ };
135
+ }
136
+ catch (err) {
137
+ throw hostError(err, this.client, this.options.error);
138
+ }
139
+ finally {
140
+ bridge?.close();
141
+ rmSync(dir, { recursive: true, force: true });
142
+ }
143
+ }
144
+ /** The answer as one piece: the client prints it when it is done. */
145
+ async doStream(options) {
146
+ const result = await this.doGenerate(options);
147
+ const text = result.content.find((c) => c.type === "text");
148
+ const parts = [
149
+ { type: "stream-start", warnings: result.warnings },
150
+ { type: "response-metadata", ...result.response },
151
+ { type: "text-start", id: "0" },
152
+ { type: "text-delta", id: "0", delta: text?.type === "text" ? text.text : "" },
153
+ { type: "text-end", id: "0" },
154
+ {
155
+ type: "finish",
156
+ usage: result.usage,
157
+ finishReason: result.finishReason,
158
+ providerMetadata: result.providerMetadata,
159
+ },
160
+ ];
161
+ return {
162
+ stream: new ReadableStream({
163
+ start(controller) {
164
+ for (const part of parts) {
165
+ controller.enqueue(part);
166
+ }
167
+ controller.close();
168
+ },
169
+ }),
170
+ };
171
+ }
172
+ }
173
+ /** A client that makes images on the person's sign-in: one client run per image. */
174
+ export class ClientImageModel {
175
+ specificationVersion = "v3";
176
+ modelId;
177
+ maxImagesPerCall = 1;
178
+ client;
179
+ options;
180
+ constructor(client, alias, options = {}) {
181
+ this.client = client;
182
+ this.modelId = alias;
183
+ this.options = options;
184
+ }
185
+ async doGenerate(options) {
186
+ const dir = callDir(this.options.workDir);
187
+ mkdirSync(dir, { recursive: true });
188
+ const warnings = [];
189
+ const files = [];
190
+ for (const file of options.files ?? []) {
191
+ if (file.type !== "file") {
192
+ warnings.push({ type: "unsupported", feature: "image url" });
193
+ continue;
194
+ }
195
+ const path = join(dir, `ref-${files.length + 1}.${extensionOf(file.mediaType)}`);
196
+ writeFileSync(path, typeof file.data === "string" ? Buffer.from(file.data, "base64") : file.data);
197
+ files.push(path);
198
+ }
199
+ for (const key of ["size", "seed", "mask"]) {
200
+ if (options[key] !== undefined) {
201
+ warnings.push({ type: "unsupported", feature: key });
202
+ }
203
+ }
204
+ try {
205
+ const image = await this.invoke({
206
+ dir,
207
+ prompt: options.prompt ?? "",
208
+ files,
209
+ aspectRatio: options.aspectRatio,
210
+ signal: options.abortSignal,
211
+ });
212
+ return {
213
+ images: [image],
214
+ warnings,
215
+ response: { timestamp: new Date(), modelId: this.modelId, headers: undefined },
216
+ };
217
+ }
218
+ catch (err) {
219
+ throw hostError(err, this.client, this.options.error);
220
+ }
221
+ finally {
222
+ rmSync(dir, { recursive: true, force: true });
223
+ }
224
+ }
225
+ }