@kabmo-labs/kabmo 0.23.0 → 0.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (151) hide show
  1. package/dist/client/index.html +1 -1
  2. package/dist/client/index.js +679 -679
  3. package/dist/client/static/js/{index-ph0q59rs.js → index-jcr5twtp.js} +769 -767
  4. package/dist/client/static/js/index-z3w7n85q.css +1 -0
  5. package/package.json +1 -1
  6. package/src/client/components/common/Modal.tsx +2 -6
  7. package/src/client/components/layout/desktop-layout/WorkspacePanels.tsx +7 -1
  8. package/src/client/components/layout/session-sidebar/about-modal/HarnessTable.test.tsx +20 -0
  9. package/src/client/components/layout/session-sidebar/about-modal/HarnessTable.tsx +23 -7
  10. package/src/client/components/layout/session-sidebar/about-modal/index.test.tsx +122 -0
  11. package/src/client/components/layout/session-sidebar/about-modal/index.tsx +27 -11
  12. package/src/client/components/settings/categories/harness-settings/EnvProviderForm.tsx +31 -0
  13. package/src/client/components/settings/categories/harness-settings/provider-panel.test.tsx +49 -0
  14. package/src/client/components/workspace/chat-timeline/ChatOverlays.tsx +5 -2
  15. package/src/client/components/workspace/chat-timeline/MessageList.test.ts +14 -0
  16. package/src/client/components/workspace/chat-timeline/chat-input/index.tsx +4 -3
  17. package/src/client/components/workspace/chat-timeline/index.tsx +2 -1
  18. package/src/client/components/workspace/chat-timeline/pending-harness.test.tsx +1 -1
  19. package/src/client/components/workspace/chat-timeline/tool-renderers/ask-panel/FrameControl.tsx +11 -20
  20. package/src/client/components/workspace/chat-timeline/tool-renderers/ask-panel/GroupedAsk.tsx +1 -1
  21. package/src/client/components/workspace/chat-timeline/tool-renderers/ask-panel/QuestionBlock.tsx +1 -1
  22. package/src/client/components/workspace/chat-timeline/tool-renderers/ask-panel/drafts.ts +1 -1
  23. package/src/client/components/workspace/chat-timeline/tool-renderers/ask-panel/index.tsx +2 -1
  24. package/src/client/components/workspace/file-explorer/index.test.ts +25 -0
  25. package/src/client/components/workspace/file-explorer/index.tsx +9 -3
  26. package/src/client/components/workspace/model-dropdown/harness-models.test.ts +17 -0
  27. package/src/client/components/workspace/model-dropdown/harness-models.ts +33 -18
  28. package/src/client/components/workspace/model-dropdown/index.tsx +3 -3
  29. package/src/client/components/workspace/model-dropdown/popover-metrics.ts +4 -1
  30. package/src/client/data/settings/omp-schema.json +4 -4
  31. package/src/client/hooks/chat/timeline/actions.ts +2 -2
  32. package/src/client/hooks/chat/timeline/ask-frames.ts +5 -4
  33. package/src/client/hooks/chat/timeline/new-chat-open.test.ts +86 -0
  34. package/src/client/hooks/chat/timeline/new-chat-open.ts +23 -5
  35. package/src/client/hooks/chat/timeline/new-chat.test.ts +32 -4
  36. package/src/client/hooks/chat/timeline/new-chat.ts +18 -6
  37. package/src/client/hooks/chat/timeline/rewind-actions.test.ts +24 -1
  38. package/src/client/hooks/chat/timeline/rewind-actions.ts +15 -11
  39. package/src/client/hooks/chat/timeline/run-identity.test.ts +52 -0
  40. package/src/client/hooks/chat/timeline/run-identity.ts +23 -11
  41. package/src/client/hooks/chat/timeline/send-execute.test.ts +17 -0
  42. package/src/client/hooks/chat/timeline/send-props.ts +5 -3
  43. package/src/client/hooks/chat/timeline/send-steer.test.ts +1 -3
  44. package/src/client/hooks/chat/timeline/send.test-util.ts +1 -1
  45. package/src/client/hooks/chat/timeline/send.test.ts +1 -3
  46. package/src/client/hooks/chat/timeline/send.ts +8 -3
  47. package/src/client/hooks/chat/timeline/session-load.test-util.ts +6 -2
  48. package/src/client/hooks/chat/timeline/session-load.test.ts +31 -0
  49. package/src/client/hooks/chat/timeline/session-load.ts +6 -14
  50. package/src/client/hooks/chat/timeline/session-shapes.ts +32 -0
  51. package/src/client/hooks/models/harness-catalog.ts +114 -0
  52. package/src/client/hooks/models/provider-writes.test.ts +81 -0
  53. package/src/client/hooks/models/provider-writes.ts +10 -3
  54. package/src/client/hooks/models/use-harnesses-controller.ts +57 -0
  55. package/src/client/hooks/models/use-harnesses-signal.test.ts +128 -0
  56. package/src/client/hooks/models/use-harnesses.test.ts +2 -1
  57. package/src/client/hooks/models/use-harnesses.ts +48 -114
  58. package/src/client/tailwind.css +9 -1
  59. package/src/server/lib/harness/acp/activation.test.ts +81 -0
  60. package/src/server/lib/harness/acp/activation.ts +72 -0
  61. package/src/server/lib/harness/acp/frames.test.ts +50 -1
  62. package/src/server/lib/harness/acp/frames.ts +17 -5
  63. package/src/server/lib/harness/acp/mapper.ts +6 -4
  64. package/src/server/lib/harness/acp/session-config.test.ts +73 -0
  65. package/src/server/lib/harness/acp/session-config.ts +87 -6
  66. package/src/server/lib/harness/acp/session-handshake.ts +9 -2
  67. package/src/server/lib/harness/acp/session-idle.ts +51 -0
  68. package/src/server/lib/harness/acp/session-notifications.ts +19 -3
  69. package/src/server/lib/harness/acp/session-observers.test.ts +9 -0
  70. package/src/server/lib/harness/acp/session-options.ts +33 -0
  71. package/src/server/lib/harness/acp/session-reaper.test.ts +96 -0
  72. package/src/server/lib/harness/acp/session.test-util.ts +31 -2
  73. package/src/server/lib/harness/acp/session.test.ts +65 -3
  74. package/src/server/lib/harness/acp/session.ts +20 -20
  75. package/src/server/lib/harness/acp/turn.ts +31 -7
  76. package/src/server/lib/harness/auto-probe.server.test.ts +121 -0
  77. package/src/server/lib/harness/auto-probe.server.ts +178 -0
  78. package/src/server/lib/harness/config.server.test.ts +1 -1
  79. package/src/server/lib/harness/config.server.ts +1 -1
  80. package/src/server/lib/harness/launch-table.ts +195 -0
  81. package/src/server/lib/harness/launch.test.ts +37 -0
  82. package/src/server/lib/harness/launch.ts +13 -115
  83. package/src/server/lib/harness/provider-entry.ts +32 -0
  84. package/src/server/lib/harness/provider-file.server.ts +3 -0
  85. package/src/server/lib/harness/provider-sources.server.test.ts +45 -0
  86. package/src/server/lib/harness/provider-sources.server.ts +26 -2
  87. package/src/server/lib/harness/provider-write.server.ts +21 -32
  88. package/src/server/lib/harness/provider-zcode.server.test.ts +270 -0
  89. package/src/server/lib/harness/provider-zcode.server.ts +324 -0
  90. package/src/server/lib/harness/update-state.server.ts +15 -20
  91. package/src/server/lib/lifecycle/after-listen.ts +7 -0
  92. package/src/server/lib/models/registry-refresh.server.test.ts +87 -0
  93. package/src/server/lib/models/registry-refresh.server.ts +98 -0
  94. package/src/server/lib/omp/rpc/child-config.ts +5 -4
  95. package/src/server/lib/omp/rpc/constants.test.ts +2 -1
  96. package/src/server/lib/omp/rpc/forked-resume.test.ts +14 -3
  97. package/src/server/lib/omp/session/delete-flow.server.ts +15 -8
  98. package/src/server/lib/omp/session/delete.server.ts +12 -0
  99. package/src/server/routes/chat/rewind.test.ts +147 -0
  100. package/src/server/routes/chat/rewind.ts +29 -7
  101. package/src/server/routes/chat/session.test.ts +165 -10
  102. package/src/server/routes/chat/session.ts +60 -7
  103. package/src/server/routes/harness/import-action.ts +18 -4
  104. package/src/server/routes/harness/root.ts +8 -49
  105. package/src/server/routes/harness/toggle.test.ts +20 -0
  106. package/src/server/routes/harness/update.ts +49 -7
  107. package/src/server/routes/harness/versions.ts +5 -1
  108. package/src/server/routes/sessions/delete-acp.test.ts +227 -0
  109. package/src/server/routes/settings/model-override.ts +5 -2
  110. package/src/server/routes/settings/provider-entry.ts +2 -2
  111. package/src/server/routes/settings/provider-model.ts +2 -2
  112. package/src/server/routes/settings/provider-models.ts +2 -2
  113. package/src/server/routes/settings/provider-refresh.ts +6 -4
  114. package/src/server/routes/settings/providers.ts +3 -1
  115. package/src/server/routes/settings/settings-config-routes.test.ts +10 -2
  116. package/src/shared/lib/chat/ask-form/fields.ts +76 -0
  117. package/src/shared/lib/chat/ask-form/index.ts +323 -0
  118. package/src/shared/lib/chat/ask-form/tokens.ts +199 -0
  119. package/src/shared/lib/chat/ask-form/types.ts +43 -0
  120. package/src/shared/lib/chat/ask-form.test.ts +137 -0
  121. package/src/shared/lib/chat/ask-questions.test.ts +65 -1
  122. package/src/shared/lib/chat/ask-questions.ts +51 -145
  123. package/src/shared/lib/chat/ask-results.ts +198 -0
  124. package/src/shared/lib/chat/timeline/omp-callbacks.ts +13 -1
  125. package/src/shared/lib/chat/timeline/prompt-error.test.ts +146 -0
  126. package/src/shared/lib/chat/timeline/prompt-error.ts +88 -0
  127. package/src/shared/lib/harness/catalog.test.ts +1 -1
  128. package/src/shared/lib/harness/config-fields.test.ts +4 -0
  129. package/src/shared/lib/harness/config-fields.ts +19 -4
  130. package/src/shared/lib/harness/dialects.test.ts +8 -0
  131. package/src/shared/lib/harness/dialects.ts +12 -0
  132. package/src/shared/lib/harness/provider-facts.test.ts +32 -8
  133. package/src/shared/lib/harness/provider-facts.ts +46 -11
  134. package/src/shared/lib/harness/providers.ts +9 -0
  135. package/src/shared/lib/harness/rewind.ts +24 -0
  136. package/src/shared/lib/harness/update-plan.test.ts +51 -1
  137. package/src/shared/lib/harness/update-plan.ts +47 -7
  138. package/src/shared/lib/harness/updates.test.ts +22 -0
  139. package/src/shared/lib/harness/updates.ts +24 -1
  140. package/src/shared/lib/models/client.ts +10 -1
  141. package/src/shared/lib/omp/dialog-methods.ts +4 -3
  142. package/src/shared/lib/theme/css.ts +2 -0
  143. package/src/shared/lib/theme/ink-scale.ts +21 -1
  144. package/src/shared/lib/theme/theme.test.ts +25 -9
  145. package/src/shared/lib/ui/safe-area.test.ts +28 -0
  146. package/src/shared/lib/ui/safe-area.ts +42 -0
  147. package/src/shared/types/harness.ts +30 -4
  148. package/src/test-support/file-explorer-render.test-util.ts +37 -0
  149. package/src/test-support/file-explorer.test-util.ts +20 -18
  150. package/src/test-support/harness-table.test-util.ts +6 -3
  151. package/dist/client/static/js/index-jhmg4w91.css +0 -1
