@causyne/agent 1.20.124 → 1.20.127

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 (235) hide show
  1. package/bin/causyne.js +1 -1
  2. package/package.json +4 -4
  3. package/src/acp/protocol.ts +19 -1
  4. package/src/acp/server.js +282 -8
  5. package/src/acp/server.ts +284 -8
  6. package/src/agent/abortableDelay.js +2 -2
  7. package/src/agent/abortableDelay.ts +2 -2
  8. package/src/agent/errorClassifier.js +9 -1
  9. package/src/agent/errorClassifier.ts +8 -1
  10. package/src/agentLoop.js +83 -27
  11. package/src/agentLoop.ts +92 -26
  12. package/src/approvalPolicy.js +34 -10
  13. package/src/approvalPolicy.ts +42 -11
  14. package/src/browser/causyneBrowser.js +30 -3
  15. package/src/browser/causyneBrowser.ts +33 -3
  16. package/src/browser/urlPolicy.js +14 -1
  17. package/src/browser/urlPolicy.ts +12 -1
  18. package/src/cliMode.js +21 -9
  19. package/src/cliMode.ts +20 -8
  20. package/src/commands.js +188 -32
  21. package/src/commands.ts +209 -32
  22. package/src/config.js +19 -4
  23. package/src/config.ts +18 -4
  24. package/src/core/contextCompactor.js +54 -7
  25. package/src/core/contextCompactor.ts +63 -7
  26. package/src/core/goalLoop.js +257 -0
  27. package/src/core/goalLoop.ts +310 -0
  28. package/src/entrypoint.js +135 -3
  29. package/src/entrypoint.ts +136 -3
  30. package/src/game/causyneCoreBridge.js +686 -0
  31. package/src/game/causyneCoreBridge.ts +702 -0
  32. package/src/game/gameLauncher.js +287 -0
  33. package/src/game/gameLauncher.ts +352 -0
  34. package/src/game/gameProvisioner.js +425 -0
  35. package/src/game/gameProvisioner.ts +488 -0
  36. package/src/headlessCli.js +19 -12
  37. package/src/headlessCli.ts +22 -8
  38. package/src/infra/atomicWriter.js +40 -4
  39. package/src/infra/atomicWriter.ts +36 -4
  40. package/src/launchIntent.js +73 -3
  41. package/src/launchIntent.ts +76 -3
  42. package/src/lsp/lspClient.js +83 -12
  43. package/src/lsp/lspClient.ts +75 -12
  44. package/src/mcp/mcpRegistry.js +75 -8
  45. package/src/mcp/mcpRegistry.ts +70 -7
  46. package/src/memory/contextBudget.js +2 -0
  47. package/src/memory/contextBudget.ts +1 -0
  48. package/src/modelVariants.js +45 -0
  49. package/src/modelVariants.ts +54 -0
  50. package/src/outputRecovery.js +3 -2
  51. package/src/outputRecovery.ts +4 -2
  52. package/src/permissionPresets.js +327 -0
  53. package/src/permissionPresets.ts +361 -0
  54. package/src/providers/antigravity.js +62 -9
  55. package/src/providers/antigravity.ts +73 -9
  56. package/src/providers/byokHttp.js +7 -1
  57. package/src/providers/byokHttp.ts +6 -1
  58. package/src/providers/byokStream.js +21 -8
  59. package/src/providers/byokStream.ts +17 -7
  60. package/src/providers/dashscope-byok.js +21 -5
  61. package/src/providers/dashscope-byok.ts +29 -11
  62. package/src/providers/moonshot.js +26 -7
  63. package/src/providers/moonshot.ts +34 -13
  64. package/src/providers/muse.js +6 -0
  65. package/src/providers/muse.ts +8 -0
  66. package/src/providers/ollama.js +39 -7
  67. package/src/providers/ollama.ts +36 -7
  68. package/src/providers/openai-compatible.js +16 -3
  69. package/src/providers/openai-compatible.ts +13 -3
  70. package/src/providers/openai.js +62 -4
  71. package/src/providers/openai.ts +50 -4
  72. package/src/providers/openrouter.js +19 -4
  73. package/src/providers/openrouter.ts +21 -4
  74. package/src/providers/qwen-byok.js +21 -5
  75. package/src/providers/qwen-byok.ts +29 -11
  76. package/src/providers/xai.js +26 -10
  77. package/src/providers/xai.ts +34 -16
  78. package/src/reporting.js +4 -2
  79. package/src/reporting.ts +4 -2
  80. package/src/sandbox.js +34 -0
  81. package/src/sandbox.ts +43 -0
  82. package/src/scheduler/scheduler.js +372 -0
  83. package/src/scheduler/scheduler.ts +433 -0
  84. package/src/sessionSearchIndex.js +267 -0
  85. package/src/sessionSearchIndex.ts +311 -0
  86. package/src/skillsManager.js +2 -3
  87. package/src/skillsManager.ts +2 -3
  88. package/src/toolPacks.js +6 -0
  89. package/src/toolPacks.ts +6 -0
  90. package/src/tools/applyPatch.js +1 -1
  91. package/src/tools/applyPatch.ts +1 -1
  92. package/src/tools/generateMediaViaApi.js +4 -3
  93. package/src/tools/generateMediaViaApi.ts +4 -3
  94. package/src/tools/nativeEngine.js +2 -2
  95. package/src/tools/nativeEngine.ts +2 -2
  96. package/src/tools/openSourceToolProvisioner.js +2 -2
  97. package/src/tools/openSourceToolProvisioner.ts +2 -2
  98. package/src/tools/payloadSanitizer.js +0 -1
  99. package/src/tools/payloadSanitizer.ts +0 -1
  100. package/src/tools/pdfReader.js +122 -20
  101. package/src/tools/pdfReader.ts +111 -20
  102. package/src/tools/presentDeliverable.js +103 -0
  103. package/src/tools/presentDeliverable.ts +127 -0
  104. package/src/tools/ptcRuntime.js +444 -0
  105. package/src/tools/ptcRuntime.ts +490 -0
  106. package/src/tools/ptyTerminal.js +1096 -0
  107. package/src/tools/ptyTerminal.ts +1231 -0
  108. package/src/tools/registry.js +21 -12
  109. package/src/tools/registry.ts +21 -12
  110. package/src/tools/toolOutputStore.js +26 -4
  111. package/src/tools/toolOutputStore.ts +22 -4
  112. package/src/tools/webFetch.js +158 -11
  113. package/src/tools/webFetch.ts +145 -11
  114. package/src/tools/webSearch.js +123 -36
  115. package/src/tools/webSearch.ts +124 -33
  116. package/src/tui/banner.js +5 -1
  117. package/src/tui/banner.ts +6 -1
  118. package/src/tui/chatRenderer.js +1 -2
  119. package/src/tui/chatRenderer.ts +1 -2
  120. package/src/tui/completion.js +1 -0
  121. package/src/tui/completion.ts +1 -0
  122. package/src/tui/composerControls.js +111 -27
  123. package/src/tui/composerControls.ts +124 -28
  124. package/src/tui/dialogs.js +3 -16
  125. package/src/tui/dialogs.ts +3 -16
  126. package/src/tui/home.js +1 -0
  127. package/src/tui/home.ts +1 -0
  128. package/src/tui/invocation.js +1 -2
  129. package/src/tui/invocation.ts +1 -2
  130. package/src/tui/modelPicker.js +22 -12
  131. package/src/tui/modelPicker.ts +22 -12
  132. package/src/tui/overlay.js +2 -5
  133. package/src/tui/overlay.ts +2 -5
  134. package/src/tui/prompt.js +6 -4
  135. package/src/tui/prompt.ts +6 -4
  136. package/src/tui/selectList.js +4 -12
  137. package/src/tui/selectList.ts +4 -12
  138. package/src/tui/setup.js +22 -9
  139. package/src/tui/setup.ts +26 -9
  140. package/src/tui/statusLine.ts +2 -0
  141. package/src/web/client/browserPanel.js +702 -0
  142. package/src/web/client/browserPanel.ts +663 -0
  143. package/src/web/client/chatStream.js +309 -0
  144. package/src/web/client/chatStream.ts +289 -0
  145. package/src/web/client/cliPanel.js +165 -0
  146. package/src/web/client/cliPanel.ts +171 -0
  147. package/src/web/client/composer.js +204 -0
  148. package/src/web/client/composer.ts +209 -0
  149. package/src/web/client/diffPanel.js +176 -0
  150. package/src/web/client/diffPanel.ts +203 -0
  151. package/src/web/client/dom.js +220 -0
  152. package/src/web/client/dom.ts +221 -0
  153. package/src/web/client/filesAndCanvas.js +231 -0
  154. package/src/web/client/filesAndCanvas.ts +238 -0
  155. package/src/web/client/gameLauncherUi.js +78 -0
  156. package/src/web/client/gameLauncherUi.ts +78 -0
  157. package/src/web/client/main.js +301 -0
  158. package/src/web/client/main.ts +368 -0
  159. package/src/web/client/markdown.js +364 -0
  160. package/src/web/client/markdown.ts +373 -0
  161. package/src/web/client/modelPicker.js +455 -0
  162. package/src/web/client/modelPicker.ts +451 -0
  163. package/src/web/client/permissionPresetsUi.js +307 -0
  164. package/src/web/client/permissionPresetsUi.ts +333 -0
  165. package/src/web/client/sessions.js +353 -0
  166. package/src/web/client/sessions.ts +372 -0
  167. package/src/web/client/settingsModal.js +191 -0
  168. package/src/web/client/settingsModal.ts +176 -0
  169. package/src/web/client/state.js +250 -0
  170. package/src/web/client/state.ts +233 -0
  171. package/src/web/client/streamSmoother.js +127 -0
  172. package/src/web/client/streamSmoother.ts +119 -0
  173. package/src/web/client/studioLayout.js +54 -0
  174. package/src/web/client/studioLayout.ts +60 -0
  175. package/src/web/client/studioShell.js +327 -0
  176. package/src/web/client/studioShell.ts +340 -0
  177. package/src/web/client/studioStart.js +77 -0
  178. package/src/web/client/studioStart.ts +89 -0
  179. package/src/web/client/terminalPanel.js +357 -0
  180. package/src/web/client/terminalPanel.ts +345 -0
  181. package/src/web/client/turnView.js +934 -0
  182. package/src/web/client/turnView.ts +981 -0
  183. package/src/web/client/types.js +1 -0
  184. package/src/web/client/types.ts +319 -0
  185. package/src/web/client/validators.js +106 -0
  186. package/src/web/client/validators.ts +96 -0
  187. package/src/web/server/activeRuns.js +152 -0
  188. package/src/web/server/activeRuns.ts +171 -0
  189. package/src/web/server/routesBrowser.js +355 -0
  190. package/src/web/server/routesBrowser.ts +386 -0
  191. package/src/web/server/routesChat.js +304 -0
  192. package/src/web/server/routesChat.ts +347 -0
  193. package/src/web/server/routesCore.js +472 -0
  194. package/src/web/server/routesCore.ts +522 -0
  195. package/src/web/server/routesTerminal.js +162 -0
  196. package/src/web/server/routesTerminal.ts +182 -0
  197. package/src/web/server/routesWorkspace.js +510 -0
  198. package/src/web/server/routesWorkspace.ts +546 -0
  199. package/src/web/server/security.js +98 -0
  200. package/src/web/server/security.ts +108 -0
  201. package/src/web/server/sessionTranscript.js +586 -0
  202. package/src/web/server/sessionTranscript.ts +566 -0
  203. package/src/web/server/staticAssets.js +80 -0
  204. package/src/web/server/staticAssets.ts +91 -0
  205. package/src/web/server/types.js +1 -0
  206. package/src/web/server/types.ts +135 -0
  207. package/src/web/server/workspaceFiles.js +368 -0
  208. package/src/web/server/workspaceFiles.ts +363 -0
  209. package/src/web/skybridgeServer.js +76 -2449
  210. package/src/web/skybridgeServer.ts +118 -2600
  211. package/src/web/skybridgeUi.js +16 -450
  212. package/src/web/skybridgeUi.ts +16 -454
  213. package/src/web/styles/agent.css +380 -0
  214. package/src/web/styles/composer.css +193 -0
  215. package/src/web/styles/overlays.css +436 -0
  216. package/src/web/styles/shell.css +387 -0
  217. package/src/web/styles/studio.css +723 -0
  218. package/src/web/styles/thread.css +221 -0
  219. package/src/web/styles/tokens.css +94 -0
  220. package/src/web/ui/brandMark.js +73 -0
  221. package/src/web/ui/brandMark.ts +82 -0
  222. package/src/web/ui/modalsTemplate.js +139 -0
  223. package/src/web/ui/modalsTemplate.ts +139 -0
  224. package/src/web/ui/sidebarTemplate.js +63 -0
  225. package/src/web/ui/sidebarTemplate.ts +64 -0
  226. package/src/web/ui/studioTemplate.js +258 -0
  227. package/src/web/ui/studioTemplate.ts +258 -0
  228. package/src/web/ui/workspaceTemplate.js +72 -0
  229. package/src/web/ui/workspaceTemplate.ts +73 -0
  230. package/src/worktreeManager.js +16 -1
  231. package/src/worktreeManager.ts +22 -1
  232. package/src/web/skybridgeClientScript.js +0 -3951
  233. package/src/web/skybridgeClientScript.ts +0 -3952
  234. package/src/web/skybridgeStyles.js +0 -827
  235. package/src/web/skybridgeStyles.ts +0 -828
