@causyne/agent 1.20.124 → 1.20.128

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 (254) hide show
  1. package/bin/causyne.js +1 -1
  2. package/docs/THIRD_PARTY_NOTICES.md +36 -2
  3. package/package.json +6 -4
  4. package/src/acp/protocol.ts +19 -1
  5. package/src/acp/server.js +282 -8
  6. package/src/acp/server.ts +284 -8
  7. package/src/agent/abortableDelay.js +2 -2
  8. package/src/agent/abortableDelay.ts +2 -2
  9. package/src/agent/errorClassifier.js +9 -1
  10. package/src/agent/errorClassifier.ts +8 -1
  11. package/src/agentLoop.js +142 -53
  12. package/src/agentLoop.ts +151 -50
  13. package/src/approvalPolicy.js +34 -10
  14. package/src/approvalPolicy.ts +42 -11
  15. package/src/browser/causyneBrowser.js +61 -3
  16. package/src/browser/causyneBrowser.ts +65 -3
  17. package/src/browser/urlPolicy.js +14 -1
  18. package/src/browser/urlPolicy.ts +12 -1
  19. package/src/cliMode.js +21 -9
  20. package/src/cliMode.ts +20 -8
  21. package/src/commands.js +365 -45
  22. package/src/commands.ts +403 -45
  23. package/src/config.js +19 -4
  24. package/src/config.ts +18 -4
  25. package/src/core/contextCompactor.js +54 -7
  26. package/src/core/contextCompactor.ts +63 -7
  27. package/src/core/goalLoop.js +257 -0
  28. package/src/core/goalLoop.ts +310 -0
  29. package/src/entrypoint.js +135 -3
  30. package/src/entrypoint.ts +136 -3
  31. package/src/game/causyneCoreBridge.js +686 -0
  32. package/src/game/causyneCoreBridge.ts +702 -0
  33. package/src/game/gameLauncher.js +287 -0
  34. package/src/game/gameLauncher.ts +352 -0
  35. package/src/game/gameProvisioner.js +425 -0
  36. package/src/game/gameProvisioner.ts +488 -0
  37. package/src/headlessCli.js +19 -12
  38. package/src/headlessCli.ts +22 -8
  39. package/src/infra/atomicWriter.js +40 -4
  40. package/src/infra/atomicWriter.ts +36 -4
  41. package/src/launchIntent.js +73 -3
  42. package/src/launchIntent.ts +76 -3
  43. package/src/lsp/lspClient.js +83 -12
  44. package/src/lsp/lspClient.ts +75 -12
  45. package/src/mcp/mcpRegistry.js +75 -8
  46. package/src/mcp/mcpRegistry.ts +70 -7
  47. package/src/memory/contextBudget.js +2 -0
  48. package/src/memory/contextBudget.ts +1 -0
  49. package/src/memory/episodicStore.js +40 -0
  50. package/src/memory/episodicStore.ts +46 -0
  51. package/src/memory.js +67 -0
  52. package/src/memory.ts +65 -0
  53. package/src/modelVariants.js +45 -0
  54. package/src/modelVariants.ts +54 -0
  55. package/src/outputRecovery.js +3 -2
  56. package/src/outputRecovery.ts +4 -2
  57. package/src/permissionPresets.js +327 -0
  58. package/src/permissionPresets.ts +361 -0
  59. package/src/personalization.js +365 -0
  60. package/src/personalization.ts +471 -0
  61. package/src/projectInstructions.js +30 -10
  62. package/src/projectInstructions.ts +31 -12
  63. package/src/providers/acp.js +3 -2
  64. package/src/providers/acp.ts +3 -2
  65. package/src/providers/antigravity.js +64 -9
  66. package/src/providers/antigravity.ts +75 -9
  67. package/src/providers/byokHttp.js +7 -1
  68. package/src/providers/byokHttp.ts +6 -1
  69. package/src/providers/byokStream.js +21 -8
  70. package/src/providers/byokStream.ts +17 -7
  71. package/src/providers/dashscope-byok.js +21 -5
  72. package/src/providers/dashscope-byok.ts +29 -11
  73. package/src/providers/moonshot.js +26 -7
  74. package/src/providers/moonshot.ts +34 -13
  75. package/src/providers/muse.js +6 -0
  76. package/src/providers/muse.ts +8 -0
  77. package/src/providers/ollama.js +39 -7
  78. package/src/providers/ollama.ts +36 -7
  79. package/src/providers/openai-compatible.js +16 -3
  80. package/src/providers/openai-compatible.ts +13 -3
  81. package/src/providers/openai.js +62 -4
  82. package/src/providers/openai.ts +50 -4
  83. package/src/providers/openrouter.js +19 -4
  84. package/src/providers/openrouter.ts +21 -4
  85. package/src/providers/qwen-byok.js +21 -5
  86. package/src/providers/qwen-byok.ts +29 -11
  87. package/src/providers/xai.js +26 -10
  88. package/src/providers/xai.ts +34 -16
  89. package/src/reporting.js +4 -2
  90. package/src/reporting.ts +4 -2
  91. package/src/sandbox.js +34 -0
  92. package/src/sandbox.ts +43 -0
  93. package/src/scheduler/scheduler.js +372 -0
  94. package/src/scheduler/scheduler.ts +433 -0
  95. package/src/sessionSearchIndex.js +267 -0
  96. package/src/sessionSearchIndex.ts +311 -0
  97. package/src/skillsManager.js +2 -3
  98. package/src/skillsManager.ts +2 -3
  99. package/src/toolPacks.js +6 -0
  100. package/src/toolPacks.ts +6 -0
  101. package/src/tools/applyPatch.js +1 -1
  102. package/src/tools/applyPatch.ts +1 -1
  103. package/src/tools/generateMediaViaApi.js +4 -3
  104. package/src/tools/generateMediaViaApi.ts +4 -3
  105. package/src/tools/memoryWrite.js +15 -1
  106. package/src/tools/memoryWrite.ts +16 -1
  107. package/src/tools/nativeEngine.js +2 -2
  108. package/src/tools/nativeEngine.ts +2 -2
  109. package/src/tools/openSourceToolProvisioner.js +2 -2
  110. package/src/tools/openSourceToolProvisioner.ts +2 -2
  111. package/src/tools/osSandbox.js +1 -1
  112. package/src/tools/osSandbox.ts +1 -1
  113. package/src/tools/payloadSanitizer.js +0 -1
  114. package/src/tools/payloadSanitizer.ts +0 -1
  115. package/src/tools/pdfReader.js +122 -20
  116. package/src/tools/pdfReader.ts +111 -20
  117. package/src/tools/presentDeliverable.js +103 -0
  118. package/src/tools/presentDeliverable.ts +127 -0
  119. package/src/tools/ptcRuntime.js +444 -0
  120. package/src/tools/ptcRuntime.ts +490 -0
  121. package/src/tools/ptyTerminal.js +1108 -0
  122. package/src/tools/ptyTerminal.ts +1245 -0
  123. package/src/tools/registry.js +21 -12
  124. package/src/tools/registry.ts +21 -12
  125. package/src/tools/toolOutputStore.js +26 -4
  126. package/src/tools/toolOutputStore.ts +22 -4
  127. package/src/tools/webFetch.js +158 -11
  128. package/src/tools/webFetch.ts +145 -11
  129. package/src/tools/webSearch.js +123 -36
  130. package/src/tools/webSearch.ts +124 -33
  131. package/src/tui/banner.js +5 -1
  132. package/src/tui/banner.ts +6 -1
  133. package/src/tui/chatRenderer.js +1 -2
  134. package/src/tui/chatRenderer.ts +1 -2
  135. package/src/tui/completion.js +1 -0
  136. package/src/tui/completion.ts +1 -0
  137. package/src/tui/composerControls.js +111 -27
  138. package/src/tui/composerControls.ts +124 -28
  139. package/src/tui/dialogs.js +3 -16
  140. package/src/tui/dialogs.ts +3 -16
  141. package/src/tui/home.js +1 -0
  142. package/src/tui/home.ts +1 -0
  143. package/src/tui/invocation.js +1 -2
  144. package/src/tui/invocation.ts +1 -2
  145. package/src/tui/modelPicker.js +22 -12
  146. package/src/tui/modelPicker.ts +22 -12
  147. package/src/tui/overlay.js +2 -5
  148. package/src/tui/overlay.ts +2 -5
  149. package/src/tui/prompt.js +6 -4
  150. package/src/tui/prompt.ts +6 -4
  151. package/src/tui/selectList.js +4 -12
  152. package/src/tui/selectList.ts +4 -12
  153. package/src/tui/setup.js +22 -9
  154. package/src/tui/setup.ts +26 -9
  155. package/src/tui/statusLine.ts +2 -0
  156. package/src/web/client/browserPanel.js +905 -0
  157. package/src/web/client/browserPanel.ts +872 -0
  158. package/src/web/client/chatStream.js +321 -0
  159. package/src/web/client/chatStream.ts +297 -0
  160. package/src/web/client/cliPanel.js +165 -0
  161. package/src/web/client/cliPanel.ts +171 -0
  162. package/src/web/client/composer.js +204 -0
  163. package/src/web/client/composer.ts +209 -0
  164. package/src/web/client/diffPanel.js +176 -0
  165. package/src/web/client/diffPanel.ts +203 -0
  166. package/src/web/client/dom.js +271 -0
  167. package/src/web/client/dom.ts +272 -0
  168. package/src/web/client/filesAndCanvas.js +233 -0
  169. package/src/web/client/filesAndCanvas.ts +240 -0
  170. package/src/web/client/gameLauncherUi.js +78 -0
  171. package/src/web/client/gameLauncherUi.ts +78 -0
  172. package/src/web/client/main.js +316 -0
  173. package/src/web/client/main.ts +391 -0
  174. package/src/web/client/markdown.js +364 -0
  175. package/src/web/client/markdown.ts +373 -0
  176. package/src/web/client/modelPicker.js +455 -0
  177. package/src/web/client/modelPicker.ts +451 -0
  178. package/src/web/client/permissionPresetsUi.js +307 -0
  179. package/src/web/client/permissionPresetsUi.ts +333 -0
  180. package/src/web/client/sessions.js +353 -0
  181. package/src/web/client/sessions.ts +372 -0
  182. package/src/web/client/settingsModal.js +824 -0
  183. package/src/web/client/settingsModal.ts +959 -0
  184. package/src/web/client/state.js +280 -0
  185. package/src/web/client/state.ts +259 -0
  186. package/src/web/client/streamSmoother.js +127 -0
  187. package/src/web/client/streamSmoother.ts +119 -0
  188. package/src/web/client/studioLayout.js +89 -0
  189. package/src/web/client/studioLayout.ts +103 -0
  190. package/src/web/client/studioShell.js +660 -0
  191. package/src/web/client/studioShell.ts +672 -0
  192. package/src/web/client/studioStart.js +77 -0
  193. package/src/web/client/studioStart.ts +89 -0
  194. package/src/web/client/terminalPanel.js +606 -0
  195. package/src/web/client/terminalPanel.ts +632 -0
  196. package/src/web/client/terminalTheme.js +249 -0
  197. package/src/web/client/terminalTheme.ts +258 -0
  198. package/src/web/client/turnView.js +934 -0
  199. package/src/web/client/turnView.ts +981 -0
  200. package/src/web/client/types.js +1 -0
  201. package/src/web/client/types.ts +322 -0
  202. package/src/web/client/validators.js +147 -0
  203. package/src/web/client/validators.ts +140 -0
  204. package/src/web/server/activeRuns.js +152 -0
  205. package/src/web/server/activeRuns.ts +171 -0
  206. package/src/web/server/routesBrowser.js +409 -0
  207. package/src/web/server/routesBrowser.ts +435 -0
  208. package/src/web/server/routesChat.js +304 -0
  209. package/src/web/server/routesChat.ts +347 -0
  210. package/src/web/server/routesCore.js +472 -0
  211. package/src/web/server/routesCore.ts +522 -0
  212. package/src/web/server/routesSettings.js +344 -0
  213. package/src/web/server/routesSettings.ts +397 -0
  214. package/src/web/server/routesTerminal.js +162 -0
  215. package/src/web/server/routesTerminal.ts +182 -0
  216. package/src/web/server/routesWorkspace.js +510 -0
  217. package/src/web/server/routesWorkspace.ts +546 -0
  218. package/src/web/server/security.js +98 -0
  219. package/src/web/server/security.ts +108 -0
  220. package/src/web/server/sessionTranscript.js +586 -0
  221. package/src/web/server/sessionTranscript.ts +566 -0
  222. package/src/web/server/staticAssets.js +104 -0
  223. package/src/web/server/staticAssets.ts +116 -0
  224. package/src/web/server/types.js +1 -0
  225. package/src/web/server/types.ts +135 -0
  226. package/src/web/server/workspaceFiles.js +368 -0
  227. package/src/web/server/workspaceFiles.ts +363 -0
  228. package/src/web/skybridgeServer.js +78 -2448
  229. package/src/web/skybridgeServer.ts +120 -2600
  230. package/src/web/skybridgeUi.js +20 -450
  231. package/src/web/skybridgeUi.ts +24 -455
  232. package/src/web/styles/agent.css +380 -0
  233. package/src/web/styles/composer.css +193 -0
  234. package/src/web/styles/overlays.css +935 -0
  235. package/src/web/styles/shell.css +387 -0
  236. package/src/web/styles/studio.css +951 -0
  237. package/src/web/styles/thread.css +221 -0
  238. package/src/web/styles/tokens.css +94 -0
  239. package/src/web/ui/brandMark.js +73 -0
  240. package/src/web/ui/brandMark.ts +82 -0
  241. package/src/web/ui/modalsTemplate.js +388 -0
  242. package/src/web/ui/modalsTemplate.ts +388 -0
  243. package/src/web/ui/sidebarTemplate.js +63 -0
  244. package/src/web/ui/sidebarTemplate.ts +64 -0
  245. package/src/web/ui/studioTemplate.js +256 -0
  246. package/src/web/ui/studioTemplate.ts +256 -0
  247. package/src/web/ui/workspaceTemplate.js +72 -0
  248. package/src/web/ui/workspaceTemplate.ts +73 -0
  249. package/src/worktreeManager.js +16 -1
  250. package/src/worktreeManager.ts +22 -1
  251. package/src/web/skybridgeClientScript.js +0 -3951
  252. package/src/web/skybridgeClientScript.ts +0 -3952
  253. package/src/web/skybridgeStyles.js +0 -827
  254. package/src/web/skybridgeStyles.ts +0 -828
