@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.ts CHANGED
@@ -75,6 +75,7 @@ import {
75
75
  selectNextZeroCostRoute
76
76
  } from './zeroCostFailover.js';
77
77
  import { formatProjectInstructionsPrompt, loadProjectInstructions } from './projectInstructions.js';
78
+ import { isExternalToolAssistedToolName, resolveEffectiveMemoryPolicy } from './personalization.js';
78
79
  import { AGENT_USER_POLICY } from './agentPolicy.js';
79
80
  import { VFETracker } from './vfeTracker.js';
80
81
  import { coldObserver } from './observer/coldObserver.js';
@@ -139,6 +140,15 @@ import { StreamingCodePreview, NativeCodeObserver, codeProgressFromAction } from
139
140
  import { StallGuardController, type StallGuardDecision, type IdenticalCallObservation } from './stallGuard.js';
140
141
  import { buildRecoverableDroppedSummary, pruneStaleToolObservations, shortenOversizedToolObservations, pruneExecutedToolArguments } from './historyPruner.js';
141
142
  import { isOutputRecoveryRead } from './outputRecovery.js';
143
+ import {
144
+ autonomyModeToPreset,
145
+ getPermissionPresetDescriptor,
146
+ normalizePermissionPreset,
147
+ presetToAutonomyMode,
148
+ renderPermissionPolicyContext,
149
+ resolveConfigPermissionPreset,
150
+ type PermissionPresetId
151
+ } from './permissionPresets.js';
142
152
  import { isPlanReviewHandoff, isPlanningOnlyRequest } from './taskContinuation.js';
