@pi-chamber/web 1.0.2-rc.1 → 1.0.3-rc.1

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 (58) hide show
  1. package/dist/assets/{DiagramView-GUJij-1P.js → DiagramView-CXjieF51.js} +1 -1
  2. package/dist/assets/DiffView-CXg8TAtI.js +18 -0
  3. package/dist/assets/{FileSaveConflictDialog-Ci6WdSiS.js → FileSaveConflictDialog-a-HOCgyP.js} +1 -1
  4. package/dist/assets/{FilesView-DBiWEo71.js → FilesView-Dcd9ltOX.js} +1 -1
  5. package/dist/assets/{GitView-DVyhqN5s.js → GitView-DF2nsuSA.js} +3 -3
  6. package/dist/assets/{JsonTreeView-BaU7aAUq.js → JsonTreeView-BRU2mRTd.js} +1 -1
  7. package/dist/assets/{MarkdownRendererImpl-6NBJLtEr.js → MarkdownRendererImpl-CeYMkg1A.js} +5 -5
  8. package/dist/assets/{PatchDiff-CvptevA2.js → PatchDiff-kSTpjhu6.js} +1 -1
  9. package/dist/assets/{SessionSwitcherContent-Cqp5FVCP.js → SessionSwitcherContent-BsXDFt24.js} +1 -1
  10. package/dist/assets/{SessionSwitcherDropdown-CRVJU16x.js → SessionSwitcherDropdown-D8fSObHr.js} +2 -2
  11. package/dist/assets/{SessionUnreadDot-CsFxImPI.js → SessionUnreadDot-BpsHyrri.js} +1 -1
  12. package/dist/assets/SettingsView-OEl7QmXC.js +6 -0
  13. package/dist/assets/{SettingsWindow-geMUhnxd.js → SettingsWindow-BMBCj_L_.js} +1 -1
  14. package/dist/assets/{ToolOutputDialog-BLGl2mNt.js → ToolOutputDialog-KOVdmTqm.js} +1 -1
  15. package/dist/assets/{ToolPartDiffPreview-BVeL1IuE.js → ToolPartDiffPreview-B9xuVvkm.js} +1 -1
  16. package/dist/assets/{VirtualizedFileDiff-9kAZ96se.js → VirtualizedFileDiff-CV_Cpmqu.js} +4 -4
  17. package/dist/assets/{collapsible-BencOwkW.js → collapsible-BH1vXEAI.js} +1 -1
  18. package/dist/assets/{computeVirtualFileMetrics-C8vH0vcM.js → computeVirtualFileMetrics-yHZbtf5H.js} +2 -2
  19. package/dist/assets/{contextFileOpenGuard-B6e3cTcl.js → contextFileOpenGuard-BA2pkQY_.js} +1 -1
  20. package/dist/assets/{gitStatusPredicates-B6w5GMNU.js → gitStatusPredicates-CpGQLvMK.js} +1 -1
  21. package/dist/assets/index-5fyXnZFi.css +1 -0
  22. package/dist/assets/{index-CpSdU-d4.js → index-C-sV_9sb.js} +3 -3
  23. package/dist/assets/{index-BifnX1Mp.js → index-D_FGGnQQ.js} +1 -1
  24. package/dist/assets/{isDiffPlainText-BepQ1JHv.js → isDiffPlainText-BNyusJZz.js} +1 -1
  25. package/dist/assets/{isFilePlainText-CA1KFaTm.js → isFilePlainText-CMAUe7qD.js} +1 -1
  26. package/dist/assets/{main-dhVDQIHu.js → main-BMLgZ5yn.js} +2 -2
  27. package/dist/assets/{main-TzeSIx1W.js → main-DNq1n9F_.js} +3 -3
  28. package/dist/assets/{markdownCore-BztwD2c9.js → markdownCore-CZWcaNr2.js} +2 -2
  29. package/dist/assets/{miniChat-smqdx0Y7.js → miniChat-B2AgUZqL.js} +2 -2
  30. package/dist/assets/{mobile-BV-WCEiE.js → mobile-BsGiRUUg.js} +2 -2
  31. package/dist/assets/{renderElectronMiniChatApp-DKmb9oa7.js → renderElectronMiniChatApp-UV9dnnbf.js} +2 -2
  32. package/dist/assets/renderMobileApp-BMifduGA.js +11 -0
  33. package/dist/assets/runtimeEndpointReset-CkvC02dQ.js +53 -0
  34. package/dist/assets/{runtimeSurface-Bm6cRkok.js → runtimeSurface-BdndJV2m.js} +1 -1
  35. package/dist/assets/{useAppFontEffects-Dq7xKVjh.js → useAppFontEffects-CclUs9KY.js} +98 -98
  36. package/dist/assets/{useFilesViewSearch-Bvlo7C3a.js → useFilesViewSearch-CI5Gy1cp.js} +1 -1
  37. package/dist/assets/{usePushVisibilityBeacon-BY4xtozp.js → usePushVisibilityBeacon-aDmGZrTW.js} +3 -3
  38. package/dist/assets/{useSwitcherItems-CkE242zK.js → useSwitcherItems-BZKyNjhp.js} +1 -1
  39. package/dist/assets/{vendor-codemirror-language-data-Bv6kN79m.js → vendor-codemirror-language-data-C6LBD7qA.js} +2 -2
  40. package/dist/assets/{web-components-CCiRgoOw.js → web-components-Cdnmh4Xb.js} +4 -4
  41. package/dist/index.html +4 -4
  42. package/dist/mini-chat.html +3 -3
  43. package/dist/mobile.html +3 -3
  44. package/package.json +1 -1
  45. package/server/lib/pi/model-config-store.js +146 -20
  46. package/server/lib/pi/model-config-store.test.js +153 -21
  47. package/server/lib/pi/routes.js +42 -1
  48. package/server/lib/pi/routes.test.js +104 -2
  49. package/server/lib/pi/session-daemon/DOCUMENTATION.md +3 -2
  50. package/server/lib/pi/session-daemon/session-daemon.js +322 -58
  51. package/server/lib/pi/session-daemon/session-daemon.test.js +335 -0
  52. package/server/lib/pi/session-daemon/session-failed-create-cleanup.test.js +372 -0
  53. package/server/lib/pi/session-persistence-gap.test.js +731 -0
  54. package/dist/assets/DiffView-BZ487Bhh.js +0 -18
  55. package/dist/assets/SettingsView-ppaIrPry.js +0 -2
  56. package/dist/assets/index-Dwz16owi.css +0 -1
  57. package/dist/assets/renderMobileApp-D3dtjeaE.js +0 -11
  58. package/dist/assets/runtimeEndpointReset-C1EENUlq.js +0 -53