@@ -0,0 +1,270 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * ZCode's personal provider file is a RULE GRAPH, and these cases pin the two
8
+ * things a map-shaped writer would get wrong:
9
+ *
10
+ * - a provider rule alone is invisible (the bridge builds its dropdown from
11
+ * `modelConfigRules`), so a write must emit one model rule per id;
12
+ * - the file also holds the desktop's manual capability blocks, headers and
13
+ * default selection — a merge that rewrites them breaks an install.
14
+ *
15
+ * Measured against the bridge's own 0.82.3 reader (`loadPersonalModels` /
16
+ * `appendPersonalOnlyProviders`): with this file present, `session/new`
17
+ * advertises `kenari\qwen3-8-27b:free` even when `config.json` does not exist.
18
+ */
19
+
20
+ import { describe, expect, test } from 'bun:test';
21
+ import fs from 'node:fs';
22
+ import os from 'node:os';
23
+ import path from 'node:path';
24
+
25
+ import { readZcodeProviderKey, readZcodeProviders, writeZcodeProvider } from '@/server/lib/harness/provider-zcode.server';
26
+ import { ProviderWriteError } from '@/server/lib/harness/provider-write-error';
27
+ import { isWindows } from '@/test-support/platform';
28
+
29
+ function tempFile(content?: string): string {
30
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'kabmo-zcode-'));
31
+ const file = path.join(dir, 'provider_config.json');
32
+ if (content !== undefined) fs.writeFileSync(file, content, { mode: 0o600 });
33
+ return file;
34
+ }
35
+
36
+ const EXISTING = JSON.stringify({
37
+ schemaVersion: 1,
38
+ config: {
39
+ providerConfigRules: {
40
+ providerRules: [
41
+ {
42
+ providerId: 'existing',
43
+ providerName: 'Existing Gateway',
44
+ enabled: true,
45
+ config: {
46
+ group: 'standard-personal',
47
+ access: { type: 'api-key', apiKey: 'sk-keep' },
48
+ api: { type: 'anthropic-messages', baseUrl: 'https://old.example', headers: { 'X-Keep': '1' } },
49
+ personalModelIds: ['old-model'],
50
+ modelOrder: ['old-model'],
51
+ visibility: 'visible',
52
+ },
53
+ },
54
+ ],
55
+ },
56
+ modelConfigRules: {
57
+ providerModelRules: [],
58
+ manualProviderModelRules: [
59
+ {
60
+ providerId: 'existing',
61
+ modelId: 'old-model',
62
+ config: {
63
+ enabled: true,
64
+ properties: { contextWindow: 64000, supportsJsonSchemaOutput: false },
65
+ optionSpecs: { reasoningLevel: { values: ['low'], map: '{}' } },
66
+ },
67
+ },
68
+ ],
69
+ },
70
+ defaultModelSelection: { providerId: 'existing', modelId: 'old-model' },
71
+ },
72
+ }, null, 2);
73
+
74
+ describe('reading the personal provider rules', () => {
75
+ test('a provider is listed with its model rules, personal ids and no key', () => {
76
+ const rows = readZcodeProviders(EXISTING, 'zcode');
77
+ expect(rows).toHaveLength(1);
78
+ expect(rows[0]).toMatchObject({
79
+ id: 'existing',
80
+ name: 'Existing Gateway',
81
+ baseUrl: 'https://old.example',
82
+ dialect: 'anthropic-messages',
83
+ protocol: 'anthropic-messages',
84
+ models: ['old-model'],
85
+ contextWindow: { 'old-model': 64000 },
86
+ hasKey: true,
87
+ source: 'zcode',
88
+ });
89
+ // The credential itself never leaves the file.
90
+ expect('apiKey' in rows[0]!).toBe(false);
91
+ });
92
+
93
+ test('custom providers added only through personalModelIds stay visible', () => {
94
+ const text = JSON.stringify({
95
+ schemaVersion: 1,
96
+ config: {
97
+ providerConfigRules: {
98
+ providerRules: [{
99
+ providerId: 'gateway',
100
+ providerName: 'Gateway',
101
+ config: { api: { type: 'openai-chat-completions', baseUrl: 'https://gw.example/v1' }, personalModelIds: ['m-1'] },
102
+ }],
103
+ },
104
+ modelConfigRules: { providerModelRules: [], manualProviderModelRules: [] },
105
+ },
106
+ });
107
+ expect(readZcodeProviders(text, 'zcode')[0]?.models).toEqual(['m-1']);
108
+ });
109
+
110
+ test('builtin and account ids are runtime-owned, but `local` is a custom id', () => {
111
+ const text = JSON.stringify({
112
+ schemaVersion: 1,
113
+ config: {
114
+ providerConfigRules: {
115
+ providerRules: [
116
+ { providerId: 'builtin:zai-coding-plan', config: {} },
117
+ { providerId: 'account:bigmodel-individual-coding-plan', config: {} },
118
+ { providerId: 'local', providerName: 'Local llama.cpp', config: {} },
119
+ ],
120
+ },
121
+ modelConfigRules: { providerModelRules: [], manualProviderModelRules: [] },
122
+ },
123
+ });
124
+ // ZCode's own reference uses `local` as its custom-provider example; the
125
+ // shared vendor census names `local` too and must not hide it here.
126
+ expect(readZcodeProviders(text, 'zcode').map((row) => row.id)).toEqual(['local']);
127
+ });
128
+
129
+ test('a malformed file yields no rows and no key', () => {
130
+ expect(readZcodeProviders('{not json', 'zcode')).toEqual([]);
131
+ expect(readZcodeProviderKey('{not json', 'existing')).toBeNull();
132
+ });
133
+
134
+ test('a stored key is read only by id', () => {
135
+ expect(readZcodeProviderKey(EXISTING, 'existing')).toBe('sk-keep');
136
+ expect(readZcodeProviderKey(EXISTING, 'missing')).toBeNull();
137
+ });
138
+ });
139
+
140
+ describe('writing a provider into the rule graph', () => {
141
+ test('a new provider gets a rule and one model rule per id', async () => {
142
+ const file = tempFile(EXISTING);
143
+ const result = await writeZcodeProvider({
144
+ path: file,
145
+ id: 'kenari',
146
+ draft: {
147
+ id: 'kenari',
148
+ name: 'Kenari',
149
+ baseUrl: 'https://kenari.id/v1',
150
+ protocol: 'openai-chat',
151
+ models: ['qwen3-8-27b:free'],
152
+ apiKey: 'kn-1',
153
+ contextWindow: { 'qwen3-8-27b:free': 262144 },
154
+ },
155
+ dialect: 'openai-chat-completions',
156
+ });
157
+ expect(result.replaced).toBe(false);
158
+ // POSIX only: Windows has no permission bits and `statSync().mode` there
159
+ // reports a synthesised 0o666 for every file — measured on the Windows gate
160
+ // as `Expected: 384, Received: 438` (0o600 vs 0o666) for a write that set
161
+ // the mode correctly on the host. `chmod` is a no-op there.
162
+ if (!isWindows) expect(fs.statSync(file).mode & 0o777).toBe(0o600);
163
+
164
+ const text = fs.readFileSync(file, 'utf8');
165
+ expect(text.endsWith('}')).toBe(true);
166
+ const doc = JSON.parse(text);
167
+ const rules = doc.config.providerConfigRules.providerRules;
168
+ expect(rules).toHaveLength(2);
169
+ expect(rules[1]).toMatchObject({
170
+ providerId: 'kenari',
171
+ providerName: 'Kenari',
172
+ enabled: true,
173
+ config: {
174
+ access: { type: 'api-key', apiKey: 'kn-1' },
175
+ api: { type: 'openai-chat-completions', baseUrl: 'https://kenari.id/v1' },
176
+ personalModelIds: ['qwen3-8-27b:free'],
177
+ },
178
+ });
179
+ expect(doc.config.modelConfigRules.providerModelRules).toEqual([{
180
+ providerId: 'kenari',
181
+ modelId: 'qwen3-8-27b:free',
182
+ config: {
183
+ enabled: true,
184
+ properties: { contextWindow: 262144 },
185
+ optionSpecs: { reasoningLevel: { values: ['disabled', 'enabled'], map: '{}' } },
186
+ },
187
+ }]);
188
+ // The desktop's own state is not ours to rewrite.
189
+ expect(doc.config.modelConfigRules.manualProviderModelRules).toHaveLength(1);
190
+ expect(doc.config.defaultModelSelection).toEqual({ providerId: 'existing', modelId: 'old-model' });
191
+ });
192
+
193
+ test('an update keeps the stored key, headers and a manual model rule', async () => {
194
+ const file = tempFile(EXISTING);
195
+ await writeZcodeProvider({
196
+ path: file,
197
+ id: 'existing',
198
+ draft: {
199
+ id: 'existing',
200
+ name: 'Existing Gateway',
201
+ baseUrl: 'https://new.example',
202
+ protocol: 'anthropic-messages',
203
+ models: ['new-model'],
204
+ },
205
+ dialect: 'anthropic-messages',
206
+ });
207
+ const doc = JSON.parse(fs.readFileSync(file, 'utf8'));
208
+ const rule = doc.config.providerConfigRules.providerRules[0];
209
+ expect(rule.config.access.apiKey).toBe('sk-keep');
210
+ expect(rule.config.api).toMatchObject({
211
+ type: 'anthropic-messages',
212
+ baseUrl: 'https://new.example',
213
+ headers: { 'X-Keep': '1' },
214
+ });
215
+ // Union, not replacement: a model the user already had is not dropped.
216
+ expect(rule.config.personalModelIds).toEqual(['old-model', 'new-model']);
217
+ // The manual rule stays manual (moving it would drop the capability block),
218
+ // and the new model gets a smart rule.
219
+ expect(doc.config.modelConfigRules.manualProviderModelRules).toHaveLength(1);
220
+ expect(doc.config.modelConfigRules.providerModelRules).toEqual([{
221
+ providerId: 'existing',
222
+ modelId: 'new-model',
223
+ config: {
224
+ enabled: true,
225
+ optionSpecs: { reasoningLevel: { values: ['disabled', 'enabled'], map: '{}' } },
226
+ },
227
+ }]);
228
+ });
229
+
230
+ test('a model rule is never duplicated across the two arrays', async () => {
231
+ const file = tempFile(EXISTING);
232
+ await writeZcodeProvider({
233
+ path: file,
234
+ id: 'existing',
235
+ draft: {
236
+ id: 'existing',
237
+ name: 'Existing Gateway',
238
+ baseUrl: 'https://old.example',
239
+ protocol: 'anthropic-messages',
240
+ models: ['old-model'],
241
+ },
242
+ dialect: 'anthropic-messages',
243
+ });
244
+ const doc = JSON.parse(fs.readFileSync(file, 'utf8'));
245
+ expect(doc.config.modelConfigRules.providerModelRules).toEqual([]);
246
+ expect(doc.config.modelConfigRules.manualProviderModelRules[0].modelId).toBe('old-model');
247
+ });
248
+
249
+ test('a malformed file is refused untouched', async () => {
250
+ const file = tempFile('{broken');
251
+ await expect(writeZcodeProvider({
252
+ path: file,
253
+ id: 'kenari',
254
+ draft: { id: 'kenari', name: 'Kenari', baseUrl: 'https://kenari.id/v1', protocol: 'openai-chat', models: ['m'] },
255
+ dialect: 'openai-chat-completions',
256
+ })).rejects.toThrow(ProviderWriteError);
257
+ expect(fs.readFileSync(file, 'utf8')).toBe('{broken');
258
+ });
259
+
260
+ test('a provider with no endpoint is refused instead of written broken', async () => {
261
+ const file = tempFile();
262
+ await expect(writeZcodeProvider({
263
+ path: file,
264
+ id: 'kenari',
265
+ draft: { id: 'kenari', name: 'Kenari', protocol: 'openai-chat', models: ['m'] },
266
+ dialect: 'openai-chat-completions',
267
+ })).rejects.toThrow(/base URL/);
268
+ expect(fs.existsSync(file)).toBe(false);
269
+ });
270
+ });
@@ -0,0 +1,324 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * ZCode's personal providers: `~/.zcode/v2/provider_config.json` (3.12+).
8
+ *
9
+ * The shape is a RULE GRAPH, not the map every other registry uses:
10
+ *
11
+ * ```json
12
+ * { "schemaVersion": 1,
13
+ * "config": {
14
+ * "providerConfigRules": { "providerRules": [ { "providerId", "providerName", "config": {
15
+ * "access": { "type": "api-key", "apiKey" },
16
+ * "api": { "type": "openai-chat-completions", "baseUrl" } } } ] },
17
+ * "modelConfigRules": {
18
+ * "providerModelRules": [ { "providerId", "modelId", "config": { "enabled": true } } ],
19
+ * "manualProviderModelRules": [] } } }
20
+ * ```
21
+ *
22
+ * Two measured reasons the file is written carefully:
23
+ *
24
+ * - **A provider alone serves nothing.** The bridge builds its dropdown from
25
+ * the MODEL rules (`loadPersonalModels` reads `modelConfigRules` only), so a
26
+ * provider rule without a model rule is invisible. The writer therefore emits
27
+ * one rule per model id, beside the provider.
28
+ * - **The top level is strict.** `schemaVersion` and `config` are the only keys
29
+ * the backend accepts; everything inside `config` is carried through
30
+ * untouched. This writer merges exactly what it owns and preserves the rest,
31
+ * including manual model rules and the user's own headers.
32
+ *
33
+ * `~/.zcode/v2/config.json` is deliberately NOT touched: it is the desktop app's
34
+ * legacy provider map and its credentials. Personal providers belong in the file
35
+ * this module owns.
36
+ */
37
+
38
+ import { withConfigLock } from '@/server/lib/fs/config-lock';
39
+ import { writeFileAtomic } from '@/server/lib/fs/atomic-write';
40
+ import { asRecord, type ProviderDraft } from '@/server/lib/harness/provider-entry';
41
+ import { ProviderWriteError } from '@/server/lib/harness/provider-write-error';
42
+ import { protocolOfSourceDialect } from '@/shared/lib/harness/dialects';
43
+ import type { ImportableProvider } from '@/server/lib/harness/provider-sources.server';
44
+ import type { ProviderWriteResult } from '@/server/lib/harness/provider-write.server';
45
+
46
+ function stringList(value: unknown): string[] {
47
+ return Array.isArray(value) ? value.filter((entry): entry is string => typeof entry === 'string' && entry.length > 0) : [];
48
+ }
49
+
50
+ function ruleProviderId(rule: Record<string, unknown>): string {
51
+ return typeof rule.providerId === 'string' ? rule.providerId : '';
52
+ }
53
+
54
+ /** The provider rules and both model-rule arrays, created when absent. */
55
+ function ruleTables(doc: Record<string, unknown>): {
56
+ providers: unknown[];
57
+ smart: unknown[];
58
+ manual: unknown[];
59
+ } {
60
+ const config = asRecord(doc.config);
61
+ doc.config = config;
62
+ const providerConfigRules = asRecord(config.providerConfigRules);
63
+ config.providerConfigRules = providerConfigRules;
64
+ const modelConfigRules = asRecord(config.modelConfigRules);
65
+ config.modelConfigRules = modelConfigRules;
66
+ const providers = Array.isArray(providerConfigRules.providerRules) ? providerConfigRules.providerRules : [];
67
+ providerConfigRules.providerRules = providers;
68
+ const smart = Array.isArray(modelConfigRules.providerModelRules) ? modelConfigRules.providerModelRules : [];
69
+ modelConfigRules.providerModelRules = smart;
70
+ const manual = Array.isArray(modelConfigRules.manualProviderModelRules) ? modelConfigRules.manualProviderModelRules : [];
71
+ modelConfigRules.manualProviderModelRules = manual;
72
+ return { providers, smart, manual };
73
+ }
74
+
75
+ /** Model ids declared by BOTH rule arrays for one provider, in file order. */
76
+ function ruleModelIds(doc: Record<string, unknown>, providerId: string): string[] {
77
+ const { smart, manual } = ruleTables(doc);
78
+ const out: string[] = [];
79
+ for (const rule of [...smart, ...manual]) {
80
+ const entry = asRecord(rule);
81
+ if (ruleProviderId(entry) !== providerId) continue;
82
+ const modelId = typeof entry.modelId === 'string' ? entry.modelId : '';
83
+ if (!modelId || asRecord(entry.config).enabled === false) continue;
84
+ if (!out.includes(modelId)) out.push(modelId);
85
+ }
86
+ return out;
87
+ }
88
+
89
+ /** Context windows a smart/manual model rule declares. */
90
+ function ruleContextWindows(doc: Record<string, unknown>): Record<string, number> {
91
+ const { smart, manual } = ruleTables(doc);
92
+ const out: Record<string, number> = {};
93
+ for (const rule of [...smart, ...manual]) {
94
+ const entry = asRecord(rule);
95
+ const providerId = ruleProviderId(entry);
96
+ const modelId = typeof entry.modelId === 'string' ? entry.modelId : '';
97
+ const size = asRecord(asRecord(entry.config).properties).contextWindow;
98
+ if (providerId && modelId && typeof size === 'number' && size > 0) out[`${providerId}/${modelId}`] = size;
99
+ }
100
+ return out;
101
+ }
102
+
103
+ /**
104
+ * Every custom provider the file holds, credential-free.
105
+ *
106
+ * A malformed document yields nothing: this reader feeds a settings card, and
107
+ * refusing to draw the page over the agent's own broken file would hide the only
108
+ * place that can explain it.
109
+ */
110
+ export function readZcodeProviders(text: string | null, source: ImportableProvider['source']): ImportableProvider[] {
111
+ if (!text) return [];
112
+ let doc: Record<string, unknown>;
113
+ try {
114
+ const parsed: unknown = JSON.parse(text);
115
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return [];
116
+ doc = parsed as Record<string, unknown>;
117
+ } catch {
118
+ return [];
119
+ }
120
+ const { providers } = ruleTables(doc);
121
+ const windows = ruleContextWindows(doc);
122
+ const out: ImportableProvider[] = [];
123
+ for (const raw of providers) {
124
+ const rule = asRecord(raw);
125
+ const id = ruleProviderId(rule);
126
+ if (!id || id.startsWith('builtin:') || id.startsWith('account:')) continue;
127
+ const config = asRecord(rule.config);
128
+ const access = asRecord(config.access);
129
+ const api = asRecord(config.api);
130
+ const dialect = typeof api.type === 'string' ? api.type : undefined;
131
+ const protocol = protocolOfSourceDialect(dialect);
132
+ const models = [...ruleModelIds(doc, id)];
133
+ for (const declared of stringList(config.personalModelIds)) {
134
+ if (!models.includes(declared)) models.push(declared);
135
+ }
136
+ const contextWindow = Object.fromEntries(
137
+ models.flatMap((modelId) => {
138
+ const size = windows[`${id}/${modelId}`];
139
+ return size ? [[modelId, size]] : [];
140
+ }),
141
+ );
142
+ out.push({
143
+ id,
144
+ name: typeof rule.providerName === 'string' && rule.providerName.trim() ? rule.providerName : id,
145
+ ...(typeof api.baseUrl === 'string' && api.baseUrl ? { baseUrl: api.baseUrl } : {}),
146
+ ...(dialect ? { dialect } : {}),
147
+ ...(protocol ? { protocol } : {}),
148
+ models,
149
+ ...(Object.keys(contextWindow).length > 0 ? { contextWindow } : {}),
150
+ source,
151
+ hasKey: typeof access.apiKey === 'string' && access.apiKey.length > 0,
152
+ });
153
+ }
154
+ return out;
155
+ }
156
+
157
+ /** One provider's credential, read only by the request that writes a target. */
158
+ export function readZcodeProviderKey(text: string | null, providerId: string): string | null {
159
+ if (!text) return null;
160
+ try {
161
+ const parsed: unknown = JSON.parse(text);
162
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null;
163
+ const { providers } = ruleTables(parsed as Record<string, unknown>);
164
+ const rule = providers.map(asRecord).find((entry) => ruleProviderId(entry) === providerId);
165
+ const key = asRecord(asRecord(rule?.config).access).apiKey;
166
+ return typeof key === 'string' && key.length > 0 ? key : null;
167
+ } catch {
168
+ return null;
169
+ }
170
+ }
171
+
172
+ /** An empty document in the file's canonical shape. */
173
+ function emptyDocument(): Record<string, unknown> {
174
+ const doc: Record<string, unknown> = { schemaVersion: 1 };
175
+ ruleTables(doc);
176
+ return doc;
177
+ }
178
+
179
+ function union(first: string[], second: string[]): string[] {
180
+ const out = [...first];
181
+ for (const entry of second) if (entry && !out.includes(entry)) out.push(entry);
182
+ return out;
183
+ }
184
+
185
+ /**
186
+ * Merge ONE provider (and its model rules) into the personal provider file.
187
+ *
188
+ * Fields this writer does not own survive: headers, `apiKeyManagementUrl`,
189
+ * `logo`, `templateId`, a manual model rule's capability block, `providerOrder`
190
+ * and `defaultModelSelection`. A stored credential is kept when the draft brings
191
+ * none, the same rule every other writer follows.
192
+ */
193
+ export async function writeZcodeProvider(input: {
194
+ path: string;
195
+ id: string;
196
+ draft: ProviderDraft;
197
+ dialect: string;
198
+ }): Promise<ProviderWriteResult> {
199
+ const { path, id, draft, dialect } = input;
200
+ // The runtime's own writer locks a DIRECTORY at `${path}.lock` (its
201
+ // `file-lock.ts`), so a file at that exact path would look like a lock it
202
+ // must reclaim. Kabmo serialises its own writers on a distinct lease and the
203
+ // final rename stays atomic; the app's poll picks the write up.
204
+ return withConfigLock(`${path}.kabmo`, async () => {
205
+ const file = Bun.file(path);
206
+ const raw = (await file.exists()) ? await file.text() : '';
207
+ let doc: Record<string, unknown>;
208
+ if (raw.trim()) {
209
+ try {
210
+ const parsed: unknown = JSON.parse(raw);
211
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error('not a document');
212
+ doc = parsed as Record<string, unknown>;
213
+ } catch (cause) {
214
+ throw new ProviderWriteError(`${path} could not be parsed, so it was left untouched: ${String(cause)}`);
215
+ }
216
+ } else {
217
+ doc = emptyDocument();
218
+ }
219
+ if (typeof doc.schemaVersion !== 'number') doc.schemaVersion = 1;
220
+
221
+ const { providers, smart, manual } = ruleTables(doc);
222
+ const index = providers.findIndex((rule) => ruleProviderId(asRecord(rule)) === id);
223
+ const existing = index >= 0 ? asRecord(providers[index]) : {};
224
+ const existingConfig = asRecord(existing.config);
225
+ const existingAccess = asRecord(existingConfig.access);
226
+ const existingApi = asRecord(existingConfig.api);
227
+ const baseUrl = draft.baseUrl?.trim() || (typeof existingApi.baseUrl === 'string' ? existingApi.baseUrl : '');
228
+ if (!baseUrl) {
229
+ throw new ProviderWriteError(
230
+ `ZCode needs a base URL for "${id}": a standalone personal provider has no inherited endpoint.`,
231
+ );
232
+ }
233
+ const apiKey = draft.apiKey?.trim();
234
+ const models = union(stringList(existingConfig.personalModelIds), draft.models);
235
+ const rule = {
236
+ ...existing,
237
+ providerId: id,
238
+ providerName: draft.name || (typeof existing.providerName === 'string' ? existing.providerName : id),
239
+ enabled: true,
240
+ config: {
241
+ ...existingConfig,
242
+ group: typeof existingConfig.group === 'string' ? existingConfig.group : 'standard-personal',
243
+ visibility: 'visible',
244
+ access: {
245
+ ...existingAccess,
246
+ type: apiKey ? 'api-key' : (typeof existingAccess.type === 'string' ? existingAccess.type : 'api-key'),
247
+ ...(apiKey ? { apiKey } : {}),
248
+ },
249
+ api: { ...existingApi, type: dialect, baseUrl },
250
+ personalModelIds: models,
251
+ modelOrder: union(stringList(existingConfig.modelOrder), models),
252
+ },
253
+ };
254
+ if (index >= 0) providers[index] = rule;
255
+ else providers.push(rule);
256
+
257
+ // One model rule per id: a provider rule with no model rule is invisible to
258
+ // the dropdown (see the module header). Existing rules are updated in place,
259
+ // and a MANUAL rule stays manual — moving it would drop the capability block
260
+ // the user configured by hand.
261
+ let addedRules = 0;
262
+ for (const modelId of models) {
263
+ const contextWindow = draft.contextWindow?.[modelId];
264
+ const manualIndex = manual.findIndex((entry) => {
265
+ const row = asRecord(entry);
266
+ return ruleProviderId(row) === id && row.modelId === modelId;
267
+ });
268
+ const smartIndex = smart.findIndex((entry) => {
269
+ const row = asRecord(entry);
270
+ return ruleProviderId(row) === id && row.modelId === modelId;
271
+ });
272
+ const target = manualIndex >= 0 ? manual : smartIndex >= 0 ? smart : null;
273
+ const at = manualIndex >= 0 ? manualIndex : smartIndex;
274
+ if (target) {
275
+ const row = asRecord(target[at]);
276
+ const config = asRecord(row.config);
277
+ const properties = asRecord(config.properties);
278
+ target[at] = {
279
+ ...row,
280
+ config: {
281
+ ...config,
282
+ enabled: true,
283
+ ...(contextWindow && typeof properties.contextWindow !== 'number'
284
+ ? { properties: { ...properties, contextWindow } }
285
+ : {}),
286
+ },
287
+ };
288
+ continue;
289
+ }
290
+ smart.push({
291
+ providerId: id,
292
+ modelId,
293
+ config: {
294
+ enabled: true,
295
+ ...(contextWindow ? { properties: { contextWindow } } : {}),
296
+ // A custom model has no catalog entry, so WITHOUT an explicit map the
297
+ // runtime inherits a family rule (measured: a `qwen3-…` id inherited
298
+ // `enable_thinking` + `thinking` + `reasoning_effort`, and the gateway
299
+ // answered 400 for every turn). The catalog's own generic rule maps no
300
+ // reasoning parameters; copying it keeps an unknown endpoint usable and
301
+ // never sends a field the endpoint did not advertise.
302
+ optionSpecs: { reasoningLevel: { values: ['disabled', 'enabled'], map: '{}' } },
303
+ },
304
+ });
305
+ addedRules += 1;
306
+ }
307
+
308
+ const text = JSON.stringify(doc, null, 2);
309
+ await writeFileAtomic(path, text, { createMode: 0o600 });
310
+ const notes: string[] = [
311
+ `Wrote ${models.length} model rule${models.length === 1 ? '' : 's'} into provider_config.json — ZCode lists a custom provider’s models from that table, not from the provider rule alone.`,
312
+ ];
313
+ if (draft.models.length === 0) {
314
+ notes.push('No model ids were given, so this provider serves nothing until one is added.');
315
+ }
316
+ if (addedRules > 0) {
317
+ notes.push('New model rules map NO reasoning parameters: the runtime otherwise inherits a catalog family mapping (measured: `enable_thinking`), which a custom endpoint can reject with 400. An existing rule keeps its own mapping.');
318
+ }
319
+ if (!apiKey && typeof existingAccess.apiKey === 'string' && existingAccess.apiKey) {
320
+ notes.push('Kept the stored API key — the draft carried none.');
321
+ }
322
+ return { id, replaced: index >= 0, path, dialect, env: {}, notes };
323
+ });
324
+ }
@@ -22,9 +22,9 @@
22
22
  * `forgetCliVersion` and `forgetProbe` so the next read states what is on disk.
