@mariozechner/pi-coding-agent 0.7.11 → 0.7.13
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/CHANGELOG.md +27 -0
- package/README.md +135 -3
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +207 -60
- package/dist/main.js.map +1 -1
- package/dist/model-config.d.ts +35 -0
- package/dist/model-config.d.ts.map +1 -0
- package/dist/model-config.js +223 -0
- package/dist/model-config.js.map +1 -0
- package/dist/settings-manager.d.ts +7 -0
- package/dist/settings-manager.d.ts.map +1 -1
- package/dist/settings-manager.js +19 -0
- package/dist/settings-manager.js.map +1 -1
- package/dist/tui/footer.d.ts.map +1 -1
- package/dist/tui/footer.js +2 -2
- package/dist/tui/footer.js.map +1 -1
- package/dist/tui/model-selector.d.ts +5 -2
- package/dist/tui/model-selector.d.ts.map +1 -1
- package/dist/tui/model-selector.js +36 -19
- package/dist/tui/model-selector.js.map +1 -1
- package/dist/tui/tui-renderer.d.ts +4 -1
- package/dist/tui/tui-renderer.d.ts.map +1 -1
- package/dist/tui/tui-renderer.js +27 -2
- package/dist/tui/tui-renderer.js.map +1 -1
- package/package.json +3 -3
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
import { getApiKey, getModels, getProviders } from "@mariozechner/pi-ai";
|
|
2
|
+
import { Type } from "@sinclair/typebox";
|
|
3
|
+
import AjvModule from "ajv";
|
|
4
|
+
import { existsSync, readFileSync } from "fs";
|
|
5
|
+
import { homedir } from "os";
|
|
6
|
+
import { join } from "path";
|
|
7
|
+
// Handle both default and named exports
|
|
8
|
+
const Ajv = AjvModule.default || AjvModule;
|
|
9
|
+
// Schema for custom model definition
|
|
10
|
+
const ModelDefinitionSchema = Type.Object({
|
|
11
|
+
id: Type.String({ minLength: 1 }),
|
|
12
|
+
name: Type.String({ minLength: 1 }),
|
|
13
|
+
api: Type.Optional(Type.Union([
|
|
14
|
+
Type.Literal("openai-completions"),
|
|
15
|
+
Type.Literal("openai-responses"),
|
|
16
|
+
Type.Literal("anthropic-messages"),
|
|
17
|
+
Type.Literal("google-generative-ai"),
|
|
18
|
+
])),
|
|
19
|
+
reasoning: Type.Boolean(),
|
|
20
|
+
input: Type.Array(Type.Union([Type.Literal("text"), Type.Literal("image")])),
|
|
21
|
+
cost: Type.Object({
|
|
22
|
+
input: Type.Number(),
|
|
23
|
+
output: Type.Number(),
|
|
24
|
+
cacheRead: Type.Number(),
|
|
25
|
+
cacheWrite: Type.Number(),
|
|
26
|
+
}),
|
|
27
|
+
contextWindow: Type.Number(),
|
|
28
|
+
maxTokens: Type.Number(),
|
|
29
|
+
});
|
|
30
|
+
const ProviderConfigSchema = Type.Object({
|
|
31
|
+
baseUrl: Type.String({ minLength: 1 }),
|
|
32
|
+
apiKey: Type.String({ minLength: 1 }),
|
|
33
|
+
api: Type.Optional(Type.Union([
|
|
34
|
+
Type.Literal("openai-completions"),
|
|
35
|
+
Type.Literal("openai-responses"),
|
|
36
|
+
Type.Literal("anthropic-messages"),
|
|
37
|
+
Type.Literal("google-generative-ai"),
|
|
38
|
+
])),
|
|
39
|
+
models: Type.Array(ModelDefinitionSchema),
|
|
40
|
+
});
|
|
41
|
+
const ModelsConfigSchema = Type.Object({
|
|
42
|
+
providers: Type.Record(Type.String(), ProviderConfigSchema),
|
|
43
|
+
});
|
|
44
|
+
// Custom provider API key mappings (provider name -> apiKey config)
|
|
45
|
+
const customProviderApiKeys = new Map();
|
|
46
|
+
/**
|
|
47
|
+
* Resolve an API key config value to an actual key.
|
|
48
|
+
* First checks if it's an environment variable, then treats as literal.
|
|
49
|
+
*/
|
|
50
|
+
export function resolveApiKey(keyConfig) {
|
|
51
|
+
// First check if it's an env var name
|
|
52
|
+
const envValue = process.env[keyConfig];
|
|
53
|
+
if (envValue)
|
|
54
|
+
return envValue;
|
|
55
|
+
// Otherwise treat as literal API key
|
|
56
|
+
return keyConfig;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Load custom models from ~/.pi/agent/models.json
|
|
60
|
+
* Returns { models, error } - either models array or error message
|
|
61
|
+
*/
|
|
62
|
+
function loadCustomModels() {
|
|
63
|
+
const configPath = join(homedir(), ".pi", "agent", "models.json");
|
|
64
|
+
if (!existsSync(configPath)) {
|
|
65
|
+
return { models: [], error: null };
|
|
66
|
+
}
|
|
67
|
+
try {
|
|
68
|
+
const content = readFileSync(configPath, "utf-8");
|
|
69
|
+
const config = JSON.parse(content);
|
|
70
|
+
// Validate schema
|
|
71
|
+
const ajv = new Ajv();
|
|
72
|
+
const validate = ajv.compile(ModelsConfigSchema);
|
|
73
|
+
if (!validate(config)) {
|
|
74
|
+
const errors = validate.errors?.map((e) => ` - ${e.instancePath || "root"}: ${e.message}`).join("\n") ||
|
|
75
|
+
"Unknown schema error";
|
|
76
|
+
return {
|
|
77
|
+
models: [],
|
|
78
|
+
error: `Invalid models.json schema:\n${errors}\n\nFile: ${configPath}`,
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
// Additional validation
|
|
82
|
+
try {
|
|
83
|
+
validateConfig(config);
|
|
84
|
+
}
|
|
85
|
+
catch (error) {
|
|
86
|
+
return {
|
|
87
|
+
models: [],
|
|
88
|
+
error: `Invalid models.json: ${error instanceof Error ? error.message : error}\n\nFile: ${configPath}`,
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
// Parse models
|
|
92
|
+
return { models: parseModels(config), error: null };
|
|
93
|
+
}
|
|
94
|
+
catch (error) {
|
|
95
|
+
if (error instanceof SyntaxError) {
|
|
96
|
+
return {
|
|
97
|
+
models: [],
|
|
98
|
+
error: `Failed to parse models.json: ${error.message}\n\nFile: ${configPath}`,
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
return {
|
|
102
|
+
models: [],
|
|
103
|
+
error: `Failed to load models.json: ${error instanceof Error ? error.message : error}\n\nFile: ${configPath}`,
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Validate config structure and requirements
|
|
109
|
+
*/
|
|
110
|
+
function validateConfig(config) {
|
|
111
|
+
for (const [providerName, providerConfig] of Object.entries(config.providers)) {
|
|
112
|
+
const hasProviderApi = !!providerConfig.api;
|
|
113
|
+
for (const modelDef of providerConfig.models) {
|
|
114
|
+
const hasModelApi = !!modelDef.api;
|
|
115
|
+
if (!hasProviderApi && !hasModelApi) {
|
|
116
|
+
throw new Error(`Provider ${providerName}, model ${modelDef.id}: no "api" specified. ` +
|
|
117
|
+
`Set at provider or model level.`);
|
|
118
|
+
}
|
|
119
|
+
// Validate required fields
|
|
120
|
+
if (!modelDef.id)
|
|
121
|
+
throw new Error(`Provider ${providerName}: model missing "id"`);
|
|
122
|
+
if (!modelDef.name)
|
|
123
|
+
throw new Error(`Provider ${providerName}: model missing "name"`);
|
|
124
|
+
if (modelDef.contextWindow <= 0)
|
|
125
|
+
throw new Error(`Provider ${providerName}, model ${modelDef.id}: invalid contextWindow`);
|
|
126
|
+
if (modelDef.maxTokens <= 0)
|
|
127
|
+
throw new Error(`Provider ${providerName}, model ${modelDef.id}: invalid maxTokens`);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Parse config into Model objects
|
|
133
|
+
*/
|
|
134
|
+
function parseModels(config) {
|
|
135
|
+
const models = [];
|
|
136
|
+
// Clear and rebuild custom provider API key mappings
|
|
137
|
+
customProviderApiKeys.clear();
|
|
138
|
+
for (const [providerName, providerConfig] of Object.entries(config.providers)) {
|
|
139
|
+
// Store API key config for this provider
|
|
140
|
+
customProviderApiKeys.set(providerName, providerConfig.apiKey);
|
|
141
|
+
for (const modelDef of providerConfig.models) {
|
|
142
|
+
// Model-level api overrides provider-level api
|
|
143
|
+
const api = modelDef.api || providerConfig.api;
|
|
144
|
+
if (!api) {
|
|
145
|
+
// This should have been caught by validateConfig, but be safe
|
|
146
|
+
continue;
|
|
147
|
+
}
|
|
148
|
+
models.push({
|
|
149
|
+
id: modelDef.id,
|
|
150
|
+
name: modelDef.name,
|
|
151
|
+
api: api,
|
|
152
|
+
provider: providerName,
|
|
153
|
+
baseUrl: providerConfig.baseUrl,
|
|
154
|
+
reasoning: modelDef.reasoning,
|
|
155
|
+
input: modelDef.input,
|
|
156
|
+
cost: modelDef.cost,
|
|
157
|
+
contextWindow: modelDef.contextWindow,
|
|
158
|
+
maxTokens: modelDef.maxTokens,
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
return models;
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* Get all models (built-in + custom), freshly loaded
|
|
166
|
+
* Returns { models, error } - either models array or error message
|
|
167
|
+
*/
|
|
168
|
+
export function loadAndMergeModels() {
|
|
169
|
+
const builtInModels = [];
|
|
170
|
+
const providers = getProviders();
|
|
171
|
+
// Load all built-in models
|
|
172
|
+
for (const provider of providers) {
|
|
173
|
+
const providerModels = getModels(provider);
|
|
174
|
+
builtInModels.push(...providerModels);
|
|
175
|
+
}
|
|
176
|
+
// Load custom models
|
|
177
|
+
const { models: customModels, error } = loadCustomModels();
|
|
178
|
+
if (error) {
|
|
179
|
+
return { models: [], error };
|
|
180
|
+
}
|
|
181
|
+
// Merge: custom models come after built-in
|
|
182
|
+
return { models: [...builtInModels, ...customModels], error: null };
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* Get API key for a model (checks custom providers first, then built-in)
|
|
186
|
+
*/
|
|
187
|
+
export function getApiKeyForModel(model) {
|
|
188
|
+
// For custom providers, check their apiKey config
|
|
189
|
+
const customKeyConfig = customProviderApiKeys.get(model.provider);
|
|
190
|
+
if (customKeyConfig) {
|
|
191
|
+
return resolveApiKey(customKeyConfig);
|
|
192
|
+
}
|
|
193
|
+
// For built-in providers, use getApiKey from @mariozechner/pi-ai
|
|
194
|
+
return getApiKey(model.provider);
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* Get only models that have valid API keys available
|
|
198
|
+
* Returns { models, error } - either models array or error message
|
|
199
|
+
*/
|
|
200
|
+
export function getAvailableModels() {
|
|
201
|
+
const { models: allModels, error } = loadAndMergeModels();
|
|
202
|
+
if (error) {
|
|
203
|
+
return { models: [], error };
|
|
204
|
+
}
|
|
205
|
+
const availableModels = allModels.filter((model) => {
|
|
206
|
+
const apiKey = getApiKeyForModel(model);
|
|
207
|
+
return !!apiKey;
|
|
208
|
+
});
|
|
209
|
+
return { models: availableModels, error: null };
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* Find a specific model by provider and ID
|
|
213
|
+
* Returns { model, error } - either model or error message
|
|
214
|
+
*/
|
|
215
|
+
export function findModel(provider, modelId) {
|
|
216
|
+
const { models: allModels, error } = loadAndMergeModels();
|
|
217
|
+
if (error) {
|
|
218
|
+
return { model: null, error };
|
|
219
|
+
}
|
|
220
|
+
const model = allModels.find((m) => m.provider === provider && m.id === modelId) || null;
|
|
221
|
+
return { model, error: null };
|
|
222
|
+
}
|
|
223
|
+
//# sourceMappingURL=model-config.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"model-config.js","sourceRoot":"","sources":["../src/model-config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAY,SAAS,EAAE,SAAS,EAAE,YAAY,EAAkC,MAAM,qBAAqB,CAAC;AACnH,OAAO,EAAe,IAAI,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,SAAS,MAAM,KAAK,CAAC;AAC5B,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,IAAI,CAAC;AAC9C,OAAO,EAAE,OAAO,EAAE,MAAM,IAAI,CAAC;AAC7B,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAE5B,wCAAwC;AACxC,MAAM,GAAG,GAAI,SAAiB,CAAC,OAAO,IAAI,SAAS,CAAC;AAEpD,qCAAqC;AACrC,MAAM,qBAAqB,GAAG,IAAI,CAAC,MAAM,CAAC;IACzC,EAAE,EAAE,IAAI,CAAC,MAA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,EAAE,KAAK,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC;IAC/B,CAAC;IAED,MAAM,KAAK,GAAG,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,KAAK,QAAQ,IAAI,CAAC,CAAC,EAAE,KAAK,OAAO,CAAC,IAAI,IAAI,CAAC;IACzF,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC;AAAA,CAC9B","sourcesContent":["import { type Api, getApiKey, getModels, getProviders, type KnownProvider, type Model } from \"@mariozechner/pi-ai\";\nimport { type Static, Type } from \"@sinclair/typebox\";\nimport AjvModule from \"ajv\";\nimport { existsSync, readFileSync } from \"fs\";\nimport { homedir } from \"os\";\nimport { join } from \"path\";\n\n// Handle both default and named exports\nconst Ajv = (AjvModule as any).default || AjvModule;\n\n// Schema for custom model definition\nconst ModelDefinitionSchema = Type.Object({\n\tid: Type.String({ minLength: 1 }),\n\tname: Type.String({ minLength: 1 }),\n\tapi: Type.Optional(\n\t\tType.Union([\n\t\t\tType.Literal(\"openai-completions\"),\n\t\t\tType.Literal(\"openai-responses\"),\n\t\t\tType.Literal(\"anthropic-messages\"),\n\t\t\tType.Literal(\"google-generative-ai\"),\n\t\t]),\n\t),\n\treasoning: Type.Boolean(),\n\tinput: Type.Array(Type.Union([Type.Literal(\"text\"), Type.Literal(\"image\")])),\n\tcost: Type.Object({\n\t\tinput: Type.Number(),\n\t\toutput: Type.Number(),\n\t\tcacheRead: Type.Number(),\n\t\tcacheWrite: Type.Number(),\n\t}),\n\tcontextWindow: Type.Number(),\n\tmaxTokens: Type.Number(),\n});\n\nconst ProviderConfigSchema = Type.Object({\n\tbaseUrl: Type.String({ minLength: 1 }),\n\tapiKey: Type.String({ minLength: 1 }),\n\tapi: Type.Optional(\n\t\tType.Union([\n\t\t\tType.Literal(\"openai-completions\"),\n\t\t\tType.Literal(\"openai-responses\"),\n\t\t\tType.Literal(\"anthropic-messages\"),\n\t\t\tType.Literal(\"google-generative-ai\"),\n\t\t]),\n\t),\n\tmodels: Type.Array(ModelDefinitionSchema),\n});\n\nconst ModelsConfigSchema = Type.Object({\n\tproviders: Type.Record(Type.String(), ProviderConfigSchema),\n});\n\ntype ModelsConfig = Static<typeof ModelsConfigSchema>;\ntype ProviderConfig = Static<typeof ProviderConfigSchema>;\ntype ModelDefinition = Static<typeof ModelDefinitionSchema>;\n\n// Custom provider API key mappings (provider name -> apiKey config)\nconst customProviderApiKeys: Map<string, string> = new Map();\n\n/**\n * Resolve an API key config value to an actual key.\n * First checks if it's an environment variable, then treats as literal.\n */\nexport function resolveApiKey(keyConfig: string): string | undefined {\n\t// First check if it's an env var name\n\tconst envValue = process.env[keyConfig];\n\tif (envValue) return envValue;\n\n\t// Otherwise treat as literal API key\n\treturn keyConfig;\n}\n\n/**\n * Load custom models from ~/.pi/agent/models.json\n * Returns { models, error } - either models array or error message\n */\nfunction loadCustomModels(): { models: Model<Api>[]; error: string | null } {\n\tconst configPath = join(homedir(), \".pi\", \"agent\", \"models.json\");\n\tif (!existsSync(configPath)) {\n\t\treturn { models: [], error: null };\n\t}\n\n\ttry {\n\t\tconst content = readFileSync(configPath, \"utf-8\");\n\t\tconst config: ModelsConfig = JSON.parse(content);\n\n\t\t// Validate schema\n\t\tconst ajv = new Ajv();\n\t\tconst validate = ajv.compile(ModelsConfigSchema);\n\t\tif (!validate(config)) {\n\t\t\tconst errors =\n\t\t\t\tvalidate.errors?.map((e: any) => ` - ${e.instancePath || \"root\"}: ${e.message}`).join(\"\\n\") ||\n\t\t\t\t\"Unknown schema error\";\n\t\t\treturn {\n\t\t\t\tmodels: [],\n\t\t\t\terror: `Invalid models.json schema:\\n${errors}\\n\\nFile: ${configPath}`,\n\t\t\t};\n\t\t}\n\n\t\t// Additional validation\n\t\ttry {\n\t\t\tvalidateConfig(config);\n\t\t} catch (error) {\n\t\t\treturn {\n\t\t\t\tmodels: [],\n\t\t\t\terror: `Invalid models.json: ${error instanceof Error ? error.message : error}\\n\\nFile: ${configPath}`,\n\t\t\t};\n\t\t}\n\n\t\t// Parse models\n\t\treturn { models: parseModels(config), error: null };\n\t} catch (error) {\n\t\tif (error instanceof SyntaxError) {\n\t\t\treturn {\n\t\t\t\tmodels: [],\n\t\t\t\terror: `Failed to parse models.json: ${error.message}\\n\\nFile: ${configPath}`,\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\tmodels: [],\n\t\t\terror: `Failed to load models.json: ${error instanceof Error ? error.message : error}\\n\\nFile: ${configPath}`,\n\t\t};\n\t}\n}\n\n/**\n * Validate config structure and requirements\n */\nfunction validateConfig(config: ModelsConfig): void {\n\tfor (const [providerName, providerConfig] of Object.entries(config.providers)) {\n\t\tconst hasProviderApi = !!providerConfig.api;\n\n\t\tfor (const modelDef of providerConfig.models) {\n\t\t\tconst hasModelApi = !!modelDef.api;\n\n\t\t\tif (!hasProviderApi && !hasModelApi) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Provider ${providerName}, model ${modelDef.id}: no \"api\" specified. ` +\n\t\t\t\t\t\t`Set at provider or model level.`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Validate required fields\n\t\t\tif (!modelDef.id) throw new Error(`Provider ${providerName}: model missing \"id\"`);\n\t\t\tif (!modelDef.name) throw new Error(`Provider ${providerName}: model missing \"name\"`);\n\t\t\tif (modelDef.contextWindow <= 0)\n\t\t\t\tthrow new Error(`Provider ${providerName}, model ${modelDef.id}: invalid contextWindow`);\n\t\t\tif (modelDef.maxTokens <= 0)\n\t\t\t\tthrow new Error(`Provider ${providerName}, model ${modelDef.id}: invalid maxTokens`);\n\t\t}\n\t}\n}\n\n/**\n * Parse config into Model objects\n */\nfunction parseModels(config: ModelsConfig): Model<Api>[] {\n\tconst models: Model<Api>[] = [];\n\n\t// Clear and rebuild custom provider API key mappings\n\tcustomProviderApiKeys.clear();\n\n\tfor (const [providerName, providerConfig] of Object.entries(config.providers)) {\n\t\t// Store API key config for this provider\n\t\tcustomProviderApiKeys.set(providerName, providerConfig.apiKey);\n\n\t\tfor (const modelDef of providerConfig.models) {\n\t\t\t// Model-level api overrides provider-level api\n\t\t\tconst api = modelDef.api || providerConfig.api;\n\n\t\t\tif (!api) {\n\t\t\t\t// This should have been caught by validateConfig, but be safe\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tmodels.push({\n\t\t\t\tid: modelDef.id,\n\t\t\t\tname: modelDef.name,\n\t\t\t\tapi: api as Api,\n\t\t\t\tprovider: providerName,\n\t\t\t\tbaseUrl: providerConfig.baseUrl,\n\t\t\t\treasoning: modelDef.reasoning,\n\t\t\t\tinput: modelDef.input as (\"text\" | \"image\")[],\n\t\t\t\tcost: modelDef.cost,\n\t\t\t\tcontextWindow: modelDef.contextWindow,\n\t\t\t\tmaxTokens: modelDef.maxTokens,\n\t\t\t});\n\t\t}\n\t}\n\n\treturn models;\n}\n\n/**\n * Get all models (built-in + custom), freshly loaded\n * Returns { models, error } - either models array or error message\n */\nexport function loadAndMergeModels(): { models: Model<Api>[]; error: string | null } {\n\tconst builtInModels: Model<Api>[] = [];\n\tconst providers = getProviders();\n\n\t// Load all built-in models\n\tfor (const provider of providers) {\n\t\tconst providerModels = getModels(provider as KnownProvider);\n\t\tbuiltInModels.push(...(providerModels as Model<Api>[]));\n\t}\n\n\t// Load custom models\n\tconst { models: customModels, error } = loadCustomModels();\n\n\tif (error) {\n\t\treturn { models: [], error };\n\t}\n\n\t// Merge: custom models come after built-in\n\treturn { models: [...builtInModels, ...customModels], error: null };\n}\n\n/**\n * Get API key for a model (checks custom providers first, then built-in)\n */\nexport function getApiKeyForModel(model: Model<Api>): string | undefined {\n\t// For custom providers, check their apiKey config\n\tconst customKeyConfig = customProviderApiKeys.get(model.provider);\n\tif (customKeyConfig) {\n\t\treturn resolveApiKey(customKeyConfig);\n\t}\n\n\t// For built-in providers, use getApiKey from @mariozechner/pi-ai\n\treturn getApiKey(model.provider as KnownProvider);\n}\n\n/**\n * Get only models that have valid API keys available\n * Returns { models, error } - either models array or error message\n */\nexport function getAvailableModels(): { models: Model<Api>[]; error: string | null } {\n\tconst { models: allModels, error } = loadAndMergeModels();\n\n\tif (error) {\n\t\treturn { models: [], error };\n\t}\n\n\tconst availableModels = allModels.filter((model) => {\n\t\tconst apiKey = getApiKeyForModel(model);\n\t\treturn !!apiKey;\n\t});\n\n\treturn { models: availableModels, error: null };\n}\n\n/**\n * Find a specific model by provider and ID\n * Returns { model, error } - either model or error message\n */\nexport function findModel(provider: string, modelId: string): { model: Model<Api> | null; error: string | null } {\n\tconst { models: allModels, error } = loadAndMergeModels();\n\n\tif (error) {\n\t\treturn { model: null, error };\n\t}\n\n\tconst model = allModels.find((m) => m.provider === provider && m.id === modelId) || null;\n\treturn { model, error: null };\n}\n"]}
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
export interface Settings {
|
|
2
2
|
lastChangelogVersion?: string;
|
|
3
|
+
defaultProvider?: string;
|
|
4
|
+
defaultModel?: string;
|
|
3
5
|
}
|
|
4
6
|
export declare class SettingsManager {
|
|
5
7
|
private settingsPath;
|
|
@@ -9,5 +11,10 @@ export declare class SettingsManager {
|
|
|
9
11
|
private save;
|
|
10
12
|
getLastChangelogVersion(): string | undefined;
|
|
11
13
|
setLastChangelogVersion(version: string): void;
|
|
14
|
+
getDefaultProvider(): string | undefined;
|
|
15
|
+
getDefaultModel(): string | undefined;
|
|
16
|
+
setDefaultProvider(provider: string): void;
|
|
17
|
+
setDefaultModel(modelId: string): void;
|
|
18
|
+
setDefaultModelAndProvider(provider: string, modelId: string): void;
|
|
12
19
|
}
|
|
13
20
|
//# sourceMappingURL=settings-manager.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"settings-manager.d.ts","sourceRoot":"","sources":["../src/settings-manager.ts"],"names":[],"mappings":"AAIA,MAAM,WAAW,QAAQ;IACxB,oBAAoB,CAAC,EAAE,MAAM,CAAC;
|
|
1
|
+
{"version":3,"file":"settings-manager.d.ts","sourceRoot":"","sources":["../src/settings-manager.ts"],"names":[],"mappings":"AAIA,MAAM,WAAW,QAAQ;IACxB,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAC9B,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,YAAY,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,qBAAa,eAAe;IAC3B,OAAO,CAAC,YAAY,CAAS;IAC7B,OAAO,CAAC,QAAQ,CAAW;IAE3B,YAAY,OAAO,CAAC,EAAE,MAAM,EAI3B;IAED,OAAO,CAAC,IAAI;IAcZ,OAAO,CAAC,IAAI;IAcZ,uBAAuB,IAAI,MAAM,GAAG,SAAS,CAE5C;IAED,uBAAuB,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAG7C;IAED,kBAAkB,IAAI,MAAM,GAAG,SAAS,CAEvC;IAED,eAAe,IAAI,MAAM,GAAG,SAAS,CAEpC;IAED,kBAAkB,CAAC,QAAQ,EAAE,MAAM,GAAG,IAAI,CAGzC;IAED,eAAe,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAGrC;IAED,0BAA0B,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,IAAI,CAIlE;CACD","sourcesContent":["import { existsSync, mkdirSync, readFileSync, writeFileSync } from \"fs\";\nimport { homedir } from \"os\";\nimport { dirname, join } from \"path\";\n\nexport interface Settings {\n\tlastChangelogVersion?: string;\n\tdefaultProvider?: string;\n\tdefaultModel?: string;\n}\n\nexport class SettingsManager {\n\tprivate settingsPath: string;\n\tprivate settings: Settings;\n\n\tconstructor(baseDir?: string) {\n\t\tconst dir = baseDir || join(homedir(), \".pi\", \"agent\");\n\t\tthis.settingsPath = join(dir, \"settings.json\");\n\t\tthis.settings = this.load();\n\t}\n\n\tprivate load(): Settings {\n\t\tif (!existsSync(this.settingsPath)) {\n\t\t\treturn {};\n\t\t}\n\n\t\ttry {\n\t\t\tconst content = readFileSync(this.settingsPath, \"utf-8\");\n\t\t\treturn JSON.parse(content);\n\t\t} catch (error) {\n\t\t\tconsole.error(`Warning: Could not read settings file: ${error}`);\n\t\t\treturn {};\n\t\t}\n\t}\n\n\tprivate save(): void {\n\t\ttry {\n\t\t\t// Ensure directory exists\n\t\t\tconst dir = dirname(this.settingsPath);\n\t\t\tif (!existsSync(dir)) {\n\t\t\t\tmkdirSync(dir, { recursive: true });\n\t\t\t}\n\n\t\t\twriteFileSync(this.settingsPath, JSON.stringify(this.settings, null, 2), \"utf-8\");\n\t\t} catch (error) {\n\t\t\tconsole.error(`Warning: Could not save settings file: ${error}`);\n\t\t}\n\t}\n\n\tgetLastChangelogVersion(): string | undefined {\n\t\treturn this.settings.lastChangelogVersion;\n\t}\n\n\tsetLastChangelogVersion(version: string): void {\n\t\tthis.settings.lastChangelogVersion = version;\n\t\tthis.save();\n\t}\n\n\tgetDefaultProvider(): string | undefined {\n\t\treturn this.settings.defaultProvider;\n\t}\n\n\tgetDefaultModel(): string | undefined {\n\t\treturn this.settings.defaultModel;\n\t}\n\n\tsetDefaultProvider(provider: string): void {\n\t\tthis.settings.defaultProvider = provider;\n\t\tthis.save();\n\t}\n\n\tsetDefaultModel(modelId: string): void {\n\t\tthis.settings.defaultModel = modelId;\n\t\tthis.save();\n\t}\n\n\tsetDefaultModelAndProvider(provider: string, modelId: string): void {\n\t\tthis.settings.defaultProvider = provider;\n\t\tthis.settings.defaultModel = modelId;\n\t\tthis.save();\n\t}\n}\n"]}
|
package/dist/settings-manager.js
CHANGED
|
@@ -42,5 +42,24 @@ export class SettingsManager {
|
|
|
42
42
|
this.settings.lastChangelogVersion = version;
|
|
43
43
|
this.save();
|
|
44
44
|
}
|
|
45
|
+
getDefaultProvider() {
|
|
46
|
+
return this.settings.defaultProvider;
|
|
47
|
+
}
|
|
48
|
+
getDefaultModel() {
|
|
49
|
+
return this.settings.defaultModel;
|
|
50
|
+
}
|
|
51
|
+
setDefaultProvider(provider) {
|
|
52
|
+
this.settings.defaultProvider = provider;
|
|
53
|
+
this.save();
|
|
54
|
+
}
|
|
55
|
+
setDefaultModel(modelId) {
|
|
56
|
+
this.settings.defaultModel = modelId;
|
|
57
|
+
this.save();
|
|
58
|
+
}
|
|
59
|
+
setDefaultModelAndProvider(provider, modelId) {
|
|
60
|
+
this.settings.defaultProvider = provider;
|
|
61
|
+
this.settings.defaultModel = modelId;
|
|
62
|
+
this.save();
|
|
63
|
+
}
|
|
45
64
|
}
|
|
46
65
|
//# sourceMappingURL=settings-manager.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"settings-manager.js","sourceRoot":"","sources":["../src/settings-manager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,IAAI,CAAC;AACxE,OAAO,EAAE,OAAO,EAAE,MAAM,IAAI,CAAC;AAC7B,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;
|
|
1
|
+
{"version":3,"file":"settings-manager.js","sourceRoot":"","sources":["../src/settings-manager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,IAAI,CAAC;AACxE,OAAO,EAAE,OAAO,EAAE,MAAM,IAAI,CAAC;AAC7B,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAQrC,MAAM,OAAO,eAAe;IACnB,YAAY,CAAS;IACrB,QAAQ,CAAW;IAE3B,YAAY,OAAgB,EAAE;QAC7B,MAAM,GAAG,GAAG,OAAO,IAAI,IAAI,CAAC,OAAO,EAAE,EAAE,KAAK,EAAE,OAAO,CAAC,CAAC;QACvD,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC,GAAG,EAAE,eAAe,CAAC,CAAC;QAC/C,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC,IAAI,EAAE,CAAC;IAAA,CAC5B;IAEO,IAAI,GAAa;QACxB,IAAI,C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GAAuB;QACrC,OAAO,IAAI,CAAC,QAAQ,CAAC,YAAY,CAAC;IAAA,CAClC;IAED,kBAAkB,CAAC,QAAgB,EAAQ;QAC1C,IAAI,CAAC,QAAQ,CAAC,eAAe,GAAG,QAAQ,CAAC;QACzC,IAAI,CAAC,IAAI,EAAE,CAAC;IAAA,CACZ;IAED,eAAe,CAAC,OAAe,EAAQ;QACtC,IAAI,CAAC,QAAQ,CAAC,YAAY,GAAG,OAAO,CAAC;QACrC,IAAI,CAAC,IAAI,EAAE,CAAC;IAAA,CACZ;IAED,0BAA0B,CAAC,QAAgB,EAAE,OAAe,EAAQ;QACnE,IAAI,CAAC,QAAQ,CAAC,eAAe,GAAG,QAAQ,CAAC;QACzC,IAAI,CAAC,QAAQ,CAAC,YAAY,GAAG,OAAO,CAAC;QACrC,IAAI,CAAC,IAAI,EAAE,CAAC;IAAA,CACZ;CACD","sourcesContent":["import { existsSync, mkdirSync, readFileSync, writeFileSync } from \"fs\";\nimport { homedir } from \"os\";\nimport { dirname, join } from \"path\";\n\nexport interface Settings {\n\tlastChangelogVersion?: string;\n\tdefaultProvider?: string;\n\tdefaultModel?: string;\n}\n\nexport class SettingsManager {\n\tprivate settingsPath: string;\n\tprivate settings: Settings;\n\n\tconstructor(baseDir?: string) {\n\t\tconst dir = baseDir || join(homedir(), \".pi\", \"agent\");\n\t\tthis.settingsPath = join(dir, \"settings.json\");\n\t\tthis.settings = this.load();\n\t}\n\n\tprivate load(): Settings {\n\t\tif (!existsSync(this.settingsPath)) {\n\t\t\treturn {};\n\t\t}\n\n\t\ttry {\n\t\t\tconst content = readFileSync(this.settingsPath, \"utf-8\");\n\t\t\treturn JSON.parse(content);\n\t\t} catch (error) {\n\t\t\tconsole.error(`Warning: Could not read settings file: ${error}`);\n\t\t\treturn {};\n\t\t}\n\t}\n\n\tprivate save(): void {\n\t\ttry {\n\t\t\t// Ensure directory exists\n\t\t\tconst dir = dirname(this.settingsPath);\n\t\t\tif (!existsSync(dir)) {\n\t\t\t\tmkdirSync(dir, { recursive: true });\n\t\t\t}\n\n\t\t\twriteFileSync(this.settingsPath, JSON.stringify(this.settings, null, 2), \"utf-8\");\n\t\t} catch (error) {\n\t\t\tconsole.error(`Warning: Could not save settings file: ${error}`);\n\t\t}\n\t}\n\n\tgetLastChangelogVersion(): string | undefined {\n\t\treturn this.settings.lastChangelogVersion;\n\t}\n\n\tsetLastChangelogVersion(version: string): void {\n\t\tthis.settings.lastChangelogVersion = version;\n\t\tthis.save();\n\t}\n\n\tgetDefaultProvider(): string | undefined {\n\t\treturn this.settings.defaultProvider;\n\t}\n\n\tgetDefaultModel(): string | undefined {\n\t\treturn this.settings.defaultModel;\n\t}\n\n\tsetDefaultProvider(provider: string): void {\n\t\tthis.settings.defaultProvider = provider;\n\t\tthis.save();\n\t}\n\n\tsetDefaultModel(modelId: string): void {\n\t\tthis.settings.defaultModel = modelId;\n\t\tthis.save();\n\t}\n\n\tsetDefaultModelAndProvider(provider: string, modelId: string): void {\n\t\tthis.settings.defaultProvider = provider;\n\t\tthis.settings.defaultModel = modelId;\n\t\tthis.save();\n\t}\n}\n"]}
|
package/dist/tui/footer.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"footer.d.ts","sourceRoot":"","sources":["../../src/tui/footer.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AAKzD;;GAEG;AACH,qBAAa,eAAe;IAC3B,OAAO,CAAC,KAAK,CAAa;IAE1B,YAAY,KAAK,EAAE,UAAU,EAE5B;IAED,WAAW,CAAC,KAAK,EAAE,UAAU,GAAG,IAAI,CAEnC;IAED,MAAM,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE,CAkG9B;CACD","sourcesContent":["import type { AgentState } from \"@mariozechner/pi-agent\";\nimport type { AssistantMessage } from \"@mariozechner/pi-ai\";\nimport { visibleWidth } from \"@mariozechner/pi-tui\";\nimport chalk from \"chalk\";\n\n/**\n * Footer component that shows pwd, token stats, and context usage\n */\nexport class FooterComponent {\n\tprivate state: AgentState;\n\n\tconstructor(state: AgentState) {\n\t\tthis.state = state;\n\t}\n\n\tupdateState(state: AgentState): void {\n\t\tthis.state = state;\n\t}\n\n\trender(width: number): string[] {\n\t\t// Calculate cumulative usage from all assistant messages\n\t\tlet totalInput = 0;\n\t\tlet totalOutput = 0;\n\t\tlet totalCacheRead = 0;\n\t\tlet totalCacheWrite = 0;\n\t\tlet totalCost = 0;\n\n\t\tfor (const message of this.state.messages) {\n\t\t\tif (message.role === \"assistant\") {\n\t\t\t\tconst assistantMsg = message as AssistantMessage;\n\t\t\t\ttotalInput += assistantMsg.usage.input;\n\t\t\t\ttotalOutput += assistantMsg.usage.output;\n\t\t\t\ttotalCacheRead += assistantMsg.usage.cacheRead;\n\t\t\t\ttotalCacheWrite += assistantMsg.usage.cacheWrite;\n\t\t\t\ttotalCost += assistantMsg.usage.cost.total;\n\t\t\t}\n\t\t}\n\n\t\t// Get last assistant message for context percentage calculation (skip aborted messages)\n\t\tconst lastAssistantMessage = this.state.messages\n\t\t\t.slice()\n\t\t\t.reverse()\n\t\t\t.find((m) => m.role === \"assistant\" && m.stopReason !== \"aborted\") as AssistantMessage | undefined;\n\n\t\t// Calculate context percentage from last message (input + output + cacheRead + cacheWrite)\n\t\tconst contextTokens = lastAssistantMessage\n\t\t\t? lastAssistantMessage.usage.input +\n\t\t\t\tlastAssistantMessage.usage.output +\n\t\t\t\tlastAssistantMessage.usage.cacheRead +\n\t\t\t\tlastAssistantMessage.usage.cacheWrite\n\t\t\t: 0;\n\t\tconst contextWindow = this.state.model
|
|
1
|
+
{"version":3,"file":"footer.d.ts","sourceRoot":"","sources":["../../src/tui/footer.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AAKzD;;GAEG;AACH,qBAAa,eAAe;IAC3B,OAAO,CAAC,KAAK,CAAa;IAE1B,YAAY,KAAK,EAAE,UAAU,EAE5B;IAED,WAAW,CAAC,KAAK,EAAE,UAAU,GAAG,IAAI,CAEnC;IAED,MAAM,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE,CAkG9B;CACD","sourcesContent":["import type { AgentState } from \"@mariozechner/pi-agent\";\nimport type { AssistantMessage } from \"@mariozechner/pi-ai\";\nimport { visibleWidth } from \"@mariozechner/pi-tui\";\nimport chalk from \"chalk\";\n\n/**\n * Footer component that shows pwd, token stats, and context usage\n */\nexport class FooterComponent {\n\tprivate state: AgentState;\n\n\tconstructor(state: AgentState) {\n\t\tthis.state = state;\n\t}\n\n\tupdateState(state: AgentState): void {\n\t\tthis.state = state;\n\t}\n\n\trender(width: number): string[] {\n\t\t// Calculate cumulative usage from all assistant messages\n\t\tlet totalInput = 0;\n\t\tlet totalOutput = 0;\n\t\tlet totalCacheRead = 0;\n\t\tlet totalCacheWrite = 0;\n\t\tlet totalCost = 0;\n\n\t\tfor (const message of this.state.messages) {\n\t\t\tif (message.role === \"assistant\") {\n\t\t\t\tconst assistantMsg = message as AssistantMessage;\n\t\t\t\ttotalInput += assistantMsg.usage.input;\n\t\t\t\ttotalOutput += assistantMsg.usage.output;\n\t\t\t\ttotalCacheRead += assistantMsg.usage.cacheRead;\n\t\t\t\ttotalCacheWrite += assistantMsg.usage.cacheWrite;\n\t\t\t\ttotalCost += assistantMsg.usage.cost.total;\n\t\t\t}\n\t\t}\n\n\t\t// Get last assistant message for context percentage calculation (skip aborted messages)\n\t\tconst lastAssistantMessage = this.state.messages\n\t\t\t.slice()\n\t\t\t.reverse()\n\t\t\t.find((m) => m.role === \"assistant\" && m.stopReason !== \"aborted\") as AssistantMessage | undefined;\n\n\t\t// Calculate context percentage from last message (input + output + cacheRead + cacheWrite)\n\t\tconst contextTokens = lastAssistantMessage\n\t\t\t? lastAssistantMessage.usage.input +\n\t\t\t\tlastAssistantMessage.usage.output +\n\t\t\t\tlastAssistantMessage.usage.cacheRead +\n\t\t\t\tlastAssistantMessage.usage.cacheWrite\n\t\t\t: 0;\n\t\tconst contextWindow = this.state.model?.contextWindow || 0;\n\t\tconst contextPercent = contextWindow > 0 ? ((contextTokens / contextWindow) * 100).toFixed(1) : \"0.0\";\n\n\t\t// Format token counts (similar to web-ui)\n\t\tconst formatTokens = (count: number): string => {\n\t\t\tif (count < 1000) return count.toString();\n\t\t\tif (count < 10000) return (count / 1000).toFixed(1) + \"k\";\n\t\t\treturn Math.round(count / 1000) + \"k\";\n\t\t};\n\n\t\t// Replace home directory with ~\n\t\tlet pwd = process.cwd();\n\t\tconst home = process.env.HOME || process.env.USERPROFILE;\n\t\tif (home && pwd.startsWith(home)) {\n\t\t\tpwd = \"~\" + pwd.slice(home.length);\n\t\t}\n\n\t\t// Truncate path if too long to fit width\n\t\tconst maxPathLength = Math.max(20, width - 10); // Leave some margin\n\t\tif (pwd.length > maxPathLength) {\n\t\t\tconst start = pwd.slice(0, Math.floor(maxPathLength / 2) - 2);\n\t\t\tconst end = pwd.slice(-(Math.floor(maxPathLength / 2) - 1));\n\t\t\tpwd = `${start}...${end}`;\n\t\t}\n\n\t\t// Build stats line\n\t\tconst statsParts = [];\n\t\tif (totalInput) statsParts.push(`↑${formatTokens(totalInput)}`);\n\t\tif (totalOutput) statsParts.push(`↓${formatTokens(totalOutput)}`);\n\t\tif (totalCacheRead) statsParts.push(`R${formatTokens(totalCacheRead)}`);\n\t\tif (totalCacheWrite) statsParts.push(`W${formatTokens(totalCacheWrite)}`);\n\t\tif (totalCost) statsParts.push(`$${totalCost.toFixed(3)}`);\n\t\tstatsParts.push(`${contextPercent}%`);\n\n\t\tconst statsLeft = statsParts.join(\" \");\n\n\t\t// Add model name on the right side\n\t\tlet modelName = this.state.model?.id || \"no-model\";\n\t\tconst statsLeftWidth = visibleWidth(statsLeft);\n\t\tconst modelWidth = visibleWidth(modelName);\n\n\t\t// Calculate available space for padding (minimum 2 spaces between stats and model)\n\t\tconst minPadding = 2;\n\t\tconst totalNeeded = statsLeftWidth + minPadding + modelWidth;\n\n\t\tlet statsLine: string;\n\t\tif (totalNeeded <= width) {\n\t\t\t// Both fit - add padding to right-align model\n\t\t\tconst padding = \" \".repeat(width - statsLeftWidth - modelWidth);\n\t\t\tstatsLine = statsLeft + padding + modelName;\n\t\t} else {\n\t\t\t// Need to truncate model name\n\t\t\tconst availableForModel = width - statsLeftWidth - minPadding;\n\t\t\tif (availableForModel > 3) {\n\t\t\t\t// Truncate model name to fit\n\t\t\t\tmodelName = modelName.substring(0, availableForModel);\n\t\t\t\tconst padding = \" \".repeat(width - statsLeftWidth - visibleWidth(modelName));\n\t\t\t\tstatsLine = statsLeft + padding + modelName;\n\t\t\t} else {\n\t\t\t\t// Not enough space for model name at all\n\t\t\t\tstatsLine = statsLeft;\n\t\t\t}\n\t\t}\n\n\t\t// Return two lines: pwd and stats\n\t\treturn [chalk.gray(pwd), chalk.gray(statsLine)];\n\t}\n}\n"]}
|
package/dist/tui/footer.js
CHANGED
|
@@ -40,7 +40,7 @@ export class FooterComponent {
|
|
|
40
40
|
lastAssistantMessage.usage.cacheRead +
|
|
41
41
|
lastAssistantMessage.usage.cacheWrite
|
|
42
42
|
: 0;
|
|
43
|
-
const contextWindow = this.state.model
|
|
43
|
+
const contextWindow = this.state.model?.contextWindow || 0;
|
|
44
44
|
const contextPercent = contextWindow > 0 ? ((contextTokens / contextWindow) * 100).toFixed(1) : "0.0";
|
|
45
45
|
// Format token counts (similar to web-ui)
|
|
46
46
|
const formatTokens = (count) => {
|
|
@@ -78,7 +78,7 @@ export class FooterComponent {
|
|
|
78
78
|
statsParts.push(`${contextPercent}%`);
|
|
79
79
|
const statsLeft = statsParts.join(" ");
|
|
80
80
|
// Add model name on the right side
|
|
81
|
-
let modelName = this.state.model
|
|
81
|
+
let modelName = this.state.model?.id || "no-model";
|
|
82
82
|
const statsLeftWidth = visibleWidth(statsLeft);
|
|
83
83
|
const modelWidth = visibleWidth(modelName);
|
|
84
84
|
// Calculate available space for padding (minimum 2 spaces between stats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AC,EAAE,iBAAiB,CAAC,CAAC;gBACtD,MAAM,OAAO,GAAG,GAAG,CAAC,MAAM,CAAC,KAAK,GAAG,cAAc,GAAG,YAAY,CAAC,SAAS,CAAC,CAAC,CAAC;gBAC7E,SAAS,GAAG,SAAS,GAAG,OAAO,GAAG,SAAS,CAAC;YAC7C,CAAC;iBAAM,CAAC;gBACP,yCAAyC;gBACzC,SAAS,GAAG,SAAS,CAAC;YACvB,CAAC;QACF,CAAC;QAED,kCAAkC;QAClC,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC;IAAA,CAChD;CACD","sourcesContent":["import type { AgentState } from \"@mariozechner/pi-agent\";\nimport type { AssistantMessage } from \"@mariozechner/pi-ai\";\nimport { visibleWidth } from \"@mariozechner/pi-tui\";\nimport chalk from \"chalk\";\n\n/**\n * Footer component that shows pwd, token stats, and context usage\n */\nexport class FooterComponent {\n\tprivate state: AgentState;\n\n\tconstructor(state: AgentState) {\n\t\tthis.state = state;\n\t}\n\n\tupdateState(state: AgentState): void {\n\t\tthis.state = state;\n\t}\n\n\trender(width: number): string[] {\n\t\t// Calculate cumulative usage from all assistant messages\n\t\tlet totalInput = 0;\n\t\tlet totalOutput = 0;\n\t\tlet totalCacheRead = 0;\n\t\tlet totalCacheWrite = 0;\n\t\tlet totalCost = 0;\n\n\t\tfor (const message of this.state.messages) {\n\t\t\tif (message.role === \"assistant\") {\n\t\t\t\tconst assistantMsg = message as AssistantMessage;\n\t\t\t\ttotalInput += assistantMsg.usage.input;\n\t\t\t\ttotalOutput += assistantMsg.usage.output;\n\t\t\t\ttotalCacheRead += assistantMsg.usage.cacheRead;\n\t\t\t\ttotalCacheWrite += assistantMsg.usage.cacheWrite;\n\t\t\t\ttotalCost += assistantMsg.usage.cost.total;\n\t\t\t}\n\t\t}\n\n\t\t// Get last assistant message for context percentage calculation (skip aborted messages)\n\t\tconst lastAssistantMessage = this.state.messages\n\t\t\t.slice()\n\t\t\t.reverse()\n\t\t\t.find((m) => m.role === \"assistant\" && m.stopReason !== \"aborted\") as AssistantMessage | undefined;\n\n\t\t// Calculate context percentage from last message (input + output + cacheRead + cacheWrite)\n\t\tconst contextTokens = lastAssistantMessage\n\t\t\t? lastAssistantMessage.usage.input +\n\t\t\t\tlastAssistantMessage.usage.output +\n\t\t\t\tlastAssistantMessage.usage.cacheRead +\n\t\t\t\tlastAssistantMessage.usage.cacheWrite\n\t\t\t: 0;\n\t\tconst contextWindow = this.state.model?.contextWindow || 0;\n\t\tconst contextPercent = contextWindow > 0 ? ((contextTokens / contextWindow) * 100).toFixed(1) : \"0.0\";\n\n\t\t// Format token counts (similar to web-ui)\n\t\tconst formatTokens = (count: number): string => {\n\t\t\tif (count < 1000) return count.toString();\n\t\t\tif (count < 10000) return (count / 1000).toFixed(1) + \"k\";\n\t\t\treturn Math.round(count / 1000) + \"k\";\n\t\t};\n\n\t\t// Replace home directory with ~\n\t\tlet pwd = process.cwd();\n\t\tconst home = process.env.HOME || process.env.USERPROFILE;\n\t\tif (home && pwd.startsWith(home)) {\n\t\t\tpwd = \"~\" + pwd.slice(home.length);\n\t\t}\n\n\t\t// Truncate path if too long to fit width\n\t\tconst maxPathLength = Math.max(20, width - 10); // Leave some margin\n\t\tif (pwd.length > maxPathLength) {\n\t\t\tconst start = pwd.slice(0, Math.floor(maxPathLength / 2) - 2);\n\t\t\tconst end = pwd.slice(-(Math.floor(maxPathLength / 2) - 1));\n\t\t\tpwd = `${start}...${end}`;\n\t\t}\n\n\t\t// Build stats line\n\t\tconst statsParts = [];\n\t\tif (totalInput) statsParts.push(`↑${formatTokens(totalInput)}`);\n\t\tif (totalOutput) statsParts.push(`↓${formatTokens(totalOutput)}`);\n\t\tif (totalCacheRead) statsParts.push(`R${formatTokens(totalCacheRead)}`);\n\t\tif (totalCacheWrite) statsParts.push(`W${formatTokens(totalCacheWrite)}`);\n\t\tif (totalCost) statsParts.push(`$${totalCost.toFixed(3)}`);\n\t\tstatsParts.push(`${contextPercent}%`);\n\n\t\tconst statsLeft = statsParts.join(\" \");\n\n\t\t// Add model name on the right side\n\t\tlet modelName = this.state.model?.id || \"no-model\";\n\t\tconst statsLeftWidth = visibleWidth(statsLeft);\n\t\tconst modelWidth = visibleWidth(modelName);\n\n\t\t// Calculate available space for padding (minimum 2 spaces between stats and model)\n\t\tconst minPadding = 2;\n\t\tconst totalNeeded = statsLeftWidth + minPadding + modelWidth;\n\n\t\tlet statsLine: string;\n\t\tif (totalNeeded <= width) {\n\t\t\t// Both fit - add padding to right-align model\n\t\t\tconst padding = \" \".repeat(width - statsLeftWidth - modelWidth);\n\t\t\tstatsLine = statsLeft + padding + modelName;\n\t\t} else {\n\t\t\t// Need to truncate model name\n\t\t\tconst availableForModel = width - statsLeftWidth - minPadding;\n\t\t\tif (availableForModel > 3) {\n\t\t\t\t// Truncate model name to fit\n\t\t\t\tmodelName = modelName.substring(0, availableForModel);\n\t\t\t\tconst padding = \" \".repeat(width - statsLeftWidth - visibleWidth(modelName));\n\t\t\t\tstatsLine = statsLeft + padding + modelName;\n\t\t\t} else {\n\t\t\t\t// Not enough space for model name at all\n\t\t\t\tstatsLine = statsLeft;\n\t\t\t}\n\t\t}\n\n\t\t// Return two lines: pwd and stats\n\t\treturn [chalk.gray(pwd), chalk.gray(statsLine)];\n\t}\n}\n"]}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import type { Model } from "@mariozechner/pi-ai";
|
|
2
2
|
import { Container, Input } from "@mariozechner/pi-tui";
|
|
3
|
+
import type { SettingsManager } from "../settings-manager.js";
|
|
3
4
|
/**
|
|
4
5
|
* Component that renders a model selector with search
|
|
5
6
|
*/
|
|
@@ -10,9 +11,11 @@ export declare class ModelSelectorComponent extends Container {
|
|
|
10
11
|
private filteredModels;
|
|
11
12
|
private selectedIndex;
|
|
12
13
|
private currentModel;
|
|
14
|
+
private settingsManager;
|
|
13
15
|
private onSelectCallback;
|
|
14
16
|
private onCancelCallback;
|
|
15
|
-
|
|
17
|
+
private errorMessage;
|
|
18
|
+
constructor(currentModel: Model<any> | null, settingsManager: SettingsManager, onSelect: (model: Model<any>) => void, onCancel: () => void);
|
|
16
19
|
private loadModels;
|
|
17
20
|
private filterModels;
|
|
18
21
|
private updateList;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"model-selector.d.ts","sourceRoot":"","sources":["../../src/tui/model-selector.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"model-selector.d.ts","sourceRoot":"","sources":["../../src/tui/model-selector.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,qBAAqB,CAAC;AACjD,OAAO,EAAE,SAAS,EAAE,KAAK,EAAgB,MAAM,sBAAsB,CAAC;AAGtE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAQ9D;;GAEG;AACH,qBAAa,sBAAuB,SAAQ,SAAS;IACpD,OAAO,CAAC,WAAW,CAAQ;IAC3B,OAAO,CAAC,aAAa,CAAY;IACjC,OAAO,CAAC,SAAS,CAAmB;IACpC,OAAO,CAAC,cAAc,CAAmB;IACzC,OAAO,CAAC,aAAa,CAAa;IAClC,OAAO,CAAC,YAAY,CAAoB;IACxC,OAAO,CAAC,eAAe,CAAkB;IACzC,OAAO,CAAC,gBAAgB,CAA8B;IACtD,OAAO,CAAC,gBAAgB,CAAa;IACrC,OAAO,CAAC,YAAY,CAAuB;IAE3C,YACC,YAAY,EAAE,KAAK,CAAC,GAAG,CAAC,GAAG,IAAI,EAC/B,eAAe,EAAE,eAAe,EAChC,QAAQ,EAAE,CAAC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,KAAK,IAAI,EACrC,QAAQ,EAAE,MAAM,IAAI,EA6CpB;IAED,OAAO,CAAC,UAAU;IAgClB,OAAO,CAAC,YAAY;IAkBpB,OAAO,CAAC,UAAU;IAqDlB,WAAW,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CA2BjC;IAED,OAAO,CAAC,YAAY;IAMpB,cAAc,IAAI,KAAK,CAEtB;CACD","sourcesContent":["import type { Model } from \"@mariozechner/pi-ai\";\nimport { Container, Input, Spacer, Text } from \"@mariozechner/pi-tui\";\nimport chalk from \"chalk\";\nimport { getAvailableModels } from \"../model-config.js\";\nimport type { SettingsManager } from \"../settings-manager.js\";\n\ninterface ModelItem {\n\tprovider: string;\n\tid: string;\n\tmodel: Model<any>;\n}\n\n/**\n * Component that renders a model selector with search\n */\nexport class ModelSelectorComponent extends Container {\n\tprivate searchInput: Input;\n\tprivate listContainer: Container;\n\tprivate allModels: ModelItem[] = [];\n\tprivate filteredModels: ModelItem[] = [];\n\tprivate selectedIndex: number = 0;\n\tprivate currentModel: Model<any> | null;\n\tprivate settingsManager: SettingsManager;\n\tprivate onSelectCallback: (model: Model<any>) => void;\n\tprivate onCancelCallback: () => void;\n\tprivate errorMessage: string | null = null;\n\n\tconstructor(\n\t\tcurrentModel: Model<any> | null,\n\t\tsettingsManager: SettingsManager,\n\t\tonSelect: (model: Model<any>) => void,\n\t\tonCancel: () => void,\n\t) {\n\t\tsuper();\n\n\t\tthis.currentModel = currentModel;\n\t\tthis.settingsManager = settingsManager;\n\t\tthis.onSelectCallback = onSelect;\n\t\tthis.onCancelCallback = onCancel;\n\n\t\t// Load all models (fresh every time)\n\t\tthis.loadModels();\n\n\t\t// Add top border\n\t\tthis.addChild(new Text(chalk.blue(\"─\".repeat(80)), 0, 0));\n\t\tthis.addChild(new Spacer(1));\n\n\t\t// Add hint about API key filtering\n\t\tthis.addChild(\n\t\t\tnew Text(chalk.yellow(\"Only showing models with configured API keys (see README for details)\"), 0, 0),\n\t\t);\n\t\tthis.addChild(new Spacer(1));\n\n\t\t// Create search input\n\t\tthis.searchInput = new Input();\n\t\tthis.searchInput.onSubmit = () => {\n\t\t\t// Enter on search input selects the first filtered item\n\t\t\tif (this.filteredModels[this.selectedIndex]) {\n\t\t\t\tthis.handleSelect(this.filteredModels[this.selectedIndex].model);\n\t\t\t}\n\t\t};\n\t\tthis.addChild(this.searchInput);\n\n\t\tthis.addChild(new Spacer(1));\n\n\t\t// Create list container\n\t\tthis.listContainer = new Container();\n\t\tthis.addChild(this.listContainer);\n\n\t\tthis.addChild(new Spacer(1));\n\n\t\t// Add bottom border\n\t\tthis.addChild(new Text(chalk.blue(\"─\".repeat(80)), 0, 0));\n\n\t\t// Initial render\n\t\tthis.updateList();\n\t}\n\n\tprivate loadModels(): void {\n\t\t// Load available models fresh (includes custom models from ~/.pi/agent/models.json)\n\t\tconst { models: availableModels, error } = getAvailableModels();\n\n\t\t// If there's an error loading models.json, we'll show it via the \"no models\" path\n\t\t// The error will be displayed to the user\n\t\tif (error) {\n\t\t\tthis.allModels = [];\n\t\t\tthis.filteredModels = [];\n\t\t\tthis.errorMessage = error;\n\t\t\treturn;\n\t\t}\n\n\t\tconst models: ModelItem[] = availableModels.map((model) => ({\n\t\t\tprovider: model.provider,\n\t\t\tid: model.id,\n\t\t\tmodel,\n\t\t}));\n\n\t\t// Sort: current model first, then by provider\n\t\tmodels.sort((a, b) => {\n\t\t\tconst aIsCurrent = this.currentModel?.id === a.model.id && this.currentModel?.provider === a.provider;\n\t\t\tconst bIsCurrent = this.currentModel?.id === b.model.id && this.currentModel?.provider === b.provider;\n\t\t\tif (aIsCurrent && !bIsCurrent) return -1;\n\t\t\tif (!aIsCurrent && bIsCurrent) return 1;\n\t\t\treturn a.provider.localeCompare(b.provider);\n\t\t});\n\n\t\tthis.allModels = models;\n\t\tthis.filteredModels = models;\n\t}\n\n\tprivate filterModels(query: string): void {\n\t\tif (!query.trim()) {\n\t\t\tthis.filteredModels = this.allModels;\n\t\t} else {\n\t\t\tconst searchTokens = query\n\t\t\t\t.toLowerCase()\n\t\t\t\t.split(/\\s+/)\n\t\t\t\t.filter((t) => t);\n\t\t\tthis.filteredModels = this.allModels.filter(({ provider, id, model }) => {\n\t\t\t\tconst searchText = `${provider} ${id} ${model.name}`.toLowerCase();\n\t\t\t\treturn searchTokens.every((token) => searchText.includes(token));\n\t\t\t});\n\t\t}\n\n\t\tthis.selectedIndex = Math.min(this.selectedIndex, Math.max(0, this.filteredModels.length - 1));\n\t\tthis.updateList();\n\t}\n\n\tprivate updateList(): void {\n\t\tthis.listContainer.clear();\n\n\t\tconst maxVisible = 10;\n\t\tconst startIndex = Math.max(\n\t\t\t0,\n\t\t\tMath.min(this.selectedIndex - Math.floor(maxVisible / 2), this.filteredModels.length - maxVisible),\n\t\t);\n\t\tconst endIndex = Math.min(startIndex + maxVisible, this.filteredModels.length);\n\n\t\t// Show visible slice of filtered models\n\t\tfor (let i = startIndex; i < endIndex; i++) {\n\t\t\tconst item = this.filteredModels[i];\n\t\t\tif (!item) continue;\n\n\t\t\tconst isSelected = i === this.selectedIndex;\n\t\t\tconst isCurrent = this.currentModel?.id === item.model.id;\n\n\t\t\tlet line = \"\";\n\t\t\tif (isSelected) {\n\t\t\t\tconst prefix = chalk.blue(\"→ \");\n\t\t\t\tconst modelText = `${item.id}`;\n\t\t\t\tconst providerBadge = chalk.gray(`[${item.provider}]`);\n\t\t\t\tconst checkmark = isCurrent ? chalk.green(\" ✓\") : \"\";\n\t\t\t\tline = prefix + chalk.blue(modelText) + \" \" + providerBadge + checkmark;\n\t\t\t} else {\n\t\t\t\tconst modelText = ` ${item.id}`;\n\t\t\t\tconst providerBadge = chalk.gray(`[${item.provider}]`);\n\t\t\t\tconst checkmark = isCurrent ? chalk.green(\" ✓\") : \"\";\n\t\t\t\tline = modelText + \" \" + providerBadge + checkmark;\n\t\t\t}\n\n\t\t\tthis.listContainer.addChild(new Text(line, 0, 0));\n\t\t}\n\n\t\t// Add scroll indicator if needed\n\t\tif (startIndex > 0 || endIndex < this.filteredModels.length) {\n\t\t\tconst scrollInfo = chalk.gray(` (${this.selectedIndex + 1}/${this.filteredModels.length})`);\n\t\t\tthis.listContainer.addChild(new Text(scrollInfo, 0, 0));\n\t\t}\n\n\t\t// Show error message or \"no results\" if empty\n\t\tif (this.errorMessage) {\n\t\t\t// Show error in red\n\t\t\tconst errorLines = this.errorMessage.split(\"\\n\");\n\t\t\tfor (const line of errorLines) {\n\t\t\t\tthis.listContainer.addChild(new Text(chalk.red(line), 0, 0));\n\t\t\t}\n\t\t} else if (this.filteredModels.length === 0) {\n\t\t\tthis.listContainer.addChild(new Text(chalk.gray(\" No matching models\"), 0, 0));\n\t\t}\n\t}\n\n\thandleInput(keyData: string): void {\n\t\t// Up arrow\n\t\tif (keyData === \"\\x1b[A\") {\n\t\t\tthis.selectedIndex = Math.max(0, this.selectedIndex - 1);\n\t\t\tthis.updateList();\n\t\t}\n\t\t// Down arrow\n\t\telse if (keyData === \"\\x1b[B\") {\n\t\t\tthis.selectedIndex = Math.min(this.filteredModels.length - 1, this.selectedIndex + 1);\n\t\t\tthis.updateList();\n\t\t}\n\t\t// Enter\n\t\telse if (keyData === \"\\r\") {\n\t\t\tconst selectedModel = this.filteredModels[this.selectedIndex];\n\t\t\tif (selectedModel) {\n\t\t\t\tthis.handleSelect(selectedModel.model);\n\t\t\t}\n\t\t}\n\t\t// Escape\n\t\telse if (keyData === \"\\x1b\") {\n\t\t\tthis.onCancelCallback();\n\t\t}\n\t\t// Pass everything else to search input\n\t\telse {\n\t\t\tthis.searchInput.handleInput(keyData);\n\t\t\tthis.filterModels(this.searchInput.getValue());\n\t\t}\n\t}\n\n\tprivate handleSelect(model: Model<any>): void {\n\t\t// Save as new default\n\t\tthis.settingsManager.setDefaultModelAndProvider(model.provider, model.id);\n\t\tthis.onSelectCallback(model);\n\t}\n\n\tgetSearchInput(): Input {\n\t\treturn this.searchInput;\n\t}\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { getApiKey, getModels, getProviders } from "@mariozechner/pi-ai";
|
|
2
1
|
import { Container, Input, Spacer, Text } from "@mariozechner/pi-tui";
|
|
3
2
|
import chalk from "chalk";
|
|
3
|
+
import { getAvailableModels } from "../model-config.js";
|
|
4
4
|
/**
|
|
5
5
|
* Component that renders a model selector with search
|
|
6
6
|
*/
|
|
@@ -11,14 +11,17 @@ export class ModelSelectorComponent extends Container {
|
|
|
11
11
|
filteredModels = [];
|
|
12
12
|
selectedIndex = 0;
|
|
13
13
|
currentModel;
|
|
14
|
+
settingsManager;
|
|
14
15
|
onSelectCallback;
|
|
15
16
|
onCancelCallback;
|
|
16
|
-
|
|
17
|
+
errorMessage = null;
|
|
18
|
+
constructor(currentModel, settingsManager, onSelect, onCancel) {
|
|
17
19
|
super();
|
|
18
20
|
this.currentModel = currentModel;
|
|
21
|
+
this.settingsManager = settingsManager;
|
|
19
22
|
this.onSelectCallback = onSelect;
|
|
20
23
|
this.onCancelCallback = onCancel;
|
|
21
|
-
// Load all models
|
|
24
|
+
// Load all models (fresh every time)
|
|
22
25
|
this.loadModels();
|
|
23
26
|
// Add top border
|
|
24
27
|
this.addChild(new Text(chalk.blue("─".repeat(80)), 0, 0));
|
|
@@ -46,28 +49,33 @@ export class ModelSelectorComponent extends Container {
|
|
|
46
49
|
this.updateList();
|
|
47
50
|
}
|
|
48
51
|
loadModels() {
|
|
49
|
-
|
|
50
|
-
const
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
52
|
+
// Load available models fresh (includes custom models from ~/.pi/agent/models.json)
|
|
53
|
+
const { models: availableModels, error } = getAvailableModels();
|
|
54
|
+
// If there's an error loading models.json, we'll show it via the "no models" path
|
|
55
|
+
// The error will be displayed to the user
|
|
56
|
+
if (error) {
|
|
57
|
+
this.allModels = [];
|
|
58
|
+
this.filteredModels = [];
|
|
59
|
+
this.errorMessage = error;
|
|
60
|
+
return;
|
|
56
61
|
}
|
|
57
|
-
|
|
58
|
-
|
|
62
|
+
const models = availableModels.map((model) => ({
|
|
63
|
+
provider: model.provider,
|
|
64
|
+
id: model.id,
|
|
65
|
+
model,
|
|
66
|
+
}));
|
|
59
67
|
// Sort: current model first, then by provider
|
|
60
|
-
|
|
61
|
-
const aIsCurrent = this.currentModel?.id === a.model.id;
|
|
62
|
-
const bIsCurrent = this.currentModel?.id === b.model.id;
|
|
68
|
+
models.sort((a, b) => {
|
|
69
|
+
const aIsCurrent = this.currentModel?.id === a.model.id && this.currentModel?.provider === a.provider;
|
|
70
|
+
const bIsCurrent = this.currentModel?.id === b.model.id && this.currentModel?.provider === b.provider;
|
|
63
71
|
if (aIsCurrent && !bIsCurrent)
|
|
64
72
|
return -1;
|
|
65
73
|
if (!aIsCurrent && bIsCurrent)
|
|
66
74
|
return 1;
|
|
67
75
|
return a.provider.localeCompare(b.provider);
|
|
68
76
|
});
|
|
69
|
-
this.allModels =
|
|
70
|
-
this.filteredModels =
|
|
77
|
+
this.allModels = models;
|
|
78
|
+
this.filteredModels = models;
|
|
71
79
|
}
|
|
72
80
|
filterModels(query) {
|
|
73
81
|
if (!query.trim()) {
|
|
@@ -119,8 +127,15 @@ export class ModelSelectorComponent extends Container {
|
|
|
119
127
|
const scrollInfo = chalk.gray(` (${this.selectedIndex + 1}/${this.filteredModels.length})`);
|
|
120
128
|
this.listContainer.addChild(new Text(scrollInfo, 0, 0));
|
|
121
129
|
}
|
|
122
|
-
// Show "no results" if empty
|
|
123
|
-
if (this.
|
|
130
|
+
// Show error message or "no results" if empty
|
|
131
|
+
if (this.errorMessage) {
|
|
132
|
+
// Show error in red
|
|
133
|
+
const errorLines = this.errorMessage.split("\n");
|
|
134
|
+
for (const line of errorLines) {
|
|
135
|
+
this.listContainer.addChild(new Text(chalk.red(line), 0, 0));
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
else if (this.filteredModels.length === 0) {
|
|
124
139
|
this.listContainer.addChild(new Text(chalk.gray(" No matching models"), 0, 0));
|
|
125
140
|
}
|
|
126
141
|
}
|
|
@@ -153,6 +168,8 @@ export class ModelSelectorComponent extends Container {
|
|
|
153
168
|
}
|
|
154
169
|
}
|
|
155
170
|
handleSelect(model) {
|
|
171
|
+
// Save as new default
|
|
172
|
+
this.settingsManager.setDefaultModelAndProvider(model.provider, model.id);
|
|
156
173
|
this.onSelectCallback(model);
|
|
157
174
|
}
|
|
158
175
|
getSearchInput() {
|