package/dist/mobile.html CHANGED
@@ -63,7 +63,7 @@
63
63
  })();
64
64
  </script>
65
65
 
66
- <script type="module" crossorigin src="/assets/mobile-BV-WCEiE.js"></script>
66
+ <script type="module" crossorigin src="/assets/mobile-BsGiRUUg.js"></script>
67
67
  <link rel="modulepreload" crossorigin href="/assets/vendor-vite-runtime-DD1OZmLC.js">
68
68
  <link rel="modulepreload" crossorigin href="/assets/vendor-scheduler-7OC5HNn7.js">
69
69
  <link rel="modulepreload" crossorigin href="/assets/vendor-react-B5Z1Mdn3.js">
@@ -71,9 +71,9 @@
71
71
  <link rel="modulepreload" crossorigin href="/assets/vendor-clsx-B-dksMZM.js">
72
72
  <link rel="modulepreload" crossorigin href="/assets/vendor-tailwind-merge-CPcsbTWB.js">
73
73
  <link rel="modulepreload" crossorigin href="/assets/vendor-fuse.js-Dw8P0qyA.js">
74
- <link rel="modulepreload" crossorigin href="/assets/index-CpSdU-d4.js">
74
+ <link rel="modulepreload" crossorigin href="/assets/index-C-sV_9sb.js">
75
75
  <link rel="modulepreload" crossorigin href="/assets/vendor-katex-CNckGUMB.js">
76
- <link rel="stylesheet" crossorigin href="/assets/index-Dwz16owi.css">
76
+ <link rel="stylesheet" crossorigin href="/assets/index-5fyXnZFi.css">
77
77
  <link rel="stylesheet" crossorigin href="/assets/vendor-katex-Cp579UoJ.css">
78
78
  </head>