23
23
  */
24
24
 
25
- import { resolveOmpBin } from '@/server/lib/omp/core/cli';
25
+ import { commandAvailable } from '@/server/lib/harness/auto-probe.server';
26
+ import { loadHarnessConfig } from '@/server/lib/harness/config.server';
26
27
  import { fetchNpmLatest } from '@/server/lib/updates/npm';
27
- import { HARNESS_LAUNCH } from '@/server/lib/harness/launch';
28
28
  import type { HarnessId } from '@/shared/lib/harness/catalog';
29
29
  import { harnessUpdateFacts, latestSourceFor } from '@/shared/lib/harness/updates';
30
30
 
@@ -59,19 +59,15 @@ export async function latestVersion(pkg: string, force = false): Promise<string
59
59
  /**
60
60
  * Is this harness's launch command resolvable?
61
61
  *
62
- * The same rule the catalog uses (`commandAvailable` in `harness/root.ts`), kept
63
- * here as well because THIS module answers "what can be updated" and a harness
64
- * that is not installed answers "nothing". Offering an Update for an absent
65
- * agent was measured: an install that never happened cannot be updated, and the
66
- * button only produced a `not found` from npm.
62
+ * The same rule the catalog uses (`commandAvailable` in `auto-probe.server`), not
63
+ * a second copy of it: the USER's configured command and a bridge's required
64
+ * runtime both decide whether this harness can run. Reading the build's table
65
+ * directly said "installed" for a zcode with no runtime, and "not installed" for
66
+ * a harness whose binary is only reachable through its configured launch line —
67
+ * so the update route refused an install the spawn would have used.
67
68
  */
