@nathanstephenson/flow 0.1.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 (141) hide show
  1. package/README.md +641 -0
  2. package/build/workflow-runtime.cjs +213964 -0
  3. package/dist/backend/claude/async-queue.js +44 -0
  4. package/dist/backend/claude/auto-compaction.js +10 -0
  5. package/dist/backend/claude/background-calls.js +116 -0
  6. package/dist/backend/claude/enquiries.js +162 -0
  7. package/dist/backend/claude/index.js +1138 -0
  8. package/dist/backend/claude/mcp.js +55 -0
  9. package/dist/backend/claude/permissions.js +106 -0
  10. package/dist/backend/claude/streamed-message.js +120 -0
  11. package/dist/backend/claude/subagents.js +128 -0
  12. package/dist/backend/claude/workflow-parent.js +12 -0
  13. package/dist/backend/claude/workflow-processes.js +95 -0
  14. package/dist/backend/claude/workflow-subagent.js +234 -0
  15. package/dist/backend/effort.js +30 -0
  16. package/dist/backend/fake/index.js +570 -0
  17. package/dist/backend/mcp.js +190 -0
  18. package/dist/backend/pi/auto-compaction.js +16 -0
  19. package/dist/backend/pi/background-calls.js +56 -0
  20. package/dist/backend/pi/enquiries.js +63 -0
  21. package/dist/backend/pi/index.js +597 -0
  22. package/dist/backend/pi/mcp.js +35 -0
  23. package/dist/backend/pi/subagents.js +23 -0
  24. package/dist/backend/pi/work.js +104 -0
  25. package/dist/backend/pi/workflow-parent.js +21 -0
  26. package/dist/backend/pi/workflow-subagent.js +199 -0
  27. package/dist/backend/registry.js +34 -0
  28. package/dist/backend/types.js +1 -0
  29. package/dist/backend/workflow-tools.js +25 -0
  30. package/dist/build-id +1 -0
  31. package/dist/cli/application.js +397 -0
  32. package/dist/cli/bootstrap.js +535 -0
  33. package/dist/cli/host-control.js +100 -0
  34. package/dist/cli/install-guard.js +270 -0
  35. package/dist/cli/install-process.js +52 -0
  36. package/dist/cli/main.js +12 -0
  37. package/dist/cli/update.js +128 -0
  38. package/dist/client/connection.js +183 -0
  39. package/dist/client/context-usage.js +66 -0
  40. package/dist/client/diff.js +36 -0
  41. package/dist/client/enquiry.js +105 -0
  42. package/dist/client/markdown.js +192 -0
  43. package/dist/client/model-choices.js +32 -0
  44. package/dist/client/permission.js +60 -0
  45. package/dist/client/project-name.js +19 -0
  46. package/dist/client/reduce.js +463 -0
  47. package/dist/client/relative-time.js +30 -0
  48. package/dist/client/scope-kind.js +28 -0
  49. package/dist/client/search.js +136 -0
  50. package/dist/client/session-label.js +9 -0
  51. package/dist/client/status.js +84 -0
  52. package/dist/client/tool-chains.js +52 -0
  53. package/dist/client/tool-summary.js +98 -0
  54. package/dist/daemon/auth.js +590 -0
  55. package/dist/daemon/config-store.js +183 -0
  56. package/dist/daemon/config.js +687 -0
  57. package/dist/daemon/credential-redaction.js +9 -0
  58. package/dist/daemon/git.js +312 -0
  59. package/dist/daemon/host-control-routes.js +29 -0
  60. package/dist/daemon/host.js +2343 -0
  61. package/dist/daemon/http.js +19 -0
  62. package/dist/daemon/log.js +44 -0
  63. package/dist/daemon/mcp-auth.js +164 -0
  64. package/dist/daemon/models.js +85 -0
  65. package/dist/daemon/ownership.js +104 -0
  66. package/dist/daemon/projects.js +317 -0
  67. package/dist/daemon/publish.js +289 -0
  68. package/dist/daemon/pull-request.js +198 -0
  69. package/dist/daemon/runtime.js +100 -0
  70. package/dist/daemon/secret-store.js +65 -0
  71. package/dist/daemon/server.js +827 -0
  72. package/dist/daemon/shell.js +220 -0
  73. package/dist/daemon/skills.js +104 -0
  74. package/dist/daemon/stack-metadata.js +24 -0
  75. package/dist/daemon/stack.js +743 -0
  76. package/dist/daemon/store.js +130 -0
  77. package/dist/daemon/summariser.js +476 -0
  78. package/dist/daemon/workflow-execution-routes.js +105 -0
  79. package/dist/daemon/workflow-executions.js +1018 -0
  80. package/dist/daemon/workflow-mcp.js +20 -0
  81. package/dist/daemon/workflow-routes.js +102 -0
  82. package/dist/protocol/attachments.js +59 -0
  83. package/dist/protocol/commands.js +1 -0
  84. package/dist/protocol/events.js +20 -0
  85. package/dist/protocol/fonts.js +26 -0
  86. package/dist/protocol/git.js +12 -0
  87. package/dist/protocol/mcp.js +51 -0
  88. package/dist/protocol/projects.js +21 -0
  89. package/dist/protocol/publish.js +1 -0
  90. package/dist/protocol/pull-request.js +1 -0
  91. package/dist/protocol/secrets.js +4 -0
  92. package/dist/protocol/settings.js +63 -0
  93. package/dist/protocol/shells.js +8 -0
  94. package/dist/protocol/skills.js +16 -0
  95. package/dist/protocol/stack.js +41 -0
  96. package/dist/protocol/workflow-executions.js +1 -0
  97. package/dist/protocol/workflows.js +1 -0
  98. package/dist/tui/app.js +518 -0
  99. package/dist/tui/keys.js +54 -0
  100. package/dist/tui/render.js +366 -0
  101. package/dist/web/assets.js +10 -0
  102. package/dist/web/embedded.js +12 -0
  103. package/dist/web/manifest.js +70 -0
  104. package/dist/workflows/decisions.js +65 -0
  105. package/dist/workflows/executors.js +132 -0
  106. package/dist/workflows/graph.js +276 -0
  107. package/dist/workflows/json-schema.js +49 -0
  108. package/dist/workflows/loops.js +102 -0
  109. package/dist/workflows/mcp.js +18 -0
  110. package/dist/workflows/records.js +111 -0
  111. package/dist/workflows/recovery.js +25 -0
  112. package/dist/workflows/runtime-asset.js +17 -0
  113. package/dist/workflows/runtime-libs.js +1 -0
  114. package/dist/workflows/runtime-settings.js +23 -0
  115. package/dist/workflows/runtime.js +343 -0
  116. package/dist/workflows/scheduler.js +573 -0
  117. package/dist/workflows/schema.js +161 -0
  118. package/dist/workflows/store.js +93 -0
  119. package/package.json +87 -0
  120. package/web/dist/assets/__vite-browser-external-2447137e-BvRk9kiK.js +0 -0
  121. package/web/dist/assets/ghostty-vt-DOMeXDrv.wasm +0 -0
  122. package/web/dist/assets/index-BC0gLS53.js +106 -0
  123. package/web/dist/assets/index-CCeZYKES.css +2 -0
  124. package/web/dist/assets/inter-cyrillic-ext-wght-normal-BOeWTOD4.woff2 +0 -0
  125. package/web/dist/assets/inter-cyrillic-wght-normal-DqGufNeO.woff2 +0 -0
  126. package/web/dist/assets/inter-greek-ext-wght-normal-DlzME5K_.woff2 +0 -0
  127. package/web/dist/assets/inter-greek-wght-normal-CkhJZR-_.woff2 +0 -0
  128. package/web/dist/assets/inter-latin-ext-wght-normal-DO1Apj_S.woff2 +0 -0
  129. package/web/dist/assets/inter-latin-wght-normal-Dx4kXJAl.woff2 +0 -0
  130. package/web/dist/assets/inter-vietnamese-wght-normal-CBcvBZtf.woff2 +0 -0
  131. package/web/dist/assets/rolldown-runtime-B0Z9INg1.js +1 -0
  132. package/web/dist/assets/select-6i3wxovH.js +1 -0
  133. package/web/dist/assets/settings-mcp-CcT0ADJR.js +1 -0
  134. package/web/dist/assets/settings-secrets-CK4uF7fd.js +1 -0
  135. package/web/dist/assets/settings-workflows-CrbZF-nM.js +23 -0
  136. package/web/dist/assets/switch-ftZleVB8.js +6 -0
  137. package/web/dist/assets/workflow-editors-naPqAmYO.js +65 -0
  138. package/web/dist/assets/workflows-D4T4Gy_7.css +1 -0
  139. package/web/dist/assets/workflows-hh6ioeEA.js +7 -0
  140. package/web/dist/assets/workflows-pane-Db-MHf7Z.js +1 -0
  141. package/web/dist/index.html +31 -0