package/src/agentLoop.js CHANGED
@@ -49,6 +49,7 @@ import { isWholeFileDeletion, requiresToolApproval, withToolAutonomyMode } from
49
49
  import { evaluateEnterprisePolicy } from './enterprisePolicy.js';
50
50
  import { isZeroCostFailoverEligible, normalizeZeroCostId, selectNextZeroCostRoute } from './zeroCostFailover.js';
51
51
  import { formatProjectInstructionsPrompt, loadProjectInstructions } from './projectInstructions.js';
52
+ import { isExternalToolAssistedToolName, resolveEffectiveMemoryPolicy } from './personalization.js';
52
53
  import { AGENT_USER_POLICY } from './agentPolicy.js';
53
54
  import { VFETracker } from './vfeTracker.js';
54
55
  import { coldObserver } from './observer/coldObserver.js';
@@ -83,6 +84,7 @@ import { StreamingCodePreview, NativeCodeObserver, codeProgressFromAction } from
83
84
  import { StallGuardController } from './stallGuard.js';
84
85
  import { buildRecoverableDroppedSummary, pruneStaleToolObservations, shortenOversizedToolObservations, pruneExecutedToolArguments } from './historyPruner.js';
85
86
  import { isOutputRecoveryRead } from './outputRecovery.js';
