pi-cowboy 0.0.0 → 0.3.2

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 (137) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +281 -2
  3. package/agents/explore.toml +40 -0
  4. package/dist/agents/agent-assets.js +261 -0
  5. package/dist/agents/agent-cleanup.js +284 -0
  6. package/dist/agents/agent-discovery.js +108 -0
  7. package/dist/agents/agent-host.js +10 -0
  8. package/dist/agents/agent-manager.js +367 -0
  9. package/dist/agents/agent-reviver.js +64 -0
  10. package/dist/agents/agent-runner.js +288 -0
  11. package/dist/agents/agent-spawn-store.js +57 -0
  12. package/dist/agents/agent-template.js +46 -0
  13. package/dist/agents/agent-types.js +144 -0
  14. package/dist/agents/batch.js +92 -0
  15. package/dist/agents/cleanup-policy.js +194 -0
  16. package/dist/agents/cleanup-report.js +128 -0
  17. package/dist/agents/default-agents.js +19 -0
  18. package/dist/agents/harness/pi-bolt.js +15 -0
  19. package/dist/agents/harness/pi-compatible.js +68 -0
  20. package/dist/agents/harness/pig.js +16 -0
  21. package/dist/agents/harness/registry.js +27 -0
  22. package/dist/agents/harness.js +32 -0
  23. package/dist/agents/result-file-permissions.js +29 -0
  24. package/dist/agents/run-state.js +270 -0
  25. package/dist/agents/schemas/cleanup-batch.schema.js +19 -0
  26. package/dist/agents/schemas/cowboy-agents.schema.js +39 -0
  27. package/dist/agents/schemas/merge-batch.schema.js +25 -0
  28. package/dist/agents/schemas/steer-batch.schema.js +22 -0
  29. package/dist/agents/schemas/stop-batch.schema.js +18 -0
  30. package/dist/agents/spawn-defaults.js +70 -0
  31. package/dist/agents/subagent-session.js +601 -0
  32. package/dist/agents/tool-cleanup.js +57 -0
  33. package/dist/agents/tool-execution.js +125 -0
  34. package/dist/agents/tool-merge.js +190 -0
  35. package/dist/agents/tool-result.js +17 -0
  36. package/dist/agents/tool-steer.js +89 -0
  37. package/dist/agents/types.js +1 -0
  38. package/dist/availability.js +38 -0
  39. package/dist/config/config-io.js +261 -0
  40. package/dist/config/config-store.js +321 -0
  41. package/dist/config/config-validation.js +173 -0
  42. package/dist/config/layered-config.js +117 -0
  43. package/dist/config/types.js +23 -0
  44. package/dist/cow-support-launch.js +43 -0
  45. package/dist/events.js +146 -0
  46. package/dist/extension-toggle.js +28 -0
  47. package/dist/harness-availability-launch.js +23 -0
  48. package/dist/index.js +52 -0
  49. package/dist/infrastructure/exec-path.js +35 -0
  50. package/dist/infrastructure/git/cow-clone.js +398 -0
  51. package/dist/infrastructure/git/git-materializer.js +342 -0
  52. package/dist/infrastructure/git/git-merger.js +234 -0
  53. package/dist/infrastructure/git/git-retention.js +43 -0
  54. package/dist/infrastructure/git/git-runner.js +145 -0
  55. package/dist/infrastructure/git/git-worktree.js +143 -0
  56. package/dist/infrastructure/git/index.js +11 -0
  57. package/dist/infrastructure/git-client.js +11 -0
  58. package/dist/infrastructure/herdr/agent-stopper.js +60 -0
  59. package/dist/infrastructure/herdr/agents.js +329 -0
  60. package/dist/infrastructure/herdr/herdr-client.js +36 -0
  61. package/dist/infrastructure/herdr/herdr-transport.js +158 -0
  62. package/dist/infrastructure/herdr/index.js +15 -0
  63. package/dist/infrastructure/herdr/panes.js +174 -0
  64. package/dist/infrastructure/herdr/polling.js +44 -0
  65. package/dist/infrastructure/herdr/worktrees.js +76 -0
  66. package/dist/infrastructure/herdr-client.js +6 -0
  67. package/dist/infrastructure/herdr-host.js +163 -0
  68. package/dist/logger.js +79 -0
  69. package/dist/models/model-groups.js +72 -0
  70. package/dist/models/model-precedence.js +50 -0
  71. package/dist/models/model-request.js +108 -0
  72. package/dist/orchestrators/briefing-section.js +14 -0
  73. package/dist/orchestrators/context.js +116 -0
  74. package/dist/orchestrators/cues.js +90 -0
  75. package/dist/orchestrators/default-orchestrators.js +36 -0
  76. package/dist/orchestrators/orchestrator-discovery.js +68 -0
  77. package/dist/orchestrators/orchestrator-template.js +43 -0
  78. package/dist/orchestrators/orchestrator-types.js +78 -0
  79. package/dist/orchestrators/protocol.js +292 -0
  80. package/dist/orchestrators/types.js +7 -0
  81. package/dist/paths.js +66 -0
  82. package/dist/pi-settings.js +7 -0
  83. package/dist/predicates.js +25 -0
  84. package/dist/prompt/prompts.js +110 -0
  85. package/dist/prompt/skill-loader.js +153 -0
  86. package/dist/prompt/subagent-system-prompt.js +173 -0
  87. package/dist/registration.js +220 -0
  88. package/dist/shell.js +225 -0
  89. package/dist/spawn/cow-support.js +53 -0
  90. package/dist/spawn/herdr-launcher.js +80 -0
  91. package/dist/spawn/repo-lock.js +34 -0
  92. package/dist/spawn/sandbox.js +286 -0
  93. package/dist/spawn/spawn-coordinator.js +255 -0
  94. package/dist/spawn/spawn-id.js +39 -0
  95. package/dist/spawn/worktree-policy.js +137 -0
  96. package/dist/status-note.js +30 -0
  97. package/dist/subagent/ipc-protocol.js +68 -0
  98. package/dist/subagent/ipc.js +110 -0
  99. package/dist/subagent/pane-supervisor.js +24 -0
  100. package/dist/subagent/socket-ipc.js +240 -0
  101. package/dist/subagent/supervisor.js +315 -0
  102. package/dist/task-registry.js +258 -0
  103. package/dist/templates/template-files.js +84 -0
  104. package/dist/types.js +84 -0
  105. package/dist/ui/action-report.js +21 -0
  106. package/dist/ui/format.js +47 -0
  107. package/dist/ui/indicator.js +480 -0
  108. package/dist/ui/menu/helpers.js +227 -0
  109. package/dist/ui/menu/menu-agent-settings.js +182 -0
  110. package/dist/ui/menu/menu-agent-status.js +444 -0
  111. package/dist/ui/menu/menu-concurrency.js +226 -0
  112. package/dist/ui/menu/menu-model-settings.js +244 -0
  113. package/dist/ui/menu/menu-spawn-defaults.js +71 -0
  114. package/dist/ui/menu/menu-spawn-wizard.js +367 -0
  115. package/dist/ui/menu/menu-spawn-worktree.js +107 -0
  116. package/dist/ui/menu/menu-system-prompt.js +104 -0
  117. package/dist/ui/menu/menu-worktree-command.js +150 -0
  118. package/dist/ui/menu/menus.js +187 -0
  119. package/dist/ui/menu/model-picker.js +160 -0
  120. package/dist/ui/menu/screen-host.js +87 -0
  121. package/dist/ui/menu/submenus/confirm.js +23 -0
  122. package/dist/ui/menu/submenus/model-select.js +42 -0
  123. package/dist/ui/menu/submenus/name-field.js +43 -0
  124. package/dist/ui/menu/submenus/numeric-input.js +61 -0
  125. package/dist/ui/menu/submenus/target-select.js +129 -0
  126. package/dist/ui/menu/submenus/text-editor.js +49 -0
  127. package/dist/ui/menu/submenus/worktree-command-name.js +73 -0
  128. package/dist/ui/menu/submenus/worktree-name.js +53 -0
  129. package/dist/ui/menu/wrappers/settings-list.js +101 -0
  130. package/dist/ui/searchable-select.js +147 -0
  131. package/dist/ui/types.js +1 -0
  132. package/dist/utils.js +70 -0
  133. package/docs/assets/grazing.png +0 -0
  134. package/docs/assets/herdr-containers.png +0 -0
  135. package/docs/assets/logo-transparent.png +0 -0
  136. package/orchestrators/with-code-review.toml +20 -0
  137. package/package.json +109 -3