79
79
  <body class="h-full bg-background text-foreground">
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pi-chamber/web",
3
- "version": "1.0.2-rc.1",
3
+ "version": "1.0.3-rc.1",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "engines": {
@@ -2,9 +2,12 @@ import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
2
2
  import { dirname, join } from 'node:path';
3
3
 
4
4
  import { withCrossProcessLock } from '../server/cross-process-lock.js';
5
-
6
5
  const PROVIDER_ID = /^[a-z0-9][a-z0-9-_]*$/;
7
6
  const API_KEY_REFERENCE = /^\{env:[A-Za-z_][A-Za-z0-9_]*\}$/;
7
+ // Intentional four-API boundary: Pi's public models.json docs list exactly
8
+ // these four as safely representable custom APIs for manual models.
9
+ // Pi supports more internal transports, but manual additions stay within the
10
+ // documented set so unknown transports cannot be smuggled through.
8
11
  const API_TYPES = new Set(['openai-completions', 'openai-responses', 'anthropic-messages', 'google-generative-ai']);
9
12
 
10
13
  // Pi accepts JSON-with-comments for models.json. Strip comments without
@@ -50,6 +53,41 @@ const invalidModelConfig = () => {
50
53
  return error;
51
54
  };
52
55
 
56
+ const duplicateModelError = () => {
57
+ const error = new Error('The model already exists for this provider.');
58
+ error.code = 'PI_MODEL_DUPLICATE';
59
+ return error;
60
+ };
61
+
62
+ const THINKING_LEVEL_KEYS = new Set(['off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max']);
63
+ const UNSAFE_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
64
+ const MAX_MODEL_HEADERS = 50;
65
+
66
+ const isPlainObject = (value) => {
67
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false;
68
+ const proto = Object.getPrototypeOf(value);
69
+ return proto === Object.prototype || proto === null;
70
+ };
71
+
72
+ const hasUnsafeKey = (value) => isPlainObject(value) && Object.keys(value).some((key) => UNSAFE_KEYS.has(key));
73
+
74
+ const validateThinkingLevelMap = (value) => {
75
+ if (!isPlainObject(value) || hasUnsafeKey(value)) throw invalidModelConfig();
76
+ const entries = Object.entries(value);
77
+ if (entries.length > THINKING_LEVEL_KEYS.size) throw invalidModelConfig();
78
+ for (const [key, mapped] of entries) {
79
+ if (!THINKING_LEVEL_KEYS.has(key) || (mapped !== null && (typeof mapped !== 'string' || mapped.length > 512))) throw invalidModelConfig();
80
+ }
81
+ return structuredClone(value);
82
+ };
83
+
84
+ const validateInputModalities = (value) => {
85
+ if (!Array.isArray(value) || value.length === 0 || value.length > 2) throw invalidModelConfig();
86
+ const unique = new Set(value);
87
+ if (unique.size !== value.length || [...unique].some((entry) => entry !== 'text' && entry !== 'image')) throw invalidModelConfig();
88
+ return [...value];
89
+ };
90
+
53
91
  const cloneRecord = (value) => {
54
92
  if (!value || typeof value !== 'object' || Array.isArray(value)) throw invalidModelConfig();
55
93
  return structuredClone(value);
@@ -57,9 +95,11 @@ const cloneRecord = (value) => {
57
95
 
58
96
  const validateHeaderMap = (headers) => {
59
97
  if (headers === undefined) return undefined;
60
- if (!headers || typeof headers !== 'object' || Array.isArray(headers)
61
- || Object.entries(headers).some(([key, value]) => !key || key.length > 256 || typeof value !== 'string' || value.length > 8_192)) throw invalidModelConfig();
62
- return headers;
98
+ if (!isPlainObject(headers) || hasUnsafeKey(headers)) throw invalidModelConfig();
99
+ const entries = Object.entries(headers);
100
+ if (entries.length > MAX_MODEL_HEADERS) throw invalidModelConfig();
101
+ if (entries.some(([key, value]) => !key || key.length > 256 || typeof value !== 'string' || value.length > 8_192)) throw invalidModelConfig();
102
+ return structuredClone(headers);
63
103
  };
64
104
 
65
105
  const publicProvider = (providerId, value) => {
@@ -71,8 +111,11 @@ const publicProvider = (providerId, value) => {
71
111
  id: model.id,
72
112
  providerId,
73
113
  ...(typeof model.name === 'string' ? { label: model.name } : {}),
74
- ...(Number.isSafeInteger(model.contextWindow) ? { contextWindow: model.contextWindow } : {}),
75
114
  ...(model.reasoning === true ? { supportsThinking: true } : {}),
115
+ ...(isPlainObject(model.thinkingLevelMap) ? { thinkingLevelMap: structuredClone(model.thinkingLevelMap) } : {}),
116
+ ...(Array.isArray(model.input) ? { input: structuredClone(model.input) } : {}),
117
+ ...(Number.isSafeInteger(model.contextWindow) ? { contextWindow: model.contextWindow } : {}),
118
+ ...(Number.isSafeInteger(model.maxTokens) ? { maxTokens: model.maxTokens } : {}),
76
119
  };
77
120
  });
78
121
  return {
@@ -92,19 +135,10 @@ const normalizeUpdate = (input) => {
92
135
  || (input.apiKeyReference !== undefined && (typeof input.apiKeyReference !== 'string' || !API_KEY_REFERENCE.test(input.apiKeyReference)))) throw invalidModelConfig();
93
136
  const modelIds = new Set();
94
137
  const models = input.models.map((model) => {
95
- if (!model || typeof model !== 'object' || typeof model.id !== 'string' || model.id.trim().length === 0 || model.id.length > 512
96
- || (typeof model.label !== 'string' || model.label.trim().length === 0 || model.label.length > 512)
97
- || (model.contextWindow !== undefined && (!Number.isSafeInteger(model.contextWindow) || model.contextWindow <= 0))
98
- || (model.supportsThinking !== undefined && typeof model.supportsThinking !== 'boolean')) throw invalidModelConfig();
99
- const id = model.id.trim();
100
- if (modelIds.has(id)) throw invalidModelConfig();
101
- modelIds.add(id);
102
- return {
103
- id,
104
- name: model.label.trim(),
105
- ...(Number.isSafeInteger(model.contextWindow) ? { contextWindow: model.contextWindow } : {}),
106
- ...(model.supportsThinking === true ? { reasoning: true } : {}),
107
- };
138
+ const normalized = normalizeAddModel({ providerId: input.providerId, model }).model;
139
+ if (modelIds.has(normalized.id)) throw invalidModelConfig();
140
+ modelIds.add(normalized.id);
141
+ return normalized;
108
142
  });
109
143
  return {
110
144
  providerId: input.providerId,
@@ -117,6 +151,38 @@ const normalizeUpdate = (input) => {
117
151
  };
118
152
  };
119
153
 
154
+ const normalizeAddModel = (input) => {
155
+ if (!input || typeof input !== 'object' || typeof input.providerId !== 'string' || !PROVIDER_ID.test(input.providerId)) throw invalidModelConfig();
156
+ const model = input.model;
157
+ if (!isPlainObject(model) || typeof model.id !== 'string' || model.id.trim().length === 0 || model.id.length > 512) throw invalidModelConfig();
158
+ if (model.name !== undefined && (typeof model.name !== 'string' || model.name.trim().length === 0 || model.name.length > 512)) throw invalidModelConfig();
159
+ if (model.reasoning !== undefined && typeof model.reasoning !== 'boolean') throw invalidModelConfig();
160
+ if (model.contextWindow !== undefined && (!Number.isSafeInteger(model.contextWindow) || model.contextWindow <= 0)) throw invalidModelConfig();
161
+ if (model.maxTokens !== undefined && (!Number.isSafeInteger(model.maxTokens) || model.maxTokens <= 0)) throw invalidModelConfig();
162
+
163
+ const thinkingLevelMap = model.thinkingLevelMap === undefined
164
+ ? undefined
165
+ : validateThinkingLevelMap(model.thinkingLevelMap);
166
+ const normalizedModel = {
167
+ id: model.id.trim(),
168
+ ...(model.name !== undefined ? { name: model.name.trim() } : {}),
169
+ ...(model.reasoning === true ? { reasoning: true } : {}),
170
+ ...(thinkingLevelMap && Object.keys(thinkingLevelMap).length > 0 ? { thinkingLevelMap } : {}),
171
+ ...(model.input !== undefined ? { input: validateInputModalities(model.input) } : {}),
172
+ ...(Number.isSafeInteger(model.contextWindow) ? { contextWindow: model.contextWindow } : {}),
173
+ ...(Number.isSafeInteger(model.maxTokens) ? { maxTokens: model.maxTokens } : {}),
174
+ };
175
+ let seed;
176
+ if (input.seed !== undefined) {
177
+ const candidate = input.seed;
178
+ if (!isPlainObject(candidate) || typeof candidate.label !== 'string' || candidate.label.trim().length === 0 || candidate.label.length > 256
179
+ || typeof candidate.baseUrl !== 'string' || !/^https?:\/\//.test(candidate.baseUrl) || candidate.baseUrl.length > 8_192
180
+ || !API_TYPES.has(candidate.api)) throw invalidModelConfig();
181
+ seed = { name: candidate.label.trim(), baseUrl: candidate.baseUrl.trim(), api: candidate.api };
182
+ }
183
+ return { providerId: input.providerId, model: normalizedModel, ...(seed ? { seed } : {}) };
184
+ };
185
+
120
186
  /**
121
187
  * Owns atomic updates to Pi's credential-blind models.json. Credentials are
122
188
  * deliberately excluded: literal keys use Pi's auth flow, and only validated
@@ -153,12 +219,23 @@ export const createPiModelConfigStore = ({ file }) => {
153
219
  const operation = writeChain.then(() => withCrossProcessLock(`${file}.lock`, async () => {
154
220
  const config = await readConfig();
155
221
  const previous = config.providers[nextProvider.providerId];
222
+ const previousModels = previous && typeof previous === 'object' && !Array.isArray(previous) && Array.isArray(previous.models)
223
+ ? new Map(previous.models.filter((model) => model && typeof model === 'object' && typeof model.id === 'string').map((model) => [model.id, model]))
224
+ : new Map();
225
+ // The UI edits only supported fields. Preserve every unexposed field on
226
+ // existing models so credential-blind edits do not erase Pi metadata.
227
+ const models = nextProvider.models.map((model) => {
228
+ const prior = previousModels.get(model.id);
229
+ if (!isPlainObject(prior)) return model;
230
+ const { id, name, reasoning, thinkingLevelMap, input, contextWindow, maxTokens, ...unexposed } = prior;
231
+ return { ...unexposed, ...model };
232
+ });
156
233
  const provider = {
157
234
  ...(previous && typeof previous === 'object' && !Array.isArray(previous) ? previous : {}),
158
235
  name: nextProvider.name,
159
236
  baseUrl: nextProvider.baseUrl,
160
237
  api: nextProvider.api,
161
- models: nextProvider.models,
238
+ models,
162
239
  ...(nextProvider.headers !== undefined ? { headers: nextProvider.headers } : {}),
163
240
  ...(nextProvider.apiKeyReference ? { apiKey: nextProvider.apiKeyReference } : {}),
164
241
  };
@@ -173,5 +250,54 @@ export const createPiModelConfigStore = ({ file }) => {
173
250
  return operation;
174
251
  };
175
252
 
176
- return { get, update };
253
+ const addModel = async (input) => {
254
+ const next = normalizeAddModel(input);
255
+ // Same cross-process serialization as update: models.json is shared
256
+ // across daemons, and the append must not lose concurrent writers.
257
+ const operation = writeChain.then(() => withCrossProcessLock(`${file}.lock`, async () => {
258
+ const config = await readConfig();
259
+ const previous = config.providers[next.providerId];
260
+ if (previous !== undefined && (typeof previous !== 'object' || Array.isArray(previous))) throw invalidModelConfig();
261
+ if (previous !== undefined && previous.models !== undefined && !Array.isArray(previous.models)) throw invalidModelConfig();
262
+ if (previous !== undefined) {
263
+ if (typeof previous.name !== 'string' || previous.name.trim().length === 0 || previous.name.length > 256
264
+ || typeof previous.baseUrl !== 'string' || !/^https?:\/\//.test(previous.baseUrl) || previous.baseUrl.length > 8_192
265
+ || !API_TYPES.has(previous.api)) throw invalidModelConfig();
266
+ const existingModels = Array.isArray(previous.models) ? previous.models : [];
267
+ const seen = new Set();
268
+ for (const entry of existingModels) {
269
+ if (!entry || typeof entry !== 'object' || typeof entry.id !== 'string') throw invalidModelConfig();
270
+ seen.add(entry.id.trim());
271
+ }
272
+ if (seen.has(next.model.id)) throw duplicateModelError();
273
+ const provider = {
274
+ ...previous,
275
+ models: [...existingModels, next.model],
276
+ };
277
+ config.providers[next.providerId] = provider;
278
+ await mkdir(dirname(file), { recursive: true, mode: 0o700 });
279
+ const temporary = join(dirname(file), `.${Date.now()}-${process.pid}-models.json.tmp`);
280
+ await writeFile(temporary, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 });
281
+ await rename(temporary, file);
282
+ return publicProvider(next.providerId, provider);
283
+ }
284
+ if (!next.seed) throw invalidModelConfig();
285
+ const provider = {
286
+ name: next.seed.name,
287
+ baseUrl: next.seed.baseUrl,
288
+ api: next.seed.api,
289
+ models: [next.model],
290
+ };
291
+ config.providers[next.providerId] = provider;
292
+ await mkdir(dirname(file), { recursive: true, mode: 0o700 });
293
+ const temporary = join(dirname(file), `.${Date.now()}-${process.pid}-models.json.tmp`);
294
+ await writeFile(temporary, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 });
295
+ await rename(temporary, file);
296
+ return publicProvider(next.providerId, provider);
297
+ }));
298
+ writeChain = operation.catch(() => {});
299
+ return operation;
300
+ };
301
+
302
+ return { get, update, addModel };
177
303
  };
@@ -5,38 +5,170 @@ import { join } from 'node:path';
5
5
 
6
6
  import { createPiModelConfigStore } from './model-config-store.js';
7
7
 
8
- describe('Pi models configuration store', () => {
9
- it('atomically writes a credential-blind custom provider while preserving unrelated Pi configuration', async () => {
10
- const root = await mkdtemp(join(tmpdir(), 'pichamber-pi-models-'));
11
- const file = join(root, 'models.json');
12
- await writeFile(file, `// Pi accepts comments in models.json\n{ "providers": { "builtin": { "baseUrl": "https://proxy.test", "api": "openai-completions" } } }`);
13
- const store = createPiModelConfigStore({ file });
8
+ const createStore = async (providers = {}) => {
9
+ const root = await mkdtemp(join(tmpdir(), 'pichamber-pi-models-'));
10
+ const file = join(root, 'models.json');
11
+ await writeFile(file, JSON.stringify({ providers }));
12
+ return { file, store: createPiModelConfigStore({ file }) };
13
+ };
14
+
15
+ const customProvider = (models = []) => ({
16
+ name: 'Custom',
17
+ baseUrl: 'https://api.example.test/v1',
18
+ api: 'openai-completions',
19
+ models,
20
+ });
14
21
 
22
+ describe('Pi models configuration store', () => {
23
+ it('writes supported custom-provider model fields without exposing credentials', async () => {
24
+ const { file, store } = await createStore({ builtin: { baseUrl: 'https://proxy.test', api: 'openai-completions' } });
15
25
  await expect(store.update({
16
- providerId: 'custom-provider', label: 'Custom Provider', baseUrl: 'https://api.example.test/v1',
17
- models: [{ id: 'model-1', providerId: 'custom-provider', label: 'Model 1', contextWindow: 128_000, supportsThinking: true }],
18
- headers: { 'X-Client': 'PiChamber' }, apiKeyReference: '{env:CUSTOM_API_KEY}',
19
- })).resolves.toEqual({
20
- providerId: 'custom-provider', label: 'Custom Provider', baseUrl: 'https://api.example.test/v1', api: 'openai-completions',
21
- models: [{ id: 'model-1', providerId: 'custom-provider', label: 'Model 1', contextWindow: 128_000, supportsThinking: true }],
22
- });
26
+ providerId: 'custom-provider',
27
+ label: 'Custom Provider',
28
+ baseUrl: 'https://api.example.test/v1',
29
+ models: [{
30
+ id: 'model-1', name: 'Model 1', contextWindow: 128_000, maxTokens: 8_192,
31
+ reasoning: true, input: ['text', 'image'], thinkingLevelMap: { high: 'high-effort' },
32
+ }],
33
+ headers: { 'X-Client': 'PiChamber' },
34
+ apiKeyReference: '{env:CUSTOM_API_KEY}',
35
+ })).resolves.toMatchObject({ providerId: 'custom-provider', models: [{ id: 'model-1', label: 'Model 1' }] });
23
36
 
24
37
  const persisted = JSON.parse(await readFile(file, 'utf8'));
25
38
  expect(persisted.providers.builtin).toEqual({ baseUrl: 'https://proxy.test', api: 'openai-completions' });
26
- expect(persisted.providers['custom-provider']).toMatchObject({ apiKey: '{env:CUSTOM_API_KEY}', headers: { 'X-Client': 'PiChamber' } });
39
+ expect(persisted.providers['custom-provider'].models[0]).toEqual({
40
+ id: 'model-1', name: 'Model 1', reasoning: true,
41
+ thinkingLevelMap: { high: 'high-effort' }, input: ['text', 'image'],
42
+ contextWindow: 128_000, maxTokens: 8_192,
43
+ });
27
44
  expect((await stat(file)).mode & 0o777).toBe(0o600);
28
45
  expect(JSON.stringify(await store.get('custom-provider'))).not.toContain('CUSTOM_API_KEY');
29
46
  expect(JSON.stringify(await store.get('custom-provider'))).not.toContain('X-Client');
30
- await expect(store.get('amazon-bedrock')).resolves.toBeNull();
31
- await expect(store.get('builtin')).resolves.toBeNull();
32
47
  });
33
48
 
34
- it('keeps malformed Pi models configuration explicit and rejects unsafe updates', async () => {
35
- const root = await mkdtemp(join(tmpdir(), 'pichamber-pi-models-'));
36
- const file = join(root, 'models.json');
49
+ it('preserves unexposed existing model metadata during provider edits', async () => {
50
+ const { file, store } = await createStore({ custom: customProvider([{
51
+ id: 'model-1', name: 'Old', maxTokens: 4096,
52
+ api: 'openai-responses', baseUrl: 'https://override.test',
53
+ headers: { 'X-Secret': 'value' }, compat: { supportsStrictMode: true },
54
+ cost: { input: 1 }, samplingParams: { temperature: 0.2 }, customMetadata: true,
55
+ }]) });
56
+
57
+ await store.update({
58
+ providerId: 'custom', label: 'Custom', baseUrl: 'https://api.example.test/v1', api: 'openai-completions',
59
+ models: [{ id: 'model-1', name: 'Edited', maxTokens: 8192 }],
60
+ });
61
+
62
+ const model = JSON.parse(await readFile(file, 'utf8')).providers.custom.models[0];
63
+ expect(model).toEqual({
64
+ id: 'model-1', name: 'Edited', maxTokens: 8192,
65
+ api: 'openai-responses', baseUrl: 'https://override.test',
66
+ headers: { 'X-Secret': 'value' }, compat: { supportsStrictMode: true },
67
+ cost: { input: 1 }, samplingParams: { temperature: 0.2 }, customMetadata: true,
68
+ });
69
+ expect(JSON.stringify(await store.get('custom'))).not.toContain('X-Secret');
70
+ });
71
+
72
+ it('appends one supported model while preserving providers and metadata', async () => {
73
+ const existing = customProvider([{ id: 'model-1', name: 'Model 1', cost: { input: 1 } }]);
74
+ existing.customMetadata = true;
75
+ const { file, store } = await createStore({ custom: existing, other: customProvider([{ id: 'other' }]) });
76
+
77
+ await expect(store.addModel({
78
+ providerId: 'custom',
79
+ model: { id: ' model-2 ', name: ' Model 2 ', contextWindow: 32_000 },
80
+ })).resolves.toMatchObject({ providerId: 'custom', models: [{ id: 'model-1' }, { id: 'model-2' }] });
81
+
82
+ const persisted = JSON.parse(await readFile(file, 'utf8'));
83
+ expect(persisted.providers.custom.models).toEqual([
84
+ { id: 'model-1', name: 'Model 1', cost: { input: 1 } },
85
+ { id: 'model-2', name: 'Model 2', contextWindow: 32_000 },
86
+ ]);
87
+ expect(persisted.providers.custom.customMetadata).toBe(true);
88
+ expect(persisted.providers.other.models).toEqual([{ id: 'other' }]);
89
+ });
90
+
91
+ it('appends to an existing provider whose model list is omitted', async () => {
92
+ const { file, store } = await createStore({
93
+ custom: { name: 'Custom', baseUrl: 'https://api.example.test/v1', api: 'openai-completions', customMetadata: true },
94
+ });
95
+
96
+ await store.addModel({ providerId: 'custom', model: { id: 'model-1' } });
97
+
98
+ expect(JSON.parse(await readFile(file, 'utf8')).providers.custom).toEqual({
99
+ name: 'Custom',
100
+ baseUrl: 'https://api.example.test/v1',
101
+ api: 'openai-completions',
102
+ customMetadata: true,
103
+ models: [{ id: 'model-1' }],
104
+ });
105
+ });
106
+
107
+ it('rejects an existing provider with missing metadata without writing', async () => {
108
+ const { file, store } = await createStore({ custom: { models: [] } });
109
+ const before = await readFile(file, 'utf8');
110
+
111
+ await expect(store.addModel({ providerId: 'custom', model: { id: 'model-1' } }))
112
+ .rejects.toMatchObject({ code: 'PI_MODEL_CONFIG_INVALID' });
113
+ await expect(readFile(file, 'utf8')).resolves.toBe(before);
114
+ });
115
+
116
+ it('rejects duplicate model IDs without writing', async () => {
117
+ const { file, store } = await createStore({ custom: customProvider([{ id: 'model-1' }]) });
118
+ const before = await readFile(file, 'utf8');
119
+ await expect(store.addModel({ providerId: 'custom', model: { id: ' model-1 ' } }))
120
+ .rejects.toMatchObject({ code: 'PI_MODEL_DUPLICATE' });
121
+ await expect(readFile(file, 'utf8')).resolves.toBe(before);
122
+ });
123
+
124
+ it('serializes concurrent duplicate additions', async () => {
125
+ const { file, store } = await createStore({ custom: customProvider([]) });
126
+ const first = store.addModel({ providerId: 'custom', model: { id: 'model-2' } });
127
+ const second = store.addModel({ providerId: 'custom', model: { id: ' model-2 ' } });
128
+ await expect(first).resolves.toBeTruthy();
129
+ await expect(second).rejects.toMatchObject({ code: 'PI_MODEL_DUPLICATE' });
130
+ expect(JSON.parse(await readFile(file, 'utf8')).providers.custom.models).toEqual([{ id: 'model-2' }]);
131
+ });
132
+
133
+ it('seeds a missing provider from validated provider metadata', async () => {
134
+ const { file, store } = await createStore();
135
+ await expect(store.addModel({ providerId: 'custom', model: { id: 'm1' } }))
136
+ .rejects.toMatchObject({ code: 'PI_MODEL_CONFIG_INVALID' });
137
+ await store.addModel({
138
+ providerId: 'custom',
139
+ model: { id: 'm1', name: 'M1', reasoning: true },
140
+ seed: { label: 'Custom', baseUrl: 'https://api.example.test/v1', api: 'openai-responses' },
141
+ });
142
+ expect(JSON.parse(await readFile(file, 'utf8')).providers.custom).toEqual({
143
+ name: 'Custom', baseUrl: 'https://api.example.test/v1', api: 'openai-responses',
144
+ models: [{ id: 'm1', name: 'M1', reasoning: true }],
145
+ });
146
+ });
147
+
148
+ it('rejects malformed supported fields without writing', async () => {
149
+ const cases = [
150
+ { id: '' },
151
+ { id: 'm', name: ' ' },
152
+ { id: 'm', contextWindow: 0 },
153
+ { id: 'm', maxTokens: -1 },
154
+ { id: 'm', input: [] },
155
+ { id: 'm', input: ['audio'] },
156
+ { id: 'm', input: ['text', 'text'] },
157
+ { id: 'm', thinkingLevelMap: { ultra: 'x' } },
158
+ { id: 'm', thinkingLevelMap: { low: 42 } },
159
+ { id: 'm', thinkingLevelMap: null },
160
+ ];
161
+ for (const model of cases) {
162
+ const { file, store } = await createStore({ custom: customProvider([]) });
163
+ const before = await readFile(file, 'utf8');
164
+ await expect(store.addModel({ providerId: 'custom', model })).rejects.toMatchObject({ code: 'PI_MODEL_CONFIG_INVALID' });
165
+ await expect(readFile(file, 'utf8')).resolves.toBe(before);
166
+ }
167
+ });
168
+
169
+ it('reports malformed files explicitly', async () => {
170
+ const { file, store } = await createStore();
37
171
  await writeFile(file, '{ invalid');
38
- const store = createPiModelConfigStore({ file });
39
172
  await expect(store.get('custom')).rejects.toMatchObject({ code: 'PI_MODEL_CONFIG_INVALID' });
40
- await expect(store.update({ providerId: '../unsafe', label: 'Unsafe', baseUrl: 'https://example.test', models: [] })).rejects.toMatchObject({ code: 'PI_MODEL_CONFIG_INVALID' });
41
173
  });
42
174
  });
@@ -351,8 +351,11 @@ const projectProviderConfig = (value) => {
351
351
  id: model.id,
352
352
  providerId: model.providerId,
353
353
  ...(typeof model.label === 'string' ? { label: model.label } : {}),
354
- ...(Number.isSafeInteger(model.contextWindow) ? { contextWindow: model.contextWindow } : {}),
355
354
  ...(model.supportsThinking === true ? { supportsThinking: true } : {}),
355
+ ...(model.thinkingLevelMap && typeof model.thinkingLevelMap === 'object' && !Array.isArray(model.thinkingLevelMap) ? { thinkingLevelMap: model.thinkingLevelMap } : {}),
356
+ ...(Array.isArray(model.input) ? { input: model.input } : {}),
357
+ ...(Number.isSafeInteger(model.contextWindow) ? { contextWindow: model.contextWindow } : {}),
358
+ ...(Number.isSafeInteger(model.maxTokens) ? { maxTokens: model.maxTokens } : {}),
356
359
  };
357
360
  }),
358
361
  },
@@ -1073,6 +1076,44 @@ export const registerPiRuntimeRoutes = (app, {
1073
1076
  }
1074
1077
  });
1075
1078
 
1079
+ app.post('/api/pi/providers/:providerId/models', async (req, res) => {
1080
+ const providerId = req.params.providerId;
1081
+ const body = req.body;
1082
+ if (typeof providerId !== 'string' || providerId.length === 0 || !body || typeof body !== 'object' || Array.isArray(body)) {
1083
+ res.status(400).json({ error: { code: 'INVALID_ARGUMENT' } });
1084
+ return;
1085
+ }
1086
+ const { id, name, reasoning, thinkingLevelMap, input, contextWindow, maxTokens } = body;
1087
+ const isPlainBag = (value) => Boolean(value) && typeof value === 'object' && !Array.isArray(value);
1088
+ if (typeof id !== 'string'
1089
+ || (name !== undefined && typeof name !== 'string')
1090
+ || (reasoning !== undefined && typeof reasoning !== 'boolean')
1091
+ || (thinkingLevelMap !== undefined && !isPlainBag(thinkingLevelMap))
1092
+ || (input !== undefined && !Array.isArray(input))
1093
+ || (contextWindow !== undefined && !Number.isSafeInteger(contextWindow))
1094
+ || (maxTokens !== undefined && !Number.isSafeInteger(maxTokens))) {
1095
+ res.status(400).json({ error: { code: 'INVALID_ARGUMENT' } });
1096
+ return;
1097
+ }
1098
+ try {
1099
+ const result = await getDaemonRuntime(getPiSessionDaemonRuntime).request('providers.models.add', {
1100
+ providerId,
1101
+ model: {
1102
+ id,
1103
+ ...(name !== undefined ? { name } : {}),
1104
+ ...(reasoning !== undefined ? { reasoning } : {}),
1105
+ ...(thinkingLevelMap !== undefined ? { thinkingLevelMap } : {}),
1106
+ ...(input !== undefined ? { input } : {}),
1107
+ ...(contextWindow !== undefined ? { contextWindow } : {}),
1108
+ ...(maxTokens !== undefined ? { maxTokens } : {}),
1109
+ },
1110
+ });
1111
+ res.status(201).json(projectProviderConfig(result));
1112
+ } catch (error) {
1113
+ writeDaemonError(res, error);
1114
+ }
1115
+ });
1116
+
1076
1117
  app.get('/api/pi/providers/:providerId/status', async (req, res) => {
1077
1118
  const providerId = req.params.providerId;
1078
1119
  if (typeof providerId !== 'string' || providerId.length === 0) {
@@ -338,7 +338,11 @@ describe('Pi runtime route', () => {
338
338
  if (command === 'providers.models.set') return { config: {
339
339
  providerId: 'custom', label: 'Custom', baseUrl: 'https://api.example.test/v1', api: 'openai-completions',
340
340
  apiKey: 'never-public', headers: { Authorization: 'never-public' },
341
- models: [{ id: 'model', providerId: 'custom', label: 'Model', contextWindow: 100, supportsThinking: true, private: true }],
341
+ models: [{
342
+ id: 'model', providerId: 'custom', label: 'Model', contextWindow: 100, maxTokens: 50,
343
+ supportsThinking: true, input: ['text', 'image'], samplingParams: { temperature: 0.2 },
344
+ compat: { supportsStrictMode: true }, headers: { 'X-Model': 'never-public' }, private: true,
345
+ }],
342
346
  } };
343
347
  throw new Error(`Unexpected command ${command}`);
344
348
  },
@@ -355,7 +359,10 @@ describe('Pi runtime route', () => {
355
359
  });
356
360
  await expect(response.json()).resolves.toEqual({ config: {
357
361
  providerId: 'custom', label: 'Custom', baseUrl: 'https://api.example.test/v1', api: 'openai-completions',
358
- models: [{ id: 'model', providerId: 'custom', label: 'Model', contextWindow: 100, supportsThinking: true }],
362
+ models: [{
363
+ id: 'model', providerId: 'custom', label: 'Model', contextWindow: 100, maxTokens: 50,
364
+ supportsThinking: true, input: ['text', 'image'],
365
+ }],
359
366
  } });
360
367
  expect(calls).toEqual([
361
368
  { command: 'providers.config.get', payload: { providerId: 'custom' } },
@@ -363,6 +370,101 @@ describe('Pi runtime route', () => {
363
370
  ]);
364
371
  });
365
372
 
373
+ it('adds a single provider model through the daemon without projecting credentials or headers', async () => {
374
+ const calls = [];
375
+ const runtime = {
376
+ request: async (command, payload) => {
377
+ calls.push({ command, payload });
378
+ if (command === 'providers.models.add') {
379
+ if (typeof payload?.model?.id !== 'string' || payload.model.id.trim().length === 0) {
380
+ throw Object.assign(new Error('The provider model request is invalid.'), { code: 'INVALID_ARGUMENT' });
381
+ }
382
+ return { config: {
383
+ providerId: 'custom', label: 'Custom', baseUrl: 'https://api.example.test/v1', api: 'openai-completions',
384
+ apiKey: 'never-public', headers: { Authorization: 'never-public' },
385
+ models: [
386
+ { id: 'model-1', providerId: 'custom', label: 'Model 1' },
387
+ { id: 'model-2', providerId: 'custom', label: 'Model 2', contextWindow: 32_000, supportsThinking: true, private: true },
388
+ ],
389
+ }, deferred: true };
390
+ }
391
+ throw new Error(`Unexpected command ${command}`);
392
+ },
393
+ };
394
+ const app = express();
395
+ app.use(express.json());
396
+ registerPiRuntimeRoutes(app, { getPiSessionDaemonRuntime: () => runtime });
397
+ server = await listen(app);
398
+ const base = `http://127.0.0.1:${server.address().port}/api/pi/providers/custom/models`;
399
+ const response = await fetch(base, {
400
+ method: 'POST', headers: { 'Content-Type': 'application/json' },
401
+ body: JSON.stringify({ id: 'model-2', name: 'Model 2', contextWindow: 32_000, reasoning: true }),
402
+ });
403
+ expect(response.status).toBe(201);
404
+ await expect(response.json()).resolves.toEqual({ config: {
405
+ providerId: 'custom', label: 'Custom', baseUrl: 'https://api.example.test/v1', api: 'openai-completions',
406
+ models: [
407
+ { id: 'model-1', providerId: 'custom', label: 'Model 1' },
408
+ { id: 'model-2', providerId: 'custom', label: 'Model 2', contextWindow: 32_000, supportsThinking: true },
409
+ ],
410
+ }, deferred: true });
411
+ expect(calls).toEqual([
412
+ { command: 'providers.models.add', payload: { providerId: 'custom', model: { id: 'model-2', name: 'Model 2', contextWindow: 32_000, reasoning: true } } },
413
+ ]);
414
+ const invalid = await fetch(base, {
415
+ method: 'POST', headers: { 'Content-Type': 'application/json' },
416
+ body: JSON.stringify({ id: ' ', label: 'Bad' }),
417
+ });
418
+ expect(invalid.status).toBe(400);
419
+ });
420
+
421
+ it('forwards supported model fields while dropping unsupported and unknown keys', async () => {
422
+ const calls = [];
423
+ const runtime = {
424
+ request: async (command, payload) => {
425
+ calls.push({ command, payload });
426
+ return { config: { providerId: 'custom', label: 'Custom', baseUrl: 'https://api.example.test/v1', api: 'openai-completions', models: [] } };
427
+ },
428
+ };
429
+ const app = express();
430
+ app.use(express.json());
431
+ registerPiRuntimeRoutes(app, { getPiSessionDaemonRuntime: () => runtime });
432
+ server = await listen(app);
433
+ const base = `http://127.0.0.1:${server.address().port}/api/pi/providers/custom/models`;
434
+ const advanced = {
435
+ id: 'model-2', name: 'Model 2', api: 'openai-responses', baseUrl: 'https://override.example.test/v1',
436
+ reasoning: true, thinkingLevelMap: { low: 'low-effort' }, input: ['text'], contextWindow: 64_000, maxTokens: 8_192,
437
+ cost: { input: 1, output: 2, cacheRead: 0, cacheWrite: 0 }, samplingParams: { temperature: 0.7 },
438
+ compat: { supportsStrictMode: true }, headers: { 'X-Model': 'secret' }, unknownField: 'dropped',
439
+ };
440
+ const response = await fetch(base, {
441
+ method: 'POST', headers: { 'Content-Type': 'application/json' },
442
+ body: JSON.stringify(advanced),
443
+ });
444
+ expect(response.status).toBe(201);
445
+ expect(calls).toHaveLength(1);
446
+ expect(calls[0].command).toBe('providers.models.add');
447
+ expect(calls[0].payload.providerId).toBe('custom');
448
+ expect(calls[0].payload.model).toEqual({
449
+ id: 'model-2', name: 'Model 2', reasoning: true,
450
+ thinkingLevelMap: { low: 'low-effort' }, input: ['text'], contextWindow: 64_000, maxTokens: 8_192,
451
+ });
452
+ // Light shape rejection stays at the route before reaching the daemon.
453
+ const badShapes = [
454
+ { id: 'm', contextWindow: 'large' },
455
+ { id: 'm', input: {} },
456
+ { id: 'm', thinkingLevelMap: [] },
457
+ ];
458
+ for (const body of badShapes) {
459
+ const invalid = await fetch(base, {
460
+ method: 'POST', headers: { 'Content-Type': 'application/json' },
461
+ body: JSON.stringify(body),
462
+ });
463
+ expect(invalid.status).toBe(400);
464
+ }
465
+ expect(calls).toHaveLength(1);
466
+ });
467
+
366
468
  it('preserves deferred status for accepted Pi mutations', async () => {
367
469
  const runtime = {
368
470
  request: async (command) => {