package/src/config.js CHANGED
@@ -5,6 +5,7 @@ import { canonicalModelId } from './modelIds.js';
5
5
  import { DEFAULT_MODEL_BY_PROVIDER } from './modelCatalogue.js';
6
6
  import { causyneHome } from './utils/paths.js';
7
7
  import { listLocalOllamaDiskModels, pickPreferredLocalOllamaModel } from './zeroCostRouting.js';
8
+ import { autonomyModeToPreset, normalizePermissionPreset } from './permissionPresets.js';
8
9
  import { ensureVaultDir, atomicWriteSecretFileSync, encryptVaultSecret, decryptVaultSecret, isEncryptedVaultSecret } from './configVault.js';
9
10
  const MAX_CONFIG_BYTES = 2 * 1024 * 1024;
10
11
  const FORBIDDEN_CONFIG_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
@@ -56,15 +57,19 @@ export function resolveProviderApiKey(config, targetProvider) {
56
57
  return '';
57
58
  }
58
59
  export function applyProviderOverrides(config, providerOverride, modelOverride) {
60
+ const prevProvider = typeof config.provider === 'string' ? config.provider.trim().toLowerCase() : '';
61
+ const prevModel = typeof config.model === 'string' ? config.model.trim() : '';
59
62
  const nextProvider = typeof providerOverride === 'string' ? providerOverride.trim() : '';
60
63
  const nextModel = typeof modelOverride === 'string' ? modelOverride.trim() : '';
64
+ let changed = false;
61
65
  if (nextProvider) {
62
- const prevNorm = typeof config.provider === 'string' ? config.provider.trim().toLowerCase() : '';
63
66
  const nextNorm = nextProvider.toLowerCase();
64
- const prevAliases = prevNorm
65
- ? (Object.hasOwn(PROVIDER_KEY_ALIASES, prevNorm) ? PROVIDER_KEY_ALIASES[prevNorm] : [prevNorm])
67
+ const prevAliases = prevProvider
68
+ ? (Object.hasOwn(PROVIDER_KEY_ALIASES, prevProvider) ? PROVIDER_KEY_ALIASES[prevProvider] : [prevProvider])
66
69
  : [];
67
- const sameFamily = Boolean(prevNorm && (prevNorm === nextNorm || prevAliases.includes(nextNorm)));
70
+ const sameFamily = Boolean(prevProvider && (prevProvider === nextNorm || prevAliases.includes(nextNorm)));
71
+ if (prevProvider !== nextNorm)
72
+ changed = true;
68
73
  config.apiKey = resolveProviderApiKey(config, nextProvider);
69
74
  config.provider = nextProvider;
70
75
  if (!sameFamily && !nextModel) {
@@ -72,8 +77,14 @@ export function applyProviderOverrides(config, providerOverride, modelOverride)
72
77
  }
73
78
  }
74
79
  if (nextModel) {
80
+ if (prevModel !== nextModel)
81
+ changed = true;
75
82
  config.model = nextModel;
76
83
  }
84
+ if (changed) {
85
+ delete config.reasoningEffort;
86
+ delete config.reasoningBudgetTokens;
87
+ }
77
88
  return config;
78
89
  }