@@ -0,0 +1,687 @@
1
+ import { mcpConnectionsSchema } from "../protocol/mcp.js";
2
+ import { readFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { DEFAULT_CHROME_FONT, DEFAULT_MONOSPACE_FONT, defaultFonts, } from "../protocol/fonts.js";
5
+ import { DEFAULT_WORKFLOW_RUNTIME, formatDuration, parseDuration, } from "../protocol/settings.js";
6
+ export { DEFAULT_CHROME_FONT, DEFAULT_MONOSPACE_FONT };
7
+ export { formatDuration, parseDuration };
8
+ export const DEFAULT_SETTLED_RETENTION = 24 * 60 * 60 * 1000;
9
+ export function defaultConfig() {
10
+ return { retention: { settled: DEFAULT_SETTLED_RETENTION }, fonts: defaultFonts(), workflowRuntime: { ...DEFAULT_WORKFLOW_RUNTIME } };
11
+ }
12
+ export function loadConfig(stateRoot) {
13
+ let raw;
14
+ try {
15
+ raw = readFileSync(join(stateRoot, "config.json"), "utf8");
16
+ }
17
+ catch {
18
+ // No config file is the normal case, not an error worth mentioning.
19
+ return { config: defaultConfig() };
20
+ }
21
+ let parsed;
22
+ try {
23
+ parsed = JSON.parse(raw);
24
+ }
25
+ catch {
26
+ return { config: defaultConfig(), warning: "config.json is not valid JSON; using defaults" };
27
+ }
28
+ const warnings = [];
29
+ const retention = parseRetention(parsed, warnings);
30
+ const fonts = parseFonts(parsed, warnings);
31
+ const projects = parseProjects(parsed, warnings);
32
+ const permissions = parsePermissions(parsed, warnings);
33
+ const providers = parseProviders(parsed, warnings);
34
+ return {
35
+ config: {
36
+ retention,
37
+ fonts,
38
+ mcp: readMcp(parsed, warnings),
39
+ workflowRuntime: readWorkflowRuntime(parsed, warnings),
40
+ ...(projects === undefined ? {} : { projects }),
41
+ ...(permissions === undefined ? {} : { permissions }),
42
+ ...(providers === undefined ? {} : { providers }),
43
+ },
44
+ ...(warnings.length > 0 ? { warning: warnings.join("; ") } : {}),
45
+ };
46
+ }
47
+ /**
48
+ * The file's manner again, and the two halves are parsed independently so a typo in one does not
49
+ * cost the other: an unreadable Summary Model still leaves the Default Models in force.
50
+ *
51
+ * An entry keyed by a Backend Adapter this build does not have is **kept, not warned about**. A
52
+ * config.json written on a machine with pi installed must survive being read on one without it —
53
+ * the same courtesy `ConfigStore.update` extends to a key no version of this daemon has parsed.
54
+ */
55
+ function patchWorkflowRuntime(current, patch) {
56
+ const next = { ...DEFAULT_WORKFLOW_RUNTIME, ...current };
57
+ if (patch === undefined)
58
+ return next;
59
+ if (!patch || typeof patch !== 'object' || Array.isArray(patch))
60
+ throw new ConfigError('workflowRuntime must be an object');
61
+ for (const [key, value] of Object.entries(patch)) {
62
+ if (key === 'externalSandbox') {
63
+ if (typeof value !== 'boolean')
64
+ throw new ConfigError('workflowRuntime.externalSandbox must be boolean');
65
+ next.externalSandbox = value;
66
+ }
67
+ else if (key === 'dockerImage' || key === 'nodePath' || key === 'dockerPath') {
68
+ if (typeof value !== 'string' || value.length > 4096 || /[\x00-\x1f]/.test(value))
69
+ throw new ConfigError('Invalid workflowRuntime field');
70
+ if (key !== 'dockerImage' && value === '') {
71
+ delete next[key];
72
+ continue;
73
+ }
74
+ if (key === 'dockerImage' ? !/^[A-Za-z0-9][A-Za-z0-9._/:@-]*$/.test(value) : !value.startsWith('/'))
75
+ throw new ConfigError('Invalid workflowRuntime field');
76
+ next[key] = value;
77
+ }
78
+ else
79
+ throw new ConfigError('Unknown workflowRuntime field');
80
+ }
81
+ return next;
82
+ }
83
+ function readWorkflowRuntime(parsed, warnings) {
84
+ const section = parsed?.workflowRuntime;
85
+ let result = { ...DEFAULT_WORKFLOW_RUNTIME };
86
+ if (section === undefined)
87
+ return result;
88
+ if (!section || typeof section !== 'object' || Array.isArray(section)) {
89
+ warnings.push('Invalid workflowRuntime; using defaults');
90
+ return result;
91
+ }
92
+ for (const [key, value] of Object.entries(section)) {
93
+ if (!['externalSandbox', 'dockerImage', 'nodePath', 'dockerPath'].includes(key))
94
+ continue;
95
+ try {
96
+ result = patchWorkflowRuntime(result, { [key]: value });
97
+ }
98
+ catch {
99
+ warnings.push('Invalid workflowRuntime field; using default');
100
+ }
101
+ }
102
+ return result;
103
+ }
104
+ function parseProviders(parsed, warnings) {
105
+ const section = parsed?.providers;
106
+ if (section === undefined || section === null)
107
+ return undefined;
108
+ if (typeof section !== "object" || Array.isArray(section)) {
109
+ warnings.push("providers must be an object; choosing no models");
110
+ return undefined;
111
+ }
112
+ let providers = {};
113
+ if (section.defaultBackend !== undefined) {
114
+ const problem = checkModelId(section.defaultBackend, "providers.defaultBackend");
115
+ if (problem)
116
+ warnings.push(`${problem}; choosing the backend automatically`);
117
+ else
118
+ providers.defaultBackend = section.defaultBackend.trim();
119
+ }
120
+ if (section.defaults !== undefined) {
121
+ if (typeof section.defaults !== "object" || section.defaults === null || Array.isArray(section.defaults)) {
122
+ warnings.push("providers.defaults must map a backend to a model id; choosing no Default Model");
123
+ }
124
+ else {
125
+ const defaults = {};
126
+ for (const [backend, modelId] of Object.entries(section.defaults)) {
127
+ const problem = checkModelId(modelId, `providers.defaults.${backend}`);
128
+ if (problem !== undefined)
129
+ warnings.push(`${problem}; choosing no Default Model for ${backend}`);
130
+ else
131
+ defaults[backend] = modelId.trim();
132
+ }
133
+ if (Object.keys(defaults).length > 0)
134
+ providers.defaults = defaults;
135
+ }
136
+ }
137
+ if (section.summary !== undefined) {
138
+ const summary = section.summary;
139
+ const problem = typeof summary !== "object" || summary === null || Array.isArray(summary)
140
+ ? "providers.summary must name a backend and a model id"
141
+ : (checkModelId(summary.backend, "providers.summary.backend") ??
142
+ checkModelId(summary.modelId, "providers.summary.modelId"));
143
+ if (problem !== undefined)
144
+ warnings.push(`${problem}; naming no Agent Sessions`);
145
+ else {
146
+ const named = summary;
147
+ // Anything that is not `false` leaves naming on, which is the file's manner applied to a
148
+ // value with a right default: a typo here should cost the *un*surprising behaviour.
149
+ if (named.automatic !== undefined && typeof named.automatic !== "boolean") {
150
+ warnings.push("providers.summary.automatic must be true or false; naming automatically");
151
+ }
152
+ providers.summary = {
153
+ backend: named.backend.trim(),
154
+ modelId: named.modelId.trim(),
155
+ automatic: named.automatic !== false,
156
+ };
157
+ }
158
+ }
159
+ for (const field of ["efforts", "summaries", "autoCompaction"]) {
160
+ const entries = section[field];
161
+ if (entries === undefined)
162
+ continue;
163
+ if (typeof entries !== "object" || entries === null || Array.isArray(entries)) {
164
+ warnings.push(`providers.${field} must be an object`);
165
+ continue;
166
+ }
167
+ for (const [backend, value] of Object.entries(entries)) {
168
+ try {
169
+ if (field === "autoCompaction" && typeof value === "object" && value !== null && !Array.isArray(value)) {
170
+ for (const [model, setting] of Object.entries(value)) {
171
+ try {
172
+ providers = patchProviders(providers, { autoCompaction: { [backend]: { [model]: setting } } }) ?? {};
173
+ }
174
+ catch (error) {
175
+ warnings.push(String(error));
176
+ }
177
+ }
178
+ }
179
+ else
180
+ providers = patchProviders(providers, { [field]: { [backend]: value } }) ?? {};
181
+ }
182
+ catch (error) {
183
+ warnings.push(String(error));
184
+ }
185
+ }
186
+ }
187
+ return Object.keys(providers).length === 0 ? undefined : providers;
188
+ }
189
+ /**
190
+ * Whether a value can serve as a model id or a Backend Adapter name, reported without saying what to
191
+ * do about it. Split from its readers for the reason `checkFontFamily` and `checkProjectRoot` are:
192
+ * the file warns and falls back, a PUT is refused outright, and the rule must not know which caller
193
+ * it is answering.
194
+ *
195
+ * **Whether any backend can actually serve the id is deliberately not checked.** Only a running
196
+ * Backend Session knows the list (`supportedModels()` is a control request on a live stream), so
197
+ * checking here would mean I/O, and `applyPatch` stays a pure merge — the same line `checkProjectRoot`
198
+ * draws around whether a directory exists. An id no adapter serves fails on the first turn instead,
199
+ * which is what the picker in the Providers section exists to prevent.
200
+ *
201
+ * Whitespace is refused rather than trimmed away mid-string: no model id or backend name contains
202
+ * any, so one that does is a paste that went wrong and saying so beats storing something unreachable.
203
+ */
204
+ export function checkModelId(value, field) {
205
+ if (typeof value !== "string" || value.trim() === "") {
206
+ return `${field} must be a model id`;
207
+ }
208
+ const id = value.trim();
209
+ if (/\s/.test(id))
210
+ return `${field}: "${id}" is not a model id`;
211
+ return undefined;
212
+ }
213
+ /**
214
+ * The file's manner once more, and here it matters more than anywhere else: a malformed
215
+ * `permissions.allow` must cost *nothing but itself*. Falling back to some other list would either
216
+ * authorise a tool nobody granted or, worse, be read as having done so.
217
+ *
218
+ * So an unusable section grants nothing, an unusable entry is dropped, and both say why.
219
+ */
220
+ function parsePermissions(parsed, warnings) {
221
+ const section = parsed?.permissions;
222
+ if (section === undefined || section === null)
223
+ return undefined;
224
+ if (section.allow === undefined)
225
+ return undefined;
226
+ if (!Array.isArray(section.allow)) {
227
+ warnings.push("permissions.allow must be a list of tool names; authorising none");
228
+ return undefined;
229
+ }
230
+ const usable = section.allow.filter((entry) => typeof entry === "string" && entry.trim() !== "");
231
+ if (usable.length !== section.allow.length) {
232
+ warnings.push("permissions.allow: ignoring an entry that is not a tool name");
233
+ }
234
+ return usable.length === 0 ? undefined : { allow: usable.map((entry) => entry.trim()) };
235
+ }
236
+ /**
237
+ * The file's manner again: an unusable value costs only itself, and says so.
238
+ *
239
+ * The root and the list are parsed independently, so a typo in one does not cost the other — a bad
240
+ * root still leaves absolute entries in `include` usable, and a malformed `include` still leaves
241
+ * the root available for the Settings page to offer candidates from.
242
+ */
243
+ function parseProjects(parsed, warnings) {
244
+ const section = parsed?.projects;
245
+ if (section === undefined || section === null)
246
+ return undefined;
247
+ const projects = {};
248
+ if (section.root !== undefined) {
249
+ const problem = checkProjectRoot(section.root);
250
+ if (problem !== undefined)
251
+ warnings.push(`${problem}; offering no Project Root`);
252
+ else
253
+ projects.root = section.root.trim();
254
+ }
255
+ if (section.include !== undefined) {
256
+ if (!Array.isArray(section.include)) {
257
+ warnings.push("projects.include must be a list of paths; offering no Projects");
258
+ }
259
+ else {
260
+ const usable = section.include.filter((entry) => typeof entry === "string");
261
+ if (usable.length !== section.include.length) {
262
+ warnings.push("projects.include: ignoring an entry that is not a path");
263
+ }
264
+ projects.include = usable;
265
+ }
266
+ }
267
+ return projects.root === undefined && projects.include === undefined ? undefined : projects;
268
+ }
269
+ /**
270
+ * Whether a value can serve as a Project Root, reported without saying what to do about it.
271
+ *
272
+ * Split for the same reason `checkFontFamily` is: the file warns and falls back, a PUT is refused
273
+ * outright, and the rule itself must not know which caller it is answering.
274
+ *
275
+ * **Existence is deliberately not checked.** A root that is not there yields no Projects, and the
276
+ * Settings page saying "no Projects found beneath <path>" tells its reader more than a refusal
277
+ * would — while keeping `applyPatch` free of filesystem I/O, so a patch stays a pure merge.
278
+ */
279
+ export function checkProjectRoot(value) {
280
+ if (typeof value !== "string" || value.trim() === "") {
281
+ return "projects.root must be a path";
282
+ }
283
+ const path = value.trim();
284
+ if (!path.startsWith("/") && !path.startsWith("~")) {
285
+ // A relative root would resolve against the daemon's working directory, which is not a thing
286
+ // its reader can see, so the same config.json would mean different directories per start.
287
+ return `projects.root: "${path}" must be absolute, or start with ~`;
288
+ }
289
+ return undefined;
290
+ }
291
+ function parseRetention(parsed, warnings) {
292
+ const settled = parsed?.retention?.settled;
293
+ if (settled === undefined)
294
+ return { settled: DEFAULT_SETTLED_RETENTION };
295
+ if (settled === "never")
296
+ return { settled: "never" };
297
+ if (typeof settled !== "string") {
298
+ warnings.push(`retention.settled must be a duration like "1d"; using defaults`);
299
+ return { settled: DEFAULT_SETTLED_RETENTION };
300
+ }
301
+ const parsedDuration = parseDuration(settled);
302
+ if (parsedDuration === undefined) {
303
+ warnings.push(`retention.settled: cannot read "${settled}" as a duration; using defaults`);
304
+ return { settled: DEFAULT_SETTLED_RETENTION };
305
+ }
306
+ return { settled: parsedDuration };
307
+ }
308
+ function parseFonts(parsed, warnings) {
309
+ const configured = parsed?.fonts;
310
+ return {
311
+ chrome: readFontFamily(configured?.chrome, "fonts.chrome", DEFAULT_CHROME_FONT, warnings),
312
+ monospace: readFontFamily(configured?.monospace, "fonts.monospace", DEFAULT_MONOSPACE_FONT, warnings),
313
+ };
314
+ }
315
+ /**
316
+ * A font-family list is only ever family names, so anything outside that alphabet is refused.
317
+ *
318
+ * This value is set as a CSS custom property in a browser. The CSSOM would reject a malformed one
319
+ * rather than execute it, so the check is not the only thing standing between a config file and the
320
+ * page — but a config file that silently does nothing is worse than one that says why, and a
321
+ * validated alphabet is how the reader finds out they typed something impossible.
322
+ *
323
+ * Split from `readFontFamily` because the same rule has to answer to two callers with opposite
324
+ * manners: a file on disk warns and falls back, and a PUT from a client is refused outright. So this
325
+ * reports the problem and says nothing about what to do about it.
326
+ */
327
+ export function checkFontFamily(value, field) {
328
+ if (typeof value !== "string" || value.trim() === "") {
329
+ return `${field} must be a CSS font-family list`;
330
+ }
331
+ if (!/^[\w\s,'"-]+$/.test(value)) {
332
+ return `${field}: "${value}" is not a font-family list`;
333
+ }
334
+ return undefined;
335
+ }
336
+ /** The file's manner: an unusable value costs only its own default, and says so. */
337
+ export function readFontFamily(value, field, fallback, warnings) {
338
+ if (value === undefined)
339
+ return fallback;
340
+ const problem = checkFontFamily(value, field);
341
+ if (problem !== undefined) {
342
+ warnings.push(`${problem}; using the default`);
343
+ return fallback;
344
+ }
345
+ return value.trim();
346
+ }
347
+ /** A patch that cannot be applied. The message is shown to whoever sent it, so it names the field. */
348
+ export class ConfigError extends Error {
349
+ }
350
+ /**
351
+ * Merge a patch onto the current Config, refusing anything unusable.
352
+ *
353
+ * The opposite manner to `loadConfig`, deliberately. A file is parsed leniently because a typo must
354
+ * not stop the daemon that owns your Presentation Transcripts from starting; a patch is refused
355
+ * outright because there is a person waiting on the other end who can fix it, and silently keeping
356
+ * the old value while reporting success is the one behaviour a settings page must never have.
357
+ */
358
+ function parseMcp(value) {
359
+ const result = mcpConnectionsSchema.safeParse(value);
360
+ if (!result.success)
361
+ throw new ConfigError("Invalid MCP connections");
362
+ return result.data;
363
+ }
364
+ function readMcp(value, warnings) {
365
+ try {
366
+ return parseMcp(value?.mcp ?? []);
367
+ }
368
+ catch {
369
+ warnings.push("Invalid MCP connections; using none");
370
+ return [];
371
+ }
372
+ }
373
+ export function applyPatch(current, patch) {
374
+ if (typeof patch !== "object" || patch === null || Array.isArray(patch)) {
375
+ throw new ConfigError("expected an object");
376
+ }
377
+ const body = patch;
378
+ refuseUnknownKeys(body, ["retention", "fonts", "projects", "permissions", "providers", "workflowRuntime", "mcp"], "config");
379
+ const projects = patchProjects(current.projects, body.projects);
380
+ const permissions = patchPermissions(current.permissions, body.permissions);
381
+ const providers = patchProviders(current.providers, body.providers);
382
+ return {
383
+ mcp: body.mcp === undefined ? current.mcp ?? [] : parseMcp(body.mcp),
384
+ workflowRuntime: patchWorkflowRuntime(current.workflowRuntime, body.workflowRuntime),
385
+ retention: { settled: patchRetention(current.retention.settled, body.retention) },
386
+ fonts: patchFonts(current.fonts, body.fonts),
387
+ ...(projects === undefined ? {} : { projects }),
388
+ ...(permissions === undefined ? {} : { permissions }),
389
+ ...(providers === undefined ? {} : { providers }),
390
+ };
391
+ }
392
+ /**
393
+ * The Default Models and the Summary Model.
394
+ *
395
+ * `defaults` **merges per backend**, which is the one place this file departs from "a list is
396
+ * replaced wholesale". That rule exists because a merged list makes a removal indistinguishable
397
+ * from an omission; a keyed map has somewhere to put a removal, and `""` is it — the same way
398
+ * `projects.root: ""` is how a form clears the root.
399
+ *
400
+ * `summary` is one value and is set whole or cleared with `null`. A merge would let a client change
401
+ * the Backend Adapter and leave behind a model id that adapter cannot serve, which is a state no
402
+ * client meant to ask for.
403
+ */
404
+ function patchProviders(current, patch) {
405
+ if (patch === undefined)
406
+ return current;
407
+ refuseUnknownKeys(patch, ["defaultBackend", "defaults", "summary", "efforts", "summaries", "autoCompaction"], "providers");
408
+ const next = {
409
+ ...(current?.autoCompaction === undefined ? {} : { autoCompaction: { ...current.autoCompaction } }),
410
+ ...(current?.defaultBackend === undefined ? {} : { defaultBackend: current.defaultBackend }),
411
+ ...(current?.efforts === undefined ? {} : { efforts: { ...current.efforts } }),
412
+ ...(current?.summaries === undefined ? {} : { summaries: { ...current.summaries } }),
413
+ ...(current?.defaults === undefined ? {} : { defaults: { ...current.defaults } }),
414
+ ...(current?.summary === undefined ? {} : { summary: current.summary }),
415
+ };
416
+ if (patch.defaultBackend !== undefined) {
417
+ if (patch.defaultBackend === "")
418
+ delete next.defaultBackend;
419
+ else {
420
+ const problem = checkModelId(patch.defaultBackend, "providers.defaultBackend");
421
+ if (problem)
422
+ throw new ConfigError(problem);
423
+ next.defaultBackend = patch.defaultBackend.trim();
424
+ }
425
+ }
426
+ if (patch.autoCompaction !== undefined) {
427
+ const entries = patch.autoCompaction;
428
+ if (typeof entries !== "object" || entries === null || Array.isArray(entries)) {
429
+ throw new ConfigError("providers.autoCompaction must be an object");
430
+ }
431
+ const merged = { ...next.autoCompaction };
432
+ for (const [backend, models] of Object.entries(entries)) {
433
+ const path = `providers.autoCompaction.${backend}`;
434
+ if (backend !== backend.trim() || checkModelId(backend, path) || typeof models !== "object" || models === null || Array.isArray(models)) {
435
+ throw new ConfigError(`${path} must map model ids to auto-compaction settings`);
436
+ }
437
+ const values = { ...merged[backend] };
438
+ for (const [model, value] of Object.entries(models)) {
439
+ const field = `${path}.${model}`;
440
+ if (model !== model.trim() || checkModelId(model, field))
441
+ throw new ConfigError(`${field} must name a model without surrounding whitespace`);
442
+ if (value === null) {
443
+ delete values[model];
444
+ continue;
445
+ }
446
+ if (typeof value !== "object" || Array.isArray(value))
447
+ throw new ConfigError(`${field} must be an auto-compaction setting`);
448
+ refuseUnknownKeys(value, value.mode === "disabled" ? ["mode"] : ["mode", "targetPercent"], field);
449
+ if (value.mode === "disabled")
450
+ values[model] = { mode: "disabled" };
451
+ else if (value.mode === "enabled" && Number.isInteger(value.targetPercent) && value.targetPercent >= 1 && value.targetPercent <= 99) {
452
+ values[model] = { mode: "enabled", targetPercent: value.targetPercent };
453
+ }
454
+ else
455
+ throw new ConfigError(`${field} must be disabled or enabled with an integer targetPercent from 1 to 99`);
456
+ }
457
+ if (Object.keys(values).length)
458
+ merged[backend] = values;
459
+ else
460
+ delete merged[backend];
461
+ }
462
+ if (Object.keys(merged).length)
463
+ next.autoCompaction = merged;
464
+ else
465
+ delete next.autoCompaction;
466
+ }
467
+ const defaults = patch.defaults;
468
+ if (defaults !== undefined) {
469
+ if (typeof defaults !== "object" || defaults === null || Array.isArray(defaults)) {
470
+ throw new ConfigError("providers.defaults must map a backend to a model id");
471
+ }
472
+ const merged = { ...next.defaults };
473
+ for (const [backend, modelId] of Object.entries(defaults)) {
474
+ if (modelId === "") {
475
+ delete merged[backend];
476
+ continue;
477
+ }
478
+ const problem = checkModelId(modelId, `providers.defaults.${backend}`);
479
+ if (problem !== undefined)
480
+ throw new ConfigError(problem);
481
+ merged[backend] = modelId.trim();
482
+ }
483
+ if (Object.keys(merged).length === 0)
484
+ delete next.defaults;
485
+ else
486
+ next.defaults = merged;
487
+ }
488
+ if (patch.summary !== undefined) {
489
+ if (patch.summary === null)
490
+ delete next.summary;
491
+ else {
492
+ const summary = patch.summary;
493
+ if (typeof summary !== "object" || Array.isArray(summary)) {
494
+ throw new ConfigError("providers.summary must name a backend and a model id");
495
+ }
496
+ refuseUnknownKeys(summary, ["backend", "modelId", "automatic"], "providers.summary");
497
+ const named = summary;
498
+ const problem = checkModelId(named.backend, "providers.summary.backend") ??
499
+ checkModelId(named.modelId, "providers.summary.modelId");
500
+ if (problem !== undefined)
501
+ throw new ConfigError(problem);
502
+ if (named.automatic !== undefined && typeof named.automatic !== "boolean") {
503
+ throw new ConfigError("providers.summary.automatic must be true or false");
504
+ }
505
+ next.summary = {
506
+ backend: named.backend.trim(),
507
+ modelId: named.modelId.trim(),
508
+ // Omitted means naming automatically, so a client that has not been taught about the
509
+ // switch cannot turn it off by not mentioning it.
510
+ automatic: named.automatic !== false,
511
+ };
512
+ }
513
+ }
514
+ for (const field of ["efforts", "summaries"]) {
515
+ const entries = patch[field];
516
+ if (entries === undefined)
517
+ continue;
518
+ if (typeof entries !== "object" || entries === null || Array.isArray(entries)) {
519
+ throw new ConfigError(`providers.${field} must be an object`);
520
+ }
521
+ for (const [backend, value] of Object.entries(entries)) {
522
+ if (field === "efforts") {
523
+ const efforts = { ...next.efforts };
524
+ if (value === "")
525
+ delete efforts[backend];
526
+ else {
527
+ if (typeof value !== "string" || !["off", "minimal", "low", "medium", "high", "xhigh", "max"].includes(value)) {
528
+ throw new ConfigError(`providers.efforts.${backend} must be a valid effort`);
529
+ }
530
+ efforts[backend] = value;
531
+ }
532
+ next.efforts = efforts;
533
+ }
534
+ else {
535
+ const summaries = { ...next.summaries };
536
+ // A per-backend edit supersedes the old singleton, including an explicit clear.
537
+ if (next.summary?.backend === backend)
538
+ delete next.summary;
539
+ if (value === null)
540
+ delete summaries[backend];
541
+ else {
542
+ if (typeof value !== "object" || Array.isArray(value))
543
+ throw new ConfigError(`providers.summaries.${backend} must name a model`);
544
+ refuseUnknownKeys(value, ["modelId", "automatic"], `providers.summaries.${backend}`);
545
+ const named = value;
546
+ const problem = checkModelId(named.modelId, `providers.summaries.${backend}.modelId`);
547
+ if (problem)
548
+ throw new ConfigError(problem);
549
+ if (named.automatic !== undefined && typeof named.automatic !== "boolean")
550
+ throw new ConfigError(`providers.summaries.${backend}.automatic must be true or false`);
551
+ summaries[backend] = { modelId: named.modelId.trim(), automatic: named.automatic !== false };
552
+ }
553
+ next.summaries = summaries;
554
+ }
555
+ }
556
+ if (Object.keys(next[field] ?? {}).length === 0)
557
+ delete next[field];
558
+ }
559
+ return Object.keys(next).length === 0 ? undefined : next;
560
+ }
561
+ /**
562
+ * The Standing Authorisations a client wants to end up with.
563
+ *
564
+ * **Replaced wholesale**, for the reason `projects.include` is and with more riding on it: a merged
565
+ * list would make a revocation indistinguishable from an omission, and the thing left un-revoked here
566
+ * is a tool the machine will run without asking. An empty list is therefore meaningful — it is how
567
+ * the last grant is taken back — and clears the section rather than being ignored.
568
+ */
569
+ function patchPermissions(current, patch) {
570
+ if (patch === undefined)
571
+ return current;
572
+ refuseUnknownKeys(patch, ["allow"], "permissions");
573
+ const allow = patch.allow;
574
+ if (allow === undefined)
575
+ return current;
576
+ if (!Array.isArray(allow))
577
+ throw new ConfigError("permissions.allow must be a list of tool names");
578
+ const names = [];
579
+ for (const entry of allow) {
580
+ if (typeof entry !== "string" || entry.trim() === "") {
581
+ throw new ConfigError("permissions.allow: every entry must be a tool name");
582
+ }
583
+ const trimmed = entry.trim();
584
+ // Deduplicated rather than refused, as `projects.include` is: two clients racing to grant the
585
+ // same tool is a mistake worth absorbing, not one worth failing a save over.
586
+ if (!names.includes(trimmed))
587
+ names.push(trimmed);
588
+ }
589
+ return names.length === 0 ? undefined : { allow: names };
590
+ }
591
+ function patchProjects(current, patch) {
592
+ if (patch === undefined)
593
+ return current;
594
+ refuseUnknownKeys(patch, ["root", "include"], "projects");
595
+ const next = { ...current };
596
+ const root = patch.root;
597
+ if (root !== undefined) {
598
+ // An empty string is how a form says "clear this field", and is the one way back to having no
599
+ // Project Root without hand-editing the file. It is distinct from omitting the key, which means
600
+ // "leave it alone".
601
+ if (root === "")
602
+ delete next.root;
603
+ else {
604
+ const problem = checkProjectRoot(root);
605
+ if (problem !== undefined)
606
+ throw new ConfigError(problem);
607
+ next.root = root.trim();
608
+ }
609
+ }
610
+ const include = patch.include;
611
+ if (include !== undefined) {
612
+ // Replaced wholesale rather than merged. Every other Setting is a value that can be patched in
613
+ // isolation; this is a list, and "merge a list" has no meaning that would not surprise someone
614
+ // — a removal would be indistinguishable from an omission.
615
+ if (!Array.isArray(include))
616
+ throw new ConfigError("projects.include must be a list of paths");
617
+ const entries = [];
618
+ for (const entry of include) {
619
+ if (typeof entry !== "string" || entry.trim() === "") {
620
+ throw new ConfigError("projects.include: every entry must be a path");
621
+ }
622
+ const trimmed = entry.trim();
623
+ // Deduplicated rather than refused: two clients racing to add the same Project is a mistake
624
+ // worth absorbing, not one worth failing a save over.
625
+ if (!entries.includes(trimmed))
626
+ entries.push(trimmed);
627
+ }
628
+ if (entries.length === 0)
629
+ delete next.include;
630
+ else
631
+ next.include = entries;
632
+ }
633
+ return next.root === undefined && next.include === undefined ? undefined : next;
634
+ }
635
+ function patchRetention(current, patch) {
636
+ if (patch === undefined)
637
+ return current;
638
+ refuseUnknownKeys(patch, ["settled"], "retention");
639
+ const settled = patch.settled;
640
+ if (settled === undefined)
641
+ return current;
642
+ if (settled === "never")
643
+ return "never";
644
+ if (typeof settled !== "string") {
645
+ throw new ConfigError(`retention.settled must be a duration like "1d", or "never"`);
646
+ }
647
+ const ms = parseDuration(settled);
648
+ if (ms === undefined) {
649
+ throw new ConfigError(`retention.settled: cannot read "${settled}" as a duration`);
650
+ }
651
+ // Zero parses, and would reap every Settled Agent Session on the next sweep. "never" is how you
652
+ // say "do not reap"; zero is how you say it by accident.
653
+ if (ms <= 0)
654
+ throw new ConfigError(`retention.settled must be longer than zero, or "never"`);
655
+ return ms;
656
+ }
657
+ function patchFonts(current, patch) {
658
+ if (patch === undefined)
659
+ return current;
660
+ refuseUnknownKeys(patch, ["chrome", "monospace"], "fonts");
661
+ for (const field of ["chrome", "monospace"]) {
662
+ const value = patch[field];
663
+ if (value === undefined)
664
+ continue;
665
+ const problem = checkFontFamily(value, `fonts.${field}`);
666
+ if (problem !== undefined)
667
+ throw new ConfigError(problem);
668
+ }
669
+ return {
670
+ chrome: patch.chrome?.trim() ?? current.chrome,
671
+ monospace: patch.monospace?.trim() ?? current.monospace,
672
+ };
673
+ }
674
+ /**
675
+ * A key this daemon does not know is a mistake worth reporting, not one to ignore.
676
+ *
677
+ * The read path does ignore them — see `ConfigStore.update`, which preserves whatever a person
678
+ * hand-wrote into the file. That is a different question: keeping a stranger's key is courtesy,
679
+ * whereas accepting one over the wire and doing nothing with it is a client bug that would present
680
+ * as a setting that will not stick.
681
+ */
682
+ function refuseUnknownKeys(value, known, field) {
683
+ const unknown = Object.keys(value).filter((key) => !known.includes(key));
684
+ if (unknown.length > 0) {
685
+ throw new ConfigError(`${field}: unknown ${unknown.length === 1 ? "field" : "fields"} ${unknown.join(", ")}`);
686
+ }
687
+ }