@engenty/wizards-runtime 0.20.4 → 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.
Files changed (87) hide show
  1. package/README.md +1 -1
  2. package/apps/runtime/dist/agents/subscription.js +19 -11
  3. package/apps/runtime/dist/cli/ollama.js +7 -76
  4. package/apps/runtime/dist/cli/setup.js +5 -4
  5. package/apps/runtime/dist/decision-model.js +1 -4
  6. package/apps/runtime/dist/docs/dev/licensing.md +7 -2
  7. package/apps/runtime/dist/docs/user-guide/command-line.md +2 -2
  8. package/apps/runtime/dist/engine/device.js +3 -2
  9. package/apps/runtime/dist/harness/antigravity.js +11 -7
  10. package/apps/runtime/dist/harness/apple.js +4 -3
  11. package/apps/runtime/dist/harness/clients.js +108 -0
  12. package/apps/runtime/dist/harness/index.js +29 -30
  13. package/apps/runtime/dist/harness/model.js +32 -270
  14. package/apps/runtime/dist/harness/prompt.js +6 -120
  15. package/apps/runtime/dist/harness/types.js +3 -2
  16. package/apps/runtime/dist/local-models.js +17 -37
  17. package/apps/runtime/dist/models.js +8 -5
  18. package/apps/runtime/dist/motion-graphics/step.js +2 -2
  19. package/apps/runtime/dist/routes/studio.js +1 -1
  20. package/apps/runtime/dist/services/work-ai.js +2 -2
  21. package/apps/web/dist/assets/{AboutDialog-CQvfeGqA.js → AboutDialog-BRUwrfQH.js} +1 -1
  22. package/apps/web/dist/assets/{CapabilitiesPage-DJRpCw2_.js → CapabilitiesPage-C30knXsS.js} +1 -1
  23. package/apps/web/dist/assets/{ChangelogDialog-F7gj0WCW.js → ChangelogDialog-BkZQOAdl.js} +1 -1
  24. package/apps/web/dist/assets/{ConnectorsSection-dXmTJOrm.js → ConnectorsSection-CmXQD7zu.js} +1 -1
  25. package/apps/web/dist/assets/{EditorPage-DNox0Po-.js → EditorPage-LEbyNWmG.js} +1 -1
  26. package/apps/web/dist/assets/{NewWizardChannels-BugegWm1.js → NewWizardChannels-CSn-9zHr.js} +1 -1
  27. package/apps/web/dist/assets/{NewWizardPage-Df359wgE.js → NewWizardPage-B4wPfClS.js} +1 -1
  28. package/apps/web/dist/assets/{ProtocolSection-B1tcJgJl.js → ProtocolSection-s4mEL_pu.js} +1 -1
  29. package/apps/web/dist/assets/{ReadOnly-DxC8kALr.js → ReadOnly-CO3ndR23.js} +1 -1
  30. package/apps/web/dist/assets/{Results-D6ecFiSB.js → Results-CC1-mElv.js} +1 -1
  31. package/apps/web/dist/assets/{RunDrawer-oPFk8yHt.js → RunDrawer-DkmSXhad.js} +1 -1
  32. package/apps/web/dist/assets/{SettingsPage-DueaPjW3.js → SettingsPage-DKs_fkNL.js} +2 -2
  33. package/apps/web/dist/assets/{SetupPage-k61GmbIs.js → SetupPage-RvmKCzF2.js} +1 -1
  34. package/apps/web/dist/assets/{SpacePage-z66Mza2y.js → SpacePage-aZqYFttF.js} +1 -1
  35. package/apps/web/dist/assets/{StudioHome-q1f_vqAI.js → StudioHome-Doua9Lyl.js} +1 -1
  36. package/apps/web/dist/assets/{TableEditor-Dfu5Qa-O.js → TableEditor-Dbq3HZZS.js} +1 -1
  37. package/apps/web/dist/assets/{UpdateCheck-y1StF2CW.js → UpdateCheck-B7etUbUf.js} +2 -2
  38. package/apps/web/dist/assets/changelog-BW79cVbx.js +1 -0
  39. package/apps/web/dist/assets/{host-Bh_WJbQv.js → host-BXSxBoOH.js} +3 -3
  40. package/apps/web/dist/assets/{index-CgSUfzBq.js → index-kDKA6ddy.js} +3 -3
  41. package/apps/web/dist/assets/{oss-credits-C4SGbRkz.js → oss-credits-B3PXhamW.js} +1 -1
  42. package/apps/web/dist/index.html +4 -4
  43. package/bin/bot-tunnel.mjs +375 -0
  44. package/bin/bot.mjs +1133 -125
  45. package/node_modules/@engenty/local-models/dist/clients/chat.d.ts +89 -0
  46. package/node_modules/@engenty/local-models/dist/clients/chat.js +22 -0
  47. package/node_modules/@engenty/local-models/dist/clients/claude.d.ts +32 -0
  48. package/node_modules/@engenty/local-models/dist/clients/claude.js +238 -0
  49. package/node_modules/@engenty/local-models/dist/clients/client.d.ts +29 -0
  50. package/node_modules/@engenty/local-models/dist/clients/client.js +2 -0
  51. package/node_modules/@engenty/local-models/dist/clients/codex.d.ts +35 -0
  52. package/node_modules/@engenty/local-models/dist/clients/codex.js +253 -0
  53. package/node_modules/@engenty/local-models/dist/clients/cursor.d.ts +33 -0
  54. package/node_modules/@engenty/local-models/dist/clients/cursor.js +180 -0
  55. package/node_modules/@engenty/local-models/dist/clients/detect.d.ts +18 -0
  56. package/node_modules/@engenty/local-models/dist/clients/detect.js +34 -0
  57. package/node_modules/@engenty/local-models/dist/clients/env.d.ts +66 -0
  58. package/{apps/runtime/dist/harness → node_modules/@engenty/local-models/dist/clients}/env.js +62 -31
  59. package/node_modules/@engenty/local-models/dist/clients/failure.d.ts +26 -0
  60. package/node_modules/@engenty/local-models/dist/clients/failure.js +35 -0
  61. package/node_modules/@engenty/local-models/dist/clients/index.d.ts +14 -0
  62. package/node_modules/@engenty/local-models/dist/clients/index.js +16 -0
  63. package/node_modules/@engenty/local-models/dist/clients/model.d.ts +126 -0
  64. package/node_modules/@engenty/local-models/dist/clients/model.js +225 -0
  65. package/node_modules/@engenty/local-models/dist/clients/prompt.d.ts +36 -0
  66. package/node_modules/@engenty/local-models/dist/clients/prompt.js +123 -0
  67. package/node_modules/@engenty/local-models/dist/clients/run.d.ts +15 -0
  68. package/node_modules/@engenty/local-models/dist/clients/run.js +41 -0
  69. package/node_modules/@engenty/local-models/dist/index.d.ts +3 -0
  70. package/node_modules/@engenty/local-models/dist/index.js +3 -0
  71. package/node_modules/@engenty/local-models/dist/ollama/api.d.ts +70 -0
  72. package/node_modules/@engenty/local-models/dist/ollama/api.js +164 -0
  73. package/node_modules/@engenty/local-models/dist/ollama/index.d.ts +2 -0
  74. package/node_modules/@engenty/local-models/dist/ollama/index.js +2 -0
  75. package/node_modules/@engenty/local-models/dist/ollama/model.d.ts +52 -0
  76. package/node_modules/@engenty/local-models/dist/ollama/model.js +302 -0
  77. package/node_modules/@engenty/local-models/dist/probe.d.ts +54 -0
  78. package/node_modules/@engenty/local-models/dist/probe.js +190 -0
  79. package/node_modules/@engenty/local-models/package.json +12 -0
  80. package/package.json +3 -1
  81. package/plugin/.claude-plugin/plugin.json +1 -1
  82. package/plugin/plugin.json +1 -1
  83. package/apps/runtime/dist/agents/chat-clients.js +0 -344
  84. package/apps/runtime/dist/harness/claude.js +0 -141
  85. package/apps/runtime/dist/harness/codex.js +0 -222
  86. package/apps/runtime/dist/harness/cursor.js +0 -89
  87. package/apps/web/dist/assets/changelog-DoEmFdnI.js +0 -1
