@best-agent/cli 0.0.2-beta.8 → 0.0.2-beta.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +44 -181
  3. package/dist/launcher.js +32 -0
  4. package/package.json +15 -27
  5. package/dist/best-agent-native-bridge.d.ts +0 -389
  6. package/dist/best-agent-native-bridge.js +0 -4645
  7. package/dist/cli-storage.d.ts +0 -5
  8. package/dist/cli-storage.js +0 -7
  9. package/dist/dimsdk/ask-user.d.ts +0 -21
  10. package/dist/dimsdk/ask-user.js +0 -131
  11. package/dist/dimsdk/cli/version.d.ts +0 -6
  12. package/dist/dimsdk/cli/version.js +0 -36
  13. package/dist/dimsdk/compat/archships/dim-agent/runtime-host.d.ts +0 -49
  14. package/dist/dimsdk/compat/archships/dim-agent/runtime-host.js +0 -215
  15. package/dist/dimsdk/compat/runtime-host.d.ts +0 -2
  16. package/dist/dimsdk/compat/runtime-host.js +0 -2
  17. package/dist/dimsdk/core/debug-log.d.ts +0 -8
  18. package/dist/dimsdk/core/debug-log.js +0 -100
  19. package/dist/dimsdk/core/env.d.ts +0 -26
  20. package/dist/dimsdk/core/env.js +0 -130
  21. package/dist/dimsdk/core/markdown/sanitize.d.ts +0 -2
  22. package/dist/dimsdk/core/markdown/sanitize.js +0 -43
  23. package/dist/dimsdk/core/markdown/wrap.d.ts +0 -9
  24. package/dist/dimsdk/core/markdown/wrap.js +0 -139
  25. package/dist/dimsdk/core/markdown.d.ts +0 -18
  26. package/dist/dimsdk/core/markdown.js +0 -62
  27. package/dist/dimsdk/core/model.d.ts +0 -273
  28. package/dist/dimsdk/core/model.js +0 -16
  29. package/dist/dimsdk/core/observability/perf-log.d.ts +0 -18
  30. package/dist/dimsdk/core/observability/perf-log.js +0 -236
  31. package/dist/dimsdk/core/store/agent-event-mappers.d.ts +0 -26
  32. package/dist/dimsdk/core/store/agent-event-mappers.js +0 -109
  33. package/dist/dimsdk/core/store/message-mutations.d.ts +0 -105
  34. package/dist/dimsdk/core/store/message-mutations.js +0 -1528
  35. package/dist/dimsdk/core/store/semantic-readers.d.ts +0 -2
  36. package/dist/dimsdk/core/store/semantic-readers.js +0 -4
  37. package/dist/dimsdk/core/store/transcript-projector.d.ts +0 -164
  38. package/dist/dimsdk/core/store/transcript-projector.js +0 -580
  39. package/dist/dimsdk/core/tool-metadata.d.ts +0 -12
  40. package/dist/dimsdk/core/tool-metadata.js +0 -70
  41. package/dist/dimsdk/core/transcript-part-id.d.ts +0 -6
  42. package/dist/dimsdk/core/transcript-part-id.js +0 -22
  43. package/dist/dimsdk/i18n/index.d.ts +0 -18
  44. package/dist/dimsdk/i18n/index.js +0 -141
  45. package/dist/dimsdk/i18n/locales/en.d.ts +0 -988
  46. package/dist/dimsdk/i18n/locales/en.js +0 -987
  47. package/dist/dimsdk/i18n/locales/index.d.ts +0 -1976
  48. package/dist/dimsdk/i18n/locales/index.js +0 -8
  49. package/dist/dimsdk/i18n/locales/zh-CN.d.ts +0 -988
  50. package/dist/dimsdk/i18n/locales/zh-CN.js +0 -987
  51. package/dist/dimsdk/i18n/types.d.ts +0 -13
  52. package/dist/dimsdk/i18n/types.js +0 -2
  53. package/dist/dimsdk/shared/value-normalizers.d.ts +0 -7
  54. package/dist/dimsdk/shared/value-normalizers.js +0 -48
  55. package/dist/dimsdk-tui.bundle-size.json +0 -169
  56. package/dist/dimsdk-tui.bundle.js +0 -330756
  57. package/dist/goatchain-adapter.d.ts +0 -41
  58. package/dist/goatchain-adapter.js +0 -499
  59. package/dist/index.d.ts +0 -3
  60. package/dist/index.js +0 -1405
  61. package/dist/native-runtime-bridge.d.ts +0 -387
  62. package/dist/native-runtime-bridge.js +0 -4624
  63. package/dist/provider-config-env.d.ts +0 -7
  64. package/dist/provider-config-env.js +0 -286
  65. package/dist/provider-model-limit-index.generated.d.ts +0 -3
  66. package/dist/provider-model-limit-index.generated.js +0 -7818
  67. package/dist/provider-model-limits.d.ts +0 -8
  68. package/dist/provider-model-limits.js +0 -43
  69. package/dist/runtime.d.ts +0 -47
  70. package/dist/runtime.js +0 -516
