@happyvertical/smrt-inference 0.60.17 → 0.61.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +35 -1
- package/README.md +86 -0
- package/agents/design-runs.md +110 -0
- package/agents/engines.md +458 -0
- package/dist/agent-cli/credentials.d.ts +28 -0
- package/dist/agent-cli/credentials.d.ts.map +1 -0
- package/dist/agent-cli/detect.d.ts +28 -0
- package/dist/agent-cli/detect.d.ts.map +1 -0
- package/dist/agent-cli/env.d.ts +14 -0
- package/dist/agent-cli/env.d.ts.map +1 -0
- package/dist/agent-cli/locate.d.ts +16 -0
- package/dist/agent-cli/locate.d.ts.map +1 -0
- package/dist/agent-cli/login.d.ts +30 -0
- package/dist/agent-cli/login.d.ts.map +1 -0
- package/dist/agent-cli/runner.d.ts +31 -0
- package/dist/agent-cli/runner.d.ts.map +1 -0
- package/dist/agent-cli/service.d.ts +20 -0
- package/dist/agent-cli/service.d.ts.map +1 -0
- package/dist/agent-cli/session.d.ts +42 -0
- package/dist/agent-cli/session.d.ts.map +1 -0
- package/dist/agent-cli/stream.d.ts +50 -0
- package/dist/agent-cli/stream.d.ts.map +1 -0
- package/dist/agent-cli/test-support.d.ts +21 -0
- package/dist/agent-cli/test-support.d.ts.map +1 -0
- package/dist/agent-cli/test-support.js +67 -0
- package/dist/agent-cli/test-support.js.map +1 -0
- package/dist/agent-cli/tools.d.ts +19 -0
- package/dist/agent-cli/tools.d.ts.map +1 -0
- package/dist/agent-cli/turn.d.ts +138 -0
- package/dist/agent-cli/turn.d.ts.map +1 -0
- package/dist/chatgpt/connection.d.ts +149 -0
- package/dist/chatgpt/connection.d.ts.map +1 -0
- package/dist/chatgpt/model.d.ts +42 -0
- package/dist/chatgpt/model.d.ts.map +1 -0
- package/dist/chatgpt/resolver.d.ts +39 -0
- package/dist/chatgpt/resolver.d.ts.map +1 -0
- package/dist/chatgpt/support.d.ts +36 -0
- package/dist/chatgpt/support.d.ts.map +1 -0
- package/dist/chunks/{InferenceOverrideCollection-ZpxhP0Zl.js → InferenceOverrideCollection-DrlOGPCI.js} +62 -3
- package/dist/chunks/InferenceOverrideCollection-DrlOGPCI.js.map +1 -0
- package/dist/chunks/work-profiles-DCgIbilc.js +484 -0
- package/dist/chunks/work-profiles-DCgIbilc.js.map +1 -0
- package/dist/design-run-store.d.ts +26 -0
- package/dist/design-run-store.d.ts.map +1 -0
- package/dist/design-run.d.ts +146 -0
- package/dist/design-run.d.ts.map +1 -0
- package/dist/engine-id.d.ts +5 -0
- package/dist/engine-id.d.ts.map +1 -0
- package/dist/engine-model.d.ts +56 -0
- package/dist/engine-model.d.ts.map +1 -0
- package/dist/engine-status.d.ts +37 -0
- package/dist/engine-status.d.ts.map +1 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/manifest.json +182 -1
- package/dist/models/DesignRunRecord.d.ts +22 -0
- package/dist/models/DesignRunRecord.d.ts.map +1 -0
- package/dist/models.d.ts +1 -0
- package/dist/models.d.ts.map +1 -1
- package/dist/models.js +2 -2
- package/dist/node.js +1 -1
- package/dist/node.js.map +1 -1
- package/dist/server.d.ts +24 -0
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +2471 -150
- package/dist/server.js.map +1 -1
- package/dist/settings/controller.d.ts +111 -0
- package/dist/settings/controller.d.ts.map +1 -0
- package/dist/settings/host.d.ts +75 -0
- package/dist/settings/host.d.ts.map +1 -0
- package/dist/settings/key-store.d.ts +35 -0
- package/dist/settings/key-store.d.ts.map +1 -0
- package/dist/settings/resolver.d.ts +6 -2
- package/dist/settings/resolver.d.ts.map +1 -1
- package/dist/smrt-knowledge.json +93 -7
- package/dist/smrt-knowledge.okf.md +15 -5
- package/dist/work-profiles.d.ts +127 -0
- package/dist/work-profiles.d.ts.map +1 -0
- package/package.json +15 -10
- package/dist/chunks/InferenceOverrideCollection-ZpxhP0Zl.js.map +0 -1
package/dist/server.js
CHANGED
|
@@ -1,9 +1,736 @@
|
|
|
1
|
-
import { B as InferenceConfigError, I as findInferenceConfigIssues, N as findFusionDefinitionIssues, P as findFusionDefinitionPromptIssues, b as listFusions, y as getFusion, z as validateInferenceTarget } from "./chunks/provider-config-BSpIQRVM.js";
|
|
1
|
+
import { B as InferenceConfigError, I as findInferenceConfigIssues, N as findFusionDefinitionIssues, P as findFusionDefinitionPromptIssues, b as listFusions, f as createInferenceResolver, y as getFusion, z as validateInferenceTarget } from "./chunks/provider-config-BSpIQRVM.js";
|
|
2
|
+
import { a as rankOpenAIWorkModels, c as runWorkModelWithFallback, d as engineLabel, f as AGENT_TOOLS, g as createDesignRunDriver, h as DesignRunConflictError, i as projectWorkModelSelection, l as strongestWorkModel, m as isAgentTool, n as WORK_MODEL_FALLBACK_MESSAGE, o as recommendedWorkProfile, p as AGENT_TOOL_INFO, r as nextWorkModel, s as resolveWorkProfile, t as OPENAI_WORK_MODEL_RANKS, u as validateWorkModel } from "./chunks/work-profiles-DCgIbilc.js";
|
|
3
|
+
import { createUserInferenceResolver, registerUserInferenceResolver } from "./resolver.js";
|
|
2
4
|
import { checkInferenceBindings, inferenceProbeUrl, probeInferenceCandidate } from "./node.js";
|
|
3
|
-
import { C as getInferenceOverrideGeneration, S as tierBinding, _ as normalizeFusionDefinition, a as INFERENCE_BINDING_NAME_PATTERN, b as parseInferenceBinding, c as TRANSCRIPTS_BINDING, d as inferenceTargetRef, f as isAllowedByList, g as normalizeDefaultTier, h as normalizeAllowList, i as DEFAULT_TIER_BINDING, l as describeInferenceTarget, m as normalizeAliasDefinition, n as APP_INFERENCE_SCOPE_ID, o as INFERENCE_MODES, p as matchesAllowPattern, r as InferenceOverride, s as InferenceBindingValueError, t as InferenceOverrideCollection, u as findKeyMember, v as normalizeTierTarget, x as stripKeyMembers, y as normalizeTranscriptSettings } from "./chunks/InferenceOverrideCollection-
|
|
4
|
-
import { DEFAULT_RETENTION_POLICY, DEFAULT_TRANSCRIPT_MAX_BYTES, DEFAULT_TRANSCRIPT_SAMPLE, INFERENCE_PRESETS, INFERENCE_PRESET_IDS, INFERENCE_TIERS, config, getInferenceConfig, getInferenceTranscriptsConfig, inferenceTargetKind, isInferencePresetId, isInferenceTier, mergeInferenceConfigs, reportAiUsage, resolveAutoTier, setAiTranscriptAppSettings } from "@happyvertical/smrt-core";
|
|
5
|
-
import { AI_PROVIDER_TYPES } from "@happyvertical/ai";
|
|
5
|
+
import { C as getInferenceOverrideGeneration, S as tierBinding, T as installDesignRunExecutor, _ as normalizeFusionDefinition, a as INFERENCE_BINDING_NAME_PATTERN, b as parseInferenceBinding, c as TRANSCRIPTS_BINDING, d as inferenceTargetRef, f as isAllowedByList, g as normalizeDefaultTier, h as normalizeAllowList, i as DEFAULT_TIER_BINDING, l as describeInferenceTarget, m as normalizeAliasDefinition, n as APP_INFERENCE_SCOPE_ID, o as INFERENCE_MODES, p as matchesAllowPattern, r as InferenceOverride, s as InferenceBindingValueError, t as InferenceOverrideCollection, u as findKeyMember, v as normalizeTierTarget, w as DesignRunRecord, x as stripKeyMembers, y as normalizeTranscriptSettings } from "./chunks/InferenceOverrideCollection-DrlOGPCI.js";
|
|
6
|
+
import { DEFAULT_RETENTION_POLICY, DEFAULT_TRANSCRIPT_MAX_BYTES, DEFAULT_TRANSCRIPT_SAMPLE, INFERENCE_PRESETS, INFERENCE_PRESET_IDS, INFERENCE_TIERS, config, getInferenceConfig, getInferenceTranscriptsConfig, inferenceTargetKind, isInferencePresetId, isInferenceTier, mergeInferenceConfigs, reportAiUsage, resolveAutoTier, setAiTranscriptAppSettings, setInferenceResolver } from "@happyvertical/smrt-core";
|
|
7
|
+
import { AI_PROVIDER_TYPES } from "@happyvertical/ai/types";
|
|
6
8
|
import { getDefaultAIKeyEnvName } from "@happyvertical/smrt-config";
|
|
9
|
+
import { SecretService } from "@happyvertical/smrt-secrets";
|
|
10
|
+
import { accessSync, constants, mkdirSync, mkdtempSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
11
|
+
import { homedir, tmpdir } from "node:os";
|
|
12
|
+
import { delimiter, dirname, join } from "node:path";
|
|
13
|
+
import { spawn } from "node:child_process";
|
|
14
|
+
import { randomUUID } from "node:crypto";
|
|
15
|
+
//#region src/agent-cli/credentials.ts
|
|
16
|
+
var AGENT_TOKEN_TTL_SECONDS = 900;
|
|
17
|
+
function tokenCredentials(store, options) {
|
|
18
|
+
return {
|
|
19
|
+
async mint(pass) {
|
|
20
|
+
const tokens = await store();
|
|
21
|
+
if (!tokens) throw new Error("This app has no local token store.");
|
|
22
|
+
return (await tokens.issue({
|
|
23
|
+
scopes: options.scopes,
|
|
24
|
+
expiresInSeconds: Math.max(900, Math.ceil((pass?.timeoutMs ?? 0) / 1e3) + 60),
|
|
25
|
+
label: options.label,
|
|
26
|
+
holder: options.holder
|
|
27
|
+
})).token;
|
|
28
|
+
},
|
|
29
|
+
async revoke() {
|
|
30
|
+
try {
|
|
31
|
+
await (await store())?.revokeHolder(options.holder);
|
|
32
|
+
} catch {}
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
//#endregion
|
|
37
|
+
//#region src/agent-cli/env.ts
|
|
38
|
+
var ALLOW_EXACT = /* @__PURE__ */ new Set([
|
|
39
|
+
"PATH",
|
|
40
|
+
"HOME",
|
|
41
|
+
"USER",
|
|
42
|
+
"LOGNAME",
|
|
43
|
+
"SHELL",
|
|
44
|
+
"LANG",
|
|
45
|
+
"TERM",
|
|
46
|
+
"TZ",
|
|
47
|
+
"TMPDIR",
|
|
48
|
+
"TEMP",
|
|
49
|
+
"TMP",
|
|
50
|
+
"DISPLAY",
|
|
51
|
+
"WAYLAND_DISPLAY",
|
|
52
|
+
"DBUS_SESSION_BUS_ADDRESS",
|
|
53
|
+
"XDG_RUNTIME_DIR",
|
|
54
|
+
"XDG_CONFIG_HOME",
|
|
55
|
+
"XDG_DATA_HOME",
|
|
56
|
+
"XDG_CACHE_HOME",
|
|
57
|
+
"XDG_STATE_HOME",
|
|
58
|
+
"CODEX_HOME",
|
|
59
|
+
"CLAUDE_CONFIG_DIR",
|
|
60
|
+
"HTTP_PROXY",
|
|
61
|
+
"HTTPS_PROXY",
|
|
62
|
+
"NO_PROXY",
|
|
63
|
+
"ALL_PROXY",
|
|
64
|
+
"http_proxy",
|
|
65
|
+
"https_proxy",
|
|
66
|
+
"no_proxy",
|
|
67
|
+
"all_proxy",
|
|
68
|
+
"SSL_CERT_FILE",
|
|
69
|
+
"SSL_CERT_DIR",
|
|
70
|
+
"NODE_EXTRA_CA_CERTS",
|
|
71
|
+
"USERPROFILE",
|
|
72
|
+
"APPDATA",
|
|
73
|
+
"LOCALAPPDATA",
|
|
74
|
+
"PROGRAMDATA",
|
|
75
|
+
"SYSTEMROOT",
|
|
76
|
+
"SystemRoot",
|
|
77
|
+
"WINDIR",
|
|
78
|
+
"windir",
|
|
79
|
+
"COMSPEC",
|
|
80
|
+
"PATHEXT",
|
|
81
|
+
"HOMEDRIVE",
|
|
82
|
+
"HOMEPATH"
|
|
83
|
+
]);
|
|
84
|
+
var DENY_EXACT = /* @__PURE__ */ new Set([
|
|
85
|
+
"ANTHROPIC_API_KEY",
|
|
86
|
+
"ANTHROPIC_AUTH_TOKEN",
|
|
87
|
+
"ANTHROPIC_BASE_URL",
|
|
88
|
+
"CLAUDE_CODE_OAUTH_TOKEN",
|
|
89
|
+
"OPENAI_API_KEY",
|
|
90
|
+
"OPENAI_BASE_URL",
|
|
91
|
+
"OPENAI_ORG_ID",
|
|
92
|
+
"OPENAI_PROJECT_ID",
|
|
93
|
+
"CODEX_API_KEY",
|
|
94
|
+
"CODEX_ACCESS_TOKEN"
|
|
95
|
+
]);
|
|
96
|
+
var DENY_PREFIXES = [
|
|
97
|
+
"SMRT_",
|
|
98
|
+
"CLAUDE_CODE_USE_",
|
|
99
|
+
"ANTHROPIC_",
|
|
100
|
+
"OPENAI_"
|
|
101
|
+
];
|
|
102
|
+
function allowed(name) {
|
|
103
|
+
if (DENY_EXACT.has(name)) return false;
|
|
104
|
+
if (DENY_PREFIXES.some((p) => name.toUpperCase().startsWith(p))) return false;
|
|
105
|
+
return ALLOW_EXACT.has(name) || name.startsWith("LC_");
|
|
106
|
+
}
|
|
107
|
+
function childEnv(base, options = {}) {
|
|
108
|
+
const out = {};
|
|
109
|
+
for (const [name, value] of Object.entries(base)) if (value !== void 0 && allowed(name)) out[name] = value;
|
|
110
|
+
const pathKey = Object.keys(out).find((k) => k.toUpperCase() === "PATH") ?? "PATH";
|
|
111
|
+
const dirs = [...options.extraPath ?? [], ...out[pathKey] ? out[pathKey].split(delimiter) : []].filter(Boolean);
|
|
112
|
+
out[pathKey] = [...new Set(dirs)].join(delimiter);
|
|
113
|
+
Object.assign(out, options.extra);
|
|
114
|
+
return out;
|
|
115
|
+
}
|
|
116
|
+
function nodeDir() {
|
|
117
|
+
return dirname(process.execPath);
|
|
118
|
+
}
|
|
119
|
+
//#endregion
|
|
120
|
+
//#region src/agent-cli/runner.ts
|
|
121
|
+
var KILL_GRACE_MS = 3e3;
|
|
122
|
+
var MAX_LINE_CHARS = 4 * 1024 * 1024;
|
|
123
|
+
var live = /* @__PURE__ */ new Set();
|
|
124
|
+
var exitHooked = false;
|
|
125
|
+
function hookExit() {
|
|
126
|
+
if (exitHooked) return;
|
|
127
|
+
exitHooked = true;
|
|
128
|
+
process.once("exit", () => {
|
|
129
|
+
for (const child of live) killNow(child, "SIGKILL");
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
function killNow(child, signal) {
|
|
133
|
+
const pid = child.pid;
|
|
134
|
+
if (!pid) return;
|
|
135
|
+
try {
|
|
136
|
+
if (process.platform === "win32") spawn("taskkill", [
|
|
137
|
+
"/pid",
|
|
138
|
+
String(pid),
|
|
139
|
+
"/T",
|
|
140
|
+
"/F"
|
|
141
|
+
], {
|
|
142
|
+
stdio: "ignore",
|
|
143
|
+
windowsHide: true
|
|
144
|
+
}).on("error", () => {});
|
|
145
|
+
else process.kill(-pid, signal);
|
|
146
|
+
} catch {
|
|
147
|
+
try {
|
|
148
|
+
child.kill(signal);
|
|
149
|
+
} catch {}
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
function killTree(child) {
|
|
153
|
+
killNow(child, "SIGTERM");
|
|
154
|
+
const timer = setTimeout(() => killNow(child, "SIGKILL"), KILL_GRACE_MS);
|
|
155
|
+
timer.unref();
|
|
156
|
+
child.once("close", () => clearTimeout(timer));
|
|
157
|
+
}
|
|
158
|
+
function runProcess(options) {
|
|
159
|
+
hookExit();
|
|
160
|
+
return new Promise((resolve) => {
|
|
161
|
+
let child;
|
|
162
|
+
try {
|
|
163
|
+
child = spawn(options.command, [...options.args], {
|
|
164
|
+
cwd: options.cwd,
|
|
165
|
+
env: options.env,
|
|
166
|
+
stdio: [
|
|
167
|
+
"pipe",
|
|
168
|
+
"pipe",
|
|
169
|
+
"pipe"
|
|
170
|
+
],
|
|
171
|
+
detached: process.platform !== "win32",
|
|
172
|
+
windowsHide: true,
|
|
173
|
+
shell: false
|
|
174
|
+
});
|
|
175
|
+
} catch (error) {
|
|
176
|
+
resolve({
|
|
177
|
+
exitCode: null,
|
|
178
|
+
termination: null,
|
|
179
|
+
timedOut: false,
|
|
180
|
+
aborted: false,
|
|
181
|
+
spawnError: error instanceof Error ? error.name : "spawn_failed",
|
|
182
|
+
stderrTail: ""
|
|
183
|
+
});
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
live.add(child);
|
|
187
|
+
let timedOut = false;
|
|
188
|
+
let aborted = false;
|
|
189
|
+
let spawnError;
|
|
190
|
+
let stderrTail = "";
|
|
191
|
+
let buffer = "";
|
|
192
|
+
let settled = false;
|
|
193
|
+
const stop = () => killTree(child);
|
|
194
|
+
const timer = setTimeout(() => {
|
|
195
|
+
timedOut = true;
|
|
196
|
+
stop();
|
|
197
|
+
}, options.timeoutMs);
|
|
198
|
+
const onAbort = () => {
|
|
199
|
+
aborted = true;
|
|
200
|
+
stop();
|
|
201
|
+
};
|
|
202
|
+
if (options.signal?.aborted) onAbort();
|
|
203
|
+
else options.signal?.addEventListener("abort", onAbort, { once: true });
|
|
204
|
+
const flushLine = (line) => {
|
|
205
|
+
if (!line) return;
|
|
206
|
+
try {
|
|
207
|
+
options.onStdoutLine?.(line);
|
|
208
|
+
} catch {}
|
|
209
|
+
};
|
|
210
|
+
child.stdout?.setEncoding("utf8");
|
|
211
|
+
child.stdout?.on("data", (chunk) => {
|
|
212
|
+
buffer += chunk;
|
|
213
|
+
let at = buffer.indexOf("\n");
|
|
214
|
+
while (at >= 0) {
|
|
215
|
+
flushLine(buffer.slice(0, at).replace(/\r$/, ""));
|
|
216
|
+
buffer = buffer.slice(at + 1);
|
|
217
|
+
at = buffer.indexOf("\n");
|
|
218
|
+
}
|
|
219
|
+
if (buffer.length > MAX_LINE_CHARS) buffer = "";
|
|
220
|
+
});
|
|
221
|
+
child.stderr?.setEncoding("utf8");
|
|
222
|
+
child.stderr?.on("data", (chunk) => {
|
|
223
|
+
stderrTail = (stderrTail + chunk).slice(-2e3);
|
|
224
|
+
});
|
|
225
|
+
child.stdin?.on("error", () => {});
|
|
226
|
+
try {
|
|
227
|
+
if (options.stdin !== void 0) child.stdin?.write(options.stdin);
|
|
228
|
+
child.stdin?.end();
|
|
229
|
+
} catch {}
|
|
230
|
+
const finish = (exitCode, termination) => {
|
|
231
|
+
if (settled) return;
|
|
232
|
+
settled = true;
|
|
233
|
+
clearTimeout(timer);
|
|
234
|
+
options.signal?.removeEventListener("abort", onAbort);
|
|
235
|
+
if (buffer) flushLine(buffer);
|
|
236
|
+
if (process.platform !== "win32") killNow(child, "SIGKILL");
|
|
237
|
+
live.delete(child);
|
|
238
|
+
resolve({
|
|
239
|
+
exitCode,
|
|
240
|
+
termination,
|
|
241
|
+
timedOut,
|
|
242
|
+
aborted,
|
|
243
|
+
...spawnError ? { spawnError } : {},
|
|
244
|
+
stderrTail
|
|
245
|
+
});
|
|
246
|
+
};
|
|
247
|
+
child.once("error", (error) => {
|
|
248
|
+
spawnError = error.code ?? error.name;
|
|
249
|
+
finish(null, null);
|
|
250
|
+
});
|
|
251
|
+
child.once("close", (code, sig) => finish(code, sig));
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
async function runCollect(options, maxChars = 64e3) {
|
|
255
|
+
const lines = [];
|
|
256
|
+
let size = 0;
|
|
257
|
+
return {
|
|
258
|
+
...await runProcess({
|
|
259
|
+
...options,
|
|
260
|
+
onStdoutLine: (line) => {
|
|
261
|
+
if (size < maxChars) {
|
|
262
|
+
lines.push(line);
|
|
263
|
+
size += line.length + 1;
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
}),
|
|
267
|
+
stdout: lines.join("\n")
|
|
268
|
+
};
|
|
269
|
+
}
|
|
270
|
+
//#endregion
|
|
271
|
+
//#region src/agent-cli/locate.ts
|
|
272
|
+
function defaultLocateDeps() {
|
|
273
|
+
return {
|
|
274
|
+
env: process.env,
|
|
275
|
+
platform: process.platform,
|
|
276
|
+
home: homedir(),
|
|
277
|
+
loginShell: true
|
|
278
|
+
};
|
|
279
|
+
}
|
|
280
|
+
function isExecutable(path, platform) {
|
|
281
|
+
try {
|
|
282
|
+
if (!statSync(path).isFile()) return false;
|
|
283
|
+
if (platform === "win32") return true;
|
|
284
|
+
accessSync(path, constants.X_OK);
|
|
285
|
+
return true;
|
|
286
|
+
} catch {
|
|
287
|
+
return false;
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
function listDirs(path) {
|
|
291
|
+
try {
|
|
292
|
+
return readdirSync(path, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => join(path, e.name));
|
|
293
|
+
} catch {
|
|
294
|
+
return [];
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
function candidateDirs(deps) {
|
|
298
|
+
const { env, platform, home } = deps;
|
|
299
|
+
const out = [];
|
|
300
|
+
const add = (...dirs) => {
|
|
301
|
+
for (const d of dirs) if (d) out.push(d);
|
|
302
|
+
};
|
|
303
|
+
if (platform === "win32") {
|
|
304
|
+
const appData = env.APPDATA ?? join(home, "AppData", "Roaming");
|
|
305
|
+
const local = env.LOCALAPPDATA ?? join(home, "AppData", "Local");
|
|
306
|
+
add(join(home, ".local", "bin"), join(appData, "npm"), join(local, "Programs", "claude"), join(local, "Microsoft", "WinGet", "Links"), join(local, "pnpm"), env.PNPM_HOME, env.NPM_CONFIG_PREFIX);
|
|
307
|
+
return [...new Set(out)];
|
|
308
|
+
}
|
|
309
|
+
add(join(home, ".local", "bin"), join(home, ".claude", "local"), join(home, ".claude", "bin"), ...deps.systemDirs ?? ["/opt/homebrew/bin", "/usr/local/bin"], join(home, ".npm-global", "bin"), env.NPM_CONFIG_PREFIX ? join(env.NPM_CONFIG_PREFIX, "bin") : void 0, env.PNPM_HOME, join(home, "Library", "pnpm"), join(home, ".local", "share", "pnpm"), join(home, ".volta", "bin"), join(home, ".bun", "bin"), join(home, ".yarn", "bin"), join(home, ".asdf", "shims"), join(home, ".local", "share", "mise", "shims"), ...deps.systemDirs ? [] : ["/snap/bin", "/usr/bin"]);
|
|
310
|
+
for (const v of listDirs(join(home, ".nvm", "versions", "node")).sort().reverse()) add(join(v, "bin"));
|
|
311
|
+
for (const v of listDirs(join(home, ".fnm", "node-versions")).sort().reverse()) add(join(v, "installation", "bin"));
|
|
312
|
+
return [...new Set(out)];
|
|
313
|
+
}
|
|
314
|
+
function names(binary, platform) {
|
|
315
|
+
return platform === "win32" ? [`${binary}.exe`] : [binary];
|
|
316
|
+
}
|
|
317
|
+
function findIn(dirs, binary, platform) {
|
|
318
|
+
for (const dir of dirs) for (const name of names(binary, platform)) {
|
|
319
|
+
const path = join(dir, name);
|
|
320
|
+
if (isExecutable(path, platform)) return path;
|
|
321
|
+
}
|
|
322
|
+
return null;
|
|
323
|
+
}
|
|
324
|
+
async function viaLoginShell(binary, deps) {
|
|
325
|
+
const shell = deps.env.SHELL;
|
|
326
|
+
if (!deps.loginShell || deps.platform === "win32" || !shell?.startsWith("/")) return null;
|
|
327
|
+
for (const flags of [["-lc"], ["-ilc"]]) {
|
|
328
|
+
const path = (await runCollect({
|
|
329
|
+
command: shell,
|
|
330
|
+
args: [...flags, `printf '__SMRT_BIN__%s\\n' "$(command -v ${binary})"`],
|
|
331
|
+
env: childEnv(deps.env),
|
|
332
|
+
timeoutMs: 5e3
|
|
333
|
+
})).stdout.split("\n").reverse().find((l) => l.startsWith("__SMRT_BIN__"))?.slice(12).trim();
|
|
334
|
+
if (path?.startsWith("/") && isExecutable(path, deps.platform)) return path;
|
|
335
|
+
}
|
|
336
|
+
return null;
|
|
337
|
+
}
|
|
338
|
+
async function locateBinary(tool, deps = defaultLocateDeps()) {
|
|
339
|
+
const { binary } = AGENT_TOOL_INFO[tool];
|
|
340
|
+
return findIn((deps.env.PATH ?? deps.env.Path ?? deps.env.path ?? "").split(delimiter).filter(Boolean), binary, deps.platform) ?? findIn(candidateDirs(deps), binary, deps.platform) ?? await viaLoginShell(binary, deps);
|
|
341
|
+
}
|
|
342
|
+
//#endregion
|
|
343
|
+
//#region src/agent-cli/stream.ts
|
|
344
|
+
var MCP_SERVER_NAME = "smrt";
|
|
345
|
+
var CLAUDE_PREFIX = `mcp__${MCP_SERVER_NAME}__`;
|
|
346
|
+
function obj(value) {
|
|
347
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
348
|
+
}
|
|
349
|
+
var str = (v) => typeof v === "string" ? v : "";
|
|
350
|
+
function parse(line) {
|
|
351
|
+
const trimmed = line.trim();
|
|
352
|
+
if (!trimmed.startsWith("{")) return null;
|
|
353
|
+
try {
|
|
354
|
+
return obj(JSON.parse(trimmed));
|
|
355
|
+
} catch {
|
|
356
|
+
return null;
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
function textOfContent(content) {
|
|
360
|
+
if (typeof content === "string") return content;
|
|
361
|
+
if (Array.isArray(content)) return content.map((part) => str(obj(part)?.text) || "").filter(Boolean).join("\n");
|
|
362
|
+
return "";
|
|
363
|
+
}
|
|
364
|
+
function shellToolName(name) {
|
|
365
|
+
return name.startsWith(CLAUDE_PREFIX) ? name.slice(CLAUDE_PREFIX.length) : name;
|
|
366
|
+
}
|
|
367
|
+
function claudeParser(outputSchema, protection = true) {
|
|
368
|
+
let streamed = false;
|
|
369
|
+
const resultIds = /* @__PURE__ */ new Set();
|
|
370
|
+
return (line) => {
|
|
371
|
+
const e = parse(line);
|
|
372
|
+
if (!e) return [];
|
|
373
|
+
const out = [];
|
|
374
|
+
const type = str(e.type);
|
|
375
|
+
const reportedModel = type === "system" && str(e.subtype) === "init" ? e.model : type === "assistant" ? obj(e.message)?.model : void 0;
|
|
376
|
+
if (typeof reportedModel === "string" && /^[a-zA-Z0-9][a-zA-Z0-9._:/-]{0,199}$/.test(reportedModel)) out.push({
|
|
377
|
+
type: "execution_model",
|
|
378
|
+
model: reportedModel
|
|
379
|
+
});
|
|
380
|
+
if (type === "system" && str(e.subtype) === "init" && str(e.session_id)) out.push({
|
|
381
|
+
type: "session",
|
|
382
|
+
id: str(e.session_id)
|
|
383
|
+
});
|
|
384
|
+
else if (type === "stream_event") {
|
|
385
|
+
const event = obj(e.event);
|
|
386
|
+
if (str(event?.type) === "message_start") streamed = false;
|
|
387
|
+
const delta = obj(event?.delta);
|
|
388
|
+
if (str(event?.type) === "content_block_delta" && str(delta?.type) === "text_delta" && str(delta?.text) && !outputSchema) {
|
|
389
|
+
if (!e.parent_tool_use_id) {
|
|
390
|
+
streamed = true;
|
|
391
|
+
out.push({
|
|
392
|
+
type: "text",
|
|
393
|
+
delta: str(delta?.text)
|
|
394
|
+
});
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
} else if (type === "assistant") {
|
|
398
|
+
const content = obj(e.message)?.content;
|
|
399
|
+
for (const block of Array.isArray(content) ? content : []) {
|
|
400
|
+
const b = obj(block);
|
|
401
|
+
if (!b) continue;
|
|
402
|
+
if (str(b.type) === "text" && !streamed && str(b.text) && !outputSchema) out.push({
|
|
403
|
+
type: "message",
|
|
404
|
+
text: str(b.text)
|
|
405
|
+
});
|
|
406
|
+
else if (str(b.type) === "tool_use") {
|
|
407
|
+
const name = str(b.name);
|
|
408
|
+
if (name === "StructuredOutput" && outputSchema) {
|
|
409
|
+
resultIds.add(str(b.id));
|
|
410
|
+
out.push({
|
|
411
|
+
type: "result_channel",
|
|
412
|
+
name: "StructuredOutput"
|
|
413
|
+
});
|
|
414
|
+
continue;
|
|
415
|
+
}
|
|
416
|
+
if (!name.startsWith(CLAUDE_PREFIX) && !protection) {
|
|
417
|
+
resultIds.add(str(b.id));
|
|
418
|
+
out.push({
|
|
419
|
+
type: "forbidden",
|
|
420
|
+
what: name,
|
|
421
|
+
kind: "native_builtin"
|
|
422
|
+
});
|
|
423
|
+
} else if (!name.startsWith(CLAUDE_PREFIX)) out.push({
|
|
424
|
+
type: "forbidden",
|
|
425
|
+
what: name || "a tool",
|
|
426
|
+
...name.startsWith("mcp__") ? { kind: "unoffered_mcp" } : {}
|
|
427
|
+
});
|
|
428
|
+
else out.push({
|
|
429
|
+
type: "tool_use",
|
|
430
|
+
id: str(b.id),
|
|
431
|
+
name: shellToolName(name),
|
|
432
|
+
args: JSON.stringify(b.input ?? {})
|
|
433
|
+
});
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
streamed = false;
|
|
437
|
+
} else if (type === "user") {
|
|
438
|
+
const content = obj(e.message)?.content;
|
|
439
|
+
for (const block of Array.isArray(content) ? content : []) {
|
|
440
|
+
const b = obj(block);
|
|
441
|
+
if (b && str(b.type) === "tool_result" && !resultIds.has(str(b.tool_use_id))) out.push({
|
|
442
|
+
type: "tool_result",
|
|
443
|
+
id: str(b.tool_use_id),
|
|
444
|
+
ok: b.is_error !== true,
|
|
445
|
+
text: textOfContent(b.content)
|
|
446
|
+
});
|
|
447
|
+
}
|
|
448
|
+
} else if (type === "result") {
|
|
449
|
+
const ok = e.is_error !== true && str(e.subtype) === "success";
|
|
450
|
+
out.push({
|
|
451
|
+
type: "done",
|
|
452
|
+
ok,
|
|
453
|
+
...outputSchema && e.structured_output && typeof e.structured_output === "object" ? { text: JSON.stringify(e.structured_output) } : str(e.result) ? { text: str(e.result) } : {},
|
|
454
|
+
...usageTokens(e.usage),
|
|
455
|
+
...!ok ? { error: ["model_not_available", "model_access_denied"].includes(str(e.error_code)) ? "plan_model_refused" : str(e.subtype) || "error" } : {}
|
|
456
|
+
});
|
|
457
|
+
}
|
|
458
|
+
return out;
|
|
459
|
+
};
|
|
460
|
+
}
|
|
461
|
+
var CODEX_ALLOWED_ITEMS = /* @__PURE__ */ new Set([
|
|
462
|
+
"agent_message",
|
|
463
|
+
"reasoning",
|
|
464
|
+
"mcp_tool_call",
|
|
465
|
+
"todo_list",
|
|
466
|
+
"error",
|
|
467
|
+
"user_message"
|
|
468
|
+
]);
|
|
469
|
+
function codexParser(options = {}) {
|
|
470
|
+
return (line) => {
|
|
471
|
+
const e = parse(line);
|
|
472
|
+
if (!e) return [];
|
|
473
|
+
const type = str(e.type);
|
|
474
|
+
if (type === "thread.started" && str(e.thread_id)) return [{
|
|
475
|
+
type: "session",
|
|
476
|
+
id: str(e.thread_id)
|
|
477
|
+
}];
|
|
478
|
+
if (type === "turn.completed") return [{
|
|
479
|
+
type: "done",
|
|
480
|
+
ok: true,
|
|
481
|
+
...usageTokens(e.usage)
|
|
482
|
+
}];
|
|
483
|
+
if (type === "turn.failed" || type === "error") {
|
|
484
|
+
const failure = obj(e.error);
|
|
485
|
+
return [{
|
|
486
|
+
type: "done",
|
|
487
|
+
ok: false,
|
|
488
|
+
error: ["model_not_available", "model_access_denied"].includes(str(failure?.code)) ? "plan_model_refused" : str(failure?.message) || str(e.message) || "error"
|
|
489
|
+
}];
|
|
490
|
+
}
|
|
491
|
+
const item = obj(e.item);
|
|
492
|
+
if (!item || !(type === "item.started" || type === "item.completed")) return [];
|
|
493
|
+
const kind = str(item.type);
|
|
494
|
+
if (kind === "error" && str(item.message).includes("code-mode host is disabled")) return [{
|
|
495
|
+
type: "done",
|
|
496
|
+
ok: false,
|
|
497
|
+
error: "tool_host_policy"
|
|
498
|
+
}];
|
|
499
|
+
if (options.confinedBuiltins && ["file_change", "command_execution"].includes(kind)) return type === "item.completed" ? [{
|
|
500
|
+
type: "forbidden",
|
|
501
|
+
what: kind === "file_change" ? "apply_patch" : "exec_command",
|
|
502
|
+
kind: "confined_builtin"
|
|
503
|
+
}] : [];
|
|
504
|
+
if (options.nativeTools && !CODEX_ALLOWED_ITEMS.has(kind)) return type === "item.completed" ? [{
|
|
505
|
+
type: "forbidden",
|
|
506
|
+
what: kind === "command_execution" ? "exec_command" : kind === "file_change" ? "apply_patch" : kind,
|
|
507
|
+
kind: "native_builtin"
|
|
508
|
+
}] : [];
|
|
509
|
+
if (!CODEX_ALLOWED_ITEMS.has(kind)) return [{
|
|
510
|
+
type: "forbidden",
|
|
511
|
+
what: kind || "an item",
|
|
512
|
+
kind: "unknown_item"
|
|
513
|
+
}];
|
|
514
|
+
if (kind === "agent_message" && type === "item.completed" && str(item.text)) return [{
|
|
515
|
+
type: "message",
|
|
516
|
+
text: str(item.text)
|
|
517
|
+
}];
|
|
518
|
+
if (kind === "mcp_tool_call") {
|
|
519
|
+
if (str(item.server) !== "smrt" && options.nativeTools) return type === "item.completed" ? [{
|
|
520
|
+
type: "forbidden",
|
|
521
|
+
what: `mcp__${str(item.server)}__${str(item.tool)}`,
|
|
522
|
+
kind: "native_builtin"
|
|
523
|
+
}] : [];
|
|
524
|
+
if (str(item.server) !== "smrt") return [{
|
|
525
|
+
type: "forbidden",
|
|
526
|
+
what: str(item.tool),
|
|
527
|
+
kind: "unoffered_mcp"
|
|
528
|
+
}];
|
|
529
|
+
const id = str(item.id);
|
|
530
|
+
if (type === "item.started") return [{
|
|
531
|
+
type: "tool_use",
|
|
532
|
+
id,
|
|
533
|
+
name: shellToolName(str(item.tool)),
|
|
534
|
+
args: JSON.stringify(item.arguments ?? {})
|
|
535
|
+
}];
|
|
536
|
+
const result = obj(item.result);
|
|
537
|
+
return [{
|
|
538
|
+
type: "tool_result",
|
|
539
|
+
id,
|
|
540
|
+
ok: !(str(item.status) === "failed" || item.error != null) && result?.is_error !== true,
|
|
541
|
+
text: textOfContent(result?.content) || str(obj(item.error)?.message) || (result?.structured_content ? JSON.stringify(result.structured_content) : "")
|
|
542
|
+
}];
|
|
543
|
+
}
|
|
544
|
+
return [];
|
|
545
|
+
};
|
|
546
|
+
}
|
|
547
|
+
function usageTokens(value) {
|
|
548
|
+
const usage = obj(value);
|
|
549
|
+
if (usage?.input_tokens === void 0 || usage.output_tokens === void 0) return {};
|
|
550
|
+
const counts = [
|
|
551
|
+
usage.input_tokens,
|
|
552
|
+
usage.output_tokens,
|
|
553
|
+
usage.cache_read_input_tokens ?? 0,
|
|
554
|
+
usage.cache_creation_input_tokens ?? 0
|
|
555
|
+
];
|
|
556
|
+
if (!counts.every((count) => typeof count === "number" && Number.isSafeInteger(count) && count >= 0)) return {};
|
|
557
|
+
const total = counts.reduce((sum, count) => sum + count, 0);
|
|
558
|
+
return Number.isSafeInteger(total) ? { tokens: total } : {};
|
|
559
|
+
}
|
|
560
|
+
//#endregion
|
|
561
|
+
//#region src/agent-cli/session.ts
|
|
562
|
+
var TOKEN_ENV = "SMRT_SHELL_MCP_TOKEN";
|
|
563
|
+
function assertLoopbackUrl(value) {
|
|
564
|
+
const url = new URL(value);
|
|
565
|
+
const host = url.hostname.replace(/^\[|\]$/g, "");
|
|
566
|
+
const loopback = host === "127.0.0.1" || host === "localhost" || host === "::1";
|
|
567
|
+
if (url.protocol !== "http:" || !loopback) throw new Error("The shell is not served from this computer.");
|
|
568
|
+
return url;
|
|
569
|
+
}
|
|
570
|
+
var toml = (value) => JSON.stringify(value);
|
|
571
|
+
function claudeSpec(input, runDir, work) {
|
|
572
|
+
const sessionId = input.resumeId ?? randomUUID();
|
|
573
|
+
const configPath = join(runDir, "mcp.json");
|
|
574
|
+
writeFileSync(configPath, JSON.stringify({ mcpServers: { [MCP_SERVER_NAME]: {
|
|
575
|
+
type: "http",
|
|
576
|
+
url: input.mcpUrl,
|
|
577
|
+
headers: { Authorization: `Bearer \${${TOKEN_ENV}}` }
|
|
578
|
+
} } }), { mode: 384 });
|
|
579
|
+
return {
|
|
580
|
+
command: input.location.path,
|
|
581
|
+
args: [
|
|
582
|
+
"-p",
|
|
583
|
+
"--output-format",
|
|
584
|
+
"stream-json",
|
|
585
|
+
"--verbose",
|
|
586
|
+
"--include-partial-messages",
|
|
587
|
+
"--model",
|
|
588
|
+
input.profile?.model ?? "fable",
|
|
589
|
+
"--effort",
|
|
590
|
+
input.profile?.effort ?? "high",
|
|
591
|
+
...input.outputSchema ? ["--json-schema", JSON.stringify(input.outputSchema)] : [],
|
|
592
|
+
...input.protection === false ? [] : [
|
|
593
|
+
"--tools",
|
|
594
|
+
"",
|
|
595
|
+
"--strict-mcp-config",
|
|
596
|
+
"--allowedTools",
|
|
597
|
+
`mcp__${MCP_SERVER_NAME}`
|
|
598
|
+
],
|
|
599
|
+
"--mcp-config",
|
|
600
|
+
configPath,
|
|
601
|
+
"--permission-mode",
|
|
602
|
+
input.protection === false ? "bypassPermissions" : "dontAsk",
|
|
603
|
+
"--permission-prompts",
|
|
604
|
+
"none",
|
|
605
|
+
...input.protection === false ? [] : [
|
|
606
|
+
"--setting-sources",
|
|
607
|
+
"",
|
|
608
|
+
"--disable-slash-commands",
|
|
609
|
+
"--no-chrome"
|
|
610
|
+
],
|
|
611
|
+
"--append-system-prompt",
|
|
612
|
+
input.systemPrompt,
|
|
613
|
+
...input.resumeId ? ["--resume", input.resumeId] : ["--session-id", sessionId]
|
|
614
|
+
],
|
|
615
|
+
cwd: work,
|
|
616
|
+
env: cliEnv(input.location, input.baseEnv, { [TOKEN_ENV]: input.token }),
|
|
617
|
+
stdin: input.prompt,
|
|
618
|
+
parse: claudeParser(input.outputSchema, input.protection !== false),
|
|
619
|
+
sessionId,
|
|
620
|
+
cleanup: () => rmSync(runDir, {
|
|
621
|
+
recursive: true,
|
|
622
|
+
force: true
|
|
623
|
+
})
|
|
624
|
+
};
|
|
625
|
+
}
|
|
626
|
+
var CODEX_DISABLED_FEATURES = [
|
|
627
|
+
"shell_tool",
|
|
628
|
+
"unified_exec",
|
|
629
|
+
"apps",
|
|
630
|
+
"plugins",
|
|
631
|
+
"hooks",
|
|
632
|
+
"multi_agent",
|
|
633
|
+
"multi_agent_v2",
|
|
634
|
+
"view_image",
|
|
635
|
+
"image_generation",
|
|
636
|
+
"browser_use",
|
|
637
|
+
"computer_use",
|
|
638
|
+
"in_app_browser",
|
|
639
|
+
"memories",
|
|
640
|
+
"skill_search",
|
|
641
|
+
"tool_suggest",
|
|
642
|
+
"goals",
|
|
643
|
+
"code_mode",
|
|
644
|
+
"request_permissions_tool"
|
|
645
|
+
];
|
|
646
|
+
var CODEX_MODERN_MCP_FEATURE = "mcp_2026_07_28";
|
|
647
|
+
function codexSpec(input, runDir, work) {
|
|
648
|
+
const server = `mcp_servers.${MCP_SERVER_NAME}`;
|
|
649
|
+
const schemaPath = join(runDir, "output-schema.json");
|
|
650
|
+
if (input.outputSchema) writeFileSync(schemaPath, JSON.stringify(input.outputSchema), { mode: 384 });
|
|
651
|
+
const overrides = [
|
|
652
|
+
["model_reasoning_effort", toml(input.profile?.effort === "max" ? "xhigh" : input.profile?.effort ?? "high")],
|
|
653
|
+
["sandbox_mode", toml(input.protection === false ? "danger-full-access" : "workspace-write")],
|
|
654
|
+
...input.protection === false ? [] : [
|
|
655
|
+
["sandbox_workspace_write.network_access", "false"],
|
|
656
|
+
["sandbox_workspace_write.writable_roots", "[]"],
|
|
657
|
+
["sandbox_workspace_write.exclude_slash_tmp", "true"],
|
|
658
|
+
["sandbox_workspace_write.exclude_tmpdir_env_var", "true"],
|
|
659
|
+
["project_doc_max_bytes", "0"],
|
|
660
|
+
["skills.bundled.enabled", "false"]
|
|
661
|
+
],
|
|
662
|
+
["shell_environment_policy.inherit", toml("none")],
|
|
663
|
+
["approval_policy", toml("never")],
|
|
664
|
+
["web_search", toml(input.protection === false ? "live" : "disabled")],
|
|
665
|
+
[`${server}.url`, toml(input.mcpUrl)],
|
|
666
|
+
[`${server}.bearer_token_env_var`, toml(TOKEN_ENV)],
|
|
667
|
+
[`${server}.required`, "true"],
|
|
668
|
+
[`${server}.default_tools_approval_mode`, toml("approve")],
|
|
669
|
+
[`${server}.startup_timeout_sec`, "30"],
|
|
670
|
+
[`${server}.tool_timeout_sec`, "300"],
|
|
671
|
+
["developer_instructions", toml(input.systemPrompt)]
|
|
672
|
+
];
|
|
673
|
+
return {
|
|
674
|
+
command: input.location.path,
|
|
675
|
+
args: [
|
|
676
|
+
"exec",
|
|
677
|
+
...input.resumeId ? ["resume"] : [],
|
|
678
|
+
"--json",
|
|
679
|
+
"--skip-git-repo-check",
|
|
680
|
+
...input.profile?.model ? ["-m", input.profile.model] : [],
|
|
681
|
+
...input.outputSchema ? ["--output-schema", schemaPath] : [],
|
|
682
|
+
...input.protection === false ? [] : [
|
|
683
|
+
"--ignore-user-config",
|
|
684
|
+
"--ignore-rules",
|
|
685
|
+
...CODEX_DISABLED_FEATURES.flatMap((f) => ["--disable", f])
|
|
686
|
+
],
|
|
687
|
+
"--enable",
|
|
688
|
+
CODEX_MODERN_MCP_FEATURE,
|
|
689
|
+
"--enable",
|
|
690
|
+
"code_mode_host",
|
|
691
|
+
...overrides.flatMap(([k, v]) => ["-c", `${k}=${v}`]),
|
|
692
|
+
...input.resumeId ? [input.resumeId] : [],
|
|
693
|
+
"-"
|
|
694
|
+
],
|
|
695
|
+
cwd: work,
|
|
696
|
+
env: cliEnv(input.location, input.baseEnv, { [TOKEN_ENV]: input.token }),
|
|
697
|
+
stdin: input.prompt,
|
|
698
|
+
parse: codexParser({
|
|
699
|
+
confinedBuiltins: input.protection !== false,
|
|
700
|
+
nativeTools: input.protection === false
|
|
701
|
+
}),
|
|
702
|
+
sessionId: input.resumeId ?? null,
|
|
703
|
+
cleanup: () => rmSync(runDir, {
|
|
704
|
+
recursive: true,
|
|
705
|
+
force: true
|
|
706
|
+
})
|
|
707
|
+
};
|
|
708
|
+
}
|
|
709
|
+
function buildAgentRun(input) {
|
|
710
|
+
assertLoopbackUrl(input.mcpUrl);
|
|
711
|
+
if (input.profile?.model !== void 0) validateWorkModel(input.profile.model);
|
|
712
|
+
const runRoot = join(input.stateDir, "run");
|
|
713
|
+
mkdirSync(runRoot, {
|
|
714
|
+
recursive: true,
|
|
715
|
+
mode: 448
|
|
716
|
+
});
|
|
717
|
+
const runDir = mkdtempSync(join(runRoot, "turn-"));
|
|
718
|
+
try {
|
|
719
|
+
const work = input.tool === "codex" && input.protection !== false ? join(runDir, "work") : join(input.stateDir, "work");
|
|
720
|
+
mkdirSync(work, {
|
|
721
|
+
recursive: true,
|
|
722
|
+
mode: 448
|
|
723
|
+
});
|
|
724
|
+
return input.tool === "claude-code" ? claudeSpec(input, runDir, work) : codexSpec(input, runDir, work);
|
|
725
|
+
} catch (error) {
|
|
726
|
+
rmSync(runDir, {
|
|
727
|
+
recursive: true,
|
|
728
|
+
force: true
|
|
729
|
+
});
|
|
730
|
+
throw error;
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
//#endregion
|
|
7
734
|
//#region src/settings/keys.ts
|
|
8
735
|
var InferenceKeyOriginError = class extends Error {
|
|
9
736
|
status = 400;
|
|
@@ -116,6 +843,1379 @@ function redactInferenceSecret(text2, secret) {
|
|
|
116
843
|
return out.replace(/\b(sk|rk|pk)-[A-Za-z0-9_-]{8,}/g, REDACTED_KEY).replace(/\b(Bearer)\s+[A-Za-z0-9._~+/=-]{8,}/gi, `$1 ${REDACTED_KEY}`);
|
|
117
844
|
}
|
|
118
845
|
//#endregion
|
|
846
|
+
//#region src/agent-cli/turn.ts
|
|
847
|
+
var DEFAULT_AGENT_LIMITS = {
|
|
848
|
+
turnTimeoutMs: 10 * 6e4,
|
|
849
|
+
toolResultChars: 12e3
|
|
850
|
+
};
|
|
851
|
+
function cut(text, max) {
|
|
852
|
+
return text.length > max ? `${text.slice(0, max)} [cut]` : text;
|
|
853
|
+
}
|
|
854
|
+
function tokenFailureCode(error) {
|
|
855
|
+
const code = error?.code;
|
|
856
|
+
return typeof code === "string" && /^[a-z_]{1,48}$/.test(code) ? code : void 0;
|
|
857
|
+
}
|
|
858
|
+
function tokenFailureMessage(code) {
|
|
859
|
+
if (code === "invalid_scope") return "The assistant could not start: the owner is missing the assistant permission. Restart the app so it can grant it, then try again.";
|
|
860
|
+
if (code === "owner_unavailable") return "The assistant could not start: finish owner setup first.";
|
|
861
|
+
return "The assistant could not start. Try again.";
|
|
862
|
+
}
|
|
863
|
+
var reportedFailures = /* @__PURE__ */ new WeakMap();
|
|
864
|
+
function blockedToolName(name) {
|
|
865
|
+
return /^[a-zA-Z0-9][a-zA-Z0-9_.:-]{0,127}$/.test(name) ? name : "unknown";
|
|
866
|
+
}
|
|
867
|
+
var diagnosticCodes = /* @__PURE__ */ new Set([
|
|
868
|
+
"agent_cli_missing",
|
|
869
|
+
"agent_cli_signed_out",
|
|
870
|
+
"agent_cli_startup",
|
|
871
|
+
"agent_cli_token",
|
|
872
|
+
"agent_cli_failed",
|
|
873
|
+
"agent_mcp_unavailable",
|
|
874
|
+
"agent_tool_blocked",
|
|
875
|
+
"agent_tool_confined",
|
|
876
|
+
"agent_tool_native",
|
|
877
|
+
"timeout",
|
|
878
|
+
"invalid_scope",
|
|
879
|
+
"owner_unavailable",
|
|
880
|
+
"runtime_unavailable",
|
|
881
|
+
"cli_invocation",
|
|
882
|
+
"working_directory",
|
|
883
|
+
"tool_host_policy",
|
|
884
|
+
"INVALID_RESPONSE",
|
|
885
|
+
"AUTH_ERROR",
|
|
886
|
+
"RATE_LIMIT",
|
|
887
|
+
"NETWORK_ERROR",
|
|
888
|
+
"TIMEOUT",
|
|
889
|
+
"chatgpt_signed_out",
|
|
890
|
+
"chatgpt_unavailable",
|
|
891
|
+
"chatgpt_usage_limit",
|
|
892
|
+
"chatgpt_session_revoked",
|
|
893
|
+
"chatgpt_workspace",
|
|
894
|
+
"chatgpt_unsupported"
|
|
895
|
+
]);
|
|
896
|
+
function reportAgentFailure(tool, phase, error, code, blocked) {
|
|
897
|
+
if (error && typeof error === "object") {
|
|
898
|
+
const existing = reportedFailures.get(error);
|
|
899
|
+
if (existing) return existing;
|
|
900
|
+
}
|
|
901
|
+
const reference = randomUUID();
|
|
902
|
+
const cause = error instanceof TypeError ? "TypeError" : error instanceof RangeError ? "RangeError" : error instanceof Error ? "Error" : "unavailable";
|
|
903
|
+
const sites = error instanceof Error ? (error.stack ?? "").slice(0, 4096).split("\n").slice(1).flatMap((line) => {
|
|
904
|
+
const match = line.match(/(?:\(|\s)([^()\s]+\.[cm]?[jt]s):(\d+):(\d+)\)?$/);
|
|
905
|
+
if (!match) return [];
|
|
906
|
+
return [`${/\/packages\/(core|chat|inference|app-runtime|users)\//.exec(match[1])?.[1] ?? "host"}:${match[2]}:${match[3]}`];
|
|
907
|
+
}).slice(0, 6) : [];
|
|
908
|
+
let requestId;
|
|
909
|
+
let providerCode;
|
|
910
|
+
let causeValue = error;
|
|
911
|
+
try {
|
|
912
|
+
for (let depth = 0; depth < 4 && causeValue && typeof causeValue === "object"; depth++) {
|
|
913
|
+
const descriptors = Object.getOwnPropertyDescriptors(causeValue);
|
|
914
|
+
const candidate = descriptors.requestId?.value;
|
|
915
|
+
if (typeof candidate === "string" && /^(?:req_[a-zA-Z0-9_-]{1,100}|[a-fA-F0-9]{8}(?:-[a-fA-F0-9]{4}){3}-[a-fA-F0-9]{12})$/.test(candidate)) requestId = candidate;
|
|
916
|
+
const candidateCode = descriptors.code?.value;
|
|
917
|
+
if (typeof candidateCode === "string" && diagnosticCodes.has(candidateCode)) providerCode = candidateCode;
|
|
918
|
+
causeValue = descriptors.cause?.value;
|
|
919
|
+
}
|
|
920
|
+
} catch {}
|
|
921
|
+
try {
|
|
922
|
+
console.error("[smrt-inference] local engine failure", {
|
|
923
|
+
reference,
|
|
924
|
+
tool,
|
|
925
|
+
phase,
|
|
926
|
+
cause,
|
|
927
|
+
code: providerCode ?? (code && diagnosticCodes.has(code) ? code : "unexpected_failure"),
|
|
928
|
+
...requestId ? { requestId } : {},
|
|
929
|
+
sites,
|
|
930
|
+
...blocked ? {
|
|
931
|
+
blockedTool: blockedToolName(blocked.name),
|
|
932
|
+
blockedKind: blocked.kind
|
|
933
|
+
} : {}
|
|
934
|
+
});
|
|
935
|
+
} catch {}
|
|
936
|
+
if (error && typeof error === "object") reportedFailures.set(error, reference);
|
|
937
|
+
return reference;
|
|
938
|
+
}
|
|
939
|
+
async function runAgentTurn(options) {
|
|
940
|
+
try {
|
|
941
|
+
return await runAgentTurnImpl(options);
|
|
942
|
+
} catch (error) {
|
|
943
|
+
reportAgentFailure(options.tool, "process", error);
|
|
944
|
+
throw error;
|
|
945
|
+
}
|
|
946
|
+
}
|
|
947
|
+
async function runAgentTurnImpl(options) {
|
|
948
|
+
const { host, tool, deps } = options;
|
|
949
|
+
if (options.profile && (options.profile.engine !== tool || !options.profile.model)) throw new Error("The work profile does not match this connected engine.");
|
|
950
|
+
if (options.profile?.model !== void 0) validateWorkModel(options.profile.model);
|
|
951
|
+
if (options.fallback?.nextModel !== void 0) validateWorkModel(options.fallback.nextModel);
|
|
952
|
+
const emit = (event) => {
|
|
953
|
+
if (event.type === "error" && !event.message.includes(" Reference: ")) {
|
|
954
|
+
const reference = reportAgentFailure(tool, "process", void 0, event.code);
|
|
955
|
+
options.emit({
|
|
956
|
+
...event,
|
|
957
|
+
message: `${event.message} Reference: ${reference}`
|
|
958
|
+
});
|
|
959
|
+
} else options.emit(event);
|
|
960
|
+
};
|
|
961
|
+
const startedAt = Date.now();
|
|
962
|
+
let toolCalls = 0;
|
|
963
|
+
let reportedModel;
|
|
964
|
+
let reportedTokens;
|
|
965
|
+
const limits = {
|
|
966
|
+
...DEFAULT_AGENT_LIMITS,
|
|
967
|
+
...options.profile ? {
|
|
968
|
+
turnTimeoutMs: options.profile.budgets.requestTimeoutMs,
|
|
969
|
+
toolResultChars: options.profile.budgets.toolResultChars
|
|
970
|
+
} : {},
|
|
971
|
+
...deps.limits
|
|
972
|
+
};
|
|
973
|
+
const label = AGENT_TOOL_INFO[tool].label;
|
|
974
|
+
const fail = (code, message, stop = "error", cause) => {
|
|
975
|
+
const causeCode = tokenFailureCode(cause);
|
|
976
|
+
const reference = reportAgentFailure(tool, code === "agent_cli_token" ? "credential" : "process", cause, causeCode ?? code);
|
|
977
|
+
if (code === "agent_cli_token" && cause instanceof Error && cause.name === "LocalRuntimeError" && causeCode && diagnosticCodes.has(causeCode)) console.error("assistant token failed:", "LocalRuntimeError", causeCode);
|
|
978
|
+
emit({
|
|
979
|
+
type: "error",
|
|
980
|
+
code,
|
|
981
|
+
message: `${message} Reference: ${reference}`
|
|
982
|
+
});
|
|
983
|
+
emit({
|
|
984
|
+
type: "done",
|
|
985
|
+
stop
|
|
986
|
+
});
|
|
987
|
+
return stop;
|
|
988
|
+
};
|
|
989
|
+
await host.appendMessage({
|
|
990
|
+
role: "user",
|
|
991
|
+
content: options.text
|
|
992
|
+
});
|
|
993
|
+
const location = await deps.locate(tool);
|
|
994
|
+
if (!location) return fail("agent_cli_missing", `${label} is not installed on this computer.`);
|
|
995
|
+
let resumeId = await host.lastSession();
|
|
996
|
+
let token;
|
|
997
|
+
try {
|
|
998
|
+
token = await deps.credentials.mint({ timeoutMs: limits.turnTimeoutMs });
|
|
999
|
+
} catch (error) {
|
|
1000
|
+
return fail("agent_cli_token", tokenFailureMessage(tokenFailureCode(error)), "error", error);
|
|
1001
|
+
}
|
|
1002
|
+
let unsubscribe;
|
|
1003
|
+
const controller = new AbortController();
|
|
1004
|
+
const onAbort = () => controller.abort();
|
|
1005
|
+
try {
|
|
1006
|
+
const raised = [];
|
|
1007
|
+
const toolIdOf = /* @__PURE__ */ new Map();
|
|
1008
|
+
unsubscribe = host.approvals.subscribe((e) => {
|
|
1009
|
+
if (e.status === "pending") {
|
|
1010
|
+
raised.push({
|
|
1011
|
+
approvalId: e.id,
|
|
1012
|
+
attached: false
|
|
1013
|
+
});
|
|
1014
|
+
return;
|
|
1015
|
+
}
|
|
1016
|
+
const known = raised.find((r) => r.approvalId === e.id);
|
|
1017
|
+
const toolId = known ? toolIdOf.get(e.id) : void 0;
|
|
1018
|
+
if (known && toolId) emit({
|
|
1019
|
+
type: "approval_decided",
|
|
1020
|
+
id: toolId,
|
|
1021
|
+
approvalId: e.id,
|
|
1022
|
+
status: e.status
|
|
1023
|
+
});
|
|
1024
|
+
});
|
|
1025
|
+
let pendingText = "";
|
|
1026
|
+
let streamedAny = false;
|
|
1027
|
+
let sawTool = false;
|
|
1028
|
+
let stop = "complete";
|
|
1029
|
+
let sessionId = null;
|
|
1030
|
+
let finished = null;
|
|
1031
|
+
const names = /* @__PURE__ */ new Map();
|
|
1032
|
+
let queue = Promise.resolve();
|
|
1033
|
+
let hostFailure;
|
|
1034
|
+
options.signal.addEventListener("abort", onAbort, { once: true });
|
|
1035
|
+
if (options.signal.aborted) controller.abort();
|
|
1036
|
+
const blockTool = (name, kind) => {
|
|
1037
|
+
stop = "error";
|
|
1038
|
+
controller.abort();
|
|
1039
|
+
const safeName = blockedToolName(name);
|
|
1040
|
+
const reference = reportAgentFailure(tool, "guard", void 0, "agent_tool_blocked", {
|
|
1041
|
+
name: safeName,
|
|
1042
|
+
kind
|
|
1043
|
+
});
|
|
1044
|
+
emit({
|
|
1045
|
+
type: "error",
|
|
1046
|
+
code: "agent_tool_blocked",
|
|
1047
|
+
message: `${label} tried to use a blocked tool (${kind}: ${safeName}). I stopped it. Reference: ${reference}`
|
|
1048
|
+
});
|
|
1049
|
+
};
|
|
1050
|
+
const handle = async (event) => {
|
|
1051
|
+
if (stop === "error" && controller.signal.aborted) return;
|
|
1052
|
+
switch (event.type) {
|
|
1053
|
+
case "session":
|
|
1054
|
+
sessionId = event.id;
|
|
1055
|
+
return;
|
|
1056
|
+
case "result_channel":
|
|
1057
|
+
try {
|
|
1058
|
+
console.info("[smrt-inference] local engine result channel", {
|
|
1059
|
+
reference: randomUUID(),
|
|
1060
|
+
tool,
|
|
1061
|
+
name: "StructuredOutput"
|
|
1062
|
+
});
|
|
1063
|
+
} catch {}
|
|
1064
|
+
return;
|
|
1065
|
+
case "text":
|
|
1066
|
+
streamedAny = true;
|
|
1067
|
+
pendingText += event.delta;
|
|
1068
|
+
if (options.protection !== false) emit({
|
|
1069
|
+
type: "text",
|
|
1070
|
+
delta: event.delta
|
|
1071
|
+
});
|
|
1072
|
+
return;
|
|
1073
|
+
case "message": {
|
|
1074
|
+
const delta = `${pendingText ? "\n\n" : ""}${event.text}`;
|
|
1075
|
+
streamedAny = true;
|
|
1076
|
+
pendingText += delta;
|
|
1077
|
+
if (options.protection !== false) emit({
|
|
1078
|
+
type: "text",
|
|
1079
|
+
delta
|
|
1080
|
+
});
|
|
1081
|
+
return;
|
|
1082
|
+
}
|
|
1083
|
+
case "forbidden":
|
|
1084
|
+
if (options.protection === false && event.kind === "native_builtin") {
|
|
1085
|
+
toolCalls++;
|
|
1086
|
+
sawTool = true;
|
|
1087
|
+
reportAgentFailure(tool, "guard", void 0, "agent_tool_native", {
|
|
1088
|
+
name: event.what,
|
|
1089
|
+
kind: event.kind
|
|
1090
|
+
});
|
|
1091
|
+
return;
|
|
1092
|
+
}
|
|
1093
|
+
if (tool === "codex" && event.kind === "confined_builtin") {
|
|
1094
|
+
toolCalls++;
|
|
1095
|
+
reportAgentFailure(tool, "guard", void 0, "agent_tool_confined", {
|
|
1096
|
+
name: event.what,
|
|
1097
|
+
kind: event.kind
|
|
1098
|
+
});
|
|
1099
|
+
return;
|
|
1100
|
+
}
|
|
1101
|
+
blockTool(event.what, event.kind === "confined_builtin" || event.kind === "native_builtin" ? "builtin" : event.kind ?? "builtin");
|
|
1102
|
+
return;
|
|
1103
|
+
case "tool_use": {
|
|
1104
|
+
toolCalls++;
|
|
1105
|
+
if (!host.allowTool(event.name)) {
|
|
1106
|
+
blockTool(event.name, "unoffered_mcp");
|
|
1107
|
+
return;
|
|
1108
|
+
}
|
|
1109
|
+
sawTool = true;
|
|
1110
|
+
names.set(event.id, event.name);
|
|
1111
|
+
const call = {
|
|
1112
|
+
id: event.id,
|
|
1113
|
+
type: "function",
|
|
1114
|
+
function: {
|
|
1115
|
+
name: event.name,
|
|
1116
|
+
arguments: event.args
|
|
1117
|
+
}
|
|
1118
|
+
};
|
|
1119
|
+
if (options.protection === false) {
|
|
1120
|
+
pendingText = redactInferenceSecret(pendingText, token);
|
|
1121
|
+
if (pendingText) emit({
|
|
1122
|
+
type: "text",
|
|
1123
|
+
delta: pendingText
|
|
1124
|
+
});
|
|
1125
|
+
call.function.arguments = redactInferenceSecret(call.function.arguments, token);
|
|
1126
|
+
}
|
|
1127
|
+
await host.appendMessage({
|
|
1128
|
+
role: "assistant",
|
|
1129
|
+
content: pendingText,
|
|
1130
|
+
toolCalls: [call]
|
|
1131
|
+
});
|
|
1132
|
+
pendingText = "";
|
|
1133
|
+
emit({
|
|
1134
|
+
type: "tool_call",
|
|
1135
|
+
id: event.id,
|
|
1136
|
+
name: event.name,
|
|
1137
|
+
args: cut(redactInferenceSecret(event.args, token), 400)
|
|
1138
|
+
});
|
|
1139
|
+
return;
|
|
1140
|
+
}
|
|
1141
|
+
case "tool_result": {
|
|
1142
|
+
const name = names.get(event.id) ?? "";
|
|
1143
|
+
const text = cut(redactInferenceSecret(event.text, token), limits.toolResultChars);
|
|
1144
|
+
const fresh = raised.find((r) => !r.attached);
|
|
1145
|
+
let approvalId;
|
|
1146
|
+
if (fresh) {
|
|
1147
|
+
fresh.attached = true;
|
|
1148
|
+
toolIdOf.set(fresh.approvalId, event.id);
|
|
1149
|
+
const view = await host.approvals.get(fresh.approvalId);
|
|
1150
|
+
if (view && [
|
|
1151
|
+
"pending",
|
|
1152
|
+
"approved",
|
|
1153
|
+
"denied",
|
|
1154
|
+
"failed",
|
|
1155
|
+
"timeout"
|
|
1156
|
+
].includes(view.status)) {
|
|
1157
|
+
approvalId = fresh.approvalId;
|
|
1158
|
+
emit({
|
|
1159
|
+
type: "approval_required",
|
|
1160
|
+
id: event.id,
|
|
1161
|
+
name,
|
|
1162
|
+
approvalId: view.id,
|
|
1163
|
+
summary: view.summary,
|
|
1164
|
+
preview: view.preview
|
|
1165
|
+
});
|
|
1166
|
+
}
|
|
1167
|
+
}
|
|
1168
|
+
const { summary, details } = await host.describeResult({
|
|
1169
|
+
name,
|
|
1170
|
+
text: event.text,
|
|
1171
|
+
ok: event.ok,
|
|
1172
|
+
approvalId
|
|
1173
|
+
});
|
|
1174
|
+
emit({
|
|
1175
|
+
type: "tool_result",
|
|
1176
|
+
id: event.id,
|
|
1177
|
+
name,
|
|
1178
|
+
ok: event.ok,
|
|
1179
|
+
summary,
|
|
1180
|
+
...details ? { details } : {}
|
|
1181
|
+
});
|
|
1182
|
+
await host.appendMessage({
|
|
1183
|
+
role: "tool",
|
|
1184
|
+
content: text,
|
|
1185
|
+
toolCallId: event.id,
|
|
1186
|
+
meta: {
|
|
1187
|
+
id: event.id,
|
|
1188
|
+
name,
|
|
1189
|
+
ok: event.ok,
|
|
1190
|
+
summary,
|
|
1191
|
+
...details,
|
|
1192
|
+
...approvalId ? { approvalId } : {}
|
|
1193
|
+
}
|
|
1194
|
+
});
|
|
1195
|
+
return;
|
|
1196
|
+
}
|
|
1197
|
+
case "execution_model":
|
|
1198
|
+
reportedModel = event.model;
|
|
1199
|
+
return;
|
|
1200
|
+
case "done":
|
|
1201
|
+
if (event.tokens !== void 0) reportedTokens = (reportedTokens ?? 0) + event.tokens;
|
|
1202
|
+
finished = event;
|
|
1203
|
+
if (!event.ok && event.error === "tool_host_policy") {
|
|
1204
|
+
emit({
|
|
1205
|
+
type: "error",
|
|
1206
|
+
code: "tool_host_policy",
|
|
1207
|
+
message: `${label} cannot use the app's tools with the required security settings. Choose a compatible engine in AI settings.`
|
|
1208
|
+
});
|
|
1209
|
+
stop = "error";
|
|
1210
|
+
controller.abort();
|
|
1211
|
+
}
|
|
1212
|
+
return;
|
|
1213
|
+
}
|
|
1214
|
+
};
|
|
1215
|
+
const checkHostFailure = () => {
|
|
1216
|
+
if (hostFailure) throw hostFailure.error;
|
|
1217
|
+
};
|
|
1218
|
+
let activeProfile = options.profile;
|
|
1219
|
+
let fallback;
|
|
1220
|
+
const attempt = async (resume) => {
|
|
1221
|
+
const guidance = await host.guidance();
|
|
1222
|
+
const spec = buildAgentRun({
|
|
1223
|
+
tool,
|
|
1224
|
+
protection: options.protection,
|
|
1225
|
+
profile: activeProfile,
|
|
1226
|
+
outputSchema: options.outputSchema,
|
|
1227
|
+
location,
|
|
1228
|
+
stateDir: await deps.stateDir(),
|
|
1229
|
+
mcpUrl: options.mcpUrl,
|
|
1230
|
+
token,
|
|
1231
|
+
systemPrompt: guidance.systemPrompt,
|
|
1232
|
+
prompt: guidance.prompt,
|
|
1233
|
+
resumeId: resume,
|
|
1234
|
+
...deps.baseEnv ? { baseEnv: deps.baseEnv } : {}
|
|
1235
|
+
});
|
|
1236
|
+
sessionId = spec.sessionId;
|
|
1237
|
+
try {
|
|
1238
|
+
return await runProcess({
|
|
1239
|
+
command: spec.command,
|
|
1240
|
+
args: spec.args,
|
|
1241
|
+
cwd: spec.cwd,
|
|
1242
|
+
env: spec.env,
|
|
1243
|
+
stdin: spec.stdin,
|
|
1244
|
+
signal: controller.signal,
|
|
1245
|
+
timeoutMs: Math.max(1, limits.turnTimeoutMs - (Date.now() - startedAt)),
|
|
1246
|
+
onStdoutLine: (line) => {
|
|
1247
|
+
const events = spec.parse(line);
|
|
1248
|
+
queue = queue.then(async () => {
|
|
1249
|
+
if (hostFailure) return;
|
|
1250
|
+
for (const e of events) await handle(e);
|
|
1251
|
+
}).catch((error) => {
|
|
1252
|
+
hostFailure = { error };
|
|
1253
|
+
controller.abort();
|
|
1254
|
+
});
|
|
1255
|
+
}
|
|
1256
|
+
});
|
|
1257
|
+
} finally {
|
|
1258
|
+
spec.cleanup();
|
|
1259
|
+
}
|
|
1260
|
+
};
|
|
1261
|
+
let result;
|
|
1262
|
+
const requestedProfile = options.profile;
|
|
1263
|
+
if (options.fallback && requestedProfile) {
|
|
1264
|
+
const outcome = await runWorkModelWithFallback({
|
|
1265
|
+
...options.fallback,
|
|
1266
|
+
profile: requestedProfile,
|
|
1267
|
+
execute: async (model, activity) => {
|
|
1268
|
+
activeProfile = {
|
|
1269
|
+
...requestedProfile,
|
|
1270
|
+
model
|
|
1271
|
+
};
|
|
1272
|
+
finished = null;
|
|
1273
|
+
reportedModel = void 0;
|
|
1274
|
+
const result2 = await attempt(resumeId);
|
|
1275
|
+
await queue;
|
|
1276
|
+
checkHostFailure();
|
|
1277
|
+
if (streamedAny) activity.markOutput();
|
|
1278
|
+
if (toolCalls > 0 || controller.signal.aborted) activity.markToolExecution();
|
|
1279
|
+
if (finished?.error === "plan_model_refused") throw Object.assign(/* @__PURE__ */ new Error("Plan model refused"), { code: "plan_model_refused" });
|
|
1280
|
+
return result2;
|
|
1281
|
+
},
|
|
1282
|
+
isPlanModelRefusal: (error) => error?.code === "plan_model_refused",
|
|
1283
|
+
notify: (message) => emit({
|
|
1284
|
+
type: "text",
|
|
1285
|
+
delta: `${message}
|
|
1286
|
+
|
|
1287
|
+
`
|
|
1288
|
+
})
|
|
1289
|
+
});
|
|
1290
|
+
result = outcome.result;
|
|
1291
|
+
fallback = outcome.fallback;
|
|
1292
|
+
} else result = await attempt(resumeId);
|
|
1293
|
+
await queue;
|
|
1294
|
+
checkHostFailure();
|
|
1295
|
+
if (resumeId && !controller.signal.aborted && !streamedAny && !sawTool && (result.exitCode !== 0 || finished?.ok === false)) {
|
|
1296
|
+
resumeId = null;
|
|
1297
|
+
finished = null;
|
|
1298
|
+
result = await attempt(null);
|
|
1299
|
+
await queue;
|
|
1300
|
+
checkHostFailure();
|
|
1301
|
+
}
|
|
1302
|
+
const done = finished;
|
|
1303
|
+
if (!streamedAny && done?.ok && done.text) {
|
|
1304
|
+
pendingText += done.text;
|
|
1305
|
+
if (options.protection !== false) emit({
|
|
1306
|
+
type: "text",
|
|
1307
|
+
delta: done.text
|
|
1308
|
+
});
|
|
1309
|
+
}
|
|
1310
|
+
if (stop === "error" && controller.signal.aborted && !options.signal.aborted) {} else if (options.signal.aborted || result.aborted) stop = "aborted";
|
|
1311
|
+
else if (result.timedOut) {
|
|
1312
|
+
emit({
|
|
1313
|
+
type: "error",
|
|
1314
|
+
code: "timeout",
|
|
1315
|
+
message: "The assistant took too long."
|
|
1316
|
+
});
|
|
1317
|
+
stop = "timeout";
|
|
1318
|
+
} else if (result.spawnError) {
|
|
1319
|
+
emit({
|
|
1320
|
+
type: "error",
|
|
1321
|
+
code: "agent_cli_failed",
|
|
1322
|
+
message: `${label} could not be started.`
|
|
1323
|
+
});
|
|
1324
|
+
stop = "error";
|
|
1325
|
+
} else if (done ? !done.ok : result.exitCode !== 0) {
|
|
1326
|
+
const mcpUnavailable = result.stderrTail.includes("MCP startup failed") || done?.error?.includes("MCP startup failed") === true;
|
|
1327
|
+
console.error("assistant cli turn failed:", tool, result.exitCode ?? result.termination);
|
|
1328
|
+
emit({
|
|
1329
|
+
type: "error",
|
|
1330
|
+
code: mcpUnavailable ? "agent_mcp_unavailable" : "agent_cli_failed",
|
|
1331
|
+
message: mcpUnavailable ? `${label} could not connect to the app's tools. Restart the app, then try again.` : `${label} could not finish. If you signed out, connect it again.`
|
|
1332
|
+
});
|
|
1333
|
+
stop = "error";
|
|
1334
|
+
} else {
|
|
1335
|
+
let waiting = false;
|
|
1336
|
+
for (const r of raised) if ((await host.approvals.get(r.approvalId))?.status === "pending") waiting = true;
|
|
1337
|
+
stop = waiting ? "waiting" : "complete";
|
|
1338
|
+
}
|
|
1339
|
+
const note = await host.completionNote?.();
|
|
1340
|
+
if (note) {
|
|
1341
|
+
pendingText += `${pendingText ? "\n\n" : ""}${note}`;
|
|
1342
|
+
if (options.protection !== false) emit({
|
|
1343
|
+
type: "text",
|
|
1344
|
+
delta: `
|
|
1345
|
+
|
|
1346
|
+
${note}`
|
|
1347
|
+
});
|
|
1348
|
+
}
|
|
1349
|
+
const execution = options.profile ? {
|
|
1350
|
+
profile: options.profile.name,
|
|
1351
|
+
engine: tool,
|
|
1352
|
+
model: reportedModel,
|
|
1353
|
+
requestedModel: activeProfile?.model,
|
|
1354
|
+
...fallback ? { fallback } : {},
|
|
1355
|
+
effort: options.profile.effort,
|
|
1356
|
+
durationMs: Date.now() - startedAt,
|
|
1357
|
+
toolCalls,
|
|
1358
|
+
...reportedTokens !== void 0 ? { tokens: reportedTokens } : {}
|
|
1359
|
+
} : void 0;
|
|
1360
|
+
if (options.protection === false) {
|
|
1361
|
+
pendingText = redactInferenceSecret(pendingText, token);
|
|
1362
|
+
if (pendingText) emit({
|
|
1363
|
+
type: "text",
|
|
1364
|
+
delta: pendingText
|
|
1365
|
+
});
|
|
1366
|
+
}
|
|
1367
|
+
if (pendingText || sessionId || execution) await host.appendMessage({
|
|
1368
|
+
role: "assistant",
|
|
1369
|
+
content: pendingText,
|
|
1370
|
+
...sessionId ? { meta: {
|
|
1371
|
+
cliSession: {
|
|
1372
|
+
tool,
|
|
1373
|
+
id: sessionId
|
|
1374
|
+
},
|
|
1375
|
+
...execution ? { workRun: execution } : {}
|
|
1376
|
+
} } : {}
|
|
1377
|
+
});
|
|
1378
|
+
if (execution) await host.recordExecution?.(execution);
|
|
1379
|
+
emit({
|
|
1380
|
+
type: "done",
|
|
1381
|
+
stop
|
|
1382
|
+
});
|
|
1383
|
+
return stop;
|
|
1384
|
+
} finally {
|
|
1385
|
+
options.signal.removeEventListener("abort", onAbort);
|
|
1386
|
+
try {
|
|
1387
|
+
unsubscribe?.();
|
|
1388
|
+
} finally {
|
|
1389
|
+
await deps.credentials.revoke();
|
|
1390
|
+
}
|
|
1391
|
+
}
|
|
1392
|
+
}
|
|
1393
|
+
//#endregion
|
|
1394
|
+
//#region src/agent-cli/detect.ts
|
|
1395
|
+
var VERSION_TIMEOUT_MS = 8e3;
|
|
1396
|
+
var STATUS_TIMEOUT_MS = 2e4;
|
|
1397
|
+
function cliEnv(location, base = process.env, extra) {
|
|
1398
|
+
return childEnv(base, {
|
|
1399
|
+
extraPath: location.extraPath,
|
|
1400
|
+
...extra ? { extra } : {}
|
|
1401
|
+
});
|
|
1402
|
+
}
|
|
1403
|
+
async function locateCli(tool, deps = defaultLocateDeps()) {
|
|
1404
|
+
const path = await locateBinary(tool, deps);
|
|
1405
|
+
return path ? {
|
|
1406
|
+
path,
|
|
1407
|
+
extraPath: [dirname(path), nodeDir()]
|
|
1408
|
+
} : null;
|
|
1409
|
+
}
|
|
1410
|
+
function versionOf(text) {
|
|
1411
|
+
return /\d+\.\d+\.\d+[\w.+-]*/.exec(text)?.[0];
|
|
1412
|
+
}
|
|
1413
|
+
function signedInFrom(tool, exitCode, stdout) {
|
|
1414
|
+
if (tool === "claude-code") try {
|
|
1415
|
+
const parsed = JSON.parse(stdout);
|
|
1416
|
+
if (typeof parsed.loggedIn === "boolean") return parsed.loggedIn;
|
|
1417
|
+
} catch {}
|
|
1418
|
+
return exitCode === 0;
|
|
1419
|
+
}
|
|
1420
|
+
async function preflightAgentCli(tool, location, baseEnv, protection = true) {
|
|
1421
|
+
const fail = (startError, cause) => {
|
|
1422
|
+
reportAgentFailure(tool, "preflight", cause, startError);
|
|
1423
|
+
return {
|
|
1424
|
+
ready: false,
|
|
1425
|
+
startError
|
|
1426
|
+
};
|
|
1427
|
+
};
|
|
1428
|
+
let directory;
|
|
1429
|
+
let spec;
|
|
1430
|
+
try {
|
|
1431
|
+
directory = mkdtempSync(join(tmpdir(), "smrt-engine-preflight-"));
|
|
1432
|
+
spec = buildAgentRun({
|
|
1433
|
+
tool,
|
|
1434
|
+
protection,
|
|
1435
|
+
location,
|
|
1436
|
+
stateDir: directory,
|
|
1437
|
+
mcpUrl: "http://127.0.0.1:1/mcp",
|
|
1438
|
+
token: "",
|
|
1439
|
+
systemPrompt: "",
|
|
1440
|
+
prompt: "",
|
|
1441
|
+
baseEnv
|
|
1442
|
+
});
|
|
1443
|
+
delete spec.env[TOKEN_ENV];
|
|
1444
|
+
const result = await runCollect({
|
|
1445
|
+
command: spec.command,
|
|
1446
|
+
args: [...spec.args, "--help"],
|
|
1447
|
+
cwd: spec.cwd,
|
|
1448
|
+
env: spec.env,
|
|
1449
|
+
stdin: "",
|
|
1450
|
+
timeoutMs: VERSION_TIMEOUT_MS
|
|
1451
|
+
});
|
|
1452
|
+
if (result.spawnError) return fail("runtime_unavailable");
|
|
1453
|
+
if (result.exitCode !== 0 || result.timedOut) return fail("cli_invocation");
|
|
1454
|
+
if (tool === "codex") {
|
|
1455
|
+
const controller = new AbortController();
|
|
1456
|
+
let started = false;
|
|
1457
|
+
let policyBlocked = false;
|
|
1458
|
+
let startupError = false;
|
|
1459
|
+
const probeEnv = {
|
|
1460
|
+
...spec.env,
|
|
1461
|
+
HOME: directory,
|
|
1462
|
+
CODEX_HOME: directory
|
|
1463
|
+
};
|
|
1464
|
+
for (const key of [
|
|
1465
|
+
"HTTP_PROXY",
|
|
1466
|
+
"HTTPS_PROXY",
|
|
1467
|
+
"ALL_PROXY",
|
|
1468
|
+
"http_proxy",
|
|
1469
|
+
"https_proxy",
|
|
1470
|
+
"all_proxy"
|
|
1471
|
+
]) delete probeEnv[key];
|
|
1472
|
+
const probe = await runProcess({
|
|
1473
|
+
command: spec.command,
|
|
1474
|
+
args: [
|
|
1475
|
+
...spec.args.slice(0, -1),
|
|
1476
|
+
"-c",
|
|
1477
|
+
"mcp_servers.smrt.enabled=false",
|
|
1478
|
+
"-c",
|
|
1479
|
+
"model_provider=\"smrt_preflight\"",
|
|
1480
|
+
"-c",
|
|
1481
|
+
"model_providers.smrt_preflight.name=\"Startup preflight\"",
|
|
1482
|
+
"-c",
|
|
1483
|
+
"model_providers.smrt_preflight.base_url=\"http://127.0.0.1:1\"",
|
|
1484
|
+
"-c",
|
|
1485
|
+
"model_providers.smrt_preflight.wire_api=\"responses\"",
|
|
1486
|
+
"-c",
|
|
1487
|
+
"model_providers.smrt_preflight.requires_openai_auth=false",
|
|
1488
|
+
"-"
|
|
1489
|
+
],
|
|
1490
|
+
cwd: spec.cwd,
|
|
1491
|
+
env: probeEnv,
|
|
1492
|
+
stdin: "Startup preflight only.",
|
|
1493
|
+
signal: controller.signal,
|
|
1494
|
+
timeoutMs: VERSION_TIMEOUT_MS,
|
|
1495
|
+
onStdoutLine(line) {
|
|
1496
|
+
let event;
|
|
1497
|
+
try {
|
|
1498
|
+
const value = JSON.parse(line);
|
|
1499
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return;
|
|
1500
|
+
event = value;
|
|
1501
|
+
} catch {
|
|
1502
|
+
return;
|
|
1503
|
+
}
|
|
1504
|
+
if (event.item?.type === "error" && typeof event.item.message === "string" && event.item.message?.includes("code-mode host is disabled")) {
|
|
1505
|
+
policyBlocked = true;
|
|
1506
|
+
controller.abort();
|
|
1507
|
+
} else if (event.item?.type === "error" && !(typeof event.item.message === "string" && event.item.message.startsWith("Under-development features enabled:"))) {
|
|
1508
|
+
startupError = true;
|
|
1509
|
+
controller.abort();
|
|
1510
|
+
} else if (event.type === "turn.started") {
|
|
1511
|
+
started = true;
|
|
1512
|
+
controller.abort();
|
|
1513
|
+
}
|
|
1514
|
+
}
|
|
1515
|
+
});
|
|
1516
|
+
if (policyBlocked) return fail("tool_host_policy");
|
|
1517
|
+
if (!started || startupError) return fail(probe.spawnError ? "runtime_unavailable" : "cli_invocation");
|
|
1518
|
+
}
|
|
1519
|
+
return { ready: true };
|
|
1520
|
+
} catch (error) {
|
|
1521
|
+
return fail("working_directory", error);
|
|
1522
|
+
} finally {
|
|
1523
|
+
spec?.cleanup();
|
|
1524
|
+
if (directory) rmSync(directory, {
|
|
1525
|
+
recursive: true,
|
|
1526
|
+
force: true
|
|
1527
|
+
});
|
|
1528
|
+
}
|
|
1529
|
+
}
|
|
1530
|
+
async function detectAgentCli(tool, deps = defaultLocateDeps(), protection = true) {
|
|
1531
|
+
const info = AGENT_TOOL_INFO[tool];
|
|
1532
|
+
const base = {
|
|
1533
|
+
tool,
|
|
1534
|
+
label: info.label,
|
|
1535
|
+
installUrl: info.installUrl
|
|
1536
|
+
};
|
|
1537
|
+
const location = await locateCli(tool, deps);
|
|
1538
|
+
if (!location) return {
|
|
1539
|
+
...base,
|
|
1540
|
+
installed: false,
|
|
1541
|
+
signedIn: false
|
|
1542
|
+
};
|
|
1543
|
+
const env = cliEnv(location, deps.env);
|
|
1544
|
+
const version = await runCollect({
|
|
1545
|
+
command: location.path,
|
|
1546
|
+
args: info.versionArgs,
|
|
1547
|
+
env,
|
|
1548
|
+
timeoutMs: VERSION_TIMEOUT_MS
|
|
1549
|
+
});
|
|
1550
|
+
if (version.spawnError || version.exitCode !== 0) return {
|
|
1551
|
+
...base,
|
|
1552
|
+
installed: true,
|
|
1553
|
+
signedIn: null
|
|
1554
|
+
};
|
|
1555
|
+
const status = await runCollect({
|
|
1556
|
+
command: location.path,
|
|
1557
|
+
args: info.statusArgs,
|
|
1558
|
+
env,
|
|
1559
|
+
timeoutMs: STATUS_TIMEOUT_MS
|
|
1560
|
+
});
|
|
1561
|
+
const found = versionOf(version.stdout);
|
|
1562
|
+
const signedIn = status.spawnError || status.timedOut ? null : signedInFrom(tool, status.exitCode, status.stdout);
|
|
1563
|
+
const startup = signedIn === true ? await preflightAgentCli(tool, location, deps.env, protection) : {};
|
|
1564
|
+
return {
|
|
1565
|
+
...base,
|
|
1566
|
+
installed: true,
|
|
1567
|
+
...found ? { version: found } : {},
|
|
1568
|
+
signedIn,
|
|
1569
|
+
...startup
|
|
1570
|
+
};
|
|
1571
|
+
}
|
|
1572
|
+
async function detectAgentClis(deps = defaultLocateDeps()) {
|
|
1573
|
+
return Promise.all(AGENT_TOOLS.map((tool) => detectAgentCli(tool, deps)));
|
|
1574
|
+
}
|
|
1575
|
+
//#endregion
|
|
1576
|
+
//#region src/agent-cli/login.ts
|
|
1577
|
+
var LOGIN_TIMEOUT_MS = 5 * 6e4;
|
|
1578
|
+
var AgentLogin = class {
|
|
1579
|
+
constructor(options = {}) {
|
|
1580
|
+
this.options = options;
|
|
1581
|
+
}
|
|
1582
|
+
options;
|
|
1583
|
+
running = /* @__PURE__ */ new Map();
|
|
1584
|
+
last = /* @__PURE__ */ new Map();
|
|
1585
|
+
snapshot(tool) {
|
|
1586
|
+
if (this.running.has(tool)) return { state: "running" };
|
|
1587
|
+
return { state: this.last.get(tool) ?? "idle" };
|
|
1588
|
+
}
|
|
1589
|
+
/**
|
|
1590
|
+
* Start the tool's sign-in. `started` / `running` (one is already open) /
|
|
1591
|
+
* `missing` (the tool is not installed).
|
|
1592
|
+
*/
|
|
1593
|
+
async start(tool) {
|
|
1594
|
+
if (this.running.has(tool)) return "running";
|
|
1595
|
+
const deps = this.options.deps ?? defaultLocateDeps();
|
|
1596
|
+
const location = await locateCli(tool, deps);
|
|
1597
|
+
if (!location) return "missing";
|
|
1598
|
+
if (this.running.has(tool)) return "running";
|
|
1599
|
+
const controller = new AbortController();
|
|
1600
|
+
const info = AGENT_TOOL_INFO[tool];
|
|
1601
|
+
const done = runProcess({
|
|
1602
|
+
command: location.path,
|
|
1603
|
+
args: info.loginArgs,
|
|
1604
|
+
env: cliEnv(location, deps.env),
|
|
1605
|
+
signal: controller.signal,
|
|
1606
|
+
timeoutMs: this.options.timeoutMs ?? 3e5
|
|
1607
|
+
}).then((result) => {
|
|
1608
|
+
this.running.delete(tool);
|
|
1609
|
+
this.last.set(tool, result.exitCode === 0 ? "finished" : "failed");
|
|
1610
|
+
this.options.onEnd?.(tool);
|
|
1611
|
+
});
|
|
1612
|
+
this.running.set(tool, {
|
|
1613
|
+
controller,
|
|
1614
|
+
done
|
|
1615
|
+
});
|
|
1616
|
+
this.last.delete(tool);
|
|
1617
|
+
return "started";
|
|
1618
|
+
}
|
|
1619
|
+
/** Stop an open sign-in (the person closed the dialog). */
|
|
1620
|
+
cancel(tool) {
|
|
1621
|
+
this.running.get(tool)?.controller.abort();
|
|
1622
|
+
}
|
|
1623
|
+
/** Tests: wait until the sign-in process has ended. */
|
|
1624
|
+
async settled(tool) {
|
|
1625
|
+
await this.running.get(tool)?.done;
|
|
1626
|
+
}
|
|
1627
|
+
};
|
|
1628
|
+
//#endregion
|
|
1629
|
+
//#region src/agent-cli/service.ts
|
|
1630
|
+
function createAgentCliService(initialDeps = null) {
|
|
1631
|
+
const CACHE_MS = 15e3;
|
|
1632
|
+
let depsOverride = initialDeps;
|
|
1633
|
+
const cache = /* @__PURE__ */ new Map();
|
|
1634
|
+
let loginManager = null;
|
|
1635
|
+
function deps() {
|
|
1636
|
+
return depsOverride ?? defaultLocateDeps();
|
|
1637
|
+
}
|
|
1638
|
+
function configureAgentCli(next) {
|
|
1639
|
+
depsOverride = next;
|
|
1640
|
+
cache.clear();
|
|
1641
|
+
loginManager = null;
|
|
1642
|
+
}
|
|
1643
|
+
function invalidateCliStatus(tool) {
|
|
1644
|
+
if (tool) {
|
|
1645
|
+
for (const key of cache.keys()) if (key.startsWith(`${tool}:`)) cache.delete(key);
|
|
1646
|
+
} else cache.clear();
|
|
1647
|
+
}
|
|
1648
|
+
function agentLogin() {
|
|
1649
|
+
loginManager ??= new AgentLogin({
|
|
1650
|
+
deps: deps(),
|
|
1651
|
+
onEnd: (tool) => invalidateCliStatus(tool)
|
|
1652
|
+
});
|
|
1653
|
+
return loginManager;
|
|
1654
|
+
}
|
|
1655
|
+
async function cliStatus(tool, options = {}) {
|
|
1656
|
+
const key = `${tool}:${options.protection !== false}`;
|
|
1657
|
+
const hit = cache.get(key);
|
|
1658
|
+
if (!options.fresh && hit && Date.now() - hit.at < CACHE_MS) return hit.status;
|
|
1659
|
+
const status = await detectAgentCli(tool, deps(), options.protection !== false);
|
|
1660
|
+
cache.set(key, {
|
|
1661
|
+
at: Date.now(),
|
|
1662
|
+
status
|
|
1663
|
+
});
|
|
1664
|
+
return status;
|
|
1665
|
+
}
|
|
1666
|
+
function allCliStatus(options = {}) {
|
|
1667
|
+
return Promise.all(AGENT_TOOLS.map((tool) => cliStatus(tool, options)));
|
|
1668
|
+
}
|
|
1669
|
+
return {
|
|
1670
|
+
configureAgentCli,
|
|
1671
|
+
invalidateCliStatus,
|
|
1672
|
+
agentLogin,
|
|
1673
|
+
cliStatus,
|
|
1674
|
+
allCliStatus,
|
|
1675
|
+
agentCliDeps: deps
|
|
1676
|
+
};
|
|
1677
|
+
}
|
|
1678
|
+
//#endregion
|
|
1679
|
+
//#region src/chatgpt/connection.ts
|
|
1680
|
+
var CHATGPT_PLAN_PROVIDER = "chatgpt-plan";
|
|
1681
|
+
var CHATGPT_AUTH_HOST = "auth.openai.com";
|
|
1682
|
+
var CHATGPT_SIGN_IN_WINDOW_MS = 10 * 6e4;
|
|
1683
|
+
var MODELS_TTL_MS = 10 * 6e4;
|
|
1684
|
+
var ChatGPTSignedOutError = class extends Error {
|
|
1685
|
+
code = "chatgpt_signed_out";
|
|
1686
|
+
constructor() {
|
|
1687
|
+
super("Sign in with ChatGPT first.");
|
|
1688
|
+
this.name = "ChatGPTSignedOutError";
|
|
1689
|
+
}
|
|
1690
|
+
};
|
|
1691
|
+
function isChatGPTAuthorizationUrl(url) {
|
|
1692
|
+
if (typeof url !== "string") return false;
|
|
1693
|
+
try {
|
|
1694
|
+
const parsed = new URL(url);
|
|
1695
|
+
return parsed.protocol === "https:" && parsed.hostname === "auth.openai.com" && !parsed.port && !parsed.username && !parsed.password && !parsed.hash;
|
|
1696
|
+
} catch {
|
|
1697
|
+
return false;
|
|
1698
|
+
}
|
|
1699
|
+
}
|
|
1700
|
+
var MESSAGES = {
|
|
1701
|
+
declined: "Sign-in was declined in the browser.",
|
|
1702
|
+
plan_permission_missing: "ChatGPT did not allow plan use for this account. Check the account and try again.",
|
|
1703
|
+
storage_busy: "Another sign-in is in progress. Try again in a moment.",
|
|
1704
|
+
timed_out: "The sign-in was not finished in time. Try again.",
|
|
1705
|
+
failed: "Sign-in did not finish. Try again."
|
|
1706
|
+
};
|
|
1707
|
+
function errorFor(code) {
|
|
1708
|
+
return {
|
|
1709
|
+
code,
|
|
1710
|
+
message: MESSAGES[code]
|
|
1711
|
+
};
|
|
1712
|
+
}
|
|
1713
|
+
function signInErrorCode(error) {
|
|
1714
|
+
const code = error?.code;
|
|
1715
|
+
if (code === "consent_declined") return "declined";
|
|
1716
|
+
if (code === "plan_permission_missing") return "plan_permission_missing";
|
|
1717
|
+
if (code === "storage_busy") return "storage_busy";
|
|
1718
|
+
return "failed";
|
|
1719
|
+
}
|
|
1720
|
+
function createChatGPTPlanConnection(options) {
|
|
1721
|
+
if (!options.credentialsPath.trim()) throw new Error("a ChatGPT credentials path is required");
|
|
1722
|
+
const now = options.now ?? Date.now;
|
|
1723
|
+
let managerPromise;
|
|
1724
|
+
const manager = () => {
|
|
1725
|
+
managerPromise ??= options.manager ? Promise.resolve(options.manager) : import("@happyvertical/auth/local").then(({ LocalChatGPTSessionManager }) => new LocalChatGPTSessionManager({
|
|
1726
|
+
appName: options.appName,
|
|
1727
|
+
path: options.credentialsPath
|
|
1728
|
+
}));
|
|
1729
|
+
managerPromise.catch(() => {
|
|
1730
|
+
managerPromise = void 0;
|
|
1731
|
+
});
|
|
1732
|
+
return managerPromise;
|
|
1733
|
+
};
|
|
1734
|
+
let pending;
|
|
1735
|
+
let lastError;
|
|
1736
|
+
let activeClientId;
|
|
1737
|
+
let modelCache;
|
|
1738
|
+
const signingIn = () => pending !== void 0 && now() - pending.startedAt < 6e5;
|
|
1739
|
+
async function current() {
|
|
1740
|
+
const sessions = (await (await manager()).sessions()).filter((s) => s.scopes.includes("chatgpt.tokens.use.direct"));
|
|
1741
|
+
return sessions.find((s) => s.clientId === activeClientId) ?? sessions.at(-1);
|
|
1742
|
+
}
|
|
1743
|
+
async function dropOthers(keep) {
|
|
1744
|
+
try {
|
|
1745
|
+
const store = await manager();
|
|
1746
|
+
for (const session of await store.sessions()) if (session.clientId !== keep) await store.logout(session.clientId).catch(() => void 0);
|
|
1747
|
+
} catch {}
|
|
1748
|
+
}
|
|
1749
|
+
const connection = {
|
|
1750
|
+
async start() {
|
|
1751
|
+
if (pending && signingIn()) return { authorizationUrl: pending.url };
|
|
1752
|
+
lastError = void 0;
|
|
1753
|
+
const store = await manager();
|
|
1754
|
+
const begun = await store.begin();
|
|
1755
|
+
if (!isChatGPTAuthorizationUrl(begun.authorizationUrl)) {
|
|
1756
|
+
begun.callback.catch(() => void 0);
|
|
1757
|
+
throw new Error("The sign-in address was not on OpenAI.");
|
|
1758
|
+
}
|
|
1759
|
+
const mine = {
|
|
1760
|
+
url: begun.authorizationUrl,
|
|
1761
|
+
startedAt: now(),
|
|
1762
|
+
cancel: begun.cancel
|
|
1763
|
+
};
|
|
1764
|
+
pending = mine;
|
|
1765
|
+
begun.callback.then((session) => {
|
|
1766
|
+
if (pending !== mine || now() - mine.startedAt >= 6e5) {
|
|
1767
|
+
store.logout(session.clientId).catch(() => void 0);
|
|
1768
|
+
return;
|
|
1769
|
+
}
|
|
1770
|
+
pending = void 0;
|
|
1771
|
+
activeClientId = session.clientId;
|
|
1772
|
+
modelCache = void 0;
|
|
1773
|
+
dropOthers(session.clientId);
|
|
1774
|
+
}, (error) => {
|
|
1775
|
+
if (pending !== mine) return;
|
|
1776
|
+
pending = void 0;
|
|
1777
|
+
lastError = errorFor(signInErrorCode(error));
|
|
1778
|
+
});
|
|
1779
|
+
return { authorizationUrl: begun.authorizationUrl };
|
|
1780
|
+
},
|
|
1781
|
+
async status() {
|
|
1782
|
+
let session;
|
|
1783
|
+
try {
|
|
1784
|
+
session = await current();
|
|
1785
|
+
} catch {
|
|
1786
|
+
session = void 0;
|
|
1787
|
+
}
|
|
1788
|
+
if (!pending || !signingIn()) {
|
|
1789
|
+
if (pending && !lastError) lastError = errorFor("timed_out");
|
|
1790
|
+
pending = void 0;
|
|
1791
|
+
}
|
|
1792
|
+
return {
|
|
1793
|
+
signedIn: session !== void 0,
|
|
1794
|
+
...session ? { account: { label: session.email?.trim() || "ChatGPT account" } } : {},
|
|
1795
|
+
signingIn: signingIn(),
|
|
1796
|
+
...lastError && !session ? { error: lastError } : {}
|
|
1797
|
+
};
|
|
1798
|
+
},
|
|
1799
|
+
async cancel() {
|
|
1800
|
+
const mine = pending;
|
|
1801
|
+
if (!mine) return;
|
|
1802
|
+
if (!mine.cancel) throw Object.assign(/* @__PURE__ */ new Error("This auth SDK cannot cancel a pending sign-in"), { code: "chatgpt_cancel_unavailable" });
|
|
1803
|
+
await mine.cancel();
|
|
1804
|
+
if (pending === mine) pending = void 0;
|
|
1805
|
+
lastError = void 0;
|
|
1806
|
+
},
|
|
1807
|
+
async signOut() {
|
|
1808
|
+
pending = void 0;
|
|
1809
|
+
lastError = void 0;
|
|
1810
|
+
modelCache = void 0;
|
|
1811
|
+
activeClientId = void 0;
|
|
1812
|
+
const store = await manager();
|
|
1813
|
+
let confirmed = true;
|
|
1814
|
+
for (const session of await store.sessions()) {
|
|
1815
|
+
const out = await store.logout(session.clientId);
|
|
1816
|
+
confirmed = confirmed && out.remoteRevocationConfirmed;
|
|
1817
|
+
}
|
|
1818
|
+
return { remoteRevocationConfirmed: confirmed };
|
|
1819
|
+
},
|
|
1820
|
+
async clientOptions(extra = {}) {
|
|
1821
|
+
const session = await current();
|
|
1822
|
+
if (!session) throw new ChatGPTSignedOutError();
|
|
1823
|
+
const store = await manager();
|
|
1824
|
+
return {
|
|
1825
|
+
type: CHATGPT_PLAN_PROVIDER,
|
|
1826
|
+
clientId: session.clientId,
|
|
1827
|
+
sessionManager: { accessToken: (clientId) => store.accessToken(clientId) },
|
|
1828
|
+
...extra.model ? { defaultModel: extra.model } : {},
|
|
1829
|
+
...extra.toolNamespace ? { toolNamespace: extra.toolNamespace } : {}
|
|
1830
|
+
};
|
|
1831
|
+
},
|
|
1832
|
+
async models() {
|
|
1833
|
+
const session = await current();
|
|
1834
|
+
if (!session) throw new ChatGPTSignedOutError();
|
|
1835
|
+
if (modelCache && modelCache.clientId === session.clientId && now() - modelCache.at < MODELS_TTL_MS) return modelCache.models;
|
|
1836
|
+
const clientOptions = await connection.clientOptions();
|
|
1837
|
+
const models = rankOpenAIWorkModels((await (options.createClient ? await options.createClient(clientOptions) : await (await import("@happyvertical/ai")).getAI(clientOptions)).getModels()).map((m) => ({
|
|
1838
|
+
id: m.id,
|
|
1839
|
+
label: m.name?.trim() || m.id,
|
|
1840
|
+
...Number.isFinite(m.intelligenceRank) ? { intelligenceRank: m.intelligenceRank } : {}
|
|
1841
|
+
})));
|
|
1842
|
+
modelCache = {
|
|
1843
|
+
at: now(),
|
|
1844
|
+
clientId: session.clientId,
|
|
1845
|
+
models
|
|
1846
|
+
};
|
|
1847
|
+
return models;
|
|
1848
|
+
},
|
|
1849
|
+
async defaultModel() {
|
|
1850
|
+
return strongestWorkModel(await connection.models());
|
|
1851
|
+
}
|
|
1852
|
+
};
|
|
1853
|
+
return connection;
|
|
1854
|
+
}
|
|
1855
|
+
//#endregion
|
|
1856
|
+
//#region src/engine-model.ts
|
|
1857
|
+
var EngineModelFailure = class extends Error {
|
|
1858
|
+
constructor(code, message, action, options) {
|
|
1859
|
+
super(message, options);
|
|
1860
|
+
this.code = code;
|
|
1861
|
+
this.action = action;
|
|
1862
|
+
this.name = "EngineModelFailure";
|
|
1863
|
+
}
|
|
1864
|
+
code;
|
|
1865
|
+
action;
|
|
1866
|
+
};
|
|
1867
|
+
function engineModelReply(response) {
|
|
1868
|
+
return {
|
|
1869
|
+
...response.model ? { model: response.model } : {},
|
|
1870
|
+
text: response.content ?? "",
|
|
1871
|
+
toolCalls: (response.toolCalls ?? []).map((c) => ({
|
|
1872
|
+
id: c.id,
|
|
1873
|
+
name: c.function.name,
|
|
1874
|
+
arguments: c.function.arguments
|
|
1875
|
+
})),
|
|
1876
|
+
...response.usage?.totalTokens !== void 0 ? { totalTokens: response.usage.totalTokens } : {},
|
|
1877
|
+
...response.toolCalls ? { raw: response.toolCalls } : {}
|
|
1878
|
+
};
|
|
1879
|
+
}
|
|
1880
|
+
//#endregion
|
|
1881
|
+
//#region src/chatgpt/resolver.ts
|
|
1882
|
+
function createChatGPTPlanResolver(options) {
|
|
1883
|
+
const { fallback } = options;
|
|
1884
|
+
const resolver = { async resolve(request, context) {
|
|
1885
|
+
if (!await options.appliesTo(request)) return fallback?.resolve(request, context);
|
|
1886
|
+
const tierResolved = request.tier === "auto" ? "good" : request.tier ?? "good";
|
|
1887
|
+
if (!(await options.connection.status()).signedIn) return {
|
|
1888
|
+
tierResolved,
|
|
1889
|
+
target: {},
|
|
1890
|
+
via: "resolver",
|
|
1891
|
+
mode: "off",
|
|
1892
|
+
unavailable: "unconfigured"
|
|
1893
|
+
};
|
|
1894
|
+
const model = await options.model?.(request) ?? await options.connection.defaultModel();
|
|
1895
|
+
return {
|
|
1896
|
+
tierResolved,
|
|
1897
|
+
target: {
|
|
1898
|
+
provider: CHATGPT_PLAN_PROVIDER,
|
|
1899
|
+
...model ? { model } : {},
|
|
1900
|
+
source: "byo"
|
|
1901
|
+
},
|
|
1902
|
+
via: "resolver",
|
|
1903
|
+
mode: "byo"
|
|
1904
|
+
};
|
|
1905
|
+
} };
|
|
1906
|
+
if (fallback?.mode) resolver.mode = (request) => fallback.mode?.(request);
|
|
1907
|
+
if (fallback?.lookupFusion) resolver.lookupFusion = (key, request, context) => fallback.lookupFusion?.(key, request, context);
|
|
1908
|
+
return resolver;
|
|
1909
|
+
}
|
|
1910
|
+
var BY_CLASS = {
|
|
1911
|
+
ChatGPTPlanUsageLimitError: "usage_limit",
|
|
1912
|
+
ChatGPTPlanSessionRevokedError: "session_revoked",
|
|
1913
|
+
ChatGPTPlanWorkspaceError: "workspace",
|
|
1914
|
+
ChatGPTPlanUsageUnavailableError: "unavailable"
|
|
1915
|
+
};
|
|
1916
|
+
function classifyChatGPTPlanFailure(error) {
|
|
1917
|
+
if (!error || typeof error !== "object") return "other";
|
|
1918
|
+
const e = error;
|
|
1919
|
+
if (typeof e.name === "string" && BY_CLASS[e.name]) return BY_CLASS[e.name];
|
|
1920
|
+
if (e.code === "subscription_sharing_unsupported_capability") return "unsupported_capability";
|
|
1921
|
+
if (e.name === "ChatGPTSessionError") {
|
|
1922
|
+
const code = e.code;
|
|
1923
|
+
if (code === "unknown_account" || code === "refresh_invalid") return "session_revoked";
|
|
1924
|
+
}
|
|
1925
|
+
return "other";
|
|
1926
|
+
}
|
|
1927
|
+
//#endregion
|
|
1928
|
+
//#region src/chatgpt/support.ts
|
|
1929
|
+
function browserCommand(url, platform = process.platform) {
|
|
1930
|
+
if (platform === "darwin") return {
|
|
1931
|
+
command: "open",
|
|
1932
|
+
args: [url]
|
|
1933
|
+
};
|
|
1934
|
+
if (platform === "win32") return {
|
|
1935
|
+
command: "cmd",
|
|
1936
|
+
args: [
|
|
1937
|
+
"/c",
|
|
1938
|
+
"start",
|
|
1939
|
+
"\"\"",
|
|
1940
|
+
`"${url}"`
|
|
1941
|
+
],
|
|
1942
|
+
verbatim: true
|
|
1943
|
+
};
|
|
1944
|
+
return {
|
|
1945
|
+
command: "xdg-open",
|
|
1946
|
+
args: [url]
|
|
1947
|
+
};
|
|
1948
|
+
}
|
|
1949
|
+
async function openSystemBrowser(url, deps = {}) {
|
|
1950
|
+
if (!isChatGPTAuthorizationUrl(url)) throw new Error("Only the ChatGPT sign-in page can be opened.");
|
|
1951
|
+
const { command, args, verbatim } = browserCommand(url, deps.platform);
|
|
1952
|
+
const run = deps.spawn ?? spawn;
|
|
1953
|
+
return new Promise((resolve) => {
|
|
1954
|
+
try {
|
|
1955
|
+
const child = run(command, args, {
|
|
1956
|
+
detached: true,
|
|
1957
|
+
stdio: "ignore",
|
|
1958
|
+
...verbatim ? { windowsVerbatimArguments: true } : {}
|
|
1959
|
+
});
|
|
1960
|
+
child.once("error", () => resolve(false));
|
|
1961
|
+
child.unref();
|
|
1962
|
+
setTimeout(() => resolve(true), 50);
|
|
1963
|
+
} catch {
|
|
1964
|
+
resolve(false);
|
|
1965
|
+
}
|
|
1966
|
+
});
|
|
1967
|
+
}
|
|
1968
|
+
var NOTES = {
|
|
1969
|
+
usage_limit: {
|
|
1970
|
+
code: "chatgpt_usage_limit",
|
|
1971
|
+
message: "Your ChatGPT plan has reached its usage limit. Try again later, or check ChatGPT Settings, Usage."
|
|
1972
|
+
},
|
|
1973
|
+
session_revoked: {
|
|
1974
|
+
code: "chatgpt_session_revoked",
|
|
1975
|
+
message: "Your ChatGPT sign-in is no longer valid. Sign in again to keep using the assistant."
|
|
1976
|
+
},
|
|
1977
|
+
workspace: {
|
|
1978
|
+
code: "chatgpt_workspace",
|
|
1979
|
+
message: "This ChatGPT account or workspace is not allowed to be used here. Sign in with another account."
|
|
1980
|
+
},
|
|
1981
|
+
unavailable: {
|
|
1982
|
+
code: "chatgpt_unavailable",
|
|
1983
|
+
message: "ChatGPT plan use is not available right now. You are still signed in. Try again in a moment."
|
|
1984
|
+
},
|
|
1985
|
+
unsupported_capability: {
|
|
1986
|
+
code: "chatgpt_unsupported",
|
|
1987
|
+
message: "The assistant sent something ChatGPT plan use does not allow, so nothing was done. This is a fault in the app, not your account."
|
|
1988
|
+
}
|
|
1989
|
+
};
|
|
1990
|
+
function chatgptFailureNote(error, settingsHref) {
|
|
1991
|
+
const kind = classifyChatGPTPlanFailure(error);
|
|
1992
|
+
if (kind === "other") return void 0;
|
|
1993
|
+
return {
|
|
1994
|
+
...NOTES[kind],
|
|
1995
|
+
...settingsHref && (kind === "session_revoked" || kind === "workspace") ? { action: {
|
|
1996
|
+
label: "Sign in again",
|
|
1997
|
+
href: settingsHref
|
|
1998
|
+
} } : {}
|
|
1999
|
+
};
|
|
2000
|
+
}
|
|
2001
|
+
//#endregion
|
|
2002
|
+
//#region src/chatgpt/model.ts
|
|
2003
|
+
async function createChatGPTModel(input) {
|
|
2004
|
+
const catalog = input.catalog ?? (input.profile ? await input.connection.models?.() : void 0);
|
|
2005
|
+
const profile = input.profile ? resolveWorkProfile({
|
|
2006
|
+
profile: input.profile,
|
|
2007
|
+
engine: "chatgpt",
|
|
2008
|
+
settings: {
|
|
2009
|
+
...input.settings,
|
|
2010
|
+
...input.model ? { model: input.model } : {}
|
|
2011
|
+
},
|
|
2012
|
+
catalog
|
|
2013
|
+
}) : void 0;
|
|
2014
|
+
if (profile && profile.engine !== "chatgpt") throw new Error("The work profile does not match this connected engine.");
|
|
2015
|
+
const selectedModel = profile?.model ?? input.model;
|
|
2016
|
+
if (selectedModel !== void 0) validateWorkModel(selectedModel);
|
|
2017
|
+
const options = await input.connection.clientOptions({
|
|
2018
|
+
...selectedModel ? { model: selectedModel } : {},
|
|
2019
|
+
toolNamespace: input.toolNamespace
|
|
2020
|
+
});
|
|
2021
|
+
const createClient = input.createClient ?? (async (options2) => {
|
|
2022
|
+
const { getAI } = await import("@happyvertical/ai");
|
|
2023
|
+
return getAI(options2);
|
|
2024
|
+
});
|
|
2025
|
+
let ai = await createClient(options);
|
|
2026
|
+
let actualModel = selectedModel;
|
|
2027
|
+
return { async complete(request) {
|
|
2028
|
+
try {
|
|
2029
|
+
const startedAt = Date.now();
|
|
2030
|
+
const execute = async (model, activity) => {
|
|
2031
|
+
if (model && model !== actualModel) {
|
|
2032
|
+
ai = await createClient(await input.connection.clientOptions({
|
|
2033
|
+
model,
|
|
2034
|
+
toolNamespace: input.toolNamespace
|
|
2035
|
+
}));
|
|
2036
|
+
actualModel = model;
|
|
2037
|
+
}
|
|
2038
|
+
return engineModelReply(await ai.chat(request.messages, {
|
|
2039
|
+
tools: request.tools,
|
|
2040
|
+
signal: request.signal,
|
|
2041
|
+
onProgress: activity ? (delta) => {
|
|
2042
|
+
if (delta) activity.markOutput();
|
|
2043
|
+
request.onText(delta);
|
|
2044
|
+
} : request.onText
|
|
2045
|
+
}));
|
|
2046
|
+
};
|
|
2047
|
+
let fallback;
|
|
2048
|
+
let reply;
|
|
2049
|
+
if (profile && input.fallback) {
|
|
2050
|
+
const outcome = await runWorkModelWithFallback({
|
|
2051
|
+
...input.fallback,
|
|
2052
|
+
nextModel: input.fallback.nextModel ?? nextWorkModel(catalog ?? [], profile.model),
|
|
2053
|
+
profile,
|
|
2054
|
+
notify: (message) => {
|
|
2055
|
+
input.fallback?.notify?.(message);
|
|
2056
|
+
request.onText(`${message}
|
|
2057
|
+
|
|
2058
|
+
`);
|
|
2059
|
+
},
|
|
2060
|
+
execute,
|
|
2061
|
+
isPlanModelRefusal: (error) => [
|
|
2062
|
+
"MODEL_NOT_AVAILABLE",
|
|
2063
|
+
"MODEL_ACCESS_DENIED",
|
|
2064
|
+
"model_not_available",
|
|
2065
|
+
"model_access_denied"
|
|
2066
|
+
].includes(error?.code ?? "")
|
|
2067
|
+
});
|
|
2068
|
+
reply = outcome.result;
|
|
2069
|
+
fallback = outcome.fallback;
|
|
2070
|
+
} else reply = await execute(actualModel);
|
|
2071
|
+
if (profile) await input.recordExecution?.({
|
|
2072
|
+
profile: profile.name,
|
|
2073
|
+
engine: "chatgpt",
|
|
2074
|
+
model: reply.model,
|
|
2075
|
+
requestedModel: actualModel,
|
|
2076
|
+
effort: profile.effort,
|
|
2077
|
+
durationMs: Date.now() - startedAt,
|
|
2078
|
+
tokens: reply.totalTokens,
|
|
2079
|
+
toolCalls: reply.toolCalls.length,
|
|
2080
|
+
...fallback ? { fallback } : {}
|
|
2081
|
+
});
|
|
2082
|
+
return reply;
|
|
2083
|
+
} catch (error) {
|
|
2084
|
+
const note = chatgptFailureNote(error, input.settingsHref);
|
|
2085
|
+
if (note) throw new EngineModelFailure(note.code, note.message, note.action, { cause: error });
|
|
2086
|
+
throw error;
|
|
2087
|
+
}
|
|
2088
|
+
} };
|
|
2089
|
+
}
|
|
2090
|
+
//#endregion
|
|
2091
|
+
//#region src/design-run-store.ts
|
|
2092
|
+
function createDesignRunStore(options) {
|
|
2093
|
+
const { db, ownerId, tenantId } = options;
|
|
2094
|
+
if (!ownerId) throw new Error("Design runs require an owner");
|
|
2095
|
+
const tenantPredicate = tenantId === null ? "tenant_id IS NULL" : "tenant_id = ?";
|
|
2096
|
+
const identity = (id) => tenantId === null ? [id, ownerId] : [
|
|
2097
|
+
id,
|
|
2098
|
+
ownerId,
|
|
2099
|
+
tenantId
|
|
2100
|
+
];
|
|
2101
|
+
const load = async (connection, id) => {
|
|
2102
|
+
const result = await connection.query(`SELECT payload FROM _smrt_inference_design_runs WHERE id = ? AND owner_id = ? AND ${tenantPredicate}`, ...identity(id));
|
|
2103
|
+
if (!result.rows.length) return null;
|
|
2104
|
+
return JSON.parse(String(result.rows[0].payload));
|
|
2105
|
+
};
|
|
2106
|
+
return {
|
|
2107
|
+
async load(id, requestedOwner) {
|
|
2108
|
+
if (requestedOwner !== ownerId) return null;
|
|
2109
|
+
return load(db, id);
|
|
2110
|
+
},
|
|
2111
|
+
async releaseLease(id, requestedOwner, leaseRevision) {
|
|
2112
|
+
if (requestedOwner !== ownerId || !options.authorizeRelease) return false;
|
|
2113
|
+
if (!db.transaction) throw new Error("Design runs require transaction support");
|
|
2114
|
+
return db.transaction(async (tx) => {
|
|
2115
|
+
const state = await load(tx, id);
|
|
2116
|
+
if (state?.status !== "stopped" || state.leaseRevision !== leaseRevision) return false;
|
|
2117
|
+
if (!await options.authorizeRelease?.(tx, state)) return false;
|
|
2118
|
+
const next = {
|
|
2119
|
+
...state,
|
|
2120
|
+
revision: state.revision + 1,
|
|
2121
|
+
leaseUntil: void 0,
|
|
2122
|
+
leaseRevision: void 0
|
|
2123
|
+
};
|
|
2124
|
+
return (await tx.query(`UPDATE _smrt_inference_design_runs SET revision = ?, payload = ?, updated_at = ?
|
|
2125
|
+
WHERE id = ? AND owner_id = ? AND ${tenantPredicate} AND revision = ? RETURNING id`, next.revision, JSON.stringify(next), (/* @__PURE__ */ new Date()).toISOString(), ...identity(id), state.revision)).rows.length === 1;
|
|
2126
|
+
});
|
|
2127
|
+
},
|
|
2128
|
+
async save(state, expectedRevision) {
|
|
2129
|
+
if (state.ownerId !== ownerId) throw new Error("Design run not found");
|
|
2130
|
+
if (!db.transaction) throw new Error("Design runs require transaction support");
|
|
2131
|
+
return db.transaction(async (tx) => {
|
|
2132
|
+
if (options.authorizeWrite && !await options.authorizeWrite(tx, state)) return false;
|
|
2133
|
+
const previous = await load(tx, state.id);
|
|
2134
|
+
const encoded = JSON.stringify(state);
|
|
2135
|
+
const date = (/* @__PURE__ */ new Date()).toISOString();
|
|
2136
|
+
if (expectedRevision === null) {
|
|
2137
|
+
if ((await tx.query(`INSERT INTO _smrt_inference_design_runs
|
|
2138
|
+
(id, slug, context, created_at, updated_at, owner_id, tenant_id, revision, payload)
|
|
2139
|
+
VALUES (?, ?, '', ?, ?, ?, ?, ?, ?) ON CONFLICT (id) DO NOTHING RETURNING id`, state.id, state.id, date, date, ownerId, tenantId, state.revision, encoded)).rows.length !== 1) return false;
|
|
2140
|
+
} else {
|
|
2141
|
+
if (!previous || state.revision !== expectedRevision + 1) return false;
|
|
2142
|
+
if ((await tx.query(`UPDATE _smrt_inference_design_runs SET revision = ?, payload = ?, updated_at = ?
|
|
2143
|
+
WHERE id = ? AND owner_id = ? AND ${tenantPredicate} AND revision = ? RETURNING id`, state.revision, encoded, date, ...identity(state.id), expectedRevision)).rows.length !== 1) return false;
|
|
2144
|
+
}
|
|
2145
|
+
if (state.status === "running" && (!previous || previous.status === "stopped" || previous.status === "waiting-approval")) await options.enqueue(tx, state);
|
|
2146
|
+
return true;
|
|
2147
|
+
});
|
|
2148
|
+
}
|
|
2149
|
+
};
|
|
2150
|
+
}
|
|
2151
|
+
//#endregion
|
|
2152
|
+
//#region src/engine-status.ts
|
|
2153
|
+
function cliTool(engine) {
|
|
2154
|
+
return engine === "claude-code" || engine === "codex" ? engine : null;
|
|
2155
|
+
}
|
|
2156
|
+
async function chatgptEngineStatus(connection, action) {
|
|
2157
|
+
const base = {
|
|
2158
|
+
engine: "chatgpt",
|
|
2159
|
+
engineLabel: "ChatGPT"
|
|
2160
|
+
};
|
|
2161
|
+
if ((await connection.status()).signedIn) return {
|
|
2162
|
+
...base,
|
|
2163
|
+
configured: true
|
|
2164
|
+
};
|
|
2165
|
+
return {
|
|
2166
|
+
...base,
|
|
2167
|
+
configured: false,
|
|
2168
|
+
code: "chatgpt_signed_out",
|
|
2169
|
+
message: "ChatGPT is not signed in.",
|
|
2170
|
+
...action ? { action } : {}
|
|
2171
|
+
};
|
|
2172
|
+
}
|
|
2173
|
+
function cliEngineStatus(tool, found, action) {
|
|
2174
|
+
const label = AGENT_TOOL_INFO[tool].label;
|
|
2175
|
+
const base = {
|
|
2176
|
+
engine: tool,
|
|
2177
|
+
engineLabel: label
|
|
2178
|
+
};
|
|
2179
|
+
if (!found.installed) return {
|
|
2180
|
+
...base,
|
|
2181
|
+
configured: false,
|
|
2182
|
+
code: "agent_cli_missing",
|
|
2183
|
+
message: `${label} is not installed on this computer.`,
|
|
2184
|
+
...action ? { action } : {}
|
|
2185
|
+
};
|
|
2186
|
+
if (found.signedIn !== true) return {
|
|
2187
|
+
...base,
|
|
2188
|
+
configured: false,
|
|
2189
|
+
code: "agent_cli_signed_out",
|
|
2190
|
+
message: `${label} is not signed in.`,
|
|
2191
|
+
...action ? { action } : {}
|
|
2192
|
+
};
|
|
2193
|
+
if (found.ready !== true) return {
|
|
2194
|
+
...base,
|
|
2195
|
+
configured: false,
|
|
2196
|
+
code: "agent_cli_startup",
|
|
2197
|
+
...found.startError ? { startError: found.startError } : {},
|
|
2198
|
+
message: found.startError === "tool_host_policy" ? `${label} cannot start the app tool host with this Codex version. Update Codex, then check again in AI settings.` : found.startError === "working_directory" ? `${label} needs a writable temporary directory.` : found.startError === "runtime_unavailable" ? `${label} cannot start in this app's process environment. Check its executable and Node installation.` : `${label} does not accept the required locked-down invocation. Update the CLI, then retry.`,
|
|
2199
|
+
...action ? { action } : {}
|
|
2200
|
+
};
|
|
2201
|
+
return {
|
|
2202
|
+
...base,
|
|
2203
|
+
configured: true
|
|
2204
|
+
};
|
|
2205
|
+
}
|
|
2206
|
+
async function inferenceEngineStatus(engine, host) {
|
|
2207
|
+
const tool = cliTool(engine);
|
|
2208
|
+
if (tool) return cliEngineStatus(tool, await host.cliStatus(tool), host.actions?.cli);
|
|
2209
|
+
if (engine === "chatgpt") return chatgptEngineStatus(host.chatgpt, host.actions?.chatgpt);
|
|
2210
|
+
const api = await host.apiStatus();
|
|
2211
|
+
return {
|
|
2212
|
+
...api,
|
|
2213
|
+
engine: "api",
|
|
2214
|
+
engineLabel: engineLabel("api"),
|
|
2215
|
+
...!api.configured && host.actions?.api ? { action: host.actions.api } : {}
|
|
2216
|
+
};
|
|
2217
|
+
}
|
|
2218
|
+
//#endregion
|
|
119
2219
|
//#region src/settings/override-service.ts
|
|
120
2220
|
var InferenceOverrideAuthorizationError = class extends Error {
|
|
121
2221
|
constructor(request) {
|
|
@@ -350,153 +2450,19 @@ async function buildInferenceOverrideLayers(rows, tenantTargetPolicy) {
|
|
|
350
2450
|
if (value === null) continue;
|
|
351
2451
|
let allowList = null;
|
|
352
2452
|
try {
|
|
353
|
-
allowList = appRows.get(binding)?.getTenantAllowList() ?? null;
|
|
354
|
-
} catch {
|
|
355
|
-
allowList = null;
|
|
356
|
-
}
|
|
357
|
-
if (await isTenantValueAllowed(binding, value, tenantId, allowList, options.tenantTargetPolicy)) allowedTenant.add(binding);
|
|
358
|
-
else blocked.push(binding);
|
|
359
|
-
}
|
|
360
|
-
return {
|
|
361
|
-
app,
|
|
362
|
-
tenant: layerFromRows(tenantRows, (binding) => allowedTenant.has(binding)),
|
|
363
|
-
blockedTenantBindings: blocked.sort(),
|
|
364
|
-
appRows,
|
|
365
|
-
tenantRows
|
|
366
|
-
};
|
|
367
|
-
}
|
|
368
|
-
//#endregion
|
|
369
|
-
//#region src/settings/preferences.ts
|
|
370
|
-
var INFERENCE_PREFERENCE_KIND = "inference";
|
|
371
|
-
var INFERENCE_PREFERENCE_SURFACE = "default";
|
|
372
|
-
var CUSTOMIZE_INFERENCE_PERMISSION = "inference.customize";
|
|
373
|
-
var PERSONALIZE_INFERENCE_PERMISSION = "inference.personalize";
|
|
374
|
-
var INFERENCE_PERMISSION_DEFINITIONS = [{
|
|
375
|
-
slug: CUSTOMIZE_INFERENCE_PERMISSION,
|
|
376
|
-
category: "inference",
|
|
377
|
-
name: "Customize Inference",
|
|
378
|
-
description: "Change the default inference mode, provider and model everyone in the tenant uses"
|
|
379
|
-
}, {
|
|
380
|
-
slug: PERSONALIZE_INFERENCE_PERMISSION,
|
|
381
|
-
category: "inference",
|
|
382
|
-
name: "Personalize Inference",
|
|
383
|
-
description: "Keep a personal inference mode, provider and model on top of the tenant default"
|
|
384
|
-
}];
|
|
385
|
-
var PROVIDER_PATTERN = /^[a-z0-9][a-z0-9._-]{0,63}$/i;
|
|
386
|
-
var MODEL_PATTERN = /^[!-~\u00a1-\uffff]{1,200}$/;
|
|
387
|
-
function issue(path, message) {
|
|
388
|
-
return {
|
|
389
|
-
path,
|
|
390
|
-
code: "invalid_setting",
|
|
391
|
-
message
|
|
392
|
-
};
|
|
393
|
-
}
|
|
394
|
-
function validBaseUrl(value) {
|
|
395
|
-
try {
|
|
396
|
-
const url = new URL(value);
|
|
397
|
-
return (url.protocol === "https:" || url.protocol === "http:") && !url.username && !url.password && !url.search && !url.hash;
|
|
398
|
-
} catch {
|
|
399
|
-
return false;
|
|
400
|
-
}
|
|
401
|
-
}
|
|
402
|
-
function validateInferencePreferences(payload) {
|
|
403
|
-
if (payload === null || payload === void 0) return {
|
|
404
|
-
ok: true,
|
|
405
|
-
canonical: null,
|
|
406
|
-
issues: []
|
|
407
|
-
};
|
|
408
|
-
if (typeof payload !== "object" || Array.isArray(payload)) return {
|
|
409
|
-
ok: false,
|
|
410
|
-
canonical: null,
|
|
411
|
-
issues: [issue("", "inference preferences are an object")]
|
|
412
|
-
};
|
|
413
|
-
const keyMember = findKeyMember(payload);
|
|
414
|
-
if (keyMember) return {
|
|
415
|
-
ok: false,
|
|
416
|
-
canonical: null,
|
|
417
|
-
issues: [issue(keyMember, "keys are never stored as preferences; they go to smrt-secrets")]
|
|
418
|
-
};
|
|
419
|
-
const input = payload;
|
|
420
|
-
const issues = [];
|
|
421
|
-
const canonical = {};
|
|
422
|
-
for (const [member, value] of Object.entries(input)) {
|
|
423
|
-
if (value === void 0 || value === null || value === "") continue;
|
|
424
|
-
switch (member) {
|
|
425
|
-
case "mode":
|
|
426
|
-
if (INFERENCE_MODES.includes(value)) canonical.mode = value;
|
|
427
|
-
else issues.push(issue(member, `mode is one of ${INFERENCE_MODES.join(", ")}`));
|
|
428
|
-
break;
|
|
429
|
-
case "provider":
|
|
430
|
-
if (typeof value === "string" && PROVIDER_PATTERN.test(value)) canonical.provider = value;
|
|
431
|
-
else issues.push(issue(member, "invalid provider id"));
|
|
432
|
-
break;
|
|
433
|
-
case "baseUrl":
|
|
434
|
-
if (typeof value === "string" && validBaseUrl(value)) canonical.baseUrl = value;
|
|
435
|
-
else issues.push(issue(member, "the base URL is an http(s) URL without credentials, query or fragment"));
|
|
436
|
-
break;
|
|
437
|
-
case "model":
|
|
438
|
-
if (typeof value === "string" && MODEL_PATTERN.test(value)) canonical.model = value;
|
|
439
|
-
else issues.push(issue(member, "invalid model id"));
|
|
440
|
-
break;
|
|
441
|
-
case "defaultTier":
|
|
442
|
-
if (isInferenceTier(value)) canonical.defaultTier = value;
|
|
443
|
-
else issues.push(issue(member, `the default tier is one of ${INFERENCE_TIERS.join(", ")}`));
|
|
444
|
-
break;
|
|
445
|
-
default: issues.push(issue(member, "unknown inference preference"));
|
|
2453
|
+
allowList = appRows.get(binding)?.getTenantAllowList() ?? null;
|
|
2454
|
+
} catch {
|
|
2455
|
+
allowList = null;
|
|
446
2456
|
}
|
|
2457
|
+
if (await isTenantValueAllowed(binding, value, tenantId, allowList, options.tenantTargetPolicy)) allowedTenant.add(binding);
|
|
2458
|
+
else blocked.push(binding);
|
|
447
2459
|
}
|
|
448
2460
|
return {
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
var inferencePreferenceKind = {
|
|
455
|
-
kind: INFERENCE_PREFERENCE_KIND,
|
|
456
|
-
formatVersion: 1,
|
|
457
|
-
permissions: {
|
|
458
|
-
tenant: CUSTOMIZE_INFERENCE_PERMISSION,
|
|
459
|
-
user: PERSONALIZE_INFERENCE_PERMISSION
|
|
460
|
-
},
|
|
461
|
-
validate(payload) {
|
|
462
|
-
return validateInferencePreferences(payload);
|
|
463
|
-
}
|
|
464
|
-
};
|
|
465
|
-
function createInferencePreferences(store, surfaceId = INFERENCE_PREFERENCE_SURFACE) {
|
|
466
|
-
return {
|
|
467
|
-
async read() {
|
|
468
|
-
const state = await store.load(INFERENCE_PREFERENCE_KIND, surfaceId);
|
|
469
|
-
const tenant = state.tenant.payload ?? null;
|
|
470
|
-
const user = state.user?.payload ?? null;
|
|
471
|
-
return {
|
|
472
|
-
choices: {
|
|
473
|
-
...tenant ?? {},
|
|
474
|
-
...user ?? {}
|
|
475
|
-
},
|
|
476
|
-
tenant,
|
|
477
|
-
user,
|
|
478
|
-
revisions: {
|
|
479
|
-
tenant: state.tenant.revision,
|
|
480
|
-
user: state.user?.revision ?? null
|
|
481
|
-
},
|
|
482
|
-
issues: state.issues,
|
|
483
|
-
canCustomize: state.canCustomize
|
|
484
|
-
};
|
|
485
|
-
},
|
|
486
|
-
/** Save choices at a scope (default `user`); `revision` is the one the client loaded. */
|
|
487
|
-
write(choices, options) {
|
|
488
|
-
return store.save(INFERENCE_PREFERENCE_KIND, surfaceId, {
|
|
489
|
-
scope: options.scope ?? "user",
|
|
490
|
-
payload: choices,
|
|
491
|
-
revision: options.revision
|
|
492
|
-
});
|
|
493
|
-
},
|
|
494
|
-
reset(options = {}) {
|
|
495
|
-
return store.reset(INFERENCE_PREFERENCE_KIND, surfaceId, {
|
|
496
|
-
scope: options.scope ?? "user",
|
|
497
|
-
revision: options.revision
|
|
498
|
-
});
|
|
499
|
-
}
|
|
2461
|
+
app,
|
|
2462
|
+
tenant: layerFromRows(tenantRows, (binding) => allowedTenant.has(binding)),
|
|
2463
|
+
blockedTenantBindings: blocked.sort(),
|
|
2464
|
+
appRows,
|
|
2465
|
+
tenantRows
|
|
500
2466
|
};
|
|
501
2467
|
}
|
|
502
2468
|
//#endregion
|
|
@@ -562,7 +2528,7 @@ function createInferenceOverrideResolver(options = {}) {
|
|
|
562
2528
|
const getCollection = () => {
|
|
563
2529
|
if (options.overrides) return Promise.resolve(options.overrides);
|
|
564
2530
|
collection ??= InferenceOverrideCollection.create({
|
|
565
|
-
...options.db ?? {},
|
|
2531
|
+
...typeof options.db === "function" ? options.db() : options.db ?? {},
|
|
566
2532
|
defaultListLimit: void 0,
|
|
567
2533
|
maxListLimit: void 0
|
|
568
2534
|
});
|
|
@@ -1133,6 +3099,361 @@ function findKeyLike(candidate) {
|
|
|
1133
3099
|
return typeof candidate.apiKey === "string" && candidate.apiKey.length > 0;
|
|
1134
3100
|
}
|
|
1135
3101
|
//#endregion
|
|
1136
|
-
|
|
3102
|
+
//#region src/settings/host.ts
|
|
3103
|
+
function createInferenceSettingsHost(options) {
|
|
3104
|
+
let secretService;
|
|
3105
|
+
const secrets = () => {
|
|
3106
|
+
secretService ??= (async () => SecretService.create({
|
|
3107
|
+
db: await options.database(),
|
|
3108
|
+
...options.masterKeyProvider ? { masterKeyProvider: options.masterKeyProvider } : {}
|
|
3109
|
+
}))().catch((cause) => {
|
|
3110
|
+
secretService = void 0;
|
|
3111
|
+
throw cause;
|
|
3112
|
+
});
|
|
3113
|
+
return secretService;
|
|
3114
|
+
};
|
|
3115
|
+
const lazySecrets = {
|
|
3116
|
+
retrieve: async (name) => (await secrets()).retrieve(name),
|
|
3117
|
+
store: async (name, value, storeOptions) => (await secrets()).store(name, value, storeOptions),
|
|
3118
|
+
delete: async (name) => (await secrets()).delete(name)
|
|
3119
|
+
};
|
|
3120
|
+
let resolver;
|
|
3121
|
+
const userResolver = () => {
|
|
3122
|
+
resolver ??= createUserInferenceResolver({
|
|
3123
|
+
secrets: lazySecrets,
|
|
3124
|
+
fallback: createInferenceOverrideResolver({ db: options.overrides })
|
|
3125
|
+
});
|
|
3126
|
+
return resolver;
|
|
3127
|
+
};
|
|
3128
|
+
return {
|
|
3129
|
+
secrets,
|
|
3130
|
+
userResolver,
|
|
3131
|
+
install: () => {
|
|
3132
|
+
if (!options.chatgptPlan) return registerUserInferenceResolver(userResolver());
|
|
3133
|
+
setInferenceResolver(createInferenceResolver(createChatGPTPlanResolver({
|
|
3134
|
+
...options.chatgptPlan,
|
|
3135
|
+
fallback: userResolver()
|
|
3136
|
+
})));
|
|
3137
|
+
return userResolver();
|
|
3138
|
+
},
|
|
3139
|
+
settingsService(session, permission) {
|
|
3140
|
+
const authorize = (request) => session.can(permission) && (request.scopeType === "app" || request.scopeId === session.tenantId);
|
|
3141
|
+
return InferenceSettingsService.create(options.overrides(), { authorize });
|
|
3142
|
+
}
|
|
3143
|
+
};
|
|
3144
|
+
}
|
|
3145
|
+
function inferenceSettingsFailure(cause) {
|
|
3146
|
+
const named = cause;
|
|
3147
|
+
if (named?.name === "InferenceOverrideAuthorizationError") return {
|
|
3148
|
+
status: 403,
|
|
3149
|
+
error: "You are not allowed to change this setting."
|
|
3150
|
+
};
|
|
3151
|
+
return {
|
|
3152
|
+
status: typeof named?.status === "number" ? named.status : 400,
|
|
3153
|
+
error: cause instanceof Error ? cause.message : "The change was refused."
|
|
3154
|
+
};
|
|
3155
|
+
}
|
|
3156
|
+
//#endregion
|
|
3157
|
+
//#region src/settings/key-store.ts
|
|
3158
|
+
async function saveInferenceKey(resolver, change, model) {
|
|
3159
|
+
const record = bindInferenceKey(change);
|
|
3160
|
+
await resolver.write("user", inferenceProviderConfigFromKey(record, { model }));
|
|
3161
|
+
}
|
|
3162
|
+
async function inferenceKeyIsSet(resolver) {
|
|
3163
|
+
try {
|
|
3164
|
+
const bindings = await resolver.resolveBindings({ redact: true });
|
|
3165
|
+
const stored = bindings.user ?? bindings.tenant;
|
|
3166
|
+
return Boolean(stored && stored.hasApiKey === true);
|
|
3167
|
+
} catch {
|
|
3168
|
+
return false;
|
|
3169
|
+
}
|
|
3170
|
+
}
|
|
3171
|
+
//#endregion
|
|
3172
|
+
//#region src/settings/preferences.ts
|
|
3173
|
+
var INFERENCE_PREFERENCE_KIND = "inference";
|
|
3174
|
+
var INFERENCE_PREFERENCE_SURFACE = "default";
|
|
3175
|
+
var CUSTOMIZE_INFERENCE_PERMISSION = "inference.customize";
|
|
3176
|
+
var PERSONALIZE_INFERENCE_PERMISSION = "inference.personalize";
|
|
3177
|
+
var INFERENCE_PERMISSION_DEFINITIONS = [{
|
|
3178
|
+
slug: CUSTOMIZE_INFERENCE_PERMISSION,
|
|
3179
|
+
category: "inference",
|
|
3180
|
+
name: "Customize Inference",
|
|
3181
|
+
description: "Change the default inference mode, provider and model everyone in the tenant uses"
|
|
3182
|
+
}, {
|
|
3183
|
+
slug: PERSONALIZE_INFERENCE_PERMISSION,
|
|
3184
|
+
category: "inference",
|
|
3185
|
+
name: "Personalize Inference",
|
|
3186
|
+
description: "Keep a personal inference mode, provider and model on top of the tenant default"
|
|
3187
|
+
}];
|
|
3188
|
+
var PROVIDER_PATTERN = /^[a-z0-9][a-z0-9._-]{0,63}$/i;
|
|
3189
|
+
var MODEL_PATTERN = /^[!-~\u00a1-\uffff]{1,200}$/;
|
|
3190
|
+
function issue(path, message) {
|
|
3191
|
+
return {
|
|
3192
|
+
path,
|
|
3193
|
+
code: "invalid_setting",
|
|
3194
|
+
message
|
|
3195
|
+
};
|
|
3196
|
+
}
|
|
3197
|
+
function validBaseUrl(value) {
|
|
3198
|
+
try {
|
|
3199
|
+
const url = new URL(value);
|
|
3200
|
+
return (url.protocol === "https:" || url.protocol === "http:") && !url.username && !url.password && !url.search && !url.hash;
|
|
3201
|
+
} catch {
|
|
3202
|
+
return false;
|
|
3203
|
+
}
|
|
3204
|
+
}
|
|
3205
|
+
function validateInferencePreferences(payload) {
|
|
3206
|
+
if (payload === null || payload === void 0) return {
|
|
3207
|
+
ok: true,
|
|
3208
|
+
canonical: null,
|
|
3209
|
+
issues: []
|
|
3210
|
+
};
|
|
3211
|
+
if (typeof payload !== "object" || Array.isArray(payload)) return {
|
|
3212
|
+
ok: false,
|
|
3213
|
+
canonical: null,
|
|
3214
|
+
issues: [issue("", "inference preferences are an object")]
|
|
3215
|
+
};
|
|
3216
|
+
const keyMember = findKeyMember(payload);
|
|
3217
|
+
if (keyMember) return {
|
|
3218
|
+
ok: false,
|
|
3219
|
+
canonical: null,
|
|
3220
|
+
issues: [issue(keyMember, "keys are never stored as preferences; they go to smrt-secrets")]
|
|
3221
|
+
};
|
|
3222
|
+
const input = payload;
|
|
3223
|
+
const issues = [];
|
|
3224
|
+
const canonical = {};
|
|
3225
|
+
for (const [member, value] of Object.entries(input)) {
|
|
3226
|
+
if (value === void 0 || value === null || value === "") continue;
|
|
3227
|
+
switch (member) {
|
|
3228
|
+
case "mode":
|
|
3229
|
+
if (INFERENCE_MODES.includes(value)) canonical.mode = value;
|
|
3230
|
+
else issues.push(issue(member, `mode is one of ${INFERENCE_MODES.join(", ")}`));
|
|
3231
|
+
break;
|
|
3232
|
+
case "provider":
|
|
3233
|
+
if (typeof value === "string" && PROVIDER_PATTERN.test(value)) canonical.provider = value;
|
|
3234
|
+
else issues.push(issue(member, "invalid provider id"));
|
|
3235
|
+
break;
|
|
3236
|
+
case "baseUrl":
|
|
3237
|
+
if (typeof value === "string" && validBaseUrl(value)) canonical.baseUrl = value;
|
|
3238
|
+
else issues.push(issue(member, "the base URL is an http(s) URL without credentials, query or fragment"));
|
|
3239
|
+
break;
|
|
3240
|
+
case "model":
|
|
3241
|
+
if (typeof value === "string" && MODEL_PATTERN.test(value)) canonical.model = value;
|
|
3242
|
+
else issues.push(issue(member, "invalid model id"));
|
|
3243
|
+
break;
|
|
3244
|
+
case "defaultTier":
|
|
3245
|
+
if (isInferenceTier(value)) canonical.defaultTier = value;
|
|
3246
|
+
else issues.push(issue(member, `the default tier is one of ${INFERENCE_TIERS.join(", ")}`));
|
|
3247
|
+
break;
|
|
3248
|
+
default: issues.push(issue(member, "unknown inference preference"));
|
|
3249
|
+
}
|
|
3250
|
+
}
|
|
3251
|
+
return {
|
|
3252
|
+
ok: issues.length === 0,
|
|
3253
|
+
canonical: Object.keys(canonical).length > 0 ? canonical : null,
|
|
3254
|
+
issues
|
|
3255
|
+
};
|
|
3256
|
+
}
|
|
3257
|
+
var inferencePreferenceKind = {
|
|
3258
|
+
kind: INFERENCE_PREFERENCE_KIND,
|
|
3259
|
+
formatVersion: 1,
|
|
3260
|
+
permissions: {
|
|
3261
|
+
tenant: CUSTOMIZE_INFERENCE_PERMISSION,
|
|
3262
|
+
user: PERSONALIZE_INFERENCE_PERMISSION
|
|
3263
|
+
},
|
|
3264
|
+
validate(payload) {
|
|
3265
|
+
return validateInferencePreferences(payload);
|
|
3266
|
+
}
|
|
3267
|
+
};
|
|
3268
|
+
function createInferencePreferences(store, surfaceId = INFERENCE_PREFERENCE_SURFACE) {
|
|
3269
|
+
return {
|
|
3270
|
+
async read() {
|
|
3271
|
+
const state = await store.load(INFERENCE_PREFERENCE_KIND, surfaceId);
|
|
3272
|
+
const tenant = state.tenant.payload ?? null;
|
|
3273
|
+
const user = state.user?.payload ?? null;
|
|
3274
|
+
return {
|
|
3275
|
+
choices: {
|
|
3276
|
+
...tenant ?? {},
|
|
3277
|
+
...user ?? {}
|
|
3278
|
+
},
|
|
3279
|
+
tenant,
|
|
3280
|
+
user,
|
|
3281
|
+
revisions: {
|
|
3282
|
+
tenant: state.tenant.revision,
|
|
3283
|
+
user: state.user?.revision ?? null
|
|
3284
|
+
},
|
|
3285
|
+
issues: state.issues,
|
|
3286
|
+
canCustomize: state.canCustomize
|
|
3287
|
+
};
|
|
3288
|
+
},
|
|
3289
|
+
/** Save choices at a scope (default `user`); `revision` is the one the client loaded. */
|
|
3290
|
+
write(choices, options) {
|
|
3291
|
+
return store.save(INFERENCE_PREFERENCE_KIND, surfaceId, {
|
|
3292
|
+
scope: options.scope ?? "user",
|
|
3293
|
+
payload: choices,
|
|
3294
|
+
revision: options.revision
|
|
3295
|
+
});
|
|
3296
|
+
},
|
|
3297
|
+
reset(options = {}) {
|
|
3298
|
+
return store.reset(INFERENCE_PREFERENCE_KIND, surfaceId, {
|
|
3299
|
+
scope: options.scope ?? "user",
|
|
3300
|
+
revision: options.revision
|
|
3301
|
+
});
|
|
3302
|
+
}
|
|
3303
|
+
};
|
|
3304
|
+
}
|
|
3305
|
+
//#endregion
|
|
3306
|
+
//#region src/settings/controller.ts
|
|
3307
|
+
var USAGE_DIMENSIONS = [
|
|
3308
|
+
"model",
|
|
3309
|
+
"tier",
|
|
3310
|
+
"prompt",
|
|
3311
|
+
"fusion",
|
|
3312
|
+
"template"
|
|
3313
|
+
];
|
|
3314
|
+
async function loadPage(options, session, by) {
|
|
3315
|
+
const { host } = options;
|
|
3316
|
+
const settings = await host.settingsService(session, CUSTOMIZE_INFERENCE_PERMISSION);
|
|
3317
|
+
const tenantId = session.tenantId;
|
|
3318
|
+
const requested = (by ?? "").split(",").filter((value) => USAGE_DIMENSIONS.includes(value));
|
|
3319
|
+
const preferences = await createInferencePreferences(await options.preferenceStore()).read();
|
|
3320
|
+
const usage = await settings.usage({
|
|
3321
|
+
by: requested.length > 0 ? requested : ["model"],
|
|
3322
|
+
tenantId
|
|
3323
|
+
}).catch(() => null);
|
|
3324
|
+
return {
|
|
3325
|
+
tenantId,
|
|
3326
|
+
canEdit: session.can(CUSTOMIZE_INFERENCE_PERMISSION),
|
|
3327
|
+
canPersonalize: session.can(PERSONALIZE_INFERENCE_PERMISSION),
|
|
3328
|
+
defaults: {
|
|
3329
|
+
...preferences.choices,
|
|
3330
|
+
keySet: await inferenceKeyIsSet(host.userResolver())
|
|
3331
|
+
},
|
|
3332
|
+
providers: settings.listProviderOptions(),
|
|
3333
|
+
tiers: await settings.listInferenceSettings({ tenantId }),
|
|
3334
|
+
defaultTier: await settings.getDefaultTierSetting({ tenantId }),
|
|
3335
|
+
aliases: await settings.listInferenceAliases(),
|
|
3336
|
+
fusions: await settings.listInferenceFusions(),
|
|
3337
|
+
transcripts: await settings.getTranscriptSettings(),
|
|
3338
|
+
usage
|
|
3339
|
+
};
|
|
3340
|
+
}
|
|
3341
|
+
var NOT_ALLOWED_OUTCOME = {
|
|
3342
|
+
ok: false,
|
|
3343
|
+
status: 403,
|
|
3344
|
+
error: "You are not allowed to change this setting."
|
|
3345
|
+
};
|
|
3346
|
+
function createInferenceSettingsController(options) {
|
|
3347
|
+
const { host } = options;
|
|
3348
|
+
const service = (session) => host.settingsService(session, CUSTOMIZE_INFERENCE_PERMISSION);
|
|
3349
|
+
const scopeOf = (session, scope) => scope === "tenant" ? {
|
|
3350
|
+
scopeType: "tenant",
|
|
3351
|
+
scopeId: session.tenantId
|
|
3352
|
+
} : {
|
|
3353
|
+
scopeType: "app",
|
|
3354
|
+
scopeId: APP_INFERENCE_SCOPE_ID
|
|
3355
|
+
};
|
|
3356
|
+
const write = async (session, run) => {
|
|
3357
|
+
try {
|
|
3358
|
+
await run(await service(session));
|
|
3359
|
+
} catch (cause) {
|
|
3360
|
+
return {
|
|
3361
|
+
ok: false,
|
|
3362
|
+
...inferenceSettingsFailure(cause)
|
|
3363
|
+
};
|
|
3364
|
+
}
|
|
3365
|
+
return {
|
|
3366
|
+
ok: true,
|
|
3367
|
+
message: "Saved."
|
|
3368
|
+
};
|
|
3369
|
+
};
|
|
3370
|
+
const probe = async (session, run) => {
|
|
3371
|
+
try {
|
|
3372
|
+
return {
|
|
3373
|
+
ok: true,
|
|
3374
|
+
result: await run(await service(session))
|
|
3375
|
+
};
|
|
3376
|
+
} catch (cause) {
|
|
3377
|
+
return {
|
|
3378
|
+
ok: false,
|
|
3379
|
+
status: 400,
|
|
3380
|
+
error: inferenceSettingsFailure(cause).error
|
|
3381
|
+
};
|
|
3382
|
+
}
|
|
3383
|
+
};
|
|
3384
|
+
return {
|
|
3385
|
+
canCustomize: (session) => session.can(CUSTOMIZE_INFERENCE_PERMISSION),
|
|
3386
|
+
load: (session, by) => loadPage(options, session, by),
|
|
3387
|
+
async saveDefaults(session, change) {
|
|
3388
|
+
const scope = session.can("inference.customize") ? "tenant" : "user";
|
|
3389
|
+
try {
|
|
3390
|
+
const preferences = createInferencePreferences(await options.preferenceStore());
|
|
3391
|
+
const current = await preferences.read();
|
|
3392
|
+
const result = await preferences.write(change, {
|
|
3393
|
+
scope,
|
|
3394
|
+
revision: current.revisions[scope]
|
|
3395
|
+
});
|
|
3396
|
+
if (!result.ok) return {
|
|
3397
|
+
ok: false,
|
|
3398
|
+
status: result.reason === "not_allowed" ? 403 : 400,
|
|
3399
|
+
error: result.reason === "conflict" ? "These settings changed elsewhere. Reload and try again." : "These choices were refused."
|
|
3400
|
+
};
|
|
3401
|
+
} catch (cause) {
|
|
3402
|
+
return {
|
|
3403
|
+
ok: false,
|
|
3404
|
+
...inferenceSettingsFailure(cause)
|
|
3405
|
+
};
|
|
3406
|
+
}
|
|
3407
|
+
return {
|
|
3408
|
+
ok: true,
|
|
3409
|
+
message: "Saved."
|
|
3410
|
+
};
|
|
3411
|
+
},
|
|
3412
|
+
async saveKey(session, change) {
|
|
3413
|
+
if (!session.can("inference.customize")) return { ...NOT_ALLOWED_OUTCOME };
|
|
3414
|
+
try {
|
|
3415
|
+
const saved = await createInferencePreferences(await options.preferenceStore()).read();
|
|
3416
|
+
await saveInferenceKey(host.userResolver(), change, saved.choices.model);
|
|
3417
|
+
} catch (cause) {
|
|
3418
|
+
return {
|
|
3419
|
+
ok: false,
|
|
3420
|
+
...inferenceSettingsFailure(cause)
|
|
3421
|
+
};
|
|
3422
|
+
}
|
|
3423
|
+
return {
|
|
3424
|
+
ok: true,
|
|
3425
|
+
message: "Saved."
|
|
3426
|
+
};
|
|
3427
|
+
},
|
|
3428
|
+
saveTier: (session, change) => write(session, (settings) => settings.setTierOverride({
|
|
3429
|
+
tier: change.tier,
|
|
3430
|
+
...scopeOf(session, change.scope),
|
|
3431
|
+
target: change.target
|
|
3432
|
+
})),
|
|
3433
|
+
saveDefaultTier: (session, change) => write(session, (settings) => settings.setDefaultTierOverride({
|
|
3434
|
+
...scopeOf(session, change.scope),
|
|
3435
|
+
tier: change.tier
|
|
3436
|
+
})),
|
|
3437
|
+
saveAlias: (session, change) => write(session, (settings) => settings.setAlias({
|
|
3438
|
+
name: change.name,
|
|
3439
|
+
alias: change.candidates === null ? null : {
|
|
3440
|
+
candidates: change.candidates,
|
|
3441
|
+
...change.description ? { description: change.description } : {}
|
|
3442
|
+
}
|
|
3443
|
+
})),
|
|
3444
|
+
saveFusion: (session, change) => write(session, (settings) => settings.setFusion({
|
|
3445
|
+
name: change.name,
|
|
3446
|
+
definition: change.definition
|
|
3447
|
+
})),
|
|
3448
|
+
saveTranscripts: (session, change) => write(session, (settings) => settings.setTranscriptSettings({ settings: change.settings })),
|
|
3449
|
+
testConnection: (session, input) => probe(session, (settings) => settings.testConnection(input)),
|
|
3450
|
+
testCandidate: (session, candidate) => probe(session, (settings) => settings.testCandidate(candidate)),
|
|
3451
|
+
async discoverModels(session) {
|
|
3452
|
+
return { discovered: await (await service(session)).discoverModels() };
|
|
3453
|
+
}
|
|
3454
|
+
};
|
|
3455
|
+
}
|
|
3456
|
+
//#endregion
|
|
3457
|
+
export { AGENT_TOKEN_TTL_SECONDS, AGENT_TOOLS, AGENT_TOOL_INFO, APP_INFERENCE_SCOPE_ID, AgentLogin, CHATGPT_AUTH_HOST, CHATGPT_PLAN_PROVIDER, CHATGPT_SIGN_IN_WINDOW_MS, CUSTOMIZE_INFERENCE_PERMISSION, ChatGPTSignedOutError, DEFAULT_AGENT_LIMITS, DEFAULT_TIER_BINDING, DesignRunConflictError, DesignRunRecord, EngineModelFailure, INFERENCE_MODES, INFERENCE_PERMISSION_DEFINITIONS, INFERENCE_PREFERENCE_KIND, INFERENCE_PREFERENCE_SURFACE, InferenceBindingInUseError, InferenceBindingValueError, InferenceKeyOriginError, InferenceOverride, InferenceOverrideAuthorizationError, InferenceOverrideCollection, InferenceOverrideService, InferenceSettingsConfigError, InferenceSettingsService, InferenceTenantTargetNotAllowedError, InvalidInferenceScopeError, LOGIN_TIMEOUT_MS, MCP_SERVER_NAME, OPENAI_WORK_MODEL_RANKS, PERSONALIZE_INFERENCE_PERMISSION, REDACTED_KEY, TOKEN_ENV, TRANSCRIPTS_BINDING, WORK_MODEL_FALLBACK_MESSAGE, applyStoredTranscriptSettings, assertLoopbackUrl, assertValidInferenceScope, bindInferenceKey, browserCommand, buildAgentRun, buildInferenceOverrideLayers, candidateDirs, chatgptEngineStatus, chatgptFailureNote, childEnv, classifyChatGPTPlanFailure, claudeParser, cliEngineStatus, cliEnv, cliTool, codexParser, createAgentCliService, createChatGPTModel, createChatGPTPlanConnection, createChatGPTPlanResolver, createDesignRunDriver, createDesignRunStore, createInferenceOverrideResolver, createInferencePreferences, createInferenceSettingsController, createInferenceSettingsHost, defaultLocateDeps, describeInferenceTarget, detectAgentCli, detectAgentClis, engineLabel, engineModelReply, inferenceEngineStatus, inferenceKeyFor, inferenceKeyIsSet, inferenceKeyOrigin, inferencePreferenceKind, inferenceProviderConfigFromKey, inferenceSettingsFailure, inferenceTargetRef, installDesignRunExecutor, isAgentTool, isAllowedByList, isChatGPTAuthorizationUrl, killTree, loadInferenceOverrideLayers, loadInferenceTranscriptSettings, locateBinary, locateCli, matchesAllowPattern, mergeSettingsConfigs, nextWorkModel, nodeDir, normalizeTranscriptSettings, openSystemBrowser, parseInferenceBinding, preflightAgentCli, projectWorkModelSelection, rankOpenAIWorkModels, readInferenceOverrideRows, recommendedWorkProfile, redactInferenceSecret, reportAgentFailure, resolveWorkProfile, runAgentTurn, runCollect, runProcess, runWorkModelWithFallback, saveInferenceKey, shellToolName, storedTranscriptSettings, stripKeyMembers, strongestWorkModel, tierBinding, tokenCredentials, tokenFailureMessage, validateInferencePreferences, validateWorkModel };
|
|
1137
3458
|
|
|
1138
3459
|
//# sourceMappingURL=server.js.map
|