@caupulican/pi-adaptative 0.80.27 → 0.80.29

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 (39) hide show
  1. package/CHANGELOG.md +15 -1
  2. package/dist/core/agent-session.d.ts +5 -0
  3. package/dist/core/agent-session.d.ts.map +1 -1
  4. package/dist/core/agent-session.js +47 -5
  5. package/dist/core/agent-session.js.map +1 -1
  6. package/dist/core/context-gc.d.ts +62 -0
  7. package/dist/core/context-gc.d.ts.map +1 -0
  8. package/dist/core/context-gc.js +332 -0
  9. package/dist/core/context-gc.js.map +1 -0
  10. package/dist/core/extensions/builtin.d.ts +3 -1
  11. package/dist/core/extensions/builtin.d.ts.map +1 -1
  12. package/dist/core/extensions/builtin.js +41 -1
  13. package/dist/core/extensions/builtin.js.map +1 -1
  14. package/dist/core/settings-manager.d.ts +26 -0
  15. package/dist/core/settings-manager.d.ts.map +1 -1
  16. package/dist/core/settings-manager.js +31 -0
  17. package/dist/core/settings-manager.js.map +1 -1
  18. package/dist/core/tools/bash.d.ts +5 -0
  19. package/dist/core/tools/bash.d.ts.map +1 -1
  20. package/dist/core/tools/bash.js +59 -21
  21. package/dist/core/tools/bash.js.map +1 -1
  22. package/dist/core/tools/output-accumulator.d.ts +33 -12
  23. package/dist/core/tools/output-accumulator.d.ts.map +1 -1
  24. package/dist/core/tools/output-accumulator.js +250 -104
  25. package/dist/core/tools/output-accumulator.js.map +1 -1
  26. package/dist/modes/interactive/components/visual-truncate.d.ts +1 -1
  27. package/dist/modes/interactive/components/visual-truncate.d.ts.map +1 -1
  28. package/dist/modes/interactive/components/visual-truncate.js +49 -9
  29. package/dist/modes/interactive/components/visual-truncate.js.map +1 -1
  30. package/docs/settings.md +30 -0
  31. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  32. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  33. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  34. package/examples/extensions/sandbox/package-lock.json +2 -2
  35. package/examples/extensions/sandbox/package.json +1 -1
  36. package/examples/extensions/with-deps/package-lock.json +2 -2
  37. package/examples/extensions/with-deps/package.json +1 -1
  38. package/npm-shrinkwrap.json +12 -12
  39. package/package.json +4 -4
@@ -100,6 +100,38 @@ function latestCompaction(entries) {
100
100
  }
101
101
  return undefined;
102
102
  }
103
+ function activeContextMessages(entries) {
104
+ const messages = [];
105
+ const compaction = latestCompaction(entries);
106
+ if (!compaction) {
107
+ for (const entry of entries) {
108
+ const message = messageFromEntry(entry);
109
+ if (message)
110
+ messages.push(message);
111
+ }
112
+ return messages;
113
+ }
114
+ messages.push(createCompactionSummaryMessage(compaction.summary, compaction.tokensBefore, compaction.timestamp));
115
+ const compactionIndex = entries.findIndex((entry) => entry.id === compaction.id);
116
+ let foundFirstKept = false;
117
+ for (let index = 0; index < compactionIndex; index++) {
118
+ const entry = entries[index];
119
+ if (entry.id === compaction.firstKeptEntryId)
120
+ foundFirstKept = true;
121
+ if (!foundFirstKept)
122
+ continue;
123
+ const message = messageFromEntry(entry);
124
+ if (message)
125
+ messages.push(message);
126
+ }
127
+ for (let index = compactionIndex + 1; index < entries.length; index++) {
128
+ const entry = entries[index];
129
+ const message = messageFromEntry(entry);
130
+ if (message)
131
+ messages.push(message);
132
+ }
133
+ return messages;
134
+ }
103
135
  function activeContextRows(entries) {
104
136
  const rows = [];
105
137
  const compaction = latestCompaction(entries);
@@ -145,7 +177,7 @@ function groupRows(rows) {
145
177
  }
146
178
  return [...groups.entries()].sort((a, b) => b[1].tokens - a[1].tokens);
147
179
  }
