actoviq-agent-sdk 0.4.7 → 0.4.8
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/CHANGELOG.md +17 -1
- package/README-zh.md +8 -5
- package/README.md +9 -6
- package/assets/actoviq-icon.png +0 -0
- package/dist/src/browser/actoviqBrowserSession.d.ts +137 -0
- package/dist/src/browser/actoviqBrowserSession.d.ts.map +1 -0
- package/dist/src/browser/actoviqBrowserSession.js +623 -0
- package/dist/src/browser/actoviqBrowserSession.js.map +1 -0
- package/dist/src/browser/actoviqBrowserTools.d.ts +80 -0
- package/dist/src/browser/actoviqBrowserTools.d.ts.map +1 -0
- package/dist/src/browser/actoviqBrowserTools.js +177 -0
- package/dist/src/browser/actoviqBrowserTools.js.map +1 -0
- package/dist/src/browser/browserSettings.d.ts +8 -0
- package/dist/src/browser/browserSettings.d.ts.map +1 -0
- package/dist/src/browser/browserSettings.js +47 -0
- package/dist/src/browser/browserSettings.js.map +1 -0
- package/dist/src/cli/actoviq-react.js +144 -4
- package/dist/src/cli/actoviq-react.js.map +1 -1
- package/dist/src/computer/actoviqComputerUse.d.ts.map +1 -1
- package/dist/src/computer/actoviqComputerUse.js +226 -40
- package/dist/src/computer/actoviqComputerUse.js.map +1 -1
- package/dist/src/computer/e2bComputerUse.d.ts +57 -0
- package/dist/src/computer/e2bComputerUse.d.ts.map +1 -0
- package/dist/src/computer/e2bComputerUse.js +401 -0
- package/dist/src/computer/e2bComputerUse.js.map +1 -0
- package/dist/src/config/agentProfiles.d.ts +8 -1
- package/dist/src/config/agentProfiles.d.ts.map +1 -1
- package/dist/src/config/agentProfiles.js +86 -4
- package/dist/src/config/agentProfiles.js.map +1 -1
- package/dist/src/config/projectSessionDirectory.d.ts +22 -0
- package/dist/src/config/projectSessionDirectory.d.ts.map +1 -1
- package/dist/src/config/projectSessionDirectory.js +512 -46
- package/dist/src/config/projectSessionDirectory.js.map +1 -1
- package/dist/src/config/resolveRuntimeConfig.d.ts.map +1 -1
- package/dist/src/config/resolveRuntimeConfig.js +12 -7
- package/dist/src/config/resolveRuntimeConfig.js.map +1 -1
- package/dist/src/gui/actoviqGui.d.ts +3 -0
- package/dist/src/gui/actoviqGui.d.ts.map +1 -1
- package/dist/src/gui/actoviqGui.js +7247 -997
- package/dist/src/gui/actoviqGui.js.map +1 -1
- package/dist/src/gui/electronMain.js +21 -4
- package/dist/src/gui/electronMain.js.map +1 -1
- package/dist/src/gui/externalCliAgentMonitor.d.ts +15 -0
- package/dist/src/gui/externalCliAgentMonitor.d.ts.map +1 -0
- package/dist/src/gui/externalCliAgentMonitor.js +133 -0
- package/dist/src/gui/externalCliAgentMonitor.js.map +1 -0
- package/dist/src/gui/projectWorkbench.d.ts +2 -0
- package/dist/src/gui/projectWorkbench.d.ts.map +1 -1
- package/dist/src/gui/projectWorkbench.js +66 -1
- package/dist/src/gui/projectWorkbench.js.map +1 -1
- package/dist/src/gui/transcript/clientBundle.d.ts.map +1 -1
- package/dist/src/gui/transcript/clientBundle.js +157 -17
- package/dist/src/gui/transcript/clientBundle.js.map +1 -1
- package/dist/src/gui/transcript/parts.d.ts.map +1 -1
- package/dist/src/gui/transcript/parts.js +28 -0
- package/dist/src/gui/transcript/parts.js.map +1 -1
- package/dist/src/index.d.ts +36 -3
- package/dist/src/index.d.ts.map +1 -1
- package/dist/src/index.js +22 -2
- package/dist/src/index.js.map +1 -1
- package/dist/src/parity/actoviqBridgeSdk.d.ts +13 -1
- package/dist/src/parity/actoviqBridgeSdk.d.ts.map +1 -1
- package/dist/src/parity/actoviqBridgeSdk.js +1022 -83
- package/dist/src/parity/actoviqBridgeSdk.js.map +1 -1
- package/dist/src/parity/bridgeConfigs.d.ts +15 -0
- package/dist/src/parity/bridgeConfigs.d.ts.map +1 -1
- package/dist/src/parity/bridgeConfigs.js +112 -3
- package/dist/src/parity/bridgeConfigs.js.map +1 -1
- package/dist/src/parity/bridgeEventAdapter.d.ts +5 -1
- package/dist/src/parity/bridgeEventAdapter.d.ts.map +1 -1
- package/dist/src/parity/bridgeEventAdapter.js +65 -12
- package/dist/src/parity/bridgeEventAdapter.js.map +1 -1
- package/dist/src/parity/bridgeExecResolver.d.ts +10 -11
- package/dist/src/parity/bridgeExecResolver.d.ts.map +1 -1
- package/dist/src/parity/bridgeExecResolver.js +40 -23
- package/dist/src/parity/bridgeExecResolver.js.map +1 -1
- package/dist/src/parity/bridgeProcessTree.d.ts +3 -0
- package/dist/src/parity/bridgeProcessTree.d.ts.map +1 -0
- package/dist/src/parity/bridgeProcessTree.js +83 -0
- package/dist/src/parity/bridgeProcessTree.js.map +1 -0
- package/dist/src/parity/bridgeProviders.d.ts +16 -2
- package/dist/src/parity/bridgeProviders.d.ts.map +1 -1
- package/dist/src/parity/bridgeProviders.js +482 -100
- package/dist/src/parity/bridgeProviders.js.map +1 -1
- package/dist/src/parity/codewhaleRuntimeAdapter.d.ts +18 -0
- package/dist/src/parity/codewhaleRuntimeAdapter.d.ts.map +1 -0
- package/dist/src/parity/codewhaleRuntimeAdapter.js +350 -0
- package/dist/src/parity/codewhaleRuntimeAdapter.js.map +1 -0
- package/dist/src/parity/crushManagedClient.d.ts +84 -0
- package/dist/src/parity/crushManagedClient.d.ts.map +1 -0
- package/dist/src/parity/crushManagedClient.js +978 -0
- package/dist/src/parity/crushManagedClient.js.map +1 -0
- package/dist/src/parity/crushSessionHistory.d.ts +53 -0
- package/dist/src/parity/crushSessionHistory.d.ts.map +1 -0
- package/dist/src/parity/crushSessionHistory.js +358 -0
- package/dist/src/parity/crushSessionHistory.js.map +1 -0
- package/dist/src/parity/externalCliAuth.d.ts +23 -0
- package/dist/src/parity/externalCliAuth.d.ts.map +1 -0
- package/dist/src/parity/externalCliAuth.js +268 -0
- package/dist/src/parity/externalCliAuth.js.map +1 -0
- package/dist/src/parity/externalCliRuntimeManager.d.ts +138 -0
- package/dist/src/parity/externalCliRuntimeManager.d.ts.map +1 -0
- package/dist/src/parity/externalCliRuntimeManager.js +527 -0
- package/dist/src/parity/externalCliRuntimeManager.js.map +1 -0
- package/dist/src/parity/externalCliSessions.d.ts +90 -0
- package/dist/src/parity/externalCliSessions.d.ts.map +1 -0
- package/dist/src/parity/externalCliSessions.js +1436 -0
- package/dist/src/parity/externalCliSessions.js.map +1 -0
- package/dist/src/parity/reasonixAcpSession.d.ts +35 -0
- package/dist/src/parity/reasonixAcpSession.d.ts.map +1 -0
- package/dist/src/parity/reasonixAcpSession.js +472 -0
- package/dist/src/parity/reasonixAcpSession.js.map +1 -0
- package/dist/src/parity/reasonixManagedClient.d.ts +56 -0
- package/dist/src/parity/reasonixManagedClient.d.ts.map +1 -0
- package/dist/src/parity/reasonixManagedClient.js +293 -0
- package/dist/src/parity/reasonixManagedClient.js.map +1 -0
- package/dist/src/parity/reasonixSessionParser.d.ts +50 -0
- package/dist/src/parity/reasonixSessionParser.d.ts.map +1 -0
- package/dist/src/parity/reasonixSessionParser.js +440 -0
- package/dist/src/parity/reasonixSessionParser.js.map +1 -0
- package/dist/src/plugins/githubPlugin.d.ts +64 -0
- package/dist/src/plugins/githubPlugin.d.ts.map +1 -0
- package/dist/src/plugins/githubPlugin.js +261 -0
- package/dist/src/plugins/githubPlugin.js.map +1 -0
- package/dist/src/plugins/kimiWebBridgePlugin.d.ts +32 -0
- package/dist/src/plugins/kimiWebBridgePlugin.d.ts.map +1 -0
- package/dist/src/plugins/kimiWebBridgePlugin.js +214 -0
- package/dist/src/plugins/kimiWebBridgePlugin.js.map +1 -0
- package/dist/src/plugins/managedPluginCatalog.d.ts +47 -0
- package/dist/src/plugins/managedPluginCatalog.d.ts.map +1 -0
- package/dist/src/plugins/managedPluginCatalog.js +399 -0
- package/dist/src/plugins/managedPluginCatalog.js.map +1 -0
- package/dist/src/plugins/managedPluginHealth.d.ts +9 -0
- package/dist/src/plugins/managedPluginHealth.d.ts.map +1 -0
- package/dist/src/plugins/managedPluginHealth.js +149 -0
- package/dist/src/plugins/managedPluginHealth.js.map +1 -0
- package/dist/src/plugins/managedPluginRuntime.d.ts +14 -0
- package/dist/src/plugins/managedPluginRuntime.d.ts.map +1 -0
- package/dist/src/plugins/managedPluginRuntime.js +331 -0
- package/dist/src/plugins/managedPluginRuntime.js.map +1 -0
- package/dist/src/plugins/ocrPlugin.d.ts +46 -0
- package/dist/src/plugins/ocrPlugin.d.ts.map +1 -0
- package/dist/src/plugins/ocrPlugin.js +464 -0
- package/dist/src/plugins/ocrPlugin.js.map +1 -0
- package/dist/src/provider/client.d.ts +7 -1
- package/dist/src/provider/client.d.ts.map +1 -1
- package/dist/src/provider/client.js +61 -6
- package/dist/src/provider/client.js.map +1 -1
- package/dist/src/provider/openai-client.d.ts.map +1 -1
- package/dist/src/provider/openai-client.js +49 -3
- package/dist/src/provider/openai-client.js.map +1 -1
- package/dist/src/runtime/actoviqAgentExecutions.d.ts +85 -0
- package/dist/src/runtime/actoviqAgentExecutions.d.ts.map +1 -0
- package/dist/src/runtime/actoviqAgentExecutions.js +479 -0
- package/dist/src/runtime/actoviqAgentExecutions.js.map +1 -0
- package/dist/src/runtime/actoviqAgents.d.ts +15 -12
- package/dist/src/runtime/actoviqAgents.d.ts.map +1 -1
- package/dist/src/runtime/actoviqAgents.js +15 -0
- package/dist/src/runtime/actoviqAgents.js.map +1 -1
- package/dist/src/runtime/actoviqBackgroundTasks.d.ts +17 -2
- package/dist/src/runtime/actoviqBackgroundTasks.d.ts.map +1 -1
- package/dist/src/runtime/actoviqBackgroundTasks.js +291 -104
- package/dist/src/runtime/actoviqBackgroundTasks.js.map +1 -1
- package/dist/src/runtime/actoviqCompact.d.ts.map +1 -1
- package/dist/src/runtime/actoviqCompact.js +10 -75
- package/dist/src/runtime/actoviqCompact.js.map +1 -1
- package/dist/src/runtime/actoviqSkills.d.ts +14 -1
- package/dist/src/runtime/actoviqSkills.d.ts.map +1 -1
- package/dist/src/runtime/actoviqSkills.js +27 -2
- package/dist/src/runtime/actoviqSkills.js.map +1 -1
- package/dist/src/runtime/agentClient.d.ts +16 -2
- package/dist/src/runtime/agentClient.d.ts.map +1 -1
- package/dist/src/runtime/agentClient.js +745 -207
- package/dist/src/runtime/agentClient.js.map +1 -1
- package/dist/src/runtime/agentExecution.d.ts +196 -0
- package/dist/src/runtime/agentExecution.d.ts.map +1 -0
- package/dist/src/runtime/agentExecution.js +360 -0
- package/dist/src/runtime/agentExecution.js.map +1 -0
- package/dist/src/runtime/agentRuntimeDiscovery.d.ts +8 -2
- package/dist/src/runtime/agentRuntimeDiscovery.d.ts.map +1 -1
- package/dist/src/runtime/agentRuntimeDiscovery.js +30 -18
- package/dist/src/runtime/agentRuntimeDiscovery.js.map +1 -1
- package/dist/src/runtime/conversationEngine.d.ts +2 -1
- package/dist/src/runtime/conversationEngine.d.ts.map +1 -1
- package/dist/src/runtime/conversationEngine.js +66 -50
- package/dist/src/runtime/conversationEngine.js.map +1 -1
- package/dist/src/runtime/externalSkillCatalog.d.ts +107 -0
- package/dist/src/runtime/externalSkillCatalog.d.ts.map +1 -0
- package/dist/src/runtime/externalSkillCatalog.js +895 -0
- package/dist/src/runtime/externalSkillCatalog.js.map +1 -0
- package/dist/src/runtime/externalSkillPreferences.d.ts +25 -0
- package/dist/src/runtime/externalSkillPreferences.d.ts.map +1 -0
- package/dist/src/runtime/externalSkillPreferences.js +132 -0
- package/dist/src/runtime/externalSkillPreferences.js.map +1 -0
- package/dist/src/runtime/externalSkillRuntime.d.ts +31 -0
- package/dist/src/runtime/externalSkillRuntime.d.ts.map +1 -0
- package/dist/src/runtime/externalSkillRuntime.js +129 -0
- package/dist/src/runtime/externalSkillRuntime.js.map +1 -0
- package/dist/src/runtime/sessionTurnCoordinator.d.ts +2 -2
- package/dist/src/runtime/sessionTurnCoordinator.js +2 -2
- package/dist/src/storage/agentExecutionStore.d.ts +31 -0
- package/dist/src/storage/agentExecutionStore.d.ts.map +1 -0
- package/dist/src/storage/agentExecutionStore.js +413 -0
- package/dist/src/storage/agentExecutionStore.js.map +1 -0
- package/dist/src/storage/backgroundTaskStore.d.ts +5 -0
- package/dist/src/storage/backgroundTaskStore.d.ts.map +1 -1
- package/dist/src/storage/backgroundTaskStore.js +79 -3
- package/dist/src/storage/backgroundTaskStore.js.map +1 -1
- package/dist/src/storage/sessionStore.d.ts +8 -0
- package/dist/src/storage/sessionStore.d.ts.map +1 -1
- package/dist/src/storage/sessionStore.js +134 -18
- package/dist/src/storage/sessionStore.js.map +1 -1
- package/dist/src/team/teamGraphLayout.d.ts +53 -1
- package/dist/src/team/teamGraphLayout.d.ts.map +1 -1
- package/dist/src/team/teamGraphLayout.js +127 -1
- package/dist/src/team/teamGraphLayout.js.map +1 -1
- package/dist/src/team/teamGraphScaffold.d.ts.map +1 -1
- package/dist/src/team/teamGraphScaffold.js +31 -0
- package/dist/src/team/teamGraphScaffold.js.map +1 -1
- package/dist/src/team/teamGraphV3.d.ts +1 -0
- package/dist/src/team/teamGraphV3.d.ts.map +1 -1
- package/dist/src/team/teamGraphV3.js +24 -5
- package/dist/src/team/teamGraphV3.js.map +1 -1
- package/dist/src/team/teamPropose.d.ts +19 -0
- package/dist/src/team/teamPropose.d.ts.map +1 -0
- package/dist/src/team/teamPropose.js +126 -0
- package/dist/src/team/teamPropose.js.map +1 -0
- package/dist/src/tools/actoviqCoreTools.d.ts.map +1 -1
- package/dist/src/tools/actoviqCoreTools.js +3 -1
- package/dist/src/tools/actoviqCoreTools.js.map +1 -1
- package/dist/src/tools/exaSearch.d.ts +56 -0
- package/dist/src/tools/exaSearch.d.ts.map +1 -0
- package/dist/src/tools/exaSearch.js +170 -0
- package/dist/src/tools/exaSearch.js.map +1 -0
- package/dist/src/tools/tavilySearch.d.ts +34 -1
- package/dist/src/tools/tavilySearch.d.ts.map +1 -1
- package/dist/src/tools/tavilySearch.js +69 -54
- package/dist/src/tools/tavilySearch.js.map +1 -1
- package/dist/src/tools/todo/TodoWriteTool.d.ts +1 -1
- package/dist/src/tui/actoviqTui.d.ts +3 -1
- package/dist/src/tui/actoviqTui.d.ts.map +1 -1
- package/dist/src/tui/actoviqTui.js +1208 -92
- package/dist/src/tui/actoviqTui.js.map +1 -1
- package/dist/src/types.d.ts +223 -14
- package/dist/src/types.d.ts.map +1 -1
- package/dist/src/types.js.map +1 -1
- package/dist/src/ui/agentExecutionView.d.ts +111 -0
- package/dist/src/ui/agentExecutionView.d.ts.map +1 -0
- package/dist/src/ui/agentExecutionView.js +442 -0
- package/dist/src/ui/agentExecutionView.js.map +1 -0
- package/dist/src/ui/commandSurface.d.ts +2 -0
- package/dist/src/ui/commandSurface.d.ts.map +1 -1
- package/dist/src/ui/commandSurface.js +38 -3
- package/dist/src/ui/commandSurface.js.map +1 -1
- package/dist/src/workflow-v2/localIsolatedProcessExecutor.d.ts.map +1 -1
- package/dist/src/workflow-v2/localIsolatedProcessExecutor.js +6 -2
- package/dist/src/workflow-v2/localIsolatedProcessExecutor.js.map +1 -1
- package/package.json +35 -7
|
@@ -1,18 +1,55 @@
|
|
|
1
1
|
import { spawn } from 'node:child_process';
|
|
2
|
-
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
3
|
+
import { chmod, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
|
|
4
|
+
import os from 'node:os';
|
|
3
5
|
import path from 'node:path';
|
|
4
6
|
import readline from 'node:readline';
|
|
5
7
|
import { fileURLToPath } from 'node:url';
|
|
6
8
|
import { createActoviqBuddyApi } from '../buddy/actoviqBuddy.js';
|
|
7
|
-
import { findExecutableOnPath, findFirstExistingPath, isExecutable, IS_WINDOWS, pathExists,
|
|
9
|
+
import { findExecutableOnPath, findFirstExistingPath, isExecutable, IS_WINDOWS, pathExists, resolveExecutableInvocation, } from './bridgeExecResolver.js';
|
|
8
10
|
import { resolveProvider } from './bridgeProviders.js';
|
|
11
|
+
import { terminateManagedProcessTree as terminateActoviqProcessTree } from './bridgeProcessTree.js';
|
|
12
|
+
import { runCrushManaged } from './crushManagedClient.js';
|
|
13
|
+
import { namedExternalCliManagedProfileId, resolveCodewhaleNativeSessionId, } from './externalCliSessions.js';
|
|
14
|
+
import { createReasonixManagedClient, } from './reasonixManagedClient.js';
|
|
9
15
|
import { getLoadedJsonConfig } from '../config/loadJsonConfigFile.js';
|
|
16
|
+
import { resolveActoviqHome } from '../config/actoviqHome.js';
|
|
10
17
|
import { ActoviqBridgeProcessError, RunAbortedError } from '../errors.js';
|
|
11
18
|
import { createActoviqMemoryApi } from '../memory/actoviqMemory.js';
|
|
12
19
|
import { AsyncQueue } from '../runtime/asyncQueue.js';
|
|
13
20
|
import { asError, isRecord } from '../runtime/helpers.js';
|
|
14
21
|
import { getActoviqBridgeCompactBoundaries, getActoviqBridgeLatestCompactBoundary, getActoviqBridgeSessionInfo, getActoviqBridgeSessionMessages, listActoviqBridgeSessions, } from './actoviqTranscripts.js';
|
|
15
22
|
const MODULE_DIR = path.dirname(fileURLToPath(import.meta.url));
|
|
23
|
+
const MAX_CAPTURED_STDOUT_BYTES = 4 * 1024 * 1024;
|
|
24
|
+
const MAX_CAPTURED_STDERR_BYTES = 1024 * 1024;
|
|
25
|
+
const MAX_RETAINED_RUN_EVENTS = 1_000;
|
|
26
|
+
const MAX_RETAINED_ASSISTANT_MESSAGES = 128;
|
|
27
|
+
const OUTPUT_TRUNCATION_MARKER = '[Actoviq output truncated]\n';
|
|
28
|
+
class BoundedRetention {
|
|
29
|
+
capacity;
|
|
30
|
+
values = [];
|
|
31
|
+
nextWriteIndex = 0;
|
|
32
|
+
constructor(capacity) {
|
|
33
|
+
this.capacity = capacity;
|
|
34
|
+
}
|
|
35
|
+
push(value) {
|
|
36
|
+
if (this.values.length < this.capacity) {
|
|
37
|
+
this.values.push(value);
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
this.values[this.nextWriteIndex] = value;
|
|
41
|
+
this.nextWriteIndex = (this.nextWriteIndex + 1) % this.capacity;
|
|
42
|
+
}
|
|
43
|
+
toArray() {
|
|
44
|
+
if (this.values.length < this.capacity || this.nextWriteIndex === 0) {
|
|
45
|
+
return [...this.values];
|
|
46
|
+
}
|
|
47
|
+
return [
|
|
48
|
+
...this.values.slice(this.nextWriteIndex),
|
|
49
|
+
...this.values.slice(0, this.nextWriteIndex),
|
|
50
|
+
];
|
|
51
|
+
}
|
|
52
|
+
}
|
|
16
53
|
function isAbortErrorLike(error) {
|
|
17
54
|
return error instanceof RunAbortedError || (error instanceof Error && error.name === 'AbortError');
|
|
18
55
|
}
|
|
@@ -97,6 +134,10 @@ function getStringValue(event, key) {
|
|
|
97
134
|
const value = event?.[key];
|
|
98
135
|
return typeof value === 'string' ? value : undefined;
|
|
99
136
|
}
|
|
137
|
+
function getNonEmptyStringValue(event, key) {
|
|
138
|
+
const value = getStringValue(event, key)?.trim();
|
|
139
|
+
return value || undefined;
|
|
140
|
+
}
|
|
100
141
|
function getNumberValue(event, key) {
|
|
101
142
|
const value = event?.[key];
|
|
102
143
|
return typeof value === 'number' ? value : undefined;
|
|
@@ -343,7 +384,6 @@ function buildRuntimeCatalog(params) {
|
|
|
343
384
|
function buildCliArgs(prompt, options) {
|
|
344
385
|
const args = [
|
|
345
386
|
'-p',
|
|
346
|
-
prompt,
|
|
347
387
|
'--output-format',
|
|
348
388
|
'stream-json',
|
|
349
389
|
'--verbose',
|
|
@@ -370,11 +410,11 @@ function buildCliArgs(prompt, options) {
|
|
|
370
410
|
args.push('--fork-session');
|
|
371
411
|
}
|
|
372
412
|
const shouldSkipPermissions = options.dangerouslySkipPermissions ??
|
|
373
|
-
|
|
413
|
+
options.permissionMode === 'bypassPermissions';
|
|
374
414
|
if (shouldSkipPermissions) {
|
|
375
415
|
args.push('--dangerously-skip-permissions');
|
|
376
416
|
}
|
|
377
|
-
appendOptionalArg(args, '--permission-mode', options.permissionMode);
|
|
417
|
+
appendOptionalArg(args, '--permission-mode', options.permissionMode ?? 'default');
|
|
378
418
|
appendOptionalArg(args, '--model', options.model);
|
|
379
419
|
appendOptionalArg(args, '--fallback-model', options.fallbackModel);
|
|
380
420
|
appendOptionalArg(args, '--effort', options.effort);
|
|
@@ -411,28 +451,474 @@ function buildCliArgs(prompt, options) {
|
|
|
411
451
|
args.push('--mcp-config', ...options.mcpConfigs.map(config => stringifyCliValue(config)));
|
|
412
452
|
}
|
|
413
453
|
if (typeof options.resume === 'string') {
|
|
414
|
-
args.push(
|
|
454
|
+
args.push(`--resume=${options.resume}`);
|
|
415
455
|
}
|
|
416
456
|
else if (options.resume === true) {
|
|
417
457
|
args.push('--resume');
|
|
418
458
|
}
|
|
419
459
|
else if (options.sessionId) {
|
|
420
|
-
args.push(
|
|
460
|
+
args.push(`--session-id=${options.sessionId}`);
|
|
421
461
|
}
|
|
422
462
|
if (options.cliArgs?.length) {
|
|
423
463
|
args.push(...options.cliArgs);
|
|
424
464
|
}
|
|
465
|
+
// Claude's `-p` is a boolean flag; the prompt is positional. Keep arbitrary
|
|
466
|
+
// prompt text behind the option terminator so it cannot be reinterpreted as
|
|
467
|
+
// a permission or configuration flag.
|
|
468
|
+
args.push('--', prompt);
|
|
425
469
|
return args;
|
|
426
470
|
}
|
|
427
|
-
function
|
|
471
|
+
async function writeReasonixTranscriptMetadata(entry, options) {
|
|
472
|
+
entry.transcriptTitle ??= options.prompt.replace(/\s+/gu, ' ').trim().slice(0, 160);
|
|
473
|
+
const extension = path.extname(entry.transcriptPath);
|
|
474
|
+
const stem = extension
|
|
475
|
+
? entry.transcriptPath.slice(0, -extension.length)
|
|
476
|
+
: entry.transcriptPath;
|
|
477
|
+
await writeFile(`${stem}.acp.json`, `${JSON.stringify({
|
|
478
|
+
sessionId: options.sessionId,
|
|
479
|
+
title: entry.transcriptTitle || options.sessionId,
|
|
480
|
+
cwd: options.cwd,
|
|
481
|
+
model: options.model,
|
|
482
|
+
createdAt: entry.transcriptCreatedAt,
|
|
483
|
+
updatedAt: new Date().toISOString(),
|
|
484
|
+
}, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 });
|
|
485
|
+
}
|
|
486
|
+
function reasonixConfigFingerprint(options) {
|
|
487
|
+
const env = Object.entries(options.env ?? {}).sort(([left], [right]) => left.localeCompare(right));
|
|
488
|
+
return createHash('sha256').update(JSON.stringify({
|
|
489
|
+
authSource: options.authSource ?? 'native',
|
|
490
|
+
apiKey: options.apiKey ?? '',
|
|
491
|
+
baseURL: options.baseURL ?? '',
|
|
492
|
+
credentialProvider: options.credentialProvider ?? '',
|
|
493
|
+
homeDir: options.homeDir ?? '',
|
|
494
|
+
model: options.model ?? '',
|
|
495
|
+
profileName: options.profileName ?? '',
|
|
496
|
+
env,
|
|
497
|
+
})).digest('hex');
|
|
498
|
+
}
|
|
499
|
+
function reasonixManagedAliasKey(configFingerprint, cwd, sessionId) {
|
|
500
|
+
return `${configFingerprint}\0${cwd}\0${sessionId}`;
|
|
501
|
+
}
|
|
502
|
+
function validateReasonixManagedSessionId(value) {
|
|
503
|
+
const normalized = value.trim();
|
|
504
|
+
if (!normalized
|
|
505
|
+
|| normalized.length > 512
|
|
506
|
+
|| normalized.startsWith('-')
|
|
507
|
+
|| /[\u0000-\u001f\u007f]/u.test(normalized)) {
|
|
508
|
+
throw new ActoviqBridgeProcessError('Reasonix session id must be a non-option value without control characters.');
|
|
509
|
+
}
|
|
510
|
+
return normalized;
|
|
511
|
+
}
|
|
512
|
+
const COMMON_UNSUPPORTED_MANAGED_OPTIONS = [
|
|
513
|
+
'fallbackModel',
|
|
514
|
+
'systemPrompt',
|
|
515
|
+
'appendSystemPrompt',
|
|
516
|
+
'maxTurns',
|
|
517
|
+
'agent',
|
|
518
|
+
'agents',
|
|
519
|
+
'tools',
|
|
520
|
+
'allowedTools',
|
|
521
|
+
'disallowedTools',
|
|
522
|
+
'addDirs',
|
|
523
|
+
'mcpConfigs',
|
|
524
|
+
'strictMcpConfig',
|
|
525
|
+
'settings',
|
|
526
|
+
'settingSources',
|
|
527
|
+
'jsonSchema',
|
|
528
|
+
'files',
|
|
529
|
+
'bare',
|
|
530
|
+
'disableSlashCommands',
|
|
531
|
+
'includeHookEvents',
|
|
532
|
+
'pluginDirs',
|
|
533
|
+
'cliArgs',
|
|
534
|
+
];
|
|
535
|
+
function managedOptionWasRequested(options, key) {
|
|
536
|
+
const value = options[key];
|
|
537
|
+
if (value == null)
|
|
538
|
+
return false;
|
|
539
|
+
// `tools: []` and `tools: 'none'` both explicitly disable the native tool
|
|
540
|
+
// set, so they remain meaningful even though the collection is empty.
|
|
541
|
+
if (key === 'tools')
|
|
542
|
+
return true;
|
|
543
|
+
if (Array.isArray(value))
|
|
544
|
+
return value.length > 0;
|
|
545
|
+
if (typeof value === 'string')
|
|
546
|
+
return value.length > 0;
|
|
547
|
+
if (typeof value === 'boolean')
|
|
548
|
+
return value;
|
|
549
|
+
return true;
|
|
550
|
+
}
|
|
551
|
+
function assertManagedOptionsSupported(runtime, options, extraUnsupported = []) {
|
|
552
|
+
const unsupported = [...COMMON_UNSUPPORTED_MANAGED_OPTIONS, ...extraUnsupported]
|
|
553
|
+
.filter(key => managedOptionWasRequested(options, key));
|
|
554
|
+
if (unsupported.length === 0)
|
|
555
|
+
return;
|
|
556
|
+
throw new ActoviqBridgeProcessError(`${runtime} managed mode cannot enforce bridge option${unsupported.length === 1 ? '' : 's'}: ${unsupported.join(', ')}.`);
|
|
557
|
+
}
|
|
558
|
+
const BRIDGE_AUTH_ENV_KEYS = new Set([
|
|
559
|
+
'ACTOVIQ_API_KEY',
|
|
560
|
+
'ACTOVIQ_AUTH_TOKEN',
|
|
561
|
+
'ACTOVIQ_BASE_URL',
|
|
562
|
+
'ANTHROPIC_API_KEY',
|
|
563
|
+
'ANTHROPIC_AUTH_TOKEN',
|
|
564
|
+
'ANTHROPIC_BASE_URL',
|
|
565
|
+
'OPENAI_API_KEY',
|
|
566
|
+
'OPENAI_BASE_URL',
|
|
567
|
+
'CODEX_API_KEY',
|
|
568
|
+
'CODEX_ACCESS_TOKEN',
|
|
569
|
+
'CLAUDE_CODE_OAUTH_TOKEN',
|
|
570
|
+
'DEEPSEEK_API_KEY',
|
|
571
|
+
'DEEPSEEK_BASE_URL',
|
|
572
|
+
'GEMINI_API_KEY',
|
|
573
|
+
'GOOGLE_API_KEY',
|
|
574
|
+
'OPENROUTER_API_KEY',
|
|
575
|
+
'XAI_API_KEY',
|
|
576
|
+
'GROQ_API_KEY',
|
|
577
|
+
'MISTRAL_API_KEY',
|
|
578
|
+
'AZURE_OPENAI_API_KEY',
|
|
579
|
+
]);
|
|
580
|
+
const ACTOVIQ_AUTH_ENV_KEYS = new Set([
|
|
581
|
+
'ACTOVIQ_API_KEY',
|
|
582
|
+
'ACTOVIQ_AUTH_TOKEN',
|
|
583
|
+
'ACTOVIQ_BASE_URL',
|
|
584
|
+
]);
|
|
585
|
+
const API_KEY_CHILD_ENV_KEYS = new Set([
|
|
586
|
+
'ALL_PROXY',
|
|
587
|
+
'APPDATA',
|
|
588
|
+
'CI',
|
|
589
|
+
'COLORTERM',
|
|
590
|
+
'COMSPEC',
|
|
591
|
+
'FORCE_COLOR',
|
|
592
|
+
'HOME',
|
|
593
|
+
'HOMEDRIVE',
|
|
594
|
+
'HOMEPATH',
|
|
595
|
+
'HTTP_PROXY',
|
|
596
|
+
'HTTPS_PROXY',
|
|
597
|
+
'LANG',
|
|
598
|
+
'LOCALAPPDATA',
|
|
599
|
+
'NODE_ENV',
|
|
600
|
+
'NO_COLOR',
|
|
601
|
+
'NO_PROXY',
|
|
602
|
+
'NUMBER_OF_PROCESSORS',
|
|
603
|
+
'OS',
|
|
604
|
+
'PATH',
|
|
605
|
+
'PATHEXT',
|
|
606
|
+
'PROCESSOR_ARCHITECTURE',
|
|
607
|
+
'PROGRAMDATA',
|
|
608
|
+
'SHELL',
|
|
609
|
+
'SYSTEMDRIVE',
|
|
610
|
+
'SYSTEMROOT',
|
|
611
|
+
'TEMP',
|
|
612
|
+
'TERM',
|
|
613
|
+
'TMP',
|
|
614
|
+
'TMPDIR',
|
|
615
|
+
'TZ',
|
|
616
|
+
'USER',
|
|
617
|
+
'USERNAME',
|
|
618
|
+
'USERPROFILE',
|
|
619
|
+
'WINDIR',
|
|
620
|
+
// Paths needed by common compiler/toolchain subprocesses. Authentication
|
|
621
|
+
// helpers (AWS/GH/SSH/etc.) are deliberately excluded.
|
|
622
|
+
'BUN_INSTALL',
|
|
623
|
+
'CARGO_HOME',
|
|
624
|
+
'CONDA_PREFIX',
|
|
625
|
+
'DOTNET_ROOT',
|
|
626
|
+
'GOPATH',
|
|
627
|
+
'GOROOT',
|
|
628
|
+
'JAVA_HOME',
|
|
629
|
+
'NVM_HOME',
|
|
630
|
+
'NVM_SYMLINK',
|
|
631
|
+
'PNPM_HOME',
|
|
632
|
+
'PYENV_ROOT',
|
|
633
|
+
'RUSTUP_HOME',
|
|
634
|
+
'VIRTUAL_ENV',
|
|
635
|
+
]);
|
|
636
|
+
const SENSITIVE_ENV_KEY = /(?:^|_)(?:API_?KEY|AUTH|COOKIE|CREDENTIALS?|KEY|PASS(?:WORD|WD)?|PRIVATE_KEY|SECRET|TOKEN)(?:$|_)/iu;
|
|
637
|
+
async function findCrushProjectConfig(workDir) {
|
|
638
|
+
let directory = path.resolve(workDir);
|
|
639
|
+
while (true) {
|
|
640
|
+
for (const name of ['crush.json', '.crush.json']) {
|
|
641
|
+
const candidate = path.join(directory, name);
|
|
642
|
+
if (await pathExists(candidate))
|
|
643
|
+
return candidate;
|
|
644
|
+
}
|
|
645
|
+
const parent = path.dirname(directory);
|
|
646
|
+
if (parent === directory)
|
|
647
|
+
return undefined;
|
|
648
|
+
directory = parent;
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
const PROVIDER_DEFAULT_API_KEY_ENV = {
|
|
652
|
+
claude: ['ANTHROPIC_API_KEY'],
|
|
653
|
+
codewhale: ['DEEPSEEK_API_KEY'],
|
|
654
|
+
pi: ['OPENAI_API_KEY'],
|
|
655
|
+
codex: ['OPENAI_API_KEY'],
|
|
656
|
+
crush: ['CRUSH_OPENAI_API_KEY'],
|
|
657
|
+
reasonix: ['DEEPSEEK_API_KEY'],
|
|
658
|
+
};
|
|
659
|
+
const CREDENTIAL_PROVIDER_ENV = {
|
|
660
|
+
anthropic: ['ANTHROPIC_API_KEY'],
|
|
661
|
+
claude: ['ANTHROPIC_API_KEY'],
|
|
662
|
+
openai: ['OPENAI_API_KEY'],
|
|
663
|
+
'openai-codex': ['OPENAI_API_KEY'],
|
|
664
|
+
codex: ['OPENAI_API_KEY'],
|
|
665
|
+
deepseek: ['DEEPSEEK_API_KEY'],
|
|
666
|
+
google: ['GEMINI_API_KEY'],
|
|
667
|
+
gemini: ['GEMINI_API_KEY'],
|
|
668
|
+
openrouter: ['OPENROUTER_API_KEY'],
|
|
669
|
+
xai: ['XAI_API_KEY'],
|
|
670
|
+
groq: ['GROQ_API_KEY'],
|
|
671
|
+
mistral: ['MISTRAL_API_KEY'],
|
|
672
|
+
azure: ['AZURE_OPENAI_API_KEY'],
|
|
673
|
+
};
|
|
674
|
+
const PROVIDER_NATIVE_AUTH_ENV = {
|
|
675
|
+
claude: [
|
|
676
|
+
'ANTHROPIC_API_KEY',
|
|
677
|
+
'ANTHROPIC_AUTH_TOKEN',
|
|
678
|
+
'CLAUDE_CODE_OAUTH_TOKEN',
|
|
679
|
+
'AWS_ACCESS_KEY_ID',
|
|
680
|
+
'AWS_SECRET_ACCESS_KEY',
|
|
681
|
+
'AWS_SESSION_TOKEN',
|
|
682
|
+
'GOOGLE_APPLICATION_CREDENTIALS',
|
|
683
|
+
],
|
|
684
|
+
codewhale: ['DEEPSEEK_API_KEY', 'ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN'],
|
|
685
|
+
pi: ['OPENAI_API_KEY'],
|
|
686
|
+
codex: ['CODEX_API_KEY', 'CODEX_ACCESS_TOKEN', 'OPENAI_API_KEY'],
|
|
687
|
+
crush: ['CRUSH_OPENAI_API_KEY'],
|
|
688
|
+
reasonix: ['DEEPSEEK_API_KEY'],
|
|
689
|
+
};
|
|
690
|
+
const PROVIDER_BASE_URL_ENV = {
|
|
691
|
+
claude: 'ANTHROPIC_BASE_URL',
|
|
692
|
+
codewhale: 'DEEPSEEK_BASE_URL',
|
|
693
|
+
pi: 'OPENAI_BASE_URL',
|
|
694
|
+
codex: 'OPENAI_BASE_URL',
|
|
695
|
+
crush: 'CRUSH_OPENAI_BASE_URL',
|
|
696
|
+
reasonix: 'DEEPSEEK_BASE_URL',
|
|
697
|
+
};
|
|
698
|
+
function withoutActoviqAuth(values) {
|
|
699
|
+
return Object.fromEntries(Object.entries(values).filter(([key]) => !ACTOVIQ_AUTH_ENV_KEYS.has(key.toUpperCase())));
|
|
700
|
+
}
|
|
701
|
+
function withoutProviderAuth(provider, values) {
|
|
702
|
+
const denied = new Set([
|
|
703
|
+
...BRIDGE_AUTH_ENV_KEYS,
|
|
704
|
+
...(PROVIDER_NATIVE_AUTH_ENV[provider.id] ?? []),
|
|
705
|
+
].map(key => key.toUpperCase()));
|
|
706
|
+
return Object.fromEntries(Object.entries(values).filter(([key]) => {
|
|
707
|
+
const normalized = key.toUpperCase();
|
|
708
|
+
return !denied.has(normalized)
|
|
709
|
+
&& !SENSITIVE_ENV_KEY.test(normalized)
|
|
710
|
+
&& normalized !== 'SSH_AUTH_SOCK'
|
|
711
|
+
&& !/^(?:AWS|AZURE|GCP|GOOGLE|GH|GITHUB|GITLAB|NPM)_/u.test(normalized)
|
|
712
|
+
&& !(provider.id === 'crush' && normalized.startsWith('CRUSH_'));
|
|
713
|
+
}));
|
|
714
|
+
}
|
|
715
|
+
function safeProxyEnvironmentValue(key, value) {
|
|
716
|
+
if (!/(?:^|_)PROXY$/iu.test(key) || key.toUpperCase() === 'NO_PROXY')
|
|
717
|
+
return true;
|
|
718
|
+
try {
|
|
719
|
+
const parsed = new URL(value);
|
|
720
|
+
return !parsed.username && !parsed.password;
|
|
721
|
+
}
|
|
722
|
+
catch {
|
|
723
|
+
return key.toUpperCase() === 'NO_PROXY';
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
function apiKeyChildBaseEnvironment(values) {
|
|
727
|
+
return Object.fromEntries(Object.entries(values).filter(([key, value]) => {
|
|
728
|
+
const normalized = key.toUpperCase();
|
|
729
|
+
return (API_KEY_CHILD_ENV_KEYS.has(normalized)
|
|
730
|
+
|| normalized.startsWith('LC_')
|
|
731
|
+
|| normalized === 'ACTOVIQ_E2E_INVOCATIONS') && safeProxyEnvironmentValue(normalized, value);
|
|
732
|
+
}));
|
|
733
|
+
}
|
|
734
|
+
function environmentValue(values, keys) {
|
|
735
|
+
const wanted = new Set(keys.map(key => key.toUpperCase()));
|
|
736
|
+
return Object.entries(values).find(([key, value]) => wanted.has(key.toUpperCase()) && Boolean(value.trim()))?.[1];
|
|
737
|
+
}
|
|
738
|
+
function credentialProviderHint(options) {
|
|
739
|
+
const explicit = options.credentialProvider?.trim().toLowerCase();
|
|
740
|
+
if (explicit)
|
|
741
|
+
return explicit;
|
|
742
|
+
const model = options.model?.trim();
|
|
743
|
+
const separator = model?.indexOf('/') ?? -1;
|
|
744
|
+
if (model && separator > 0)
|
|
745
|
+
return model.slice(0, separator).toLowerCase();
|
|
746
|
+
const baseURL = options.baseURL?.toLowerCase() ?? '';
|
|
747
|
+
return Object.keys(CREDENTIAL_PROVIDER_ENV).find(name => baseURL.includes(name));
|
|
748
|
+
}
|
|
749
|
+
function providerCredentialKeys(provider, options) {
|
|
750
|
+
const hint = credentialProviderHint(options);
|
|
751
|
+
const keys = (hint && CREDENTIAL_PROVIDER_ENV[hint])
|
|
752
|
+
|| PROVIDER_DEFAULT_API_KEY_ENV[provider.id]
|
|
753
|
+
|| [];
|
|
754
|
+
return provider.id === 'crush'
|
|
755
|
+
? keys.map(key => key.startsWith('CRUSH_') ? key : `CRUSH_${key}`)
|
|
756
|
+
: keys;
|
|
757
|
+
}
|
|
758
|
+
function crushManagedModel(options, credentialProvider) {
|
|
759
|
+
const model = options.model?.trim();
|
|
760
|
+
if (!model)
|
|
761
|
+
return undefined;
|
|
762
|
+
const separator = model.indexOf('/');
|
|
763
|
+
if (separator <= 0 || !credentialProvider)
|
|
764
|
+
return model;
|
|
765
|
+
return model.slice(0, separator).toLowerCase() === credentialProvider
|
|
766
|
+
? model.slice(separator + 1)
|
|
767
|
+
: model;
|
|
768
|
+
}
|
|
769
|
+
function providerApiKeyEnvironment(provider, options, apiKey, baseURL) {
|
|
770
|
+
const env = {};
|
|
771
|
+
const normalizedKey = apiKey?.trim();
|
|
772
|
+
if (normalizedKey) {
|
|
773
|
+
for (const key of providerCredentialKeys(provider, options))
|
|
774
|
+
env[key] = normalizedKey;
|
|
775
|
+
}
|
|
776
|
+
const normalizedBaseURL = baseURL?.trim();
|
|
777
|
+
const credentialKey = providerCredentialKeys(provider, options)[0];
|
|
778
|
+
const baseURLKey = credentialKey?.replace(/_API_KEY$/u, '_BASE_URL')
|
|
779
|
+
?? PROVIDER_BASE_URL_ENV[provider.id];
|
|
780
|
+
if (normalizedBaseURL && baseURLKey)
|
|
781
|
+
env[baseURLKey] = normalizedBaseURL;
|
|
782
|
+
return env;
|
|
783
|
+
}
|
|
784
|
+
function credentialValues(values) {
|
|
785
|
+
return [...new Set(Object.entries(values)
|
|
786
|
+
.filter(([key, value]) => value
|
|
787
|
+
&& /(?:KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL|PRIVATE_KEY|COOKIE)$/iu.test(key))
|
|
788
|
+
.map(([, value]) => value))];
|
|
789
|
+
}
|
|
790
|
+
async function ensurePrivateDirectory(directory) {
|
|
791
|
+
await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
792
|
+
if (!IS_WINDOWS)
|
|
793
|
+
await chmod(directory, 0o700);
|
|
794
|
+
}
|
|
795
|
+
async function persistentExternalCliProfile(provider, options) {
|
|
796
|
+
const namedIdentity = options.profileName?.trim();
|
|
797
|
+
const identity = namedIdentity
|
|
798
|
+
? `name:${namedIdentity}`
|
|
799
|
+
: `anonymous:${credentialProviderHint(options) ?? ''}\0${options.baseURL ?? ''}`;
|
|
800
|
+
const profileId = namedIdentity
|
|
801
|
+
? namedExternalCliManagedProfileId(provider.id, namedIdentity)
|
|
802
|
+
: createHash('sha256').update(`${provider.id}\0${identity}`).digest('hex');
|
|
803
|
+
const root = path.join(resolveActoviqHome(options.homeDir), 'external-cli-profiles', provider.id, profileId);
|
|
804
|
+
await ensurePrivateDirectory(root);
|
|
805
|
+
return root;
|
|
806
|
+
}
|
|
807
|
+
async function buildChildEnvironment(provider, options, directCli) {
|
|
428
808
|
const loadedConfig = getLoadedJsonConfig();
|
|
429
|
-
// Actoviq settings are the single source of model/credential config. Each
|
|
430
|
-
// provider decides how to translate the settings env block into the
|
|
431
|
-
// credential variables its CLI reads (claude: ANTHROPIC_*; pi/codex: their
|
|
432
|
-
// own) and in what order they override the inherited process env.
|
|
433
809
|
const settingsEnv = loadedConfig?.env ?? {};
|
|
434
810
|
const baseEnv = Object.fromEntries(Object.entries(process.env).filter((entry) => typeof entry[1] === 'string'));
|
|
435
|
-
|
|
811
|
+
const envOverrides = options.env ?? {};
|
|
812
|
+
const authSource = options.authSource ?? (directCli ? 'native' : undefined);
|
|
813
|
+
// Native mode deliberately bypasses provider.buildChildEnv: Claude's legacy
|
|
814
|
+
// builder maps ACTOVIQ_* into ANTHROPIC_*, which would override the CLI's
|
|
815
|
+
// OAuth/keychain login. Inherited process env remains untouched because it is
|
|
816
|
+
// part of the environment in which the user normally launches the CLI.
|
|
817
|
+
if (authSource === 'native') {
|
|
818
|
+
const env = {
|
|
819
|
+
...withoutActoviqAuth(baseEnv),
|
|
820
|
+
...withoutActoviqAuth(envOverrides),
|
|
821
|
+
};
|
|
822
|
+
return {
|
|
823
|
+
env,
|
|
824
|
+
secrets: credentialValues(env),
|
|
825
|
+
};
|
|
826
|
+
}
|
|
827
|
+
if (authSource === 'apiKey') {
|
|
828
|
+
const legacyOverrideKeys = provider.id === 'codex' ? ['OPENAI_API_KEY'] : [];
|
|
829
|
+
const requestedApiKey = options.apiKey
|
|
830
|
+
?? environmentValue(envOverrides, [
|
|
831
|
+
...providerCredentialKeys(provider, options),
|
|
832
|
+
...legacyOverrideKeys,
|
|
833
|
+
]);
|
|
834
|
+
const baseURLKey = PROVIDER_BASE_URL_ENV[provider.id];
|
|
835
|
+
const requestedBaseURL = options.baseURL
|
|
836
|
+
?? (baseURLKey ? environmentValue(envOverrides, [baseURLKey]) : undefined);
|
|
837
|
+
const authEnv = providerApiKeyEnvironment(provider, options, requestedApiKey, requestedBaseURL);
|
|
838
|
+
if (credentialValues(authEnv).length === 0) {
|
|
839
|
+
throw new ActoviqBridgeProcessError('authSource "apiKey" requires apiKey or a provider credential in env.');
|
|
840
|
+
}
|
|
841
|
+
const env = {
|
|
842
|
+
...withoutProviderAuth(provider, apiKeyChildBaseEnvironment(baseEnv)),
|
|
843
|
+
// Direct CLI mode never imports ~/.actoviq/settings.json env wholesale.
|
|
844
|
+
// It may contain unrelated GitHub/AWS/database secrets. Explicit per-run
|
|
845
|
+
// overrides remain supported, minus competing runtime credentials.
|
|
846
|
+
...withoutProviderAuth(provider, envOverrides),
|
|
847
|
+
...authEnv,
|
|
848
|
+
};
|
|
849
|
+
if (directCli
|
|
850
|
+
&& (provider.id === 'pi'
|
|
851
|
+
|| provider.id === 'codewhale'
|
|
852
|
+
|| provider.id === 'reasonix'
|
|
853
|
+
|| provider.id === 'crush')) {
|
|
854
|
+
// These CLIs prefer their native credential store over environment keys.
|
|
855
|
+
// An empty per-run config home makes the explicit child-only key win
|
|
856
|
+
// without reading or modifying the user's login files.
|
|
857
|
+
const isolatedHome = await mkdtemp(path.join(os.tmpdir(), `actoviq-${provider.id}-auth-`));
|
|
858
|
+
if (provider.id === 'pi') {
|
|
859
|
+
env.PI_CODING_AGENT_DIR = isolatedHome;
|
|
860
|
+
env.PI_CODING_AGENT_SESSION_DIR = path.join(await persistentExternalCliProfile(provider, options), 'sessions');
|
|
861
|
+
await ensurePrivateDirectory(env.PI_CODING_AGENT_SESSION_DIR);
|
|
862
|
+
}
|
|
863
|
+
if (provider.id === 'codewhale') {
|
|
864
|
+
env.CODEWHALE_HOME = await persistentExternalCliProfile(provider, options);
|
|
865
|
+
env.CODEWHALE_CONFIG_PATH = path.join(isolatedHome, 'config.json');
|
|
866
|
+
}
|
|
867
|
+
if (provider.id === 'reasonix') {
|
|
868
|
+
const profileHome = await persistentExternalCliProfile(provider, options);
|
|
869
|
+
// Reasonix 0.53 ignores REASONIX_HOME and resolves ~/.reasonix through
|
|
870
|
+
// os.homedir(). Override both home variables so explicit-key mode does
|
|
871
|
+
// not read or mutate the user's native config, memory, or skills.
|
|
872
|
+
env.HOME = profileHome;
|
|
873
|
+
env.USERPROFILE = profileHome;
|
|
874
|
+
env.REASONIX_HOME = path.join(profileHome, '.reasonix');
|
|
875
|
+
await ensurePrivateDirectory(env.REASONIX_HOME);
|
|
876
|
+
}
|
|
877
|
+
if (provider.id === 'crush') {
|
|
878
|
+
const profile = await persistentExternalCliProfile(provider, options);
|
|
879
|
+
env.CRUSH_GLOBAL_CONFIG = path.join(isolatedHome, 'config');
|
|
880
|
+
env.CRUSH_GLOBAL_DATA = path.join(profile, 'data');
|
|
881
|
+
env.CRUSH_CACHE_DIR = path.join(isolatedHome, 'cache');
|
|
882
|
+
env.XDG_CONFIG_HOME = path.join(isolatedHome, 'xdg-config');
|
|
883
|
+
await ensurePrivateDirectory(env.CRUSH_GLOBAL_DATA);
|
|
884
|
+
}
|
|
885
|
+
return {
|
|
886
|
+
env,
|
|
887
|
+
secrets: credentialValues(env),
|
|
888
|
+
cleanup: () => rm(isolatedHome, { recursive: true, force: true }),
|
|
889
|
+
};
|
|
890
|
+
}
|
|
891
|
+
return { env, secrets: credentialValues(env) };
|
|
892
|
+
}
|
|
893
|
+
// The vendored bridge keeps its historical Actoviq settings mapping when no
|
|
894
|
+
// auth source is selected. This preserves the existing non-direct API.
|
|
895
|
+
return {
|
|
896
|
+
env: provider.buildChildEnv(baseEnv, settingsEnv, envOverrides),
|
|
897
|
+
secrets: [],
|
|
898
|
+
};
|
|
899
|
+
}
|
|
900
|
+
function redactText(value, secrets) {
|
|
901
|
+
let redacted = value;
|
|
902
|
+
for (const secret of secrets) {
|
|
903
|
+
if (!secret)
|
|
904
|
+
continue;
|
|
905
|
+
redacted = redacted.split(secret).join('[REDACTED]');
|
|
906
|
+
}
|
|
907
|
+
return redacted;
|
|
908
|
+
}
|
|
909
|
+
function redactEventValue(value, secrets) {
|
|
910
|
+
if (typeof value === 'string')
|
|
911
|
+
return redactText(value, secrets);
|
|
912
|
+
if (Array.isArray(value))
|
|
913
|
+
return value.map(item => redactEventValue(item, secrets));
|
|
914
|
+
if (!isRecord(value))
|
|
915
|
+
return value;
|
|
916
|
+
return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, redactEventValue(item, secrets)]));
|
|
917
|
+
}
|
|
918
|
+
function redactEvent(event, secrets) {
|
|
919
|
+
if (secrets.length === 0)
|
|
920
|
+
return event;
|
|
921
|
+
return redactEventValue(event, secrets);
|
|
436
922
|
}
|
|
437
923
|
async function prefersSystemRipgrep(envOverrides) {
|
|
438
924
|
const explicit = envOverrides?.USE_BUILTIN_RIPGREP ?? process.env.USE_BUILTIN_RIPGREP;
|
|
@@ -441,7 +927,7 @@ async function prefersSystemRipgrep(envOverrides) {
|
|
|
441
927
|
}
|
|
442
928
|
return Boolean(await findExecutableOnPath('rg'));
|
|
443
929
|
}
|
|
444
|
-
async function parseStdoutEvents(child, onEvent, normalizer) {
|
|
930
|
+
async function parseStdoutEvents(child, onEvent, normalizer, control, secrets = []) {
|
|
445
931
|
if (!child.stdout) {
|
|
446
932
|
return;
|
|
447
933
|
}
|
|
@@ -453,8 +939,8 @@ async function parseStdoutEvents(child, onEvent, normalizer) {
|
|
|
453
939
|
}
|
|
454
940
|
if (normalizer.rawText) {
|
|
455
941
|
// Plain-text provider — feed each line as-is; no JSON structure.
|
|
456
|
-
for (const event of normalizer.translate({ _raw: trimmed })) {
|
|
457
|
-
onEvent(event);
|
|
942
|
+
for (const event of normalizer.translate({ _raw: trimmed }, control)) {
|
|
943
|
+
onEvent(redactEvent(event, secrets));
|
|
458
944
|
}
|
|
459
945
|
continue;
|
|
460
946
|
}
|
|
@@ -463,49 +949,61 @@ async function parseStdoutEvents(child, onEvent, normalizer) {
|
|
|
463
949
|
parsed = JSON.parse(trimmed);
|
|
464
950
|
}
|
|
465
951
|
catch (error) {
|
|
466
|
-
throw new ActoviqBridgeProcessError(`Failed to parse Actoviq Runtime stream line: ${trimmed}`, {
|
|
952
|
+
throw new ActoviqBridgeProcessError(`Failed to parse Actoviq Runtime stream line: ${redactText(trimmed, secrets)}`, {
|
|
467
953
|
cause: error,
|
|
468
954
|
});
|
|
469
955
|
}
|
|
470
|
-
if (!isRecord(parsed) || typeof parsed.type !== 'string') {
|
|
956
|
+
if (!isRecord(parsed) || (!normalizer.interactive && typeof parsed.type !== 'string')) {
|
|
471
957
|
throw new ActoviqBridgeProcessError('Actoviq Runtime emitted a malformed stream event.');
|
|
472
958
|
}
|
|
473
959
|
// Providers whose native wire format differs from the canonical
|
|
474
960
|
// system/assistant/result trio (pi, codex) translate here; claude is a
|
|
475
961
|
// passthrough normalizer, so its behavior is unchanged.
|
|
476
|
-
for (const event of normalizer.translate(parsed)) {
|
|
477
|
-
onEvent(event);
|
|
962
|
+
for (const event of normalizer.translate(parsed, control)) {
|
|
963
|
+
onEvent(redactEvent(event, secrets));
|
|
478
964
|
}
|
|
479
965
|
}
|
|
480
966
|
// Raw-text providers flush accumulated text at stream end.
|
|
481
967
|
if (normalizer.flush) {
|
|
482
968
|
for (const event of normalizer.flush()) {
|
|
483
|
-
onEvent(event);
|
|
969
|
+
onEvent(redactEvent(event, secrets));
|
|
484
970
|
}
|
|
485
971
|
}
|
|
486
972
|
}
|
|
487
|
-
async function
|
|
488
|
-
if (!
|
|
973
|
+
async function readBoundedText(stream, maxBytes) {
|
|
974
|
+
if (!stream)
|
|
489
975
|
return '';
|
|
976
|
+
const markerBytes = Buffer.byteLength(OUTPUT_TRUNCATION_MARKER);
|
|
977
|
+
const payloadLimit = Math.max(0, maxBytes - markerBytes);
|
|
978
|
+
let retained = Buffer.alloc(0);
|
|
979
|
+
let truncated = false;
|
|
980
|
+
for await (const chunk of stream) {
|
|
981
|
+
const next = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk));
|
|
982
|
+
const combined = retained.length === 0 ? next : Buffer.concat([retained, next]);
|
|
983
|
+
if (combined.length > payloadLimit) {
|
|
984
|
+
retained = Buffer.from(combined.subarray(combined.length - payloadLimit));
|
|
985
|
+
truncated = true;
|
|
986
|
+
}
|
|
987
|
+
else {
|
|
988
|
+
retained = combined;
|
|
989
|
+
}
|
|
490
990
|
}
|
|
491
|
-
|
|
492
|
-
for await (const chunk of child.stderr) {
|
|
493
|
-
stderr += chunk.toString();
|
|
494
|
-
}
|
|
495
|
-
return stderr;
|
|
991
|
+
return `${truncated ? OUTPUT_TRUNCATION_MARKER : ''}${retained.toString('utf8')}`;
|
|
496
992
|
}
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
for await (const chunk of child.stdout) {
|
|
503
|
-
stdout += chunk.toString();
|
|
504
|
-
}
|
|
505
|
-
return stdout;
|
|
993
|
+
function readStderr(child) {
|
|
994
|
+
return readBoundedText(child.stderr, MAX_CAPTURED_STDERR_BYTES);
|
|
995
|
+
}
|
|
996
|
+
function readStdout(child) {
|
|
997
|
+
return readBoundedText(child.stdout, MAX_CAPTURED_STDOUT_BYTES);
|
|
506
998
|
}
|
|
507
999
|
export class ActoviqBridgeRunStream {
|
|
508
|
-
queue = new AsyncQueue(
|
|
1000
|
+
queue = new AsyncQueue({
|
|
1001
|
+
capacity: MAX_RETAINED_RUN_EVENTS,
|
|
1002
|
+
overflowStrategy: 'drop-oldest',
|
|
1003
|
+
isPriority: event => event.type === 'system' || event.type === 'result',
|
|
1004
|
+
priorityReserve: 2,
|
|
1005
|
+
canDrop: event => event.type !== 'system' && event.type !== 'result',
|
|
1006
|
+
});
|
|
509
1007
|
result;
|
|
510
1008
|
constructor(executor) {
|
|
511
1009
|
this.result = (async () => {
|
|
@@ -531,22 +1029,26 @@ export class ActoviqBridgeRunStream {
|
|
|
531
1029
|
}
|
|
532
1030
|
export class ActoviqBridgeSession {
|
|
533
1031
|
client;
|
|
534
|
-
id;
|
|
535
1032
|
title;
|
|
536
1033
|
defaults;
|
|
537
1034
|
started;
|
|
538
1035
|
runAttempt = 0;
|
|
1036
|
+
runtimeSessionId;
|
|
539
1037
|
constructor(client, id, title, defaults, started = false) {
|
|
540
1038
|
this.client = client;
|
|
541
|
-
this.id = id;
|
|
542
1039
|
this.title = title;
|
|
543
1040
|
this.defaults = defaults;
|
|
1041
|
+
this.runtimeSessionId = id;
|
|
544
1042
|
this.started = started;
|
|
545
1043
|
}
|
|
1044
|
+
get id() {
|
|
1045
|
+
return this.runtimeSessionId;
|
|
1046
|
+
}
|
|
546
1047
|
async send(prompt, options = {}) {
|
|
547
1048
|
const runOptions = this.buildRunOptions(options);
|
|
548
1049
|
this.runAttempt += 1;
|
|
549
1050
|
const result = await this.client.run(prompt, runOptions);
|
|
1051
|
+
this.adoptRuntimeSessionId(result);
|
|
550
1052
|
this.started = true;
|
|
551
1053
|
return result;
|
|
552
1054
|
}
|
|
@@ -557,12 +1059,10 @@ export class ActoviqBridgeSession {
|
|
|
557
1059
|
const runStream = this.client.stream(prompt, runOptions);
|
|
558
1060
|
this.runAttempt = attempt;
|
|
559
1061
|
this.started = true;
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
});
|
|
565
|
-
}
|
|
1062
|
+
void runStream.result.then(result => this.adoptRuntimeSessionId(result), () => {
|
|
1063
|
+
if (!wasStarted && this.runAttempt === attempt)
|
|
1064
|
+
this.started = false;
|
|
1065
|
+
});
|
|
566
1066
|
return runStream;
|
|
567
1067
|
}
|
|
568
1068
|
runSlashCommand(commandName, args = '', options = {}) {
|
|
@@ -628,6 +1128,11 @@ export class ActoviqBridgeSession {
|
|
|
628
1128
|
}
|
|
629
1129
|
return merged;
|
|
630
1130
|
}
|
|
1131
|
+
adoptRuntimeSessionId(result) {
|
|
1132
|
+
const sessionId = result.sessionId.trim();
|
|
1133
|
+
if (sessionId)
|
|
1134
|
+
this.runtimeSessionId = sessionId;
|
|
1135
|
+
}
|
|
631
1136
|
}
|
|
632
1137
|
export class ActoviqBridgeAgentHandle {
|
|
633
1138
|
client;
|
|
@@ -894,6 +1399,12 @@ export class ActoviqBridgeSdkClient {
|
|
|
894
1399
|
context;
|
|
895
1400
|
buddy;
|
|
896
1401
|
memory;
|
|
1402
|
+
activeChildren = new Set();
|
|
1403
|
+
/** Graceful reclaim hooks (protocol cancel + terminate) for active child runs. */
|
|
1404
|
+
activeChildReclaims = new Map();
|
|
1405
|
+
reasonixManagedEntries = new Map();
|
|
1406
|
+
reasonixManagedEntryPromises = new Map();
|
|
1407
|
+
closed = false;
|
|
897
1408
|
constructor(executable, cliPath, directCli, provider, defaults) {
|
|
898
1409
|
this.executable = executable;
|
|
899
1410
|
this.cliPath = cliPath;
|
|
@@ -1015,7 +1526,32 @@ export class ActoviqBridgeSdkClient {
|
|
|
1015
1526
|
return new ActoviqBridgeSession(this, sessionId, options.title, this.mergeOptions(options), true);
|
|
1016
1527
|
}
|
|
1017
1528
|
async close() {
|
|
1018
|
-
|
|
1529
|
+
if (this.closed
|
|
1530
|
+
&& this.activeChildren.size === 0
|
|
1531
|
+
&& this.activeChildReclaims.size === 0
|
|
1532
|
+
&& this.reasonixManagedEntries.size === 0
|
|
1533
|
+
&& this.reasonixManagedEntryPromises.size === 0)
|
|
1534
|
+
return;
|
|
1535
|
+
this.closed = true;
|
|
1536
|
+
const pendingEntries = await Promise.allSettled([
|
|
1537
|
+
...this.reasonixManagedEntryPromises.values(),
|
|
1538
|
+
]);
|
|
1539
|
+
const reasonixEntries = new Set(this.reasonixManagedEntries.values());
|
|
1540
|
+
for (const pending of pendingEntries) {
|
|
1541
|
+
if (pending.status === 'fulfilled')
|
|
1542
|
+
reasonixEntries.add(pending.value);
|
|
1543
|
+
}
|
|
1544
|
+
await Promise.all([...reasonixEntries].map(entry => this.releaseReasonixEntry(entry)));
|
|
1545
|
+
// Prefer protocol cancel (e.g. Reasonix session/cancel) before hard kill so
|
|
1546
|
+
// interactive ACP turns shut down the same way AbortSignal does.
|
|
1547
|
+
const reclaimers = [...this.activeChildReclaims.values()];
|
|
1548
|
+
await Promise.all(reclaimers.map(reclaim => reclaim().catch(() => undefined)));
|
|
1549
|
+
const children = [...this.activeChildren];
|
|
1550
|
+
await Promise.all(children.map(child => terminateActoviqProcessTree(child)));
|
|
1551
|
+
for (const child of children) {
|
|
1552
|
+
this.activeChildren.delete(child);
|
|
1553
|
+
this.activeChildReclaims.delete(child);
|
|
1554
|
+
}
|
|
1019
1555
|
}
|
|
1020
1556
|
async getRuntimeInfo(options = {}) {
|
|
1021
1557
|
const result = await this.run('/cost', {
|
|
@@ -1108,33 +1644,60 @@ export class ActoviqBridgeSdkClient {
|
|
|
1108
1644
|
};
|
|
1109
1645
|
}
|
|
1110
1646
|
async runRawCliCommand(rawArgs, options = {}) {
|
|
1647
|
+
if (this.closed) {
|
|
1648
|
+
throw new ActoviqBridgeProcessError('The Actoviq Runtime client is closed.');
|
|
1649
|
+
}
|
|
1111
1650
|
if (options.signal?.aborted) {
|
|
1112
1651
|
throw new RunAbortedError('The Actoviq Runtime command was aborted before it started.');
|
|
1113
1652
|
}
|
|
1114
1653
|
const merged = this.mergeOptions(options);
|
|
1115
|
-
|
|
1654
|
+
if (this.closed)
|
|
1655
|
+
throw new ActoviqBridgeProcessError('The Actoviq Runtime client is closed.');
|
|
1656
|
+
if (options.signal?.aborted) {
|
|
1657
|
+
throw new RunAbortedError('The Actoviq Runtime command was aborted before it started.');
|
|
1658
|
+
}
|
|
1659
|
+
const childEnvironment = await buildChildEnvironment(this.provider, merged, this.directCli);
|
|
1116
1660
|
if (await prefersSystemRipgrep(merged.env)) {
|
|
1117
|
-
|
|
1661
|
+
childEnvironment.env.USE_BUILTIN_RIPGREP = '0';
|
|
1118
1662
|
}
|
|
1119
1663
|
const spawnArgs = this.directCli
|
|
1120
1664
|
? (this.cliPath ? [this.cliPath, ...rawArgs] : rawArgs)
|
|
1121
1665
|
: [merged.cliPath ?? this.cliPath, ...rawArgs];
|
|
1122
|
-
const
|
|
1666
|
+
const invocation = await resolveExecutableInvocation(merged.executable ?? this.executable, spawnArgs);
|
|
1667
|
+
if (this.closed)
|
|
1668
|
+
throw new ActoviqBridgeProcessError('The Actoviq Runtime client is closed.');
|
|
1669
|
+
if (options.signal?.aborted) {
|
|
1670
|
+
throw new RunAbortedError('The Actoviq Runtime command was aborted before it started.');
|
|
1671
|
+
}
|
|
1672
|
+
const child = spawn(invocation.file, invocation.args, {
|
|
1123
1673
|
cwd: merged.workDir ?? this.defaults.workDir ?? process.cwd(),
|
|
1124
|
-
env:
|
|
1674
|
+
env: childEnvironment.env,
|
|
1125
1675
|
stdio: ['ignore', 'pipe', 'pipe'],
|
|
1126
1676
|
windowsHide: true,
|
|
1127
|
-
shell:
|
|
1128
|
-
|
|
1677
|
+
shell: false,
|
|
1678
|
+
detached: !IS_WINDOWS,
|
|
1679
|
+
});
|
|
1680
|
+
this.activeChildren.add(child);
|
|
1681
|
+
child.once('close', () => {
|
|
1682
|
+
this.activeChildren.delete(child);
|
|
1683
|
+
this.activeChildReclaims.delete(child);
|
|
1129
1684
|
});
|
|
1130
1685
|
let aborted = false;
|
|
1686
|
+
let terminationPromise;
|
|
1131
1687
|
const abort = () => {
|
|
1132
1688
|
aborted = true;
|
|
1133
|
-
child
|
|
1689
|
+
terminationPromise ??= terminateActoviqProcessTree(child);
|
|
1134
1690
|
};
|
|
1691
|
+
this.activeChildReclaims.set(child, async () => {
|
|
1692
|
+
abort();
|
|
1693
|
+
if (terminationPromise)
|
|
1694
|
+
await terminationPromise;
|
|
1695
|
+
});
|
|
1135
1696
|
options.signal?.addEventListener('abort', abort, { once: true });
|
|
1136
|
-
|
|
1137
|
-
|
|
1697
|
+
if (options.signal?.aborted)
|
|
1698
|
+
abort();
|
|
1699
|
+
const stdoutPromise = readStdout(child).then(value => redactText(value, childEnvironment.secrets));
|
|
1700
|
+
const stderrPromise = readStderr(child).then(value => redactText(value, childEnvironment.secrets));
|
|
1138
1701
|
const exitCodePromise = new Promise((resolve, reject) => {
|
|
1139
1702
|
child.once('error', reject);
|
|
1140
1703
|
child.once('close', code => resolve(code));
|
|
@@ -1156,23 +1719,37 @@ export class ActoviqBridgeSdkClient {
|
|
|
1156
1719
|
return { stdout, stderr, exitCode };
|
|
1157
1720
|
}
|
|
1158
1721
|
catch (error) {
|
|
1722
|
+
terminationPromise ??= terminateActoviqProcessTree(child);
|
|
1159
1723
|
const normalized = asError(error);
|
|
1160
1724
|
if (aborted || isAbortErrorLike(normalized)) {
|
|
1161
1725
|
throw new RunAbortedError('The Actoviq Runtime command was aborted.', { cause: error });
|
|
1162
1726
|
}
|
|
1163
|
-
throw new ActoviqBridgeProcessError(normalized.message, { cause: error });
|
|
1727
|
+
throw new ActoviqBridgeProcessError(redactText(normalized.message, childEnvironment.secrets), { cause: error });
|
|
1164
1728
|
}
|
|
1165
1729
|
finally {
|
|
1166
1730
|
options.signal?.removeEventListener('abort', abort);
|
|
1731
|
+
if (terminationPromise)
|
|
1732
|
+
await terminationPromise;
|
|
1733
|
+
this.activeChildren.delete(child);
|
|
1734
|
+
this.activeChildReclaims.delete(child);
|
|
1735
|
+
await childEnvironment.cleanup?.();
|
|
1167
1736
|
}
|
|
1168
1737
|
}
|
|
1169
1738
|
async execute(prompt, options, controller) {
|
|
1739
|
+
if (this.closed) {
|
|
1740
|
+
throw new ActoviqBridgeProcessError('The Actoviq Runtime client is closed.');
|
|
1741
|
+
}
|
|
1170
1742
|
if (options.signal?.aborted) {
|
|
1171
1743
|
throw new RunAbortedError('The Actoviq Runtime run was aborted before it started.');
|
|
1172
1744
|
}
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1745
|
+
if (this.directCli && this.provider.id === 'reasonix') {
|
|
1746
|
+
return this.executeManagedReasonix(prompt, options, controller);
|
|
1747
|
+
}
|
|
1748
|
+
if (this.directCli && this.provider.id === 'crush') {
|
|
1749
|
+
return this.executeManagedCrush(prompt, options, controller);
|
|
1750
|
+
}
|
|
1751
|
+
if (options.signal?.aborted) {
|
|
1752
|
+
throw new RunAbortedError('The Actoviq Runtime run was aborted before it started.');
|
|
1176
1753
|
}
|
|
1177
1754
|
// argv: claude (bundle or directCli) reuses the full stream-json flag set
|
|
1178
1755
|
// in buildCliArgs(); pi/codex use their provider-specific buildArgs().
|
|
@@ -1182,45 +1759,104 @@ export class ActoviqBridgeSdkClient {
|
|
|
1182
1759
|
const args = this.directCli
|
|
1183
1760
|
? (this.cliPath ? [this.cliPath, ...cliArgs] : cliArgs)
|
|
1184
1761
|
: [options.cliPath ?? this.cliPath, ...cliArgs];
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
const
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1762
|
+
const invocation = await resolveExecutableInvocation(options.executable ?? this.executable, args);
|
|
1763
|
+
if (this.closed)
|
|
1764
|
+
throw new ActoviqBridgeProcessError('The Actoviq Runtime client is closed.');
|
|
1765
|
+
if (options.signal?.aborted) {
|
|
1766
|
+
throw new RunAbortedError('The Actoviq Runtime run was aborted before it started.');
|
|
1767
|
+
}
|
|
1768
|
+
const childEnvironment = await buildChildEnvironment(this.provider, options, this.directCli);
|
|
1769
|
+
if (await prefersSystemRipgrep(options.env)) {
|
|
1770
|
+
childEnvironment.env.USE_BUILTIN_RIPGREP = '0';
|
|
1771
|
+
}
|
|
1772
|
+
const normalizer = this.provider.createNormalizer(prompt, options);
|
|
1773
|
+
const effectiveWorkDir = path.resolve(options.workDir ?? this.defaults.workDir ?? process.cwd());
|
|
1774
|
+
const runStartedAtMs = Date.now();
|
|
1775
|
+
const child = spawn(invocation.file, invocation.args, {
|
|
1776
|
+
cwd: effectiveWorkDir,
|
|
1777
|
+
env: childEnvironment.env,
|
|
1778
|
+
stdio: [normalizer.interactive ? 'pipe' : 'ignore', 'pipe', 'pipe'],
|
|
1196
1779
|
windowsHide: true,
|
|
1197
|
-
shell:
|
|
1780
|
+
shell: false,
|
|
1781
|
+
detached: !IS_WINDOWS,
|
|
1782
|
+
});
|
|
1783
|
+
this.activeChildren.add(child);
|
|
1784
|
+
child.once('close', () => {
|
|
1785
|
+
this.activeChildren.delete(child);
|
|
1786
|
+
this.activeChildReclaims.delete(child);
|
|
1787
|
+
});
|
|
1788
|
+
let inputEnded = false;
|
|
1789
|
+
child.stdin?.on('error', () => {
|
|
1790
|
+
// The child may close stdin after its terminal protocol response. The
|
|
1791
|
+
// process exit/result path below remains the source of truth.
|
|
1198
1792
|
});
|
|
1199
|
-
const
|
|
1200
|
-
|
|
1793
|
+
const processControl = {
|
|
1794
|
+
write: record => {
|
|
1795
|
+
if (inputEnded || !child.stdin || child.stdin.destroyed)
|
|
1796
|
+
return;
|
|
1797
|
+
child.stdin.write(`${JSON.stringify(record)}\n`);
|
|
1798
|
+
},
|
|
1799
|
+
endInput: () => {
|
|
1800
|
+
if (inputEnded)
|
|
1801
|
+
return;
|
|
1802
|
+
inputEnded = true;
|
|
1803
|
+
child.stdin?.end();
|
|
1804
|
+
},
|
|
1805
|
+
};
|
|
1806
|
+
const retainedEvents = new BoundedRetention(MAX_RETAINED_RUN_EVENTS);
|
|
1807
|
+
const retainedAssistantMessages = new BoundedRetention(MAX_RETAINED_ASSISTANT_MESSAGES);
|
|
1201
1808
|
let initEvent;
|
|
1202
1809
|
let resultEvent;
|
|
1810
|
+
let codewhaleNativeSessionId;
|
|
1203
1811
|
let aborted = false;
|
|
1812
|
+
let terminationPromise;
|
|
1204
1813
|
const abort = () => {
|
|
1205
1814
|
aborted = true;
|
|
1206
|
-
|
|
1815
|
+
if (normalizer.abort) {
|
|
1816
|
+
normalizer.abort(processControl);
|
|
1817
|
+
terminationPromise ??= (async () => {
|
|
1818
|
+
await new Promise(resolve => setTimeout(resolve, normalizer.abortGraceMs ?? 250));
|
|
1819
|
+
await terminateActoviqProcessTree(child);
|
|
1820
|
+
})();
|
|
1821
|
+
}
|
|
1822
|
+
else {
|
|
1823
|
+
terminationPromise ??= terminateActoviqProcessTree(child);
|
|
1824
|
+
}
|
|
1207
1825
|
};
|
|
1826
|
+
// Close should request protocol cancel like AbortSignal, but leave the run
|
|
1827
|
+
// to surface a closed/exited error rather than RunAbortedError.
|
|
1828
|
+
this.activeChildReclaims.set(child, async () => {
|
|
1829
|
+
if (normalizer.abort) {
|
|
1830
|
+
normalizer.abort(processControl);
|
|
1831
|
+
terminationPromise ??= (async () => {
|
|
1832
|
+
await new Promise(resolve => setTimeout(resolve, normalizer.abortGraceMs ?? 250));
|
|
1833
|
+
await terminateActoviqProcessTree(child);
|
|
1834
|
+
})();
|
|
1835
|
+
}
|
|
1836
|
+
else {
|
|
1837
|
+
terminationPromise ??= terminateActoviqProcessTree(child);
|
|
1838
|
+
}
|
|
1839
|
+
if (terminationPromise)
|
|
1840
|
+
await terminationPromise;
|
|
1841
|
+
});
|
|
1208
1842
|
options.signal?.addEventListener('abort', abort, { once: true });
|
|
1209
|
-
|
|
1843
|
+
if (options.signal?.aborted)
|
|
1844
|
+
abort();
|
|
1845
|
+
normalizer.start?.(processControl);
|
|
1210
1846
|
const stdoutPromise = parseStdoutEvents(child, event => {
|
|
1211
|
-
|
|
1847
|
+
retainedEvents.push(structuredClone(event));
|
|
1212
1848
|
if (event.type === 'system' && event.subtype === 'init') {
|
|
1213
1849
|
initEvent = structuredClone(event);
|
|
1214
1850
|
}
|
|
1215
1851
|
if (event.type === 'assistant') {
|
|
1216
|
-
|
|
1852
|
+
retainedAssistantMessages.push(structuredClone(event));
|
|
1217
1853
|
}
|
|
1218
1854
|
if (event.type === 'result') {
|
|
1219
1855
|
resultEvent = structuredClone(event);
|
|
1220
1856
|
}
|
|
1221
1857
|
controller.emit(event);
|
|
1222
|
-
}, normalizer);
|
|
1223
|
-
const stderrPromise = readStderr(child);
|
|
1858
|
+
}, normalizer, processControl, childEnvironment.secrets);
|
|
1859
|
+
const stderrPromise = readStderr(child).then(value => redactText(value, childEnvironment.secrets));
|
|
1224
1860
|
const exitCodePromise = new Promise((resolve, reject) => {
|
|
1225
1861
|
child.once('error', reject);
|
|
1226
1862
|
child.once('close', code => resolve(code));
|
|
@@ -1229,16 +1865,43 @@ export class ActoviqBridgeSdkClient {
|
|
|
1229
1865
|
let exitCode = null;
|
|
1230
1866
|
try {
|
|
1231
1867
|
[stderr, exitCode] = await Promise.all([stderrPromise, exitCodePromise, stdoutPromise]).then(([nextStderr, nextExitCode]) => [nextStderr, nextExitCode]);
|
|
1868
|
+
if (this.provider.id === 'codewhale' && resultEvent) {
|
|
1869
|
+
const correlationHint = getStringValue(resultEvent, 'correlationHint')
|
|
1870
|
+
?? getStringValue(initEvent, 'correlationHint');
|
|
1871
|
+
if (correlationHint) {
|
|
1872
|
+
const codewhaleHome = environmentValue(childEnvironment.env, ['CODEWHALE_HOME']);
|
|
1873
|
+
codewhaleNativeSessionId = await resolveCodewhaleNativeSessionId({
|
|
1874
|
+
correlationHint,
|
|
1875
|
+
cwd: getStringValue(initEvent, 'cwd') ?? effectiveWorkDir,
|
|
1876
|
+
startedAtMs: runStartedAtMs,
|
|
1877
|
+
finishedAtMs: Date.now(),
|
|
1878
|
+
homeDir: options.homeDir
|
|
1879
|
+
?? environmentValue(childEnvironment.env, ['HOME', 'USERPROFILE']),
|
|
1880
|
+
codewhaleRoot: codewhaleHome
|
|
1881
|
+
? path.join(path.resolve(effectiveWorkDir, codewhaleHome), 'sessions')
|
|
1882
|
+
: undefined,
|
|
1883
|
+
}).catch(() => undefined);
|
|
1884
|
+
}
|
|
1885
|
+
}
|
|
1232
1886
|
}
|
|
1233
1887
|
catch (error) {
|
|
1888
|
+
// A parser/normalizer/pipe failure can reject before the CLI exits. Keep
|
|
1889
|
+
// the child supervised until its entire process tree has been reclaimed;
|
|
1890
|
+
// otherwise close() would lose it when the record is removed below.
|
|
1891
|
+
terminationPromise ??= terminateActoviqProcessTree(child);
|
|
1234
1892
|
const normalized = asError(error);
|
|
1235
1893
|
if (aborted || isAbortErrorLike(normalized)) {
|
|
1236
1894
|
throw new RunAbortedError('The Actoviq Runtime run was aborted.', { cause: error });
|
|
1237
1895
|
}
|
|
1238
|
-
throw new ActoviqBridgeProcessError(normalized.message, { cause: error, stderr, exitCode });
|
|
1896
|
+
throw new ActoviqBridgeProcessError(redactText(normalized.message, childEnvironment.secrets), { cause: error, stderr, exitCode });
|
|
1239
1897
|
}
|
|
1240
1898
|
finally {
|
|
1241
1899
|
options.signal?.removeEventListener('abort', abort);
|
|
1900
|
+
if (terminationPromise)
|
|
1901
|
+
await terminationPromise;
|
|
1902
|
+
this.activeChildren.delete(child);
|
|
1903
|
+
this.activeChildReclaims.delete(child);
|
|
1904
|
+
await childEnvironment.cleanup?.();
|
|
1242
1905
|
}
|
|
1243
1906
|
if (aborted && !resultEvent) {
|
|
1244
1907
|
throw new RunAbortedError('The Actoviq Runtime run was aborted.');
|
|
@@ -1248,10 +1911,13 @@ export class ActoviqBridgeSdkClient {
|
|
|
1248
1911
|
? `Actoviq Runtime exited without a result event: ${stderr.trim()}`
|
|
1249
1912
|
: 'Actoviq Runtime exited without emitting a result event.', { stderr, exitCode });
|
|
1250
1913
|
}
|
|
1914
|
+
const assistantMessages = retainedAssistantMessages.toArray();
|
|
1915
|
+
const events = retainedEvents.toArray();
|
|
1251
1916
|
const result = {
|
|
1252
1917
|
text: deriveResultText(resultEvent, assistantMessages),
|
|
1253
|
-
sessionId:
|
|
1254
|
-
|
|
1918
|
+
sessionId: getNonEmptyStringValue(resultEvent, 'session_id') ??
|
|
1919
|
+
getNonEmptyStringValue(initEvent, 'session_id') ??
|
|
1920
|
+
codewhaleNativeSessionId ??
|
|
1255
1921
|
options.sessionId ??
|
|
1256
1922
|
(typeof options.resume === 'string' ? options.resume : ''),
|
|
1257
1923
|
isError: getBooleanValue(resultEvent, 'is_error') ?? false,
|
|
@@ -1269,6 +1935,279 @@ export class ActoviqBridgeSdkClient {
|
|
|
1269
1935
|
};
|
|
1270
1936
|
return result;
|
|
1271
1937
|
}
|
|
1938
|
+
async executeManagedReasonix(prompt, options, controller) {
|
|
1939
|
+
assertManagedOptionsSupported('Reasonix', options);
|
|
1940
|
+
if (options.forkSession) {
|
|
1941
|
+
throw new ActoviqBridgeProcessError('Reasonix managed mode does not expose a native session-fork operation.');
|
|
1942
|
+
}
|
|
1943
|
+
if (options.resume === true || options.continueMostRecent) {
|
|
1944
|
+
throw new ActoviqBridgeProcessError('Reasonix managed mode requires an exact persisted session id.');
|
|
1945
|
+
}
|
|
1946
|
+
const nativeSessionId = typeof options.resume === 'string'
|
|
1947
|
+
? validateReasonixManagedSessionId(options.resume)
|
|
1948
|
+
: undefined;
|
|
1949
|
+
const cwd = path.resolve(options.workDir ?? this.defaults.workDir ?? process.cwd());
|
|
1950
|
+
const configFingerprint = reasonixConfigFingerprint(options);
|
|
1951
|
+
const logicalSessionId = (nativeSessionId ?? options.sessionId?.trim()) || '__default__';
|
|
1952
|
+
const aliasKey = reasonixManagedAliasKey(configFingerprint, cwd, logicalSessionId);
|
|
1953
|
+
const entry = await this.getOrCreateReasonixEntry(aliasKey, configFingerprint, cwd, nativeSessionId, options);
|
|
1954
|
+
const retainedEvents = new BoundedRetention(MAX_RETAINED_RUN_EVENTS);
|
|
1955
|
+
const retainedAssistantMessages = new BoundedRetention(MAX_RETAINED_ASSISTANT_MESSAGES);
|
|
1956
|
+
let initEvent;
|
|
1957
|
+
let resultEvent;
|
|
1958
|
+
const onEvent = (event) => {
|
|
1959
|
+
retainedEvents.push(structuredClone(event));
|
|
1960
|
+
if (event.type === 'system' && event.subtype === 'init') {
|
|
1961
|
+
initEvent = structuredClone(event);
|
|
1962
|
+
}
|
|
1963
|
+
if (event.type === 'assistant') {
|
|
1964
|
+
retainedAssistantMessages.push(structuredClone(event));
|
|
1965
|
+
}
|
|
1966
|
+
if (event.type === 'result') {
|
|
1967
|
+
resultEvent = structuredClone(event);
|
|
1968
|
+
}
|
|
1969
|
+
controller.emit(event);
|
|
1970
|
+
};
|
|
1971
|
+
try {
|
|
1972
|
+
const managed = await entry.client.run({
|
|
1973
|
+
prompt,
|
|
1974
|
+
model: options.model,
|
|
1975
|
+
effort: options.effort,
|
|
1976
|
+
maxBudgetUsd: options.maxBudgetUsd,
|
|
1977
|
+
permissionMode: options.dangerouslySkipPermissions
|
|
1978
|
+
? 'bypassPermissions'
|
|
1979
|
+
: options.permissionMode ?? 'default',
|
|
1980
|
+
signal: options.signal,
|
|
1981
|
+
onEvent,
|
|
1982
|
+
});
|
|
1983
|
+
if (!resultEvent) {
|
|
1984
|
+
await this.releaseReasonixEntry(entry);
|
|
1985
|
+
throw new ActoviqBridgeProcessError(managed.stderr.trim()
|
|
1986
|
+
? `Reasonix exited without a result event: ${managed.stderr.trim()}`
|
|
1987
|
+
: 'Reasonix exited without emitting a result event.', { stderr: managed.stderr, exitCode: managed.exitCode });
|
|
1988
|
+
}
|
|
1989
|
+
if (managed.reusable && managed.sessionId) {
|
|
1990
|
+
await writeReasonixTranscriptMetadata(entry, {
|
|
1991
|
+
sessionId: managed.sessionId,
|
|
1992
|
+
cwd,
|
|
1993
|
+
model: options.model,
|
|
1994
|
+
prompt,
|
|
1995
|
+
}).catch(() => undefined);
|
|
1996
|
+
this.reasonixManagedEntries.set(reasonixManagedAliasKey(configFingerprint, cwd, managed.sessionId), entry);
|
|
1997
|
+
}
|
|
1998
|
+
else if (!managed.reusable) {
|
|
1999
|
+
await this.releaseReasonixEntry(entry);
|
|
2000
|
+
}
|
|
2001
|
+
const assistantMessages = retainedAssistantMessages.toArray();
|
|
2002
|
+
return {
|
|
2003
|
+
text: deriveResultText(resultEvent, assistantMessages),
|
|
2004
|
+
sessionId: getNonEmptyStringValue(resultEvent, 'session_id')
|
|
2005
|
+
?? getNonEmptyStringValue(initEvent, 'session_id')
|
|
2006
|
+
?? managed.sessionId,
|
|
2007
|
+
isError: getBooleanValue(resultEvent, 'is_error') ?? false,
|
|
2008
|
+
subtype: getStringValue(resultEvent, 'subtype'),
|
|
2009
|
+
stopReason: getStringValue(resultEvent, 'stop_reason'),
|
|
2010
|
+
durationMs: getNumberValue(resultEvent, 'duration_ms'),
|
|
2011
|
+
totalCostUsd: getNumberValue(resultEvent, 'total_cost_usd'),
|
|
2012
|
+
numTurns: getNumberValue(resultEvent, 'num_turns'),
|
|
2013
|
+
exitCode: managed.exitCode,
|
|
2014
|
+
stderr: managed.stderr,
|
|
2015
|
+
initEvent,
|
|
2016
|
+
resultEvent,
|
|
2017
|
+
assistantMessages,
|
|
2018
|
+
events: retainedEvents.toArray(),
|
|
2019
|
+
};
|
|
2020
|
+
}
|
|
2021
|
+
catch (error) {
|
|
2022
|
+
await this.releaseReasonixEntry(entry);
|
|
2023
|
+
const normalized = asError(error);
|
|
2024
|
+
if (options.signal?.aborted || isAbortErrorLike(normalized)) {
|
|
2025
|
+
throw new RunAbortedError('The Reasonix managed run was aborted.', { cause: error });
|
|
2026
|
+
}
|
|
2027
|
+
if (error instanceof ActoviqBridgeProcessError)
|
|
2028
|
+
throw error;
|
|
2029
|
+
throw new ActoviqBridgeProcessError(normalized.message, { cause: error });
|
|
2030
|
+
}
|
|
2031
|
+
}
|
|
2032
|
+
async getOrCreateReasonixEntry(aliasKey, configFingerprint, cwd, nativeSessionId, options) {
|
|
2033
|
+
const cached = this.reasonixManagedEntries.get(aliasKey);
|
|
2034
|
+
if (cached)
|
|
2035
|
+
return cached;
|
|
2036
|
+
const pending = this.reasonixManagedEntryPromises.get(aliasKey);
|
|
2037
|
+
if (pending)
|
|
2038
|
+
return pending;
|
|
2039
|
+
const creation = (async () => {
|
|
2040
|
+
const childEnvironment = await buildChildEnvironment(this.provider, options, true);
|
|
2041
|
+
try {
|
|
2042
|
+
const cliArgs = this.provider.buildArgs('', options);
|
|
2043
|
+
const transcriptRoot = path.join(await persistentExternalCliProfile(this.provider, options), '.reasonix', 'sessions');
|
|
2044
|
+
await ensurePrivateDirectory(transcriptRoot);
|
|
2045
|
+
const transcriptIdentity = nativeSessionId
|
|
2046
|
+
? createHash('sha256').update(nativeSessionId).digest('hex').slice(0, 32)
|
|
2047
|
+
: randomUUID();
|
|
2048
|
+
const transcriptPath = path.join(transcriptRoot, `managed-${transcriptIdentity}.jsonl`);
|
|
2049
|
+
cliArgs.push('--dir', cwd, '--transcript', transcriptPath);
|
|
2050
|
+
const args = this.cliPath ? [this.cliPath, ...cliArgs] : cliArgs;
|
|
2051
|
+
const invocation = await resolveExecutableInvocation(options.executable ?? this.executable, args);
|
|
2052
|
+
if (this.closed) {
|
|
2053
|
+
throw new ActoviqBridgeProcessError('The Actoviq Runtime client is closed.');
|
|
2054
|
+
}
|
|
2055
|
+
const client = createReasonixManagedClient({
|
|
2056
|
+
executable: invocation.file,
|
|
2057
|
+
args: invocation.args,
|
|
2058
|
+
cwd,
|
|
2059
|
+
env: childEnvironment.env,
|
|
2060
|
+
nativeSessionId,
|
|
2061
|
+
secrets: childEnvironment.secrets,
|
|
2062
|
+
onSpawn: child => {
|
|
2063
|
+
this.activeChildren.add(child);
|
|
2064
|
+
child.once('close', () => {
|
|
2065
|
+
this.activeChildren.delete(child);
|
|
2066
|
+
});
|
|
2067
|
+
},
|
|
2068
|
+
});
|
|
2069
|
+
const entry = {
|
|
2070
|
+
client,
|
|
2071
|
+
transcriptPath,
|
|
2072
|
+
transcriptCreatedAt: new Date().toISOString(),
|
|
2073
|
+
cleanup: childEnvironment.cleanup,
|
|
2074
|
+
};
|
|
2075
|
+
this.reasonixManagedEntries.set(aliasKey, entry);
|
|
2076
|
+
return entry;
|
|
2077
|
+
}
|
|
2078
|
+
catch (error) {
|
|
2079
|
+
await childEnvironment.cleanup?.();
|
|
2080
|
+
throw error;
|
|
2081
|
+
}
|
|
2082
|
+
})();
|
|
2083
|
+
this.reasonixManagedEntryPromises.set(aliasKey, creation);
|
|
2084
|
+
try {
|
|
2085
|
+
return await creation;
|
|
2086
|
+
}
|
|
2087
|
+
finally {
|
|
2088
|
+
if (this.reasonixManagedEntryPromises.get(aliasKey) === creation) {
|
|
2089
|
+
this.reasonixManagedEntryPromises.delete(aliasKey);
|
|
2090
|
+
}
|
|
2091
|
+
}
|
|
2092
|
+
}
|
|
2093
|
+
async releaseReasonixEntry(entry) {
|
|
2094
|
+
for (const [key, candidate] of this.reasonixManagedEntries) {
|
|
2095
|
+
if (candidate === entry)
|
|
2096
|
+
this.reasonixManagedEntries.delete(key);
|
|
2097
|
+
}
|
|
2098
|
+
if (!entry.cleanupPromise) {
|
|
2099
|
+
entry.cleanupPromise = (async () => {
|
|
2100
|
+
await entry.client.close().catch(() => undefined);
|
|
2101
|
+
await entry.cleanup?.().catch(() => undefined);
|
|
2102
|
+
})();
|
|
2103
|
+
}
|
|
2104
|
+
await entry.cleanupPromise;
|
|
2105
|
+
}
|
|
2106
|
+
async executeManagedCrush(prompt, options, controller) {
|
|
2107
|
+
assertManagedOptionsSupported('Crush', options, ['effort', 'maxBudgetUsd']);
|
|
2108
|
+
if (options.forkSession) {
|
|
2109
|
+
throw new ActoviqBridgeProcessError('Crush managed mode does not expose a native session-fork operation.');
|
|
2110
|
+
}
|
|
2111
|
+
if (options.resume === true || options.continueMostRecent) {
|
|
2112
|
+
throw new ActoviqBridgeProcessError('Crush managed mode requires an exact native session id to resume.');
|
|
2113
|
+
}
|
|
2114
|
+
const cwd = path.resolve(options.workDir ?? this.defaults.workDir ?? process.cwd());
|
|
2115
|
+
if (options.trustProjectResources !== true) {
|
|
2116
|
+
const projectConfig = await findCrushProjectConfig(cwd);
|
|
2117
|
+
if (projectConfig) {
|
|
2118
|
+
throw new ActoviqBridgeProcessError(`Crush project config requires trustProjectResources: ${projectConfig}`);
|
|
2119
|
+
}
|
|
2120
|
+
}
|
|
2121
|
+
const childEnvironment = await buildChildEnvironment(this.provider, options, true);
|
|
2122
|
+
const retainedEvents = new BoundedRetention(MAX_RETAINED_RUN_EVENTS);
|
|
2123
|
+
const retainedAssistantMessages = new BoundedRetention(MAX_RETAINED_ASSISTANT_MESSAGES);
|
|
2124
|
+
let initEvent;
|
|
2125
|
+
let resultEvent;
|
|
2126
|
+
const onEvent = (event) => {
|
|
2127
|
+
retainedEvents.push(structuredClone(event));
|
|
2128
|
+
if (event.type === 'system' && event.subtype === 'init') {
|
|
2129
|
+
initEvent = structuredClone(event);
|
|
2130
|
+
}
|
|
2131
|
+
if (event.type === 'assistant') {
|
|
2132
|
+
retainedAssistantMessages.push(structuredClone(event));
|
|
2133
|
+
}
|
|
2134
|
+
if (event.type === 'result') {
|
|
2135
|
+
resultEvent = structuredClone(event);
|
|
2136
|
+
}
|
|
2137
|
+
controller.emit(event);
|
|
2138
|
+
};
|
|
2139
|
+
try {
|
|
2140
|
+
const credentialProvider = credentialProviderHint(options);
|
|
2141
|
+
const explicitApiKeyMode = (options.authSource ?? 'native') === 'apiKey';
|
|
2142
|
+
const credentialKeys = providerCredentialKeys(this.provider, options);
|
|
2143
|
+
const credentialBaseUrlKeys = credentialKeys
|
|
2144
|
+
.map(key => key.replace(/_API_KEY$/u, '_BASE_URL'));
|
|
2145
|
+
const managed = await runCrushManaged({
|
|
2146
|
+
executable: options.executable ?? this.executable,
|
|
2147
|
+
executableArgs: this.cliPath ? [this.cliPath] : undefined,
|
|
2148
|
+
cwd,
|
|
2149
|
+
prompt,
|
|
2150
|
+
nativeSessionId: typeof options.resume === 'string' ? options.resume : undefined,
|
|
2151
|
+
model: crushManagedModel(options, credentialProvider),
|
|
2152
|
+
credentialProvider,
|
|
2153
|
+
apiKey: explicitApiKeyMode
|
|
2154
|
+
? environmentValue(childEnvironment.env, credentialKeys)
|
|
2155
|
+
: undefined,
|
|
2156
|
+
baseURL: explicitApiKeyMode
|
|
2157
|
+
? options.baseURL
|
|
2158
|
+
?? environmentValue(childEnvironment.env, credentialBaseUrlKeys)
|
|
2159
|
+
: undefined,
|
|
2160
|
+
permissionMode: options.dangerouslySkipPermissions
|
|
2161
|
+
? 'bypassPermissions'
|
|
2162
|
+
: options.permissionMode,
|
|
2163
|
+
env: childEnvironment.env,
|
|
2164
|
+
inheritEnvironment: false,
|
|
2165
|
+
signal: options.signal,
|
|
2166
|
+
spawnFn: (file, args, spawnOptions) => {
|
|
2167
|
+
const child = spawn(file, [...args], spawnOptions);
|
|
2168
|
+
this.activeChildren.add(child);
|
|
2169
|
+
child.once('close', () => this.activeChildren.delete(child));
|
|
2170
|
+
return child;
|
|
2171
|
+
},
|
|
2172
|
+
}, onEvent);
|
|
2173
|
+
if (!resultEvent) {
|
|
2174
|
+
throw new ActoviqBridgeProcessError(managed.stderr.trim()
|
|
2175
|
+
? `Crush exited without a result event: ${managed.stderr.trim()}`
|
|
2176
|
+
: 'Crush exited without emitting a result event.', { stderr: managed.stderr, exitCode: managed.exitCode });
|
|
2177
|
+
}
|
|
2178
|
+
const assistantMessages = retainedAssistantMessages.toArray();
|
|
2179
|
+
return {
|
|
2180
|
+
text: deriveResultText(resultEvent, assistantMessages),
|
|
2181
|
+
sessionId: getStringValue(resultEvent, 'session_id')
|
|
2182
|
+
?? getStringValue(initEvent, 'session_id')
|
|
2183
|
+
?? managed.sessionId,
|
|
2184
|
+
isError: getBooleanValue(resultEvent, 'is_error') ?? false,
|
|
2185
|
+
subtype: getStringValue(resultEvent, 'subtype'),
|
|
2186
|
+
stopReason: getStringValue(resultEvent, 'stop_reason'),
|
|
2187
|
+
durationMs: getNumberValue(resultEvent, 'duration_ms'),
|
|
2188
|
+
totalCostUsd: getNumberValue(resultEvent, 'total_cost_usd'),
|
|
2189
|
+
numTurns: getNumberValue(resultEvent, 'num_turns'),
|
|
2190
|
+
exitCode: managed.exitCode,
|
|
2191
|
+
stderr: managed.stderr,
|
|
2192
|
+
initEvent,
|
|
2193
|
+
resultEvent,
|
|
2194
|
+
assistantMessages,
|
|
2195
|
+
events: retainedEvents.toArray(),
|
|
2196
|
+
};
|
|
2197
|
+
}
|
|
2198
|
+
catch (error) {
|
|
2199
|
+
const normalized = asError(error);
|
|
2200
|
+
if (options.signal?.aborted || isAbortErrorLike(normalized)) {
|
|
2201
|
+
throw new RunAbortedError('The Crush managed run was aborted.', { cause: error });
|
|
2202
|
+
}
|
|
2203
|
+
if (error instanceof ActoviqBridgeProcessError)
|
|
2204
|
+
throw error;
|
|
2205
|
+
throw new ActoviqBridgeProcessError(redactText(normalized.message, childEnvironment.secrets), { cause: error });
|
|
2206
|
+
}
|
|
2207
|
+
finally {
|
|
2208
|
+
await childEnvironment.cleanup?.();
|
|
2209
|
+
}
|
|
2210
|
+
}
|
|
1272
2211
|
}
|
|
1273
2212
|
export async function createActoviqBridgeSdk(options = {}) {
|
|
1274
2213
|
return ActoviqBridgeSdkClient.create(options);
|