79
90
  function configDir() {
@@ -182,6 +193,9 @@ export function loadConfig() {
182
193
  saveConfig(parsed);
183
194
  }
184
195
  }
196
+ if (!normalizePermissionPreset(parsed.permissionPreset) && parsed.autonomyMode) {
197
+ parsed.permissionPreset = autonomyModeToPreset(parsed.autonomyMode);
198
+ }
185
199
  return parsed;
186
200
  }
187
201
  catch (e) {
@@ -193,6 +207,7 @@ export function loadConfig() {
193
207
  provider: envDetected ? envDetected.provider : '',
194
208
  model: envDetected ? envDetected.model : '',
195
209
  apiKey: envDetected ? envDetected.apiKey : '',
210
+ permissionPreset: 'workspace-write',
196
211
  autonomyMode: 'B',
197
212
  tokenBudget: {
198
213
  enabled: false,
package/src/config.ts CHANGED
@@ -5,6 +5,7 @@ import { canonicalModelId } from './modelIds.js';
5
5
  import { DEFAULT_MODEL_BY_PROVIDER } from './modelCatalogue.js';
6
6
  import { causyneHome } from './utils/paths.js';
7
7
  import { listLocalOllamaDiskModels, pickPreferredLocalOllamaModel } from './zeroCostRouting.js';
8
+ import { autonomyModeToPreset, normalizePermissionPreset } from './permissionPresets.js';
8
9
  import {
9
10
  ensureVaultDir,
10
11
  atomicWriteSecretFileSync,
@@ -78,15 +79,18 @@ export function applyProviderOverrides(
78
79
  providerOverride?: string | null,
79
80
  modelOverride?: string | null
80
81
  ): CausyneConfig {
82
+ const prevProvider = typeof config.provider === 'string' ? config.provider.trim().toLowerCase() : '';
83
+ const prevModel = typeof config.model === 'string' ? config.model.trim() : '';
81
84
  const nextProvider = typeof providerOverride === 'string' ? providerOverride.trim() : '';
82
85
  const nextModel = typeof modelOverride === 'string' ? modelOverride.trim() : '';
86
+ let changed = false;
83
87
  if (nextProvider) {
84
- const prevNorm = typeof config.provider === 'string' ? config.provider.trim().toLowerCase() : '';
85
88
  const nextNorm = nextProvider.toLowerCase();
86
- const prevAliases = prevNorm
87
- ? (Object.hasOwn(PROVIDER_KEY_ALIASES, prevNorm) ? PROVIDER_KEY_ALIASES[prevNorm]! : [prevNorm])
89
+ const prevAliases = prevProvider
90
+ ? (Object.hasOwn(PROVIDER_KEY_ALIASES, prevProvider) ? PROVIDER_KEY_ALIASES[prevProvider]! : [prevProvider])
88
91
  : [];
89
- const sameFamily = Boolean(prevNorm && (prevNorm === nextNorm || prevAliases.includes(nextNorm)));
92
+ const sameFamily = Boolean(prevProvider && (prevProvider === nextNorm || prevAliases.includes(nextNorm)));
93
+ if (prevProvider !== nextNorm) changed = true;
90
94
  config.apiKey = resolveProviderApiKey(config, nextProvider);
91
95
  config.provider = nextProvider;
92
96
  if (!sameFamily && !nextModel) {
@@ -94,8 +98,13 @@ export function applyProviderOverrides(
94
98
  }
95
99
  }
96
100
  if (nextModel) {
101
+ if (prevModel !== nextModel) changed = true;
97
102
  config.model = nextModel;
98
103
  }
104
+ if (changed) {
105
+ delete config.reasoningEffort;
106
+ delete config.reasoningBudgetTokens;
107
+ }
99
108
  return config;
100
109
  }
101
110
 
@@ -209,6 +218,10 @@ export function loadConfig(): CausyneConfig {
209
218
  }
210
219
  }
211
220
 
221
+ if (!normalizePermissionPreset(parsed.permissionPreset) && parsed.autonomyMode) {
222
+ parsed.permissionPreset = autonomyModeToPreset(parsed.autonomyMode);
223
+ }
224
+
212
225
  return parsed;
213
226
  } catch (e: unknown) {
214
227
  console.error('Error reading config.json:', e);
@@ -220,6 +233,7 @@ export function loadConfig(): CausyneConfig {
220
233
  provider: envDetected ? envDetected.provider : '',
221
234
  model: envDetected ? envDetected.model : '',
222
235
  apiKey: envDetected ? envDetected.apiKey : '',
236
+ permissionPreset: 'workspace-write',
223
237
  autonomyMode: 'B',
224
238
  tokenBudget: {
225
239
  enabled: false,
@@ -1,12 +1,13 @@
1
1
  /**
2
2
  * @file src/core/contextCompactor.ts
3
- * Enterprise-Grade Context Compactor (OpenAI Codex & Claude Code Architecture).
3
+ * Causyne Agent — Enterprise Structured Context Compactor.
4
4
  *
5
5
  * Provides:
6
6
  * 1. High-fidelity structured state summarization (Goal, Architecture, Files, Milestones, Next Steps).
7
7
  * 2. Non-destructive physical in-place compaction preserving root anchor and recent turns.
8
- * 3. Proactive auto-compaction before context limits or token budgets choke execution.
9
- * 4. User-facing `/compact` slash-command handler.
8
+ * 3. Proactive auto-compaction with output-token reservation and strict shrink verification.
9
+ * 4. Reactive oldest-image offloading to recover cleanly from multimodal context limits.
10
+ * 5. User-facing `/compact` slash-command handler.
10
11
  *
11
12
  * Authorship: Strict TypeScript (Causyne Agent).
12
13
  */
@@ -141,9 +142,9 @@ export function buildCodexStyleSummary(droppedMessages, originalPrompt, extra) {
141
142
  }
142
143
  }
143
144
  }
144
- // Build the Codex-style structured report
145
+ // Build the structured compaction summary report
145
146
  const sections = [];
146
- sections.push('### [COMPACTED CONTEXT CHECKPOINT — CODEX STATE PRESERVATION]');
147
+ sections.push('### [COMPACTED CONTEXT CHECKPOINT — CAUSYNE STATE PRESERVATION]');
147
148
  if (originalPrompt && originalPrompt.trim()) {
148
149
  sections.push(`**Goal & User Intent:**\n${originalPrompt.trim()}`);
149
150
  }
@@ -266,6 +267,50 @@ export function compactSessionMessages(messages, options = {}) {
266
267
  summaryText: fullRecoverableSummary
267
268
  };
268
269
  }
270
+ /**
271
+ * Output-reservation threshold formula: reserves completion output tokens and
272
+ * safety headroom before computing the auto-compaction trigger ceiling.
273
+ */
274
+ export function computeCompactionThresholdChars(maxPoolChars, options = {}) {
275
+ const safePool = Math.max(256, Math.floor(maxPoolChars));
276
+ const fraction = options.thresholdFraction ?? 0.75;
277
+ const reservedChars = Math.max(0, (options.reservedOutputTokens ?? 4_096) * CHARS_PER_TOKEN);
278
+ const headroomChars = Math.max(0, (options.headroomTokens ?? 2_048) * CHARS_PER_TOKEN);
279
+ const byFraction = Math.floor(safePool * fraction);
280
+ const byBudget = safePool > (reservedChars + headroomChars)
281
+ ? Math.max(Math.floor(safePool * 0.45), safePool - reservedChars - headroomChars)
282
+ : byFraction;
283
+ return Math.min(byFraction, byBudget);
284
+ }
285
+ /**
286
+ * Reactively offloads up to `maxToOffload` oldest inline input image blocks
287
+ * (from user or tool messages) into lightweight placeholder text without
288
+ * mutating assistant replies or dropping surrounding conversation text.
289
+ */
290
+ export function offloadOldestInputImages(messages, maxToOffload = 4) {
291
+ let offloadedCount = 0;
292
+ for (let i = 0; i < messages.length && offloadedCount < maxToOffload; i++) {
293
+ const msg = messages[i];
294
+ if (!msg || (msg.role !== 'user' && msg.role !== 'tool') || !Array.isArray(msg.content))
295
+ continue;
296
+ for (let j = 0; j < msg.content.length && offloadedCount < maxToOffload; j++) {
297
+ const part = msg.content[j];
298
+ if (!part || typeof part !== 'object')
299
+ continue;
300
+ const isImage = part.type === 'image_url'
301
+ || part.type === 'image'
302
+ || part.type === 'input_image';
303
+ if (!isImage)
304
+ continue;
305
+ msg.content[j] = {
306
+ type: 'text',
307
+ text: '[Image offloaded to preserve context capacity; re-inspect the workspace file if visual detail is needed.]'
308
+ };
309
+ offloadedCount++;
310
+ }
311
+ }
312
+ return { offloadedCount };
313
+ }
269
314
  /**
270
315
  * Proactively checks memory pressure and runs auto-compaction if context threshold is exceeded.
271
316
  * Operates silently and seamlessly without interrupting active work.
@@ -274,10 +319,12 @@ export function autoCompactIfUnderPressure(loop, options = {}) {
274
319
  if (!loop || !Array.isArray(loop.messages) || loop.messages.length < (options.minMessages ?? 12)) {
275
320
  return null;
276
321
  }
277
- const thresholdFraction = options.thresholdFraction ?? 0.70;
278
322
  const currentChars = measureMessages(loop.messages);
279
323
  const maxPool = loop._contextLimitChars || 120_000;
280
- if (currentChars >= maxPool * thresholdFraction) {
324
+ const triggerChars = computeCompactionThresholdChars(maxPool, {
325
+ thresholdFraction: options.thresholdFraction ?? 0.70
326
+ });
327
+ if (currentChars >= triggerChars) {
281
328
  const result = compactSessionMessages(loop.messages, {
282
329
  keepRecentTurns: 4,
283
330
  taskId: loop.taskId,
@@ -1,12 +1,13 @@
1
1
  /**
2
2
  * @file src/core/contextCompactor.ts
3
- * Enterprise-Grade Context Compactor (OpenAI Codex & Claude Code Architecture).
3
+ * Causyne Agent — Enterprise Structured Context Compactor.
4
4
  *
5
5
  * Provides:
6
6
  * 1. High-fidelity structured state summarization (Goal, Architecture, Files, Milestones, Next Steps).
7
7
  * 2. Non-destructive physical in-place compaction preserving root anchor and recent turns.
8
- * 3. Proactive auto-compaction before context limits or token budgets choke execution.
9
- * 4. User-facing `/compact` slash-command handler.
8
+ * 3. Proactive auto-compaction with output-token reservation and strict shrink verification.
9
+ * 4. Reactive oldest-image offloading to recover cleanly from multimodal context limits.
10
+ * 5. User-facing `/compact` slash-command handler.
10
11
  *
11
12
  * Authorship: Strict TypeScript (Causyne Agent).
12
13
  */
@@ -188,10 +189,10 @@ export function buildCodexStyleSummary(
188
189
  }
189
190
  }
190
191
 
191
- // Build the Codex-style structured report
192
+ // Build the structured compaction summary report
192
193
  const sections: string[] = [];
193
194
 
194
- sections.push('### [COMPACTED CONTEXT CHECKPOINT — CODEX STATE PRESERVATION]');
195
+ sections.push('### [COMPACTED CONTEXT CHECKPOINT — CAUSYNE STATE PRESERVATION]');
195
196
 
196
197
  if (originalPrompt && originalPrompt.trim()) {
197
198
  sections.push(`**Goal & User Intent:**\n${originalPrompt.trim()}`);
@@ -337,6 +338,59 @@ export function compactSessionMessages(
337
338
  };
338
339
  }
339
340
 
341
+ /**
342
+ * Output-reservation threshold formula: reserves completion output tokens and
343
+ * safety headroom before computing the auto-compaction trigger ceiling.
344
+ */
345
+ export function computeCompactionThresholdChars(
346
+ maxPoolChars: number,
347
+ options: {
348
+ thresholdFraction?: number | undefined;
349
+ reservedOutputTokens?: number | undefined;
350
+ headroomTokens?: number | undefined;
351
+ } = {}
352
+ ): number {
353
+ const safePool = Math.max(256, Math.floor(maxPoolChars));
354
+ const fraction = options.thresholdFraction ?? 0.75;
355
+ const reservedChars = Math.max(0, (options.reservedOutputTokens ?? 4_096) * CHARS_PER_TOKEN);
356
+ const headroomChars = Math.max(0, (options.headroomTokens ?? 2_048) * CHARS_PER_TOKEN);
357
+ const byFraction = Math.floor(safePool * fraction);
358
+ const byBudget = safePool > (reservedChars + headroomChars)
359
+ ? Math.max(Math.floor(safePool * 0.45), safePool - reservedChars - headroomChars)
360
+ : byFraction;
361
+ return Math.min(byFraction, byBudget);
362
+ }
363
+
364
+ /**
365
+ * Reactively offloads up to `maxToOffload` oldest inline input image blocks
366
+ * (from user or tool messages) into lightweight placeholder text without
367
+ * mutating assistant replies or dropping surrounding conversation text.
368
+ */
369
+ export function offloadOldestInputImages(
370
+ messages: any[],
371
+ maxToOffload = 4
372
+ ): { offloadedCount: number } {
373
+ let offloadedCount = 0;
374
+ for (let i = 0; i < messages.length && offloadedCount < maxToOffload; i++) {
375
+ const msg = messages[i];
376
+ if (!msg || (msg.role !== 'user' && msg.role !== 'tool') || !Array.isArray(msg.content)) continue;
377
+ for (let j = 0; j < msg.content.length && offloadedCount < maxToOffload; j++) {
378
+ const part = msg.content[j];
379
+ if (!part || typeof part !== 'object') continue;
380
+ const isImage = part.type === 'image_url'
381
+ || part.type === 'image'
382
+ || part.type === 'input_image';
383
+ if (!isImage) continue;
384
+ msg.content[j] = {
385
+ type: 'text',
386
+ text: '[Image offloaded to preserve context capacity; re-inspect the workspace file if visual detail is needed.]'
387
+ };
388
+ offloadedCount++;
389
+ }
390
+ }
391
+ return { offloadedCount };
392
+ }
393
+
340
394
  /**
341
395
  * Proactively checks memory pressure and runs auto-compaction if context threshold is exceeded.
342
396
  * Operates silently and seamlessly without interrupting active work.
@@ -349,11 +403,13 @@ export function autoCompactIfUnderPressure(
349
403
  return null;
350
404
  }
351
405
 
352
- const thresholdFraction = options.thresholdFraction ?? 0.70;
353
406
  const currentChars = measureMessages(loop.messages);
354
407
  const maxPool = loop._contextLimitChars || 120_000;
408
+ const triggerChars = computeCompactionThresholdChars(maxPool, {
409
+ thresholdFraction: options.thresholdFraction ?? 0.70
410
+ });
355
411
 
356
- if (currentChars >= maxPool * thresholdFraction) {
412
+ if (currentChars >= triggerChars) {
357
413
  const result = compactSessionMessages(loop.messages, {
358
414
  keepRecentTurns: 4,
359
415
  taskId: loop.taskId,
@@ -0,0 +1,257 @@
1
+ /**
2
+ * Causyne Agent — Persisted Same-Session Goal Loop State Machine & Tool
3
+ *
4
+ * Implements a CAS-revisioned multi-round goal tracker (`active | paused | blocked | complete`)
5
+ * with strict safety invariants:
6
+ * - Durable state persisted atomically per session under `~/.causyne/goals/`.
7
+ * - Process-local `armed` / `disarmed` activation is NEVER persisted, so resumed
8
+ * or forked sessions never silently auto-drive without human confirmation.
9
+ * - Anti-premature-give-up gate rejects `blocked` before `minRoundsBeforeBlock`
10
+ * (default 3) consecutive rounds have been executed.
11
+ * - Subagents cannot create, pause, or resume top-level user goals.
12
+ */
13
+ import fs from 'node:fs';
14
+ import path from 'node:path';
15
+ import crypto from 'node:crypto';
16
+ import { atomicWriteFileSync } from '../infra/atomicWriter.js';
17
+ import { causyneHome } from '../utils/paths.js';
18
+ import { boundedInteger, sanitizeToolError } from '../tools/toolPathSafety.js';
19
+ const DEFAULT_MAX_ROUNDS = 24;
20
+ const DEFAULT_MIN_ROUNDS_BEFORE_BLOCK = 3;
21
+ const SAFE_SESSION_KEY_RE = /[^a-zA-Z0-9_-]/g;
22
+ // Process-local activation map — intentionally never persisted to disk
23
+ const armedSessions = new Map();
24
+ function goalFilePath(sessionId) {
25
+ const safeId = String(sessionId || 'default').replace(SAFE_SESSION_KEY_RE, '_').slice(0, 80) || 'default';
26
+ return path.join(causyneHome(), 'goals', `${safeId}.json`);
27
+ }
28
+ function readPersistedGoal(sessionId) {
29
+ const filePath = goalFilePath(sessionId);
30
+ if (!fs.existsSync(filePath))
31
+ return null;
32
+ try {
33
+ const stat = fs.lstatSync(filePath);
34
+ if (stat.isSymbolicLink() || !stat.isFile())
35
+ return null;
36
+ const parsed = JSON.parse(fs.readFileSync(filePath, 'utf8'));
37
+ if (!parsed || typeof parsed.id !== 'string' || typeof parsed.objective !== 'string')
38
+ return null;
39
+ return {
40
+ id: parsed.id,
41
+ sessionId: parsed.sessionId || sessionId,
42
+ revision: Number.isInteger(parsed.revision) ? Number(parsed.revision) : 1,
43
+ objective: parsed.objective,
44
+ phase: parsed.phase === 'paused' || parsed.phase === 'blocked' || parsed.phase === 'complete' ? parsed.phase : 'active',
45
+ roundsStarted: Number.isInteger(parsed.roundsStarted) ? Number(parsed.roundsStarted) : 0,
46
+ consecutiveRounds: Number.isInteger(parsed.consecutiveRounds) ? Number(parsed.consecutiveRounds) : 0,
47
+ maxRounds: Number.isInteger(parsed.maxRounds) ? Number(parsed.maxRounds) : DEFAULT_MAX_ROUNDS,
48
+ minRoundsBeforeBlock: Number.isInteger(parsed.minRoundsBeforeBlock) ? Number(parsed.minRoundsBeforeBlock) : DEFAULT_MIN_ROUNDS_BEFORE_BLOCK,
49
+ summary: typeof parsed.summary === 'string' ? parsed.summary : '',
50
+ blocker: typeof parsed.blocker === 'string' ? parsed.blocker : '',
51
+ createdAt: Number(parsed.createdAt || Date.now()),
52
+ updatedAt: Number(parsed.updatedAt || Date.now())
53
+ };
54
+ }
55
+ catch {
56
+ return null;
57
+ }
58
+ }
59
+ function writePersistedGoal(record) {
60
+ const filePath = goalFilePath(record.sessionId);
61
+ fs.mkdirSync(path.dirname(filePath), { recursive: true, mode: 0o700 });
62
+ atomicWriteFileSync(filePath, `${JSON.stringify(record, null, 2)}\n`);
63
+ }
64
+ function attachActivation(record) {
65
+ const armed = armedSessions.get(record.sessionId);
66
+ const isArmed = Boolean(record.phase === 'active'
67
+ && armed
68
+ && armed.goalId === record.id
69
+ && armed.revision === record.revision);
70
+ return { ...record, activation: isArmed ? 'armed' : 'disarmed' };
71
+ }
72
+ export class GoalManager {
73
+ getGoal(sessionId) {
74
+ const rec = readPersistedGoal(sessionId);
75
+ return rec ? attachActivation(rec) : null;
76
+ }
77
+ createGoal(options) {
78
+ const objective = String(options.objective || '').trim();
79
+ if (!objective || objective.length > 4000) {
80
+ throw new Error('Goal objective must contain 1-4000 characters.');
81
+ }
82
+ const now = Date.now();
83
+ const record = {
84
+ id: `goal_${crypto.randomBytes(6).toString('hex')}`,
85
+ sessionId: options.sessionId,
86
+ revision: 1,
87
+ objective,
88
+ phase: 'active',
89
+ roundsStarted: 0,
90
+ consecutiveRounds: 0,
91
+ maxRounds: boundedInteger(options.maxRounds, DEFAULT_MAX_ROUNDS, 1, 256),
92
+ minRoundsBeforeBlock: boundedInteger(options.minRoundsBeforeBlock, DEFAULT_MIN_ROUNDS_BEFORE_BLOCK, 1, 20),
93
+ summary: '',
94
+ blocker: '',
95
+ createdAt: now,
96
+ updatedAt: now
97
+ };
98
+ writePersistedGoal(record);
99
+ if (options.arm !== false) {
100
+ armedSessions.set(record.sessionId, { goalId: record.id, revision: record.revision });
101
+ }
102
+ else {
103
+ armedSessions.delete(record.sessionId);
104
+ }
105
+ return attachActivation(record);
106
+ }
107
+ updateGoal(options) {
108
+ const existing = readPersistedGoal(options.sessionId);
109
+ if (options.action === 'clear') {
110
+ armedSessions.delete(options.sessionId);
111
+ const fp = goalFilePath(options.sessionId);
112
+ if (fs.existsSync(fp))
113
+ fs.unlinkSync(fp);
114
+ return null;
115
+ }
116
+ if (!existing) {
117
+ throw new Error('No active goal exists in this session.');
118
+ }
119
+ if (options.expectedRevision !== undefined && existing.revision !== options.expectedRevision) {
120
+ throw new Error(`Goal revision conflict (expected ${options.expectedRevision}, actual ${existing.revision}).`);
121
+ }
122
+ const next = {
123
+ ...existing,
124
+ revision: existing.revision + 1,
125
+ updatedAt: Date.now()
126
+ };
127
+ if (options.action === 'edit') {
128
+ const objective = String(options.objective || '').trim();
129
+ if (!objective || objective.length > 4000)
130
+ throw new Error('Updated objective must contain 1-4000 characters.');
131
+ next.objective = objective;
132
+ next.consecutiveRounds = 0;
133
+ }
134
+ else if (options.action === 'pause') {
135
+ next.phase = 'paused';
136
+ armedSessions.delete(options.sessionId);
137
+ }
138
+ else if (options.action === 'resume') {
139
+ if (existing.phase === 'paused' && options.isHumanInitiated !== true) {
140
+ throw new Error('GOAL_TOOL_RESUME_PAUSED: Only a direct human turn can resume a paused goal.');
141
+ }
142
+ next.phase = 'active';
143
+ next.blocker = '';
144
+ armedSessions.set(options.sessionId, { goalId: next.id, revision: next.revision });
145
+ }
146
+ else if (options.action === 'advance') {
147
+ if (existing.phase !== 'active')
148
+ throw new Error(`Cannot advance goal in phase "${existing.phase}".`);
149
+ if (existing.roundsStarted >= existing.maxRounds) {
150
+ next.phase = 'blocked';
151
+ next.blocker = `Reached round limit (${existing.maxRounds}).`;
152
+ armedSessions.delete(options.sessionId);
153
+ }
154
+ else {
155
+ next.roundsStarted += 1;
156
+ next.consecutiveRounds += 1;
157
+ armedSessions.set(options.sessionId, { goalId: next.id, revision: next.revision });
158
+ }
159
+ }
160
+ else if (options.action === 'complete') {
161
+ const summary = String(options.summary || '').trim();
162
+ if (!summary)
163
+ throw new Error('Completing a goal requires a grounded verification summary.');
164
+ next.phase = 'complete';
165
+ next.summary = summary.slice(0, 4000);
166
+ next.blocker = '';
167
+ armedSessions.delete(options.sessionId);
168
+ }
169
+ else if (options.action === 'blocked') {
170
+ const blocker = String(options.blocker || '').trim();
171
+ if (!blocker)
172
+ throw new Error('Marking a goal blocked requires a concrete blocker description.');
173
+ if (existing.consecutiveRounds < existing.minRoundsBeforeBlock && options.isHumanInitiated !== true) {
174
+ throw new Error(`GOAL_TOOL_BLOCK_THRESHOLD: Cannot mark goal blocked after only ${existing.consecutiveRounds} round(s); `
175
+ + `at least ${existing.minRoundsBeforeBlock} consecutive rounds are required before giving up.`);
176
+ }
177
+ next.phase = 'blocked';
178
+ next.blocker = blocker.slice(0, 2000);
179
+ armedSessions.delete(options.sessionId);
180
+ }
181
+ writePersistedGoal(next);
182
+ return attachActivation(next);
183
+ }
184
+ }
185
+ export const goalManager = new GoalManager();
186
+ export const goalLoopTool = {
187
+ schema: {
188
+ name: 'goal',
189
+ description: 'Manage a persistent, CAS-revisioned multi-round goal for the current session (status, create, edit, pause, resume, advance, complete, blocked, clear). Enforces anti-premature-block thresholds and non-persisted armed/disarmed activation safety.',
190
+ parameters: {
191
+ type: 'object',
192
+ properties: {
193
+ action: {
194
+ type: 'string',
195
+ enum: ['status', 'create', 'edit', 'pause', 'resume', 'advance', 'complete', 'blocked', 'clear']
196
+ },
197
+ objective: { type: 'string', description: 'Goal objective (required for create/edit).' },
198
+ summary: { type: 'string', description: 'Grounded completion summary with verified evidence (required for complete).' },
199
+ blocker: { type: 'string', description: 'Concrete blocker explanation (required for blocked).' },
200
+ expectedRevision: { type: 'integer', description: 'Optional CAS revision guard.' },
201
+ maxRounds: { type: 'integer', description: 'Maximum autonomous rounds (1-256, default 24).' }
202
+ },
203
+ required: ['action'],
204
+ additionalProperties: false
205
+ }
206
+ },
207
+ async execute(args, context = {}) {
208
+ try {
209
+ if (context.isSubagent) {
210
+ return { success: false, error: 'Subagents cannot mutate top-level session goals.' };
211
+ }
212
+ const sessionId = context.parentLoop?.sessionId || context.parentLoop?.taskId || 'default';
213
+ if (args.action === 'status') {
214
+ const current = goalManager.getGoal(sessionId);
215
+ return {
216
+ success: true,
217
+ goal: current,
218
+ output: current
219
+ ? `Goal ${current.id} (rev ${current.revision}, phase=${current.phase}, ${current.activation}, rounds=${current.roundsStarted}/${current.maxRounds}): ${current.objective}`
220
+ : 'No persisted goal for this session.'
221
+ };
222
+ }
223
+ if (args.action === 'create') {
224
+ const created = goalManager.createGoal({
225
+ sessionId,
226
+ objective: args.objective || '',
227
+ maxRounds: args.maxRounds
228
+ });
229
+ return {
230
+ success: true,
231
+ goal: created,
232
+ output: `Created goal ${created.id} (rev ${created.revision}, armed): ${created.objective}`
233
+ };
234
+ }
235
+ const updated = goalManager.updateGoal({
236
+ sessionId,
237
+ action: args.action,
238
+ expectedRevision: args.expectedRevision,
239
+ objective: args.objective,
240
+ summary: args.summary,
241
+ blocker: args.blocker,
242
+ isHumanInitiated: false
243
+ });
244
+ if (!updated) {
245
+ return { success: true, goal: null, output: 'Cleared session goal.' };
246
+ }
247
+ return {
248
+ success: true,
249
+ goal: updated,
250
+ output: `Updated goal ${updated.id} -> phase=${updated.phase} (rev ${updated.revision}, rounds=${updated.roundsStarted}/${updated.maxRounds})`
251
+ };
252
+ }
253
+ catch (error) {
254
+ return { success: false, error: sanitizeToolError(error) };
255
+ }
256
+ }
257
+ };