148
- export function createCoreDiagnosticsToolDefinitions(getActiveTools, getAllTools) {
180
+ export function createCoreDiagnosticsToolDefinitions(getActiveTools, getAllTools, getContextGcReport) {
149
181
  return [
150
182
  {
151
183
  name: "context_audit",
@@ -172,6 +204,8 @@ export function createCoreDiagnosticsToolDefinitions(getActiveTools, getAllTools
172
204
  const query = params.query?.trim().toLowerCase();
173
205
  const branch = ctx.sessionManager.getBranch();
174
206
  const rows = activeContextRows(branch);
207
+ const activeMessages = activeContextMessages(branch);
208
+ const contextGcReport = getContextGcReport?.(activeMessages);
175
209
  const contextUsage = ctx.getContextUsage();
176
210
  const systemPrompt = ctx.getSystemPrompt?.() || "";
177
211
  const activeTools = new Set(getActiveTools());
@@ -186,6 +220,7 @@ export function createCoreDiagnosticsToolDefinitions(getActiveTools, getAllTools
186
220
  }))).length;
187
221
  const toolSchemaTokens = Math.ceil(toolSchemaChars / 4);
188
222
  const rowTokenSum = rows.reduce((sum, row) => sum + row.tokens, 0);
223
+ const effectiveRowTokenSum = Math.max(0, rowTokenSum - (contextGcReport?.savedTokens ?? 0));
189
224
  const usageText = contextUsage
190
225
  ? contextUsage.tokens === null || contextUsage.percent === null
191
226
  ? `provider usage: unknown/${contextUsage.contextWindow} tokens (usually right after compaction)`
@@ -213,6 +248,9 @@ export function createCoreDiagnosticsToolDefinitions(getActiveTools, getAllTools
213
248
  "Context audit",
214
249
  usageText,
215
250
  `active branch rows: ${rows.length}; session row estimate: ${rowTokenSum} tokens`,
251
+ contextGcReport
252
+ ? `Context GC estimate: ${contextGcReport.savedTokens} tokens saved by packing ${contextGcReport.packedCount} stale row(s); effective session row estimate: ${effectiveRowTokenSum} tokens`
253
+ : undefined,
216
254
  `system prompt estimate: ${systemTokens} tokens (${systemPrompt.length} chars)`,
217
255
  `active tool schema estimate: ${toolSchemaTokens} tokens across ${activeToolInfos.length} active tool(s)`,
218
256
  unattributed === null
@@ -237,6 +275,8 @@ export function createCoreDiagnosticsToolDefinitions(getActiveTools, getAllTools
237
275
  activeTools: activeToolInfos.map((tool) => tool.name),
238
276
  toolSchemaEstimate: { chars: toolSchemaChars, estimatedTokens: toolSchemaTokens },
239
277
  rowTokenSum,
278
+ effectiveRowTokenSum,
279
+ contextGc: contextGcReport,
240
280
  rows,
241
281
  },
242
282
  };
@@ -1 +1 @@
1
- {"version":3,"file":"builtin.js","sourceRoot":"","sources":["../../../src/core/extensions/builtin.ts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EAAE;wBACjF,WAAW;wBACX,IAAI;qBACJ;iBACD,CAAC;YAAA,CACF;SACD;KACD,CAAC;AAAA,CACF","sourcesContent":["import type { AgentMessage } from \"@caupulican/pi-agent-core\";\nimport { Type } from \"typebox\";\nimport { estimateTokens } from \"../compaction/compaction.ts\";\nimport { createBranchSummaryMessage, createCompactionSummaryMessage, createCustomMessage } from \"../messages.ts\";\nimport type { CompactionEntry, SessionEntry } from \"../session-manager.ts\";\nimport type { ToolDefinition, ToolInfo } from \"./types.ts\";\n\ntype ContextAuditParams = {\n\tmaxItems?: number;\n\tminTokens?: number;\n\tquery?: string;\n\tincludePreviews?: boolean;\n};\n\ntype AuditRow = {\n\tkind: string;\n\trole?: string;\n\tentryId?: string;\n\ttimestamp?: string;\n\ttokens: number;\n\tchars: number;\n\tlabel: string;\n\tpreview: string;\n};\n\nconst DEFAULT_MAX_ITEMS = 40;\nconst MAX_MAX_ITEMS = 200;\nconst DEFAULT_PREVIEW_CHARS = 220;\nconst MAX_PREVIEW_CHARS = 600;\n\nfunction estimateTextTokens(text: string): number {\n\treturn Math.ceil(text.length / 4);\n}\n\nfunction cap(text: string, limit = DEFAULT_PREVIEW_CHARS): string {\n\tconst compact = text.replace(/\\s+/g, \" \").trim();\n\treturn compact.length > limit ? `${compact.slice(0, Math.max(0, limit - 1))}…` : compact;\n}\n\nfunction contentText(content: unknown): string {\n\tif (typeof content === \"string\") return content;\n\tif (!Array.isArray(content)) return \"\";\n\treturn content\n\t\t.map((part) => {\n\t\t\tif (!part || typeof part !== \"object\") return \"\";\n\t\t\tconst typed = part as { type?: string; text?: string; thinking?: string; name?: string; arguments?: unknown };\n\t\t\tif (typed.type === \"text\") return typed.text || \"\";\n\t\t\tif (typed.type === \"thinking\") return `[thinking ${typed.thinking?.length ?? 0} chars]`;\n\t\t\tif (typed.type === \"toolCall\")\n\t\t\t\treturn `[toolCall ${typed.name || \"unknown\"} ${JSON.stringify(typed.arguments ?? {})}]`;\n\t\t\tif (typed.type === \"image\") return \"[image]\";\n\t\t\treturn \"\";\n\t\t})\n\t\t.filter(Boolean)\n\t\t.join(\"\\n\");\n}\n\nfunction messagePreview(message: AgentMessage): string {\n\tswitch (message.role) {\n\t\tcase \"assistant\":\n\t\tcase \"user\":\n\t\tcase \"toolResult\":\n\t\tcase \"custom\":\n\t\t\treturn contentText((message as { content?: unknown }).content);\n\t\tcase \"bashExecution\":\n\t\t\treturn `Ran ${message.command}\\n${message.output}`;\n\t\tcase \"branchSummary\":\n\t\tcase \"compactionSummary\":\n\t\t\treturn message.summary;\n\t\tdefault:\n\t\t\treturn \"\";\n\t}\n}\n\nfunction messageLabel(message: AgentMessage): string {\n\tif (message.role === \"assistant\") {\n\t\tconst toolCalls = message.content.filter((part) => part.type === \"toolCall\").length;\n\t\treturn toolCalls > 0 ? `assistant (${toolCalls} tool call${toolCalls === 1 ? \"\" : \"s\"})` : \"assistant\";\n\t}\n\tif (message.role === \"toolResult\") return `tool result: ${message.toolName}`;\n\tif (message.role === \"custom\") return `custom: ${message.customType}`;\n\tif (message.role === \"bashExecution\") return \"bash execution\";\n\tif (message.role === \"branchSummary\") return \"branch summary\";\n\tif (message.role === \"compactionSummary\") return \"compaction summary\";\n\treturn message.role;\n}\n\nfunction addRow(rows: AuditRow[], entry: SessionEntry, message: AgentMessage, kindOverride?: string) {\n\tconst preview = messagePreview(message);\n\trows.push({\n\t\tkind: kindOverride || entry.type,\n\t\trole: message.role,\n\t\tentryId: entry.id,\n\t\ttimestamp: entry.timestamp,\n\t\ttokens: estimateTokens(message),\n\t\tchars: preview.length,\n\t\tlabel: messageLabel(message),\n\t\tpreview: cap(preview),\n\t});\n}\n\nfunction messageFromEntry(entry: SessionEntry): AgentMessage | undefined {\n\tif (entry.type === \"message\") return entry.message;\n\tif (entry.type === \"custom_message\") {\n\t\treturn createCustomMessage(entry.customType, entry.content, entry.display, entry.details, entry.timestamp);\n\t}\n\tif (entry.type === \"branch_summary\" && entry.summary) {\n\t\treturn createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp);\n\t}\n\treturn undefined;\n}\n\nfunction latestCompaction(entries: SessionEntry[]): CompactionEntry | undefined {\n\tfor (let index = entries.length - 1; index >= 0; index--) {\n\t\tconst entry = entries[index];\n\t\tif (entry?.type === \"compaction\") return entry;\n\t}\n\treturn undefined;\n}\n\nfunction activeContextRows(entries: SessionEntry[]): AuditRow[] {\n\tconst rows: AuditRow[] = [];\n\tconst compaction = latestCompaction(entries);\n\tif (!compaction) {\n\t\tfor (const entry of entries) {\n\t\t\tconst message = messageFromEntry(entry);\n\t\t\tif (message) addRow(rows, entry, message);\n\t\t}\n\t\treturn rows;\n\t}\n\n\tconst compactionMessage = createCompactionSummaryMessage(\n\t\tcompaction.summary,\n\t\tcompaction.tokensBefore,\n\t\tcompaction.timestamp,\n\t);\n\taddRow(rows, compaction, compactionMessage, \"compaction\");\n\n\tconst compactionIndex = entries.findIndex((entry) => entry.id === compaction.id);\n\tlet foundFirstKept = false;\n\tfor (let index = 0; index < compactionIndex; index++) {\n\t\tconst entry = entries[index];\n\t\tif (entry.id === compaction.firstKeptEntryId) foundFirstKept = true;\n\t\tif (!foundFirstKept) continue;\n\t\tconst message = messageFromEntry(entry);\n\t\tif (message) addRow(rows, entry, message);\n\t}\n\tfor (let index = compactionIndex + 1; index < entries.length; index++) {\n\t\tconst entry = entries[index];\n\t\tconst message = messageFromEntry(entry);\n\t\tif (message) addRow(rows, entry, message);\n\t}\n\treturn rows;\n}\n\nfunction groupRows(rows: AuditRow[]): Array<[string, { count: number; tokens: number; chars: number }]> {\n\tconst groups = new Map<string, { count: number; tokens: number; chars: number }>();\n\tfor (const row of rows) {\n\t\tconst key = row.label;\n\t\tconst current = groups.get(key) ?? { count: 0, tokens: 0, chars: 0 };\n\t\tcurrent.count += 1;\n\t\tcurrent.tokens += row.tokens;\n\t\tcurrent.chars += row.chars;\n\t\tgroups.set(key, current);\n\t}\n\treturn [...groups.entries()].sort((a, b) => b[1].tokens - a[1].tokens);\n}\n\nexport function createCoreDiagnosticsToolDefinitions(\n\tgetActiveTools: () => string[],\n\tgetAllTools: () => ToolInfo[],\n): ToolDefinition[] {\n\treturn [\n\t\t{\n\t\t\tname: \"context_audit\",\n\t\t\tlabel: \"Context Audit\",\n\t\t\tdescription:\n\t\t\t\t\"Audit the current provider-visible context composition: model window usage, system prompt estimate, active tool schema estimate, active session message rows, and heaviest context contributors.\",\n\t\t\tpromptSnippet: \"Audit current loaded context composition before optimizing context usage.\",\n\t\t\tpromptGuidelines: [\n\t\t\t\t\"Use context_audit when the user asks what is consuming context, why the footer shows a high percentage, or which messages/tools/system prompt content are loaded.\",\n\t\t\t\t\"Keep output bounded; use query/minTokens/maxItems to narrow rather than dumping full context.\",\n\t\t\t\t\"Treat token counts as estimates except provider usage from ctx.getContextUsage, which is still model/provider dependent.\",\n\t\t\t],\n\t\t\tparameters: Type.Object(\n\t\t\t\t{\n\t\t\t\t\tmaxItems: Type.Optional(\n\t\t\t\t\t\tType.Number({ description: \"Maximum heaviest session-context rows to show. Default 40, max 200.\" }),\n\t\t\t\t\t),\n\t\t\t\t\tminTokens: Type.Optional(\n\t\t\t\t\t\tType.Number({\n\t\t\t\t\t\t\tdescription: \"Only show session-context rows with at least this many estimated tokens.\",\n\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t\t\tquery: Type.Optional(\n\t\t\t\t\t\tType.String({ description: \"Case-insensitive filter over row label and preview.\" }),\n\t\t\t\t\t),\n\t\t\t\t\tincludePreviews: Type.Optional(\n\t\t\t\t\t\tType.Boolean({ description: \"Include bounded row previews. Defaults true.\" }),\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t\t{ additionalProperties: false },\n\t\t\t),\n\t\t\tasync execute(_toolCallId, params: ContextAuditParams, _signal, _onUpdate, ctx) {\n\t\t\t\tconst maxItems = Math.max(1, Math.min(MAX_MAX_ITEMS, Math.floor(params.maxItems ?? DEFAULT_MAX_ITEMS)));\n\t\t\t\tconst minTokens = Math.max(0, Math.floor(params.minTokens ?? 0));\n\t\t\t\tconst includePreviews = params.includePreviews !== false;\n\t\t\t\tconst query = params.query?.trim().toLowerCase();\n\n\t\t\t\tconst branch = ctx.sessionManager.getBranch();\n\t\t\t\tconst rows = activeContextRows(branch);\n\t\t\t\tconst contextUsage = ctx.getContextUsage();\n\t\t\t\tconst systemPrompt = ctx.getSystemPrompt?.() || \"\";\n\t\t\t\tconst activeTools = new Set(getActiveTools());\n\t\t\t\tconst allTools = getAllTools();\n\t\t\t\tconst activeToolInfos = allTools.filter((tool) => activeTools.has(tool.name));\n\t\t\t\tconst systemTokens = estimateTextTokens(systemPrompt);\n\t\t\t\tconst toolSchemaChars = JSON.stringify(\n\t\t\t\t\tactiveToolInfos.map((tool) => ({\n\t\t\t\t\t\tname: tool.name,\n\t\t\t\t\t\tdescription: tool.description,\n\t\t\t\t\t\tparameters: tool.parameters,\n\t\t\t\t\t\tpromptGuidelines: tool.promptGuidelines,\n\t\t\t\t\t})),\n\t\t\t\t).length;\n\t\t\t\tconst toolSchemaTokens = Math.ceil(toolSchemaChars / 4);\n\t\t\t\tconst rowTokenSum = rows.reduce((sum, row) => sum + row.tokens, 0);\n\t\t\t\tconst usageText = contextUsage\n\t\t\t\t\t? contextUsage.tokens === null || contextUsage.percent === null\n\t\t\t\t\t\t? `provider usage: unknown/${contextUsage.contextWindow} tokens (usually right after compaction)`\n\t\t\t\t\t\t: `provider usage: ${contextUsage.tokens}/${contextUsage.contextWindow} tokens (${contextUsage.percent.toFixed(1)}%)`\n\t\t\t\t\t: \"provider usage: unavailable (no active model/context window)\";\n\t\t\t\tconst providerTokens = contextUsage?.tokens ?? null;\n\t\t\t\tconst unattributed =\n\t\t\t\t\tproviderTokens === null\n\t\t\t\t\t\t? null\n\t\t\t\t\t\t: Math.max(0, providerTokens - systemTokens - toolSchemaTokens - rowTokenSum);\n\n\t\t\t\tlet filtered = rows.filter((row) => row.tokens >= minTokens);\n\t\t\t\tif (query) {\n\t\t\t\t\tfiltered = filtered.filter((row) => `${row.label}\\n${row.preview}`.toLowerCase().includes(query));\n\t\t\t\t}\n\t\t\t\tconst heaviest = [...filtered].sort((a, b) => b.tokens - a.tokens).slice(0, maxItems);\n\t\t\t\tconst groupLines = groupRows(rows)\n\t\t\t\t\t.slice(0, 12)\n\t\t\t\t\t.map(([label, group]) => `- ${label}: ${group.tokens} est tok across ${group.count} row(s)`);\n\t\t\t\tconst rowLines = heaviest.map((row, index) => {\n\t\t\t\t\tconst base = `${index + 1}. ${row.tokens} est tok · ${row.label} · ${row.entryId ?? \"no-entry\"}`;\n\t\t\t\t\treturn includePreviews\n\t\t\t\t\t\t? `${base}\\n ${cap(row.preview, MAX_PREVIEW_CHARS) || \"(no text preview)\"}`\n\t\t\t\t\t\t: base;\n\t\t\t\t});\n\n\t\t\t\tconst lines = [\n\t\t\t\t\t\"Context audit\",\n\t\t\t\t\tusageText,\n\t\t\t\t\t`active branch rows: ${rows.length}; session row estimate: ${rowTokenSum} tokens`,\n\t\t\t\t\t`system prompt estimate: ${systemTokens} tokens (${systemPrompt.length} chars)`,\n\t\t\t\t\t`active tool schema estimate: ${toolSchemaTokens} tokens across ${activeToolInfos.length} active tool(s)`,\n\t\t\t\t\tunattributed === null\n\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t: `provider-reported remainder not mapped by chars/4 rows: ${unattributed} tokens`,\n\t\t\t\t\t\"\",\n\t\t\t\t\t\"Largest groups:\",\n\t\t\t\t\t...(groupLines.length ? groupLines : [\"- none\"]),\n\t\t\t\t\t\"\",\n\t\t\t\t\t`Heaviest rows${query ? ` matching ${JSON.stringify(params.query)}` : \"\"}:`,\n\t\t\t\t\t...(rowLines.length ? rowLines : [\"- none\"]),\n\t\t\t\t].filter((line): line is string => line !== undefined);\n\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\" as const, text: lines.join(\"\\n\") }],\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\tcontextUsage,\n\t\t\t\t\t\tsystemPrompt: {\n\t\t\t\t\t\t\tchars: systemPrompt.length,\n\t\t\t\t\t\t\testimatedTokens: systemTokens,\n\t\t\t\t\t\t\tpreview: cap(systemPrompt, MAX_PREVIEW_CHARS),\n\t\t\t\t\t\t},\n\t\t\t\t\t\tactiveTools: activeToolInfos.map((tool) => tool.name),\n\t\t\t\t\t\ttoolSchemaEstimate: { chars: toolSchemaChars, estimatedTokens: toolSchemaTokens },\n\t\t\t\t\t\trowTokenSum,\n\t\t\t\t\t\trows,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t},\n\t\t},\n\t];\n}\n"]}
1
+ {"version":3,"file":"builtin.js","sourceRoot":"","sources":["../../../src/core/extensions/builtin.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAC/B,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAE7D,OAAO,EAAE,0BAA0B,EAAE,8BAA8B,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAsBjH,MAAM,iBAAiB,GAAG,EAAE,CAAC;AAC7B,MAAM,aAAa,GAAG,GAAG,CAAC;AAC1B,MAAM,qBAAqB,GAAG,GAAG,CAAC;AAClC,MAAM,iBAAiB,GAAG,GAAG,CAAC;AAE9B,SAAS,kBAAkB,CAAC,IAAY,EAAU;IACjD,OAAO,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;AAAA,CAClC;AAED,SAAS,GAAG,CAAC,IAAY,EAAE,KAAK,GAAG,qBAAqB,EAAU;IACjE,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC;IACjD,OAAO,OAAO,CAAC,MAAM,GAAG,KAAK,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,KAAK,GAAG,CAAC,CAAC,CAAC,K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estimateTokens } from \"../compaction/compaction.ts\";\nimport type { ContextGcReport } from \"../context-gc.ts\";\nimport { createBranchSummaryMessage, createCompactionSummaryMessage, createCustomMessage } from \"../messages.ts\";\nimport type { CompactionEntry, SessionEntry } from \"../session-manager.ts\";\nimport type { ToolDefinition, ToolInfo } from \"./types.ts\";\n\ntype ContextAuditParams = {\n\tmaxItems?: number;\n\tminTokens?: number;\n\tquery?: string;\n\tincludePreviews?: boolean;\n};\n\ntype AuditRow = {\n\tkind: string;\n\trole?: string;\n\tentryId?: string;\n\ttimestamp?: string;\n\ttokens: number;\n\tchars: number;\n\tlabel: string;\n\tpreview: string;\n};\n\nconst DEFAULT_MAX_ITEMS = 40;\nconst MAX_MAX_ITEMS = 200;\nconst DEFAULT_PREVIEW_CHARS = 220;\nconst MAX_PREVIEW_CHARS = 600;\n\nfunction estimateTextTokens(text: string): number {\n\treturn Math.ceil(text.length / 4);\n}\n\nfunction cap(text: string, limit = DEFAULT_PREVIEW_CHARS): string {\n\tconst compact = text.replace(/\\s+/g, \" \").trim();\n\treturn compact.length > limit ? `${compact.slice(0, Math.max(0, limit - 1))}…` : compact;\n}\n\nfunction contentText(content: unknown): string {\n\tif (typeof content === \"string\") return content;\n\tif (!Array.isArray(content)) return \"\";\n\treturn content\n\t\t.map((part) => {\n\t\t\tif (!part || typeof part !== \"object\") return \"\";\n\t\t\tconst typed = part as { type?: string; text?: string; thinking?: string; name?: string; arguments?: unknown };\n\t\t\tif (typed.type === \"text\") return typed.text || \"\";\n\t\t\tif (typed.type === \"thinking\") return `[thinking ${typed.thinking?.length ?? 0} chars]`;\n\t\t\tif (typed.type === \"toolCall\")\n\t\t\t\treturn `[toolCall ${typed.name || \"unknown\"} ${JSON.stringify(typed.arguments ?? {})}]`;\n\t\t\tif (typed.type === \"image\") return \"[image]\";\n\t\t\treturn \"\";\n\t\t})\n\t\t.filter(Boolean)\n\t\t.join(\"\\n\");\n}\n\nfunction messagePreview(message: AgentMessage): string {\n\tswitch (message.role) {\n\t\tcase \"assistant\":\n\t\tcase \"user\":\n\t\tcase \"toolResult\":\n\t\tcase \"custom\":\n\t\t\treturn contentText((message as { content?: unknown }).content);\n\t\tcase \"bashExecution\":\n\t\t\treturn `Ran ${message.command}\\n${message.output}`;\n\t\tcase \"branchSummary\":\n\t\tcase \"compactionSummary\":\n\t\t\treturn message.summary;\n\t\tdefault:\n\t\t\treturn \"\";\n\t}\n}\n\nfunction messageLabel(message: AgentMessage): string {\n\tif (message.role === \"assistant\") {\n\t\tconst toolCalls = message.content.filter((part) => part.type === \"toolCall\").length;\n\t\treturn toolCalls > 0 ? `assistant (${toolCalls} tool call${toolCalls === 1 ? \"\" : \"s\"})` : \"assistant\";\n\t}\n\tif (message.role === \"toolResult\") return `tool result: ${message.toolName}`;\n\tif (message.role === \"custom\") return `custom: ${message.customType}`;\n\tif (message.role === \"bashExecution\") return \"bash execution\";\n\tif (message.role === \"branchSummary\") return \"branch summary\";\n\tif (message.role === \"compactionSummary\") return \"compaction summary\";\n\treturn message.role;\n}\n\nfunction addRow(rows: AuditRow[], entry: SessionEntry, message: AgentMessage, kindOverride?: string) {\n\tconst preview = messagePreview(message);\n\trows.push({\n\t\tkind: kindOverride || entry.type,\n\t\trole: message.role,\n\t\tentryId: entry.id,\n\t\ttimestamp: entry.timestamp,\n\t\ttokens: estimateTokens(message),\n\t\tchars: preview.length,\n\t\tlabel: messageLabel(message),\n\t\tpreview: cap(preview),\n\t});\n}\n\nfunction messageFromEntry(entry: SessionEntry): AgentMessage | undefined {\n\tif (entry.type === \"message\") return entry.message;\n\tif (entry.type === \"custom_message\") {\n\t\treturn createCustomMessage(entry.customType, entry.content, entry.display, entry.details, entry.timestamp);\n\t}\n\tif (entry.type === \"branch_summary\" && entry.summary) {\n\t\treturn createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp);\n\t}\n\treturn undefined;\n}\n\nfunction latestCompaction(entries: SessionEntry[]): CompactionEntry | undefined {\n\tfor (let index = entries.length - 1; index >= 0; index--) {\n\t\tconst entry = entries[index];\n\t\tif (entry?.type === \"compaction\") return entry;\n\t}\n\treturn undefined;\n}\n\nfunction activeContextMessages(entries: SessionEntry[]): AgentMessage[] {\n\tconst messages: AgentMessage[] = [];\n\tconst compaction = latestCompaction(entries);\n\tif (!compaction) {\n\t\tfor (const entry of entries) {\n\t\t\tconst message = messageFromEntry(entry);\n\t\t\tif (message) messages.push(message);\n\t\t}\n\t\treturn messages;\n\t}\n\n\tmessages.push(createCompactionSummaryMessage(compaction.summary, compaction.tokensBefore, compaction.timestamp));\n\tconst compactionIndex = entries.findIndex((entry) => entry.id === compaction.id);\n\tlet foundFirstKept = false;\n\tfor (let index = 0; index < compactionIndex; index++) {\n\t\tconst entry = entries[index];\n\t\tif (entry.id === compaction.firstKeptEntryId) foundFirstKept = true;\n\t\tif (!foundFirstKept) continue;\n\t\tconst message = messageFromEntry(entry);\n\t\tif (message) messages.push(message);\n\t}\n\tfor (let index = compactionIndex + 1; index < entries.length; index++) {\n\t\tconst entry = entries[index];\n\t\tconst message = messageFromEntry(entry);\n\t\tif (message) messages.push(message);\n\t}\n\treturn messages;\n}\n\nfunction activeContextRows(entries: SessionEntry[]): AuditRow[] {\n\tconst rows: AuditRow[] = [];\n\tconst compaction = latestCompaction(entries);\n\tif (!compaction) {\n\t\tfor (const entry of entries) {\n\t\t\tconst message = messageFromEntry(entry);\n\t\t\tif (message) addRow(rows, entry, message);\n\t\t}\n\t\treturn rows;\n\t}\n\n\tconst compactionMessage = createCompactionSummaryMessage(\n\t\tcompaction.summary,\n\t\tcompaction.tokensBefore,\n\t\tcompaction.timestamp,\n\t);\n\taddRow(rows, compaction, compactionMessage, \"compaction\");\n\n\tconst compactionIndex = entries.findIndex((entry) => entry.id === compaction.id);\n\tlet foundFirstKept = false;\n\tfor (let index = 0; index < compactionIndex; index++) {\n\t\tconst entry = entries[index];\n\t\tif (entry.id === compaction.firstKeptEntryId) foundFirstKept = true;\n\t\tif (!foundFirstKept) continue;\n\t\tconst message = messageFromEntry(entry);\n\t\tif (message) addRow(rows, entry, message);\n\t}\n\tfor (let index = compactionIndex + 1; index < entries.length; index++) {\n\t\tconst entry = entries[index];\n\t\tconst message = messageFromEntry(entry);\n\t\tif (message) addRow(rows, entry, message);\n\t}\n\treturn rows;\n}\n\nfunction groupRows(rows: AuditRow[]): Array<[string, { count: number; tokens: number; chars: number }]> {\n\tconst groups = new Map<string, { count: number; tokens: number; chars: number }>();\n\tfor (const row of rows) {\n\t\tconst key = row.label;\n\t\tconst current = groups.get(key) ?? { count: 0, tokens: 0, chars: 0 };\n\t\tcurrent.count += 1;\n\t\tcurrent.tokens += row.tokens;\n\t\tcurrent.chars += row.chars;\n\t\tgroups.set(key, current);\n\t}\n\treturn [...groups.entries()].sort((a, b) => b[1].tokens - a[1].tokens);\n}\n\nexport function createCoreDiagnosticsToolDefinitions(\n\tgetActiveTools: () => string[],\n\tgetAllTools: () => ToolInfo[],\n\tgetContextGcReport?: (messages: AgentMessage[]) => ContextGcReport,\n): ToolDefinition[] {\n\treturn [\n\t\t{\n\t\t\tname: \"context_audit\",\n\t\t\tlabel: \"Context Audit\",\n\t\t\tdescription:\n\t\t\t\t\"Audit the current provider-visible context composition: model window usage, system prompt estimate, active tool schema estimate, active session message rows, and heaviest context contributors.\",\n\t\t\tpromptSnippet: \"Audit current loaded context composition before optimizing context usage.\",\n\t\t\tpromptGuidelines: [\n\t\t\t\t\"Use context_audit when the user asks what is consuming context, why the footer shows a high percentage, or which messages/tools/system prompt content are loaded.\",\n\t\t\t\t\"Keep output bounded; use query/minTokens/maxItems to narrow rather than dumping full context.\",\n\t\t\t\t\"Treat token counts as estimates except provider usage from ctx.getContextUsage, which is still model/provider dependent.\",\n\t\t\t],\n\t\t\tparameters: Type.Object(\n\t\t\t\t{\n\t\t\t\t\tmaxItems: Type.Optional(\n\t\t\t\t\t\tType.Number({ description: \"Maximum heaviest session-context rows to show. Default 40, max 200.\" }),\n\t\t\t\t\t),\n\t\t\t\t\tminTokens: Type.Optional(\n\t\t\t\t\t\tType.Number({\n\t\t\t\t\t\t\tdescription: \"Only show session-context rows with at least this many estimated tokens.\",\n\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t\t\tquery: Type.Optional(\n\t\t\t\t\t\tType.String({ description: \"Case-insensitive filter over row label and preview.\" }),\n\t\t\t\t\t),\n\t\t\t\t\tincludePreviews: Type.Optional(\n\t\t\t\t\t\tType.Boolean({ description: \"Include bounded row previews. Defaults true.\" }),\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t\t{ additionalProperties: false },\n\t\t\t),\n\t\t\tasync execute(_toolCallId, params: ContextAuditParams, _signal, _onUpdate, ctx) {\n\t\t\t\tconst maxItems = Math.max(1, Math.min(MAX_MAX_ITEMS, Math.floor(params.maxItems ?? DEFAULT_MAX_ITEMS)));\n\t\t\t\tconst minTokens = Math.max(0, Math.floor(params.minTokens ?? 0));\n\t\t\t\tconst includePreviews = params.includePreviews !== false;\n\t\t\t\tconst query = params.query?.trim().toLowerCase();\n\n\t\t\t\tconst branch = ctx.sessionManager.getBranch();\n\t\t\t\tconst rows = activeContextRows(branch);\n\t\t\t\tconst activeMessages = activeContextMessages(branch);\n\t\t\t\tconst contextGcReport = getContextGcReport?.(activeMessages);\n\t\t\t\tconst contextUsage = ctx.getContextUsage();\n\t\t\t\tconst systemPrompt = ctx.getSystemPrompt?.() || \"\";\n\t\t\t\tconst activeTools = new Set(getActiveTools());\n\t\t\t\tconst allTools = getAllTools();\n\t\t\t\tconst activeToolInfos = allTools.filter((tool) => activeTools.has(tool.name));\n\t\t\t\tconst systemTokens = estimateTextTokens(systemPrompt);\n\t\t\t\tconst toolSchemaChars = JSON.stringify(\n\t\t\t\t\tactiveToolInfos.map((tool) => ({\n\t\t\t\t\t\tname: tool.name,\n\t\t\t\t\t\tdescription: tool.description,\n\t\t\t\t\t\tparameters: tool.parameters,\n\t\t\t\t\t\tpromptGuidelines: tool.promptGuidelines,\n\t\t\t\t\t})),\n\t\t\t\t).length;\n\t\t\t\tconst toolSchemaTokens = Math.ceil(toolSchemaChars / 4);\n\t\t\t\tconst rowTokenSum = rows.reduce((sum, row) => sum + row.tokens, 0);\n\t\t\t\tconst effectiveRowTokenSum = Math.max(0, rowTokenSum - (contextGcReport?.savedTokens ?? 0));\n\t\t\t\tconst usageText = contextUsage\n\t\t\t\t\t? contextUsage.tokens === null || contextUsage.percent === null\n\t\t\t\t\t\t? `provider usage: unknown/${contextUsage.contextWindow} tokens (usually right after compaction)`\n\t\t\t\t\t\t: `provider usage: ${contextUsage.tokens}/${contextUsage.contextWindow} tokens (${contextUsage.percent.toFixed(1)}%)`\n\t\t\t\t\t: \"provider usage: unavailable (no active model/context window)\";\n\t\t\t\tconst providerTokens = contextUsage?.tokens ?? null;\n\t\t\t\tconst unattributed =\n\t\t\t\t\tproviderTokens === null\n\t\t\t\t\t\t? null\n\t\t\t\t\t\t: Math.max(0, providerTokens - systemTokens - toolSchemaTokens - rowTokenSum);\n\n\t\t\t\tlet filtered = rows.filter((row) => row.tokens >= minTokens);\n\t\t\t\tif (query) {\n\t\t\t\t\tfiltered = filtered.filter((row) => `${row.label}\\n${row.preview}`.toLowerCase().includes(query));\n\t\t\t\t}\n\t\t\t\tconst heaviest = [...filtered].sort((a, b) => b.tokens - a.tokens).slice(0, maxItems);\n\t\t\t\tconst groupLines = groupRows(rows)\n\t\t\t\t\t.slice(0, 12)\n\t\t\t\t\t.map(([label, group]) => `- ${label}: ${group.tokens} est tok across ${group.count} row(s)`);\n\t\t\t\tconst rowLines = heaviest.map((row, index) => {\n\t\t\t\t\tconst base = `${index + 1}. ${row.tokens} est tok · ${row.label} · ${row.entryId ?? \"no-entry\"}`;\n\t\t\t\t\treturn includePreviews\n\t\t\t\t\t\t? `${base}\\n ${cap(row.preview, MAX_PREVIEW_CHARS) || \"(no text preview)\"}`\n\t\t\t\t\t\t: base;\n\t\t\t\t});\n\n\t\t\t\tconst lines = [\n\t\t\t\t\t\"Context audit\",\n\t\t\t\t\tusageText,\n\t\t\t\t\t`active branch rows: ${rows.length}; session row estimate: ${rowTokenSum} tokens`,\n\t\t\t\t\tcontextGcReport\n\t\t\t\t\t\t? `Context GC estimate: ${contextGcReport.savedTokens} tokens saved by packing ${contextGcReport.packedCount} stale row(s); effective session row estimate: ${effectiveRowTokenSum} tokens`\n\t\t\t\t\t\t: undefined,\n\t\t\t\t\t`system prompt estimate: ${systemTokens} tokens (${systemPrompt.length} chars)`,\n\t\t\t\t\t`active tool schema estimate: ${toolSchemaTokens} tokens across ${activeToolInfos.length} active tool(s)`,\n\t\t\t\t\tunattributed === null\n\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t: `provider-reported remainder not mapped by chars/4 rows: ${unattributed} tokens`,\n\t\t\t\t\t\"\",\n\t\t\t\t\t\"Largest groups:\",\n\t\t\t\t\t...(groupLines.length ? groupLines : [\"- none\"]),\n\t\t\t\t\t\"\",\n\t\t\t\t\t`Heaviest rows${query ? ` matching ${JSON.stringify(params.query)}` : \"\"}:`,\n\t\t\t\t\t...(rowLines.length ? rowLines : [\"- none\"]),\n\t\t\t\t].filter((line): line is string => line !== undefined);\n\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\" as const, text: lines.join(\"\\n\") }],\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\tcontextUsage,\n\t\t\t\t\t\tsystemPrompt: {\n\t\t\t\t\t\t\tchars: systemPrompt.length,\n\t\t\t\t\t\t\testimatedTokens: systemTokens,\n\t\t\t\t\t\t\tpreview: cap(systemPrompt, MAX_PREVIEW_CHARS),\n\t\t\t\t\t\t},\n\t\t\t\t\t\tactiveTools: activeToolInfos.map((tool) => tool.name),\n\t\t\t\t\t\ttoolSchemaEstimate: { chars: toolSchemaChars, estimatedTokens: toolSchemaTokens },\n\t\t\t\t\t\trowTokenSum,\n\t\t\t\t\t\teffectiveRowTokenSum,\n\t\t\t\t\t\tcontextGc: contextGcReport,\n\t\t\t\t\t\trows,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t},\n\t\t},\n\t];\n}\n"]}
@@ -4,6 +4,19 @@ export interface CompactionSettings {
4
4
  reserveTokens?: number;
5
5
  keepRecentTokens?: number;
6
6
  }
7
+ export interface SemanticMemoryGcSettings {
8
+ enabled?: boolean;
9
+ preserveRecentPages?: number;
10
+ minChars?: number;
11
+ markers?: string[];
12
+ }
13
+ export interface ContextGcSettings {
14
+ enabled?: boolean;
15
+ preserveRecentMessages?: number;
16
+ minToolResultChars?: number;
17
+ tools?: string[];
18
+ semanticMemory?: SemanticMemoryGcSettings;
19
+ }
7
20
  export interface BranchSummarySettings {
8
21
  reserveTokens?: number;
9
22
  skipPrompt?: boolean;
@@ -101,6 +114,7 @@ export interface Settings {
101
114
  followUpMode?: "all" | "one-at-a-time";
102
115
  theme?: string;
103
116
  compaction?: CompactionSettings;
117
+ contextGc?: ContextGcSettings;
104
118
  branchSummary?: BranchSummarySettings;
105
119
  retry?: RetrySettings;
106
120
  hideThinkingBlock?: boolean;
@@ -267,6 +281,18 @@ export declare class SettingsManager {
267
281
  reserveTokens: number;
268
282
  keepRecentTokens: number;
269
283
  };
284
+ getContextGcSettings(): {
285
+ enabled: boolean;
286
+ preserveRecentMessages: number;
287
+ minToolResultChars: number;
288
+ tools: string[];
289
+ semanticMemory: {
290
+ enabled: boolean;
291
+ preserveRecentPages: number;
292
+ minChars: number;
293
+ markers: string[];
294
+ };
295
+ };
270
296
  getBranchSummarySettings(): {
271
297
  reserveTokens: number;
272
298
  skipPrompt: boolean;
@@ -1 +1 @@
1
- {"version":3,"file":"settings-manager.d.ts","sourceRoot":"","sources":["../../src/core/settings-manager.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAWnD,MAAM,WAAW,kBAAkB;IAClC,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC1B;AAED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WAAW,IAAI,eAAe,CAE7B;IAED,WAAW,CAAC,QAAQ,EAAE,eAAe,GAAG,IAAI,CAI3C;IAED,2BAA2B,IAAI;QAAE,OAAO,EAAE,OAAO,CAAC;QAAC,UAAU,CAAC,EAAE,MAAM,CAAA;KAAE,CAKvE;IAED,2BAA2B,CAAC,QAAQ,EAAE,wBAAwB,EAAE,KAAK,GAAE,aAAwB,GAAG,IAAI,CAYrG;IAED,mBAAmB,IAAI;QAAE,IAAI,EAAE,YAAY,CAAA;KAAE,CAG5C;IAED,mBAAmB,CAAC,QAAQ,EAAE,gBAAgB,EAAE,KAAK,GAAE,aAAwB,GAAG,IAAI,CAYrF;IAED,oBAAoB,IAAI,iBAAiB,CAExC;IAED,oBAAoB,CAAC,QAAQ,EAAE,iBAAiB,EAAE,KAAK,GAAE,aAAwB,GAAG,IAAI,CAYvF;CACD","sourcesContent":["import type { Transport } from \"@caupulican/pi-ai\";\nimport { createHash } from \"crypto\";\nimport { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from \"fs\";\nimport { minimatch } from \"minimatch\";\nimport { basename, dirname, join, relative, resolve, sep } from \"path\";\nimport lockfile from \"proper-lockfile\";\nimport { CONFIG_DIR_NAME, getAgentDir } from \"../config.ts\";\nimport { normalizePath, resolvePath } from \"../utils/paths.ts\";\nimport { DEFAULT_HTTP_IDLE_TIMEOUT_MS, parseHttpIdleTimeoutMs } from \"./http-dispatcher.ts\";\nimport { mergeResourceProfileMap } from \"./resource-profile-blocks.ts\";\n\nexport interface CompactionSettings {\n\tenabled?: boolean; // default: true\n\treserveTokens?: number; // default: 16384\n\tkeepRecentTokens?: number; // default: 20000\n}\n\nexport interface BranchSummarySettings {\n\treserveTokens?: number; // default: 16384 (tokens reserved for prompt + LLM response)\n\tskipPrompt?: boolean; // default: false - when true, skips \"Summarize branch?\" prompt and defaults to no summary\n}\n\nexport interface ProviderRetrySettings {\n\ttimeoutMs?: number; // SDK/provider request timeout in milliseconds\n\tmaxRetries?: number; // SDK/provider retry attempts\n\tmaxRetryDelayMs?: number; // default: 60000 (max server-requested delay before failing)\n}\n\nexport interface RetrySettings {\n\tenabled?: boolean; // default: true\n\tmaxRetries?: number; // default: 3\n\tbaseDelayMs?: number; // default: 2000 (exponential backoff: 2s, 4s, 8s)\n\tprovider?: ProviderRetrySettings;\n}\n\nexport interface TerminalSettings {\n\tshowImages?: boolean; // default: true (only relevant if terminal supports images)\n\timageWidthCells?: number; // default: 60 (preferred inline image width in terminal cells)\n\tclearOnShrink?: boolean; // default: false (clear empty rows when content shrinks)\n\tshowTerminalProgress?: boolean; // default: false (OSC 9;4 terminal progress indicators)\n}\n\nexport interface ImageSettings {\n\tautoResize?: boolean; // default: true (resize images to 2000x2000 max for better model compatibility)\n\tblockImages?: boolean; // default: false - when true, prevents all images from being sent to LLM providers\n}\n\nexport interface ThinkingBudgetsSettings {\n\tminimal?: number;\n\tlow?: number;\n\tmedium?: number;\n\thigh?: number;\n}\n\nexport interface MarkdownSettings {\n\tcodeBlockIndent?: string; // default: \" \"\n}\n\nexport interface WarningSettings {\n\tanthropicExtraUsage?: boolean; // default: true\n}\n\nexport interface SelfModificationSettings {\n\tenabled?: boolean; // default: false\n\tsourcePath?: string; // Path to the pi-adaptative source tree when self-modification is enabled\n}\n\nexport interface AutoLearnSettings {\n\tenabled?: boolean; // default: false - autonomously trigger background history scavenging for long sessions\n\tmodel?: string; // \"active\" or omitted uses the current session model; otherwise a pi --model pattern\n\tlongSessionMessages?: number; // default: 64\n\tlongSessionContextPercent?: number; // default: 85\n\tcooldownMinutes?: number; // default: 1440 per session tenant (manual /auto-learn run bypasses)\n\tleaseMinutes?: number; // default: 90 for background learner state leases\n\tmaxConcurrentLearners?: number; // default: 2 per session tenant\n\tapplyHighConfidence?: boolean; // default: false unless the learning extension config opts in\n\treflectionReview?: boolean; // default: true when Auto Learn is enabled - post-turn review after corrective/complex turns\n\treflectionMinToolCalls?: number; // default: 8 tool calls in a turn before reflection review triggers\n\treflectionCooldownMinutes?: number; // default: 1440 per session tenant for reflection reviews\n}\n\nexport type AutonomyMode = \"off\" | \"safe\" | \"balanced\" | \"full\";\n\nexport interface AutonomySettings {\n\tmode?: AutonomyMode; // default: off; presets drive Auto Learn/reflection without many knobs\n}\n\nexport type TransportSetting = Transport;\n\n/**\n * Package source for npm/git packages.\n * - String form: load all resources from the package\n * - Object form: filter which resources to load\n */\nexport type PackageSource =\n\t| string\n\t| {\n\t\t\tsource: string;\n\t\t\textensions?: string[];\n\t\t\tskills?: string[];\n\t\t\tprompts?: string[];\n\t\t\tthemes?: string[];\n\t };\n\nexport type ResourceProfileKind = \"extensions\" | \"skills\" | \"prompts\" | \"themes\" | \"agents\" | \"tools\";\n\nexport interface ResourceProfileFilterSettings {\n\t/** Allowlist patterns. When non-empty, only matching resources stay available. */\n\tallow?: string[];\n\t/** Blocklist patterns. Applied after allow. */\n\tblock?: string[];\n}\n\nexport type ResourceProfileSettings = Partial<Record<ResourceProfileKind, ResourceProfileFilterSettings>>;\n\nexport interface DisabledResourcesSettings {\n\textensions?: string[];\n\tskills?: string[];\n\tprompts?: string[];\n\tthemes?: string[];\n\tagents?: string[];\n\ttools?: string[];\n}\n\nexport interface Settings {\n\tlastChangelogVersion?: string;\n\tdefaultProvider?: string;\n\tdefaultModel?: string;\n\tdefaultThinkingLevel?: \"off\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\";\n\ttransport?: TransportSetting; // default: \"auto\"\n\tsteeringMode?: \"all\" | \"one-at-a-time\";\n\tfollowUpMode?: \"all\" | \"one-at-a-time\";\n\ttheme?: string;\n\tcompaction?: CompactionSettings;\n\tbranchSummary?: BranchSummarySettings;\n\tretry?: RetrySettings;\n\thideThinkingBlock?: boolean;\n\tshellPath?: string; // Custom shell path (e.g., for Cygwin users on Windows)\n\tquietStartup?: boolean;\n\tshellCommandPrefix?: string; // Prefix prepended to every bash command (e.g., \"shopt -s expand_aliases\" for alias support)\n\tnpmCommand?: string[]; // Command used for npm package lookup/install operations, argv-style (e.g., [\"mise\", \"exec\", \"node@20\", \"--\", \"npm\"])\n\tcollapseChangelog?: boolean; // Show condensed changelog after update (use /changelog for full)\n\tenableInstallTelemetry?: boolean; // default: true - anonymous version/update ping after changelog-detected updates\n\tpackages?: PackageSource[]; // Array of npm/git package sources (string or object with filtering)\n\textensions?: string[]; // Array of local extension file paths/directories or include/exclude patterns\n\tskills?: string[]; // Array of local skill file paths/directories or include/exclude patterns\n\tprompts?: string[]; // Array of local prompt template paths/directories or include/exclude patterns\n\tthemes?: string[]; // Array of local theme file paths/directories or include/exclude patterns\n\tdisabledResources?: DisabledResourcesSettings; // Legacy reversible block filters for extensions/skills/prompts/themes/agents/tools\n\tresourceProfiles?: Record<string, ResourceProfileSettings>; // Named resource allow/block filters\n\tactiveResourceProfile?: string | string[]; // Active profile name(s), applied after global/project/directory settings merge\n\tactiveResourceProfiles?: string[]; // Active profile names, equivalent to activeResourceProfile array\n\tenableSkillCommands?: boolean; // default: true - register skills as /skill:name commands\n\tterminal?: TerminalSettings;\n\timages?: ImageSettings;\n\tenabledModels?: string[]; // Model patterns for cycling (same format as --models CLI flag)\n\tdoubleEscapeAction?: \"fork\" | \"tree\" | \"none\"; // Action for double-escape with empty editor (default: \"tree\")\n\ttreeFilterMode?: \"default\" | \"no-tools\" | \"user-only\" | \"labeled-only\" | \"all\"; // Default filter when opening /tree\n\tthinkingBudgets?: ThinkingBudgetsSettings; // Custom token budgets for thinking levels\n\teditorPaddingX?: number; // Horizontal padding for input editor (default: 0)\n\tautocompleteMaxVisible?: number; // Max visible items in autocomplete dropdown (default: 5)\n\tshowHardwareCursor?: boolean; // Show terminal cursor while still positioning it for IME\n\tmarkdown?: MarkdownSettings;\n\twarnings?: WarningSettings;\n\tselfModification?: SelfModificationSettings; // Local guardrails for modifying the pi-adaptative source/harness\n\tautonomy?: AutonomySettings; // Low-config autonomy preset controlling background learning/reflection defaults\n\tautoLearn?: AutoLearnSettings; // Setting-gated autonomous background learning for long sessions\n\tsessionDir?: string; // Custom session storage directory (same format as --session-dir CLI flag)\n\thttpIdleTimeoutMs?: number; // HTTP header/body idle timeout in milliseconds; 0 disables it\n\twebsocketConnectTimeoutMs?: number; // WebSocket connect/open handshake timeout in milliseconds; 0 disables it\n}\n\n/** Deep merge settings: project/overrides take precedence, nested objects merge recursively */\nfunction deepMergeSettings(base: Settings, overrides: Settings): Settings {\n\tconst result: Settings = { ...base };\n\n\tfor (const key of Object.keys(overrides) as (keyof Settings)[]) {\n\t\tconst overrideValue = overrides[key];\n\t\tconst baseValue = base[key];\n\n\t\tif (overrideValue === undefined) {\n\t\t\tcontinue;\n\t\t}\n\n\t\t// For nested objects, merge recursively\n\t\tif (\n\t\t\ttypeof overrideValue === \"object\" &&\n\t\t\toverrideValue !== null &&\n\t\t\t!Array.isArray(overrideValue) &&\n\t\t\ttypeof baseValue === \"object\" &&\n\t\t\tbaseValue !== null &&\n\t\t\t!Array.isArray(baseValue)\n\t\t) {\n\t\t\t(result as Record<string, unknown>)[key] = { ...baseValue, ...overrideValue };\n\t\t} else {\n\t\t\t// For primitives and arrays, override value wins\n\t\t\t(result as Record<string, unknown>)[key] = overrideValue;\n\t\t}\n\t}\n\n\treturn result;\n}\n\nfunction toPosixPath(p: string): string {\n\treturn p.split(sep).join(\"/\");\n}\n\nfunction findDirectoryProfileRoot(cwd: string): string {\n\tlet current = resolvePath(cwd);\n\twhile (true) {\n\t\tfor (const marker of [\".git\", \".hg\", \".svn\"]) {\n\t\t\ttry {\n\t\t\t\tstatSync(join(current, marker));\n\t\t\t\treturn current;\n\t\t\t} catch {}\n\t\t}\n\t\tconst parent = resolve(current, \"..\");\n\t\tif (parent === current) return resolvePath(cwd);\n\t\tcurrent = parent;\n\t}\n}\n\nexport interface DirectoryResourceProfileInfo {\n\troot: string;\n\thash: string;\n\tpath: string;\n}\n\nexport function getDirectoryResourceProfileInfo(\n\tcwd: string,\n\tagentDir: string = getAgentDir(),\n): DirectoryResourceProfileInfo {\n\tconst root = findDirectoryProfileRoot(cwd);\n\tconst hash = createHash(\"sha256\").update(root).digest(\"hex\").slice(0, 16);\n\treturn {\n\t\troot,\n\t\thash,\n\t\tpath: join(resolvePath(agentDir), \"resource-profiles\", hash, \"settings.json\"),\n\t};\n}\n\nexport function matchesResourceProfilePattern(resourcePath: string, patterns: string[], baseDir = \"\"): boolean {\n\tif (patterns.length === 0) return false;\n\tconst resolvedBase = baseDir ? resolvePath(baseDir) : \"\";\n\tconst rel = resolvedBase ? toPosixPath(relative(resolvedBase, resourcePath)) : toPosixPath(resourcePath);\n\tconst name = basename(resourcePath);\n\tconst filePathPosix = toPosixPath(resourcePath);\n\tconst parentDir = dirname(resourcePath);\n\tconst parentRel = resolvedBase ? toPosixPath(relative(resolvedBase, parentDir)) : toPosixPath(parentDir);\n\tconst parentName = basename(parentDir);\n\tconst parentDirPosix = toPosixPath(parentDir);\n\n\treturn patterns.some((pattern) => {\n\t\tconst normalizedPattern = toPosixPath(pattern);\n\t\treturn (\n\t\t\tminimatch(rel, normalizedPattern) ||\n\t\t\tminimatch(name, normalizedPattern) ||\n\t\t\tminimatch(filePathPosix, normalizedPattern) ||\n\t\t\tminimatch(parentRel, normalizedPattern) ||\n\t\t\tminimatch(parentName, normalizedPattern) ||\n\t\t\tminimatch(parentDirPosix, normalizedPattern)\n\t\t);\n\t});\n}\n\nfunction normalizeResourceProfileNames(value: unknown): string[] {\n\tconst values: string[] = [];\n\tconst add = (candidate: unknown) => {\n\t\tif (Array.isArray(candidate)) {\n\t\t\tfor (const item of candidate) add(item);\n\t\t\treturn;\n\t\t}\n\t\tif (typeof candidate === \"string\") {\n\t\t\tfor (const part of candidate.split(\",\")) {\n\t\t\t\tconst trimmed = part.trim();\n\t\t\t\tif (trimmed) values.push(trimmed);\n\t\t\t}\n\t\t}\n\t};\n\tadd(value);\n\treturn [...new Set(values)];\n}\n\nfunction normalizeActiveResourceProfiles(settings: Settings): string[] {\n\tconst explicitProfiles = normalizeResourceProfileNames(settings.activeResourceProfiles);\n\tconst values =\n\t\texplicitProfiles.length > 0 ? explicitProfiles : normalizeResourceProfileNames(settings.activeResourceProfile);\n\tif (values.length === 0 && settings.resourceProfiles?.default) {\n\t\tvalues.push(\"default\");\n\t}\n\treturn [...new Set(values)];\n}\n\nfunction appendFilter(target: ResourceProfileFilterSettings, source?: ResourceProfileFilterSettings): void {\n\tif (!source) return;\n\tif (Array.isArray(source.allow)) target.allow = [...(target.allow ?? []), ...source.allow];\n\tif (Array.isArray(source.block)) target.block = [...(target.block ?? []), ...source.block];\n}\n\nfunction collectLegacyDisabledFilterFromSettings(\n\tsettings: Settings,\n\tkind: ResourceProfileKind,\n): ResourceProfileFilterSettings {\n\tconst legacyDisabled = settings.disabledResources?.[kind];\n\treturn Array.isArray(legacyDisabled) ? { block: legacyDisabled } : {};\n}\n\nfunction collectNamedResourceProfileFilters(\n\tsettings: Settings,\n\tkind: ResourceProfileKind,\n\tprofileNames: string[],\n): ResourceProfileFilterSettings {\n\tconst result: ResourceProfileFilterSettings = {};\n\tfor (const profileName of profileNames) {\n\t\tappendFilter(result, settings.resourceProfiles?.[profileName]?.[kind]);\n\t}\n\treturn result;\n}\n\nfunction mergeResourceProfileFilters(...filters: ResourceProfileFilterSettings[]): ResourceProfileFilterSettings {\n\tconst result: ResourceProfileFilterSettings = {};\n\tfor (const filter of filters) appendFilter(result, filter);\n\treturn result;\n}\n\nfunction parseTimeoutSetting(value: unknown, settingName: string): number | undefined {\n\tconst timeoutMs = parseHttpIdleTimeoutMs(value);\n\tif (timeoutMs !== undefined) {\n\t\treturn timeoutMs;\n\t}\n\tif (value !== undefined) {\n\t\tthrow new Error(`Invalid ${settingName} setting: ${String(value)}`);\n\t}\n\treturn undefined;\n}\n\nexport type SettingsScope = \"global\" | \"project\";\nexport type SettingsErrorScope = SettingsScope | \"directoryProfile\";\n\nexport interface SettingsManagerCreateOptions {\n\tprojectTrusted?: boolean;\n}\n\nexport interface SettingsStorage {\n\twithLock(scope: SettingsScope, fn: (current: string | undefined) => string | undefined): void;\n}\n\nexport interface SettingsError {\n\tscope: SettingsErrorScope;\n\terror: Error;\n}\n\nexport class FileSettingsStorage implements SettingsStorage {\n\tprivate globalSettingsPath: string;\n\tprivate projectSettingsPath: string;\n\tprivate directoryProfileInfo: DirectoryResourceProfileInfo;\n\n\tconstructor(cwd: string, agentDir: string) {\n\t\tconst resolvedCwd = resolvePath(cwd);\n\t\tconst resolvedAgentDir = resolvePath(agentDir);\n\t\tthis.globalSettingsPath = join(resolvedAgentDir, \"settings.json\");\n\t\tthis.projectSettingsPath = join(resolvedCwd, CONFIG_DIR_NAME, \"settings.json\");\n\t\tthis.directoryProfileInfo = getDirectoryResourceProfileInfo(resolvedCwd, resolvedAgentDir);\n\t}\n\n\tgetDirectoryResourceProfileInfo(): DirectoryResourceProfileInfo {\n\t\treturn { ...this.directoryProfileInfo };\n\t}\n\n\treadDirectoryResourceProfile(): string | undefined {\n\t\tconst path = this.directoryProfileInfo.path;\n\t\treturn existsSync(path) ? readFileSync(path, \"utf-8\") : undefined;\n\t}\n\n\tprivate acquireLockSyncWithRetry(path: string): () => void {\n\t\tconst maxAttempts = 10;\n\t\tconst delayMs = 20;\n\t\tlet lastError: unknown;\n\n\t\tfor (let attempt = 1; attempt <= maxAttempts; attempt++) {\n\t\t\ttry {\n\t\t\t\treturn lockfile.lockSync(path, { realpath: false });\n\t\t\t} catch (error) {\n\t\t\t\tconst code =\n\t\t\t\t\ttypeof error === \"object\" && error !== null && \"code\" in error\n\t\t\t\t\t\t? String((error as { code?: unknown }).code)\n\t\t\t\t\t\t: undefined;\n\t\t\t\tif (code !== \"ELOCKED\" || attempt === maxAttempts) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tlastError = error;\n\t\t\t\tconst start = Date.now();\n\t\t\t\twhile (Date.now() - start < delayMs) {\n\t\t\t\t\t// Sleep synchronously to avoid changing callers to async.\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tthrow (lastError as Error) ?? new Error(\"Failed to acquire settings lock\");\n\t}\n\n\twithLock(scope: SettingsScope, fn: (current: string | undefined) => string | undefined): void {\n\t\tconst path = scope === \"global\" ? this.globalSettingsPath : this.projectSettingsPath;\n\t\tconst dir = dirname(path);\n\n\t\tlet release: (() => void) | undefined;\n\t\ttry {\n\t\t\t// Only create directory and lock if file exists or we need to write\n\t\t\tconst fileExists = existsSync(path);\n\t\t\tif (fileExists) {\n\t\t\t\trelease = this.acquireLockSyncWithRetry(path);\n\t\t\t}\n\t\t\tconst current = fileExists ? readFileSync(path, \"utf-8\") : undefined;\n\t\t\tconst next = fn(current);\n\t\t\tif (next !== undefined) {\n\t\t\t\t// Only create directory when we actually need to write\n\t\t\t\tif (!existsSync(dir)) {\n\t\t\t\t\tmkdirSync(dir, { recursive: true });\n\t\t\t\t}\n\t\t\t\tif (!release) {\n\t\t\t\t\trelease = this.acquireLockSyncWithRetry(path);\n\t\t\t\t}\n\t\t\t\twriteFileSync(path, next, \"utf-8\");\n\t\t\t}\n\t\t} finally {\n\t\t\tif (release) {\n\t\t\t\trelease();\n\t\t\t}\n\t\t}\n\t}\n}\n\nexport class InMemorySettingsStorage implements SettingsStorage {\n\tprivate global: string | undefined;\n\tprivate project: string | undefined;\n\n\twithLock(scope: SettingsScope, fn: (current: string | undefined) => string | undefined): void {\n\t\tconst current = scope === \"global\" ? this.global : this.project;\n\t\tconst next = fn(current);\n\t\tif (next !== undefined) {\n\t\t\tif (scope === \"global\") {\n\t\t\t\tthis.global = next;\n\t\t\t} else {\n\t\t\t\tthis.project = next;\n\t\t\t}\n\t\t}\n\t}\n}\n\nexport class SettingsManager {\n\tprivate storage: SettingsStorage;\n\tprivate globalSettings: Settings;\n\tprivate projectSettings: Settings;\n\tprivate directoryProfileSettings: Settings;\n\tprivate runtimeResourceProfiles: string[] | undefined;\n\tprivate inlineResourceProfileDefinitions: Record<string, ResourceProfileSettings> = {};\n\tprivate discoveredResourceProfileDefinitions: Record<string, ResourceProfileSettings> = {};\n\tprivate settings: Settings;\n\tprivate projectTrusted: boolean;\n\tprivate modifiedFields = new Set<keyof Settings>(); // Track global fields modified during session\n\tprivate modifiedNestedFields = new Map<keyof Settings, Set<string>>(); // Track global nested field modifications\n\tprivate modifiedProjectFields = new Set<keyof Settings>(); // Track project fields modified during session\n\tprivate modifiedProjectNestedFields = new Map<keyof Settings, Set<string>>(); // Track project nested field modifications\n\tprivate globalSettingsLoadError: Error | null = null; // Track if global settings file had parse errors\n\tprivate projectSettingsLoadError: Error | null = null; // Track if project settings file had parse errors\n\tprivate directoryProfileInfo: DirectoryResourceProfileInfo | null = null;\n\tprivate writeQueue: Promise<void> = Promise.resolve();\n\tprivate errors: SettingsError[];\n\n\tprivate constructor(\n\t\tstorage: SettingsStorage,\n\t\tinitialGlobal: Settings,\n\t\tinitialProject: Settings,\n\t\tinitialDirectoryProfile: Settings = {},\n\t\tglobalLoadError: Error | null = null,\n\t\tprojectLoadError: Error | null = null,\n\t\tinitialErrors: SettingsError[] = [],\n\t\tprojectTrusted = true,\n\t\tdirectoryProfileInfo: DirectoryResourceProfileInfo | null = null,\n\t) {\n\t\tthis.storage = storage;\n\t\tthis.globalSettings = initialGlobal;\n\t\tthis.projectSettings = initialProject;\n\t\tthis.directoryProfileSettings = initialDirectoryProfile;\n\t\tthis.projectTrusted = projectTrusted;\n\t\tthis.globalSettingsLoadError = globalLoadError;\n\t\tthis.projectSettingsLoadError = projectLoadError;\n\t\tthis.directoryProfileInfo = directoryProfileInfo;\n\t\tthis.errors = [...initialErrors];\n\t\tthis.settings = this.mergeEffectiveSettings();\n\t}\n\n\tprivate mergeEffectiveSettings(): Settings {\n\t\tlet merged = deepMergeSettings(this.globalSettings, this.projectSettings);\n\t\tmerged = deepMergeSettings(merged, this.directoryProfileSettings);\n\t\tif (this.runtimeResourceProfiles) {\n\t\t\tmerged = deepMergeSettings(merged, { activeResourceProfiles: this.runtimeResourceProfiles });\n\t\t}\n\t\treturn merged;\n\t}\n\n\tprivate recomputeSettings(): void {\n\t\tthis.settings = this.mergeEffectiveSettings();\n\t}\n\n\t/** Create a SettingsManager that loads from files */\n\tstatic create(\n\t\tcwd: string,\n\t\tagentDir: string = getAgentDir(),\n\t\toptions: SettingsManagerCreateOptions = {},\n\t): SettingsManager {\n\t\tconst storage = new FileSettingsStorage(cwd, agentDir);\n\t\treturn SettingsManager.fromStorage(storage, options);\n\t}\n\n\t/** Create a SettingsManager from an arbitrary storage backend */\n\tstatic fromStorage(storage: SettingsStorage, options: SettingsManagerCreateOptions = {}): SettingsManager {\n\t\tconst projectTrusted = options.projectTrusted ?? true;\n\t\tconst globalLoad = SettingsManager.tryLoadFromStorage(storage, \"global\");\n\t\tconst projectLoad = SettingsManager.tryLoadFromStorage(storage, \"project\", projectTrusted);\n\t\tconst directoryProfileLoad = SettingsManager.tryLoadDirectoryProfileFromStorage(storage);\n\t\tconst initialErrors: SettingsError[] = [];\n\t\tif (globalLoad.error) {\n\t\t\tinitialErrors.push({ scope: \"global\", error: globalLoad.error });\n\t\t}\n\t\tif (projectLoad.error) {\n\t\t\tinitialErrors.push({ scope: \"project\", error: projectLoad.error });\n\t\t}\n\t\tif (directoryProfileLoad.error) {\n\t\t\tinitialErrors.push({ scope: \"directoryProfile\", error: directoryProfileLoad.error });\n\t\t}\n\n\t\treturn new SettingsManager(\n\t\t\tstorage,\n\t\t\tglobalLoad.settings,\n\t\t\tprojectLoad.settings,\n\t\t\tdirectoryProfileLoad.settings,\n\t\t\tglobalLoad.error,\n\t\t\tprojectLoad.error,\n\t\t\tinitialErrors,\n\t\t\tprojectTrusted,\n\t\t\tdirectoryProfileLoad.info,\n\t\t);\n\t}\n\n\t/** Create an in-memory SettingsManager (no file I/O) */\n\tstatic inMemory(settings: Partial<Settings> = {}): SettingsManager {\n\t\tconst storage = new InMemorySettingsStorage();\n\t\tconst initialSettings = SettingsManager.migrateSettings(structuredClone(settings) as Record<string, unknown>);\n\t\tstorage.withLock(\"global\", () => JSON.stringify(initialSettings, null, 2));\n\t\treturn SettingsManager.fromStorage(storage);\n\t}\n\n\tprivate static loadFromStorage(storage: SettingsStorage, scope: SettingsScope, projectTrusted = true): Settings {\n\t\tif (scope === \"project\" && !projectTrusted) {\n\t\t\treturn {};\n\t\t}\n\n\t\tlet content: string | undefined;\n\t\tstorage.withLock(scope, (current) => {\n\t\t\tcontent = current;\n\t\t\treturn undefined;\n\t\t});\n\n\t\tif (!content) {\n\t\t\treturn {};\n\t\t}\n\t\tconst settings = JSON.parse(content);\n\t\treturn SettingsManager.migrateSettings(settings);\n\t}\n\n\tprivate static tryLoadFromStorage(\n\t\tstorage: SettingsStorage,\n\t\tscope: SettingsScope,\n\t\tprojectTrusted = true,\n\t): { settings: Settings; error: Error | null } {\n\t\ttry {\n\t\t\treturn { settings: SettingsManager.loadFromStorage(storage, scope, projectTrusted), error: null };\n\t\t} catch (error) {\n\t\t\treturn { settings: {}, error: error as Error };\n\t\t}\n\t}\n\n\tprivate static tryLoadDirectoryProfileFromStorage(storage: SettingsStorage): {\n\t\tsettings: Settings;\n\t\terror: Error | null;\n\t\tinfo: DirectoryResourceProfileInfo | null;\n\t} {\n\t\tif (!(storage instanceof FileSettingsStorage)) {\n\t\t\treturn { settings: {}, error: null, info: null };\n\t\t}\n\t\tconst info = storage.getDirectoryResourceProfileInfo();\n\t\ttry {\n\t\t\tconst content = storage.readDirectoryResourceProfile();\n\t\t\tif (!content) return { settings: {}, error: null, info };\n\t\t\tconst settings = JSON.parse(content);\n\t\t\treturn { settings: SettingsManager.migrateSettings(settings), error: null, info };\n\t\t} catch (error) {\n\t\t\treturn { settings: {}, error: error as Error, info };\n\t\t}\n\t}\n\n\t/** Migrate old settings format to new format */\n\tprivate static migrateSettings(settings: Record<string, unknown>): Settings {\n\t\t// Migrate queueMode -> steeringMode\n\t\tif (\"queueMode\" in settings && !(\"steeringMode\" in settings)) {\n\t\t\tsettings.steeringMode = settings.queueMode;\n\t\t\tdelete settings.queueMode;\n\t\t}\n\n\t\t// Migrate legacy websockets boolean -> transport enum\n\t\tif (!(\"transport\" in settings) && typeof settings.websockets === \"boolean\") {\n\t\t\tsettings.transport = settings.websockets ? \"websocket\" : \"sse\";\n\t\t\tdelete settings.websockets;\n\t\t}\n\n\t\t// Migrate old skills object format to new array format\n\t\tif (\n\t\t\t\"skills\" in settings &&\n\t\t\ttypeof settings.skills === \"object\" &&\n\t\t\tsettings.skills !== null &&\n\t\t\t!Array.isArray(settings.skills)\n\t\t) {\n\t\t\tconst skillsSettings = settings.skills as {\n\t\t\t\tenableSkillCommands?: boolean;\n\t\t\t\tcustomDirectories?: unknown;\n\t\t\t};\n\t\t\tif (skillsSettings.enableSkillCommands !== undefined && settings.enableSkillCommands === undefined) {\n\t\t\t\tsettings.enableSkillCommands = skillsSettings.enableSkillCommands;\n\t\t\t}\n\t\t\tif (Array.isArray(skillsSettings.customDirectories) && skillsSettings.customDirectories.length > 0) {\n\t\t\t\tsettings.skills = skillsSettings.customDirectories;\n\t\t\t} else {\n\t\t\t\tdelete settings.skills;\n\t\t\t}\n\t\t}\n\n\t\t// Migrate retry.maxDelayMs -> retry.provider.maxRetryDelayMs\n\t\tif (\n\t\t\t\"retry\" in settings &&\n\t\t\ttypeof settings.retry === \"object\" &&\n\t\t\tsettings.retry !== null &&\n\t\t\t!Array.isArray(settings.retry)\n\t\t) {\n\t\t\tconst retrySettings = settings.retry as Record<string, unknown>;\n\t\t\tconst providerSettings =\n\t\t\t\ttypeof retrySettings.provider === \"object\" && retrySettings.provider !== null\n\t\t\t\t\t? (retrySettings.provider as Record<string, unknown>)\n\t\t\t\t\t: undefined;\n\t\t\tif (\n\t\t\t\ttypeof retrySettings.maxDelayMs === \"number\" &&\n\t\t\t\t(providerSettings?.maxRetryDelayMs === undefined || providerSettings?.maxRetryDelayMs === null)\n\t\t\t) {\n\t\t\t\tretrySettings.provider = {\n\t\t\t\t\t...(providerSettings ?? {}),\n\t\t\t\t\tmaxRetryDelayMs: retrySettings.maxDelayMs,\n\t\t\t\t};\n\t\t\t}\n\t\t\tdelete retrySettings.maxDelayMs;\n\t\t}\n\n\t\treturn settings as Settings;\n\t}\n\n\tgetGlobalSettings(): Settings {\n\t\treturn structuredClone(this.globalSettings);\n\t}\n\n\tgetProjectSettings(): Settings {\n\t\treturn structuredClone(this.projectSettings);\n\t}\n\n\tgetDirectoryResourceProfileSettings(): Settings {\n\t\treturn structuredClone(this.directoryProfileSettings);\n\t}\n\n\tgetDirectoryResourceProfileInfo(): DirectoryResourceProfileInfo | null {\n\t\treturn this.directoryProfileInfo ? { ...this.directoryProfileInfo } : null;\n\t}\n\n\tgetActiveResourceProfileNames(): string[] {\n\t\tif (this.runtimeResourceProfiles && this.runtimeResourceProfiles.length > 0) {\n\t\t\treturn [...this.runtimeResourceProfiles];\n\t\t}\n\t\treturn normalizeActiveResourceProfiles(this.settings);\n\t}\n\n\tgetResourceProfileFilter(kind: ResourceProfileKind): Required<ResourceProfileFilterSettings> {\n\t\tconst legacyFilter = mergeResourceProfileFilters(\n\t\t\tcollectLegacyDisabledFilterFromSettings(this.globalSettings, kind),\n\t\t\tcollectLegacyDisabledFilterFromSettings(this.projectSettings, kind),\n\t\t\tcollectLegacyDisabledFilterFromSettings(this.directoryProfileSettings, kind),\n\t\t);\n\t\tconst activeProfiles = this.getActiveResourceProfileNames();\n\t\tconst profileFilter = mergeResourceProfileFilters(\n\t\t\tcollectNamedResourceProfileFilters(this.globalSettings, kind, activeProfiles),\n\t\t\tcollectNamedResourceProfileFilters(this.projectSettings, kind, activeProfiles),\n\t\t\tcollectNamedResourceProfileFilters(this.directoryProfileSettings, kind, activeProfiles),\n\t\t\tcollectNamedResourceProfileFilters(\n\t\t\t\t{ resourceProfiles: this.inlineResourceProfileDefinitions },\n\t\t\t\tkind,\n\t\t\t\tactiveProfiles,\n\t\t\t),\n\t\t\tcollectNamedResourceProfileFilters(\n\t\t\t\t{ resourceProfiles: this.discoveredResourceProfileDefinitions },\n\t\t\t\tkind,\n\t\t\t\tactiveProfiles,\n\t\t\t),\n\t\t);\n\t\tconst filter = mergeResourceProfileFilters(legacyFilter, profileFilter);\n\t\treturn {\n\t\t\tallow: [...new Set(filter.allow ?? [])],\n\t\t\tblock: [...new Set(filter.block ?? [])],\n\t\t};\n\t}\n\n\tisResourceAllowedByProfile(kind: ResourceProfileKind, resourcePath: string, baseDir = \"\"): boolean {\n\t\tconst filter = this.getResourceProfileFilter(kind);\n\t\tif (filter.allow.length > 0 && !matchesResourceProfilePattern(resourcePath, filter.allow, baseDir)) {\n\t\t\treturn false;\n\t\t}\n\t\tif (matchesResourceProfilePattern(resourcePath, filter.block, baseDir)) {\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\n\tisProjectTrusted(): boolean {\n\t\treturn this.projectTrusted;\n\t}\n\n\tsetProjectTrusted(trusted: boolean): void {\n\t\tif (this.projectTrusted === trusted) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.projectTrusted = trusted;\n\t\tthis.modifiedProjectFields.clear();\n\t\tthis.modifiedProjectNestedFields.clear();\n\n\t\tif (!trusted) {\n\t\t\tthis.projectSettings = {};\n\t\t\tthis.projectSettingsLoadError = null;\n\t\t\tthis.recomputeSettings();\n\t\t\treturn;\n\t\t}\n\n\t\tconst projectLoad = SettingsManager.tryLoadFromStorage(this.storage, \"project\", trusted);\n\t\tthis.projectSettings = projectLoad.settings;\n\t\tthis.projectSettingsLoadError = projectLoad.error;\n\t\tif (projectLoad.error) {\n\t\t\tthis.recordError(\"project\", projectLoad.error);\n\t\t}\n\t\tthis.recomputeSettings();\n\t}\n\n\tasync reload(): Promise<void> {\n\t\tawait this.writeQueue;\n\t\tconst globalLoad = SettingsManager.tryLoadFromStorage(this.storage, \"global\");\n\t\tif (!globalLoad.error) {\n\t\t\tthis.globalSettings = globalLoad.settings;\n\t\t\tthis.globalSettingsLoadError = null;\n\t\t} else {\n\t\t\tthis.globalSettingsLoadError = globalLoad.error;\n\t\t\tthis.recordError(\"global\", globalLoad.error);\n\t\t}\n\n\t\tthis.modifiedFields.clear();\n\t\tthis.modifiedNestedFields.clear();\n\t\tthis.modifiedProjectFields.clear();\n\t\tthis.modifiedProjectNestedFields.clear();\n\n\t\tconst projectLoad = SettingsManager.tryLoadFromStorage(this.storage, \"project\", this.projectTrusted);\n\t\tif (!projectLoad.error) {\n\t\t\tthis.projectSettings = projectLoad.settings;\n\t\t\tthis.projectSettingsLoadError = null;\n\t\t} else {\n\t\t\tthis.projectSettingsLoadError = projectLoad.error;\n\t\t\tthis.recordError(\"project\", projectLoad.error);\n\t\t}\n\n\t\tconst directoryProfileLoad = SettingsManager.tryLoadDirectoryProfileFromStorage(this.storage);\n\t\tthis.directoryProfileInfo = directoryProfileLoad.info;\n\t\tif (!directoryProfileLoad.error) {\n\t\t\tthis.directoryProfileSettings = directoryProfileLoad.settings;\n\t\t} else {\n\t\t\tthis.recordError(\"directoryProfile\", directoryProfileLoad.error);\n\t\t}\n\n\t\tthis.recomputeSettings();\n\t}\n\n\t/** Apply additional overrides on top of current settings */\n\tapplyOverrides(overrides: Partial<Settings>): void {\n\t\tthis.settings = deepMergeSettings(this.settings, overrides);\n\t}\n\n\t/** Select runtime-only resource profiles, e.g. from CLI/subagent launch options. */\n\tsetRuntimeResourceProfiles(profileNames: string[]): void {\n\t\tthis.runtimeResourceProfiles = profileNames.length > 0 ? [...profileNames] : undefined;\n\t\tthis.recomputeSettings();\n\t}\n\n\t/** Add one-shot profile definitions from CLI/SDK/ephemeral agent launch input. Never writes to disk. */\n\taddInlineResourceProfileDefinitions(profiles: Record<string, ResourceProfileSettings>): void {\n\t\tthis.inlineResourceProfileDefinitions = mergeResourceProfileMap(this.inlineResourceProfileDefinitions, profiles);\n\t}\n\n\t/** Replace profile definitions discovered inside loaded resource files. Never writes to disk. */\n\treplaceDiscoveredResourceProfileDefinitions(profiles: Record<string, ResourceProfileSettings>): void {\n\t\tthis.discoveredResourceProfileDefinitions = { ...profiles };\n\t}\n\n\t/** Add profile definitions discovered after resource resolution, e.g. context agent files. Never writes to disk. */\n\taddDiscoveredResourceProfileDefinitions(profiles: Record<string, ResourceProfileSettings>): void {\n\t\tthis.discoveredResourceProfileDefinitions = mergeResourceProfileMap(\n\t\t\tthis.discoveredResourceProfileDefinitions,\n\t\t\tprofiles,\n\t\t);\n\t}\n\n\t/** Mark a global field as modified during this session */\n\tprivate markModified(field: keyof Settings, nestedKey?: string): void {\n\t\tthis.modifiedFields.add(field);\n\t\tif (nestedKey) {\n\t\t\tif (!this.modifiedNestedFields.has(field)) {\n\t\t\t\tthis.modifiedNestedFields.set(field, new Set());\n\t\t\t}\n\t\t\tthis.modifiedNestedFields.get(field)!.add(nestedKey);\n\t\t}\n\t}\n\n\t/** Mark a project field as modified during this session */\n\tprivate markProjectModified(field: keyof Settings, nestedKey?: string): void {\n\t\tthis.modifiedProjectFields.add(field);\n\t\tif (nestedKey) {\n\t\t\tif (!this.modifiedProjectNestedFields.has(field)) {\n\t\t\t\tthis.modifiedProjectNestedFields.set(field, new Set());\n\t\t\t}\n\t\t\tthis.modifiedProjectNestedFields.get(field)!.add(nestedKey);\n\t\t}\n\t}\n\n\tprivate assertProjectTrustedForWrite(): void {\n\t\tif (!this.projectTrusted) {\n\t\t\tthrow new Error(\"Project is not trusted; refusing to write project settings\");\n\t\t}\n\t}\n\n\tprivate recordError(scope: SettingsErrorScope, error: unknown): void {\n\t\tconst normalizedError = error instanceof Error ? error : new Error(String(error));\n\t\tthis.errors.push({ scope, error: normalizedError });\n\t}\n\n\tprivate clearModifiedScope(scope: SettingsScope): void {\n\t\tif (scope === \"global\") {\n\t\t\tthis.modifiedFields.clear();\n\t\t\tthis.modifiedNestedFields.clear();\n\t\t\treturn;\n\t\t}\n\n\t\tthis.modifiedProjectFields.clear();\n\t\tthis.modifiedProjectNestedFields.clear();\n\t}\n\n\tprivate enqueueWrite(scope: SettingsScope, task: () => void): void {\n\t\tthis.writeQueue = this.writeQueue\n\t\t\t.then(() => {\n\t\t\t\tif (scope === \"project\") {\n\t\t\t\t\tthis.assertProjectTrustedForWrite();\n\t\t\t\t}\n\t\t\t\ttask();\n\t\t\t\tthis.clearModifiedScope(scope);\n\t\t\t})\n\t\t\t.catch((error) => {\n\t\t\t\tthis.recordError(scope, error);\n\t\t\t});\n\t}\n\n\tprivate cloneModifiedNestedFields(source: Map<keyof Settings, Set<string>>): Map<keyof Settings, Set<string>> {\n\t\tconst snapshot = new Map<keyof Settings, Set<string>>();\n\t\tfor (const [key, value] of source.entries()) {\n\t\t\tsnapshot.set(key, new Set(value));\n\t\t}\n\t\treturn snapshot;\n\t}\n\n\tprivate persistScopedSettings(\n\t\tscope: SettingsScope,\n\t\tsnapshotSettings: Settings,\n\t\tmodifiedFields: Set<keyof Settings>,\n\t\tmodifiedNestedFields: Map<keyof Settings, Set<string>>,\n\t): void {\n\t\tthis.storage.withLock(scope, (current) => {\n\t\t\tconst currentFileSettings = current\n\t\t\t\t? SettingsManager.migrateSettings(JSON.parse(current) as Record<string, unknown>)\n\t\t\t\t: {};\n\t\t\tconst mergedSettings: Settings = { ...currentFileSettings };\n\t\t\tfor (const field of modifiedFields) {\n\t\t\t\tconst value = snapshotSettings[field];\n\t\t\t\tif (modifiedNestedFields.has(field) && typeof value === \"object\" && value !== null) {\n\t\t\t\t\tconst nestedModified = modifiedNestedFields.get(field)!;\n\t\t\t\t\tconst baseNested = (currentFileSettings[field] as Record<string, unknown>) ?? {};\n\t\t\t\t\tconst inMemoryNested = value as Record<string, unknown>;\n\t\t\t\t\tconst mergedNested = { ...baseNested };\n\t\t\t\t\tfor (const nestedKey of nestedModified) {\n\t\t\t\t\t\tmergedNested[nestedKey] = inMemoryNested[nestedKey];\n\t\t\t\t\t}\n\t\t\t\t\t(mergedSettings as Record<string, unknown>)[field] = mergedNested;\n\t\t\t\t} else {\n\t\t\t\t\t(mergedSettings as Record<string, unknown>)[field] = value;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn JSON.stringify(mergedSettings, null, 2);\n\t\t});\n\t}\n\n\tprivate save(): void {\n\t\tthis.recomputeSettings();\n\n\t\tif (this.globalSettingsLoadError) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst snapshotGlobalSettings = structuredClone(this.globalSettings);\n\t\tconst modifiedFields = new Set(this.modifiedFields);\n\t\tconst modifiedNestedFields = this.cloneModifiedNestedFields(this.modifiedNestedFields);\n\n\t\tthis.enqueueWrite(\"global\", () => {\n\t\t\tthis.persistScopedSettings(\"global\", snapshotGlobalSettings, modifiedFields, modifiedNestedFields);\n\t\t});\n\t}\n\n\tprivate saveProjectSettings(settings: Settings): void {\n\t\tthis.assertProjectTrustedForWrite();\n\t\tthis.projectSettings = structuredClone(settings);\n\t\tthis.recomputeSettings();\n\n\t\tif (this.projectSettingsLoadError) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst snapshotProjectSettings = structuredClone(this.projectSettings);\n\t\tconst modifiedFields = new Set(this.modifiedProjectFields);\n\t\tconst modifiedNestedFields = this.cloneModifiedNestedFields(this.modifiedProjectNestedFields);\n\t\tthis.enqueueWrite(\"project\", () => {\n\t\t\tthis.persistScopedSettings(\"project\", snapshotProjectSettings, modifiedFields, modifiedNestedFields);\n\t\t});\n\t}\n\n\tprivate updateProjectSettings(field: keyof Settings, update: (settings: Settings) => void): void {\n\t\tthis.assertProjectTrustedForWrite();\n\t\tconst projectSettings = structuredClone(this.projectSettings);\n\t\tupdate(projectSettings);\n\t\tthis.markProjectModified(field);\n\t\tthis.saveProjectSettings(projectSettings);\n\t}\n\n\tasync flush(): Promise<void> {\n\t\tawait this.writeQueue;\n\t}\n\n\tdrainErrors(): SettingsError[] {\n\t\tconst drained = [...this.errors];\n\t\tthis.errors = [];\n\t\treturn drained;\n\t}\n\n\tgetLastChangelogVersion(): string | undefined {\n\t\treturn this.settings.lastChangelogVersion;\n\t}\n\n\tsetLastChangelogVersion(version: string): void {\n\t\tthis.globalSettings.lastChangelogVersion = version;\n\t\tthis.markModified(\"lastChangelogVersion\");\n\t\tthis.save();\n\t}\n\n\tgetSessionDir(): string | undefined {\n\t\tconst sessionDir = this.settings.sessionDir;\n\t\treturn sessionDir ? normalizePath(sessionDir) : sessionDir;\n\t}\n\n\tgetDefaultProvider(): string | undefined {\n\t\treturn this.settings.defaultProvider;\n\t}\n\n\tgetDefaultModel(): string | undefined {\n\t\treturn this.settings.defaultModel;\n\t}\n\n\tsetDefaultProvider(provider: string): void {\n\t\tthis.globalSettings.defaultProvider = provider;\n\t\tthis.markModified(\"defaultProvider\");\n\t\tthis.save();\n\t}\n\n\tsetDefaultModel(modelId: string): void {\n\t\tthis.globalSettings.defaultModel = modelId;\n\t\tthis.markModified(\"defaultModel\");\n\t\tthis.save();\n\t}\n\n\tsetDefaultModelAndProvider(provider: string, modelId: string): void {\n\t\tthis.globalSettings.defaultProvider = provider;\n\t\tthis.globalSettings.defaultModel = modelId;\n\t\tthis.markModified(\"defaultProvider\");\n\t\tthis.markModified(\"defaultModel\");\n\t\tthis.save();\n\t}\n\n\tgetSteeringMode(): \"all\" | \"one-at-a-time\" {\n\t\treturn this.settings.steeringMode || \"one-at-a-time\";\n\t}\n\n\tsetSteeringMode(mode: \"all\" | \"one-at-a-time\"): void {\n\t\tthis.globalSettings.steeringMode = mode;\n\t\tthis.markModified(\"steeringMode\");\n\t\tthis.save();\n\t}\n\n\tgetFollowUpMode(): \"all\" | \"one-at-a-time\" {\n\t\treturn this.settings.followUpMode || \"one-at-a-time\";\n\t}\n\n\tsetFollowUpMode(mode: \"all\" | \"one-at-a-time\"): void {\n\t\tthis.globalSettings.followUpMode = mode;\n\t\tthis.markModified(\"followUpMode\");\n\t\tthis.save();\n\t}\n\n\tgetTheme(): string | undefined {\n\t\treturn this.settings.theme;\n\t}\n\n\tsetTheme(theme: string): void {\n\t\tthis.globalSettings.theme = theme;\n\t\tthis.markModified(\"theme\");\n\t\tthis.save();\n\t}\n\n\tgetDefaultThinkingLevel(): \"off\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\" | undefined {\n\t\treturn this.settings.defaultThinkingLevel;\n\t}\n\n\tsetDefaultThinkingLevel(level: \"off\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\"): void {\n\t\tthis.globalSettings.defaultThinkingLevel = level;\n\t\tthis.markModified(\"defaultThinkingLevel\");\n\t\tthis.save();\n\t}\n\n\tgetTransport(): TransportSetting {\n\t\treturn this.settings.transport ?? \"auto\";\n\t}\n\n\tsetTransport(transport: TransportSetting): void {\n\t\tthis.globalSettings.transport = transport;\n\t\tthis.markModified(\"transport\");\n\t\tthis.save();\n\t}\n\n\tgetCompactionEnabled(): boolean {\n\t\treturn this.settings.compaction?.enabled ?? true;\n\t}\n\n\tsetCompactionEnabled(enabled: boolean): void {\n\t\tif (!this.globalSettings.compaction) {\n\t\t\tthis.globalSettings.compaction = {};\n\t\t}\n\t\tthis.globalSettings.compaction.enabled = enabled;\n\t\tthis.markModified(\"compaction\", \"enabled\");\n\t\tthis.save();\n\t}\n\n\tgetCompactionReserveTokens(): number {\n\t\treturn this.settings.compaction?.reserveTokens ?? 16384;\n\t}\n\n\tgetCompactionKeepRecentTokens(): number {\n\t\treturn this.settings.compaction?.keepRecentTokens ?? 20000;\n\t}\n\n\tgetCompactionSettings(): { enabled: boolean; reserveTokens: number; keepRecentTokens: number } {\n\t\treturn {\n\t\t\tenabled: this.getCompactionEnabled(),\n\t\t\treserveTokens: this.getCompactionReserveTokens(),\n\t\t\tkeepRecentTokens: this.getCompactionKeepRecentTokens(),\n\t\t};\n\t}\n\n\tgetBranchSummarySettings(): { reserveTokens: number; skipPrompt: boolean } {\n\t\treturn {\n\t\t\treserveTokens: this.settings.branchSummary?.reserveTokens ?? 16384,\n\t\t\tskipPrompt: this.settings.branchSummary?.skipPrompt ?? false,\n\t\t};\n\t}\n\n\tgetBranchSummarySkipPrompt(): boolean {\n\t\treturn this.settings.branchSummary?.skipPrompt ?? false;\n\t}\n\n\tgetRetryEnabled(): boolean {\n\t\treturn this.settings.retry?.enabled ?? true;\n\t}\n\n\tsetRetryEnabled(enabled: boolean): void {\n\t\tif (!this.globalSettings.retry) {\n\t\t\tthis.globalSettings.retry = {};\n\t\t}\n\t\tthis.globalSettings.retry.enabled = enabled;\n\t\tthis.markModified(\"retry\", \"enabled\");\n\t\tthis.save();\n\t}\n\n\tgetRetrySettings(): { enabled: boolean; maxRetries: number; baseDelayMs: number } {\n\t\treturn {\n\t\t\tenabled: this.getRetryEnabled(),\n\t\t\tmaxRetries: this.settings.retry?.maxRetries ?? 3,\n\t\t\tbaseDelayMs: this.settings.retry?.baseDelayMs ?? 2000,\n\t\t};\n\t}\n\n\tgetHttpIdleTimeoutMs(): number {\n\t\treturn parseTimeoutSetting(this.settings.httpIdleTimeoutMs, \"httpIdleTimeoutMs\") ?? DEFAULT_HTTP_IDLE_TIMEOUT_MS;\n\t}\n\n\tsetHttpIdleTimeoutMs(timeoutMs: number): void {\n\t\tif (!Number.isFinite(timeoutMs) || timeoutMs < 0) {\n\t\t\tthrow new Error(`Invalid httpIdleTimeoutMs setting: ${String(timeoutMs)}`);\n\t\t}\n\t\tthis.globalSettings.httpIdleTimeoutMs = Math.floor(timeoutMs);\n\t\tthis.markModified(\"httpIdleTimeoutMs\");\n\t\tthis.save();\n\t}\n\n\tgetProviderRetrySettings(): { timeoutMs?: number; maxRetries?: number; maxRetryDelayMs: number } {\n\t\treturn {\n\t\t\ttimeoutMs: this.settings.retry?.provider?.timeoutMs,\n\t\t\tmaxRetries: this.settings.retry?.provider?.maxRetries,\n\t\t\tmaxRetryDelayMs: this.settings.retry?.provider?.maxRetryDelayMs ?? 60000,\n\t\t};\n\t}\n\n\tgetWebSocketConnectTimeoutMs(): number | undefined {\n\t\treturn parseTimeoutSetting(this.settings.websocketConnectTimeoutMs, \"websocketConnectTimeoutMs\");\n\t}\n\n\tgetHideThinkingBlock(): boolean {\n\t\treturn this.settings.hideThinkingBlock ?? false;\n\t}\n\n\tsetHideThinkingBlock(hide: boolean): void {\n\t\tthis.globalSettings.hideThinkingBlock = hide;\n\t\tthis.markModified(\"hideThinkingBlock\");\n\t\tthis.save();\n\t}\n\n\tgetShellPath(): string | undefined {\n\t\treturn this.settings.shellPath;\n\t}\n\n\tsetShellPath(path: string | undefined): void {\n\t\tthis.globalSettings.shellPath = path;\n\t\tthis.markModified(\"shellPath\");\n\t\tthis.save();\n\t}\n\n\tgetQuietStartup(): boolean {\n\t\treturn this.settings.quietStartup ?? false;\n\t}\n\n\tsetQuietStartup(quiet: boolean): void {\n\t\tthis.globalSettings.quietStartup = quiet;\n\t\tthis.markModified(\"quietStartup\");\n\t\tthis.save();\n\t}\n\n\tgetShellCommandPrefix(): string | undefined {\n\t\treturn this.settings.shellCommandPrefix;\n\t}\n\n\tsetShellCommandPrefix(prefix: string | undefined): void {\n\t\tthis.globalSettings.shellCommandPrefix = prefix;\n\t\tthis.markModified(\"shellCommandPrefix\");\n\t\tthis.save();\n\t}\n\n\tgetNpmCommand(): string[] | undefined {\n\t\treturn this.settings.npmCommand ? [...this.settings.npmCommand] : undefined;\n\t}\n\n\tsetNpmCommand(command: string[] | undefined): void {\n\t\tthis.globalSettings.npmCommand = command ? [...command] : undefined;\n\t\tthis.markModified(\"npmCommand\");\n\t\tthis.save();\n\t}\n\n\tgetCollapseChangelog(): boolean {\n\t\treturn this.settings.collapseChangelog ?? false;\n\t}\n\n\tsetCollapseChangelog(collapse: boolean): void {\n\t\tthis.globalSettings.collapseChangelog = collapse;\n\t\tthis.markModified(\"collapseChangelog\");\n\t\tthis.save();\n\t}\n\n\tgetEnableInstallTelemetry(): boolean {\n\t\treturn this.settings.enableInstallTelemetry ?? true;\n\t}\n\n\tsetEnableInstallTelemetry(enabled: boolean): void {\n\t\tthis.globalSettings.enableInstallTelemetry = enabled;\n\t\tthis.markModified(\"enableInstallTelemetry\");\n\t\tthis.save();\n\t}\n\n\tgetPackages(): PackageSource[] {\n\t\treturn [...(this.settings.packages ?? [])];\n\t}\n\n\tsetPackages(packages: PackageSource[]): void {\n\t\tthis.globalSettings.packages = packages;\n\t\tthis.markModified(\"packages\");\n\t\tthis.save();\n\t}\n\n\tsetProjectPackages(packages: PackageSource[]): void {\n\t\tthis.updateProjectSettings(\"packages\", (settings) => {\n\t\t\tsettings.packages = packages;\n\t\t});\n\t}\n\n\tgetExtensionPaths(): string[] {\n\t\treturn [...(this.settings.extensions ?? [])];\n\t}\n\n\tsetExtensionPaths(paths: string[]): void {\n\t\tthis.globalSettings.extensions = paths;\n\t\tthis.markModified(\"extensions\");\n\t\tthis.save();\n\t}\n\n\tsetProjectExtensionPaths(paths: string[]): void {\n\t\tthis.updateProjectSettings(\"extensions\", (settings) => {\n\t\t\tsettings.extensions = paths;\n\t\t});\n\t}\n\n\tgetSkillPaths(): string[] {\n\t\treturn [...(this.settings.skills ?? [])];\n\t}\n\n\tsetSkillPaths(paths: string[]): void {\n\t\tthis.globalSettings.skills = paths;\n\t\tthis.markModified(\"skills\");\n\t\tthis.save();\n\t}\n\n\tsetProjectSkillPaths(paths: string[]): void {\n\t\tthis.updateProjectSettings(\"skills\", (settings) => {\n\t\t\tsettings.skills = paths;\n\t\t});\n\t}\n\n\tgetPromptTemplatePaths(): string[] {\n\t\treturn [...(this.settings.prompts ?? [])];\n\t}\n\n\tsetPromptTemplatePaths(paths: string[]): void {\n\t\tthis.globalSettings.prompts = paths;\n\t\tthis.markModified(\"prompts\");\n\t\tthis.save();\n\t}\n\n\tsetProjectPromptTemplatePaths(paths: string[]): void {\n\t\tthis.updateProjectSettings(\"prompts\", (settings) => {\n\t\t\tsettings.prompts = paths;\n\t\t});\n\t}\n\n\tgetThemePaths(): string[] {\n\t\treturn [...(this.settings.themes ?? [])];\n\t}\n\n\tsetThemePaths(paths: string[]): void {\n\t\tthis.globalSettings.themes = paths;\n\t\tthis.markModified(\"themes\");\n\t\tthis.save();\n\t}\n\n\tsetProjectThemePaths(paths: string[]): void {\n\t\tthis.updateProjectSettings(\"themes\", (settings) => {\n\t\t\tsettings.themes = paths;\n\t\t});\n\t}\n\n\tgetEnableSkillCommands(): boolean {\n\t\treturn this.settings.enableSkillCommands ?? true;\n\t}\n\n\tsetEnableSkillCommands(enabled: boolean): void {\n\t\tthis.globalSettings.enableSkillCommands = enabled;\n\t\tthis.markModified(\"enableSkillCommands\");\n\t\tthis.save();\n\t}\n\n\tgetThinkingBudgets(): ThinkingBudgetsSettings | undefined {\n\t\treturn this.settings.thinkingBudgets;\n\t}\n\n\tgetShowImages(): boolean {\n\t\treturn this.settings.terminal?.showImages ?? true;\n\t}\n\n\tsetShowImages(show: boolean): void {\n\t\tif (!this.globalSettings.terminal) {\n\t\t\tthis.globalSettings.terminal = {};\n\t\t}\n\t\tthis.globalSettings.terminal.showImages = show;\n\t\tthis.markModified(\"terminal\", \"showImages\");\n\t\tthis.save();\n\t}\n\n\tgetImageWidthCells(): number {\n\t\tconst width = this.settings.terminal?.imageWidthCells;\n\t\tif (typeof width !== \"number\" || !Number.isFinite(width)) {\n\t\t\treturn 60;\n\t\t}\n\t\treturn Math.max(1, Math.floor(width));\n\t}\n\n\tsetImageWidthCells(width: number): void {\n\t\tif (!this.globalSettings.terminal) {\n\t\t\tthis.globalSettings.terminal = {};\n\t\t}\n\t\tthis.globalSettings.terminal.imageWidthCells = Math.max(1, Math.floor(width));\n\t\tthis.markModified(\"terminal\", \"imageWidthCells\");\n\t\tthis.save();\n\t}\n\n\tgetClearOnShrink(): boolean {\n\t\t// Settings takes precedence, then env var, then default false\n\t\tif (this.settings.terminal?.clearOnShrink !== undefined) {\n\t\t\treturn this.settings.terminal.clearOnShrink;\n\t\t}\n\t\treturn process.env.PI_CLEAR_ON_SHRINK === \"1\";\n\t}\n\n\tsetClearOnShrink(enabled: boolean): void {\n\t\tif (!this.globalSettings.terminal) {\n\t\t\tthis.globalSettings.terminal = {};\n\t\t}\n\t\tthis.globalSettings.terminal.clearOnShrink = enabled;\n\t\tthis.markModified(\"terminal\", \"clearOnShrink\");\n\t\tthis.save();\n\t}\n\n\tgetShowTerminalProgress(): boolean {\n\t\treturn this.settings.terminal?.showTerminalProgress ?? false;\n\t}\n\n\tsetShowTerminalProgress(enabled: boolean): void {\n\t\tif (!this.globalSettings.terminal) {\n\t\t\tthis.globalSettings.terminal = {};\n\t\t}\n\t\tthis.globalSettings.terminal.showTerminalProgress = enabled;\n\t\tthis.markModified(\"terminal\", \"showTerminalProgress\");\n\t\tthis.save();\n\t}\n\n\tgetImageAutoResize(): boolean {\n\t\treturn this.settings.images?.autoResize ?? true;\n\t}\n\n\tsetImageAutoResize(enabled: boolean): void {\n\t\tif (!this.globalSettings.images) {\n\t\t\tthis.globalSettings.images = {};\n\t\t}\n\t\tthis.globalSettings.images.autoResize = enabled;\n\t\tthis.markModified(\"images\", \"autoResize\");\n\t\tthis.save();\n\t}\n\n\tgetBlockImages(): boolean {\n\t\treturn this.settings.images?.blockImages ?? false;\n\t}\n\n\tsetBlockImages(blocked: boolean): void {\n\t\tif (!this.globalSettings.images) {\n\t\t\tthis.globalSettings.images = {};\n\t\t}\n\t\tthis.globalSettings.images.blockImages = blocked;\n\t\tthis.markModified(\"images\", \"blockImages\");\n\t\tthis.save();\n\t}\n\n\tgetEnabledModels(): string[] | undefined {\n\t\treturn this.settings.enabledModels;\n\t}\n\n\tsetEnabledModels(patterns: string[] | undefined): void {\n\t\tthis.globalSettings.enabledModels = patterns;\n\t\tthis.markModified(\"enabledModels\");\n\t\tthis.save();\n\t}\n\n\tgetDoubleEscapeAction(): \"fork\" | \"tree\" | \"none\" {\n\t\treturn this.settings.doubleEscapeAction ?? \"tree\";\n\t}\n\n\tsetDoubleEscapeAction(action: \"fork\" | \"tree\" | \"none\"): void {\n\t\tthis.globalSettings.doubleEscapeAction = action;\n\t\tthis.markModified(\"doubleEscapeAction\");\n\t\tthis.save();\n\t}\n\n\tgetTreeFilterMode(): \"default\" | \"no-tools\" | \"user-only\" | \"labeled-only\" | \"all\" {\n\t\tconst mode = this.settings.treeFilterMode;\n\t\tconst valid = [\"default\", \"no-tools\", \"user-only\", \"labeled-only\", \"all\"];\n\t\treturn mode && valid.includes(mode) ? mode : \"default\";\n\t}\n\n\tsetTreeFilterMode(mode: \"default\" | \"no-tools\" | \"user-only\" | \"labeled-only\" | \"all\"): void {\n\t\tthis.globalSettings.treeFilterMode = mode;\n\t\tthis.markModified(\"treeFilterMode\");\n\t\tthis.save();\n\t}\n\n\tgetShowHardwareCursor(): boolean {\n\t\treturn this.settings.showHardwareCursor ?? process.env.PI_HARDWARE_CURSOR === \"1\";\n\t}\n\n\tsetShowHardwareCursor(enabled: boolean): void {\n\t\tthis.globalSettings.showHardwareCursor = enabled;\n\t\tthis.markModified(\"showHardwareCursor\");\n\t\tthis.save();\n\t}\n\n\tgetEditorPaddingX(): number {\n\t\treturn this.settings.editorPaddingX ?? 0;\n\t}\n\n\tsetEditorPaddingX(padding: number): void {\n\t\tthis.globalSettings.editorPaddingX = Math.max(0, Math.min(3, Math.floor(padding)));\n\t\tthis.markModified(\"editorPaddingX\");\n\t\tthis.save();\n\t}\n\n\tgetAutocompleteMaxVisible(): number {\n\t\treturn this.settings.autocompleteMaxVisible ?? 5;\n\t}\n\n\tsetAutocompleteMaxVisible(maxVisible: number): void {\n\t\tthis.globalSettings.autocompleteMaxVisible = Math.max(3, Math.min(20, Math.floor(maxVisible)));\n\t\tthis.markModified(\"autocompleteMaxVisible\");\n\t\tthis.save();\n\t}\n\n\tgetCodeBlockIndent(): string {\n\t\treturn this.settings.markdown?.codeBlockIndent ?? \" \";\n\t}\n\n\tgetWarnings(): WarningSettings {\n\t\treturn { ...(this.settings.warnings ?? {}) };\n\t}\n\n\tsetWarnings(warnings: WarningSettings): void {\n\t\tthis.globalSettings.warnings = { ...warnings };\n\t\tthis.markModified(\"warnings\");\n\t\tthis.save();\n\t}\n\n\tgetSelfModificationSettings(): { enabled: boolean; sourcePath?: string } {\n\t\treturn {\n\t\t\tenabled: this.settings.selfModification?.enabled ?? false,\n\t\t\tsourcePath: this.settings.selfModification?.sourcePath,\n\t\t};\n\t}\n\n\tsetSelfModificationSettings(settings: SelfModificationSettings, scope: SettingsScope = \"global\"): void {\n\t\tif (scope === \"project\") {\n\t\t\tconst projectSettings = structuredClone(this.projectSettings);\n\t\t\tprojectSettings.selfModification = { ...settings };\n\t\t\tthis.markProjectModified(\"selfModification\");\n\t\t\tthis.saveProjectSettings(projectSettings);\n\t\t\treturn;\n\t\t}\n\n\t\tthis.globalSettings.selfModification = { ...settings };\n\t\tthis.markModified(\"selfModification\");\n\t\tthis.save();\n\t}\n\n\tgetAutonomySettings(): { mode: AutonomyMode } {\n\t\tconst mode = this.settings.autonomy?.mode;\n\t\treturn { mode: mode === \"safe\" || mode === \"balanced\" || mode === \"full\" ? mode : \"off\" };\n\t}\n\n\tsetAutonomySettings(settings: AutonomySettings, scope: SettingsScope = \"global\"): void {\n\t\tif (scope === \"project\") {\n\t\t\tconst projectSettings = structuredClone(this.projectSettings);\n\t\t\tprojectSettings.autonomy = { ...settings };\n\t\t\tthis.markProjectModified(\"autonomy\");\n\t\t\tthis.saveProjectSettings(projectSettings);\n\t\t\treturn;\n\t\t}\n\n\t\tthis.globalSettings.autonomy = { ...settings };\n\t\tthis.markModified(\"autonomy\");\n\t\tthis.save();\n\t}\n\n\tgetAutoLearnSettings(): AutoLearnSettings {\n\t\treturn { ...(this.settings.autoLearn ?? {}) };\n\t}\n\n\tsetAutoLearnSettings(settings: AutoLearnSettings, scope: SettingsScope = \"global\"): void {\n\t\tif (scope === \"project\") {\n\t\t\tconst projectSettings = structuredClone(this.projectSettings);\n\t\t\tprojectSettings.autoLearn = { ...settings };\n\t\t\tthis.markProjectModified(\"autoLearn\");\n\t\t\tthis.saveProjectSettings(projectSettings);\n\t\t\treturn;\n\t\t}\n\n\t\tthis.globalSettings.autoLearn = { ...settings };\n\t\tthis.markModified(\"autoLearn\");\n\t\tthis.save();\n\t}\n}\n"]}
1
+ {"version":3,"file":"settings-manager.d.ts","sourceRoot":"","sources":["../../src/core/settings-manager.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAWnD,MAAM,WA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CAG5C;IAED,mBAAmB,CAAC,QAAQ,EAAE,gBAAgB,EAAE,KAAK,GAAE,aAAwB,GAAG,IAAI,CAYrF;IAED,oBAAoB,IAAI,iBAAiB,CAExC;IAED,oBAAoB,CAAC,QAAQ,EAAE,iBAAiB,EAAE,KAAK,GAAE,aAAwB,GAAG,IAAI,CAYvF;CACD","sourcesContent":["import type { Transport } from \"@caupulican/pi-ai\";\nimport { createHash } from \"crypto\";\nimport { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from \"fs\";\nimport { minimatch } from \"minimatch\";\nimport { basename, dirname, join, relative, resolve, sep } from \"path\";\nimport lockfile from \"proper-lockfile\";\nimport { CONFIG_DIR_NAME, getAgentDir } from \"../config.ts\";\nimport { normalizePath, resolvePath } from \"../utils/paths.ts\";\nimport { DEFAULT_HTTP_IDLE_TIMEOUT_MS, parseHttpIdleTimeoutMs } from \"./http-dispatcher.ts\";\nimport { mergeResourceProfileMap } from \"./resource-profile-blocks.ts\";\n\nexport interface CompactionSettings {\n\tenabled?: boolean; // default: true\n\treserveTokens?: number; // default: 16384\n\tkeepRecentTokens?: number; // default: 20000\n}\n\nexport interface SemanticMemoryGcSettings {\n\tenabled?: boolean; // default: true\n\tpreserveRecentPages?: number; // default: 2\n\tminChars?: number; // default: 1200\n\tmarkers?: string[]; // default: Automata/Mind XML-ish response tags\n}\n\nexport interface ContextGcSettings {\n\tenabled?: boolean; // default: true\n\tpreserveRecentMessages?: number; // default: 12\n\tminToolResultChars?: number; // default: 2500\n\ttools?: string[]; // default: read,bash,rg,grep,context_headroom_retrieve,headroom_retrieve\n\tsemanticMemory?: SemanticMemoryGcSettings;\n}\n\nexport interface BranchSummarySettings {\n\treserveTokens?: number; // default: 16384 (tokens reserved for prompt + LLM response)\n\tskipPrompt?: boolean; // default: false - when true, skips \"Summarize branch?\" prompt and defaults to no summary\n}\n\nexport interface ProviderRetrySettings {\n\ttimeoutMs?: number; // SDK/provider request timeout in milliseconds\n\tmaxRetries?: number; // SDK/provider retry attempts\n\tmaxRetryDelayMs?: number; // default: 60000 (max server-requested delay before failing)\n}\n\nexport interface RetrySettings {\n\tenabled?: boolean; // default: true\n\tmaxRetries?: number; // default: 3\n\tbaseDelayMs?: number; // default: 2000 (exponential backoff: 2s, 4s, 8s)\n\tprovider?: ProviderRetrySettings;\n}\n\nexport interface TerminalSettings {\n\tshowImages?: boolean; // default: true (only relevant if terminal supports images)\n\timageWidthCells?: number; // default: 60 (preferred inline image width in terminal cells)\n\tclearOnShrink?: boolean; // default: false (clear empty rows when content shrinks)\n\tshowTerminalProgress?: boolean; // default: false (OSC 9;4 terminal progress indicators)\n}\n\nexport interface ImageSettings {\n\tautoResize?: boolean; // default: true (resize images to 2000x2000 max for better model compatibility)\n\tblockImages?: boolean; // default: false - when true, prevents all images from being sent to LLM providers\n}\n\nexport interface ThinkingBudgetsSettings {\n\tminimal?: number;\n\tlow?: number;\n\tmedium?: number;\n\thigh?: number;\n}\n\nexport interface MarkdownSettings {\n\tcodeBlockIndent?: string; // default: \" \"\n}\n\nexport interface WarningSettings {\n\tanthropicExtraUsage?: boolean; // default: true\n}\n\nexport interface SelfModificationSettings {\n\tenabled?: boolean; // default: false\n\tsourcePath?: string; // Path to the pi-adaptative source tree when self-modification is enabled\n}\n\nexport interface AutoLearnSettings {\n\tenabled?: boolean; // default: false - autonomously trigger background history scavenging for long sessions\n\tmodel?: string; // \"active\" or omitted uses the current session model; otherwise a pi --model pattern\n\tlongSessionMessages?: number; // default: 64\n\tlongSessionContextPercent?: number; // default: 85\n\tcooldownMinutes?: number; // default: 1440 per session tenant (manual /auto-learn run bypasses)\n\tleaseMinutes?: number; // default: 90 for background learner state leases\n\tmaxConcurrentLearners?: number; // default: 2 per session tenant\n\tapplyHighConfidence?: boolean; // default: false unless the learning extension config opts in\n\treflectionReview?: boolean; // default: true when Auto Learn is enabled - post-turn review after corrective/complex turns\n\treflectionMinToolCalls?: number; // default: 8 tool calls in a turn before reflection review triggers\n\treflectionCooldownMinutes?: number; // default: 1440 per session tenant for reflection reviews\n}\n\nexport type AutonomyMode = \"off\" | \"safe\" | \"balanced\" | \"full\";\n\nexport interface AutonomySettings {\n\tmode?: AutonomyMode; // default: off; presets drive Auto Learn/reflection without many knobs\n}\n\nexport type TransportSetting = Transport;\n\n/**\n * Package source for npm/git packages.\n * - String form: load all resources from the package\n * - Object form: filter which resources to load\n */\nexport type PackageSource =\n\t| string\n\t| {\n\t\t\tsource: string;\n\t\t\textensions?: string[];\n\t\t\tskills?: string[];\n\t\t\tprompts?: string[];\n\t\t\tthemes?: string[];\n\t };\n\nexport type ResourceProfileKind = \"extensions\" | \"skills\" | \"prompts\" | \"themes\" | \"agents\" | \"tools\";\n\nexport interface ResourceProfileFilterSettings {\n\t/** Allowlist patterns. When non-empty, only matching resources stay available. */\n\tallow?: string[];\n\t/** Blocklist patterns. Applied after allow. */\n\tblock?: string[];\n}\n\nexport type ResourceProfileSettings = Partial<Record<ResourceProfileKind, ResourceProfileFilterSettings>>;\n\nexport interface DisabledResourcesSettings {\n\textensions?: string[];\n\tskills?: string[];\n\tprompts?: string[];\n\tthemes?: string[];\n\tagents?: string[];\n\ttools?: string[];\n}\n\nexport interface Settings {\n\tlastChangelogVersion?: string;\n\tdefaultProvider?: string;\n\tdefaultModel?: string;\n\tdefaultThinkingLevel?: \"off\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\";\n\ttransport?: TransportSetting; // default: \"auto\"\n\tsteeringMode?: \"all\" | \"one-at-a-time\";\n\tfollowUpMode?: \"all\" | \"one-at-a-time\";\n\ttheme?: string;\n\tcompaction?: CompactionSettings;\n\tcontextGc?: ContextGcSettings;\n\tbranchSummary?: BranchSummarySettings;\n\tretry?: RetrySettings;\n\thideThinkingBlock?: boolean;\n\tshellPath?: string; // Custom shell path (e.g., for Cygwin users on Windows)\n\tquietStartup?: boolean;\n\tshellCommandPrefix?: string; // Prefix prepended to every bash command (e.g., \"shopt -s expand_aliases\" for alias support)\n\tnpmCommand?: string[]; // Command used for npm package lookup/install operations, argv-style (e.g., [\"mise\", \"exec\", \"node@20\", \"--\", \"npm\"])\n\tcollapseChangelog?: boolean; // Show condensed changelog after update (use /changelog for full)\n\tenableInstallTelemetry?: boolean; // default: true - anonymous version/update ping after changelog-detected updates\n\tpackages?: PackageSource[]; // Array of npm/git package sources (string or object with filtering)\n\textensions?: string[]; // Array of local extension file paths/directories or include/exclude patterns\n\tskills?: string[]; // Array of local skill file paths/directories or include/exclude patterns\n\tprompts?: string[]; // Array of local prompt template paths/directories or include/exclude patterns\n\tthemes?: string[]; // Array of local theme file paths/directories or include/exclude patterns\n\tdisabledResources?: DisabledResourcesSettings; // Legacy reversible block filters for extensions/skills/prompts/themes/agents/tools\n\tresourceProfiles?: Record<string, ResourceProfileSettings>; // Named resource allow/block filters\n\tactiveResourceProfile?: string | string[]; // Active profile name(s), applied after global/project/directory settings merge\n\tactiveResourceProfiles?: string[]; // Active profile names, equivalent to activeResourceProfile array\n\tenableSkillCommands?: boolean; // default: true - register skills as /skill:name commands\n\tterminal?: TerminalSettings;\n\timages?: ImageSettings;\n\tenabledModels?: string[]; // Model patterns for cycling (same format as --models CLI flag)\n\tdoubleEscapeAction?: \"fork\" | \"tree\" | \"none\"; // Action for double-escape with empty editor (default: \"tree\")\n\ttreeFilterMode?: \"default\" | \"no-tools\" | \"user-only\" | \"labeled-only\" | \"all\"; // Default filter when opening /tree\n\tthinkingBudgets?: ThinkingBudgetsSettings; // Custom token budgets for thinking levels\n\teditorPaddingX?: number; // Horizontal padding for input editor (default: 0)\n\tautocompleteMaxVisible?: number; // Max visible items in autocomplete dropdown (default: 5)\n\tshowHardwareCursor?: boolean; // Show terminal cursor while still positioning it for IME\n\tmarkdown?: MarkdownSettings;\n\twarnings?: WarningSettings;\n\tselfModification?: SelfModificationSettings; // Local guardrails for modifying the pi-adaptative source/harness\n\tautonomy?: AutonomySettings; // Low-config autonomy preset controlling background learning/reflection defaults\n\tautoLearn?: AutoLearnSettings; // Setting-gated autonomous background learning for long sessions\n\tsessionDir?: string; // Custom session storage directory (same format as --session-dir CLI flag)\n\thttpIdleTimeoutMs?: number; // HTTP header/body idle timeout in milliseconds; 0 disables it\n\twebsocketConnectTimeoutMs?: number; // WebSocket connect/open handshake timeout in milliseconds; 0 disables it\n}\n\n/** Deep merge settings: project/overrides take precedence, nested objects merge recursively */\nfunction deepMergeSettings(base: Settings, overrides: Settings): Settings {\n\tconst result: Settings = { ...base };\n\n\tfor (const key of Object.keys(overrides) as (keyof Settings)[]) {\n\t\tconst overrideValue = overrides[key];\n\t\tconst baseValue = base[key];\n\n\t\tif (overrideValue === undefined) {\n\t\t\tcontinue;\n\t\t}\n\n\t\t// For nested objects, merge recursively\n\t\tif (\n\t\t\ttypeof overrideValue === \"object\" &&\n\t\t\toverrideValue !== null &&\n\t\t\t!Array.isArray(overrideValue) &&\n\t\t\ttypeof baseValue === \"object\" &&\n\t\t\tbaseValue !== null &&\n\t\t\t!Array.isArray(baseValue)\n\t\t) {\n\t\t\t(result as Record<string, unknown>)[key] = { ...baseValue, ...overrideValue };\n\t\t} else {\n\t\t\t// For primitives and arrays, override value wins\n\t\t\t(result as Record<string, unknown>)[key] = overrideValue;\n\t\t}\n\t}\n\n\treturn result;\n}\n\nfunction toPosixPath(p: string): string {\n\treturn p.split(sep).join(\"/\");\n}\n\nfunction findDirectoryProfileRoot(cwd: string): string {\n\tlet current = resolvePath(cwd);\n\twhile (true) {\n\t\tfor (const marker of [\".git\", \".hg\", \".svn\"]) {\n\t\t\ttry {\n\t\t\t\tstatSync(join(current, marker));\n\t\t\t\treturn current;\n\t\t\t} catch {}\n\t\t}\n\t\tconst parent = resolve(current, \"..\");\n\t\tif (parent === current) return resolvePath(cwd);\n\t\tcurrent = parent;\n\t}\n}\n\nexport interface DirectoryResourceProfileInfo {\n\troot: string;\n\thash: string;\n\tpath: string;\n}\n\nexport function getDirectoryResourceProfileInfo(\n\tcwd: string,\n\tagentDir: string = getAgentDir(),\n): DirectoryResourceProfileInfo {\n\tconst root = findDirectoryProfileRoot(cwd);\n\tconst hash = createHash(\"sha256\").update(root).digest(\"hex\").slice(0, 16);\n\treturn {\n\t\troot,\n\t\thash,\n\t\tpath: join(resolvePath(agentDir), \"resource-profiles\", hash, \"settings.json\"),\n\t};\n}\n\nexport function matchesResourceProfilePattern(resourcePath: string, patterns: string[], baseDir = \"\"): boolean {\n\tif (patterns.length === 0) return false;\n\tconst resolvedBase = baseDir ? resolvePath(baseDir) : \"\";\n\tconst rel = resolvedBase ? toPosixPath(relative(resolvedBase, resourcePath)) : toPosixPath(resourcePath);\n\tconst name = basename(resourcePath);\n\tconst filePathPosix = toPosixPath(resourcePath);\n\tconst parentDir = dirname(resourcePath);\n\tconst parentRel = resolvedBase ? toPosixPath(relative(resolvedBase, parentDir)) : toPosixPath(parentDir);\n\tconst parentName = basename(parentDir);\n\tconst parentDirPosix = toPosixPath(parentDir);\n\n\treturn patterns.some((pattern) => {\n\t\tconst normalizedPattern = toPosixPath(pattern);\n\t\treturn (\n\t\t\tminimatch(rel, normalizedPattern) ||\n\t\t\tminimatch(name, normalizedPattern) ||\n\t\t\tminimatch(filePathPosix, normalizedPattern) ||\n\t\t\tminimatch(parentRel, normalizedPattern) ||\n\t\t\tminimatch(parentName, normalizedPattern) ||\n\t\t\tminimatch(parentDirPosix, normalizedPattern)\n\t\t);\n\t});\n}\n\nfunction normalizeResourceProfileNames(value: unknown): string[] {\n\tconst values: string[] = [];\n\tconst add = (candidate: unknown) => {\n\t\tif (Array.isArray(candidate)) {\n\t\t\tfor (const item of candidate) add(item);\n\t\t\treturn;\n\t\t}\n\t\tif (typeof candidate === \"string\") {\n\t\t\tfor (const part of candidate.split(\",\")) {\n\t\t\t\tconst trimmed = part.trim();\n\t\t\t\tif (trimmed) values.push(trimmed);\n\t\t\t}\n\t\t}\n\t};\n\tadd(value);\n\treturn [...new Set(values)];\n}\n\nfunction normalizeActiveResourceProfiles(settings: Settings): string[] {\n\tconst explicitProfiles = normalizeResourceProfileNames(settings.activeResourceProfiles);\n\tconst values =\n\t\texplicitProfiles.length > 0 ? explicitProfiles : normalizeResourceProfileNames(settings.activeResourceProfile);\n\tif (values.length === 0 && settings.resourceProfiles?.default) {\n\t\tvalues.push(\"default\");\n\t}\n\treturn [...new Set(values)];\n}\n\nfunction appendFilter(target: ResourceProfileFilterSettings, source?: ResourceProfileFilterSettings): void {\n\tif (!source) return;\n\tif (Array.isArray(source.allow)) target.allow = [...(target.allow ?? []), ...source.allow];\n\tif (Array.isArray(source.block)) target.block = [...(target.block ?? []), ...source.block];\n}\n\nfunction collectLegacyDisabledFilterFromSettings(\n\tsettings: Settings,\n\tkind: ResourceProfileKind,\n): ResourceProfileFilterSettings {\n\tconst legacyDisabled = settings.disabledResources?.[kind];\n\treturn Array.isArray(legacyDisabled) ? { block: legacyDisabled } : {};\n}\n\nfunction collectNamedResourceProfileFilters(\n\tsettings: Settings,\n\tkind: ResourceProfileKind,\n\tprofileNames: string[],\n): ResourceProfileFilterSettings {\n\tconst result: ResourceProfileFilterSettings = {};\n\tfor (const profileName of profileNames) {\n\t\tappendFilter(result, settings.resourceProfiles?.[profileName]?.[kind]);\n\t}\n\treturn result;\n}\n\nfunction mergeResourceProfileFilters(...filters: ResourceProfileFilterSettings[]): ResourceProfileFilterSettings {\n\tconst result: ResourceProfileFilterSettings = {};\n\tfor (const filter of filters) appendFilter(result, filter);\n\treturn result;\n}\n\nfunction parseTimeoutSetting(value: unknown, settingName: string): number | undefined {\n\tconst timeoutMs = parseHttpIdleTimeoutMs(value);\n\tif (timeoutMs !== undefined) {\n\t\treturn timeoutMs;\n\t}\n\tif (value !== undefined) {\n\t\tthrow new Error(`Invalid ${settingName} setting: ${String(value)}`);\n\t}\n\treturn undefined;\n}\n\nexport type SettingsScope = \"global\" | \"project\";\nexport type SettingsErrorScope = SettingsScope | \"directoryProfile\";\n\nexport interface SettingsManagerCreateOptions {\n\tprojectTrusted?: boolean;\n}\n\nexport interface SettingsStorage {\n\twithLock(scope: SettingsScope, fn: (current: string | undefined) => string | undefined): void;\n}\n\nexport interface SettingsError {\n\tscope: SettingsErrorScope;\n\terror: Error;\n}\n\nexport class FileSettingsStorage implements SettingsStorage {\n\tprivate globalSettingsPath: string;\n\tprivate projectSettingsPath: string;\n\tprivate directoryProfileInfo: DirectoryResourceProfileInfo;\n\n\tconstructor(cwd: string, agentDir: string) {\n\t\tconst resolvedCwd = resolvePath(cwd);\n\t\tconst resolvedAgentDir = resolvePath(agentDir);\n\t\tthis.globalSettingsPath = join(resolvedAgentDir, \"settings.json\");\n\t\tthis.projectSettingsPath = join(resolvedCwd, CONFIG_DIR_NAME, \"settings.json\");\n\t\tthis.directoryProfileInfo = getDirectoryResourceProfileInfo(resolvedCwd, resolvedAgentDir);\n\t}\n\n\tgetDirectoryResourceProfileInfo(): DirectoryResourceProfileInfo {\n\t\treturn { ...this.directoryProfileInfo };\n\t}\n\n\treadDirectoryResourceProfile(): string | undefined {\n\t\tconst path = this.directoryProfileInfo.path;\n\t\treturn existsSync(path) ? readFileSync(path, \"utf-8\") : undefined;\n\t}\n\n\tprivate acquireLockSyncWithRetry(path: string): () => void {\n\t\tconst maxAttempts = 10;\n\t\tconst delayMs = 20;\n\t\tlet lastError: unknown;\n\n\t\tfor (let attempt = 1; attempt <= maxAttempts; attempt++) {\n\t\t\ttry {\n\t\t\t\treturn lockfile.lockSync(path, { realpath: false });\n\t\t\t} catch (error) {\n\t\t\t\tconst code =\n\t\t\t\t\ttypeof error === \"object\" && error !== null && \"code\" in error\n\t\t\t\t\t\t? String((error as { code?: unknown }).code)\n\t\t\t\t\t\t: undefined;\n\t\t\t\tif (code !== \"ELOCKED\" || attempt === maxAttempts) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tlastError = error;\n\t\t\t\tconst start = Date.now();\n\t\t\t\twhile (Date.now() - start < delayMs) {\n\t\t\t\t\t// Sleep synchronously to avoid changing callers to async.\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tthrow (lastError as Error) ?? new Error(\"Failed to acquire settings lock\");\n\t}\n\n\twithLock(scope: SettingsScope, fn: (current: string | undefined) => string | undefined): void {\n\t\tconst path = scope === \"global\" ? this.globalSettingsPath : this.projectSettingsPath;\n\t\tconst dir = dirname(path);\n\n\t\tlet release: (() => void) | undefined;\n\t\ttry {\n\t\t\t// Only create directory and lock if file exists or we need to write\n\t\t\tconst fileExists = existsSync(path);\n\t\t\tif (fileExists) {\n\t\t\t\trelease = this.acquireLockSyncWithRetry(path);\n\t\t\t}\n\t\t\tconst current = fileExists ? readFileSync(path, \"utf-8\") : undefined;\n\t\t\tconst next = fn(current);\n\t\t\tif (next !== undefined) {\n\t\t\t\t// Only create directory when we actually need to write\n\t\t\t\tif (!existsSync(dir)) {\n\t\t\t\t\tmkdirSync(dir, { recursive: true });\n\t\t\t\t}\n\t\t\t\tif (!release) {\n\t\t\t\t\trelease = this.acquireLockSyncWithRetry(path);\n\t\t\t\t}\n\t\t\t\twriteFileSync(path, next, \"utf-8\");\n\t\t\t}\n\t\t} finally {\n\t\t\tif (release) {\n\t\t\t\trelease();\n\t\t\t}\n\t\t}\n\t}\n}\n\nexport class InMemorySettingsStorage implements SettingsStorage {\n\tprivate global: string | undefined;\n\tprivate project: string | undefined;\n\n\twithLock(scope: SettingsScope, fn: (current: string | undefined) => string | undefined): void {\n\t\tconst current = scope === \"global\" ? this.global : this.project;\n\t\tconst next = fn(current);\n\t\tif (next !== undefined) {\n\t\t\tif (scope === \"global\") {\n\t\t\t\tthis.global = next;\n\t\t\t} else {\n\t\t\t\tthis.project = next;\n\t\t\t}\n\t\t}\n\t}\n}\n\nexport class SettingsManager {\n\tprivate storage: SettingsStorage;\n\tprivate globalSettings: Settings;\n\tprivate projectSettings: Settings;\n\tprivate directoryProfileSettings: Settings;\n\tprivate runtimeResourceProfiles: string[] | undefined;\n\tprivate inlineResourceProfileDefinitions: Record<string, ResourceProfileSettings> = {};\n\tprivate discoveredResourceProfileDefinitions: Record<string, ResourceProfileSettings> = {};\n\tprivate settings: Settings;\n\tprivate projectTrusted: boolean;\n\tprivate modifiedFields = new Set<keyof Settings>(); // Track global fields modified during session\n\tprivate modifiedNestedFields = new Map<keyof Settings, Set<string>>(); // Track global nested field modifications\n\tprivate modifiedProjectFields = new Set<keyof Settings>(); // Track project fields modified during session\n\tprivate modifiedProjectNestedFields = new Map<keyof Settings, Set<string>>(); // Track project nested field modifications\n\tprivate globalSettingsLoadError: Error | null = null; // Track if global settings file had parse errors\n\tprivate projectSettingsLoadError: Error | null = null; // Track if project settings file had parse errors\n\tprivate directoryProfileInfo: DirectoryResourceProfileInfo | null = null;\n\tprivate writeQueue: Promise<void> = Promise.resolve();\n\tprivate errors: SettingsError[];\n\n\tprivate constructor(\n\t\tstorage: SettingsStorage,\n\t\tinitialGlobal: Settings,\n\t\tinitialProject: Settings,\n\t\tinitialDirectoryProfile: Settings = {},\n\t\tglobalLoadError: Error | null = null,\n\t\tprojectLoadError: Error | null = null,\n\t\tinitialErrors: SettingsError[] = [],\n\t\tprojectTrusted = true,\n\t\tdirectoryProfileInfo: DirectoryResourceProfileInfo | null = null,\n\t) {\n\t\tthis.storage = storage;\n\t\tthis.globalSettings = initialGlobal;\n\t\tthis.projectSettings = initialProject;\n\t\tthis.directoryProfileSettings = initialDirectoryProfile;\n\t\tthis.projectTrusted = projectTrusted;\n\t\tthis.globalSettingsLoadError = globalLoadError;\n\t\tthis.projectSettingsLoadError = projectLoadError;\n\t\tthis.directoryProfileInfo = directoryProfileInfo;\n\t\tthis.errors = [...initialErrors];\n\t\tthis.settings = this.mergeEffectiveSettings();\n\t}\n\n\tprivate mergeEffectiveSettings(): Settings {\n\t\tlet merged = deepMergeSettings(this.globalSettings, this.projectSettings);\n\t\tmerged = deepMergeSettings(merged, this.directoryProfileSettings);\n\t\tif (this.runtimeResourceProfiles) {\n\t\t\tmerged = deepMergeSettings(merged, { activeResourceProfiles: this.runtimeResourceProfiles });\n\t\t}\n\t\treturn merged;\n\t}\n\n\tprivate recomputeSettings(): void {\n\t\tthis.settings = this.mergeEffectiveSettings();\n\t}\n\n\t/** Create a SettingsManager that loads from files */\n\tstatic create(\n\t\tcwd: string,\n\t\tagentDir: string = getAgentDir(),\n\t\toptions: SettingsManagerCreateOptions = {},\n\t): SettingsManager {\n\t\tconst storage = new FileSettingsStorage(cwd, agentDir);\n\t\treturn SettingsManager.fromStorage(storage, options);\n\t}\n\n\t/** Create a SettingsManager from an arbitrary storage backend */\n\tstatic fromStorage(storage: SettingsStorage, options: SettingsManagerCreateOptions = {}): SettingsManager {\n\t\tconst projectTrusted = options.projectTrusted ?? true;\n\t\tconst globalLoad = SettingsManager.tryLoadFromStorage(storage, \"global\");\n\t\tconst projectLoad = SettingsManager.tryLoadFromStorage(storage, \"project\", projectTrusted);\n\t\tconst directoryProfileLoad = SettingsManager.tryLoadDirectoryProfileFromStorage(storage);\n\t\tconst initialErrors: SettingsError[] = [];\n\t\tif (globalLoad.error) {\n\t\t\tinitialErrors.push({ scope: \"global\", error: globalLoad.error });\n\t\t}\n\t\tif (projectLoad.error) {\n\t\t\tinitialErrors.push({ scope: \"project\", error: projectLoad.error });\n\t\t}\n\t\tif (directoryProfileLoad.error) {\n\t\t\tinitialErrors.push({ scope: \"directoryProfile\", error: directoryProfileLoad.error });\n\t\t}\n\n\t\treturn new SettingsManager(\n\t\t\tstorage,\n\t\t\tglobalLoad.settings,\n\t\t\tprojectLoad.settings,\n\t\t\tdirectoryProfileLoad.settings,\n\t\t\tglobalLoad.error,\n\t\t\tprojectLoad.error,\n\t\t\tinitialErrors,\n\t\t\tprojectTrusted,\n\t\t\tdirectoryProfileLoad.info,\n\t\t);\n\t}\n\n\t/** Create an in-memory SettingsManager (no file I/O) */\n\tstatic inMemory(settings: Partial<Settings> = {}): SettingsManager {\n\t\tconst storage = new InMemorySettingsStorage();\n\t\tconst initialSettings = SettingsManager.migrateSettings(structuredClone(settings) as Record<string, unknown>);\n\t\tstorage.withLock(\"global\", () => JSON.stringify(initialSettings, null, 2));\n\t\treturn SettingsManager.fromStorage(storage);\n\t}\n\n\tprivate static loadFromStorage(storage: SettingsStorage, scope: SettingsScope, projectTrusted = true): Settings {\n\t\tif (scope === \"project\" && !projectTrusted) {\n\t\t\treturn {};\n\t\t}\n\n\t\tlet content: string | undefined;\n\t\tstorage.withLock(scope, (current) => {\n\t\t\tcontent = current;\n\t\t\treturn undefined;\n\t\t});\n\n\t\tif (!content) {\n\t\t\treturn {};\n\t\t}\n\t\tconst settings = JSON.parse(content);\n\t\treturn SettingsManager.migrateSettings(settings);\n\t}\n\n\tprivate static tryLoadFromStorage(\n\t\tstorage: SettingsStorage,\n\t\tscope: SettingsScope,\n\t\tprojectTrusted = true,\n\t): { settings: Settings; error: Error | null } {\n\t\ttry {\n\t\t\treturn { settings: SettingsManager.loadFromStorage(storage, scope, projectTrusted), error: null };\n\t\t} catch (error) {\n\t\t\treturn { settings: {}, error: error as Error };\n\t\t}\n\t}\n\n\tprivate static tryLoadDirectoryProfileFromStorage(storage: SettingsStorage): {\n\t\tsettings: Settings;\n\t\terror: Error | null;\n\t\tinfo: DirectoryResourceProfileInfo | null;\n\t} {\n\t\tif (!(storage instanceof FileSettingsStorage)) {\n\t\t\treturn { settings: {}, error: null, info: null };\n\t\t}\n\t\tconst info = storage.getDirectoryResourceProfileInfo();\n\t\ttry {\n\t\t\tconst content = storage.readDirectoryResourceProfile();\n\t\t\tif (!content) return { settings: {}, error: null, info };\n\t\t\tconst settings = JSON.parse(content);\n\t\t\treturn { settings: SettingsManager.migrateSettings(settings), error: null, info };\n\t\t} catch (error) {\n\t\t\treturn { settings: {}, error: error as Error, info };\n\t\t}\n\t}\n\n\t/** Migrate old settings format to new format */\n\tprivate static migrateSettings(settings: Record<string, unknown>): Settings {\n\t\t// Migrate queueMode -> steeringMode\n\t\tif (\"queueMode\" in settings && !(\"steeringMode\" in settings)) {\n\t\t\tsettings.steeringMode = settings.queueMode;\n\t\t\tdelete settings.queueMode;\n\t\t}\n\n\t\t// Migrate legacy websockets boolean -> transport enum\n\t\tif (!(\"transport\" in settings) && typeof settings.websockets === \"boolean\") {\n\t\t\tsettings.transport = settings.websockets ? \"websocket\" : \"sse\";\n\t\t\tdelete settings.websockets;\n\t\t}\n\n\t\t// Migrate old skills object format to new array format\n\t\tif (\n\t\t\t\"skills\" in settings &&\n\t\t\ttypeof settings.skills === \"object\" &&\n\t\t\tsettings.skills !== null &&\n\t\t\t!Array.isArray(settings.skills)\n\t\t) {\n\t\t\tconst skillsSettings = settings.skills as {\n\t\t\t\tenableSkillCommands?: boolean;\n\t\t\t\tcustomDirectories?: unknown;\n\t\t\t};\n\t\t\tif (skillsSettings.enableSkillCommands !== undefined && settings.enableSkillCommands === undefined) {\n\t\t\t\tsettings.enableSkillCommands = skillsSettings.enableSkillCommands;\n\t\t\t}\n\t\t\tif (Array.isArray(skillsSettings.customDirectories) && skillsSettings.customDirectories.length > 0) {\n\t\t\t\tsettings.skills = skillsSettings.customDirectories;\n\t\t\t} else {\n\t\t\t\tdelete settings.skills;\n\t\t\t}\n\t\t}\n\n\t\t// Migrate retry.maxDelayMs -> retry.provider.maxRetryDelayMs\n\t\tif (\n\t\t\t\"retry\" in settings &&\n\t\t\ttypeof settings.retry === \"object\" &&\n\t\t\tsettings.retry !== null &&\n\t\t\t!Array.isArray(settings.retry)\n\t\t) {\n\t\t\tconst retrySettings = settings.retry as Record<string, unknown>;\n\t\t\tconst providerSettings =\n\t\t\t\ttypeof retrySettings.provider === \"object\" && retrySettings.provider !== null\n\t\t\t\t\t? (retrySettings.provider as Record<string, unknown>)\n\t\t\t\t\t: undefined;\n\t\t\tif (\n\t\t\t\ttypeof retrySettings.maxDelayMs === \"number\" &&\n\t\t\t\t(providerSettings?.maxRetryDelayMs === undefined || providerSettings?.maxRetryDelayMs === null)\n\t\t\t) {\n\t\t\t\tretrySettings.provider = {\n\t\t\t\t\t...(providerSettings ?? {}),\n\t\t\t\t\tmaxRetryDelayMs: retrySettings.maxDelayMs,\n\t\t\t\t};\n\t\t\t}\n\t\t\tdelete retrySettings.maxDelayMs;\n\t\t}\n\n\t\treturn settings as Settings;\n\t}\n\n\tgetGlobalSettings(): Settings {\n\t\treturn structuredClone(this.globalSettings);\n\t}\n\n\tgetProjectSettings(): Settings {\n\t\treturn structuredClone(this.projectSettings);\n\t}\n\n\tgetDirectoryResourceProfileSettings(): Settings {\n\t\treturn structuredClone(this.directoryProfileSettings);\n\t}\n\n\tgetDirectoryResourceProfileInfo(): DirectoryResourceProfileInfo | null {\n\t\treturn this.directoryProfileInfo ? { ...this.directoryProfileInfo } : null;\n\t}\n\n\tgetActiveResourceProfileNames(): string[] {\n\t\tif (this.runtimeResourceProfiles && this.runtimeResourceProfiles.length > 0) {\n\t\t\treturn [...this.runtimeResourceProfiles];\n\t\t}\n\t\treturn normalizeActiveResourceProfiles(this.settings);\n\t}\n\n\tgetResourceProfileFilter(kind: ResourceProfileKind): Required<ResourceProfileFilterSettings> {\n\t\tconst legacyFilter = mergeResourceProfileFilters(\n\t\t\tcollectLegacyDisabledFilterFromSettings(this.globalSettings, kind),\n\t\t\tcollectLegacyDisabledFilterFromSettings(this.projectSettings, kind),\n\t\t\tcollectLegacyDisabledFilterFromSettings(this.directoryProfileSettings, kind),\n\t\t);\n\t\tconst activeProfiles = this.getActiveResourceProfileNames();\n\t\tconst profileFilter = mergeResourceProfileFilters(\n\t\t\tcollectNamedResourceProfileFilters(this.globalSettings, kind, activeProfiles),\n\t\t\tcollectNamedResourceProfileFilters(this.projectSettings, kind, activeProfiles),\n\t\t\tcollectNamedResourceProfileFilters(this.directoryProfileSettings, kind, activeProfiles),\n\t\t\tcollectNamedResourceProfileFilters(\n\t\t\t\t{ resourceProfiles: this.inlineResourceProfileDefinitions },\n\t\t\t\tkind,\n\t\t\t\tactiveProfiles,\n\t\t\t),\n\t\t\tcollectNamedResourceProfileFilters(\n\t\t\t\t{ resourceProfiles: this.discoveredResourceProfileDefinitions },\n\t\t\t\tkind,\n\t\t\t\tactiveProfiles,\n\t\t\t),\n\t\t);\n\t\tconst filter = mergeResourceProfileFilters(legacyFilter, profileFilter);\n\t\treturn {\n\t\t\tallow: [...new Set(filter.allow ?? [])],\n\t\t\tblock: [...new Set(filter.block ?? [])],\n\t\t};\n\t}\n\n\tisResourceAllowedByProfile(kind: ResourceProfileKind, resourcePath: string, baseDir = \"\"): boolean {\n\t\tconst filter = this.getResourceProfileFilter(kind);\n\t\tif (filter.allow.length > 0 && !matchesResourceProfilePattern(resourcePath, filter.allow, baseDir)) {\n\t\t\treturn false;\n\t\t}\n\t\tif (matchesResourceProfilePattern(resourcePath, filter.block, baseDir)) {\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\n\tisProjectTrusted(): boolean {\n\t\treturn this.projectTrusted;\n\t}\n\n\tsetProjectTrusted(trusted: boolean): void {\n\t\tif (this.projectTrusted === trusted) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.projectTrusted = trusted;\n\t\tthis.modifiedProjectFields.clear();\n\t\tthis.modifiedProjectNestedFields.clear();\n\n\t\tif (!trusted) {\n\t\t\tthis.projectSettings = {};\n\t\t\tthis.projectSettingsLoadError = null;\n\t\t\tthis.recomputeSettings();\n\t\t\treturn;\n\t\t}\n\n\t\tconst projectLoad = SettingsManager.tryLoadFromStorage(this.storage, \"project\", trusted);\n\t\tthis.projectSettings = projectLoad.settings;\n\t\tthis.projectSettingsLoadError = projectLoad.error;\n\t\tif (projectLoad.error) {\n\t\t\tthis.recordError(\"project\", projectLoad.error);\n\t\t}\n\t\tthis.recomputeSettings();\n\t}\n\n\tasync reload(): Promise<void> {\n\t\tawait this.writeQueue;\n\t\tconst globalLoad = SettingsManager.tryLoadFromStorage(this.storage, \"global\");\n\t\tif (!globalLoad.error) {\n\t\t\tthis.globalSettings = globalLoad.settings;\n\t\t\tthis.globalSettingsLoadError = null;\n\t\t} else {\n\t\t\tthis.globalSettingsLoadError = globalLoad.error;\n\t\t\tthis.recordError(\"global\", globalLoad.error);\n\t\t}\n\n\t\tthis.modifiedFields.clear();\n\t\tthis.modifiedNestedFields.clear();\n\t\tthis.modifiedProjectFields.clear();\n\t\tthis.modifiedProjectNestedFields.clear();\n\n\t\tconst projectLoad = SettingsManager.tryLoadFromStorage(this.storage, \"project\", this.projectTrusted);\n\t\tif (!projectLoad.error) {\n\t\t\tthis.projectSettings = projectLoad.settings;\n\t\t\tthis.projectSettingsLoadError = null;\n\t\t} else {\n\t\t\tthis.projectSettingsLoadError = projectLoad.error;\n\t\t\tthis.recordError(\"project\", projectLoad.error);\n\t\t}\n\n\t\tconst directoryProfileLoad = SettingsManager.tryLoadDirectoryProfileFromStorage(this.storage);\n\t\tthis.directoryProfileInfo = directoryProfileLoad.info;\n\t\tif (!directoryProfileLoad.error) {\n\t\t\tthis.directoryProfileSettings = directoryProfileLoad.settings;\n\t\t} else {\n\t\t\tthis.recordError(\"directoryProfile\", directoryProfileLoad.error);\n\t\t}\n\n\t\tthis.recomputeSettings();\n\t}\n\n\t/** Apply additional overrides on top of current settings */\n\tapplyOverrides(overrides: Partial<Settings>): void {\n\t\tthis.settings = deepMergeSettings(this.settings, overrides);\n\t}\n\n\t/** Select runtime-only resource profiles, e.g. from CLI/subagent launch options. */\n\tsetRuntimeResourceProfiles(profileNames: string[]): void {\n\t\tthis.runtimeResourceProfiles = profileNames.length > 0 ? [...profileNames] : undefined;\n\t\tthis.recomputeSettings();\n\t}\n\n\t/** Add one-shot profile definitions from CLI/SDK/ephemeral agent launch input. Never writes to disk. */\n\taddInlineResourceProfileDefinitions(profiles: Record<string, ResourceProfileSettings>): void {\n\t\tthis.inlineResourceProfileDefinitions = mergeResourceProfileMap(this.inlineResourceProfileDefinitions, profiles);\n\t}\n\n\t/** Replace profile definitions discovered inside loaded resource files. Never writes to disk. */\n\treplaceDiscoveredResourceProfileDefinitions(profiles: Record<string, ResourceProfileSettings>): void {\n\t\tthis.discoveredResourceProfileDefinitions = { ...profiles };\n\t}\n\n\t/** Add profile definitions discovered after resource resolution, e.g. context agent files. Never writes to disk. */\n\taddDiscoveredResourceProfileDefinitions(profiles: Record<string, ResourceProfileSettings>): void {\n\t\tthis.discoveredResourceProfileDefinitions = mergeResourceProfileMap(\n\t\t\tthis.discoveredResourceProfileDefinitions,\n\t\t\tprofiles,\n\t\t);\n\t}\n\n\t/** Mark a global field as modified during this session */\n\tprivate markModified(field: keyof Settings, nestedKey?: string): void {\n\t\tthis.modifiedFields.add(field);\n\t\tif (nestedKey) {\n\t\t\tif (!this.modifiedNestedFields.has(field)) {\n\t\t\t\tthis.modifiedNestedFields.set(field, new Set());\n\t\t\t}\n\t\t\tthis.modifiedNestedFields.get(field)!.add(nestedKey);\n\t\t}\n\t}\n\n\t/** Mark a project field as modified during this session */\n\tprivate markProjectModified(field: keyof Settings, nestedKey?: string): void {\n\t\tthis.modifiedProjectFields.add(field);\n\t\tif (nestedKey) {\n\t\t\tif (!this.modifiedProjectNestedFields.has(field)) {\n\t\t\t\tthis.modifiedProjectNestedFields.set(field, new Set());\n\t\t\t}\n\t\t\tthis.modifiedProjectNestedFields.get(field)!.add(nestedKey);\n\t\t}\n\t}\n\n\tprivate assertProjectTrustedForWrite(): void {\n\t\tif (!this.projectTrusted) {\n\t\t\tthrow new Error(\"Project is not trusted; refusing to write project settings\");\n\t\t}\n\t}\n\n\tprivate recordError(scope: SettingsErrorScope, error: unknown): void {\n\t\tconst normalizedError = error instanceof Error ? error : new Error(String(error));\n\t\tthis.errors.push({ scope, error: normalizedError });\n\t}\n\n\tprivate clearModifiedScope(scope: SettingsScope): void {\n\t\tif (scope === \"global\") {\n\t\t\tthis.modifiedFields.clear();\n\t\t\tthis.modifiedNestedFields.clear();\n\t\t\treturn;\n\t\t}\n\n\t\tthis.modifiedProjectFields.clear();\n\t\tthis.modifiedProjectNestedFields.clear();\n\t}\n\n\tprivate enqueueWrite(scope: SettingsScope, task: () => void): void {\n\t\tthis.writeQueue = this.writeQueue\n\t\t\t.then(() => {\n\t\t\t\tif (scope === \"project\") {\n\t\t\t\t\tthis.assertProjectTrustedForWrite();\n\t\t\t\t}\n\t\t\t\ttask();\n\t\t\t\tthis.clearModifiedScope(scope);\n\t\t\t})\n\t\t\t.catch((error) => {\n\t\t\t\tthis.recordError(scope, error);\n\t\t\t});\n\t}\n\n\tprivate cloneModifiedNestedFields(source: Map<keyof Settings, Set<string>>): Map<keyof Settings, Set<string>> {\n\t\tconst snapshot = new Map<keyof Settings, Set<string>>();\n\t\tfor (const [key, value] of source.entries()) {\n\t\t\tsnapshot.set(key, new Set(value));\n\t\t}\n\t\treturn snapshot;\n\t}\n\n\tprivate persistScopedSettings(\n\t\tscope: SettingsScope,\n\t\tsnapshotSettings: Settings,\n\t\tmodifiedFields: Set<keyof Settings>,\n\t\tmodifiedNestedFields: Map<keyof Settings, Set<string>>,\n\t): void {\n\t\tthis.storage.withLock(scope, (current) => {\n\t\t\tconst currentFileSettings = current\n\t\t\t\t? SettingsManager.migrateSettings(JSON.parse(current) as Record<string, unknown>)\n\t\t\t\t: {};\n\t\t\tconst mergedSettings: Settings = { ...currentFileSettings };\n\t\t\tfor (const field of modifiedFields) {\n\t\t\t\tconst value = snapshotSettings[field];\n\t\t\t\tif (modifiedNestedFields.has(field) && typeof value === \"object\" && value !== null) {\n\t\t\t\t\tconst nestedModified = modifiedNestedFields.get(field)!;\n\t\t\t\t\tconst baseNested = (currentFileSettings[field] as Record<string, unknown>) ?? {};\n\t\t\t\t\tconst inMemoryNested = value as Record<string, unknown>;\n\t\t\t\t\tconst mergedNested = { ...baseNested };\n\t\t\t\t\tfor (const nestedKey of nestedModified) {\n\t\t\t\t\t\tmergedNested[nestedKey] = inMemoryNested[nestedKey];\n\t\t\t\t\t}\n\t\t\t\t\t(mergedSettings as Record<string, unknown>)[field] = mergedNested;\n\t\t\t\t} else {\n\t\t\t\t\t(mergedSettings as Record<string, unknown>)[field] = value;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn JSON.stringify(mergedSettings, null, 2);\n\t\t});\n\t}\n\n\tprivate save(): void {\n\t\tthis.recomputeSettings();\n\n\t\tif (this.globalSettingsLoadError) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst snapshotGlobalSettings = structuredClone(this.globalSettings);\n\t\tconst modifiedFields = new Set(this.modifiedFields);\n\t\tconst modifiedNestedFields = this.cloneModifiedNestedFields(this.modifiedNestedFields);\n\n\t\tthis.enqueueWrite(\"global\", () => {\n\t\t\tthis.persistScopedSettings(\"global\", snapshotGlobalSettings, modifiedFields, modifiedNestedFields);\n\t\t});\n\t}\n\n\tprivate saveProjectSettings(settings: Settings): void {\n\t\tthis.assertProjectTrustedForWrite();\n\t\tthis.projectSettings = structuredClone(settings);\n\t\tthis.recomputeSettings();\n\n\t\tif (this.projectSettingsLoadError) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst snapshotProjectSettings = structuredClone(this.projectSettings);\n\t\tconst modifiedFields = new Set(this.modifiedProjectFields);\n\t\tconst modifiedNestedFields = this.cloneModifiedNestedFields(this.modifiedProjectNestedFields);\n\t\tthis.enqueueWrite(\"project\", () => {\n\t\t\tthis.persistScopedSettings(\"project\", snapshotProjectSettings, modifiedFields, modifiedNestedFields);\n\t\t});\n\t}\n\n\tprivate updateProjectSettings(field: keyof Settings, update: (settings: Settings) => void): void {\n\t\tthis.assertProjectTrustedForWrite();\n\t\tconst projectSettings = structuredClone(this.projectSettings);\n\t\tupdate(projectSettings);\n\t\tthis.markProjectModified(field);\n\t\tthis.saveProjectSettings(projectSettings);\n\t}\n\n\tasync flush(): Promise<void> {\n\t\tawait this.writeQueue;\n\t}\n\n\tdrainErrors(): SettingsError[] {\n\t\tconst drained = [...this.errors];\n\t\tthis.errors = [];\n\t\treturn drained;\n\t}\n\n\tgetLastChangelogVersion(): string | undefined {\n\t\treturn this.settings.lastChangelogVersion;\n\t}\n\n\tsetLastChangelogVersion(version: string): void {\n\t\tthis.globalSettings.lastChangelogVersion = version;\n\t\tthis.markModified(\"lastChangelogVersion\");\n\t\tthis.save();\n\t}\n\n\tgetSessionDir(): string | undefined {\n\t\tconst sessionDir = this.settings.sessionDir;\n\t\treturn sessionDir ? normalizePath(sessionDir) : sessionDir;\n\t}\n\n\tgetDefaultProvider(): string | undefined {\n\t\treturn this.settings.defaultProvider;\n\t}\n\n\tgetDefaultModel(): string | undefined {\n\t\treturn this.settings.defaultModel;\n\t}\n\n\tsetDefaultProvider(provider: string): void {\n\t\tthis.globalSettings.defaultProvider = provider;\n\t\tthis.markModified(\"defaultProvider\");\n\t\tthis.save();\n\t}\n\n\tsetDefaultModel(modelId: string): void {\n\t\tthis.globalSettings.defaultModel = modelId;\n\t\tthis.markModified(\"defaultModel\");\n\t\tthis.save();\n\t}\n\n\tsetDefaultModelAndProvider(provider: string, modelId: string): void {\n\t\tthis.globalSettings.defaultProvider = provider;\n\t\tthis.globalSettings.defaultModel = modelId;\n\t\tthis.markModified(\"defaultProvider\");\n\t\tthis.markModified(\"defaultModel\");\n\t\tthis.save();\n\t}\n\n\tgetSteeringMode(): \"all\" | \"one-at-a-time\" {\n\t\treturn this.settings.steeringMode || \"one-at-a-time\";\n\t}\n\n\tsetSteeringMode(mode: \"all\" | \"one-at-a-time\"): void {\n\t\tthis.globalSettings.steeringMode = mode;\n\t\tthis.markModified(\"steeringMode\");\n\t\tthis.save();\n\t}\n\n\tgetFollowUpMode(): \"all\" | \"one-at-a-time\" {\n\t\treturn this.settings.followUpMode || \"one-at-a-time\";\n\t}\n\n\tsetFollowUpMode(mode: \"all\" | \"one-at-a-time\"): void {\n\t\tthis.globalSettings.followUpMode = mode;\n\t\tthis.markModified(\"followUpMode\");\n\t\tthis.save();\n\t}\n\n\tgetTheme(): string | undefined {\n\t\treturn this.settings.theme;\n\t}\n\n\tsetTheme(theme: string): void {\n\t\tthis.globalSettings.theme = theme;\n\t\tthis.markModified(\"theme\");\n\t\tthis.save();\n\t}\n\n\tgetDefaultThinkingLevel(): \"off\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\" | undefined {\n\t\treturn this.settings.defaultThinkingLevel;\n\t}\n\n\tsetDefaultThinkingLevel(level: \"off\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\"): void {\n\t\tthis.globalSettings.defaultThinkingLevel = level;\n\t\tthis.markModified(\"defaultThinkingLevel\");\n\t\tthis.save();\n\t}\n\n\tgetTransport(): TransportSetting {\n\t\treturn this.settings.transport ?? \"auto\";\n\t}\n\n\tsetTransport(transport: TransportSetting): void {\n\t\tthis.globalSettings.transport = transport;\n\t\tthis.markModified(\"transport\");\n\t\tthis.save();\n\t}\n\n\tgetCompactionEnabled(): boolean {\n\t\treturn this.settings.compaction?.enabled ?? true;\n\t}\n\n\tsetCompactionEnabled(enabled: boolean): void {\n\t\tif (!this.globalSettings.compaction) {\n\t\t\tthis.globalSettings.compaction = {};\n\t\t}\n\t\tthis.globalSettings.compaction.enabled = enabled;\n\t\tthis.markModified(\"compaction\", \"enabled\");\n\t\tthis.save();\n\t}\n\n\tgetCompactionReserveTokens(): number {\n\t\treturn this.settings.compaction?.reserveTokens ?? 16384;\n\t}\n\n\tgetCompactionKeepRecentTokens(): number {\n\t\treturn this.settings.compaction?.keepRecentTokens ?? 20000;\n\t}\n\n\tgetCompactionSettings(): { enabled: boolean; reserveTokens: number; keepRecentTokens: number } {\n\t\treturn {\n\t\t\tenabled: this.getCompactionEnabled(),\n\t\t\treserveTokens: this.getCompactionReserveTokens(),\n\t\t\tkeepRecentTokens: this.getCompactionKeepRecentTokens(),\n\t\t};\n\t}\n\n\tgetContextGcSettings(): {\n\t\tenabled: boolean;\n\t\tpreserveRecentMessages: number;\n\t\tminToolResultChars: number;\n\t\ttools: string[];\n\t\tsemanticMemory: {\n\t\t\tenabled: boolean;\n\t\t\tpreserveRecentPages: number;\n\t\t\tminChars: number;\n\t\t\tmarkers: string[];\n\t\t};\n\t} {\n\t\treturn {\n\t\t\tenabled: this.settings.contextGc?.enabled ?? true,\n\t\t\tpreserveRecentMessages: this.settings.contextGc?.preserveRecentMessages ?? 12,\n\t\t\tminToolResultChars: this.settings.contextGc?.minToolResultChars ?? 2500,\n\t\t\ttools: this.settings.contextGc?.tools ?? [\n\t\t\t\t\"read\",\n\t\t\t\t\"bash\",\n\t\t\t\t\"rg\",\n\t\t\t\t\"grep\",\n\t\t\t\t\"context_headroom_retrieve\",\n\t\t\t\t\"headroom_retrieve\",\n\t\t\t],\n\t\t\tsemanticMemory: {\n\t\t\t\tenabled: this.settings.contextGc?.semanticMemory?.enabled ?? true,\n\t\t\t\tpreserveRecentPages: this.settings.contextGc?.semanticMemory?.preserveRecentPages ?? 2,\n\t\t\t\tminChars: this.settings.contextGc?.semanticMemory?.minChars ?? 1200,\n\t\t\t\tmarkers: this.settings.contextGc?.semanticMemory?.markers ?? [\n\t\t\t\t\t\"<automata_context\",\n\t\t\t\t\t\"<automata_response\",\n\t\t\t\t\t\"<automata_query\",\n\t\t\t\t\t\"<automata_fetch\",\n\t\t\t\t\t\"<memory_lifecycle_audit\",\n\t\t\t\t\t\"<memory_lifecycle_purge\",\n\t\t\t\t\t\"<automata_doctor\",\n\t\t\t\t\t\"<automata_optimizer\",\n\t\t\t\t\t\"<automata_mesh\",\n\t\t\t\t],\n\t\t\t},\n\t\t};\n\t}\n\n\tgetBranchSummarySettings(): { reserveTokens: number; skipPrompt: boolean } {\n\t\treturn {\n\t\t\treserveTokens: this.settings.branchSummary?.reserveTokens ?? 16384,\n\t\t\tskipPrompt: this.settings.branchSummary?.skipPrompt ?? false,\n\t\t};\n\t}\n\n\tgetBranchSummarySkipPrompt(): boolean {\n\t\treturn this.settings.branchSummary?.skipPrompt ?? false;\n\t}\n\n\tgetRetryEnabled(): boolean {\n\t\treturn this.settings.retry?.enabled ?? true;\n\t}\n\n\tsetRetryEnabled(enabled: boolean): void {\n\t\tif (!this.globalSettings.retry) {\n\t\t\tthis.globalSettings.retry = {};\n\t\t}\n\t\tthis.globalSettings.retry.enabled = enabled;\n\t\tthis.markModified(\"retry\", \"enabled\");\n\t\tthis.save();\n\t}\n\n\tgetRetrySettings(): { enabled: boolean; maxRetries: number; baseDelayMs: number } {\n\t\treturn {\n\t\t\tenabled: this.getRetryEnabled(),\n\t\t\tmaxRetries: this.settings.retry?.maxRetries ?? 3,\n\t\t\tbaseDelayMs: this.settings.retry?.baseDelayMs ?? 2000,\n\t\t};\n\t}\n\n\tgetHttpIdleTimeoutMs(): number {\n\t\treturn parseTimeoutSetting(this.settings.httpIdleTimeoutMs, \"httpIdleTimeoutMs\") ?? DEFAULT_HTTP_IDLE_TIMEOUT_MS;\n\t}\n\n\tsetHttpIdleTimeoutMs(timeoutMs: number): void {\n\t\tif (!Number.isFinite(timeoutMs) || timeoutMs < 0) {\n\t\t\tthrow new Error(`Invalid httpIdleTimeoutMs setting: ${String(timeoutMs)}`);\n\t\t}\n\t\tthis.globalSettings.httpIdleTimeoutMs = Math.floor(timeoutMs);\n\t\tthis.markModified(\"httpIdleTimeoutMs\");\n\t\tthis.save();\n\t}\n\n\tgetProviderRetrySettings(): { timeoutMs?: number; maxRetries?: number; maxRetryDelayMs: number } {\n\t\treturn {\n\t\t\ttimeoutMs: this.settings.retry?.provider?.timeoutMs,\n\t\t\tmaxRetries: this.settings.retry?.provider?.maxRetries,\n\t\t\tmaxRetryDelayMs: this.settings.retry?.provider?.maxRetryDelayMs ?? 60000,\n\t\t};\n\t}\n\n\tgetWebSocketConnectTimeoutMs(): number | undefined {\n\t\treturn parseTimeoutSetting(this.settings.websocketConnectTimeoutMs, \"websocketConnectTimeoutMs\");\n\t}\n\n\tgetHideThinkingBlock(): boolean {\n\t\treturn this.settings.hideThinkingBlock ?? false;\n\t}\n\n\tsetHideThinkingBlock(hide: boolean): void {\n\t\tthis.globalSettings.hideThinkingBlock = hide;\n\t\tthis.markModified(\"hideThinkingBlock\");\n\t\tthis.save();\n\t}\n\n\tgetShellPath(): string | undefined {\n\t\treturn this.settings.shellPath;\n\t}\n\n\tsetShellPath(path: string | undefined): void {\n\t\tthis.globalSettings.shellPath = path;\n\t\tthis.markModified(\"shellPath\");\n\t\tthis.save();\n\t}\n\n\tgetQuietStartup(): boolean {\n\t\treturn this.settings.quietStartup ?? false;\n\t}\n\n\tsetQuietStartup(quiet: boolean): void {\n\t\tthis.globalSettings.quietStartup = quiet;\n\t\tthis.markModified(\"quietStartup\");\n\t\tthis.save();\n\t}\n\n\tgetShellCommandPrefix(): string | undefined {\n\t\treturn this.settings.shellCommandPrefix;\n\t}\n\n\tsetShellCommandPrefix(prefix: string | undefined): void {\n\t\tthis.globalSettings.shellCommandPrefix = prefix;\n\t\tthis.markModified(\"shellCommandPrefix\");\n\t\tthis.save();\n\t}\n\n\tgetNpmCommand(): string[] | undefined {\n\t\treturn this.settings.npmCommand ? [...this.settings.npmCommand] : undefined;\n\t}\n\n\tsetNpmCommand(command: string[] | undefined): void {\n\t\tthis.globalSettings.npmCommand = command ? [...command] : undefined;\n\t\tthis.markModified(\"npmCommand\");\n\t\tthis.save();\n\t}\n\n\tgetCollapseChangelog(): boolean {\n\t\treturn this.settings.collapseChangelog ?? false;\n\t}\n\n\tsetCollapseChangelog(collapse: boolean): void {\n\t\tthis.globalSettings.collapseChangelog = collapse;\n\t\tthis.markModified(\"collapseChangelog\");\n\t\tthis.save();\n\t}\n\n\tgetEnableInstallTelemetry(): boolean {\n\t\treturn this.settings.enableInstallTelemetry ?? true;\n\t}\n\n\tsetEnableInstallTelemetry(enabled: boolean): void {\n\t\tthis.globalSettings.enableInstallTelemetry = enabled;\n\t\tthis.markModified(\"enableInstallTelemetry\");\n\t\tthis.save();\n\t}\n\n\tgetPackages(): PackageSource[] {\n\t\treturn [...(this.settings.packages ?? [])];\n\t}\n\n\tsetPackages(packages: PackageSource[]): void {\n\t\tthis.globalSettings.packages = packages;\n\t\tthis.markModified(\"packages\");\n\t\tthis.save();\n\t}\n\n\tsetProjectPackages(packages: PackageSource[]): void {\n\t\tthis.updateProjectSettings(\"packages\", (settings) => {\n\t\t\tsettings.packages = packages;\n\t\t});\n\t}\n\n\tgetExtensionPaths(): string[] {\n\t\treturn [...(this.settings.extensions ?? [])];\n\t}\n\n\tsetExtensionPaths(paths: string[]): void {\n\t\tthis.globalSettings.extensions = paths;\n\t\tthis.markModified(\"extensions\");\n\t\tthis.save();\n\t}\n\n\tsetProjectExtensionPaths(paths: string[]): void {\n\t\tthis.updateProjectSettings(\"extensions\", (settings) => {\n\t\t\tsettings.extensions = paths;\n\t\t});\n\t}\n\n\tgetSkillPaths(): string[] {\n\t\treturn [...(this.settings.skills ?? [])];\n\t}\n\n\tsetSkillPaths(paths: string[]): void {\n\t\tthis.globalSettings.skills = paths;\n\t\tthis.markModified(\"skills\");\n\t\tthis.save();\n\t}\n\n\tsetProjectSkillPaths(paths: string[]): void {\n\t\tthis.updateProjectSettings(\"skills\", (settings) => {\n\t\t\tsettings.skills = paths;\n\t\t});\n\t}\n\n\tgetPromptTemplatePaths(): string[] {\n\t\treturn [...(this.settings.prompts ?? [])];\n\t}\n\n\tsetPromptTemplatePaths(paths: string[]): void {\n\t\tthis.globalSettings.prompts = paths;\n\t\tthis.markModified(\"prompts\");\n\t\tthis.save();\n\t}\n\n\tsetProjectPromptTemplatePaths(paths: string[]): void {\n\t\tthis.updateProjectSettings(\"prompts\", (settings) => {\n\t\t\tsettings.prompts = paths;\n\t\t});\n\t}\n\n\tgetThemePaths(): string[] {\n\t\treturn [...(this.settings.themes ?? [])];\n\t}\n\n\tsetThemePaths(paths: string[]): void {\n\t\tthis.globalSettings.themes = paths;\n\t\tthis.markModified(\"themes\");\n\t\tthis.save();\n\t}\n\n\tsetProjectThemePaths(paths: string[]): void {\n\t\tthis.updateProjectSettings(\"themes\", (settings) => {\n\t\t\tsettings.themes = paths;\n\t\t});\n\t}\n\n\tgetEnableSkillCommands(): boolean {\n\t\treturn this.settings.enableSkillCommands ?? true;\n\t}\n\n\tsetEnableSkillCommands(enabled: boolean): void {\n\t\tthis.globalSettings.enableSkillCommands = enabled;\n\t\tthis.markModified(\"enableSkillCommands\");\n\t\tthis.save();\n\t}\n\n\tgetThinkingBudgets(): ThinkingBudgetsSettings | undefined {\n\t\treturn this.settings.thinkingBudgets;\n\t}\n\n\tgetShowImages(): boolean {\n\t\treturn this.settings.terminal?.showImages ?? true;\n\t}\n\n\tsetShowImages(show: boolean): void {\n\t\tif (!this.globalSettings.terminal) {\n\t\t\tthis.globalSettings.terminal = {};\n\t\t}\n\t\tthis.globalSettings.terminal.showImages = show;\n\t\tthis.markModified(\"terminal\", \"showImages\");\n\t\tthis.save();\n\t}\n\n\tgetImageWidthCells(): number {\n\t\tconst width = this.settings.terminal?.imageWidthCells;\n\t\tif (typeof width !== \"number\" || !Number.isFinite(width)) {\n\t\t\treturn 60;\n\t\t}\n\t\treturn Math.max(1, Math.floor(width));\n\t}\n\n\tsetImageWidthCells(width: number): void {\n\t\tif (!this.globalSettings.terminal) {\n\t\t\tthis.globalSettings.terminal = {};\n\t\t}\n\t\tthis.globalSettings.terminal.imageWidthCells = Math.max(1, Math.floor(width));\n\t\tthis.markModified(\"terminal\", \"imageWidthCells\");\n\t\tthis.save();\n\t}\n\n\tgetClearOnShrink(): boolean {\n\t\t// Settings takes precedence, then env var, then default false\n\t\tif (this.settings.terminal?.clearOnShrink !== undefined) {\n\t\t\treturn this.settings.terminal.clearOnShrink;\n\t\t}\n\t\treturn process.env.PI_CLEAR_ON_SHRINK === \"1\";\n\t}\n\n\tsetClearOnShrink(enabled: boolean): void {\n\t\tif (!this.globalSettings.terminal) {\n\t\t\tthis.globalSettings.terminal = {};\n\t\t}\n\t\tthis.globalSettings.terminal.clearOnShrink = enabled;\n\t\tthis.markModified(\"terminal\", \"clearOnShrink\");\n\t\tthis.save();\n\t}\n\n\tgetShowTerminalProgress(): boolean {\n\t\treturn this.settings.terminal?.showTerminalProgress ?? false;\n\t}\n\n\tsetShowTerminalProgress(enabled: boolean): void {\n\t\tif (!this.globalSettings.terminal) {\n\t\t\tthis.globalSettings.terminal = {};\n\t\t}\n\t\tthis.globalSettings.terminal.showTerminalProgress = enabled;\n\t\tthis.markModified(\"terminal\", \"showTerminalProgress\");\n\t\tthis.save();\n\t}\n\n\tgetImageAutoResize(): boolean {\n\t\treturn this.settings.images?.autoResize ?? true;\n\t}\n\n\tsetImageAutoResize(enabled: boolean): void {\n\t\tif (!this.globalSettings.images) {\n\t\t\tthis.globalSettings.images = {};\n\t\t}\n\t\tthis.globalSettings.images.autoResize = enabled;\n\t\tthis.markModified(\"images\", \"autoResize\");\n\t\tthis.save();\n\t}\n\n\tgetBlockImages(): boolean {\n\t\treturn this.settings.images?.blockImages ?? false;\n\t}\n\n\tsetBlockImages(blocked: boolean): void {\n\t\tif (!this.globalSettings.images) {\n\t\t\tthis.globalSettings.images = {};\n\t\t}\n\t\tthis.globalSettings.images.blockImages = blocked;\n\t\tthis.markModified(\"images\", \"blockImages\");\n\t\tthis.save();\n\t}\n\n\tgetEnabledModels(): string[] | undefined {\n\t\treturn this.settings.enabledModels;\n\t}\n\n\tsetEnabledModels(patterns: string[] | undefined): void {\n\t\tthis.globalSettings.enabledModels = patterns;\n\t\tthis.markModified(\"enabledModels\");\n\t\tthis.save();\n\t}\n\n\tgetDoubleEscapeAction(): \"fork\" | \"tree\" | \"none\" {\n\t\treturn this.settings.doubleEscapeAction ?? \"tree\";\n\t}\n\n\tsetDoubleEscapeAction(action: \"fork\" | \"tree\" | \"none\"): void {\n\t\tthis.globalSettings.doubleEscapeAction = action;\n\t\tthis.markModified(\"doubleEscapeAction\");\n\t\tthis.save();\n\t}\n\n\tgetTreeFilterMode(): \"default\" | \"no-tools\" | \"user-only\" | \"labeled-only\" | \"all\" {\n\t\tconst mode = this.settings.treeFilterMode;\n\t\tconst valid = [\"default\", \"no-tools\", \"user-only\", \"labeled-only\", \"all\"];\n\t\treturn mode && valid.includes(mode) ? mode : \"default\";\n\t}\n\n\tsetTreeFilterMode(mode: \"default\" | \"no-tools\" | \"user-only\" | \"labeled-only\" | \"all\"): void {\n\t\tthis.globalSettings.treeFilterMode = mode;\n\t\tthis.markModified(\"treeFilterMode\");\n\t\tthis.save();\n\t}\n\n\tgetShowHardwareCursor(): boolean {\n\t\treturn this.settings.showHardwareCursor ?? process.env.PI_HARDWARE_CURSOR === \"1\";\n\t}\n\n\tsetShowHardwareCursor(enabled: boolean): void {\n\t\tthis.globalSettings.showHardwareCursor = enabled;\n\t\tthis.markModified(\"showHardwareCursor\");\n\t\tthis.save();\n\t}\n\n\tgetEditorPaddingX(): number {\n\t\treturn this.settings.editorPaddingX ?? 0;\n\t}\n\n\tsetEditorPaddingX(padding: number): void {\n\t\tthis.globalSettings.editorPaddingX = Math.max(0, Math.min(3, Math.floor(padding)));\n\t\tthis.markModified(\"editorPaddingX\");\n\t\tthis.save();\n\t}\n\n\tgetAutocompleteMaxVisible(): number {\n\t\treturn this.settings.autocompleteMaxVisible ?? 5;\n\t}\n\n\tsetAutocompleteMaxVisible(maxVisible: number): void {\n\t\tthis.globalSettings.autocompleteMaxVisible = Math.max(3, Math.min(20, Math.floor(maxVisible)));\n\t\tthis.markModified(\"autocompleteMaxVisible\");\n\t\tthis.save();\n\t}\n\n\tgetCodeBlockIndent(): string {\n\t\treturn this.settings.markdown?.codeBlockIndent ?? \" \";\n\t}\n\n\tgetWarnings(): WarningSettings {\n\t\treturn { ...(this.settings.warnings ?? {}) };\n\t}\n\n\tsetWarnings(warnings: WarningSettings): void {\n\t\tthis.globalSettings.warnings = { ...warnings };\n\t\tthis.markModified(\"warnings\");\n\t\tthis.save();\n\t}\n\n\tgetSelfModificationSettings(): { enabled: boolean; sourcePath?: string } {\n\t\treturn {\n\t\t\tenabled: this.settings.selfModification?.enabled ?? false,\n\t\t\tsourcePath: this.settings.selfModification?.sourcePath,\n\t\t};\n\t}\n\n\tsetSelfModificationSettings(settings: SelfModificationSettings, scope: SettingsScope = \"global\"): void {\n\t\tif (scope === \"project\") {\n\t\t\tconst projectSettings = structuredClone(this.projectSettings);\n\t\t\tprojectSettings.selfModification = { ...settings };\n\t\t\tthis.markProjectModified(\"selfModification\");\n\t\t\tthis.saveProjectSettings(projectSettings);\n\t\t\treturn;\n\t\t}\n\n\t\tthis.globalSettings.selfModification = { ...settings };\n\t\tthis.markModified(\"selfModification\");\n\t\tthis.save();\n\t}\n\n\tgetAutonomySettings(): { mode: AutonomyMode } {\n\t\tconst mode = this.settings.autonomy?.mode;\n\t\treturn { mode: mode === \"safe\" || mode === \"balanced\" || mode === \"full\" ? mode : \"off\" };\n\t}\n\n\tsetAutonomySettings(settings: AutonomySettings, scope: SettingsScope = \"global\"): void {\n\t\tif (scope === \"project\") {\n\t\t\tconst projectSettings = structuredClone(this.projectSettings);\n\t\t\tprojectSettings.autonomy = { ...settings };\n\t\t\tthis.markProjectModified(\"autonomy\");\n\t\t\tthis.saveProjectSettings(projectSettings);\n\t\t\treturn;\n\t\t}\n\n\t\tthis.globalSettings.autonomy = { ...settings };\n\t\tthis.markModified(\"autonomy\");\n\t\tthis.save();\n\t}\n\n\tgetAutoLearnSettings(): AutoLearnSettings {\n\t\treturn { ...(this.settings.autoLearn ?? {}) };\n\t}\n\n\tsetAutoLearnSettings(settings: AutoLearnSettings, scope: SettingsScope = \"global\"): void {\n\t\tif (scope === \"project\") {\n\t\t\tconst projectSettings = structuredClone(this.projectSettings);\n\t\t\tprojectSettings.autoLearn = { ...settings };\n\t\t\tthis.markProjectModified(\"autoLearn\");\n\t\t\tthis.saveProjectSettings(projectSettings);\n\t\t\treturn;\n\t\t}\n\n\t\tthis.globalSettings.autoLearn = { ...settings };\n\t\tthis.markModified(\"autoLearn\");\n\t\tthis.save();\n\t}\n}\n"]}