68
- export function harnessLaunchable(id: HarnessId): boolean {
69
- if (id === 'omp-acp') return Boolean(resolveOmpBin());
70
- const launch = HARNESS_LAUNCH[id];
71
- const [binary] = launch?.command ?? [];
72
- if (!binary) return false;
73
- if (binary === 'npx') return Boolean(Bun.which('npx') ?? Bun.which('node'));
74
- return Boolean(Bun.which(binary));
69
+ export async function harnessLaunchable(id: HarnessId): Promise<boolean> {
70
+ return commandAvailable(id, await loadHarnessConfig(id));
75
71
  }
76
72
 
77
73
  /** How long a CLI version read is reused. A binary does not change under us. */
@@ -163,7 +159,7 @@ export async function harnessVersionState(
163
159
  force = false,
164
160
  ): Promise<HarnessVersionState> {
165
161
  const facts = harnessUpdateFacts(id);
166
- const installed = id === 'omp-rpc' ? true : harnessLaunchable(id);
162
+ const installed = id === 'omp-rpc' ? true : await harnessLaunchable(id);
167
163
 
168
164
  // An ABSENT harness gets no registry read: there is no install to update, and
169
165
  // the npm number would describe a package this machine does not have.
@@ -173,11 +169,10 @@ export async function harnessVersionState(
173
169
  let cli: HarnessCliVersions | null = null;
174
170
  if (facts?.cli) {
175
171
  const version = installed ? await cliVersion(facts.cli.bin) : null;
176
- // The CLI's own package is only asked about when the harness names BOTH its
177
- // package and its updater: a newer registry number Kabmo cannot install is a
178
- // promise the row could not keep, and `claude`'s updater is what keeps a
179
- // package-manager install consistent with itself.
180
- const movable = Boolean(facts.command && facts.cli.pkg);
172
+ // The CLI's own package is read whenever the facts name one: an npm CLI
173
+ // (dsh) moves through that package too, and reporting no latest for it would
174
+ // leave a stale CLI with no way to say so.
175
+ const movable = Boolean(facts.cli.pkg);
181
176
  const cliLatest = version && movable ? await latestVersion(facts.cli.pkg as string, force) : null;
182
177
  cli = { name: facts.cli.name, bin: facts.cli.bin, version, latest: cliLatest };
183
178
  }
@@ -19,6 +19,7 @@
19
19
  */
20
20
 
21
21
  import { getDb } from '@/server/db.server';
22
+ import { startHarnessAutoProbe } from '@/server/lib/harness/auto-probe.server';
22
23
  import { compactChatOverlayRows } from '@/server/lib/db/compact-chat-overlay';
23
24
  import { packageDir } from '@/server/lib/fs/package-root';
24
25
  import { isTrayEnabledByArgv } from '@/server/lib/lifecycle/argv-flags';
@@ -65,6 +66,12 @@ export async function runAfterListenTasks(target: AfterListenTarget): Promise<vo
65
66
 
66
67
  // A full collection past the ceiling, never a schedule (`lifecycle/memory.ts`).
67
68
  installMemoryMaintenance();
69
+
70
+ // The harness probes for the agents this install keeps ON. Deliberately LAST
71
+ // and never awaited: a probe spawns an agent that may take a minute, and the
72
+ // listener is already serving tabs and chats. The pass is per PROCESS, so a
73
+ // `bun --hot` reload does not start every agent again — see the module header.
74
+ startHarnessAutoProbe();
68
75
  }
69
76
 
70
77
  /**