87
+ import { autonomyModeToPreset, getPermissionPresetDescriptor, normalizePermissionPreset, presetToAutonomyMode, renderPermissionPolicyContext, resolveConfigPermissionPreset } from './permissionPresets.js';
86
88
  import { isPlanReviewHandoff, isPlanningOnlyRequest } from './taskContinuation.js';
87
89
  export function noncachedTokens(usage) {
88
90
  if (!usage)
@@ -128,6 +130,11 @@ ${PEER_COLLABORATION_POLICY}
128
130
 
129
131
  ${AGENT_USER_POLICY}
130
132
 
133
+ # Personalization & Project Instructions (HIGH-PRIORITY DIRECTIVE)
134
+ - **Treat Project Personalization as a Big Deal**: Developers configure per-project Personalization (\`.causyne/personalization.md\`), repository rules (\`CAUSYNE.md\`, \`AGENTS.md\`, \`.causyne/rules/*.md\`), and global instructions (\`~/.causyne/CAUSYNE.md\`) to encode their project's vision, mission, architectural standards, coding taste, and working comfort.
135
+ - **Strict Obedience Under Core Safety**: Whenever Personalization or Project Instructions are provided in this session, treat them as a **binding high-priority operational contract**. Actively honor every detail—communication style, language, conventions, constraints, and engineering rules—over generic habits or defaults. Only Causyne's Absolute Ethical Safety Net, active permission preset, and workspace/sandbox security boundaries supersede Personalization.
136
+ - **Per-Project Precedence**: Project-scoped Personalization (\`.causyne/personalization.md\`) and repository rules apply specifically to the active project and take precedence over general global preferences if they differ.
137
+
131
138
  # Operational Guidelines & Engineering Discipline
132
139
  - **Language & Communication**: Communicate clearly in the user's language by default unless repository instructions (such as \`AGENTS.md\` or \`CAUSYNE.md\`) specify a required language.
133
140
  - **Conciseness & Output**: Keep replies concise (<4 lines unless detail is requested). No preambles or postambles. Output exact file paths for files created or modified. Answer greetings or pure questions directly without tools.
@@ -136,10 +143,10 @@ ${AGENT_USER_POLICY}
136
143
  - **Code Quality**: Write clear, runnable, idiomatic code following existing project conventions without trivial inline comments or TODO placeholders. Preserve unrelated behavior.
137
144
  - **Planning & Decisions**: Batch independent read-only calls together. Use \`update_plan\` only for genuinely complex multi-stage implementations (keep one step \`in_progress\`). Use \`request_decision\` only when a material architecture/product/security choice genuinely blocks progress.
138
145
  - **Git Commits**: Follow the target repository's commit message conventions and project instructions (such as \`AGENTS.md\` or \`git log\`) when committing changes.
139
- - **Autonomy & Safety Boundaries**:
140
- - **Mode A (Passive)**: Ask permission before mutating files, running shell commands, or installing dependencies.
141
- - **Mode B (Supervised)**: Ordinary dev dependencies allowed; ask before OS-level changes or \`sudo\`.
142
- - **Mode C (Autonomous)**: Execute ordinary in-scope work independently; whole-file/directory deletion, hard policy blocks, and workspace boundaries still require approval/compliance. Avoid interactive shell flags; use non-interactive flags (\`-y\`).
146
+ - **Permission Presets & Safety Boundaries**:
147
+ - **Read Only (\`read-only\`)**: Inspect files, search code, and read documentation only; file modifications and mutating shell commands are blocked.
148
+ - **Workspace Write (\`workspace-write\`)**: Read and edit files scoped to the active workspace; ask approval before dangerous operations, OS-level changes, or \`sudo\`.
149
+ - **Full access (\`danger-full-access\`)**: Execute ordinary in-scope workspace edits and commands directly; whole-file/directory deletion, credential safeguards, hard policy blocks, and workspace boundaries remain enforced. Avoid interactive shell flags; use non-interactive flags (\`-y\`).
143
150
  - **SSRF**: Never fetch cloud metadata (169.254.169.254, metadata.google.internal) or private LAN ranges. Loopback (\`localhost\`, \`127.0.0.1\`, \`::1\`) is permitted for local dev verification.
144
151
  - **Tool Schema Discipline**: Invoke only active Causyne or permitted peer tools using exact schema parameter names and valid JSON (no unescaped newlines or trailing commas). Respect BYOK token limits.
145
152
 
@@ -409,6 +416,9 @@ export class AgentLoop {
409
416
  this.peerMcpServers = Array.isArray(options.peerMcpServers)
410
417
  ? [...options.peerMcpServers]
411
418
  : [];
419
+ this.hostSystemInstructions = typeof options.hostSystemInstructions === 'string' && options.hostSystemInstructions.trim()
420
+ ? options.hostSystemInstructions.trim()
421
+ : null;
412
422
  this.config = loadConfig();
413
423
  applyProviderOverrides(this.config, this.providerOverride, this.modelOverride);
414
424
  if (this.variantOverride) {
@@ -508,6 +518,7 @@ export class AgentLoop {
508
518
  // be recomputed on every single step (cortex retrieval, skills index,
509
519
  // design detection, workspace domain scan).
510
520
  this.staticContext = null;
521
+ this._memoryPollutedByExternalTools = false;
511
522
  this.vfeTracker = new VFETracker();
512
523
  this._lessonSimilarity = 0;
513
524
  this._paradigmShiftPending = false;
@@ -792,7 +803,8 @@ export class AgentLoop {
792
803
  async buildStaticContext() {
793
804
  let lessonsLearned = '';
794
805
  this._lessonSimilarity = 0;
795
- const cortexEnabled = Boolean(this.config?.cortex?.enabled);
806
+ const startupMemoryPolicy = resolveEffectiveMemoryPolicy(this.workspaceRoot);
807
+ const cortexEnabled = Boolean(this.config?.cortex?.enabled) && startupMemoryPolicy.enabled;
796
808
  if (cortexEnabled && this.currentTaskPrompt && isSearchablePrompt(this.currentTaskPrompt)) {
797
809
  try {
798
810
  const matches = await cortexDb.search(this.currentTaskPrompt, 2, { workspace: this.workspaceRoot });
@@ -859,11 +871,13 @@ export class AgentLoop {
859
871
  this.debugLog(`plan cache hint skipped: ${e.message}`);
860
872
  }
861
873
  let episodicContext = '';
862
- try {
863
- episodicContext = episodicStore.buildStartupEpisodicContext(this.workspaceRoot);
864
- }
865
- catch (e) {
866
- this.debugLog(`episodic context build skipped: ${e.message}`);
874
+ if (startupMemoryPolicy.enabled) {
875
+ try {
876
+ episodicContext = episodicStore.buildStartupEpisodicContext(this.workspaceRoot);
877
+ }
878
+ catch (e) {
879
+ this.debugLog(`episodic context build skipped: ${e.message}`);
880
+ }
867
881
  }
868
882
  let projectInstructions = '';
869
883
  try {
@@ -874,6 +888,9 @@ export class AgentLoop {
874
888
  }
875
889
  return { lessonsLearned, designContext, antiRepeatDirective, universalSkillsContext, planHint, episodicContext, projectInstructions };
876
890
  }
891
+ isMemoryPollutedByExternalTools() {
892
+ return Boolean(this._memoryPollutedByExternalTools);
893
+ }
877
894
  rearmAbortController() {
878
895
  this.abortController = new AbortController();
879
896
  }
@@ -909,13 +926,40 @@ export class AgentLoop {
909
926
  }
910
927
  }
911
928
  }
929
+ activePermissionPreset() {
930
+ const fromOverride = normalizePermissionPreset(this.autonomyOverride);
931
+ if (fromOverride)
932
+ return fromOverride;
933
+ return resolveConfigPermissionPreset(this.config, 'danger-full-access');
934
+ }
912
935
  setAutonomyMode(mode) {
913
- const normalized = String(mode || '').trim().toUpperCase();
914
- if (!['A', 'B', 'C'].includes(normalized)) {
915
- throw new Error('autonomy mode must be A, B, or C');
936
+ const preset = normalizePermissionPreset(mode);
937
+ if (!preset) {
938
+ throw new Error('permission preset must be read-only, workspace-write, or danger-full-access (or A, B, C)');
916
939
  }
940
+ const normalized = presetToAutonomyMode(preset);
917
941
  this.autonomyOverride = normalized;
918
942
  this.config.autonomyMode = normalized;
943
+ this.config.permissionPreset = preset;
944
+ if (this.sandbox) {
945
+ this.sandbox.autonomyMode = normalized;
946
+ this.sandbox.permissionPreset = preset;
947
+ }
948
+ }
949
+ setPermissionPreset(rawPreset) {
950
+ const preset = normalizePermissionPreset(rawPreset);
951
+ if (!preset) {
952
+ throw new Error('permission preset must be read-only, workspace-write, or danger-full-access');
953
+ }
954
+ const mode = presetToAutonomyMode(preset);
955
+ this.autonomyOverride = mode;
956
+ this.config.autonomyMode = mode;
957
+ this.config.permissionPreset = preset;
958
+ if (this.sandbox) {
959
+ this.sandbox.autonomyMode = mode;
960
+ this.sandbox.permissionPreset = preset;
961
+ }
962
+ return preset;
919
963
  }
920
964
  /**
921
965
  * A provider for UTILITY work — condensation, classification, filtering.
@@ -987,9 +1031,9 @@ export class AgentLoop {
987
1031
  const prefetched = new Map();
988
1032
  if (!Array.isArray(toolCalls) || toolCalls.length < 2)
989
1033
  return prefetched;
990
- // Mode A promises approval before every tool, including reads. Starting a
1034
+ // Read Only promises approval before every tool, including reads. Starting a
991
1035
  // read here would execute it before the serial approval and hook gates.
992
- if ((this.config.autonomyMode || 'C') === 'A')
1036
+ if (this.activePermissionPreset() === 'read-only')
993
1037
  return prefetched;
994
1038
  const eligible = [];
995
1039
  for (const toolCall of toolCalls) {
@@ -1142,11 +1186,13 @@ export class AgentLoop {
1142
1186
  const assessment = await coldObserver.evaluateMutation(tool, args, { workspaceRoot: this.workspaceRoot });
1143
1187
  if (assessment.veto)
1144
1188
  return false;
1145
- const isModeC = (this.config.autonomyMode || 'C') === 'C';
1189
+ const activePreset = this.activePermissionPreset();
1190
+ const isFullAccess = activePreset === 'danger-full-access';
1146
1191
  const needsApproval = enterpriseDecision.effect === 'ask'
1147
- || (!isModeC && uncertain)
1192
+ || (!isFullAccess && uncertain)
1148
1193
  || requiresToolApproval({
1149
- mode: this.config.autonomyMode || 'C', tool, args,
1194
+ permissionPreset: activePreset,
1195
+ mode: presetToAutonomyMode(activePreset), tool, args,
1150
1196
  risk: assessment.requiresConfirmation ? 'dangerous' : validation.risk,
1151
1197
  heavyDownload: false, standingApproval: this.isAlwaysAllowed(tool)
1152
1198
  });
@@ -1574,8 +1620,22 @@ export class AgentLoop {
1574
1620
  }
1575
1621
  updateTierLimits() {
1576
1622
  this.config = loadConfig();
1577
- if (this.autonomyOverride)
1578
- this.config.autonomyMode = this.autonomyOverride;
1623
+ if (this.autonomyOverride) {
1624
+ const overridePreset = normalizePermissionPreset(this.autonomyOverride);
1625
+ if (overridePreset) {
1626
+ this.config.permissionPreset = overridePreset;
1627
+ this.config.autonomyMode = presetToAutonomyMode(overridePreset);
1628
+ }
1629
+ else {
1630
+ this.config.autonomyMode = this.autonomyOverride;
1631
+ }
1632
+ }
1633
+ const syncedPreset = resolveConfigPermissionPreset(this.config, 'workspace-write');
1634
+ this.config.permissionPreset = syncedPreset;
1635
+ if (this.sandbox) {
1636
+ this.sandbox.permissionPreset = syncedPreset;
1637
+ this.sandbox.autonomyMode = presetToAutonomyMode(syncedPreset);
1638
+ }
1579
1639
  applyProviderOverrides(this.config, this.providerOverride, this.modelOverride);
1580
1640
  if (this.variantOverride) {
1581
1641
  this.config.reasoningEffort = this.variantOverride;
@@ -1794,6 +1854,7 @@ export class AgentLoop {
1794
1854
  this.slopReviewAttempts = 0;
1795
1855
  this.slopLastAuditHash = '';
1796
1856
  this.staticContext = null;
1857
+ this._memoryPollutedByExternalTools = false;
1797
1858
  // Plan cache: the procedure THIS task follows, and the template (if any)
1798
1859
  // that was offered to it. Both reset per task — a plan is a property of one
1799
1860
  // request, not of the session.
@@ -2100,7 +2161,7 @@ export class AgentLoop {
2100
2161
  if (!this.currentTaskPrompt && this.userPrompt) {
2101
2162
  this.currentTaskPrompt = this.userPrompt;
2102
2163
  }
2103
- const isAutonomousMode = (this.config.autonomyMode || 'C') === 'C';
2164
+ const isAutonomousMode = this.activePermissionPreset() === 'danger-full-access';
2104
2165
  const recoveryPaths = new Set();
2105
2166
  let modelCallIndex = 0;
2106
2167
  let softUsageNoticeIssued = false;
@@ -2264,7 +2325,8 @@ export class AgentLoop {
2264
2325
  // All transports receive the same compact catalog and selected host
2265
2326
  // schemas. Peer-native tools and native schema deferral remain provider
2266
2327
  // features; neither changes host authorization or schema selection.
2267
- const eligibleTools = await getDynamicTools(this.config.autonomyMode, this.llm.supportsVision, {
2328
+ const activePreset = this.activePermissionPreset();
2329
+ const eligibleTools = await getDynamicTools(activePreset, this.llm.supportsVision, {
2268
2330
  grantAllTools: true,
2269
2331
  allowedTools: this.sandbox.allowedTools,
2270
2332
  deniedTools: this.config.deniedTools
@@ -2297,7 +2359,8 @@ export class AgentLoop {
2297
2359
  }
2298
2360
  }
2299
2361
  // Dynamically inject the absolute latest System context
2300
- const autonomyMode = this.config.autonomyMode || 'C';
2362
+ const activePresetDesc = getPermissionPresetDescriptor(activePreset);
2363
+ const permissionPolicyLine = renderPermissionPolicyContext(activePreset, this.workspaceRoot);
2301
2364
  const allowedPaths = this.sandbox.grantAllAccess
2302
2365
  ? "/ (ALL ACCESS GRANTED - You can read/write anywhere EXCEPT system protected folders like /etc or /System)"
2303
2366
  : (this.sandbox.workspacePaths ? this.sandbox.workspacePaths.join(', ') : this.workspaceRoot);
@@ -2323,7 +2386,10 @@ Verify Web/UI/3D work programmatically via browser_act (DOM snapshot + runtimeEr
2323
2386
  isVisualOrWebTask ? WEB_VERIFICATION_PROMPT : ''
2324
2387
  ].join('');
2325
2388
  const providerPrompt = `${baseProviderPrompt}${sensoryAwareness}${domainPrompts}`;
2326
- const memoryContext = getMemoryContextString({ workspaceRoot: this.workspaceRoot });
2389
+ const turnMemoryPolicy = resolveEffectiveMemoryPolicy(this.workspaceRoot);
2390
+ const memoryContext = turnMemoryPolicy.enabled
2391
+ ? getMemoryContextString({ workspaceRoot: this.workspaceRoot })
2392
+ : '';
2327
2393
  // --- PER-TASK STATIC CONTEXT (computed once, not once per step) ---
2328
2394
  // Cortex retrieval, design detection, creative-pattern lookup and the
2329
2395
  // workspace domain scan are all constant for the duration of a task, but
@@ -2475,13 +2541,14 @@ Verify Web/UI/3D work programmatically via browser_act (DOM snapshot + runtimeEr
2475
2541
  // time a different skill is invoked. This one is stable for the task,
2476
2542
  // so it anchors too.
2477
2543
  ...(skillSystemMessage(this.activeSkill) || []),
2544
+ ...(this.hostSystemInstructions ? [{ role: 'system', content: this.hostSystemInstructions }] : []),
2478
2545
  // [5] VOLATILE tail — the only bytes that may differ between steps:
2479
2546
  // autonomy/workspace paths (change via config), live shared browser
2480
2547
  // state, and persistent memory (grows via memory_write mid-task).
2481
2548
  // Kept LAST and UNcached so a change here never invalidates [1]-[3].
2482
2549
  {
2483
2550
  role: 'system',
2484
- content: `${uncertaintyDirective ? uncertaintyDirective + '\n\n' : ''}${describeSession(this.taskId)}CURRENT AUTONOMY MODE: ${autonomyMode}\nALLOWED WORKSPACE PATHS: ${allowedPaths}\n(You MUST NOT write files outside these paths!)${sharedBrowserPrompt}${memoryContext ? `\n\n◆ PERSISTENT MEMORY (workspace-relevant notes — actual repository files and docs on disk always override memory if anything conflicts):\n${memoryContext}` : ''}`
2551
+ content: `${uncertaintyDirective ? uncertaintyDirective + '\n\n' : ''}${describeSession(this.taskId)}PERMISSION PRESET: ${activePresetDesc.label} (${activePreset})\n${permissionPolicyLine}\nALLOWED WORKSPACE PATHS: ${allowedPaths}\n(You MUST NOT write files outside these paths!)${sharedBrowserPrompt}${memoryContext ? `\n\n◆ PERSISTENT MEMORY (workspace-relevant notes — actual repository files and docs on disk always override memory if anything conflicts):\n${memoryContext}` : ''}`
2485
2552
  }
2486
2553
  ];
2487
2554
  // Dev-only visibility into what fills each step's prompt. Set
@@ -2766,16 +2833,22 @@ Verify Web/UI/3D work programmatically via browser_act (DOM snapshot + runtimeEr
2766
2833
  ...(isFailed ? { error: action.detail || `${action.name} failed` } : {})
2767
2834
  };
2768
2835
  coldObserver.recordToolOutcome(this.taskId, action.name, actionArgs, actionOutcome);
2836
+ if (isExternalToolAssistedToolName(action.name)) {
2837
+ this._memoryPollutedByExternalTools = true;
2838
+ }
2769
2839
  try {
2770
- const compiledObs = compileToolObservation({
2771
- taskId: this.taskId,
2772
- workspace: this.workspaceRoot,
2773
- toolName: action.name,
2774
- args: actionArgs,
2775
- result: actionOutcome
2776
- });
2777
- if (compiledObs)
2778
- episodicStore.recordObservation(compiledObs);
2840
+ const memPolicy = resolveEffectiveMemoryPolicy(this.workspaceRoot);
2841
+ if (memPolicy.enabled && (memPolicy.allowToolAssisted || !this._memoryPollutedByExternalTools)) {
2842
+ const compiledObs = compileToolObservation({
2843
+ taskId: this.taskId,
2844
+ workspace: this.workspaceRoot,
2845
+ toolName: action.name,
2846
+ args: actionArgs,
2847
+ result: actionOutcome
2848
+ });
2849
+ if (compiledObs)
2850
+ episodicStore.recordObservation(compiledObs);
2851
+ }
2779
2852
  }
2780
2853
  catch { /* never block peer action on episodic recording */ }
2781
2854
  const recovery = this.timeMachine.observe(action.name, actionArgs, actionOutcome, coldObserver.getToolOutcomes(this.taskId));
@@ -3926,9 +3999,13 @@ Verify Web/UI/3D work programmatically via browser_act (DOM snapshot + runtimeEr
3926
3999
  this.debugLog(`plan cache write skipped: ${e.message}`);
3927
4000
  }
3928
4001
  try {
4002
+ const memPolicy = resolveEffectiveMemoryPolicy(this.workspaceRoot);
3929
4003
  const reqText = String(this.currentTaskPrompt || this.userPrompt || '').trim();
3930
4004
  const completedText = String(response.content || 'Completed task execution.').replace(/\s+/g, ' ').trim();
3931
- if (reqText && (this.stepsCompleted > 0 || completedNativeActionIds.size > 0)) {
4005
+ if (memPolicy.enabled
4006
+ && (memPolicy.allowToolAssisted || !this._memoryPollutedByExternalTools)
4007
+ && reqText
4008
+ && (this.stepsCompleted > 0 || completedNativeActionIds.size > 0)) {
3932
4009
  episodicStore.recordSessionSummary({
3933
4010
  taskId: this.taskId,
3934
4011
  workspace: this.workspaceRoot,
@@ -4185,8 +4262,9 @@ Verify Web/UI/3D work programmatically via browser_act (DOM snapshot + runtimeEr
4185
4262
  // 4-Layer Security Sandbox Validation
4186
4263
  // 2. Sandbox Security Validation (CRITICAL FIX: Prevent Infinite Loop on Block)
4187
4264
  let validation = this.sandbox.validate(functionName, args);
4265
+ const recoveryCandidatePath = args.path ?? args.file_path ?? args.target ?? args.dir;
4188
4266
  if (!validation.allowed && /^Path outside allowed workspace:/.test(validation.reason || '')
4189
- && isOutputRecoveryRead(functionName, args.path, recoveryPaths)) {
4267
+ && isOutputRecoveryRead(functionName, recoveryCandidatePath, recoveryPaths)) {
4190
4268
  validation = { allowed: true, risk: 'safe', reason: 'Read exact tool output referenced by this session' };
4191
4269
  }
4192
4270
  if (!validation.allowed) {
@@ -4370,14 +4448,16 @@ Verify Web/UI/3D work programmatically via browser_act (DOM snapshot + runtimeEr
4370
4448
  });
4371
4449
  continue;
4372
4450
  }
4373
- // A standing grant can avoid repeat prompts in supervised modes.
4374
- // Mode C is autonomous for in-scope work. Whole-file deletion asks
4451
+ // A standing grant can avoid repeat prompts in Workspace Write.
4452
+ // Full access runs in-scope work directly. Whole-file deletion asks
4375
4453
  // unless this session explicitly granted the fs_delete tool; a broad
4376
4454
  // shell grant cannot authorize deletion. Sandbox denials and observer
4377
4455
  // vetoes have already run and are never lifted by prompt policy.
4456
+ const stepPreset = this.activePermissionPreset();
4378
4457
  const standingApproval = this.isAlwaysAllowed(functionName);
4379
4458
  let needsToolApproval = requiresToolApproval({
4380
- mode: this.config.autonomyMode || 'C',
4459
+ permissionPreset: stepPreset,
4460
+ mode: presetToAutonomyMode(stepPreset),
4381
4461
  tool: functionName,
4382
4462
  args,
4383
4463
  risk: validation.risk,
@@ -4409,7 +4489,7 @@ Verify Web/UI/3D work programmatically via browser_act (DOM snapshot + runtimeEr
4409
4489
  reason: enterpriseDecision.reason
4410
4490
  });
4411
4491
  }
4412
- if (standingApproval && !needsToolApproval && this.config.autonomyMode !== 'C' && enterpriseDecision.effect !== 'allow') {
4492
+ if (standingApproval && !needsToolApproval && stepPreset !== 'danger-full-access' && enterpriseDecision.effect !== 'allow') {
4413
4493
  auditLog.log({
4414
4494
  event: 'approval_auto_granted', taskId: this.taskId,
4415
4495
  tool: functionName, risk: validation.risk, reason: 'allow_always'
@@ -4602,16 +4682,22 @@ Verify Web/UI/3D work programmatically via browser_act (DOM snapshot + runtimeEr
4602
4682
  ? { success: true, _is_image_marker: true, visionDelivered: imageCanReachModel, filename: result.filename, mimeType: result.mimeType }
4603
4683
  : result;
4604
4684
  coldObserver.recordToolOutcome(this.taskId, functionName, args, observedResult);
4685
+ if (isExternalToolAssistedToolName(functionName)) {
4686
+ this._memoryPollutedByExternalTools = true;
4687
+ }
4605
4688
  try {
4606
- const compiledObs = compileToolObservation({
4607
- taskId: this.taskId,
4608
- workspace: this.workspaceRoot,
4609
- toolName: functionName,
4610
- args: args || {},
4611
- result: observedResult && typeof observedResult === 'object' ? observedResult : { success: true }
4612
- });
4613
- if (compiledObs)
4614
- episodicStore.recordObservation(compiledObs);
4689
+ const memPolicy = resolveEffectiveMemoryPolicy(this.workspaceRoot);
4690
+ if (memPolicy.enabled && (memPolicy.allowToolAssisted || !this._memoryPollutedByExternalTools)) {
4691
+ const compiledObs = compileToolObservation({
4692
+ taskId: this.taskId,
4693
+ workspace: this.workspaceRoot,
4694
+ toolName: functionName,
4695
+ args: args || {},
4696
+ result: observedResult && typeof observedResult === 'object' ? observedResult : { success: true }
4697
+ });
4698
+ if (compiledObs)
4699
+ episodicStore.recordObservation(compiledObs);
4700
+ }
4615
4701
  }
4616
4702
  catch { /* never block tool execution on episodic recording */ }
4617
4703
  const recovery = this.timeMachine.observe(functionName, args, observedResult, coldObserver.getToolOutcomes(this.taskId));
@@ -4706,7 +4792,7 @@ Verify Web/UI/3D work programmatically via browser_act (DOM snapshot + runtimeEr
4706
4792
  }
4707
4793
  // Sovereign 100-Step Circuit Breaker Checkpoint Gate
4708
4794
  if (this.consecutiveCommands === 100 && !this.circuitBreakerUnlocked) {
4709
- if (this.config.autonomyMode === 'C') {
4795
+ if (this.activePermissionPreset() === 'danger-full-access') {
4710
4796
  this.circuitBreakerUnlocked = true;
4711
4797
  this.emitEvent({ type: 'status', message: `Continuing within the configured ${this.maxSteps}-step task limit.` });
4712
4798
  }
@@ -4737,7 +4823,7 @@ Verify Web/UI/3D work programmatically via browser_act (DOM snapshot + runtimeEr
4737
4823
  }
4738
4824
  // Sovereign Tier Budget Extension Checkpoint Gate
4739
4825
  if (this.stepsCompleted >= this.maxSteps && !this.stopRequested) {
4740
- if (this.config.autonomyMode === 'C') {
4826
+ if (this.activePermissionPreset() === 'danger-full-access') {
4741
4827
  this.stopRequested = true;
4742
4828
  this.emitEvent({ type: 'error', message: `Task reached the configured ${this.maxSteps}-step limit without verified completion.` });
4743
4829
  }
@@ -4837,11 +4923,12 @@ Verify Web/UI/3D work programmatically via browser_act (DOM snapshot + runtimeEr
4837
4923
  // Per tool, not one number for all of them. A build log and a
4838
4924
  // source file are not equally worth their space in the window.
4839
4925
  // Compatibility fallback preserves complete output when primary store is unavailable.
4926
+ const isRecoveryRead = functionName === 'fs_read' && isOutputRecoveryRead(functionName, args?.path ?? args?.file_path ?? args?.target, recoveryPaths);
4840
4927
  const MAX_RESULT_CHARS = resultCapFor(functionName);
4841
- const inlineLimit = Math.min(MAX_RESULT_CHARS, functionName === 'fs_read_skill' ? 16000 : functionName === 'tool_search' ? 8000 : 2500);
4928
+ const inlineLimit = Math.min(MAX_RESULT_CHARS, functionName === 'fs_read_skill' || functionName === 'fs_read' ? 16000 : functionName === 'tool_search' ? 8000 : 2500);
4842
4929
  const originalFingerprint = createHash('sha256').update(resultString).digest('hex');
4843
4930
  let spill = null;
4844
- if (resultString.length > inlineLimit) {
4931
+ if (!isRecoveryRead && resultString.length > inlineLimit) {
4845
4932
  const document = renderSpillDocument(result, { taskId: this.taskId, step: this.stepsCompleted, tool: functionName });
4846
4933
  const store = inlineLimit > 2500 ? new ToolOutputStore({ maxChars: inlineLimit, maxLines: 400, maxBytes: Math.max(50 * 1024, inlineLimit * 4) }) : defaultToolOutputStore;
4847
4934
  const stored = processToolOutputWithStore(this.taskId, toolCall.id, document, store);
@@ -5250,6 +5337,8 @@ Verify Web/UI/3D work programmatically via browser_act (DOM snapshot + runtimeEr
5250
5337
  apiKey: nextRoute.apiKey
5251
5338
  };
5252
5339
  delete this.config.baseUrl;
5340
+ delete this.config.reasoningEffort;
5341
+ delete this.config.reasoningBudgetTokens;
5253
5342
  this.llm = this.initializeProvider();
5254
5343
  this._utilityLlm = null;
5255
5344
  this.consecutiveFailures = 0;