@@ -1,8 +1,45 @@
1
- import { spawn } from "node:child_process";
2
- import { join } from "node:path";
3
- import { runFile } from "../cli/exec.js";
4
- import { layout } from "../cli/home.js";
5
- export const run = runFile;
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
+ }
6
43
  /** A version probe that could not finish: the machine is busy, the client may well be there. */
7
44
  export class ProbeUndecided extends Error {
8
45
  }
@@ -30,16 +67,16 @@ let shellEnv = null;
30
67
  /** The person's login shell, asked once: a desktop app and a bare dev server start without its variables. */
31
68
  export function loginShellEnv() {
32
69
  shellEnv ??= new Promise((done) => {
33
- // Windows has no login shell to ask: the runtime's own environment is the person's.
70
+ // Windows has no login shell to ask: the process's own environment is the person's.
34
71
  if (process.platform === "win32") {
35
72
  done({});
36
73
  return;
37
74
  }
38
75
  const shell = process.env.SHELL || "/bin/zsh";
39
- // In a session of its own, away from the terminal `wizards` runs in: an interactive
76
+ // In a session of its own, away from the terminal this process runs in: an interactive
40
77
  // shell takes over that terminal for its job control and keeps it when it ends, and Ctrl-C
41
78
  // then reaches nobody. (execFile cannot do this: it drops `detached`.)
42
- const child = spawn(shell, ["-l", "-i", "-c", "env"], {
79
+ const child = spawnDetached(shell, ["-l", "-i", "-c", "env"], {
43
80
  detached: true,
44
81
  stdio: ["ignore", "pipe", "ignore"],
45
82
  timeout: 10_000,
@@ -69,13 +106,18 @@ export function loginShellEnv() {
69
106
  });
70
107
  return shellEnv;
71
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;
72
114
  /**
73
115
  * The environment a client gets: its sign-in as the login shell sets it (else as this process
74
116
  * has it), PATH as the shell has it so the client is found from a GUI app too, and nothing else —
75
- * no key of ours, no session of a parent client.
117
+ * no key of the host's, no session of a parent client.
76
118
  */
77
- export function pickEnv(shell, own, passThrough,
78
- /** Folders before the shell's PATH: the clients the setup installed. */
119
+ export function clientEnv(shell, own, passThrough,
120
+ /** Folders before the shell's PATH: the clients the host installed. */
79
121
  first = [], platform = process.platform) {
80
122
  const picked = {};
81
123
  const source = Object.keys(shell).length ? shell : own;
@@ -104,11 +146,7 @@ first = [], platform = process.platform) {
104
146
  TERM: "dumb",
105
147
  };
106
148
  }
107
- /**
108
- * What a Windows program needs of the environment to start at all: the system's folders, the
109
- * user's folders, and how commands are found and run (a .cmd needs ComSpec).
110
- */
111
- 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;
149
+ /** The environment without the named keys. */
112
150
  export function stripKeys(env, keyVars) {
113
151
  const bare = { ...env };
114
152
  for (const key of keyVars) {
@@ -116,21 +154,14 @@ export function stripKeys(env, keyVars) {
116
154
  }
117
155
  return bare;
118
156
  }
157
+ let folders = () => [];
119
158
  /**
120
- * Where the setup installs clients, whoever started this runtime: npm's prefix (on Windows the
121
- * prefix itself), and on Windows where Claude Code and Cursor Agent put themselves.
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.
122
161
  */
123
- const installed = () => {
124
- if (process.platform !== "win32") {
125
- return [join(layout().clients, "bin")];
126
- }
127
- const { USERPROFILE: home, LOCALAPPDATA: local } = process.env;
128
- return [
129
- layout().clients,
130
- ...(home ? [join(home, ".local", "bin")] : []),
131
- ...(local ? [join(local, "cursor-agent"), join(local, "agy", "bin")] : []),
132
- ];
133
- };
162
+ export function setClientFolders(list) {
163
+ folders = list;
164
+ }
134
165
  const resolved = new Map();
135
166
  /**
136
167
  * The environment a client runs in, decided once: the subscription sign-in comes first — it is
@@ -141,7 +172,7 @@ export function resolveEnv(spec) {
141
172
  let pending = resolved.get(spec.id);
142
173
  if (!pending) {
143
174
  pending = (async () => {
144
- const withKey = pickEnv(await loginShellEnv(), process.env, spec.passThrough, installed());
175
+ const withKey = clientEnv(await loginShellEnv(), process.env, spec.passThrough, folders());
145
176
  const bare = stripKeys(withKey, spec.keyVars);
146
177
  const own = await spec.auth(bare);
147
178
  if (own !== "none") {
@@ -161,7 +192,7 @@ export function resolveEnv(spec) {
161
192
  }
162
193
  /** The environment of a sign-in: the client on its own, without a key of the shell, in a real terminal. */
163
194
  export async function loginEnv(spec) {
164
- const bare = stripKeys(pickEnv(await loginShellEnv(), process.env, spec.passThrough, installed()), spec.keyVars);
195
+ const bare = stripKeys(clientEnv(await loginShellEnv(), process.env, spec.passThrough, folders()), spec.keyVars);
165
196
  return { ...bare, TERM: "xterm-256color", COLORTERM: "truecolor" };
166
197
  }
167
198
  /** The client's sign-in right now, on its own: asked again and again while the person signs in. */
@@ -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
+ }
@@ -0,0 +1,36 @@
1
+ import type { LanguageModel } from "ai";
2
+ type V3 = Extract<LanguageModel, {
3
+ specificationVersion: "v3";
4
+ }>;
5
+ type CallOptions = Parameters<V3["doGenerate"]>[0];
6
+ type GenerateResult = Awaited<ReturnType<V3["doGenerate"]>>;
7
+ export type Message = CallOptions["prompt"][number];
8
+ export type Warning = GenerateResult["warnings"][number];
9
+ /** The sentences a client reads besides the call's own messages; a host may word them itself. */
10
+ export interface PromptWords {
11
+ /** Where a saved attachment stood in the prompt. */
12
+ attachedFile(path: string): string;
13
+ /** Added to the system prompt when the client gets a whole thread as one prompt. */
14
+ conversationNote(): string;
15
+ /** For a client without a schema option; `schema` is the JSON Schema, as JSON. */
16
+ jsonInstruction(schema: string): string;
17
+ }
18
+ export declare const DEFAULT_WORDS: PromptWords;
19
+ /** The extension a saved attachment gets, so the client reads it as what it is. */
20
+ export declare function extensionOf(mediaType: string, filename?: string): string;
21
+ /**
22
+ * The conversation as a client takes it: one system prompt and one prompt on stdin. A single
23
+ * user message goes as it is; a longer thread is written out with its speakers, and the client
24
+ * is asked to answer its last message. Attachments are saved to `dir` and named in the prompt.
25
+ */
26
+ export declare function renderPrompt(messages: Message[], dir?: string, words?: PromptWords): {
27
+ system: string;
28
+ prompt: string;
29
+ files: string[];
30
+ warnings: Warning[];
31
+ };
32
+ /** What a client without a schema option is told so its answer parses. */
33
+ export declare function jsonInstruction(schema: unknown, words?: PromptWords): string;
34
+ /** A client's answer as JSON: the fences and prose some wrap around it are taken off. */
35
+ export declare function parseJsonAnswer(text: string): unknown;
36
+ export {};