@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.
- package/bin/causyne.js +1 -1
- package/docs/THIRD_PARTY_NOTICES.md +36 -2
- package/package.json +6 -4
- package/src/acp/protocol.ts +19 -1
- package/src/acp/server.js +282 -8
- package/src/acp/server.ts +284 -8
- package/src/agent/abortableDelay.js +2 -2
- package/src/agent/abortableDelay.ts +2 -2
- package/src/agent/errorClassifier.js +9 -1
- package/src/agent/errorClassifier.ts +8 -1
- package/src/agentLoop.js +142 -53
- package/src/agentLoop.ts +151 -50
- package/src/approvalPolicy.js +34 -10
- package/src/approvalPolicy.ts +42 -11
- package/src/browser/causyneBrowser.js +61 -3
- package/src/browser/causyneBrowser.ts +65 -3
- package/src/browser/urlPolicy.js +14 -1
- package/src/browser/urlPolicy.ts +12 -1
- package/src/cliMode.js +21 -9
- package/src/cliMode.ts +20 -8
- package/src/commands.js +365 -45
- package/src/commands.ts +403 -45
- package/src/config.js +19 -4
- package/src/config.ts +18 -4
- package/src/core/contextCompactor.js +54 -7
- package/src/core/contextCompactor.ts +63 -7
- package/src/core/goalLoop.js +257 -0
- package/src/core/goalLoop.ts +310 -0
- package/src/entrypoint.js +135 -3
- package/src/entrypoint.ts +136 -3
- package/src/game/causyneCoreBridge.js +686 -0
- package/src/game/causyneCoreBridge.ts +702 -0
- package/src/game/gameLauncher.js +287 -0
- package/src/game/gameLauncher.ts +352 -0
- package/src/game/gameProvisioner.js +425 -0
- package/src/game/gameProvisioner.ts +488 -0
- package/src/headlessCli.js +19 -12
- package/src/headlessCli.ts +22 -8
- package/src/infra/atomicWriter.js +40 -4
- package/src/infra/atomicWriter.ts +36 -4
- package/src/launchIntent.js +73 -3
- package/src/launchIntent.ts +76 -3
- package/src/lsp/lspClient.js +83 -12
- package/src/lsp/lspClient.ts +75 -12
- package/src/mcp/mcpRegistry.js +75 -8
- package/src/mcp/mcpRegistry.ts +70 -7
- package/src/memory/contextBudget.js +2 -0
- package/src/memory/contextBudget.ts +1 -0
- package/src/memory/episodicStore.js +40 -0
- package/src/memory/episodicStore.ts +46 -0
- package/src/memory.js +67 -0
- package/src/memory.ts +65 -0
- package/src/modelVariants.js +45 -0
- package/src/modelVariants.ts +54 -0
- package/src/outputRecovery.js +3 -2
- package/src/outputRecovery.ts +4 -2
- package/src/permissionPresets.js +327 -0
- package/src/permissionPresets.ts +361 -0
- package/src/personalization.js +365 -0
- package/src/personalization.ts +471 -0
- package/src/projectInstructions.js +30 -10
- package/src/projectInstructions.ts +31 -12
- package/src/providers/acp.js +3 -2
- package/src/providers/acp.ts +3 -2
- package/src/providers/antigravity.js +64 -9
- package/src/providers/antigravity.ts +75 -9
- package/src/providers/byokHttp.js +7 -1
- package/src/providers/byokHttp.ts +6 -1
- package/src/providers/byokStream.js +21 -8
- package/src/providers/byokStream.ts +17 -7
- package/src/providers/dashscope-byok.js +21 -5
- package/src/providers/dashscope-byok.ts +29 -11
- package/src/providers/moonshot.js +26 -7
- package/src/providers/moonshot.ts +34 -13
- package/src/providers/muse.js +6 -0
- package/src/providers/muse.ts +8 -0
- package/src/providers/ollama.js +39 -7
- package/src/providers/ollama.ts +36 -7
- package/src/providers/openai-compatible.js +16 -3
- package/src/providers/openai-compatible.ts +13 -3
- package/src/providers/openai.js +62 -4
- package/src/providers/openai.ts +50 -4
- package/src/providers/openrouter.js +19 -4
- package/src/providers/openrouter.ts +21 -4
- package/src/providers/qwen-byok.js +21 -5
- package/src/providers/qwen-byok.ts +29 -11
- package/src/providers/xai.js +26 -10
- package/src/providers/xai.ts +34 -16
- package/src/reporting.js +4 -2
- package/src/reporting.ts +4 -2
- package/src/sandbox.js +34 -0
- package/src/sandbox.ts +43 -0
- package/src/scheduler/scheduler.js +372 -0
- package/src/scheduler/scheduler.ts +433 -0
- package/src/sessionSearchIndex.js +267 -0
- package/src/sessionSearchIndex.ts +311 -0
- package/src/skillsManager.js +2 -3
- package/src/skillsManager.ts +2 -3
- package/src/toolPacks.js +6 -0
- package/src/toolPacks.ts +6 -0
- package/src/tools/applyPatch.js +1 -1
- package/src/tools/applyPatch.ts +1 -1
- package/src/tools/generateMediaViaApi.js +4 -3
- package/src/tools/generateMediaViaApi.ts +4 -3
- package/src/tools/memoryWrite.js +15 -1
- package/src/tools/memoryWrite.ts +16 -1
- package/src/tools/nativeEngine.js +2 -2
- package/src/tools/nativeEngine.ts +2 -2
- package/src/tools/openSourceToolProvisioner.js +2 -2
- package/src/tools/openSourceToolProvisioner.ts +2 -2
- package/src/tools/osSandbox.js +1 -1
- package/src/tools/osSandbox.ts +1 -1
- package/src/tools/payloadSanitizer.js +0 -1
- package/src/tools/payloadSanitizer.ts +0 -1
- package/src/tools/pdfReader.js +122 -20
- package/src/tools/pdfReader.ts +111 -20
- package/src/tools/presentDeliverable.js +103 -0
- package/src/tools/presentDeliverable.ts +127 -0
- package/src/tools/ptcRuntime.js +444 -0
- package/src/tools/ptcRuntime.ts +490 -0
- package/src/tools/ptyTerminal.js +1108 -0
- package/src/tools/ptyTerminal.ts +1245 -0
- package/src/tools/registry.js +21 -12
- package/src/tools/registry.ts +21 -12
- package/src/tools/toolOutputStore.js +26 -4
- package/src/tools/toolOutputStore.ts +22 -4
- package/src/tools/webFetch.js +158 -11
- package/src/tools/webFetch.ts +145 -11
- package/src/tools/webSearch.js +123 -36
- package/src/tools/webSearch.ts +124 -33
- package/src/tui/banner.js +5 -1
- package/src/tui/banner.ts +6 -1
- package/src/tui/chatRenderer.js +1 -2
- package/src/tui/chatRenderer.ts +1 -2
- package/src/tui/completion.js +1 -0
- package/src/tui/completion.ts +1 -0
- package/src/tui/composerControls.js +111 -27
- package/src/tui/composerControls.ts +124 -28
- package/src/tui/dialogs.js +3 -16
- package/src/tui/dialogs.ts +3 -16
- package/src/tui/home.js +1 -0
- package/src/tui/home.ts +1 -0
- package/src/tui/invocation.js +1 -2
- package/src/tui/invocation.ts +1 -2
- package/src/tui/modelPicker.js +22 -12
- package/src/tui/modelPicker.ts +22 -12
- package/src/tui/overlay.js +2 -5
- package/src/tui/overlay.ts +2 -5
- package/src/tui/prompt.js +6 -4
- package/src/tui/prompt.ts +6 -4
- package/src/tui/selectList.js +4 -12
- package/src/tui/selectList.ts +4 -12
- package/src/tui/setup.js +22 -9
- package/src/tui/setup.ts +26 -9
- package/src/tui/statusLine.ts +2 -0
- package/src/web/client/browserPanel.js +905 -0
- package/src/web/client/browserPanel.ts +872 -0
- package/src/web/client/chatStream.js +321 -0
- package/src/web/client/chatStream.ts +297 -0
- package/src/web/client/cliPanel.js +165 -0
- package/src/web/client/cliPanel.ts +171 -0
- package/src/web/client/composer.js +204 -0
- package/src/web/client/composer.ts +209 -0
- package/src/web/client/diffPanel.js +176 -0
- package/src/web/client/diffPanel.ts +203 -0
- package/src/web/client/dom.js +271 -0
- package/src/web/client/dom.ts +272 -0
- package/src/web/client/filesAndCanvas.js +233 -0
- package/src/web/client/filesAndCanvas.ts +240 -0
- package/src/web/client/gameLauncherUi.js +78 -0
- package/src/web/client/gameLauncherUi.ts +78 -0
- package/src/web/client/main.js +316 -0
- package/src/web/client/main.ts +391 -0
- package/src/web/client/markdown.js +364 -0
- package/src/web/client/markdown.ts +373 -0
- package/src/web/client/modelPicker.js +455 -0
- package/src/web/client/modelPicker.ts +451 -0
- package/src/web/client/permissionPresetsUi.js +307 -0
- package/src/web/client/permissionPresetsUi.ts +333 -0
- package/src/web/client/sessions.js +353 -0
- package/src/web/client/sessions.ts +372 -0
- package/src/web/client/settingsModal.js +824 -0
- package/src/web/client/settingsModal.ts +959 -0
- package/src/web/client/state.js +280 -0
- package/src/web/client/state.ts +259 -0
- package/src/web/client/streamSmoother.js +127 -0
- package/src/web/client/streamSmoother.ts +119 -0
- package/src/web/client/studioLayout.js +89 -0
- package/src/web/client/studioLayout.ts +103 -0
- package/src/web/client/studioShell.js +660 -0
- package/src/web/client/studioShell.ts +672 -0
- package/src/web/client/studioStart.js +77 -0
- package/src/web/client/studioStart.ts +89 -0
- package/src/web/client/terminalPanel.js +606 -0
- package/src/web/client/terminalPanel.ts +632 -0
- package/src/web/client/terminalTheme.js +249 -0
- package/src/web/client/terminalTheme.ts +258 -0
- package/src/web/client/turnView.js +934 -0
- package/src/web/client/turnView.ts +981 -0
- package/src/web/client/types.js +1 -0
- package/src/web/client/types.ts +322 -0
- package/src/web/client/validators.js +147 -0
- package/src/web/client/validators.ts +140 -0
- package/src/web/server/activeRuns.js +152 -0
- package/src/web/server/activeRuns.ts +171 -0
- package/src/web/server/routesBrowser.js +409 -0
- package/src/web/server/routesBrowser.ts +435 -0
- package/src/web/server/routesChat.js +304 -0
- package/src/web/server/routesChat.ts +347 -0
- package/src/web/server/routesCore.js +472 -0
- package/src/web/server/routesCore.ts +522 -0
- package/src/web/server/routesSettings.js +344 -0
- package/src/web/server/routesSettings.ts +397 -0
- package/src/web/server/routesTerminal.js +162 -0
- package/src/web/server/routesTerminal.ts +182 -0
- package/src/web/server/routesWorkspace.js +510 -0
- package/src/web/server/routesWorkspace.ts +546 -0
- package/src/web/server/security.js +98 -0
- package/src/web/server/security.ts +108 -0
- package/src/web/server/sessionTranscript.js +586 -0
- package/src/web/server/sessionTranscript.ts +566 -0
- package/src/web/server/staticAssets.js +104 -0
- package/src/web/server/staticAssets.ts +116 -0
- package/src/web/server/types.js +1 -0
- package/src/web/server/types.ts +135 -0
- package/src/web/server/workspaceFiles.js +368 -0
- package/src/web/server/workspaceFiles.ts +363 -0
- package/src/web/skybridgeServer.js +78 -2448
- package/src/web/skybridgeServer.ts +120 -2600
- package/src/web/skybridgeUi.js +20 -450
- package/src/web/skybridgeUi.ts +24 -455
- package/src/web/styles/agent.css +380 -0
- package/src/web/styles/composer.css +193 -0
- package/src/web/styles/overlays.css +935 -0
- package/src/web/styles/shell.css +387 -0
- package/src/web/styles/studio.css +951 -0
- package/src/web/styles/thread.css +221 -0
- package/src/web/styles/tokens.css +94 -0
- package/src/web/ui/brandMark.js +73 -0
- package/src/web/ui/brandMark.ts +82 -0
- package/src/web/ui/modalsTemplate.js +388 -0
- package/src/web/ui/modalsTemplate.ts +388 -0
- package/src/web/ui/sidebarTemplate.js +63 -0
- package/src/web/ui/sidebarTemplate.ts +64 -0
- package/src/web/ui/studioTemplate.js +256 -0
- package/src/web/ui/studioTemplate.ts +256 -0
- package/src/web/ui/workspaceTemplate.js +72 -0
- package/src/web/ui/workspaceTemplate.ts +73 -0
- package/src/worktreeManager.js +16 -1
- package/src/worktreeManager.ts +22 -1
- package/src/web/skybridgeClientScript.js +0 -3951
- package/src/web/skybridgeClientScript.ts +0 -3952
- package/src/web/skybridgeStyles.js +0 -827
- package/src/web/skybridgeStyles.ts +0 -828
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 =
|
|
87
|
-
? (Object.hasOwn(PROVIDER_KEY_ALIASES,
|
|
89
|
+
const prevAliases = prevProvider
|
|
90
|
+
? (Object.hasOwn(PROVIDER_KEY_ALIASES, prevProvider) ? PROVIDER_KEY_ALIASES[prevProvider]! : [prevProvider])
|
|
88
91
|
: [];
|
|
89
|
-
const sameFamily = Boolean(
|
|
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
|
-
*
|
|
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
|
|
9
|
-
* 4.
|
|
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
|
|
145
|
+
// Build the structured compaction summary report
|
|
145
146
|
const sections = [];
|
|
146
|
-
sections.push('### [COMPACTED CONTEXT CHECKPOINT —
|
|
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
|
-
|
|
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
|
-
*
|
|
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
|
|
9
|
-
* 4.
|
|
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
|
|
192
|
+
// Build the structured compaction summary report
|
|
192
193
|
const sections: string[] = [];
|
|
193
194
|
|
|
194
|
-
sections.push('### [COMPACTED CONTEXT CHECKPOINT —
|
|
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 >=
|
|
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
|
+
};
|