@@ -0,0 +1,261 @@
1
+ /**
2
+ * config-io.ts — config persistence with global + project override layers.
3
+ * Effective config merges project over global over built-in defaults; each
4
+ * file stores only its own keys and the merged config is never written back.
5
+ * The project layer may carry only model and concurrency keys; a key it may
6
+ * not carry does not apply. A malformed project file is never overwritten.
7
+ */
8
+ import * as fs from "node:fs";
9
+ import * as path from "node:path";
10
+ import { DEFAULT_HARNESS, parseHarnessId } from "../agents/harness.js";
11
+ import { defaultExtensionDir, EXTENSION_NAME } from "../paths.js";
12
+ import { isRecord } from "../predicates.js";
13
+ import { DEFAULT_WORKTREE_CHECKOUT_TYPE, DEFAULT_WORKTREE_MATERIALIZATION, parseWorktreeCheckoutType, parseWorktreeMaterialization, } from "../spawn/worktree-policy.js";
14
+ import { DEFAULT_AGENT_TYPE, DEFAULT_ORCHESTRATOR_NAME } from "../types.js";
15
+ import { errorMessage } from "../utils.js";
16
+ import { CONFIG_AGENT_NON_MODEL_KEYS } from "./types.js";
17
+ import { validateRawLayer } from "./config-validation.js";
18
+ /** File name of the config in the extension dir and a project's `.pi/<extension>` dir. */
19
+ const CONFIG_FILE_NAME = "config.json";
20
+ /**
21
+ * Resolved at call time: the extension dir can be redirected per process, so
22
+ * it must never be snapshotted at module scope.
23
+ */
24
+ function configPath() {
25
+ return path.join(defaultExtensionDir(), CONFIG_FILE_NAME);
26
+ }
27
+ /** Resolved at call time (see configPath). */
28
+ export function customPromptPath() {
29
+ return path.join(defaultExtensionDir(), "prompt.md");
30
+ }
31
+ export const VALID_SYSTEM_PROMPT_MODES = new Set([
32
+ "replace",
33
+ "inherit",
34
+ "custom",
35
+ ]);
36
+ /** Default concurrency config — used for resets. */
37
+ const DEFAULT_CONCURRENCY = {
38
+ default: 4,
39
+ };
40
+ /** Default agent settings — merged into loaded config so callers get a complete shape. */
41
+ const DEFAULT_AGENT = {
42
+ default: null,
43
+ defaultAgentType: DEFAULT_AGENT_TYPE,
44
+ defaultOrchestrator: DEFAULT_ORCHESTRATOR_NAME,
45
+ systemPromptMode: "replace",
46
+ includeContextFiles: true,
47
+ disableDefaultAgents: false,
48
+ extensionEnabled: true,
49
+ showActiveIndicator: true,
50
+ grazingEnabled: true,
51
+ worktreeMaterialization: DEFAULT_WORKTREE_MATERIALIZATION,
52
+ worktreeCheckoutType: DEFAULT_WORKTREE_CHECKOUT_TYPE,
53
+ harnessType: DEFAULT_HARNESS,
54
+ };
55
+ /** Agent keys a project file may set: the model family plus per-type overrides. */
56
+ export const MODEL_FAMILY_KEYS = new Set(["default", "defaultThinking"]);
57
+ /** True when a project file may carry this agent key (model keys only). */
58
+ export function isProjectAllowedAgentKey(key) {
59
+ return (MODEL_FAMILY_KEYS.has(key) || !CONFIG_AGENT_NON_MODEL_KEYS.includes(key));
60
+ }
61
+ /**
62
+ * Each save touches only its own layer. A malformed project file is never
63
+ * written; without a project dir the project layer is untrusted. A malformed
64
+ * global file is reported and never written either.
65
+ */
66
+ export function createConfigIO(projectDir) {
67
+ const projectPath = projectDir
68
+ ? path.join(projectDir, EXTENSION_NAME, CONFIG_FILE_NAME)
69
+ : null;
70
+ let projectStatus = projectDir ? "absent" : "untrusted";
71
+ let projectRaw = null;
72
+ let globalMalformed = false;
73
+ return {
74
+ load: () => {
75
+ const globalRead = readGlobalRaw();
76
+ const global = globalRead.raw;
77
+ globalMalformed = globalRead.malformed;
78
+ if (projectPath) {
79
+ const read = readProjectRaw(projectPath);
80
+ if (read === null) {
81
+ projectRaw = null;
82
+ projectStatus = "absent";
83
+ }
84
+ else if (read === "malformed") {
85
+ projectRaw = null;
86
+ projectStatus = "malformed";
87
+ }
88
+ else {
89
+ projectRaw = read.raw;
90
+ projectStatus = "loaded";
91
+ }
92
+ }
93
+ else {
94
+ projectRaw = null;
95
+ projectStatus = "untrusted";
96
+ }
97
+ return { global, project: projectRaw, projectStatus };
98
+ },
99
+ isGlobalWritable: () => !globalMalformed,
100
+ saveGlobal: (config) => {
101
+ if (globalMalformed) {
102
+ console.warn("[subagents] Refusing to write global config (malformed); change not saved");
103
+ return;
104
+ }
105
+ writeJsonAtomic(configPath(), config);
106
+ },
107
+ saveProject: (config) => {
108
+ if (!projectPath ||
109
+ projectStatus === "malformed" ||
110
+ projectStatus === "untrusted") {
111
+ console.warn(`[subagents] Refusing to write project config (${projectStatus}); change not saved`);
112
+ return;
113
+ }
114
+ writeJsonAtomic(projectPath, config);
115
+ },
116
+ };
117
+ }
118
+ /**
119
+ * Project keys win; absent keys inherit from global. Non-model project agent
120
+ * keys are dropped. Concurrency merges per entry. Pure — no I/O.
121
+ */
122
+ export function mergeLayers(global, project) {
123
+ const agent = { ...global.agent };
124
+ if (project?.agent) {
125
+ for (const [key, value] of Object.entries(project.agent)) {
126
+ if (isProjectAllowedAgentKey(key))
127
+ agent[key] = value;
128
+ }
129
+ }
130
+ return {
131
+ agent,
132
+ concurrency: mergeRawConcurrency(global.concurrency, project?.concurrency),
133
+ };
134
+ }
135
+ /** Highest priority last. Never emits `default: undefined`, which would override the baked default in mergeDefaults' spread. */
136
+ function mergeRawConcurrency(...layers) {
137
+ const out = {};
138
+ const providers = {};
139
+ const models = {};
140
+ for (const layer of layers) {
141
+ if (!layer)
142
+ continue;
143
+ if (layer.default !== undefined)
144
+ out.default = layer.default;
145
+ Object.assign(providers, layer.providers ?? {});
146
+ Object.assign(models, layer.models ?? {});
147
+ }
148
+ if (Object.keys(providers).length > 0)
149
+ out.providers = providers;
150
+ if (Object.keys(models).length > 0)
151
+ out.models = models;
152
+ return out;
153
+ }
154
+ /** Bake hardcoded defaults into a raw config. */
155
+ export function mergeDefaults(raw) {
156
+ // Spread form so the loaded value wins; values come from JSON, hence the casts.
157
+ const concurrency = {
158
+ ...DEFAULT_CONCURRENCY,
159
+ ...raw.concurrency,
160
+ };
161
+ const agent = {
162
+ ...DEFAULT_AGENT,
163
+ ...raw.agent,
164
+ };
165
+ agent.worktreeMaterialization =
166
+ parseWorktreeMaterialization(agent.worktreeMaterialization) ??
167
+ DEFAULT_WORKTREE_MATERIALIZATION;
168
+ agent.worktreeCheckoutType =
169
+ parseWorktreeCheckoutType(agent.worktreeCheckoutType) ??
170
+ DEFAULT_WORKTREE_CHECKOUT_TYPE;
171
+ agent.harnessType = parseHarnessId(agent.harnessType) ?? DEFAULT_HARNESS;
172
+ return {
173
+ agent,
174
+ concurrency,
175
+ };
176
+ }
177
+ /** A missing file reads as {}; an unparsable one warns, reads as {}, and is not written over. */
178
+ function readGlobalRaw() {
179
+ let text;
180
+ try {
181
+ text = fs.readFileSync(configPath(), "utf-8");
182
+ }
183
+ catch (err) {
184
+ if (err?.code === "ENOENT") {
185
+ return { raw: {}, malformed: false };
186
+ }
187
+ return warnMalformedGlobal(err);
188
+ }
189
+ let parsed;
190
+ try {
191
+ parsed = JSON.parse(text);
192
+ }
193
+ catch (err) {
194
+ return warnMalformedGlobal(err);
195
+ }
196
+ // Per-value validation: drop bad values with a warning, keep valid keys.
197
+ return { raw: validateRawLayer(parsed, configPath()), malformed: false };
198
+ }
199
+ function warnMalformedGlobal(err) {
200
+ console.warn(`[subagents] Ignoring malformed global config ${configPath()}: ${errorMessage(err)}`);
201
+ return { raw: {}, malformed: true };
202
+ }
203
+ /** Missing reads as absent; unreadable/invalid warns and reads as malformed. */
204
+ function readProjectRaw(projectPath) {
205
+ if (!fs.existsSync(projectPath))
206
+ return null;
207
+ let text;
208
+ try {
209
+ text = fs.readFileSync(projectPath, "utf-8");
210
+ }
211
+ catch (err) {
212
+ console.warn(`[subagents] Ignoring malformed project config ${projectPath}: ${errorMessage(err)}`);
213
+ return "malformed";
214
+ }
215
+ return parseProjectContents(text, projectPath);
216
+ }
217
+ /** Malformed input warns and reads as "malformed". */
218
+ function parseProjectContents(text, filePath) {
219
+ let parsed;
220
+ try {
221
+ parsed = JSON.parse(text);
222
+ }
223
+ catch (err) {
224
+ console.warn(`[subagents] Ignoring malformed project config ${filePath}: ${errorMessage(err)}`);
225
+ return "malformed";
226
+ }
227
+ if (!isRecord(parsed)) {
228
+ console.warn(`[subagents] Ignoring malformed project config ${filePath}: not a JSON object`);
229
+ return "malformed";
230
+ }
231
+ const raw = parsed;
232
+ if (raw.agent !== undefined && !isRecord(raw.agent))
233
+ return malformedSection(filePath, "agent");
234
+ if (raw.concurrency !== undefined && !isRecord(raw.concurrency)) {
235
+ return malformedSection(filePath, "concurrency");
236
+ }
237
+ if (raw.concurrency?.providers !== undefined &&
238
+ !isRecord(raw.concurrency.providers)) {
239
+ return malformedSection(filePath, "concurrency.providers");
240
+ }
241
+ if (raw.concurrency?.models !== undefined &&
242
+ !isRecord(raw.concurrency.models)) {
243
+ return malformedSection(filePath, "concurrency.models");
244
+ }
245
+ return { raw: validateRawLayer(raw, filePath) };
246
+ }
247
+ function malformedSection(projectPath, section) {
248
+ console.warn(`[subagents] Ignoring malformed project config ${projectPath}: "${section}" is not a JSON object`);
249
+ return "malformed";
250
+ }
251
+ function writeJsonAtomic(filePath, config) {
252
+ const tmpPath = filePath + ".tmp";
253
+ try {
254
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
255
+ fs.writeFileSync(tmpPath, JSON.stringify(config, null, 2), "utf-8");
256
+ fs.renameSync(tmpPath, filePath);
257
+ }
258
+ catch (err) {
259
+ console.error(`[subagents] Failed to save config: ${errorMessage(err)}`);
260
+ }
261
+ }
@@ -0,0 +1,321 @@
1
+ /**
2
+ * config-store.ts — persisted config + per-session overrides.
3
+ * Reads return defaults baked in. Each persisted mutation persists with its
4
+ * side effect, so a side effect cannot be forgotten. Effective config
5
+ * resolves session overrides → project file → global file → built-in
6
+ * defaults. Per-session lifecycle: `reload()` at session_start, `dispose()`
7
+ * at session_shutdown.
8
+ */
9
+ import { resolveModel } from "../models/model-precedence.js";
10
+ import { DEFAULT_HARNESS, parseHarnessId, } from "../agents/harness.js";
11
+ import { DEFAULT_WORKTREE_CHECKOUT_TYPE, DEFAULT_WORKTREE_MATERIALIZATION, parseWorktreeCheckoutType, parseWorktreeMaterialization, } from "../spawn/worktree-policy.js";
12
+ import { DEFAULT_AGENT_TYPE, DEFAULT_ORCHESTRATOR_NAME } from "../types.js";
13
+ import { CONFIG_AGENT_NON_MODEL_KEYS } from "./types.js";
14
+ import { LayeredConfig } from "./layered-config.js";
15
+ import { VALID_SYSTEM_PROMPT_MODES, MODEL_FAMILY_KEYS, createConfigIO, isProjectAllowedAgentKey, } from "./config-io.js";
16
+ const fileConfigIO = createConfigIO();
17
+ /** True when a raw agent layer carries a model setting (model family or per-type key). */
18
+ function agentLayerHasModelSettings(layer) {
19
+ const agent = layer?.agent;
20
+ if (!agent)
21
+ return false;
22
+ return Object.keys(agent).some((key) => isProjectAllowedAgentKey(key) && agent[key] !== undefined);
23
+ }
24
+ /** True when a raw layer carries the agent key with a defined value. */
25
+ function layerHasAgentKey(layer, key) {
26
+ return layer?.agent != null && layer.agent[key] !== undefined;
27
+ }
28
+ function sessionOverridesHasModelSettings(overrides) {
29
+ return Object.values(overrides).some((value) => value != null);
30
+ }
31
+ function concurrencyLayerHasSettings(layer) {
32
+ return (layer.default !== undefined ||
33
+ (layer.providers != null && Object.keys(layer.providers).length > 0) ||
34
+ (layer.models != null && Object.keys(layer.models).length > 0));
35
+ }
36
+ const CLEAR_ALL_KEPT_AGENT_KEYS = new Set(CONFIG_AGENT_NON_MODEL_KEYS.filter((key) => !MODEL_FAMILY_KEYS.has(key)));
37
+ function nonEmptyString(value) {
38
+ if (typeof value !== "string")
39
+ return undefined;
40
+ const trimmed = value.trim();
41
+ return trimmed === "" ? undefined : trimmed;
42
+ }
43
+ export class ConfigStore {
44
+ layers;
45
+ sessionOverrides = { default: null };
46
+ sessionConcurrencyLayer = {};
47
+ manager;
48
+ constructor(io = fileConfigIO) {
49
+ this.layers = new LayeredConfig(io);
50
+ }
51
+ /** Does not reload; session_start follows with reload(). */
52
+ setProjectDir(projectDir) {
53
+ this.layers.setProjectDir(projectDir);
54
+ }
55
+ /** A write creates an absent project file; only an untrusted or malformed one is refused. */
56
+ get isProjectWritable() {
57
+ return this.layers.isProjectWritable;
58
+ }
59
+ get agent() {
60
+ const a = this.layers.effective.agent;
61
+ return {
62
+ defaultModel: a.default ?? null,
63
+ defaultAgentType: nonEmptyString(a.defaultAgentType) ?? DEFAULT_AGENT_TYPE,
64
+ defaultOrchestrator: nonEmptyString(a.defaultOrchestrator) ?? DEFAULT_ORCHESTRATOR_NAME,
65
+ systemPromptMode: VALID_SYSTEM_PROMPT_MODES.has(a.systemPromptMode)
66
+ ? a.systemPromptMode
67
+ : "replace",
68
+ includeContextFiles: a.includeContextFiles ?? true,
69
+ defaultThinking: a.defaultThinking,
70
+ loadSkillsImplicitly: a.loadSkillsImplicitly !== false,
71
+ loadExtensionsImplicitly: a.loadExtensionsImplicitly !== false,
72
+ disableDefaultAgents: a.disableDefaultAgents === true,
73
+ extensionEnabled: a.extensionEnabled !== false,
74
+ showActiveIndicator: a.showActiveIndicator !== false,
75
+ grazingEnabled: a.grazingEnabled === true,
76
+ worktreeRoot: typeof a.worktreeRoot === "string" && a.worktreeRoot.trim() !== ""
77
+ ? a.worktreeRoot
78
+ : undefined,
79
+ worktreeMaterialization: parseWorktreeMaterialization(a.worktreeMaterialization) ??
80
+ DEFAULT_WORKTREE_MATERIALIZATION,
81
+ worktreeCheckoutType: parseWorktreeCheckoutType(a.worktreeCheckoutType) ??
82
+ DEFAULT_WORKTREE_CHECKOUT_TYPE,
83
+ harnessType: parseHarnessId(a.harnessType) ?? DEFAULT_HARNESS,
84
+ };
85
+ }
86
+ get concurrency() {
87
+ const base = this.layers.effective.concurrency;
88
+ const session = this.sessionConcurrencyLayer;
89
+ return {
90
+ default: session.default ?? base.default,
91
+ providers: { ...base.providers, ...session.providers },
92
+ models: { ...base.models, ...session.models },
93
+ };
94
+ }
95
+ get sessionDefaultModel() {
96
+ return this.sessionOverrides.default ?? null;
97
+ }
98
+ sessionModelOverride(type) {
99
+ return this.sessionOverrides[type] ?? null;
100
+ }
101
+ hasGlobalModelKey(key) {
102
+ return layerHasAgentKey(this.layers.global, key);
103
+ }
104
+ hasProjectModelKey(key) {
105
+ return layerHasAgentKey(this.layers.project, key);
106
+ }
107
+ get hasSessionModelSettings() {
108
+ return sessionOverridesHasModelSettings(this.sessionOverrides);
109
+ }
110
+ get hasGlobalModelSettings() {
111
+ return agentLayerHasModelSettings(this.layers.global);
112
+ }
113
+ get hasProjectModelSettings() {
114
+ return agentLayerHasModelSettings(this.layers.project);
115
+ }
116
+ get projectConcurrency() {
117
+ return { ...this.layers.project?.concurrency };
118
+ }
119
+ get globalConcurrency() {
120
+ return { ...this.layers.global.concurrency };
121
+ }
122
+ get sessionConcurrency() {
123
+ return { ...this.sessionConcurrencyLayer };
124
+ }
125
+ get hasSessionConcurrencySettings() {
126
+ return concurrencyLayerHasSettings(this.sessionConcurrencyLayer);
127
+ }
128
+ get hasGlobalConcurrencySettings() {
129
+ return concurrencyLayerHasSettings(this.layers.global.concurrency ?? {});
130
+ }
131
+ get hasProjectConcurrencySettings() {
132
+ return concurrencyLayerHasSettings(this.layers.project?.concurrency ?? {});
133
+ }
134
+ /** Raw agent config incl. dynamic per-type model keys. */
135
+ agentConfigSnapshot() {
136
+ return this.layers.effective.agent;
137
+ }
138
+ /**
139
+ * Precedence: session per-type → config per-type → agent template →
140
+ * session default → config default → parentModelId. Null when the whole
141
+ * chain is unset and the parent has no model to inherit.
142
+ */
143
+ modelFor(type, parentModelId, agentConfig) {
144
+ return resolveModel({
145
+ subagentType: type,
146
+ agentConfig,
147
+ config: this.layers.effective,
148
+ parentModelId,
149
+ sessionOverrides: this.sessionOverrides,
150
+ });
151
+ }
152
+ // Session methods are in-memory only. Target-aware methods default to the
153
+ // global layer; "all" clears every layer.
154
+ mutate = {
155
+ agent: {
156
+ setDefaultModel: (value, target = "global") => {
157
+ this.setAgentModelKey("default", value, target);
158
+ },
159
+ setModelOverride: (type, value, target = "global") => {
160
+ this.setAgentModelKey(type, value, target);
161
+ },
162
+ clearModelOverride: (type, target = "global") => {
163
+ this.layers.clear(target, (raw) => {
164
+ if (raw.agent)
165
+ delete raw.agent[type];
166
+ }, () => {
167
+ delete this.sessionOverrides[type];
168
+ });
169
+ },
170
+ /** Keeps non-model settings. */
171
+ clearAllModelOverrides: (target = "global") => {
172
+ this.layers.clear(target, (raw) => this.clearAgentModelKeys(raw), () => {
173
+ this.sessionOverrides = { default: null };
174
+ });
175
+ },
176
+ /** Undefined clears back to the built-in fallback. */
177
+ setDefaultAgentType: (type) => this.setAgentLayerEntry("defaultAgentType", type, "global"),
178
+ /** Undefined clears back to the built-in fallback. */
179
+ setDefaultOrchestrator: (name) => this.setAgentLayerEntry("defaultOrchestrator", name, "global"),
180
+ setSystemPromptMode: (mode) => this.setAgentLayerEntry("systemPromptMode", mode, "global"),
181
+ setIncludeContextFiles: (enabled) => this.setAgentLayerEntry("includeContextFiles", enabled, "global"),
182
+ setDefaultThinking: (level, target = "global") => {
183
+ this.setAgentLayerEntry("defaultThinking", level, target);
184
+ },
185
+ setLoadSkillsImplicitly: (value) => this.setAgentLayerEntry("loadSkillsImplicitly", value, "global"),
186
+ setLoadExtensionsImplicitly: (value) => this.setAgentLayerEntry("loadExtensionsImplicitly", value, "global"),
187
+ setDisableDefaultAgents: (value) => this.setAgentLayerEntry("disableDefaultAgents", value, "global"),
188
+ setExtensionEnabled: (value) => this.setAgentLayerEntry("extensionEnabled", value, "global"),
189
+ setShowActiveIndicator: (value) => this.setAgentLayerEntry("showActiveIndicator", value, "global"),
190
+ setGrazingEnabled: (value) => this.setAgentLayerEntry("grazingEnabled", value, "global"),
191
+ /** Undefined clears back to the default. */
192
+ setWorktreeRoot: (root) => this.setAgentLayerEntry("worktreeRoot", root, "global"),
193
+ setWorktreeMaterialization: (materialization) => this.setAgentLayerEntry("worktreeMaterialization", materialization, "global"),
194
+ setWorktreeCheckoutType: (policy) => this.setAgentLayerEntry("worktreeCheckoutType", policy, "global"),
195
+ setHarnessType: (harnessType) => this.setAgentLayerEntry("harnessType", harnessType, "global"),
196
+ },
197
+ concurrency: {
198
+ setDefault: (n, target = "global") => {
199
+ this.applyConcurrencyWrite(target, (layer) => {
200
+ layer.default = n;
201
+ });
202
+ },
203
+ setProvider: (key, n, target = "global") => {
204
+ this.applyConcurrencyWrite(target, (layer) => {
205
+ layer.providers = { ...layer.providers, [key]: n };
206
+ });
207
+ },
208
+ setModel: (key, n, target = "global") => {
209
+ this.applyConcurrencyWrite(target, (layer) => {
210
+ layer.models = { ...layer.models, [key]: n };
211
+ });
212
+ },
213
+ removeProvider: (key, target = "global") => {
214
+ this.removeConcurrencyEntry("providers", key, target);
215
+ },
216
+ removeDefault: (target = "global") => {
217
+ this.removeConcurrencyEntry("default", undefined, target);
218
+ },
219
+ removeModel: (key, target = "global") => {
220
+ this.removeConcurrencyEntry("models", key, target);
221
+ },
222
+ /** Effective values fall through. */
223
+ clearAll: (target = "global") => {
224
+ this.layers.clear(target, (raw) => {
225
+ delete raw.concurrency;
226
+ }, () => {
227
+ this.sessionConcurrencyLayer = {};
228
+ });
229
+ this.applyConcurrency();
230
+ },
231
+ },
232
+ session: {
233
+ /** Not persisted. */
234
+ setOverride: (type, model) => {
235
+ this.sessionOverrides[type] = model;
236
+ },
237
+ clearOverride: (type) => {
238
+ delete this.sessionOverrides[type];
239
+ },
240
+ clearAll: () => {
241
+ this.sessionOverrides = { default: null };
242
+ },
243
+ },
244
+ };
245
+ /** Called at session_start. */
246
+ reload() {
247
+ this.layers.reload();
248
+ this.sessionOverrides = { default: null };
249
+ this.sessionConcurrencyLayer = {};
250
+ this.applyConcurrency();
251
+ }
252
+ /** Re-syncs whatever deps are present. */
253
+ setDeps(deps) {
254
+ if (deps.manager !== undefined)
255
+ this.manager = deps.manager;
256
+ this.applyConcurrency();
257
+ }
258
+ /** The manager is disposed by the composition root. */
259
+ dispose() {
260
+ this.manager = undefined;
261
+ }
262
+ /** Undefined deletes the key. */
263
+ setAgentLayerEntry(key, value, target) {
264
+ this.layers.mutate(target, (raw) => {
265
+ raw.agent ??= {};
266
+ if (value === undefined)
267
+ delete raw.agent[key];
268
+ else
269
+ raw.agent[key] = value;
270
+ });
271
+ }
272
+ /** Session model overrides are in-memory; the raw layers hold the rest. */
273
+ setAgentModelKey(key, value, target) {
274
+ if (target === "session") {
275
+ this.sessionOverrides[key] = value;
276
+ return;
277
+ }
278
+ this.setAgentLayerEntry(key, value, target);
279
+ }
280
+ /** A session write lands in memory; a file write persists, then re-syncs. */
281
+ applyConcurrencyWrite(target, write) {
282
+ if (target === "session") {
283
+ write(this.sessionConcurrencyLayer);
284
+ }
285
+ else if (!this.layers.mutate(target, (raw) => {
286
+ raw.concurrency ??= {};
287
+ write(raw.concurrency);
288
+ })) {
289
+ // The project target was unavailable: nothing changed, so nothing to sync.
290
+ return;
291
+ }
292
+ this.applyConcurrency();
293
+ }
294
+ clearAgentModelKeys(layer) {
295
+ if (!layer.agent)
296
+ return;
297
+ for (const key of Object.keys(layer.agent)) {
298
+ if (!CLEAR_ALL_KEPT_AGENT_KEYS.has(key))
299
+ delete layer.agent[key];
300
+ }
301
+ }
302
+ removeConcurrencyEntry(section, key, target) {
303
+ const removeFrom = (layer) => {
304
+ if (!layer)
305
+ return;
306
+ if (section === "default") {
307
+ delete layer.default;
308
+ }
309
+ else if (key) {
310
+ const entries = layer[section];
311
+ if (entries)
312
+ delete entries[key];
313
+ }
314
+ };
315
+ this.layers.clear(target, (raw) => removeFrom(raw.concurrency), () => removeFrom(this.sessionConcurrencyLayer));
316
+ this.applyConcurrency();
317
+ }
318
+ applyConcurrency() {
319
+ this.manager?.setConcurrency(this.concurrency);
320
+ }
321
+ }