143
153
  export function noncachedTokens(usage: any): number {
144
154
  if (!usage) return 0;
@@ -207,6 +217,7 @@ export interface AgentLoopOptions {
207
217
  provider?: string;
208
218
  model?: string;
209
219
  variant?: string;
220
+ hostSystemInstructions?: string | undefined;
210
221
  peerMcpServers?: McpServer[] | undefined;
211
222
  }
212
223
 
@@ -238,6 +249,11 @@ ${PEER_COLLABORATION_POLICY}
238
249
 
239
250
  ${AGENT_USER_POLICY}
240
251
 
252
+ # Personalization & Project Instructions (HIGH-PRIORITY DIRECTIVE)
253
+ - **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.
254
+ - **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.
255
+ - **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.
256
+
241
257
  # Operational Guidelines & Engineering Discipline
242
258
  - **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.
243
259
  - **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.
@@ -246,10 +262,10 @@ ${AGENT_USER_POLICY}
246
262
  - **Code Quality**: Write clear, runnable, idiomatic code following existing project conventions without trivial inline comments or TODO placeholders. Preserve unrelated behavior.
247
263
  - **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.
248
264
  - **Git Commits**: Follow the target repository's commit message conventions and project instructions (such as \`AGENTS.md\` or \`git log\`) when committing changes.
249
- - **Autonomy & Safety Boundaries**:
250
- - **Mode A (Passive)**: Ask permission before mutating files, running shell commands, or installing dependencies.
251
- - **Mode B (Supervised)**: Ordinary dev dependencies allowed; ask before OS-level changes or \`sudo\`.
252
- - **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\`).
265
+ - **Permission Presets & Safety Boundaries**:
266
+ - **Read Only (\`read-only\`)**: Inspect files, search code, and read documentation only; file modifications and mutating shell commands are blocked.
267
+ - **Workspace Write (\`workspace-write\`)**: Read and edit files scoped to the active workspace; ask approval before dangerous operations, OS-level changes, or \`sudo\`.
268
+ - **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\`).
253
269
  - **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.
254
270
  - **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.
255
271
 
@@ -556,6 +572,9 @@ export class AgentLoop {
556
572
  this.peerMcpServers = Array.isArray(options.peerMcpServers)
557
573
  ? [...options.peerMcpServers]
558
574
  : [];
575
+ this.hostSystemInstructions = typeof options.hostSystemInstructions === 'string' && options.hostSystemInstructions.trim()
576
+ ? options.hostSystemInstructions.trim()
577
+ : null;
559
578
 
560
579
  this.config = loadConfig();
561
580
  applyProviderOverrides(this.config, this.providerOverride, this.modelOverride);
@@ -651,6 +670,7 @@ export class AgentLoop {
651
670
  // be recomputed on every single step (cortex retrieval, skills index,
652
671
  // design detection, workspace domain scan).
653
672
  this.staticContext = null;
673
+ this._memoryPollutedByExternalTools = false;
654
674
  this.vfeTracker = new VFETracker();
655
675
  this._lessonSimilarity = 0;
656
676
  this._paradigmShiftPending = false;
@@ -947,7 +967,8 @@ export class AgentLoop {
947
967
  async buildStaticContext() {
948
968
  let lessonsLearned = '';
949
969
  this._lessonSimilarity = 0;
950
- const cortexEnabled = Boolean(this.config?.cortex?.enabled);
970
+ const startupMemoryPolicy = resolveEffectiveMemoryPolicy(this.workspaceRoot);
971
+ const cortexEnabled = Boolean(this.config?.cortex?.enabled) && startupMemoryPolicy.enabled;
951
972
  if (cortexEnabled && this.currentTaskPrompt && isSearchablePrompt(this.currentTaskPrompt)) {
952
973
  try {
953
974
  const matches = await cortexDb.search(this.currentTaskPrompt, 2, { workspace: this.workspaceRoot });
@@ -1014,10 +1035,12 @@ export class AgentLoop {
1014
1035
  }
1015
1036
 
1016
1037
  let episodicContext = '';
1017
- try {
1018
- episodicContext = episodicStore.buildStartupEpisodicContext(this.workspaceRoot);
1019
- } catch (e: any) {
1020
- this.debugLog(`episodic context build skipped: ${e.message}`);
1038
+ if (startupMemoryPolicy.enabled) {
1039
+ try {
1040
+ episodicContext = episodicStore.buildStartupEpisodicContext(this.workspaceRoot);
1041
+ } catch (e: any) {
1042
+ this.debugLog(`episodic context build skipped: ${e.message}`);
1043
+ }
1021
1044
  }
1022
1045
 
1023
1046
  let projectInstructions = '';
@@ -1030,7 +1053,10 @@ export class AgentLoop {
1030
1053
  return { lessonsLearned, designContext, antiRepeatDirective, universalSkillsContext, planHint, episodicContext, projectInstructions };
1031
1054
  }
1032
1055
 
1033
-
1056
+ isMemoryPollutedByExternalTools(): boolean {
1057
+ return Boolean(this._memoryPollutedByExternalTools);
1058
+ }
1059
+
1034
1060
  rearmAbortController() {
1035
1061
  this.abortController = new AbortController();
1036
1062
  }
@@ -1064,13 +1090,41 @@ export class AgentLoop {
1064
1090
  }
1065
1091
  }
1066
1092
 
1093
+ activePermissionPreset(): PermissionPresetId {
1094
+ const fromOverride = normalizePermissionPreset(this.autonomyOverride);
1095
+ if (fromOverride) return fromOverride;
1096
+ return resolveConfigPermissionPreset(this.config, 'danger-full-access');
1097
+ }
1098
+
1067
1099
  setAutonomyMode(mode: string) {
1068
- const normalized = String(mode || '').trim().toUpperCase();
1069
- if (!['A', 'B', 'C'].includes(normalized)) {
1070
- throw new Error('autonomy mode must be A, B, or C');
1100
+ const preset = normalizePermissionPreset(mode);
1101
+ if (!preset) {
1102
+ throw new Error('permission preset must be read-only, workspace-write, or danger-full-access (or A, B, C)');
1071
1103
  }
1104
+ const normalized = presetToAutonomyMode(preset);
1072
1105
  this.autonomyOverride = normalized;
1073
1106
  this.config.autonomyMode = normalized;
1107
+ this.config.permissionPreset = preset;
1108
+ if (this.sandbox) {
1109
+ this.sandbox.autonomyMode = normalized;
1110
+ this.sandbox.permissionPreset = preset;
1111
+ }
1112
+ }
1113
+
1114
+ setPermissionPreset(rawPreset: string): PermissionPresetId {
1115
+ const preset = normalizePermissionPreset(rawPreset);
1116
+ if (!preset) {
1117
+ throw new Error('permission preset must be read-only, workspace-write, or danger-full-access');
1118
+ }
1119
+ const mode = presetToAutonomyMode(preset);
1120
+ this.autonomyOverride = mode;
1121
+ this.config.autonomyMode = mode;
1122
+ this.config.permissionPreset = preset;
1123
+ if (this.sandbox) {
1124
+ this.sandbox.autonomyMode = mode;
1125
+ this.sandbox.permissionPreset = preset;
1126
+ }
1127
+ return preset;
1074
1128
  }
1075
1129
 
1076
1130
  /**
@@ -1143,9 +1197,9 @@ export class AgentLoop {
1143
1197
  const prefetched = new Map();
1144
1198
  if (!Array.isArray(toolCalls) || toolCalls.length < 2) return prefetched;
1145
1199
 
1146
- // Mode A promises approval before every tool, including reads. Starting a
1200
+ // Read Only promises approval before every tool, including reads. Starting a
1147
1201
  // read here would execute it before the serial approval and hook gates.
1148
- if ((this.config.autonomyMode || 'C') === 'A') return prefetched;
1202
+ if (this.activePermissionPreset() === 'read-only') return prefetched;
1149
1203
 
1150
1204
  const eligible: any[] = [];
1151
1205
  for (const toolCall of toolCalls) {
@@ -1282,11 +1336,13 @@ export class AgentLoop {
1282
1336
  if (hook?.denied) return false;
1283
1337
  const assessment = await coldObserver.evaluateMutation(tool, args, { workspaceRoot: this.workspaceRoot });
1284
1338
  if (assessment.veto) return false;
1285
- const isModeC = (this.config.autonomyMode || 'C') === 'C';
1339
+ const activePreset = this.activePermissionPreset();
1340
+ const isFullAccess = activePreset === 'danger-full-access';
1286
1341
  const needsApproval = enterpriseDecision.effect === 'ask'
1287
- || (!isModeC && uncertain)
1342
+ || (!isFullAccess && uncertain)
1288
1343
  || requiresToolApproval({
1289
- mode: this.config.autonomyMode || 'C', tool, args,
1344
+ permissionPreset: activePreset,
1345
+ mode: presetToAutonomyMode(activePreset), tool, args,
1290
1346
  risk: assessment.requiresConfirmation ? 'dangerous' : validation.risk,
1291
1347
  heavyDownload: false, standingApproval: this.isAlwaysAllowed(tool)
1292
1348
  });
@@ -1670,7 +1726,21 @@ export class AgentLoop {
1670
1726
 
1671
1727
  updateTierLimits() {
1672
1728
  this.config = loadConfig();
1673
- if (this.autonomyOverride) this.config.autonomyMode = this.autonomyOverride;
1729
+ if (this.autonomyOverride) {
1730
+ const overridePreset = normalizePermissionPreset(this.autonomyOverride);
1731
+ if (overridePreset) {
1732
+ this.config.permissionPreset = overridePreset;
1733
+ this.config.autonomyMode = presetToAutonomyMode(overridePreset);
1734
+ } else {
1735
+ this.config.autonomyMode = this.autonomyOverride;
1736
+ }
1737
+ }
1738
+ const syncedPreset = resolveConfigPermissionPreset(this.config, 'workspace-write');
1739
+ this.config.permissionPreset = syncedPreset;
1740
+ if (this.sandbox) {
1741
+ this.sandbox.permissionPreset = syncedPreset;
1742
+ this.sandbox.autonomyMode = presetToAutonomyMode(syncedPreset);
1743
+ }
1674
1744
  applyProviderOverrides(this.config, this.providerOverride, this.modelOverride);
1675
1745
  if (this.variantOverride) {
1676
1746
  this.config.reasoningEffort = this.variantOverride;
@@ -1884,6 +1954,7 @@ export class AgentLoop {
1884
1954
  this.slopReviewAttempts = 0;
1885
1955
  this.slopLastAuditHash = '';
1886
1956
  this.staticContext = null;
1957
+ this._memoryPollutedByExternalTools = false;
1887
1958
  // Plan cache: the procedure THIS task follows, and the template (if any)
1888
1959
  // that was offered to it. Both reset per task — a plan is a property of one
1889
1960
  // request, not of the session.
@@ -2202,7 +2273,7 @@ export class AgentLoop {
2202
2273
  if (!this.currentTaskPrompt && this.userPrompt) {
2203
2274
  this.currentTaskPrompt = this.userPrompt;
2204
2275
  }
2205
- const isAutonomousMode = (this.config.autonomyMode || 'C') === 'C';
2276
+ const isAutonomousMode = this.activePermissionPreset() === 'danger-full-access';
2206
2277
  const recoveryPaths = new Set<string>();
2207
2278
  let modelCallIndex = 0;
2208
2279
  let softUsageNoticeIssued = false;
@@ -2374,7 +2445,8 @@ export class AgentLoop {
2374
2445
  // All transports receive the same compact catalog and selected host
2375
2446
  // schemas. Peer-native tools and native schema deferral remain provider
2376
2447
  // features; neither changes host authorization or schema selection.
2377
- const eligibleTools = await getDynamicTools(this.config.autonomyMode, this.llm.supportsVision, {
2448
+ const activePreset = this.activePermissionPreset();
2449
+ const eligibleTools = await getDynamicTools(activePreset, this.llm.supportsVision, {
2378
2450
  grantAllTools: true,
2379
2451
  allowedTools: this.sandbox.allowedTools,
2380
2452
  deniedTools: this.config.deniedTools
@@ -2410,7 +2482,8 @@ export class AgentLoop {
2410
2482
  }
2411
2483
 
2412
2484
  // Dynamically inject the absolute latest System context
2413
- const autonomyMode = this.config.autonomyMode || 'C';
2485
+ const activePresetDesc = getPermissionPresetDescriptor(activePreset);
2486
+ const permissionPolicyLine = renderPermissionPolicyContext(activePreset, this.workspaceRoot);
2414
2487
  const allowedPaths = this.sandbox.grantAllAccess
2415
2488
  ? "/ (ALL ACCESS GRANTED - You can read/write anywhere EXCEPT system protected folders like /etc or /System)"
2416
2489
  : (this.sandbox.workspacePaths ? this.sandbox.workspacePaths.join(', ') : this.workspaceRoot);
@@ -2436,7 +2509,10 @@ Verify Web/UI/3D work programmatically via browser_act (DOM snapshot + runtimeEr
2436
2509
  isVisualOrWebTask ? WEB_VERIFICATION_PROMPT : ''
2437
2510
  ].join('');
2438
2511
  const providerPrompt = `${baseProviderPrompt}${sensoryAwareness}${domainPrompts}`;
2439
- const memoryContext = getMemoryContextString({ workspaceRoot: this.workspaceRoot });
2512
+ const turnMemoryPolicy = resolveEffectiveMemoryPolicy(this.workspaceRoot);
2513
+ const memoryContext = turnMemoryPolicy.enabled
2514
+ ? getMemoryContextString({ workspaceRoot: this.workspaceRoot })
2515
+ : '';
2440
2516
 
2441
2517
  // --- PER-TASK STATIC CONTEXT (computed once, not once per step) ---
2442
2518
  // Cortex retrieval, design detection, creative-pattern lookup and the
@@ -2602,13 +2678,14 @@ Verify Web/UI/3D work programmatically via browser_act (DOM snapshot + runtimeEr
2602
2678
  // time a different skill is invoked. This one is stable for the task,
2603
2679
  // so it anchors too.
2604
2680
  ...(skillSystemMessage(this.activeSkill) || []),
2681
+ ...(this.hostSystemInstructions ? [{ role: 'system', content: this.hostSystemInstructions }] : []),
2605
2682
  // [5] VOLATILE tail — the only bytes that may differ between steps:
2606
2683
  // autonomy/workspace paths (change via config), live shared browser
2607
2684
  // state, and persistent memory (grows via memory_write mid-task).
2608
2685
  // Kept LAST and UNcached so a change here never invalidates [1]-[3].
2609
2686
  {
2610
2687
  role: 'system',
2611
- 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}` : ''}`
2688
+ 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}` : ''}`
2612
2689
  }
2613
2690
  ];
2614
2691
 
@@ -2893,15 +2970,21 @@ Verify Web/UI/3D work programmatically via browser_act (DOM snapshot + runtimeEr
2893
2970
  ...(isFailed ? { error: action.detail || `${action.name} failed` } : {})
2894
2971
  };
2895
2972
  coldObserver.recordToolOutcome(this.taskId, action.name, actionArgs, actionOutcome);
2973
+ if (isExternalToolAssistedToolName(action.name)) {
2974
+ this._memoryPollutedByExternalTools = true;
2975
+ }
2896
2976
  try {
2897
- const compiledObs = compileToolObservation({
2898
- taskId: this.taskId,
2899
- workspace: this.workspaceRoot,
2900
- toolName: action.name,
2901
- args: actionArgs,
2902
- result: actionOutcome
2903
- });
2904
- if (compiledObs) episodicStore.recordObservation(compiledObs);
2977
+ const memPolicy = resolveEffectiveMemoryPolicy(this.workspaceRoot);
2978
+ if (memPolicy.enabled && (memPolicy.allowToolAssisted || !this._memoryPollutedByExternalTools)) {
2979
+ const compiledObs = compileToolObservation({
2980
+ taskId: this.taskId,
2981
+ workspace: this.workspaceRoot,
2982
+ toolName: action.name,
2983
+ args: actionArgs,
2984
+ result: actionOutcome
2985
+ });
2986
+ if (compiledObs) episodicStore.recordObservation(compiledObs);
2987
+ }
2905
2988
  } catch { /* never block peer action on episodic recording */ }
2906
2989
  const recovery = this.timeMachine.observe(
2907
2990
  action.name, actionArgs, actionOutcome, coldObserver.getToolOutcomes(this.taskId)
@@ -4125,9 +4208,15 @@ Verify Web/UI/3D work programmatically via browser_act (DOM snapshot + runtimeEr
4125
4208
  }
4126
4209
 
4127
4210
  try {
4211
+ const memPolicy = resolveEffectiveMemoryPolicy(this.workspaceRoot);
4128
4212
  const reqText = String(this.currentTaskPrompt || this.userPrompt || '').trim();
4129
4213
  const completedText = String(response.content || 'Completed task execution.').replace(/\s+/g, ' ').trim();
4130
- if (reqText && (this.stepsCompleted > 0 || completedNativeActionIds.size > 0)) {
4214
+ if (
4215
+ memPolicy.enabled
4216
+ && (memPolicy.allowToolAssisted || !this._memoryPollutedByExternalTools)
4217
+ && reqText
4218
+ && (this.stepsCompleted > 0 || completedNativeActionIds.size > 0)
4219
+ ) {
4131
4220
  episodicStore.recordSessionSummary({
4132
4221
  taskId: this.taskId,
4133
4222
  workspace: this.workspaceRoot,
@@ -4398,8 +4487,9 @@ Verify Web/UI/3D work programmatically via browser_act (DOM snapshot + runtimeEr
4398
4487
  // 4-Layer Security Sandbox Validation
4399
4488
  // 2. Sandbox Security Validation (CRITICAL FIX: Prevent Infinite Loop on Block)
4400
4489
  let validation = this.sandbox.validate(functionName, args);
4490
+ const recoveryCandidatePath = args.path ?? args.file_path ?? args.target ?? args.dir;
4401
4491
  if (!validation.allowed && /^Path outside allowed workspace:/.test(validation.reason || '')
4402
- && isOutputRecoveryRead(functionName, args.path, recoveryPaths)) {
4492
+ && isOutputRecoveryRead(functionName, recoveryCandidatePath, recoveryPaths)) {
4403
4493
  validation = { allowed: true, risk: 'safe', reason: 'Read exact tool output referenced by this session' };
4404
4494
  }
4405
4495
  if (!validation.allowed) {
@@ -4607,14 +4697,16 @@ Verify Web/UI/3D work programmatically via browser_act (DOM snapshot + runtimeEr
4607
4697
  continue;
4608
4698
  }
4609
4699
 
4610
- // A standing grant can avoid repeat prompts in supervised modes.
4611
- // Mode C is autonomous for in-scope work. Whole-file deletion asks
4700
+ // A standing grant can avoid repeat prompts in Workspace Write.
4701
+ // Full access runs in-scope work directly. Whole-file deletion asks
4612
4702
  // unless this session explicitly granted the fs_delete tool; a broad
4613
4703
  // shell grant cannot authorize deletion. Sandbox denials and observer
4614
4704
  // vetoes have already run and are never lifted by prompt policy.
4705
+ const stepPreset = this.activePermissionPreset();
4615
4706
  const standingApproval = this.isAlwaysAllowed(functionName);
4616
4707
  let needsToolApproval = requiresToolApproval({
4617
- mode: this.config.autonomyMode || 'C',
4708
+ permissionPreset: stepPreset,
4709
+ mode: presetToAutonomyMode(stepPreset),
4618
4710
  tool: functionName,
4619
4711
  args,
4620
4712
  risk: validation.risk,
@@ -4647,7 +4739,7 @@ Verify Web/UI/3D work programmatically via browser_act (DOM snapshot + runtimeEr
4647
4739
  reason: enterpriseDecision.reason
4648
4740
  });
4649
4741
  }
4650
- if (standingApproval && !needsToolApproval && this.config.autonomyMode !== 'C' && enterpriseDecision.effect !== 'allow') {
4742
+ if (standingApproval && !needsToolApproval && stepPreset !== 'danger-full-access' && enterpriseDecision.effect !== 'allow') {
4651
4743
  auditLog.log({
4652
4744
  event: 'approval_auto_granted', taskId: this.taskId,
4653
4745
  tool: functionName, risk: validation.risk, reason: 'allow_always'
@@ -4852,15 +4944,21 @@ Verify Web/UI/3D work programmatically via browser_act (DOM snapshot + runtimeEr
4852
4944
  ? { success: true, _is_image_marker: true, visionDelivered: imageCanReachModel, filename: result.filename, mimeType: result.mimeType }
4853
4945
  : result;
4854
4946
  coldObserver.recordToolOutcome(this.taskId, functionName, args, observedResult);
4947
+ if (isExternalToolAssistedToolName(functionName)) {
4948
+ this._memoryPollutedByExternalTools = true;
4949
+ }
4855
4950
  try {
4856
- const compiledObs = compileToolObservation({
4857
- taskId: this.taskId,
4858
- workspace: this.workspaceRoot,
4859
- toolName: functionName,
4860
- args: args || {},
4861
- result: observedResult && typeof observedResult === 'object' ? observedResult : { success: true }
4862
- });
4863
- if (compiledObs) episodicStore.recordObservation(compiledObs);
4951
+ const memPolicy = resolveEffectiveMemoryPolicy(this.workspaceRoot);
4952
+ if (memPolicy.enabled && (memPolicy.allowToolAssisted || !this._memoryPollutedByExternalTools)) {
4953
+ const compiledObs = compileToolObservation({
4954
+ taskId: this.taskId,
4955
+ workspace: this.workspaceRoot,
4956
+ toolName: functionName,
4957
+ args: args || {},
4958
+ result: observedResult && typeof observedResult === 'object' ? observedResult : { success: true }
4959
+ });
4960
+ if (compiledObs) episodicStore.recordObservation(compiledObs);
4961
+ }
4864
4962
  } catch { /* never block tool execution on episodic recording */ }
4865
4963
  const recovery = this.timeMachine.observe(
4866
4964
  functionName, args, observedResult, coldObserver.getToolOutcomes(this.taskId)
@@ -4967,7 +5065,7 @@ Verify Web/UI/3D work programmatically via browser_act (DOM snapshot + runtimeEr
4967
5065
 
4968
5066
  // Sovereign 100-Step Circuit Breaker Checkpoint Gate
4969
5067
  if (this.consecutiveCommands === 100 && !this.circuitBreakerUnlocked) {
4970
- if (this.config.autonomyMode === 'C') {
5068
+ if (this.activePermissionPreset() === 'danger-full-access') {
4971
5069
  this.circuitBreakerUnlocked = true;
4972
5070
  this.emitEvent({ type: 'status', message: `Continuing within the configured ${this.maxSteps}-step task limit.` });
4973
5071
  } else {
@@ -4998,7 +5096,7 @@ Verify Web/UI/3D work programmatically via browser_act (DOM snapshot + runtimeEr
4998
5096
 
4999
5097
  // Sovereign Tier Budget Extension Checkpoint Gate
5000
5098
  if (this.stepsCompleted >= this.maxSteps && !this.stopRequested) {
5001
- if (this.config.autonomyMode === 'C') {
5099
+ if (this.activePermissionPreset() === 'danger-full-access') {
5002
5100
  this.stopRequested = true;
5003
5101
  this.emitEvent({ type: 'error', message: `Task reached the configured ${this.maxSteps}-step limit without verified completion.` });
5004
5102
  } else {
@@ -5097,11 +5195,12 @@ Verify Web/UI/3D work programmatically via browser_act (DOM snapshot + runtimeEr
5097
5195
  // Per tool, not one number for all of them. A build log and a
5098
5196
  // source file are not equally worth their space in the window.
5099
5197
  // Compatibility fallback preserves complete output when primary store is unavailable.
5198
+ const isRecoveryRead = functionName === 'fs_read' && isOutputRecoveryRead(functionName, args?.path ?? args?.file_path ?? args?.target, recoveryPaths);
5100
5199
  const MAX_RESULT_CHARS = resultCapFor(functionName);
5101
- const inlineLimit = Math.min(MAX_RESULT_CHARS, functionName === 'fs_read_skill' ? 16000 : functionName === 'tool_search' ? 8000 : 2500);
5200
+ const inlineLimit = Math.min(MAX_RESULT_CHARS, functionName === 'fs_read_skill' || functionName === 'fs_read' ? 16000 : functionName === 'tool_search' ? 8000 : 2500);
5102
5201
  const originalFingerprint = createHash('sha256').update(resultString).digest('hex');
5103
5202
  let spill = null;
5104
- if (resultString.length > inlineLimit) {
5203
+ if (!isRecoveryRead && resultString.length > inlineLimit) {
5105
5204
  const document = renderSpillDocument(result, { taskId: this.taskId, step: this.stepsCompleted, tool: functionName });
5106
5205
  const store = inlineLimit > 2500 ? new ToolOutputStore({ maxChars: inlineLimit, maxLines: 400, maxBytes: Math.max(50 * 1024, inlineLimit * 4) }) : defaultToolOutputStore;
5107
5206
  const stored = processToolOutputWithStore(this.taskId, toolCall.id, document, store);
@@ -5543,6 +5642,8 @@ Verify Web/UI/3D work programmatically via browser_act (DOM snapshot + runtimeEr
5543
5642
  apiKey: nextRoute.apiKey
5544
5643
  };
5545
5644
  delete this.config.baseUrl;
5645
+ delete this.config.reasoningEffort;
5646
+ delete this.config.reasoningBudgetTokens;
5546
5647
  this.llm = this.initializeProvider();
5547
5648
  this._utilityLlm = null;
5548
5649
  this.consecutiveFailures = 0;
@@ -1,13 +1,35 @@
1
1
  import { AsyncLocalStorage } from 'node:async_hooks';
2
+ import { normalizePermissionPreset, presetToAutonomyMode, resolveConfigPermissionPreset } from './permissionPresets.js';
2
3
  const toolAutonomy = new AsyncLocalStorage();
3
- /** Session-scoped context for legacy tools whose execute signature has no context parameter. */
4
+ const toolPreset = new AsyncLocalStorage();
5
+ /** Session-scoped context for tools whose execute signature has no context parameter. */
6
+ export function withToolPermissionPreset(preset, run) {
7
+ const mode = presetToAutonomyMode(preset);
8
+ return toolPreset.run(preset, () => toolAutonomy.run(mode, run));
9
+ }
10
+ export function currentToolPermissionPreset() {
11
+ const direct = toolPreset.getStore();
12
+ if (direct)
13
+ return direct;
14
+ const legacy = toolAutonomy.getStore();
15
+ return legacy ? (normalizePermissionPreset(legacy) ?? undefined) : undefined;
16
+ }
17
+ /** Legacy compatibility wrapper delegating to permission presets. */
4
18
  export function withToolAutonomyMode(mode, run) {
19
+ const preset = normalizePermissionPreset(mode);
20
+ if (preset) {
21
+ return toolPreset.run(preset, () => toolAutonomy.run(mode, run));
22
+ }
5
23
  return toolAutonomy.run(mode, run);
6
24
  }
7
25
  export function currentToolAutonomyMode() {
8
- return toolAutonomy.getStore();
26
+ const direct = toolAutonomy.getStore();
27
+ if (direct !== undefined)
28
+ return direct;
29
+ const preset = toolPreset.getStore();
30
+ return preset ? presetToAutonomyMode(preset) : undefined;
9
31
  }
10
- /** Read the live session mode from the tool context; never infer it from a tool argument. */
32
+ /** Read the live session permission preset from the tool context; never infer it from a tool argument. */
11
33
  export function isAutonomousToolContext(context) {
12
34
  if (!context || typeof context !== 'object' || Array.isArray(context))
13
35
  return false;
@@ -17,10 +39,9 @@ export function isAutonomousToolContext(context) {
17
39
  const config = parentLoop.config;
18
40
  if (!config || typeof config !== 'object' || Array.isArray(config))
19
41
  return false;
20
- const mode = config.autonomyMode;
21
- return mode === 'C' || mode === undefined;
42
+ return resolveConfigPermissionPreset(config, 'danger-full-access') === 'danger-full-access';
22
43
  }
23
- const SHELL_TOOLS = new Set(['sysRun', 'sysRunBg', 'terminal_persistent_shell', 'task_bg']);
44
+ const SHELL_TOOLS = new Set(['sysRun', 'sysRunBg', 'terminal_persistent_shell', 'terminal_pty', 'task_bg']);
24
45
  const WHOLE_FILE_DELETE = /(?:^|[;&|\n(]\s*)(?:(?:sudo|doas|pkexec|command|env)\s+)*(?:rm|unlink|rmdir|shred|srm|del|erase|Remove-Item)\b|\bgit\s+rm\b/i;
25
46
  const DELETE_API_CALL = /\b(?:os\.(?:remove|unlink)|shutil\.rmtree|fs\.(?:rm|unlink)(?:Sync)?|\.unlink|\.rmdir)\s*\(/i;
26
47
  const NESTED_SHELL_DELETE = /\b(?:bash|sh|zsh|dash)\s+-c\s+['"]\s*(?:rm|unlink|rmdir|shred|srm)\b|\b(?:powershell|pwsh)\s+(?:-Command|-c)\s+['"]?\s*Remove-Item\b/i;
@@ -71,7 +92,7 @@ export function isWholeFileDeletion(tool, args) {
71
92
  || DELETE_API_CALL.test(command)
72
93
  || NESTED_SHELL_DELETE.test(command));
73
94
  }
74
- /** Routine browser verification inside the isolated agent browser (preview, snapshot, click, fill, screenshot, etc.) does not require HITL in Mode B or C unless uploading or downloading files. */
95
+ /** Routine browser verification inside the isolated agent browser (preview, snapshot, click, fill, screenshot, etc.) does not require HITL in Workspace Write or Full access unless uploading or downloading files. */
75
96
  export function isRoutineBrowserVerification(tool, args) {
76
97
  if (canonicalPolicyTool(tool) !== 'browser_act')
77
98
  return false;
@@ -110,7 +131,10 @@ export function requiresToolApproval(input) {
110
131
  if (!input || typeof input !== 'object')
111
132
  return true;
112
133
  const canonical = canonicalPolicyTool(input.tool);
113
- if (input.mode === 'C') {
134
+ const preset = normalizePermissionPreset(input.permissionPreset)
135
+ ?? normalizePermissionPreset(input.mode)
136
+ ?? 'danger-full-access';
137
+ if (preset === 'danger-full-access') {
114
138
  if (touchesCredentialMaterial(input)) {
115
139
  return true;
116
140
  }
@@ -124,11 +148,11 @@ export function requiresToolApproval(input) {
124
148
  }
125
149
  if (input.standingApproval)
126
150
  return false;
127
- if (input.mode !== 'A' && isRoutineBrowserVerification(input.tool, input.args)) {
151
+ if (preset !== 'read-only' && isRoutineBrowserVerification(input.tool, input.args)) {
128
152
  return false;
129
153
  }
130
154
  return input.risk === 'extreme'
131
155
  || input.heavyDownload
132
156
  || input.risk === 'dangerous'
133
- || input.mode === 'A';
157
+ || preset === 'read-only';
134
158
  }
@@ -1,20 +1,48 @@
1
1
  import { AsyncLocalStorage } from 'node:async_hooks';
2
+ import {
3
+ normalizePermissionPreset,
4
+ presetToAutonomyMode,
5
+ resolveConfigPermissionPreset,
6
+ type PermissionPresetId
7
+ } from './permissionPresets.js';
2
8
 
3
9
  export type AutonomyMode = 'A' | 'B' | 'C' | string;
4
10
 
5
11
  const toolAutonomy = new AsyncLocalStorage<AutonomyMode>();
12
+ const toolPreset = new AsyncLocalStorage<PermissionPresetId>();
6
13
 
7
- /** Session-scoped context for legacy tools whose execute signature has no context parameter. */
14
+ /** Session-scoped context for tools whose execute signature has no context parameter. */
15
+ export function withToolPermissionPreset<T>(preset: PermissionPresetId, run: () => Promise<T>): Promise<T> {
16
+ const mode = presetToAutonomyMode(preset);
17
+ return toolPreset.run(preset, () => toolAutonomy.run(mode, run));
18
+ }
19
+
20
+ export function currentToolPermissionPreset(): PermissionPresetId | undefined {
21
+ const direct = toolPreset.getStore();
22
+ if (direct) return direct;
23
+ const legacy = toolAutonomy.getStore();
24
+ return legacy ? (normalizePermissionPreset(legacy) ?? undefined) : undefined;
25
+ }
26
+
27
+ /** Legacy compatibility wrapper delegating to permission presets. */
8
28
  export function withToolAutonomyMode<T>(mode: AutonomyMode, run: () => Promise<T>): Promise<T> {
29
+ const preset = normalizePermissionPreset(mode);
30
+ if (preset) {
31
+ return toolPreset.run(preset, () => toolAutonomy.run(mode, run));
32
+ }
9
33
  return toolAutonomy.run(mode, run);
10
34
  }
11
35
 
12
36
  export function currentToolAutonomyMode(): AutonomyMode | undefined {
13
- return toolAutonomy.getStore();
37
+ const direct = toolAutonomy.getStore();
38
+ if (direct !== undefined) return direct;
39
+ const preset = toolPreset.getStore();
40
+ return preset ? presetToAutonomyMode(preset) : undefined;
14
41
  }
15
42
 
16
43
  export interface ToolApprovalInput {
17
- mode: AutonomyMode;
44
+ permissionPreset?: PermissionPresetId | string | undefined;
45
+ mode?: AutonomyMode | undefined;
18
46
  tool: string;
19
47
  args: Record<string, unknown>;
20
48
  risk: string;
@@ -23,18 +51,17 @@ export interface ToolApprovalInput {
23
51
  reason?: string | undefined;
24
52
  }
25
53
 
26
- /** Read the live session mode from the tool context; never infer it from a tool argument. */
54
+ /** Read the live session permission preset from the tool context; never infer it from a tool argument. */
27
55
  export function isAutonomousToolContext(context: unknown): boolean {
28
56
  if (!context || typeof context !== 'object' || Array.isArray(context)) return false;
29
57
  const parentLoop = (context as { parentLoop?: unknown }).parentLoop;
30
58
  if (!parentLoop || typeof parentLoop !== 'object' || Array.isArray(parentLoop)) return false;
31
59
  const config = (parentLoop as { config?: unknown }).config;
32
60
  if (!config || typeof config !== 'object' || Array.isArray(config)) return false;
33
- const mode = (config as { autonomyMode?: unknown }).autonomyMode;
34
- return mode === 'C' || mode === undefined;
61
+ return resolveConfigPermissionPreset(config as Record<string, unknown>, 'danger-full-access') === 'danger-full-access';
35
62
  }
36
63
 
37
- const SHELL_TOOLS = new Set(['sysRun', 'sysRunBg', 'terminal_persistent_shell', 'task_bg']);
64
+ const SHELL_TOOLS = new Set(['sysRun', 'sysRunBg', 'terminal_persistent_shell', 'terminal_pty', 'task_bg']);
38
65
  const WHOLE_FILE_DELETE = /(?:^|[;&|\n(]\s*)(?:(?:sudo|doas|pkexec|command|env)\s+)*(?:rm|unlink|rmdir|shred|srm|del|erase|Remove-Item)\b|\bgit\s+rm\b/i;
39
66
  const DELETE_API_CALL = /\b(?:os\.(?:remove|unlink)|shutil\.rmtree|fs\.(?:rm|unlink)(?:Sync)?|\.unlink|\.rmdir)\s*\(/i;
40
67
  const NESTED_SHELL_DELETE = /\b(?:bash|sh|zsh|dash)\s+-c\s+['"]\s*(?:rm|unlink|rmdir|shred|srm)\b|\b(?:powershell|pwsh)\s+(?:-Command|-c)\s+['"]?\s*Remove-Item\b/i;
@@ -84,7 +111,7 @@ export function isWholeFileDeletion(tool: string, args: Record<string, unknown>)
84
111
  || NESTED_SHELL_DELETE.test(command));
85
112
  }
86
113
 
87
- /** Routine browser verification inside the isolated agent browser (preview, snapshot, click, fill, screenshot, etc.) does not require HITL in Mode B or C unless uploading or downloading files. */
114
+ /** Routine browser verification inside the isolated agent browser (preview, snapshot, click, fill, screenshot, etc.) does not require HITL in Workspace Write or Full access unless uploading or downloading files. */
88
115
  export function isRoutineBrowserVerification(tool: string, args: Record<string, unknown>): boolean {
89
116
  if (canonicalPolicyTool(tool) !== 'browser_act') return false;
90
117
  const actions = Array.isArray(args?.actions) ? args.actions : [];
@@ -120,7 +147,11 @@ function touchesCredentialMaterial(input: ToolApprovalInput): boolean {
120
147
  export function requiresToolApproval(input: ToolApprovalInput): boolean {
121
148
  if (!input || typeof input !== 'object') return true;
122
149
  const canonical = canonicalPolicyTool(input.tool);
123
- if (input.mode === 'C') {
150
+ const preset = normalizePermissionPreset(input.permissionPreset)
151
+ ?? normalizePermissionPreset(input.mode)
152
+ ?? 'danger-full-access';
153
+
154
+ if (preset === 'danger-full-access') {
124
155
  if (touchesCredentialMaterial(input)) {
125
156
  return true;
126
157
  }
@@ -132,11 +163,11 @@ export function requiresToolApproval(input: ToolApprovalInput): boolean {
132
163
  return canonical !== 'fs_delete' || !input.standingApproval;
133
164
  }
134
165
  if (input.standingApproval) return false;
135
- if (input.mode !== 'A' && isRoutineBrowserVerification(input.tool, input.args)) {
166
+ if (preset !== 'read-only' && isRoutineBrowserVerification(input.tool, input.args)) {
136
167
  return false;
137
168
  }
138
169
  return input.risk === 'extreme'
139
170
  || input.heavyDownload
140
171
  || input.risk === 'dangerous'
141
- || input.mode === 'A';
172
+ || preset === 'read-only';
142
173
  }