@@ -1,8 +0,0 @@
1
- import { type IndexedProviderAdapter } from "./provider-model-limit-index.generated.js";
2
- export type { IndexedProviderAdapter };
3
- export interface ProviderModelLimit {
4
- context?: number;
5
- output?: number;
6
- }
7
- export declare function inferProviderModelLimit(modelId: string, adapter?: IndexedProviderAdapter, strategy?: "lowest" | "highest"): ProviderModelLimit | undefined;
8
- //# sourceMappingURL=provider-model-limits.d.ts.map
@@ -1,43 +0,0 @@
1
- import { MODEL_LIMIT_INDEX, } from "./provider-model-limit-index.generated.js";
2
- export function inferProviderModelLimit(modelId, adapter, strategy = "highest") {
3
- const normalizedModelId = modelId.trim().toLowerCase();
4
- if (!normalizedModelId) {
5
- return undefined;
6
- }
7
- const adapters = adapter ? [adapter] : Object.keys(MODEL_LIMIT_INDEX);
8
- let bestContext;
9
- let bestOutput;
10
- for (const adapterId of adapters) {
11
- const entry = MODEL_LIMIT_INDEX[adapterId]?.[normalizedModelId];
12
- if (!entry) {
13
- continue;
14
- }
15
- const [minContext, maxContext, minOutput, maxOutput] = entry;
16
- const nextContext = strategy === "lowest" ? minContext : maxContext;
17
- const nextOutput = strategy === "lowest" ? minOutput : maxOutput;
18
- if (nextContext > 0) {
19
- bestContext =
20
- bestContext == null
21
- ? nextContext
22
- : strategy === "lowest"
23
- ? Math.min(bestContext, nextContext)
24
- : Math.max(bestContext, nextContext);
25
- }
26
- if (nextOutput > 0) {
27
- bestOutput =
28
- bestOutput == null
29
- ? nextOutput
30
- : strategy === "lowest"
31
- ? Math.min(bestOutput, nextOutput)
32
- : Math.max(bestOutput, nextOutput);
33
- }
34
- }
35
- if (bestContext == null && bestOutput == null) {
36
- return undefined;
37
- }
38
- return {
39
- ...(bestContext != null ? { context: bestContext } : {}),
40
- ...(bestOutput != null ? { output: bestOutput } : {}),
41
- };
42
- }
43
- //# sourceMappingURL=provider-model-limits.js.map
package/dist/runtime.d.ts DELETED
@@ -1,47 +0,0 @@
1
- import { AgentRuntime, type ToolDefinition } from "@best-agent/engine";
2
- import { type ExtensionRegistry } from "@best-agent/extensions";
3
- import type { ProviderConfig } from "@best-agent/protocol";
4
- export { resolveCliStorageRoot } from "./cli-storage.js";
5
- export type CliPersistedState = Readonly<{
6
- dimsdk?: {
7
- providerState?: Record<string, unknown>;
8
- };
9
- providerConfig?: ProviderConfig;
10
- }>;
11
- export type CliRuntimeOptions = Readonly<{
12
- approvalTimeoutMs?: number;
13
- cwd?: string;
14
- extensionsRoot?: string;
15
- guardian?: {
16
- enabled?: boolean;
17
- model?: string;
18
- threshold?: number;
19
- timeoutMs?: number;
20
- };
21
- providerConfig?: ProviderConfig;
22
- storageRoot?: string;
23
- }>;
24
- export declare function resolveCliReadableRoots(cwd?: string): string[];
25
- export declare function resolveCliAllowAllShell(): boolean;
26
- export declare function createCliRuntime(options: CliRuntimeOptions, injected?: Readonly<{
27
- persistedState?: CliPersistedState;
28
- }>): Promise<AgentRuntime>;
29
- export declare function readCliPersistedState(storageRoot: string): CliPersistedState | undefined;
30
- export declare function writeCliPersistedState(storageRoot: string, state: CliPersistedState): void;
31
- export declare function hydrateDimSdkProviderSelection(state: {
32
- config: {
33
- model?: unknown;
34
- };
35
- provider: Record<string, unknown>;
36
- }, input: Readonly<{
37
- persistedProviderState?: Record<string, unknown>;
38
- providerConfig?: ProviderConfig;
39
- }>): void;
40
- export declare function resolveProviderConfigFromDimSdkState(state: Readonly<{
41
- config?: {
42
- model?: unknown;
43
- };
44
- provider?: Record<string, unknown>;
45
- }>, fallback?: ProviderConfig): ProviderConfig | undefined;
46
- export declare function loadMcpTools(registry: ExtensionRegistry): ToolDefinition[];
47
- //# sourceMappingURL=runtime.d.ts.map
package/dist/runtime.js DELETED
@@ -1,516 +0,0 @@
1
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
- import { homedir } from "node:os";
3
- import { delimiter, dirname, join, resolve } from "node:path";
4
- import { AgentRuntime, DEFAULT_ALLOWED_TOOLS, LocalSandbox, createCommandToolDefinition, createDefaultRuntimePolicy, createDefaultToolRegistry, createMcpToolDefinition, } from "@best-agent/engine";
5
- import { loadExtensionRegistry, resolveInstalledExtensionSkills, } from "@best-agent/extensions";
6
- import { isRecord, markStartup, withStartupSpan, withStartupSpanAsync, } from "@best-agent/foundation";
7
- import { enrichProviderConfig, parseProviderCompatibilityMode, parseProviderDecisionTransportMode, parseProviderKind, } from "./provider-config-env.js";
8
- import { withPerfSpan, withPerfSpanAsync } from "./dimsdk/core/observability/perf-log.js";
9
- import { resolveCliStorageRoot } from "./cli-storage.js";
10
- export { resolveCliStorageRoot } from "./cli-storage.js";
11
- const PROVIDER_KIND_BY_DIMSDK_ID = {
12
- aihubmix: "aihubmix",
13
- "aihubmix-responses": "aihubmix-responses",
14
- anthropic: "anthropic",
15
- custom: "customProvider",
16
- deepseek: "deepseek",
17
- google: "google",
18
- moonshot: "moonshotai",
19
- "moonshot-ai": "moonshotai",
20
- "dimcode-api-oauth": "customProvider",
21
- "flymux-anthropic": "customProvider",
22
- "flymux-openai": "customProvider",
23
- "xiaomi-token-plan-ams": "customProvider",
24
- "xiaomi-token-plan-cn": "customProvider",
25
- "xiaomi-token-plan-sgp": "customProvider",
26
- openai: "openai",
27
- "openai-responses": "openai-responses",
28
- xai: "xai",
29
- "xai-responses": "xai-responses",
30
- zenmux: "zenmux",
31
- };
32
- const DIMSDK_ID_BY_PROVIDER_KIND = {
33
- aihubmix: "aihubmix",
34
- "aihubmix-responses": "aihubmix-responses",
35
- anthropic: "anthropic",
36
- customProvider: "custom",
37
- deepseek: "deepseek",
38
- google: "google",
39
- moonshotai: "moonshot-ai",
40
- openai: "openai",
41
- "openai-responses": "openai-responses",
42
- xai: "xai",
43
- "xai-responses": "xai-responses",
44
- zenmux: "zenmux",
45
- };
46
- const DEFAULT_WEB_SEARCH_API_ENDPOINT = "https://google.serper.dev/search?format=json";
47
- const DEFAULT_WEB_SEARCH_NUM_RESULTS = 10;
48
- const ALLOW_ALL_SHELL_ENV = "BEST_AGENT_ALLOW_ALL_SHELL";
49
- const EXTRA_READABLE_ROOTS_ENV = "BEST_AGENT_EXTRA_READABLE_ROOTS";
50
- function resolveRuntimeContextTokenBudget() {
51
- const raw = process.env.BEST_AGENT_CONTEXT_TOKEN_BUDGET ?? process.env.DIMCODE_CONTEXT_WINDOW;
52
- if (!raw) {
53
- return undefined;
54
- }
55
- const parsed = Number(raw);
56
- return Number.isFinite(parsed) && parsed >= 256 ? Math.floor(parsed) : undefined;
57
- }
58
- function normalizePlainText(value) {
59
- return String(value ?? "").trim();
60
- }
61
- function normalizeOptionalText(value) {
62
- const next = normalizePlainText(value);
63
- return next || undefined;
64
- }
65
- function parsePositiveInt(value) {
66
- const normalized = normalizePlainText(value);
67
- if (!normalized) {
68
- return undefined;
69
- }
70
- const parsed = Number.parseInt(normalized, 10);
71
- return Number.isFinite(parsed) && parsed > 0 ? parsed : undefined;
72
- }
73
- export function resolveCliReadableRoots(cwd) {
74
- const roots = [resolve(cwd ?? process.cwd())];
75
- const raw = normalizeOptionalText(process.env[EXTRA_READABLE_ROOTS_ENV]);
76
- if (!raw) {
77
- return roots;
78
- }
79
- for (const entry of raw.split(delimiter)) {
80
- const normalized = normalizeOptionalText(entry);
81
- if (!normalized) {
82
- continue;
83
- }
84
- roots.push(resolve(normalized));
85
- }
86
- return Array.from(new Set(roots));
87
- }
88
- export function resolveCliAllowAllShell() {
89
- const raw = normalizePlainText(process.env[ALLOW_ALL_SHELL_ENV]).toLowerCase();
90
- return raw === "1" || raw === "true" || raw === "yes" || raw === "on";
91
- }
92
- function buildCliWebSearchQuery(input) {
93
- const query = normalizePlainText(input.query);
94
- const domains = (input.domains ?? [])
95
- .map((domain) => normalizeOptionalText(domain))
96
- .filter((domain) => Boolean(domain));
97
- if (domains.length === 0) {
98
- return query;
99
- }
100
- if (domains.length === 1) {
101
- return `${query} site:${domains[0]}`;
102
- }
103
- return `${query} (${domains.map((domain) => `site:${domain}`).join(" OR ")})`;
104
- }
105
- function selectCliWebSearchResults(payload) {
106
- if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
107
- return [];
108
- }
109
- const organic = payload.organic;
110
- if (!Array.isArray(organic)) {
111
- return [];
112
- }
113
- return organic.flatMap((entry) => {
114
- if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
115
- return [];
116
- }
117
- const record = entry;
118
- const link = normalizeOptionalText(record.link);
119
- if (!link) {
120
- return [];
121
- }
122
- return [
123
- {
124
- link,
125
- snippet: normalizeOptionalText(record.snippet),
126
- title: normalizeOptionalText(record.title),
127
- },
128
- ];
129
- });
130
- }
131
- function formatCliWebSearchResults(input) {
132
- const lines = [`Search results for "${input.query}" (${input.results.length} found):`];
133
- if (input.results.length === 0) {
134
- lines.push("No results found.");
135
- return lines.join("\n");
136
- }
137
- input.results.forEach((result, index) => {
138
- lines.push(`${index + 1}. ${result.title ?? result.link}`);
139
- lines.push(` URL: ${result.link}`);
140
- if (result.snippet) {
141
- lines.push(` Snippet: ${result.snippet}`);
142
- }
143
- });
144
- return lines.join("\n");
145
- }
146
- async function loadCliWebSearchAdapter() {
147
- const dimcodeHome = String(process.env.DIMCODE_HOME ?? "").trim() || join(homedir(), ".dimcode");
148
- const toolsPath = join(dimcodeHome, "tools.json");
149
- if (!existsSync(toolsPath)) {
150
- return undefined;
151
- }
152
- let settings;
153
- try {
154
- const parsed = JSON.parse(readFileSync(toolsPath, "utf8"));
155
- settings = parsed.settings?.websearch;
156
- }
157
- catch {
158
- return undefined;
159
- }
160
- if (!settings) {
161
- return undefined;
162
- }
163
- const apiEndpoint = normalizeOptionalText(settings.apiEndpoint) ?? DEFAULT_WEB_SEARCH_API_ENDPOINT;
164
- const apiKey = normalizeOptionalText(settings.apiKey);
165
- const numResults = parsePositiveInt(settings.numResults) ?? DEFAULT_WEB_SEARCH_NUM_RESULTS;
166
- return {
167
- webSearchAvailability: () => Boolean(apiKey),
168
- webSearch: async (input) => {
169
- if (!apiKey) {
170
- return "Web search is not available in this runtime. Use fetch-url with a known URL or ask the user for a source.";
171
- }
172
- const limit = Math.min(parsePositiveInt(input.limit) ?? numResults, DEFAULT_WEB_SEARCH_NUM_RESULTS);
173
- const response = await globalThis.fetch(apiEndpoint, {
174
- method: "POST",
175
- headers: {
176
- "Content-Type": "application/json",
177
- "X-API-KEY": apiKey,
178
- },
179
- body: JSON.stringify({
180
- num: limit,
181
- q: buildCliWebSearchQuery(input),
182
- }),
183
- });
184
- if (!response.ok) {
185
- throw new Error(`Web search request failed with ${response.status} ${response.statusText}: ${await response.text()}`);
186
- }
187
- const payload = await response.json();
188
- return formatCliWebSearchResults({
189
- query: normalizePlainText(input.query),
190
- results: selectCliWebSearchResults(payload).slice(0, limit),
191
- });
192
- },
193
- };
194
- }
195
- export async function createCliRuntime(options, injected) {
196
- return await withStartupSpanAsync("cliRuntime.create", undefined, async () => {
197
- return await withPerfSpanAsync("createCliRuntime", undefined, async () => {
198
- const extensionRoot = options.extensionsRoot ?? process.env.BEST_AGENT_EXTENSIONS_ROOT;
199
- const extensionRegistry = withStartupSpan("cliRuntime.loadExtensionRegistry", undefined, () => withPerfSpan("loadExtensionRegistry", undefined, () => loadExtensionRegistry(extensionRoot)));
200
- const commandTools = withStartupSpan("cliRuntime.loadCommandTools", undefined, () => withPerfSpan("loadCommandTools", undefined, () => loadCommandTools(extensionRegistry)));
201
- const mcpTools = withStartupSpan("cliRuntime.loadMcpTools", undefined, () => withPerfSpan("loadMcpTools", undefined, () => loadMcpTools(extensionRegistry)));
202
- const extensionSkills = await withStartupSpanAsync("cliRuntime.loadSkills", `static=${extensionRegistry.getSkills().length} command=${extensionRegistry.getCommandSkills().length}`, () => withPerfSpanAsync("loadSkills", undefined, () => loadSkills(extensionRegistry)));
203
- const storageRoot = withStartupSpan("cliRuntime.resolveStorageRoot", undefined, () => resolveCliStorageRoot(options));
204
- const persistedState = injected?.persistedState ??
205
- withStartupSpan("cliRuntime.readPersistedState", undefined, () => readCliPersistedState(storageRoot));
206
- const providerConfig = options.providerConfig ?? persistedState?.providerConfig;
207
- const normalizedProviderConfig = providerConfig
208
- ? enrichProviderConfig(providerConfig)
209
- : undefined;
210
- const contextTokenBudget = resolveRuntimeContextTokenBudget();
211
- const webSearchAdapter = await withStartupSpanAsync("cliRuntime.loadWebSearchAdapter", undefined, () => withPerfSpanAsync("loadCliWebSearchAdapter", undefined, () => loadCliWebSearchAdapter()));
212
- const agentProfiles = withStartupSpan("cliRuntime.loadAgentProfiles", undefined, () => loadAgentProfiles(extensionRegistry));
213
- const tools = withStartupSpan("cliRuntime.createToolRegistry", undefined, () => createDefaultToolRegistry([...commandTools, ...mcpTools]));
214
- const runtime = withStartupSpan("cliRuntime.instantiateAgentRuntime", `profiles=${agentProfiles.length} skills=${extensionSkills.length} commandTools=${commandTools.length} mcpTools=${mcpTools.length}`, () => new AgentRuntime({
215
- ...options,
216
- providerConfig: normalizedProviderConfig,
217
- storageRoot,
218
- ...(contextTokenBudget ? { memory: { contextTokenBudget } } : {}),
219
- agentProfiles,
220
- policy: createDefaultRuntimePolicy({
221
- allowedTools: [
222
- ...DEFAULT_ALLOWED_TOOLS,
223
- ...commandTools.map((tool) => tool.name),
224
- ...mcpTools.map((tool) => tool.name),
225
- ],
226
- allowAllShell: resolveCliAllowAllShell(),
227
- cwd: options.cwd,
228
- readableRoots: resolveCliReadableRoots(options.cwd),
229
- writableRoots: [`${storageRoot}/threads`],
230
- }),
231
- skills: extensionSkills,
232
- tools,
233
- ...(webSearchAdapter
234
- ? {
235
- webSearch: webSearchAdapter.webSearch,
236
- webSearchAvailability: webSearchAdapter.webSearchAvailability,
237
- }
238
- : {}),
239
- }));
240
- markStartup("cliRuntime.ready", `profiles=${agentProfiles.length} skills=${extensionSkills.length} commandTools=${commandTools.length} mcpTools=${mcpTools.length}`);
241
- return runtime;
242
- });
243
- });
244
- }
245
- export function readCliPersistedState(storageRoot) {
246
- const filePath = cliStatePath(storageRoot);
247
- if (!existsSync(filePath)) {
248
- return undefined;
249
- }
250
- try {
251
- const parsed = JSON.parse(readFileSync(filePath, "utf8"));
252
- return parseCliPersistedState(parsed);
253
- }
254
- catch { }
255
- return undefined;
256
- }
257
- function parseCliPersistedState(value) {
258
- if (!isRecord(value)) {
259
- return undefined;
260
- }
261
- const dimsdk = parsePersistedDimSdkState(value.dimsdk);
262
- const providerConfig = parsePersistedProviderConfig(value.providerConfig);
263
- return {
264
- ...(dimsdk ? { dimsdk } : {}),
265
- ...(providerConfig ? { providerConfig } : {}),
266
- };
267
- }
268
- function parsePersistedDimSdkState(value) {
269
- if (!isRecord(value)) {
270
- return undefined;
271
- }
272
- return isRecord(value.providerState) ? { providerState: value.providerState } : {};
273
- }
274
- function parsePersistedProviderConfig(value) {
275
- if (!isRecord(value)) {
276
- return undefined;
277
- }
278
- const kind = parseProviderKind(readOptionalString(value.kind));
279
- const model = readOptionalString(value.model);
280
- if (!kind || !model) {
281
- return undefined;
282
- }
283
- const compatibilityMode = parseOptionalPersistedProviderCompatibilityMode(value.compatibilityMode);
284
- const decisionTransport = parseOptionalPersistedProviderDecisionTransport(value.decisionTransport);
285
- if (compatibilityMode === "invalid" || decisionTransport === "invalid") {
286
- return undefined;
287
- }
288
- return enrichProviderConfig({
289
- kind,
290
- model,
291
- apiKey: readOptionalString(value.apiKey),
292
- baseURL: readOptionalString(value.baseURL),
293
- compatibilityMode,
294
- decisionTransport,
295
- maxInputTokens: readOptionalPositiveNumber(value.maxInputTokens),
296
- maxOutputTokens: readOptionalPositiveNumber(value.maxOutputTokens),
297
- systemPrompt: readOptionalString(value.systemPrompt),
298
- timeoutMs: readOptionalPositiveNumber(value.timeoutMs),
299
- });
300
- }
301
- function parseOptionalPersistedProviderCompatibilityMode(value) {
302
- if (value == null) {
303
- return undefined;
304
- }
305
- return parseProviderCompatibilityMode(readOptionalString(value)) ?? "invalid";
306
- }
307
- function parseOptionalPersistedProviderDecisionTransport(value) {
308
- if (value == null) {
309
- return undefined;
310
- }
311
- const raw = readOptionalString(value);
312
- if (!raw) {
313
- return "invalid";
314
- }
315
- try {
316
- return parseProviderDecisionTransportMode(raw);
317
- }
318
- catch {
319
- return "invalid";
320
- }
321
- }
322
- export function writeCliPersistedState(storageRoot, state) {
323
- const filePath = cliStatePath(storageRoot);
324
- mkdirSync(dirname(filePath), { recursive: true });
325
- writeFileSync(filePath, JSON.stringify(state, null, 2));
326
- }
327
- export function hydrateDimSdkProviderSelection(state, input) {
328
- const nextProviderState = input.persistedProviderState
329
- ? cloneJson(input.persistedProviderState)
330
- : input.providerConfig
331
- ? providerStateFromProviderConfig(input.providerConfig)
332
- : undefined;
333
- if (!nextProviderState) {
334
- return;
335
- }
336
- replaceObjectContents(state.provider, nextProviderState);
337
- const activeId = normalizeText(state.provider.activeId);
338
- const activeModelByProvider = asRecord(state.provider.activeModelByProvider);
339
- const nextModel = (activeId ? normalizeText(activeModelByProvider[activeId]) : undefined) ??
340
- input.providerConfig?.model;
341
- if (nextModel) {
342
- state.config.model = nextModel;
343
- }
344
- }
345
- export function resolveProviderConfigFromDimSdkState(state, fallback) {
346
- const providerState = asRecord(state.provider);
347
- const activeId = normalizeText(providerState.activeId);
348
- const activeModelByProvider = asRecord(providerState.activeModelByProvider);
349
- const model = normalizeText(state.config?.model) ??
350
- (activeId ? normalizeText(activeModelByProvider[activeId]) : undefined) ??
351
- normalizeText(fallback?.model);
352
- if (!model) {
353
- return undefined;
354
- }
355
- const customProviders = Array.isArray(providerState.customProviders)
356
- ? providerState.customProviders
357
- : [];
358
- const customProvider = activeId?.startsWith("cp_")
359
- ? customProviders.find((candidate) => normalizeText(candidate?.id) === activeId)
360
- : undefined;
361
- const customConfig = asRecord(customProvider);
362
- const legacyCustom = asRecord(providerState.custom);
363
- const connections = asRecord(providerState.connections);
364
- const connection = (activeId === "custom" ? legacyCustom : activeId ? asRecord(connections[activeId]) : {});
365
- const adapter = normalizeText(customConfig.adapter);
366
- const kind = resolveProviderKind(activeId, adapter, fallback?.kind);
367
- if (!kind) {
368
- return fallback ? { ...fallback, model } : undefined;
369
- }
370
- const baseURL = normalizeText(customConfig.baseUrl) ??
371
- normalizeText(connection.baseUrl) ??
372
- normalizeText(legacyCustom.baseUrl) ??
373
- normalizeText(fallback?.baseURL);
374
- const apiKey = normalizeText(customConfig.apiKey) ??
375
- normalizeText(connection.apiKey) ??
376
- normalizeText(legacyCustom.apiKey) ??
377
- normalizeText(fallback?.apiKey);
378
- const nextConfig = {
379
- compatibilityMode: fallback?.compatibilityMode,
380
- kind,
381
- model,
382
- ...(typeof fallback?.maxInputTokens === "number"
383
- ? { maxInputTokens: fallback.maxInputTokens }
384
- : {}),
385
- ...(typeof fallback?.maxOutputTokens === "number"
386
- ? { maxOutputTokens: fallback.maxOutputTokens }
387
- : {}),
388
- systemPrompt: fallback?.systemPrompt,
389
- timeoutMs: fallback?.timeoutMs,
390
- };
391
- if (apiKey) {
392
- nextConfig.apiKey = apiKey;
393
- }
394
- if (baseURL) {
395
- nextConfig.baseURL = baseURL;
396
- }
397
- return enrichProviderConfig(nextConfig);
398
- }
399
- function providerStateFromProviderConfig(providerConfig) {
400
- const providerId = DIMSDK_ID_BY_PROVIDER_KIND[providerConfig.kind];
401
- const activeModelByProvider = providerId ? { [providerId]: providerConfig.model } : {};
402
- if (providerConfig.kind === "customProvider") {
403
- return {
404
- activeId: "custom",
405
- activeModelByProvider,
406
- connections: {},
407
- custom: {
408
- apiKey: providerConfig.apiKey,
409
- baseUrl: providerConfig.baseURL,
410
- models: providerConfig.model ? [{ id: providerConfig.model }] : [],
411
- },
412
- customProviders: [],
413
- };
414
- }
415
- return {
416
- activeId: providerId,
417
- activeModelByProvider,
418
- connections: providerId
419
- ? {
420
- [providerId]: {
421
- apiKey: providerConfig.apiKey,
422
- baseUrl: providerConfig.baseURL,
423
- },
424
- }
425
- : {},
426
- custom: {
427
- apiKey: undefined,
428
- baseUrl: undefined,
429
- models: [],
430
- },
431
- customProviders: [],
432
- };
433
- }
434
- function resolveProviderKind(providerId, adapter, fallback) {
435
- if (providerId?.startsWith("cp_")) {
436
- return PROVIDER_KIND_BY_DIMSDK_ID[adapter ?? ""] ?? fallback ?? "customProvider";
437
- }
438
- return (PROVIDER_KIND_BY_DIMSDK_ID[providerId ?? ""] ??
439
- PROVIDER_KIND_BY_DIMSDK_ID[adapter ?? ""] ??
440
- fallback);
441
- }
442
- function replaceObjectContents(target, source) {
443
- for (const key of Object.keys(target)) {
444
- delete target[key];
445
- }
446
- Object.assign(target, source);
447
- }
448
- function asRecord(value) {
449
- if (!value || typeof value !== "object" || Array.isArray(value)) {
450
- return {};
451
- }
452
- return value;
453
- }
454
- function normalizeText(value) {
455
- return readOptionalString(value);
456
- }
457
- function readOptionalString(value) {
458
- return typeof value === "string" && value.trim().length > 0 ? value.trim() : undefined;
459
- }
460
- function readOptionalPositiveNumber(value) {
461
- return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : undefined;
462
- }
463
- function cloneJson(value) {
464
- return JSON.parse(JSON.stringify(value ?? null));
465
- }
466
- function loadAgentProfiles(registry) {
467
- return registry.getAgentProfiles().map((profile) => ({
468
- allowedTools: profile.allowedTools ?? [],
469
- defaultSkills: (profile.defaultSkills ?? []).map((skillName) => `skill:${profile.sourceExtension}:${skillName}`),
470
- description: profile.description,
471
- name: profile.name,
472
- source: "extension",
473
- systemPrompt: profile.systemPrompt,
474
- }));
475
- }
476
- async function loadSkills(registry) {
477
- return (await resolveInstalledExtensionSkills(registry, async ({ args, command, cwd }) => new LocalSandbox().runCommand([command, ...args], cwd))).map((skill) => ({
478
- allowedTools: skill.allowedTools,
479
- content: skill.content,
480
- contextMode: skill.contextMode,
481
- description: skill.description,
482
- effort: skill.effort,
483
- executionMode: skill.executionMode,
484
- id: `skill:${skill.sourceExtension}:${skill.name}`,
485
- model: skill.model,
486
- name: skill.name,
487
- pathScope: skill.pathScope,
488
- source: "extension",
489
- sourceExtension: skill.sourceExtension,
490
- whenToUse: skill.whenToUse,
491
- }));
492
- }
493
- export function loadMcpTools(registry) {
494
- return registry.listMcpServers().flatMap((server) => server.tools.map((tool) => createMcpToolDefinition({
495
- args: server.args,
496
- command: server.command,
497
- description: tool.description,
498
- inputSchema: tool.inputSchema,
499
- sourceExtension: server.sourceExtension,
500
- serverName: server.name,
501
- toolName: tool.name,
502
- })));
503
- }
504
- function loadCommandTools(registry) {
505
- return registry.getCommandTools().map((tool) => createCommandToolDefinition({
506
- args: tool.args,
507
- command: tool.command,
508
- description: tool.description,
509
- extensionName: tool.sourceExtension,
510
- toolName: tool.name,
511
- }));
512
- }
513
- function cliStatePath(storageRoot) {
514
- return join(storageRoot, "cli-state.json");
515
- }
516
- //# sourceMappingURL=runtime.js.map