@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,283 +1,45 @@
1
- import { mkdirSync, rmSync, writeFileSync } from "node:fs";
2
1
  import { join } from "node:path";
2
+ import { clientFailure, } from "@engenty/local-models/clients";
3
3
  import { note } from "@engenty/wizards-shared/run";
4
- import spawn from "cross-spawn";
5
- import { nanoid } from "nanoid";
6
4
  import { env } from "../env.js";
7
5
  import { openBridge } from "../mcp/bridge.js";
8
6
  import { ModelUnavailableError } from "../model-errors.js";
9
- import { extensionOf, jsonInstruction, parseJsonAnswer, renderPrompt } from "./prompt.js";
10
- const workDir = join(env.dataDir, "harness");
7
+ import { CLIENT_WORDS } from "./prompt.js";
11
8
  export const signedOut = (h) => note("clientNotSignedIn", { name: h.name });
12
9
  export const notInstalled = (h) => note("clientNotInstalled", { name: h.name });
13
10
  export const notServed = (h) => note("clientAccountNotServed", { name: h.name });
14
11
  export const exhausted = (h) => h.exhausted ?? note("clientNoCredit", { name: h.name });
15
- /** The failure a client reports, as the person should read it. */
16
- export function failureOf(h, detail) {
17
- // The client's own words stay in the log: the sentence below sums them up for the person.
18
- console.warn(`[${h.id}] ${detail.replace(/\s+/g, " ").trim().slice(0, 1500)}`);
19
- if (/credit balance|billing|too low|usage limit|quota|insufficient|rate.?limit|\b429\b/i.test(detail)) {
20
- return new ModelUnavailableError(exhausted(h));
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 new ModelUnavailableError(notServed(h));
26
- }
27
- if (/authenticat|log ?in|logged in|oauth|credential|unauthori[sz]ed|\b401\b|api key/i.test(detail)) {
28
- return new ModelUnavailableError(signedOut(h));
12
+ /** A client's failure as the person should read it. */
13
+ export function clientError(h, failure) {
14
+ if (failure.code === "not_installed") {
15
+ return new ModelUnavailableError(notInstalled(h));
16
+ }
17
+ // The client's own words stay in the log: the note sums them up for the person.
18
+ if (failure.raw) {
19
+ console.warn(`[${h.id}] the client failed:`, failure.raw);
20
+ }
21
+ console.warn(`[${h.id}] ${failure.detail.replace(/\s+/g, " ").trim().slice(0, 1500)}`);
22
+ switch (failure.code) {
23
+ case "exhausted":
24
+ return new ModelUnavailableError(exhausted(h));
25
+ case "not_served":
26
+ return new ModelUnavailableError(notServed(h));
27
+ case "signed_out":
28
+ return new ModelUnavailableError(signedOut(h));
29
+ default:
30
+ return failure;
29
31
  }
30
- return new Error(`${h.name}: ${detail}`.slice(0, 500));
31
32
  }
32
- /** Runs a client once with the prompt on stdin; a client that is not there raises ENOENT. */
33
- export function runClient(bin, args, opts) {
34
- return new Promise((resolve, reject) => {
35
- const child = spawn(bin, args, {
36
- cwd: opts.cwd,
37
- stdio: ["pipe", "pipe", "pipe"],
38
- signal: opts.signal,
39
- env: opts.env,
40
- });
41
- let stdout = "";
42
- let stderr = "";
43
- child.stdout.on("data", (chunk) => {
44
- stdout += String(chunk);
45
- });
46
- child.stderr.on("data", (chunk) => {
47
- stderr = (stderr + String(chunk)).slice(-4000);
48
- });
49
- child.on("error", reject);
50
- child.on("close", (code) => resolve({ stdout, stderr, code }));
51
- child.stdin.on("error", () => {
52
- // The client went away before reading the prompt; `close` reports it.
53
- });
54
- child.stdin.end(opts.stdin ?? "");
55
- });
56
- }
57
- /** The last line of an output that is a JSON object. */
58
- export function lastJson(stdout) {
59
- for (const line of stdout.trim().split("\n").reverse()) {
60
- try {
61
- const value = JSON.parse(line);
62
- if (value && typeof value === "object") {
63
- return value;
64
- }
65
- }
66
- catch {
67
- // not it
68
- }
69
- }
70
- return null;
71
- }
72
- export class HarnessModel {
73
- specificationVersion = "v3";
74
- modelId;
75
- supportedUrls = {};
76
- /** Whether the client validates structured output against the schema itself. */
77
- nativeSchema = false;
78
- /** Whether the client runs a call's tools (over the bridge); else they are left out, with a warning. */
79
- usesTools = true;
80
- /** The same, for whoever builds the call: a step tells such a client no tools exist. */
81
- get takesTools() {
82
- return this.usesTools;
83
- }
84
- /** Whether the client searches the web with a tool of its own, tools of the call or not. */
85
- searchesWeb = true;
86
- effort;
87
- harness;
88
- executors = new Map();
89
- constructor(harness, alias, effort) {
90
- this.harness = harness;
91
- this.modelId = alias;
92
- this.effort = effort;
93
- }
94
- /** The tools a call may name, by the names the agent gives them: the client runs them over the bridge. */
95
- attach(tools) {
96
- for (const [name, tool] of Object.entries(tools)) {
97
- const t = tool;
98
- if (typeof t?.execute === "function") {
99
- this.executors.set(name, t);
100
- if (t.id) {
101
- this.executors.set(t.id, t);
102
- }
103
- }
104
- }
105
- }
106
- async doGenerate(options) {
107
- const dir = join(workDir, nanoid(10));
108
- mkdirSync(dir, { recursive: true });
109
- const { system, prompt, files, warnings } = renderPrompt(options.prompt, dir);
110
- const bridged = [];
111
- let webSearch = false;
112
- for (const tool of options.tools ?? []) {
113
- // The client searches with its own tool; naming `web_search` is what switches it on.
114
- if (tool.type === "function" && tool.name === "web_search" && this.searchesWeb) {
115
- webSearch = true;
116
- continue;
117
- }
118
- if (tool.type !== "function" || !this.usesTools) {
119
- warnings.push({ type: "unsupported", feature: `tool ${tool.name}` });
120
- continue;
121
- }
122
- const executor = this.executors.get(tool.name);
123
- if (!executor?.execute) {
124
- warnings.push({
125
- type: "unsupported",
126
- feature: `tool ${tool.name}`,
127
- details: "no executor",
128
- });
129
- continue;
130
- }
131
- bridged.push({
132
- name: tool.name,
133
- description: tool.description,
134
- inputSchema: tool.inputSchema,
135
- execute: (input) => executor.execute(input),
136
- toModelOutput: executor.toModelOutput,
137
- });
138
- }
139
- for (const key of ["temperature", "topP", "topK", "seed", "stopSequences"]) {
140
- if (options[key] !== undefined) {
141
- warnings.push({ type: "unsupported", feature: key });
142
- }
143
- }
144
- const structured = options.responseFormat?.type === "json";
145
- const schema = structured && options.responseFormat?.type === "json"
146
- ? (options.responseFormat.schema ?? null)
147
- : null;
148
- const bridge = bridged.length ? openBridge(bridged) : null;
149
- try {
150
- const answer = await this.invoke({
151
- dir,
152
- system: structured && !this.nativeSchema
153
- ? [system, jsonInstruction(schema)].filter(Boolean).join("\n\n")
154
- : system,
155
- prompt,
156
- files,
157
- bridgeUrl: bridge?.url ?? null,
158
- schema: this.nativeSchema ? schema : null,
159
- webSearch,
160
- effort: this.effort,
161
- signal: options.abortSignal,
162
- });
163
- const u = answer.usage ?? {};
164
- const cacheRead = u.cacheRead ?? 0;
165
- const cacheWrite = u.cacheWrite ?? 0;
166
- const input = u.input ?? 0;
167
- return {
168
- content: [
169
- {
170
- type: "text",
171
- text: structured ? JSON.stringify(parseJsonAnswer(answer.text)) : answer.text,
172
- },
173
- ],
174
- finishReason: { unified: "stop", raw: answer.stopReason },
175
- usage: {
176
- inputTokens: {
177
- total: input,
178
- noCache: Math.max(0, input - cacheRead - cacheWrite),
179
- cacheRead,
180
- cacheWrite,
181
- },
182
- outputTokens: { total: u.output ?? 0, text: u.output ?? 0, reasoning: undefined },
183
- raw: u,
184
- },
185
- providerMetadata: { [this.provider]: answer.meta ?? {} },
186
- response: { id: answer.sessionId, modelId: this.modelId },
187
- warnings,
188
- };
189
- }
190
- catch (err) {
191
- if (err.code === "ENOENT") {
192
- throw new ModelUnavailableError(notInstalled(this.harness));
193
- }
194
- throw err;
195
- }
196
- finally {
197
- bridge?.close();
198
- rmSync(dir, { recursive: true, force: true });
199
- }
200
- }
201
- /** The answer as one piece: the client prints it when it is done. */
202
- async doStream(options) {
203
- const result = await this.doGenerate(options);
204
- const text = result.content.find((c) => c.type === "text");
205
- const parts = [
206
- { type: "stream-start", warnings: result.warnings },
207
- { type: "response-metadata", ...result.response },
208
- { type: "text-start", id: "0" },
209
- { type: "text-delta", id: "0", delta: text?.type === "text" ? text.text : "" },
210
- { type: "text-end", id: "0" },
211
- {
212
- type: "finish",
213
- usage: result.usage,
214
- finishReason: result.finishReason,
215
- providerMetadata: result.providerMetadata,
216
- },
217
- ];
218
- return {
219
- stream: new ReadableStream({
220
- start(controller) {
221
- for (const part of parts) {
222
- controller.enqueue(part);
223
- }
224
- controller.close();
225
- },
226
- }),
227
- };
228
- }
33
+ /** The failure a client reports, as the person should read it. */
34
+ export function failureOf(h, detail) {
35
+ return clientError(h, clientFailure(h, detail));
229
36
  }
230
- /** A client that makes images on the person's sign-in: one client run per image. */
231
- export class HarnessImageModel {
232
- specificationVersion = "v3";
233
- modelId;
234
- maxImagesPerCall = 1;
235
- harness;
236
- constructor(harness, alias) {
237
- this.harness = harness;
238
- this.modelId = alias;
239
- }
240
- async doGenerate(options) {
241
- const dir = join(workDir, nanoid(10));
242
- mkdirSync(dir, { recursive: true });
243
- const warnings = [];
244
- const files = [];
245
- for (const file of options.files ?? []) {
246
- if (file.type !== "file") {
247
- warnings.push({ type: "unsupported", feature: "image url" });
248
- continue;
249
- }
250
- const path = join(dir, `ref-${files.length + 1}.${extensionOf(file.mediaType)}`);
251
- writeFileSync(path, typeof file.data === "string" ? Buffer.from(file.data, "base64") : file.data);
252
- files.push(path);
253
- }
254
- for (const key of ["size", "seed", "mask"]) {
255
- if (options[key] !== undefined) {
256
- warnings.push({ type: "unsupported", feature: key });
257
- }
258
- }
259
- try {
260
- const image = await this.invoke({
261
- dir,
262
- prompt: options.prompt ?? "",
263
- files,
264
- aspectRatio: options.aspectRatio,
265
- signal: options.abortSignal,
266
- });
267
- return {
268
- images: [image],
269
- warnings,
270
- response: { timestamp: new Date(), modelId: this.modelId, headers: undefined },
271
- };
272
- }
273
- catch (err) {
274
- if (err.code === "ENOENT") {
275
- throw new ModelUnavailableError(notInstalled(this.harness));
276
- }
277
- throw err;
278
- }
279
- finally {
280
- rmSync(dir, { recursive: true, force: true });
281
- }
282
- }
37
+ /** How the runtime runs a client as a model. */
38
+ export function modelOptions(h) {
39
+ return {
40
+ workDir: join(env.dataDir, "harness"),
41
+ bridge: openBridge,
42
+ words: CLIENT_WORDS,
43
+ error: (failure) => clientError(h, failure),
44
+ };
283
45
  }
@@ -1,121 +1,7 @@
1
- import { writeFileSync } from "node:fs";
2
- import { join } from "node:path";
3
1
  import { prompt } from "../prompts.js";
4
- /** The extension a saved attachment gets, so the client reads it as what it is. */
5
- export function extensionOf(mediaType, filename) {
6
- const own = filename?.match(/\.([a-z0-9]{1,5})$/i)?.[1];
7
- if (own) {
8
- return own.toLowerCase();
9
- }
10
- const sub = mediaType.split("/")[1] ?? "bin";
11
- return { jpeg: "jpg", "svg+xml": "svg", plain: "txt", markdown: "md" }[sub] ?? sub;
12
- }
13
- /**
14
- * The conversation as a client takes it: one system prompt and one prompt on stdin. A single
15
- * user message goes as it is; a longer thread is written out with its speakers, and the client
16
- * is asked to answer its last message. Attachments are saved to `dir` and named in the prompt.
17
- */
18
- export function renderPrompt(messages, dir) {
19
- const warnings = [];
20
- const files = [];
21
- const system = [];
22
- const turns = [];
23
- const saveFile = (input) => {
24
- // A file's content comes tagged: { type: "data", data } | { type: "url", url } | { type: "text", text }.
25
- const tagged = input.data;
26
- const data = tagged && typeof tagged === "object" && typeof tagged.type === "string"
27
- ? tagged.type === "url"
28
- ? tagged.url
29
- : tagged.type === "text"
30
- ? Buffer.from(tagged.text ?? "", "utf8")
31
- : tagged.data
32
- : input.data;
33
- const part = { ...input, data };
34
- if (part.data instanceof URL) {
35
- return `[Attachment at ${part.data.href} (${part.mediaType})]`;
36
- }
37
- if (typeof part.data !== "string" && !(part.data instanceof Uint8Array)) {
38
- warnings.push({ type: "unsupported", feature: "file parts" });
39
- return `[Attachment: ${part.filename ?? part.mediaType}]`;
40
- }
41
- if (!dir) {
42
- warnings.push({ type: "unsupported", feature: "file parts" });
43
- return `[Attachment: ${part.filename ?? part.mediaType}]`;
44
- }
45
- const path = join(dir, `${files.length + 1}.${extensionOf(part.mediaType, part.filename)}`);
46
- const bytes = typeof part.data === "string" ? Buffer.from(part.data, "base64") : part.data;
47
- writeFileSync(path, bytes);
48
- files.push(path);
49
- return prompt("services", "harness.attached_file", { path });
50
- };
51
- for (const m of messages) {
52
- if (m.role === "system") {
53
- system.push(m.content);
54
- continue;
55
- }
56
- const text = m.content
57
- .map((part) => {
58
- switch (part.type) {
59
- case "text":
60
- return part.text;
61
- case "file":
62
- return saveFile(part);
63
- case "reasoning":
64
- return "";
65
- case "tool-call":
66
- return `[Called ${part.toolName} with ${JSON.stringify(part.input)}]`;
67
- case "tool-result": {
68
- const out = part.output;
69
- const value = out.type === "text" || out.type === "error-text"
70
- ? String(out.value)
71
- : out.type === "json" || out.type === "error-json"
72
- ? JSON.stringify(out.value)
73
- : out.type === "execution-denied"
74
- ? `denied${out.reason ? `: ${out.reason}` : ""}`
75
- : JSON.stringify(out.value ?? out);
76
- return `[Result of ${part.toolName}: ${value}]`;
77
- }
78
- default:
79
- return "";
80
- }
81
- })
82
- .filter(Boolean)
83
- .join("\n");
84
- turns.push({ role: m.role, text });
85
- }
86
- const request = turns.length === 1 && turns[0].role === "user"
87
- ? turns[0].text
88
- : turns
89
- .map((t) => `${t.role === "user" ? "User" : t.role === "tool" ? "Tool" : "Assistant"}:\n${t.text}`)
90
- .join("\n\n");
91
- if (turns.length > 1) {
92
- system.push(prompt("services", "harness.conversation_note"));
93
- }
94
- return { system: system.join("\n\n"), prompt: request, files, warnings };
95
- }
96
- /** What a client without a schema option is told so its answer parses. */
97
- export function jsonInstruction(schema) {
98
- return prompt("services", "harness.json_instruction", {
99
- schema: JSON.stringify(schema ?? { type: "object" }),
100
- });
101
- }
102
- /** A client's answer as JSON: the fences and prose some wrap around it are taken off. */
103
- export function parseJsonAnswer(text) {
104
- const trimmed = text.trim();
105
- const unfenced = trimmed
106
- .replace(/^\s*```(?:json)?\s*/i, "")
107
- .replace(/\s*```\s*$/, "")
108
- .trim();
109
- try {
110
- return JSON.parse(unfenced);
111
- }
112
- catch {
113
- // Prose around the value: take the outermost object or array.
114
- const start = unfenced.search(/[{[]/);
115
- const end = Math.max(unfenced.lastIndexOf("}"), unfenced.lastIndexOf("]"));
116
- if (start >= 0 && end > start) {
117
- return JSON.parse(unfenced.slice(start, end + 1));
118
- }
119
- throw new Error("The answer is not JSON.");
120
- }
121
- }
2
+ /** The sentences an installed client reads besides a call's messages, from prompts/services.md. */
3
+ export const CLIENT_WORDS = {
4
+ attachedFile: (path) => prompt("services", "harness.attached_file", { path }),
5
+ conversationNote: () => prompt("services", "harness.conversation_note"),
6
+ jsonInstruction: (schema) => prompt("services", "harness.json_instruction", { schema }),
7
+ };
@@ -1,7 +1,8 @@
1
1
  /**
2
2
  * A harness is an AI client installed on this machine — Claude Code, Codex, Antigravity, Cursor
3
3
  * Agent — that answers on the person's own subscription or sign-in. The runtime runs it headless
4
- * as a model (./model.ts) and signs it in through the inline terminal (./terminal.ts). Nothing of
5
- * this process reaches it: no key of ours, no session of a parent client.
4
+ * as a model (@engenty/local-models/clients, ./model.ts) and signs it in through the inline
5
+ * terminal (./terminal.ts). Nothing of this process reaches it: no key of ours, no session of a
6
+ * parent client.
6
7
  */
7
8
  export const HARNESS_IDS = ["claude", "codex", "antigravity", "cursor"];
@@ -1,5 +1,5 @@
1
1
  import { totalmem } from "node:os";
2
- import { ollamaRoot } from "./decision-model.js";
2
+ import { fits, installedModels as ollamaModels, ollamaRoot, ollamaState, pullModel, } from "@engenty/local-models/ollama";
3
3
  import { env } from "./env.js";
4
4
  import { forgetLocalModels, localOllamaUrl } from "./models.js";
5
5
  /**
@@ -19,44 +19,25 @@ const JOB_OF = {
19
19
  decision: "decision",
20
20
  };
21
21
  const gb = (bytes) => Math.round((bytes / 1e9) * 10) / 10;
22
- async function getJson(url, init, timeoutMs = 2000) {
22
+ async function getJson(url, timeoutMs) {
23
23
  try {
24
- const res = await fetch(url, { ...init, signal: AbortSignal.timeout(timeoutMs) });
24
+ const res = await fetch(url, { signal: AbortSignal.timeout(timeoutMs) });
25
25
  return res.ok ? (await res.json()) : null;
26
26
  }
27
27
  catch {
28
28
  return null;
29
29
  }
30
30
  }
31
- /** What `/api/show` said about a model, by its digest: it does not change while the digest stays. */
32
- const shown = new Map();
31
+ /** The models Ollama holds, with the jobs each can do here. */
33
32
  async function installedModels(root) {
34
- const [tags, ps] = await Promise.all([
35
- getJson(`${root}/api/tags`),
36
- getJson(`${root}/api/ps`),
37
- ]);
38
- const loaded = new Set((ps?.models ?? []).map((m) => m.name));
39
- return Promise.all((tags?.models ?? []).map(async (m) => {
40
- let show = shown.get(m.digest);
41
- if (!show) {
42
- show =
43
- (await getJson(`${root}/api/show`, {
44
- method: "POST",
45
- headers: { "content-type": "application/json" },
46
- body: JSON.stringify({ model: m.name }),
47
- }, 5000)) ?? {};
48
- shown.set(m.digest, show);
49
- }
50
- const capabilities = show.capabilities ?? [];
51
- return {
52
- name: m.name,
53
- size: gb(m.size),
54
- jobs: LOCAL_JOBS.filter((job) => capabilities.some((c) => JOB_OF[c] === job)),
55
- capabilities,
56
- runner: show.details?.runner || null,
57
- quantization: show.details?.quantization_level || null,
58
- loaded: loaded.has(m.name),
59
- };
33
+ return (await ollamaModels(root)).map((m) => ({
34
+ name: m.name,
35
+ size: gb(m.size),
36
+ jobs: LOCAL_JOBS.filter((job) => m.capabilities.some((c) => JOB_OF[c] === job)),
37
+ capabilities: m.capabilities,
38
+ runner: m.runner,
39
+ quantization: m.quantization,
40
+ loaded: m.running,
60
41
  }));
61
42
  }
62
43
  /** The Manage-App's list at the last look: kept for an hour, asked again after five minutes when it did not answer. */
@@ -65,7 +46,7 @@ async function offeredModels() {
65
46
  if (offered && Date.now() < offered.at) {
66
47
  return offered.models;
67
48
  }
68
- const body = await getJson(`${env.local.accountUrl}/v1/local-models`, undefined, 3000);
49
+ const body = await getJson(`${env.local.accountUrl}/v1/local-models`, 3000);
69
50
  const models = body?.models?.filter((m) => LOCAL_JOBS.includes(m.job)) ?? null;
70
51
  offered = { models, at: Date.now() + (models ? 60 : 5) * 60_000 };
71
52
  return models;
@@ -78,7 +59,7 @@ export async function localModels() {
78
59
  const url = await localOllamaUrl();
79
60
  const root = ollamaRoot(url);
80
61
  const { findOllama, freeGb } = await import("./cli/ollama.js");
81
- const version = (await getJson(`${root}/api/version`))?.version ?? null;
62
+ const { version } = await ollamaState(root);
82
63
  const memory = Math.round(totalmem() / 2 ** 30);
83
64
  const installed = version ? await installedModels(root) : [];
84
65
  const held = new Set(installed.map((m) => m.name));
@@ -102,7 +83,7 @@ export async function localModels() {
102
83
  offered: list?.map((m) => ({
103
84
  ...m,
104
85
  installed: held.has(m.name) || held.has(`${m.name}:latest`),
105
- fits: m.memory <= memory * MEMORY_SHARE,
86
+ fits: fits(m.memory, memory, MEMORY_SHARE),
106
87
  })) ?? null,
107
88
  downloads: [...downloads.values()],
108
89
  };
@@ -118,11 +99,10 @@ export async function downloadLocalModel(model, then) {
118
99
  }
119
100
  const state = { model, done: 0, total: 0, error: null, finished: false };
120
101
  downloads.set(model, state);
121
- const { pullModel } = await import("./cli/ollama.js");
122
- void pullModel(model, (done, total) => {
102
+ void pullModel(await localOllamaUrl(), model, (done, total) => {
123
103
  state.done = done;
124
104
  state.total = total;
125
- }, { OLLAMA_URL: await localOllamaUrl() })
105
+ })
126
106
  .then(async () => {
127
107
  forgetLocalModels();
128
108
  state.finished = true;
@@ -6,18 +6,21 @@ import { createGateway } from "@ai-sdk/gateway";
6
6
  import { createGoogle } from "@ai-sdk/google";
7
7
  import { createOpenAI } from "@ai-sdk/openai";
8
8
  import { createReplicate } from "@ai-sdk/replicate";
9
+ import { ClientModel } from "@engenty/local-models/clients";
10
+ import { ollamaRoot } from "@engenty/local-models/ollama";
9
11
  import { DEFINITION_VERSION, MODEL_CLASSES, TEXT_CLASSES, } from "@engenty/wizards-shared/definition";
10
12
  import { blockingNeeds, CAPABILITY_CLASSES, creditsModelOf, creditsRef, isCreditsRef, missingNeeds, PROVIDER_IDS, providerInfo, providerOfRef, traitsOf, } from "@engenty/wizards-shared/providers";
11
13
  import { note, saidText } from "@engenty/wizards-shared/run";
12
14
  import { policyEntry, } from "@engenty/wizards-shared/tiers";
13
15
  import { generateSpeech, generateText, } from "ai";
14
16
  import { accountToken, linkedAccount } from "./auth/account.js";
15
- import { LOCAL_DECISION_MODEL, ollamaDecisionModel, ollamaRoot } from "./decision-model.js";
17
+ import { LOCAL_DECISION_MODEL, ollamaDecisionModel } from "./decision-model.js";
16
18
  import { DeviceModel, deviceThinks } from "./engine/device.js";
17
19
  import { env } from "./env.js";
18
20
  import { feature, remoteFeatures } from "./features.js";
19
21
  import { appleModel, appleStatus, appleTranscriptionModel, appleUnavailableNote, } from "./harness/apple.js";
20
- import { detectHarness, HarnessModel, harness, isHarnessVendor, notInstalled, signedOut, } from "./harness/index.js";
22
+ import { detectHarness, harness, isHarnessVendor, } from "./harness/index.js";
23
+ import { notInstalled, signedOut } from "./harness/model.js";
21
24
  import { managed, tenantInfo } from "./manage.js";
22
25
  import { hasFfmpeg } from "./media/ffmpeg.js";
23
26
  import { ModelUnavailableError, saidOf } from "./model-errors.js";
@@ -845,7 +848,7 @@ export async function chatModel(way, cls) {
845
848
  * without the generic ones (engine/device.ts).
846
849
  */
847
850
  export function attachTools(resolved, tools, ignorable = false) {
848
- if (resolved.model instanceof HarnessModel) {
851
+ if (resolved.model instanceof ClientModel) {
849
852
  resolved.model.attach(tools);
850
853
  }
851
854
  else if (resolved.model instanceof DeviceModel) {
@@ -854,13 +857,13 @@ export function attachTools(resolved, tools, ignorable = false) {
854
857
  }
855
858
  /** A model whose tool loop runs in a process of its own: an installed client, the run's device. */
856
859
  export function keepsOwnLoop(resolved) {
857
- return (resolved.model instanceof HarnessModel ||
860
+ return (resolved.model instanceof ClientModel ||
858
861
  resolved.model instanceof DeviceModel ||
859
862
  isHarnessVendor(resolved.vendor));
860
863
  }
861
864
  /** Whether the model can call tools: an installed client that runs none cannot. */
862
865
  export function takesTools(resolved) {
863
- return !(resolved.model instanceof HarnessModel) || resolved.model.takesTools;
866
+ return !(resolved.model instanceof ClientModel) || resolved.model.takesTools;
864
867
  }
865
868
  /** Gemini image models of the gateway are chat models answering with image files. */
866
869
  export function isChatImageModel(ref) {
@@ -2,10 +2,10 @@ import { spawn } from "node:child_process";
2
2
  import { existsSync } from "node:fs";
3
3
  import { readFile, rm, stat } from "node:fs/promises";
4
4
  import { isAbsolute, join, normalize } from "node:path";
5
+ import { CLAUDE_BIN, CLIENTS, resolveEnv } from "@engenty/local-models/clients";
5
6
  import { MOTION_SIZES, textClassOf, } from "@engenty/wizards-shared/definition";
6
7
  import { note as runNote } from "@engenty/wizards-shared/run";
7
8
  import { StepError } from "../engine/types.js";
8
- import { CLAUDE_BIN, claudeEnv } from "../harness/claude.js";
9
9
  import { failureOf } from "../harness/model.js";
10
10
  import { openBridge } from "../mcp/bridge.js";
11
11
  import { saidOf } from "../model-errors.js";
@@ -160,7 +160,7 @@ export async function runMotionGraphicsStep(step, ctx) {
160
160
  void (async () => {
161
161
  const child = spawn(CLAUDE_BIN, args, {
162
162
  cwd: root,
163
- env: await claudeEnv(),
163
+ env: (await resolveEnv(CLIENTS.claude)).env,
164
164
  stdio: ["pipe", "pipe", "pipe"],
165
165
  signal: limit,
166
166
  });
@@ -1,5 +1,6 @@
1
1
  import { mkdirSync } from "node:fs";
2
2
  import { join } from "node:path";
3
+ import { freshAuth, loginEnv } from "@engenty/local-models/clients";
3
4
  import { ASSISTANT_LAYOUTS, ASSISTANT_PAGE_BYTES, ASSISTANT_WIDTH, assistantSignalSchema, assistantTurnSchema, } from "@engenty/wizards-shared/assistant";
4
5
  import { LANGS, MODEL_CLASSES, TEXT_CLASSES, } from "@engenty/wizards-shared/definition";
5
6
  import { CATEGORY_TYPES, whereSchema } from "@engenty/wizards-shared/knowledge";
@@ -36,7 +37,6 @@ import { missingConnections, missingModels, stepsWithoutModel, unwatchedConnecti
36
37
  import { env } from "../env.js";
37
38
  import { feature, features, forgetAccountFeatures } from "../features.js";
38
39
  import { appleStatus } from "../harness/apple.js";
39
- import { freshAuth, loginEnv } from "../harness/env.js";
40
40
  import { detectHarness, detectHarnesses, HARNESS_IDS, harness, installSpec, } from "../harness/index.js";
41
41
  import { closeTerminal, openTerminal, resizeTerminal, subscribeTerminal, writeTerminal, } from "../harness/terminal.js";
42
42
  import { connectorsView, filesView, spacesView, translationsView, wizardsView, wizardView, } from "../live/views.js";