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
|
@@ -0,0 +1,1436 @@
|
|
|
1
|
+
import { Buffer } from 'node:buffer';
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { createReadStream, realpath as realpathCallback } from 'node:fs';
|
|
4
|
+
import { lstat, readdir, stat } from 'node:fs/promises';
|
|
5
|
+
import os from 'node:os';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import { promisify } from 'node:util';
|
|
8
|
+
import { resolveActoviqHome } from '../config/actoviqHome.js';
|
|
9
|
+
import { ActoviqSdkError } from '../errors.js';
|
|
10
|
+
import { isCrushSessionReference, listCrushSessionHistory, parseCrushSessionReferenceDetails, readCrushSessionHistory, } from './crushSessionHistory.js';
|
|
11
|
+
import { parseReasonixSessionJsonl, resolveReasonixSessionRoots, } from './reasonixSessionParser.js';
|
|
12
|
+
/** Prefer native realpath so Windows 8.3 short names canonicalize consistently. */
|
|
13
|
+
const realpathNative = promisify(realpathCallback.native);
|
|
14
|
+
const DEFAULT_SUMMARY_MAX_BYTES = 128 * 1024;
|
|
15
|
+
const DEFAULT_SUMMARY_MAX_MESSAGES = 512;
|
|
16
|
+
const DEFAULT_DETAIL_MAX_BYTES = 16 * 1024 * 1024;
|
|
17
|
+
const DEFAULT_DETAIL_MAX_MESSAGES = 4_000;
|
|
18
|
+
const MAX_REASONIX_METADATA_BYTES = 256 * 1024;
|
|
19
|
+
const MAX_SUMMARY_CACHE_ENTRIES = 1_000;
|
|
20
|
+
const DEFAULT_CODEWHALE_CORRELATION_CLOCK_SKEW_MS = 5_000;
|
|
21
|
+
const CODEWHALE_LOG_FINGERPRINT_OFFSET_BASIS = 0xcbf29ce484222325n;
|
|
22
|
+
const CODEWHALE_LOG_FINGERPRINT_PRIME = 0x00000100000001b3n;
|
|
23
|
+
const CODEWHALE_REDACTED_IDENTIFIER = /^<redacted:[0-9a-f]{16}>$/u;
|
|
24
|
+
const MANAGED_PROFILE_ID_PATTERN = /^[0-9a-f]{64}$/u;
|
|
25
|
+
const MAX_MANAGED_PROFILES_PER_RUNTIME = 256;
|
|
26
|
+
const MAX_CRUSH_HISTORY_COMMAND_CONCURRENCY = 8;
|
|
27
|
+
const ISOLATED_MANAGED_PROFILE_RUNTIMES = new Set([
|
|
28
|
+
'pi',
|
|
29
|
+
'codewhale',
|
|
30
|
+
'reasonix',
|
|
31
|
+
'crush',
|
|
32
|
+
]);
|
|
33
|
+
const summaryCache = new Map();
|
|
34
|
+
export function namedExternalCliManagedProfileId(runtime, profileName) {
|
|
35
|
+
const normalizedName = profileName.trim();
|
|
36
|
+
if (!normalizedName)
|
|
37
|
+
throw new TypeError('External CLI managed profile name is required.');
|
|
38
|
+
return createHash('sha256')
|
|
39
|
+
.update(`${runtime}\0name:${normalizedName}`)
|
|
40
|
+
.digest('hex');
|
|
41
|
+
}
|
|
42
|
+
function sessionManagedProfileId(summary, options) {
|
|
43
|
+
if (summary.runtime === 'crush') {
|
|
44
|
+
return parseCrushSessionReferenceDetails(summary.path)?.managedProfileId;
|
|
45
|
+
}
|
|
46
|
+
if (!ISOLATED_MANAGED_PROFILE_RUNTIMES.has(summary.runtime))
|
|
47
|
+
return undefined;
|
|
48
|
+
const runtimeRoot = path.resolve(resolveManagedActoviqHome(options), 'external-cli-profiles', summary.runtime);
|
|
49
|
+
const relative = path.relative(runtimeRoot, path.resolve(summary.path));
|
|
50
|
+
if (!relative
|
|
51
|
+
|| relative === '..'
|
|
52
|
+
|| relative.startsWith(`..${path.sep}`)
|
|
53
|
+
|| path.isAbsolute(relative)) {
|
|
54
|
+
return undefined;
|
|
55
|
+
}
|
|
56
|
+
const [profileId] = relative.split(path.sep);
|
|
57
|
+
return MANAGED_PROFILE_ID_PATTERN.test(profileId ?? '') ? profileId : undefined;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Bind a discovered history entry to the same native-login or isolated-key
|
|
61
|
+
* store used by a saved CLI config. Runtime + native session id alone is not
|
|
62
|
+
* sufficient because different stores may legally reuse the same id.
|
|
63
|
+
*/
|
|
64
|
+
export function externalCliSessionMatchesConfig(summary, config, options = {}) {
|
|
65
|
+
if (summary.runtime !== config.runtime)
|
|
66
|
+
return false;
|
|
67
|
+
if (!ISOLATED_MANAGED_PROFILE_RUNTIMES.has(summary.runtime))
|
|
68
|
+
return true;
|
|
69
|
+
const actualProfileId = sessionManagedProfileId(summary, options);
|
|
70
|
+
if (config.authSource !== 'apiKey')
|
|
71
|
+
return actualProfileId === undefined;
|
|
72
|
+
if (!config.profileName?.trim())
|
|
73
|
+
return false;
|
|
74
|
+
return actualProfileId === namedExternalCliManagedProfileId(summary.runtime, config.profileName);
|
|
75
|
+
}
|
|
76
|
+
/** Matches CodeWhale's official redacted_identifier_for_log correlation value. */
|
|
77
|
+
export function codewhaleRedactedIdentifierForLog(identifier) {
|
|
78
|
+
if (!identifier) {
|
|
79
|
+
return '<redacted:empty>';
|
|
80
|
+
}
|
|
81
|
+
const bytes = Buffer.from(identifier, 'utf8');
|
|
82
|
+
let hash = CODEWHALE_LOG_FINGERPRINT_OFFSET_BASIS;
|
|
83
|
+
for (const byte of bytes) {
|
|
84
|
+
hash = BigInt.asUintN(64, (hash ^ BigInt(byte)) * CODEWHALE_LOG_FINGERPRINT_PRIME);
|
|
85
|
+
}
|
|
86
|
+
hash = BigInt.asUintN(64, (hash ^ BigInt(bytes.length)) * CODEWHALE_LOG_FINGERPRINT_PRIME);
|
|
87
|
+
return `<redacted:${hash.toString(16).padStart(16, '0')}>`;
|
|
88
|
+
}
|
|
89
|
+
export async function resolveCodewhaleNativeSessionId(options) {
|
|
90
|
+
const finishedAtMs = options.finishedAtMs ?? Date.now();
|
|
91
|
+
if (!CODEWHALE_REDACTED_IDENTIFIER.test(options.correlationHint)
|
|
92
|
+
|| !options.cwd.trim()
|
|
93
|
+
|| !Number.isFinite(options.startedAtMs)
|
|
94
|
+
|| !Number.isFinite(finishedAtMs)
|
|
95
|
+
|| finishedAtMs < options.startedAtMs) {
|
|
96
|
+
return undefined;
|
|
97
|
+
}
|
|
98
|
+
const clockSkewMs = normalizedNonNegativeInteger(options.clockSkewMs, DEFAULT_CODEWHALE_CORRELATION_CLOCK_SKEW_MS);
|
|
99
|
+
const earliestMtimeMs = options.startedAtMs - clockSkewMs;
|
|
100
|
+
const latestMtimeMs = finishedAtMs + clockSkewMs;
|
|
101
|
+
const nativeSessionIds = new Set();
|
|
102
|
+
const seenPaths = new Set();
|
|
103
|
+
for (const configuredRoot of await getConfiguredRoots(options)) {
|
|
104
|
+
if (configuredRoot.runtime !== 'codewhale') {
|
|
105
|
+
continue;
|
|
106
|
+
}
|
|
107
|
+
const root = await resolveDirectory(configuredRoot.root);
|
|
108
|
+
if (!root) {
|
|
109
|
+
continue;
|
|
110
|
+
}
|
|
111
|
+
for (const filePath of await collectCodewhaleSessionFiles(root)) {
|
|
112
|
+
const candidate = await inspectSessionFile('codewhale', root, filePath);
|
|
113
|
+
if (!candidate
|
|
114
|
+
|| seenPaths.has(candidate.path)
|
|
115
|
+
|| candidate.stats.mtimeMs < earliestMtimeMs
|
|
116
|
+
|| candidate.stats.mtimeMs > latestMtimeMs) {
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
seenPaths.add(candidate.path);
|
|
120
|
+
const savedSession = await readCodewhaleSavedSessionPrefix(candidate.path, candidate.stats, DEFAULT_SUMMARY_MAX_BYTES);
|
|
121
|
+
if (!savedSession) {
|
|
122
|
+
continue;
|
|
123
|
+
}
|
|
124
|
+
const nativeSessionId = stringValue(savedSession.metadata.id);
|
|
125
|
+
const workspace = stringValue(savedSession.metadata.workspace);
|
|
126
|
+
if (nativeSessionId
|
|
127
|
+
&& workspace
|
|
128
|
+
&& sameResolvedPath(workspace, options.cwd)
|
|
129
|
+
&& codewhaleRedactedIdentifierForLog(nativeSessionId) === options.correlationHint) {
|
|
130
|
+
nativeSessionIds.add(nativeSessionId);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
return nativeSessionIds.size === 1 ? nativeSessionIds.values().next().value : undefined;
|
|
135
|
+
}
|
|
136
|
+
export async function listExternalCliSessions(options = {}) {
|
|
137
|
+
const candidates = [];
|
|
138
|
+
const seenPaths = new Set();
|
|
139
|
+
for (const configuredRoot of await getConfiguredRoots(options)) {
|
|
140
|
+
if (options.runtimes?.length && !options.runtimes.includes(configuredRoot.runtime)) {
|
|
141
|
+
continue;
|
|
142
|
+
}
|
|
143
|
+
const root = await resolveDirectory(configuredRoot.root);
|
|
144
|
+
if (!root) {
|
|
145
|
+
continue;
|
|
146
|
+
}
|
|
147
|
+
const sessionFiles = configuredRoot.runtime === 'codewhale'
|
|
148
|
+
? await collectCodewhaleSessionFiles(root)
|
|
149
|
+
: configuredRoot.runtime === 'reasonix'
|
|
150
|
+
? await collectReasonixSessionFiles(root)
|
|
151
|
+
: await collectJsonlFiles(root);
|
|
152
|
+
for (const filePath of sessionFiles) {
|
|
153
|
+
const candidate = await inspectSessionFile(configuredRoot.runtime, root, filePath);
|
|
154
|
+
if (!candidate || seenPaths.has(candidate.path)) {
|
|
155
|
+
continue;
|
|
156
|
+
}
|
|
157
|
+
seenPaths.add(candidate.path);
|
|
158
|
+
candidates.push(candidate);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
const includeCrush = options.runtimes?.includes('crush') === true
|
|
162
|
+
|| (!options.runtimes?.length && Boolean(options.crushCwd));
|
|
163
|
+
const managedCrushProfiles = includeCrush
|
|
164
|
+
? await managedCrushHistoryProfiles(options)
|
|
165
|
+
: [];
|
|
166
|
+
const crushHistorySources = includeCrush
|
|
167
|
+
? [
|
|
168
|
+
toCrushHistoryOptions(options),
|
|
169
|
+
...managedCrushProfiles.map(profile => toCrushHistoryOptions(options, profile)),
|
|
170
|
+
]
|
|
171
|
+
: [];
|
|
172
|
+
const crushSummaries = [];
|
|
173
|
+
for (let sourceIndex = 0; sourceIndex < crushHistorySources.length; sourceIndex += MAX_CRUSH_HISTORY_COMMAND_CONCURRENCY) {
|
|
174
|
+
const summaryGroups = await Promise.all(crushHistorySources
|
|
175
|
+
.slice(sourceIndex, sourceIndex + MAX_CRUSH_HISTORY_COMMAND_CONCURRENCY)
|
|
176
|
+
.map(source => listCrushSessionHistory(source).catch(() => [])));
|
|
177
|
+
crushSummaries.push(...summaryGroups.flat());
|
|
178
|
+
}
|
|
179
|
+
const entries = [
|
|
180
|
+
...candidates.map(candidate => ({
|
|
181
|
+
kind: 'file',
|
|
182
|
+
candidate,
|
|
183
|
+
sortTime: candidate.stats.mtimeMs,
|
|
184
|
+
path: candidate.path,
|
|
185
|
+
})),
|
|
186
|
+
...crushSummaries.map(summary => ({
|
|
187
|
+
kind: 'crush',
|
|
188
|
+
summary,
|
|
189
|
+
sortTime: Date.parse(summary.updatedAt),
|
|
190
|
+
path: summary.path,
|
|
191
|
+
})),
|
|
192
|
+
];
|
|
193
|
+
entries.sort((left, right) => {
|
|
194
|
+
const timeDifference = right.sortTime - left.sortTime;
|
|
195
|
+
return timeDifference || left.path.localeCompare(right.path);
|
|
196
|
+
});
|
|
197
|
+
const offset = normalizedNonNegativeInteger(options.offset, 0);
|
|
198
|
+
const limit = options.limit == null
|
|
199
|
+
? entries.length
|
|
200
|
+
: normalizedNonNegativeInteger(options.limit, entries.length);
|
|
201
|
+
const selectedEntries = entries.slice(offset, offset + limit);
|
|
202
|
+
const bounds = {
|
|
203
|
+
maxBytes: normalizedPositiveInteger(options.summaryMaxBytes, DEFAULT_SUMMARY_MAX_BYTES),
|
|
204
|
+
maxMessages: normalizedPositiveInteger(options.summaryMaxMessages, DEFAULT_SUMMARY_MAX_MESSAGES),
|
|
205
|
+
};
|
|
206
|
+
const summaries = [];
|
|
207
|
+
for (const entry of selectedEntries) {
|
|
208
|
+
if (entry.kind === 'crush') {
|
|
209
|
+
summaries.push(entry.summary);
|
|
210
|
+
continue;
|
|
211
|
+
}
|
|
212
|
+
const candidate = entry.candidate;
|
|
213
|
+
// Reasonix summary fields can change in a metadata sidecar while the
|
|
214
|
+
// checkpoint JSONL itself remains untouched.
|
|
215
|
+
const cached = candidate.runtime === 'reasonix'
|
|
216
|
+
? undefined
|
|
217
|
+
: getCachedSummary(candidate, bounds);
|
|
218
|
+
if (cached) {
|
|
219
|
+
summaries.push(cached);
|
|
220
|
+
continue;
|
|
221
|
+
}
|
|
222
|
+
const session = await parseSessionFile(candidate.runtime, candidate.path, bounds, candidate.stats);
|
|
223
|
+
if (session) {
|
|
224
|
+
if (candidate.runtime !== 'reasonix') {
|
|
225
|
+
cacheSummary(candidate, bounds, session.summary);
|
|
226
|
+
}
|
|
227
|
+
summaries.push(session.summary);
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
return summaries;
|
|
231
|
+
}
|
|
232
|
+
export async function readExternalCliSession(filePath, options = {}) {
|
|
233
|
+
if (isCrushSessionReference(filePath)) {
|
|
234
|
+
if (options.runtimes?.length && !options.runtimes.includes('crush'))
|
|
235
|
+
return undefined;
|
|
236
|
+
const reference = parseCrushSessionReferenceDetails(filePath);
|
|
237
|
+
if (!reference)
|
|
238
|
+
return undefined;
|
|
239
|
+
if (!reference.managedProfileId) {
|
|
240
|
+
return readCrushSessionHistory(filePath, toCrushHistoryOptions(options));
|
|
241
|
+
}
|
|
242
|
+
const profile = (await managedCrushHistoryProfiles(options))
|
|
243
|
+
.find(candidate => candidate.id === reference.managedProfileId);
|
|
244
|
+
if (!profile)
|
|
245
|
+
return undefined;
|
|
246
|
+
return readCrushSessionHistory(filePath, toCrushHistoryOptions(options, profile));
|
|
247
|
+
}
|
|
248
|
+
const requestedPath = path.resolve(filePath);
|
|
249
|
+
const canonicalPath = await resolveFile(requestedPath);
|
|
250
|
+
if (!canonicalPath) {
|
|
251
|
+
return undefined;
|
|
252
|
+
}
|
|
253
|
+
// Canonicalize roots before containment checks so Windows short/long path
|
|
254
|
+
// forms of the same directory are not treated as distinct trees.
|
|
255
|
+
const allowedRoots = [];
|
|
256
|
+
for (const configuredRoot of await getConfiguredRoots(options)) {
|
|
257
|
+
const canonicalRoot = await resolveDirectory(configuredRoot.root);
|
|
258
|
+
if (canonicalRoot && isPathInside(canonicalRoot, canonicalPath)) {
|
|
259
|
+
allowedRoots.push({ ...configuredRoot, root: canonicalRoot });
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
if (allowedRoots.length === 0) {
|
|
263
|
+
throw unsafeSessionPath(requestedPath);
|
|
264
|
+
}
|
|
265
|
+
const root = allowedRoots
|
|
266
|
+
.filter(allowedRoot => isSessionFileForRuntime(allowedRoot, canonicalPath))
|
|
267
|
+
.sort((left, right) => right.root.length - left.root.length)[0];
|
|
268
|
+
if (!root) {
|
|
269
|
+
return undefined;
|
|
270
|
+
}
|
|
271
|
+
return parseSessionFile(root.runtime, canonicalPath, {
|
|
272
|
+
maxBytes: normalizedPositiveInteger(options.detailMaxBytes, DEFAULT_DETAIL_MAX_BYTES),
|
|
273
|
+
maxMessages: normalizedPositiveInteger(options.detailMaxMessages, DEFAULT_DETAIL_MAX_MESSAGES),
|
|
274
|
+
});
|
|
275
|
+
}
|
|
276
|
+
function toCrushHistoryOptions(options, profile) {
|
|
277
|
+
return {
|
|
278
|
+
executable: options.crushExecutable,
|
|
279
|
+
cwd: options.crushCwd,
|
|
280
|
+
env: profile
|
|
281
|
+
? { ...options.crushEnv, CRUSH_GLOBAL_DATA: profile.dataDir }
|
|
282
|
+
: options.crushEnv,
|
|
283
|
+
commandRunner: options.crushCommandRunner,
|
|
284
|
+
maxOutputBytes: options.detailMaxBytes,
|
|
285
|
+
maxMessages: options.detailMaxMessages,
|
|
286
|
+
managedProfileId: profile?.id,
|
|
287
|
+
};
|
|
288
|
+
}
|
|
289
|
+
async function getConfiguredRoots(options) {
|
|
290
|
+
const homeDir = path.resolve(options.homeDir ?? os.homedir());
|
|
291
|
+
const explicitRootMode = Boolean(options.claudeRoot
|
|
292
|
+
|| options.codexRoot
|
|
293
|
+
|| options.piRoot
|
|
294
|
+
|| options.codewhaleRoot
|
|
295
|
+
|| options.reasonixRoot);
|
|
296
|
+
const claudeConfigDir = process.env.CLAUDE_CONFIG_DIR
|
|
297
|
+
? path.resolve(process.env.CLAUDE_CONFIG_DIR)
|
|
298
|
+
: path.join(homeDir, '.claude');
|
|
299
|
+
const codexHome = process.env.CODEX_HOME
|
|
300
|
+
? path.resolve(process.env.CODEX_HOME)
|
|
301
|
+
: path.join(homeDir, '.codex');
|
|
302
|
+
const piSessions = process.env.PI_CODING_AGENT_SESSION_DIR
|
|
303
|
+
? path.resolve(process.env.PI_CODING_AGENT_SESSION_DIR)
|
|
304
|
+
: process.env.PI_CODING_AGENT_DIR
|
|
305
|
+
? path.join(path.resolve(process.env.PI_CODING_AGENT_DIR), 'sessions')
|
|
306
|
+
: path.join(homeDir, '.pi', 'agent', 'sessions');
|
|
307
|
+
const codewhaleRoots = options.codewhaleRoot
|
|
308
|
+
? [path.resolve(options.codewhaleRoot)]
|
|
309
|
+
: process.env.CODEWHALE_HOME
|
|
310
|
+
? [path.join(path.resolve(process.env.CODEWHALE_HOME), 'sessions')]
|
|
311
|
+
: [
|
|
312
|
+
path.join(homeDir, '.codewhale', 'sessions'),
|
|
313
|
+
path.join(homeDir, '.deepseek', 'sessions'),
|
|
314
|
+
];
|
|
315
|
+
const reasonixRoots = options.reasonixRoot
|
|
316
|
+
? [path.resolve(options.reasonixRoot)]
|
|
317
|
+
: resolveReasonixSessionRoots(homeDir, options.homeDir && !sameResolvedPath(homeDir, os.homedir())
|
|
318
|
+
? { ...process.env, APPDATA: undefined }
|
|
319
|
+
: process.env);
|
|
320
|
+
const roots = [
|
|
321
|
+
...(!explicitRootMode || options.claudeRoot ? [{
|
|
322
|
+
runtime: 'claude',
|
|
323
|
+
root: path.resolve(options.claudeRoot ?? path.join(claudeConfigDir, 'projects')),
|
|
324
|
+
}] : []),
|
|
325
|
+
...(!explicitRootMode || options.codexRoot ? [{
|
|
326
|
+
runtime: 'codex',
|
|
327
|
+
root: path.resolve(options.codexRoot ?? path.join(codexHome, 'sessions')),
|
|
328
|
+
}] : []),
|
|
329
|
+
...(!explicitRootMode || options.piRoot ? [{
|
|
330
|
+
runtime: 'pi',
|
|
331
|
+
root: path.resolve(options.piRoot ?? piSessions),
|
|
332
|
+
}] : []),
|
|
333
|
+
...(!explicitRootMode || options.codewhaleRoot ? codewhaleRoots.map(root => ({
|
|
334
|
+
runtime: 'codewhale',
|
|
335
|
+
root,
|
|
336
|
+
})) : []),
|
|
337
|
+
...(!explicitRootMode || options.reasonixRoot ? reasonixRoots.map(root => ({
|
|
338
|
+
runtime: 'reasonix',
|
|
339
|
+
root,
|
|
340
|
+
})) : []),
|
|
341
|
+
];
|
|
342
|
+
if (!explicitRootMode) {
|
|
343
|
+
roots.push(...await managedExternalCliProfileRoots(options));
|
|
344
|
+
}
|
|
345
|
+
const seen = new Set();
|
|
346
|
+
return roots.filter(item => {
|
|
347
|
+
const normalized = path.resolve(item.root);
|
|
348
|
+
const key = `${item.runtime}\0${path.sep === '\\' ? normalized.toLowerCase() : normalized}`;
|
|
349
|
+
if (seen.has(key))
|
|
350
|
+
return false;
|
|
351
|
+
seen.add(key);
|
|
352
|
+
return true;
|
|
353
|
+
});
|
|
354
|
+
}
|
|
355
|
+
async function managedExternalCliProfileRoots(options) {
|
|
356
|
+
const profilesRoot = path.join(resolveManagedActoviqHome(options), 'external-cli-profiles');
|
|
357
|
+
const roots = [];
|
|
358
|
+
for (const runtime of ['pi', 'codewhale', 'reasonix']) {
|
|
359
|
+
const runtimeRoot = path.join(profilesRoot, runtime);
|
|
360
|
+
let entries;
|
|
361
|
+
try {
|
|
362
|
+
entries = await readdir(runtimeRoot, { withFileTypes: true });
|
|
363
|
+
}
|
|
364
|
+
catch {
|
|
365
|
+
continue;
|
|
366
|
+
}
|
|
367
|
+
for (const entry of entries
|
|
368
|
+
.filter(candidate => candidate.isDirectory() && MANAGED_PROFILE_ID_PATTERN.test(candidate.name))
|
|
369
|
+
.sort((left, right) => left.name.localeCompare(right.name))
|
|
370
|
+
.slice(0, MAX_MANAGED_PROFILES_PER_RUNTIME)) {
|
|
371
|
+
roots.push({
|
|
372
|
+
runtime,
|
|
373
|
+
root: runtime === 'reasonix'
|
|
374
|
+
? path.join(runtimeRoot, entry.name, '.reasonix', 'sessions')
|
|
375
|
+
: path.join(runtimeRoot, entry.name, 'sessions'),
|
|
376
|
+
});
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
return roots;
|
|
380
|
+
}
|
|
381
|
+
async function managedCrushHistoryProfiles(options) {
|
|
382
|
+
const requestedRuntimeRoot = path.join(resolveManagedActoviqHome(options), 'external-cli-profiles', 'crush');
|
|
383
|
+
// resolveDirectory already rejects symlinks via lstat. Do not compare the
|
|
384
|
+
// realpathed result against the lexical request path: on Windows, native
|
|
385
|
+
// realpath expands 8.3 short names (RUNNER~1 → runneradmin) and that must
|
|
386
|
+
// not look like a redirected/symlinked profile root.
|
|
387
|
+
const runtimeRoot = await resolveDirectory(requestedRuntimeRoot);
|
|
388
|
+
if (!runtimeRoot)
|
|
389
|
+
return [];
|
|
390
|
+
let entries;
|
|
391
|
+
try {
|
|
392
|
+
entries = await readdir(runtimeRoot, { withFileTypes: true });
|
|
393
|
+
}
|
|
394
|
+
catch {
|
|
395
|
+
return [];
|
|
396
|
+
}
|
|
397
|
+
const profiles = [];
|
|
398
|
+
for (const entry of entries
|
|
399
|
+
.filter(candidate => candidate.isDirectory() && MANAGED_PROFILE_ID_PATTERN.test(candidate.name))
|
|
400
|
+
.sort((left, right) => left.name.localeCompare(right.name))) {
|
|
401
|
+
if (profiles.length >= MAX_MANAGED_PROFILES_PER_RUNTIME)
|
|
402
|
+
break;
|
|
403
|
+
const requestedProfileRoot = path.join(runtimeRoot, entry.name);
|
|
404
|
+
const profileRoot = await resolveDirectory(requestedProfileRoot);
|
|
405
|
+
if (!profileRoot)
|
|
406
|
+
continue;
|
|
407
|
+
const requestedDataDir = path.join(profileRoot, 'data');
|
|
408
|
+
const dataDir = await resolveDirectory(requestedDataDir);
|
|
409
|
+
if (!dataDir)
|
|
410
|
+
continue;
|
|
411
|
+
profiles.push({ id: entry.name, dataDir });
|
|
412
|
+
}
|
|
413
|
+
return profiles;
|
|
414
|
+
}
|
|
415
|
+
function resolveManagedActoviqHome(options) {
|
|
416
|
+
return options.actoviqHomeDir?.trim()
|
|
417
|
+
? resolveActoviqHome(options.actoviqHomeDir, { inputKind: 'dataRoot' })
|
|
418
|
+
: resolveActoviqHome(options.homeDir);
|
|
419
|
+
}
|
|
420
|
+
async function resolveDirectory(directory) {
|
|
421
|
+
try {
|
|
422
|
+
const requestedInfo = await lstat(directory);
|
|
423
|
+
if (requestedInfo.isSymbolicLink() || !requestedInfo.isDirectory()) {
|
|
424
|
+
return undefined;
|
|
425
|
+
}
|
|
426
|
+
const canonicalPath = await realpathNative(directory);
|
|
427
|
+
return (await stat(canonicalPath)).isDirectory() ? canonicalPath : undefined;
|
|
428
|
+
}
|
|
429
|
+
catch {
|
|
430
|
+
return undefined;
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
async function resolveFile(filePath) {
|
|
434
|
+
try {
|
|
435
|
+
const requestedInfo = await lstat(filePath);
|
|
436
|
+
if (requestedInfo.isSymbolicLink() || !requestedInfo.isFile()) {
|
|
437
|
+
return undefined;
|
|
438
|
+
}
|
|
439
|
+
const canonicalPath = await realpathNative(filePath);
|
|
440
|
+
const canonicalInfo = await lstat(canonicalPath);
|
|
441
|
+
return !canonicalInfo.isSymbolicLink() && canonicalInfo.isFile() ? canonicalPath : undefined;
|
|
442
|
+
}
|
|
443
|
+
catch {
|
|
444
|
+
return undefined;
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
async function inspectSessionFile(runtime, root, filePath) {
|
|
448
|
+
try {
|
|
449
|
+
const resolvedPath = path.resolve(filePath);
|
|
450
|
+
if (!isPathInside(root, resolvedPath)) {
|
|
451
|
+
return undefined;
|
|
452
|
+
}
|
|
453
|
+
const fileInfo = await lstat(resolvedPath);
|
|
454
|
+
if (fileInfo.isSymbolicLink() || !fileInfo.isFile()) {
|
|
455
|
+
return undefined;
|
|
456
|
+
}
|
|
457
|
+
return {
|
|
458
|
+
runtime,
|
|
459
|
+
path: resolvedPath,
|
|
460
|
+
stats: fileInfo,
|
|
461
|
+
};
|
|
462
|
+
}
|
|
463
|
+
catch {
|
|
464
|
+
return undefined;
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
async function collectJsonlFiles(directory) {
|
|
468
|
+
let entries;
|
|
469
|
+
try {
|
|
470
|
+
entries = await readdir(directory, { withFileTypes: true });
|
|
471
|
+
}
|
|
472
|
+
catch {
|
|
473
|
+
return [];
|
|
474
|
+
}
|
|
475
|
+
const files = [];
|
|
476
|
+
for (const entry of entries) {
|
|
477
|
+
if (entry.isSymbolicLink()) {
|
|
478
|
+
continue;
|
|
479
|
+
}
|
|
480
|
+
const entryPath = path.join(directory, entry.name);
|
|
481
|
+
if (entry.isDirectory()) {
|
|
482
|
+
for (const nestedFile of await collectJsonlFiles(entryPath)) {
|
|
483
|
+
files.push(nestedFile);
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
else if (entry.isFile() && entry.name.toLowerCase().endsWith('.jsonl')) {
|
|
487
|
+
files.push(entryPath);
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
return files;
|
|
491
|
+
}
|
|
492
|
+
async function collectCodewhaleSessionFiles(directory) {
|
|
493
|
+
let entries;
|
|
494
|
+
try {
|
|
495
|
+
entries = await readdir(directory, { withFileTypes: true });
|
|
496
|
+
}
|
|
497
|
+
catch {
|
|
498
|
+
return [];
|
|
499
|
+
}
|
|
500
|
+
return entries
|
|
501
|
+
.filter(entry => entry.isFile() && isCodewhaleSessionFileName(entry.name))
|
|
502
|
+
.map(entry => path.join(directory, entry.name));
|
|
503
|
+
}
|
|
504
|
+
async function collectReasonixSessionFiles(directory) {
|
|
505
|
+
let entries;
|
|
506
|
+
try {
|
|
507
|
+
entries = await readdir(directory, { withFileTypes: true });
|
|
508
|
+
}
|
|
509
|
+
catch {
|
|
510
|
+
return [];
|
|
511
|
+
}
|
|
512
|
+
return entries
|
|
513
|
+
.filter(entry => entry.isFile() && isReasonixSessionFileName(entry.name))
|
|
514
|
+
.map(entry => path.join(directory, entry.name));
|
|
515
|
+
}
|
|
516
|
+
function isSessionFileForRuntime(root, filePath) {
|
|
517
|
+
if (root.runtime === 'codewhale') {
|
|
518
|
+
return path.relative(root.root, path.dirname(filePath)) === '' &&
|
|
519
|
+
isCodewhaleSessionFileName(path.basename(filePath));
|
|
520
|
+
}
|
|
521
|
+
if (root.runtime === 'reasonix') {
|
|
522
|
+
return path.relative(root.root, path.dirname(filePath)) === '' &&
|
|
523
|
+
isReasonixSessionFileName(path.basename(filePath));
|
|
524
|
+
}
|
|
525
|
+
return path.extname(filePath).toLowerCase() === '.jsonl';
|
|
526
|
+
}
|
|
527
|
+
function isCodewhaleSessionFileName(fileName) {
|
|
528
|
+
return /^[A-Za-z0-9_-]+\.json$/u.test(fileName);
|
|
529
|
+
}
|
|
530
|
+
function isReasonixSessionFileName(fileName) {
|
|
531
|
+
return /^[^\\/\u0000-\u001f\u007f]+\.jsonl$/iu.test(fileName) &&
|
|
532
|
+
!/(?:^|\.)(?:events|guardian)\.jsonl$/iu.test(fileName);
|
|
533
|
+
}
|
|
534
|
+
function sameResolvedPath(left, right) {
|
|
535
|
+
const resolvedLeft = path.resolve(left);
|
|
536
|
+
const resolvedRight = path.resolve(right);
|
|
537
|
+
return process.platform === 'win32'
|
|
538
|
+
? resolvedLeft.toLowerCase() === resolvedRight.toLowerCase()
|
|
539
|
+
: resolvedLeft === resolvedRight;
|
|
540
|
+
}
|
|
541
|
+
function isPathInside(root, candidate) {
|
|
542
|
+
const relative = path.relative(path.resolve(root), path.resolve(candidate));
|
|
543
|
+
return relative !== '' &&
|
|
544
|
+
relative !== '..' &&
|
|
545
|
+
!relative.startsWith(`..${path.sep}`) &&
|
|
546
|
+
!path.isAbsolute(relative);
|
|
547
|
+
}
|
|
548
|
+
function unsafeSessionPath(filePath) {
|
|
549
|
+
return new ActoviqSdkError(`External CLI session path is outside the allowed roots: ${filePath}`, 'EXTERNAL_CLI_SESSION_PATH_UNSAFE');
|
|
550
|
+
}
|
|
551
|
+
async function parseSessionFile(runtime, filePath, bounds, knownFileInfo) {
|
|
552
|
+
let fileInfo;
|
|
553
|
+
try {
|
|
554
|
+
fileInfo = knownFileInfo ?? await stat(filePath);
|
|
555
|
+
}
|
|
556
|
+
catch {
|
|
557
|
+
return undefined;
|
|
558
|
+
}
|
|
559
|
+
if (runtime === 'codewhale') {
|
|
560
|
+
return parseCodewhaleSessionFile(filePath, bounds, fileInfo);
|
|
561
|
+
}
|
|
562
|
+
if (runtime === 'reasonix') {
|
|
563
|
+
return parseReasonixSessionFile(filePath, bounds, fileInfo);
|
|
564
|
+
}
|
|
565
|
+
const state = {
|
|
566
|
+
messages: [],
|
|
567
|
+
fallbackMessages: [],
|
|
568
|
+
piEntries: [],
|
|
569
|
+
piMessageCount: 0,
|
|
570
|
+
};
|
|
571
|
+
let truncated;
|
|
572
|
+
try {
|
|
573
|
+
truncated = await scanSessionFile(runtime, filePath, fileInfo, state, bounds);
|
|
574
|
+
}
|
|
575
|
+
catch {
|
|
576
|
+
return undefined;
|
|
577
|
+
}
|
|
578
|
+
if (runtime === 'pi') {
|
|
579
|
+
finalizePiState(state);
|
|
580
|
+
}
|
|
581
|
+
const messages = runtime === 'codex' && !hasConversationMessages(state.messages)
|
|
582
|
+
? state.fallbackMessages
|
|
583
|
+
: state.messages;
|
|
584
|
+
const nativeSessionId = state.nativeSessionId ?? sessionIdFromFileName(filePath);
|
|
585
|
+
const firstUserText = messages.find(message => message.role === 'user' && message.text)?.text;
|
|
586
|
+
const firstAssistantText = messages.find(message => message.role === 'assistant' && message.text)?.text;
|
|
587
|
+
const fallbackCreated = fileInfo.birthtimeMs > 0 ? fileInfo.birthtimeMs : fileInfo.mtimeMs;
|
|
588
|
+
const created = state.earliestTimestamp ?? fallbackCreated;
|
|
589
|
+
const updated = truncated
|
|
590
|
+
? Math.max(state.latestTimestamp ?? 0, fileInfo.mtimeMs)
|
|
591
|
+
: state.latestTimestamp ?? fileInfo.mtimeMs;
|
|
592
|
+
const summary = {
|
|
593
|
+
runtime,
|
|
594
|
+
nativeSessionId,
|
|
595
|
+
title: normalizeTitle(state.nativeTitle ?? firstUserText ?? firstAssistantText ?? nativeSessionId),
|
|
596
|
+
cwd: state.cwd,
|
|
597
|
+
createdAt: new Date(created).toISOString(),
|
|
598
|
+
updatedAt: new Date(updated).toISOString(),
|
|
599
|
+
messageCount: messages.length,
|
|
600
|
+
path: filePath,
|
|
601
|
+
...(truncated ? { truncated: true } : {}),
|
|
602
|
+
};
|
|
603
|
+
return { summary, messages, ...(truncated ? { truncated: true } : {}) };
|
|
604
|
+
}
|
|
605
|
+
async function parseReasonixSessionFile(filePath, bounds, fileInfo) {
|
|
606
|
+
const metadata = await readReasonixMetadataSidecar(filePath);
|
|
607
|
+
if (fileInfo.size === 0 && !metadata) {
|
|
608
|
+
return undefined;
|
|
609
|
+
}
|
|
610
|
+
const bytesToRead = Math.min(fileInfo.size, bounds.maxBytes);
|
|
611
|
+
let source = '';
|
|
612
|
+
if (bytesToRead > 0) {
|
|
613
|
+
try {
|
|
614
|
+
source = await readBoundedUtf8File(filePath, bytesToRead);
|
|
615
|
+
}
|
|
616
|
+
catch {
|
|
617
|
+
return undefined;
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
const parsed = parseReasonixSessionJsonl(source, {
|
|
621
|
+
filePath,
|
|
622
|
+
metadata,
|
|
623
|
+
fileCreatedAt: fileInfo.birthtimeMs > 0 ? fileInfo.birthtimeMs : fileInfo.mtimeMs,
|
|
624
|
+
fileUpdatedAt: fileInfo.mtimeMs,
|
|
625
|
+
maxRecords: bounds.maxMessages * 2,
|
|
626
|
+
maxMessages: bounds.maxMessages,
|
|
627
|
+
maxRecordChars: bounds.maxBytes,
|
|
628
|
+
maxTextChars: bounds.maxBytes,
|
|
629
|
+
maxToolPayloadChars: Math.min(bounds.maxBytes, 64 * 1024),
|
|
630
|
+
});
|
|
631
|
+
if (parsed.messageCount === 0 && !metadata) {
|
|
632
|
+
return undefined;
|
|
633
|
+
}
|
|
634
|
+
const messages = parsed.messages.map(normalizeReasonixMessage);
|
|
635
|
+
const nativeSessionId = parsed.nativeSessionId ?? sessionIdFromFileName(filePath);
|
|
636
|
+
const fallbackCreated = fileInfo.birthtimeMs > 0 ? fileInfo.birthtimeMs : fileInfo.mtimeMs;
|
|
637
|
+
const truncated = fileInfo.size > bytesToRead || parsed.truncated;
|
|
638
|
+
const parsedUpdatedAt = parsed.updatedAt ? Date.parse(parsed.updatedAt) : Number.NaN;
|
|
639
|
+
const updatedAt = truncated
|
|
640
|
+
? new Date(Math.max(Number.isFinite(parsedUpdatedAt) ? parsedUpdatedAt : 0, fileInfo.mtimeMs)).toISOString()
|
|
641
|
+
: parsed.updatedAt ?? new Date(fileInfo.mtimeMs).toISOString();
|
|
642
|
+
const summary = {
|
|
643
|
+
runtime: 'reasonix',
|
|
644
|
+
nativeSessionId,
|
|
645
|
+
title: normalizeTitle(parsed.title ?? nativeSessionId),
|
|
646
|
+
cwd: parsed.cwd,
|
|
647
|
+
createdAt: parsed.createdAt ?? new Date(fallbackCreated).toISOString(),
|
|
648
|
+
updatedAt,
|
|
649
|
+
messageCount: parsed.messageCount,
|
|
650
|
+
path: filePath,
|
|
651
|
+
...(truncated ? { truncated: true } : {}),
|
|
652
|
+
};
|
|
653
|
+
return { summary, messages, ...(truncated ? { truncated: true } : {}) };
|
|
654
|
+
}
|
|
655
|
+
async function readReasonixMetadataSidecar(filePath) {
|
|
656
|
+
const extension = path.extname(filePath);
|
|
657
|
+
const stem = extension ? filePath.slice(0, -extension.length) : filePath;
|
|
658
|
+
const parent = path.dirname(filePath);
|
|
659
|
+
for (const sidecarPath of [`${stem}.acp.json`, `${stem}.meta.json`]) {
|
|
660
|
+
const canonicalPath = await resolveFile(sidecarPath);
|
|
661
|
+
if (!canonicalPath) {
|
|
662
|
+
continue;
|
|
663
|
+
}
|
|
664
|
+
const relative = path.relative(parent, canonicalPath);
|
|
665
|
+
if (!relative || path.dirname(relative) !== '.' || path.isAbsolute(relative)) {
|
|
666
|
+
continue;
|
|
667
|
+
}
|
|
668
|
+
let sidecarInfo;
|
|
669
|
+
try {
|
|
670
|
+
sidecarInfo = await stat(canonicalPath);
|
|
671
|
+
}
|
|
672
|
+
catch {
|
|
673
|
+
continue;
|
|
674
|
+
}
|
|
675
|
+
if (sidecarInfo.size === 0 || sidecarInfo.size > MAX_REASONIX_METADATA_BYTES) {
|
|
676
|
+
continue;
|
|
677
|
+
}
|
|
678
|
+
try {
|
|
679
|
+
const source = await readBoundedUtf8File(canonicalPath, sidecarInfo.size);
|
|
680
|
+
const parsed = JSON.parse(source);
|
|
681
|
+
if (isRecord(parsed)) {
|
|
682
|
+
return parsed;
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
catch {
|
|
686
|
+
// A corrupt current sidecar may still have a usable legacy fallback.
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
return undefined;
|
|
690
|
+
}
|
|
691
|
+
function normalizeReasonixMessage(message) {
|
|
692
|
+
const role = message.role === 'think'
|
|
693
|
+
? 'assistant'
|
|
694
|
+
: message.role;
|
|
695
|
+
return {
|
|
696
|
+
role,
|
|
697
|
+
text: message.text,
|
|
698
|
+
...(message.timestamp ? { timestamp: message.timestamp } : {}),
|
|
699
|
+
...(message.model ? { model: message.model } : {}),
|
|
700
|
+
...(message.tools?.length
|
|
701
|
+
? { tools: message.tools.map(tool => ({ ...tool })) }
|
|
702
|
+
: {}),
|
|
703
|
+
};
|
|
704
|
+
}
|
|
705
|
+
async function parseCodewhaleSessionFile(filePath, bounds, fileInfo) {
|
|
706
|
+
const savedSessionPrefix = await readCodewhaleSavedSessionPrefix(filePath, fileInfo, bounds.maxBytes);
|
|
707
|
+
if (!savedSessionPrefix) {
|
|
708
|
+
return undefined;
|
|
709
|
+
}
|
|
710
|
+
const { bytesToRead, metadata, savedSession, source } = savedSessionPrefix;
|
|
711
|
+
const rawMessages = savedSession && Array.isArray(savedSession.messages)
|
|
712
|
+
? savedSession.messages.slice(0, bounds.maxMessages + 1)
|
|
713
|
+
: extractCodewhaleMessages(source, bounds.maxMessages + 1);
|
|
714
|
+
const stoppedForMessageLimit = rawMessages.length > bounds.maxMessages;
|
|
715
|
+
const messages = [];
|
|
716
|
+
const model = stringValue(metadata.model);
|
|
717
|
+
for (const rawMessage of rawMessages.slice(0, bounds.maxMessages)) {
|
|
718
|
+
if (isRecord(rawMessage)) {
|
|
719
|
+
consumeCodewhaleMessage(rawMessage, model, messages);
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
const nativeSessionId = stringValue(metadata.id) ?? sessionIdFromFileName(filePath);
|
|
723
|
+
const firstUserText = messages.find(message => message.role === 'user' && message.text)?.text;
|
|
724
|
+
const firstAssistantText = messages.find(message => message.role === 'assistant' && message.text)?.text;
|
|
725
|
+
const fallbackCreated = fileInfo.birthtimeMs > 0 ? fileInfo.birthtimeMs : fileInfo.mtimeMs;
|
|
726
|
+
const createdAt = normalizeTimestamp(metadata.created_at)
|
|
727
|
+
?? new Date(fallbackCreated).toISOString();
|
|
728
|
+
const updatedAt = normalizeTimestamp(metadata.updated_at)
|
|
729
|
+
?? new Date(fileInfo.mtimeMs).toISOString();
|
|
730
|
+
const truncated = fileInfo.size > bytesToRead || stoppedForMessageLimit;
|
|
731
|
+
const summary = {
|
|
732
|
+
runtime: 'codewhale',
|
|
733
|
+
nativeSessionId,
|
|
734
|
+
title: normalizeTitle(stringValue(metadata.title) ?? firstUserText ?? firstAssistantText ?? nativeSessionId),
|
|
735
|
+
cwd: stringValue(metadata.workspace),
|
|
736
|
+
createdAt,
|
|
737
|
+
updatedAt,
|
|
738
|
+
messageCount: nonNegativeIntegerValue(metadata.message_count) ?? messages.length,
|
|
739
|
+
path: filePath,
|
|
740
|
+
...(truncated ? { truncated: true } : {}),
|
|
741
|
+
};
|
|
742
|
+
return { summary, messages, ...(truncated ? { truncated: true } : {}) };
|
|
743
|
+
}
|
|
744
|
+
async function readCodewhaleSavedSessionPrefix(filePath, fileInfo, maxBytes) {
|
|
745
|
+
if (fileInfo.size === 0) {
|
|
746
|
+
return undefined;
|
|
747
|
+
}
|
|
748
|
+
const bytesToRead = Math.min(fileInfo.size, maxBytes);
|
|
749
|
+
let source;
|
|
750
|
+
try {
|
|
751
|
+
source = await readBoundedUtf8File(filePath, bytesToRead);
|
|
752
|
+
}
|
|
753
|
+
catch {
|
|
754
|
+
return undefined;
|
|
755
|
+
}
|
|
756
|
+
let savedSession;
|
|
757
|
+
if (fileInfo.size <= bytesToRead) {
|
|
758
|
+
try {
|
|
759
|
+
const parsed = JSON.parse(source);
|
|
760
|
+
if (!isRecord(parsed)) {
|
|
761
|
+
return undefined;
|
|
762
|
+
}
|
|
763
|
+
savedSession = parsed;
|
|
764
|
+
}
|
|
765
|
+
catch {
|
|
766
|
+
return undefined;
|
|
767
|
+
}
|
|
768
|
+
}
|
|
769
|
+
const metadata = savedSession && isRecord(savedSession.metadata)
|
|
770
|
+
? savedSession.metadata
|
|
771
|
+
: extractCodewhaleMetadata(source);
|
|
772
|
+
return metadata ? { source, savedSession, metadata, bytesToRead } : undefined;
|
|
773
|
+
}
|
|
774
|
+
async function readBoundedUtf8File(filePath, maxBytes) {
|
|
775
|
+
const stream = createReadStream(filePath, {
|
|
776
|
+
encoding: 'utf8',
|
|
777
|
+
start: 0,
|
|
778
|
+
end: maxBytes - 1,
|
|
779
|
+
highWaterMark: 64 * 1024,
|
|
780
|
+
});
|
|
781
|
+
let source = '';
|
|
782
|
+
try {
|
|
783
|
+
for await (const chunk of stream) {
|
|
784
|
+
source += chunk;
|
|
785
|
+
}
|
|
786
|
+
return source;
|
|
787
|
+
}
|
|
788
|
+
finally {
|
|
789
|
+
stream.destroy();
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
function extractCodewhaleMetadata(source) {
|
|
793
|
+
const valueStart = findTopLevelJsonPropertyValueStart(source, 'metadata');
|
|
794
|
+
if (valueStart == null || source[valueStart] !== '{') {
|
|
795
|
+
return undefined;
|
|
796
|
+
}
|
|
797
|
+
const valueEnd = findJsonCompositeEnd(source, valueStart);
|
|
798
|
+
if (valueEnd == null) {
|
|
799
|
+
return undefined;
|
|
800
|
+
}
|
|
801
|
+
try {
|
|
802
|
+
const parsed = JSON.parse(source.slice(valueStart, valueEnd));
|
|
803
|
+
return isRecord(parsed) ? parsed : undefined;
|
|
804
|
+
}
|
|
805
|
+
catch {
|
|
806
|
+
return undefined;
|
|
807
|
+
}
|
|
808
|
+
}
|
|
809
|
+
function extractCodewhaleMessages(source, limit) {
|
|
810
|
+
const arrayStart = findTopLevelJsonPropertyValueStart(source, 'messages');
|
|
811
|
+
if (arrayStart == null || source[arrayStart] !== '[') {
|
|
812
|
+
return [];
|
|
813
|
+
}
|
|
814
|
+
const messages = [];
|
|
815
|
+
let cursor = arrayStart + 1;
|
|
816
|
+
while (messages.length < limit) {
|
|
817
|
+
while (cursor < source.length && /[\s,]/u.test(source[cursor])) {
|
|
818
|
+
cursor += 1;
|
|
819
|
+
}
|
|
820
|
+
if (source[cursor] === ']' || source[cursor] !== '{') {
|
|
821
|
+
break;
|
|
822
|
+
}
|
|
823
|
+
const valueEnd = findJsonCompositeEnd(source, cursor);
|
|
824
|
+
if (valueEnd == null) {
|
|
825
|
+
break;
|
|
826
|
+
}
|
|
827
|
+
try {
|
|
828
|
+
messages.push(JSON.parse(source.slice(cursor, valueEnd)));
|
|
829
|
+
}
|
|
830
|
+
catch {
|
|
831
|
+
break;
|
|
832
|
+
}
|
|
833
|
+
cursor = valueEnd;
|
|
834
|
+
}
|
|
835
|
+
return messages;
|
|
836
|
+
}
|
|
837
|
+
function findTopLevelJsonPropertyValueStart(source, propertyName) {
|
|
838
|
+
let depth = 0;
|
|
839
|
+
let cursor = 0;
|
|
840
|
+
while (cursor < source.length) {
|
|
841
|
+
const character = source[cursor];
|
|
842
|
+
if (character === '"') {
|
|
843
|
+
const stringEnd = findJsonStringEnd(source, cursor);
|
|
844
|
+
if (stringEnd == null) {
|
|
845
|
+
return undefined;
|
|
846
|
+
}
|
|
847
|
+
if (depth === 1) {
|
|
848
|
+
let separator = stringEnd + 1;
|
|
849
|
+
while (separator < source.length && /\s/u.test(source[separator])) {
|
|
850
|
+
separator += 1;
|
|
851
|
+
}
|
|
852
|
+
if (source[separator] === ':') {
|
|
853
|
+
try {
|
|
854
|
+
const key = JSON.parse(source.slice(cursor, stringEnd + 1));
|
|
855
|
+
if (key === propertyName) {
|
|
856
|
+
separator += 1;
|
|
857
|
+
while (separator < source.length && /\s/u.test(source[separator])) {
|
|
858
|
+
separator += 1;
|
|
859
|
+
}
|
|
860
|
+
return separator;
|
|
861
|
+
}
|
|
862
|
+
}
|
|
863
|
+
catch {
|
|
864
|
+
return undefined;
|
|
865
|
+
}
|
|
866
|
+
}
|
|
867
|
+
}
|
|
868
|
+
cursor = stringEnd + 1;
|
|
869
|
+
continue;
|
|
870
|
+
}
|
|
871
|
+
if (character === '{' || character === '[') {
|
|
872
|
+
depth += 1;
|
|
873
|
+
}
|
|
874
|
+
else if (character === '}' || character === ']') {
|
|
875
|
+
depth -= 1;
|
|
876
|
+
}
|
|
877
|
+
cursor += 1;
|
|
878
|
+
}
|
|
879
|
+
return undefined;
|
|
880
|
+
}
|
|
881
|
+
function findJsonCompositeEnd(source, start) {
|
|
882
|
+
const opening = source[start];
|
|
883
|
+
if (opening !== '{' && opening !== '[') {
|
|
884
|
+
return undefined;
|
|
885
|
+
}
|
|
886
|
+
const stack = [opening];
|
|
887
|
+
let cursor = start + 1;
|
|
888
|
+
while (cursor < source.length) {
|
|
889
|
+
const character = source[cursor];
|
|
890
|
+
if (character === '"') {
|
|
891
|
+
const stringEnd = findJsonStringEnd(source, cursor);
|
|
892
|
+
if (stringEnd == null) {
|
|
893
|
+
return undefined;
|
|
894
|
+
}
|
|
895
|
+
cursor = stringEnd + 1;
|
|
896
|
+
continue;
|
|
897
|
+
}
|
|
898
|
+
if (character === '{' || character === '[') {
|
|
899
|
+
stack.push(character);
|
|
900
|
+
}
|
|
901
|
+
else if (character === '}' || character === ']') {
|
|
902
|
+
const expectedOpening = character === '}' ? '{' : '[';
|
|
903
|
+
if (stack.pop() !== expectedOpening) {
|
|
904
|
+
return undefined;
|
|
905
|
+
}
|
|
906
|
+
if (stack.length === 0) {
|
|
907
|
+
return cursor + 1;
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
cursor += 1;
|
|
911
|
+
}
|
|
912
|
+
return undefined;
|
|
913
|
+
}
|
|
914
|
+
function findJsonStringEnd(source, start) {
|
|
915
|
+
let cursor = start + 1;
|
|
916
|
+
while (cursor < source.length) {
|
|
917
|
+
if (source[cursor] === '\\') {
|
|
918
|
+
cursor += 2;
|
|
919
|
+
continue;
|
|
920
|
+
}
|
|
921
|
+
if (source[cursor] === '"') {
|
|
922
|
+
return cursor;
|
|
923
|
+
}
|
|
924
|
+
cursor += 1;
|
|
925
|
+
}
|
|
926
|
+
return undefined;
|
|
927
|
+
}
|
|
928
|
+
function consumeCodewhaleMessage(message, model, messages) {
|
|
929
|
+
const role = normalizeRole(message.role);
|
|
930
|
+
if (!role) {
|
|
931
|
+
return;
|
|
932
|
+
}
|
|
933
|
+
const content = extractCodewhaleContent(message.content);
|
|
934
|
+
pushMessage(messages, {
|
|
935
|
+
role: content.toolResultOnly ? 'tool' : role,
|
|
936
|
+
text: content.text,
|
|
937
|
+
model,
|
|
938
|
+
tools: content.tools,
|
|
939
|
+
});
|
|
940
|
+
}
|
|
941
|
+
function extractCodewhaleContent(content) {
|
|
942
|
+
if (typeof content === 'string') {
|
|
943
|
+
return { text: content.trim(), tools: [], toolResultOnly: false };
|
|
944
|
+
}
|
|
945
|
+
if (!Array.isArray(content)) {
|
|
946
|
+
return { text: '', tools: [], toolResultOnly: false };
|
|
947
|
+
}
|
|
948
|
+
const textParts = [];
|
|
949
|
+
const tools = [];
|
|
950
|
+
let hasPlainText = false;
|
|
951
|
+
for (const block of content) {
|
|
952
|
+
if (!isRecord(block)) {
|
|
953
|
+
continue;
|
|
954
|
+
}
|
|
955
|
+
const type = stringValue(block.type);
|
|
956
|
+
if (type === 'text' || type === 'thinking') {
|
|
957
|
+
const text = stringValue(type === 'thinking' ? block.thinking : block.text);
|
|
958
|
+
if (text) {
|
|
959
|
+
textParts.push(text);
|
|
960
|
+
hasPlainText = true;
|
|
961
|
+
}
|
|
962
|
+
continue;
|
|
963
|
+
}
|
|
964
|
+
if (type === 'tool_use' || type === 'server_tool_use') {
|
|
965
|
+
tools.push({
|
|
966
|
+
kind: 'call',
|
|
967
|
+
id: stringValue(block.id),
|
|
968
|
+
name: stringValue(block.name),
|
|
969
|
+
input: block.input,
|
|
970
|
+
});
|
|
971
|
+
continue;
|
|
972
|
+
}
|
|
973
|
+
if (type === 'tool_result') {
|
|
974
|
+
const output = visibleText(block.content) || visibleText(block.content_blocks);
|
|
975
|
+
tools.push({
|
|
976
|
+
kind: 'result',
|
|
977
|
+
id: stringValue(block.tool_use_id),
|
|
978
|
+
output,
|
|
979
|
+
isError: booleanValue(block.is_error),
|
|
980
|
+
});
|
|
981
|
+
if (output) {
|
|
982
|
+
textParts.push(output);
|
|
983
|
+
}
|
|
984
|
+
}
|
|
985
|
+
}
|
|
986
|
+
return {
|
|
987
|
+
text: textParts.join('\n').trim(),
|
|
988
|
+
tools,
|
|
989
|
+
toolResultOnly: tools.some(tool => tool.kind === 'result') && !hasPlainText,
|
|
990
|
+
};
|
|
991
|
+
}
|
|
992
|
+
async function scanSessionFile(runtime, filePath, fileInfo, state, bounds) {
|
|
993
|
+
if (fileInfo.size === 0) {
|
|
994
|
+
return false;
|
|
995
|
+
}
|
|
996
|
+
const bytesToRead = Math.min(fileInfo.size, bounds.maxBytes);
|
|
997
|
+
const stream = createReadStream(filePath, {
|
|
998
|
+
encoding: 'utf8',
|
|
999
|
+
start: 0,
|
|
1000
|
+
end: bytesToRead - 1,
|
|
1001
|
+
highWaterMark: 64 * 1024,
|
|
1002
|
+
});
|
|
1003
|
+
let pending = '';
|
|
1004
|
+
let stoppedForMessageLimit = false;
|
|
1005
|
+
try {
|
|
1006
|
+
scan: for await (const chunk of stream) {
|
|
1007
|
+
pending += chunk;
|
|
1008
|
+
let newlineIndex = pending.indexOf('\n');
|
|
1009
|
+
while (newlineIndex >= 0) {
|
|
1010
|
+
const line = pending.slice(0, newlineIndex).replace(/\r$/u, '');
|
|
1011
|
+
pending = pending.slice(newlineIndex + 1);
|
|
1012
|
+
consumeSessionLine(runtime, line, state);
|
|
1013
|
+
if (parsedMessageCount(runtime, state) >= bounds.maxMessages) {
|
|
1014
|
+
stoppedForMessageLimit = true;
|
|
1015
|
+
break scan;
|
|
1016
|
+
}
|
|
1017
|
+
newlineIndex = pending.indexOf('\n');
|
|
1018
|
+
}
|
|
1019
|
+
}
|
|
1020
|
+
const stoppedForByteLimit = fileInfo.size > bytesToRead;
|
|
1021
|
+
if (!stoppedForByteLimit && !stoppedForMessageLimit && pending.trim()) {
|
|
1022
|
+
consumeSessionLine(runtime, pending.replace(/\r$/u, ''), state);
|
|
1023
|
+
}
|
|
1024
|
+
return stoppedForByteLimit || stoppedForMessageLimit;
|
|
1025
|
+
}
|
|
1026
|
+
finally {
|
|
1027
|
+
stream.destroy();
|
|
1028
|
+
}
|
|
1029
|
+
}
|
|
1030
|
+
function consumeSessionLine(runtime, line, state) {
|
|
1031
|
+
if (!line.trim()) {
|
|
1032
|
+
return;
|
|
1033
|
+
}
|
|
1034
|
+
try {
|
|
1035
|
+
const record = JSON.parse(line);
|
|
1036
|
+
if (!isRecord(record)) {
|
|
1037
|
+
return;
|
|
1038
|
+
}
|
|
1039
|
+
if (runtime === 'claude') {
|
|
1040
|
+
consumeClaudeRecord(record, state);
|
|
1041
|
+
}
|
|
1042
|
+
else if (runtime === 'codex') {
|
|
1043
|
+
consumeCodexRecord(record, state);
|
|
1044
|
+
}
|
|
1045
|
+
else if (runtime === 'pi') {
|
|
1046
|
+
consumePiRecord(record, state);
|
|
1047
|
+
}
|
|
1048
|
+
}
|
|
1049
|
+
catch {
|
|
1050
|
+
// A CLI can be terminated while appending its final JSONL record.
|
|
1051
|
+
}
|
|
1052
|
+
}
|
|
1053
|
+
function parsedMessageCount(runtime, state) {
|
|
1054
|
+
if (runtime === 'pi') {
|
|
1055
|
+
return state.piMessageCount;
|
|
1056
|
+
}
|
|
1057
|
+
return hasConversationMessages(state.messages)
|
|
1058
|
+
? state.messages.length
|
|
1059
|
+
: state.fallbackMessages.length;
|
|
1060
|
+
}
|
|
1061
|
+
function getCachedSummary(candidate, bounds) {
|
|
1062
|
+
const cached = summaryCache.get(candidate.path);
|
|
1063
|
+
if (!cached ||
|
|
1064
|
+
cached.runtime !== candidate.runtime ||
|
|
1065
|
+
cached.mtimeMs !== candidate.stats.mtimeMs ||
|
|
1066
|
+
cached.size !== candidate.stats.size ||
|
|
1067
|
+
cached.maxBytes !== bounds.maxBytes ||
|
|
1068
|
+
cached.maxMessages !== bounds.maxMessages) {
|
|
1069
|
+
return undefined;
|
|
1070
|
+
}
|
|
1071
|
+
summaryCache.delete(candidate.path);
|
|
1072
|
+
summaryCache.set(candidate.path, cached);
|
|
1073
|
+
return { ...cached.summary };
|
|
1074
|
+
}
|
|
1075
|
+
function cacheSummary(candidate, bounds, summary) {
|
|
1076
|
+
summaryCache.delete(candidate.path);
|
|
1077
|
+
summaryCache.set(candidate.path, {
|
|
1078
|
+
runtime: candidate.runtime,
|
|
1079
|
+
mtimeMs: candidate.stats.mtimeMs,
|
|
1080
|
+
size: candidate.stats.size,
|
|
1081
|
+
maxBytes: bounds.maxBytes,
|
|
1082
|
+
maxMessages: bounds.maxMessages,
|
|
1083
|
+
summary: { ...summary },
|
|
1084
|
+
});
|
|
1085
|
+
while (summaryCache.size > MAX_SUMMARY_CACHE_ENTRIES) {
|
|
1086
|
+
const oldestKey = summaryCache.keys().next().value;
|
|
1087
|
+
if (!oldestKey) {
|
|
1088
|
+
break;
|
|
1089
|
+
}
|
|
1090
|
+
summaryCache.delete(oldestKey);
|
|
1091
|
+
}
|
|
1092
|
+
}
|
|
1093
|
+
function normalizedNonNegativeInteger(value, fallback) {
|
|
1094
|
+
return typeof value === 'number' && Number.isFinite(value)
|
|
1095
|
+
? Math.max(0, Math.floor(value))
|
|
1096
|
+
: fallback;
|
|
1097
|
+
}
|
|
1098
|
+
function normalizedPositiveInteger(value, fallback) {
|
|
1099
|
+
return typeof value === 'number' && Number.isFinite(value) && value > 0
|
|
1100
|
+
? Math.floor(value)
|
|
1101
|
+
: fallback;
|
|
1102
|
+
}
|
|
1103
|
+
function nonNegativeIntegerValue(value) {
|
|
1104
|
+
return typeof value === 'number' && Number.isFinite(value) && value >= 0
|
|
1105
|
+
? Math.floor(value)
|
|
1106
|
+
: undefined;
|
|
1107
|
+
}
|
|
1108
|
+
function consumeClaudeRecord(record, state) {
|
|
1109
|
+
const timestamp = rememberTimestamp(state, record.timestamp);
|
|
1110
|
+
state.nativeSessionId ??= stringValue(record.sessionId);
|
|
1111
|
+
state.cwd ??= stringValue(record.cwd);
|
|
1112
|
+
if (record.type === 'summary') {
|
|
1113
|
+
state.nativeTitle ??= stringValue(record.summary);
|
|
1114
|
+
return;
|
|
1115
|
+
}
|
|
1116
|
+
if (record.type !== 'user' && record.type !== 'assistant' && record.type !== 'system') {
|
|
1117
|
+
return;
|
|
1118
|
+
}
|
|
1119
|
+
const message = isRecord(record.message) ? record.message : record;
|
|
1120
|
+
const role = normalizeRole(message.role) ?? normalizeRole(record.type);
|
|
1121
|
+
if (!role) {
|
|
1122
|
+
return;
|
|
1123
|
+
}
|
|
1124
|
+
const content = extractContent(message.content);
|
|
1125
|
+
const normalizedRole = content.toolResultOnly ? 'tool' : role;
|
|
1126
|
+
pushMessage(state.messages, {
|
|
1127
|
+
role: normalizedRole,
|
|
1128
|
+
text: content.text,
|
|
1129
|
+
timestamp,
|
|
1130
|
+
model: stringValue(message.model),
|
|
1131
|
+
tools: content.tools,
|
|
1132
|
+
});
|
|
1133
|
+
}
|
|
1134
|
+
function consumeCodexRecord(record, state) {
|
|
1135
|
+
const timestamp = rememberTimestamp(state, record.timestamp);
|
|
1136
|
+
const payload = isRecord(record.payload) ? record.payload : undefined;
|
|
1137
|
+
if (!payload) {
|
|
1138
|
+
return;
|
|
1139
|
+
}
|
|
1140
|
+
if (record.type === 'session_meta') {
|
|
1141
|
+
state.nativeSessionId ??= stringValue(payload.id);
|
|
1142
|
+
state.cwd ??= stringValue(payload.cwd);
|
|
1143
|
+
rememberTimestamp(state, payload.timestamp);
|
|
1144
|
+
return;
|
|
1145
|
+
}
|
|
1146
|
+
if (record.type === 'turn_context') {
|
|
1147
|
+
state.cwd ??= stringValue(payload.cwd);
|
|
1148
|
+
state.model = stringValue(payload.model) ?? state.model;
|
|
1149
|
+
return;
|
|
1150
|
+
}
|
|
1151
|
+
if (record.type === 'response_item') {
|
|
1152
|
+
consumeCodexResponseItem(payload, state, timestamp);
|
|
1153
|
+
return;
|
|
1154
|
+
}
|
|
1155
|
+
if (record.type === 'event_msg') {
|
|
1156
|
+
consumeCodexEventMessage(payload, state, timestamp);
|
|
1157
|
+
}
|
|
1158
|
+
}
|
|
1159
|
+
function consumeCodexResponseItem(payload, state, timestamp) {
|
|
1160
|
+
if (payload.type === 'message') {
|
|
1161
|
+
const role = normalizeRole(payload.role);
|
|
1162
|
+
if (!role) {
|
|
1163
|
+
return;
|
|
1164
|
+
}
|
|
1165
|
+
const content = extractContent(payload.content);
|
|
1166
|
+
pushMessage(state.messages, {
|
|
1167
|
+
role: content.toolResultOnly ? 'tool' : role,
|
|
1168
|
+
text: content.text,
|
|
1169
|
+
timestamp,
|
|
1170
|
+
model: stringValue(payload.model) ?? state.model,
|
|
1171
|
+
tools: content.tools,
|
|
1172
|
+
});
|
|
1173
|
+
return;
|
|
1174
|
+
}
|
|
1175
|
+
const tool = codexToolMetadata(payload);
|
|
1176
|
+
if (!tool) {
|
|
1177
|
+
return;
|
|
1178
|
+
}
|
|
1179
|
+
pushMessage(state.messages, {
|
|
1180
|
+
role: tool.kind === 'result' ? 'tool' : 'assistant',
|
|
1181
|
+
text: tool.output ?? '',
|
|
1182
|
+
timestamp,
|
|
1183
|
+
model: state.model,
|
|
1184
|
+
tools: [tool],
|
|
1185
|
+
});
|
|
1186
|
+
}
|
|
1187
|
+
function consumeCodexEventMessage(payload, state, timestamp) {
|
|
1188
|
+
const role = payload.type === 'user_message'
|
|
1189
|
+
? 'user'
|
|
1190
|
+
: payload.type === 'agent_message'
|
|
1191
|
+
? 'assistant'
|
|
1192
|
+
: undefined;
|
|
1193
|
+
if (!role) {
|
|
1194
|
+
return;
|
|
1195
|
+
}
|
|
1196
|
+
pushMessage(state.fallbackMessages, {
|
|
1197
|
+
role,
|
|
1198
|
+
text: visibleText(payload.message),
|
|
1199
|
+
timestamp,
|
|
1200
|
+
model: stringValue(payload.model) ?? state.model,
|
|
1201
|
+
});
|
|
1202
|
+
}
|
|
1203
|
+
function consumePiRecord(record, state) {
|
|
1204
|
+
rememberTimestamp(state, record.timestamp);
|
|
1205
|
+
if (record.type === 'session') {
|
|
1206
|
+
state.nativeSessionId ??= stringValue(record.id);
|
|
1207
|
+
state.cwd ??= stringValue(record.cwd);
|
|
1208
|
+
return;
|
|
1209
|
+
}
|
|
1210
|
+
const id = stringValue(record.id);
|
|
1211
|
+
const parentId = record.parentId === null ? null : stringValue(record.parentId);
|
|
1212
|
+
if (!id || parentId === undefined) {
|
|
1213
|
+
return;
|
|
1214
|
+
}
|
|
1215
|
+
state.piEntries.push({ id, parentId, record });
|
|
1216
|
+
if (record.type === 'message' && isRecord(record.message)) {
|
|
1217
|
+
const role = record.message.role;
|
|
1218
|
+
if (role === 'user' || role === 'assistant' || role === 'toolResult') {
|
|
1219
|
+
state.piMessageCount += 1;
|
|
1220
|
+
}
|
|
1221
|
+
}
|
|
1222
|
+
}
|
|
1223
|
+
function finalizePiState(state) {
|
|
1224
|
+
state.messages = [];
|
|
1225
|
+
state.nativeTitle = undefined;
|
|
1226
|
+
state.model = undefined;
|
|
1227
|
+
const entriesById = new Map(state.piEntries.map(entry => [entry.id, entry]));
|
|
1228
|
+
const branch = [];
|
|
1229
|
+
const visited = new Set();
|
|
1230
|
+
let entry = state.piEntries.at(-1);
|
|
1231
|
+
while (entry && !visited.has(entry.id)) {
|
|
1232
|
+
visited.add(entry.id);
|
|
1233
|
+
branch.push(entry);
|
|
1234
|
+
entry = entry.parentId === null ? undefined : entriesById.get(entry.parentId);
|
|
1235
|
+
}
|
|
1236
|
+
branch.reverse();
|
|
1237
|
+
for (const branchEntry of branch) {
|
|
1238
|
+
const record = branchEntry.record;
|
|
1239
|
+
if (record.type === 'session_info') {
|
|
1240
|
+
state.nativeTitle = stringValue(record.name) ?? state.nativeTitle;
|
|
1241
|
+
continue;
|
|
1242
|
+
}
|
|
1243
|
+
if (record.type === 'model_change') {
|
|
1244
|
+
state.model = stringValue(record.modelId) ?? state.model;
|
|
1245
|
+
continue;
|
|
1246
|
+
}
|
|
1247
|
+
if (record.type === 'message' && isRecord(record.message)) {
|
|
1248
|
+
consumePiMessage(record.message, state, normalizeTimestamp(record.timestamp));
|
|
1249
|
+
}
|
|
1250
|
+
}
|
|
1251
|
+
}
|
|
1252
|
+
function consumePiMessage(message, state, timestamp) {
|
|
1253
|
+
const content = extractContent(message.content);
|
|
1254
|
+
if (message.role === 'user' || message.role === 'assistant') {
|
|
1255
|
+
pushMessage(state.messages, {
|
|
1256
|
+
role: message.role,
|
|
1257
|
+
text: content.text,
|
|
1258
|
+
timestamp,
|
|
1259
|
+
model: stringValue(message.model) ?? state.model,
|
|
1260
|
+
tools: content.tools,
|
|
1261
|
+
});
|
|
1262
|
+
return;
|
|
1263
|
+
}
|
|
1264
|
+
if (message.role === 'toolResult') {
|
|
1265
|
+
pushMessage(state.messages, {
|
|
1266
|
+
role: 'tool',
|
|
1267
|
+
text: content.text,
|
|
1268
|
+
timestamp,
|
|
1269
|
+
model: state.model,
|
|
1270
|
+
tools: [{
|
|
1271
|
+
kind: 'result',
|
|
1272
|
+
id: stringValue(message.toolCallId ?? message.tool_call_id),
|
|
1273
|
+
name: stringValue(message.toolName ?? message.tool_name),
|
|
1274
|
+
output: content.text,
|
|
1275
|
+
isError: booleanValue(message.isError ?? message.is_error),
|
|
1276
|
+
}],
|
|
1277
|
+
});
|
|
1278
|
+
}
|
|
1279
|
+
}
|
|
1280
|
+
function codexToolMetadata(payload) {
|
|
1281
|
+
const type = stringValue(payload.type);
|
|
1282
|
+
if (!type) {
|
|
1283
|
+
return undefined;
|
|
1284
|
+
}
|
|
1285
|
+
if (type.endsWith('_output') || type.endsWith('_result')) {
|
|
1286
|
+
const output = visibleText(payload.output ?? payload.result);
|
|
1287
|
+
return {
|
|
1288
|
+
kind: 'result',
|
|
1289
|
+
id: stringValue(payload.call_id ?? payload.id),
|
|
1290
|
+
output,
|
|
1291
|
+
isError: booleanValue(payload.is_error ?? payload.isError),
|
|
1292
|
+
};
|
|
1293
|
+
}
|
|
1294
|
+
if (type.endsWith('_call') || type === 'local_shell_call') {
|
|
1295
|
+
return {
|
|
1296
|
+
kind: 'call',
|
|
1297
|
+
id: stringValue(payload.call_id ?? payload.id),
|
|
1298
|
+
name: stringValue(payload.name) ?? type.replace(/_call$/u, ''),
|
|
1299
|
+
input: payload.arguments ?? payload.input ?? payload.command,
|
|
1300
|
+
};
|
|
1301
|
+
}
|
|
1302
|
+
return undefined;
|
|
1303
|
+
}
|
|
1304
|
+
function extractContent(content) {
|
|
1305
|
+
if (typeof content === 'string') {
|
|
1306
|
+
return { text: content.trim(), tools: [], toolResultOnly: false };
|
|
1307
|
+
}
|
|
1308
|
+
if (!Array.isArray(content)) {
|
|
1309
|
+
return { text: '', tools: [], toolResultOnly: false };
|
|
1310
|
+
}
|
|
1311
|
+
const textParts = [];
|
|
1312
|
+
const tools = [];
|
|
1313
|
+
let hasPlainText = false;
|
|
1314
|
+
for (const block of content) {
|
|
1315
|
+
if (!isRecord(block)) {
|
|
1316
|
+
continue;
|
|
1317
|
+
}
|
|
1318
|
+
const type = stringValue(block.type);
|
|
1319
|
+
if (type === 'text' || type === 'input_text' || type === 'output_text') {
|
|
1320
|
+
const text = stringValue(block.text);
|
|
1321
|
+
if (text) {
|
|
1322
|
+
textParts.push(text);
|
|
1323
|
+
hasPlainText = true;
|
|
1324
|
+
}
|
|
1325
|
+
continue;
|
|
1326
|
+
}
|
|
1327
|
+
if (type === 'tool_use' ||
|
|
1328
|
+
type === 'function_call' ||
|
|
1329
|
+
type === 'custom_tool_call' ||
|
|
1330
|
+
type === 'toolCall') {
|
|
1331
|
+
tools.push({
|
|
1332
|
+
kind: 'call',
|
|
1333
|
+
id: stringValue(block.id ?? block.call_id),
|
|
1334
|
+
name: stringValue(block.name),
|
|
1335
|
+
input: block.input ?? block.arguments,
|
|
1336
|
+
});
|
|
1337
|
+
continue;
|
|
1338
|
+
}
|
|
1339
|
+
if (type === 'tool_result' || type === 'function_call_output') {
|
|
1340
|
+
const output = visibleText(block.content ?? block.output);
|
|
1341
|
+
tools.push({
|
|
1342
|
+
kind: 'result',
|
|
1343
|
+
id: stringValue(block.tool_use_id ?? block.call_id ?? block.id),
|
|
1344
|
+
output,
|
|
1345
|
+
isError: booleanValue(block.is_error ?? block.isError),
|
|
1346
|
+
});
|
|
1347
|
+
if (output) {
|
|
1348
|
+
textParts.push(output);
|
|
1349
|
+
}
|
|
1350
|
+
}
|
|
1351
|
+
}
|
|
1352
|
+
return {
|
|
1353
|
+
text: textParts.join('\n').trim(),
|
|
1354
|
+
tools,
|
|
1355
|
+
toolResultOnly: tools.some(tool => tool.kind === 'result') && !hasPlainText,
|
|
1356
|
+
};
|
|
1357
|
+
}
|
|
1358
|
+
function visibleText(value) {
|
|
1359
|
+
if (typeof value === 'string') {
|
|
1360
|
+
return value.trim();
|
|
1361
|
+
}
|
|
1362
|
+
if (Array.isArray(value)) {
|
|
1363
|
+
return value.map(visibleText).filter(Boolean).join('\n').trim();
|
|
1364
|
+
}
|
|
1365
|
+
if (!isRecord(value)) {
|
|
1366
|
+
return '';
|
|
1367
|
+
}
|
|
1368
|
+
if ((value.type === 'text' || value.type === 'input_text' || value.type === 'output_text') &&
|
|
1369
|
+
typeof value.text === 'string') {
|
|
1370
|
+
return value.text.trim();
|
|
1371
|
+
}
|
|
1372
|
+
return visibleText(value.content);
|
|
1373
|
+
}
|
|
1374
|
+
function pushMessage(messages, message) {
|
|
1375
|
+
const tools = message.tools?.filter(Boolean);
|
|
1376
|
+
if (!message.text && !tools?.length) {
|
|
1377
|
+
return;
|
|
1378
|
+
}
|
|
1379
|
+
messages.push({
|
|
1380
|
+
...message,
|
|
1381
|
+
...(tools?.length ? { tools } : { tools: undefined }),
|
|
1382
|
+
});
|
|
1383
|
+
}
|
|
1384
|
+
function hasConversationMessages(messages) {
|
|
1385
|
+
return messages.some(message => Boolean(message.text) && (message.role === 'user' || message.role === 'assistant'));
|
|
1386
|
+
}
|
|
1387
|
+
function rememberTimestamp(state, value) {
|
|
1388
|
+
const timestamp = normalizeTimestamp(value);
|
|
1389
|
+
if (timestamp) {
|
|
1390
|
+
const milliseconds = Date.parse(timestamp);
|
|
1391
|
+
state.earliestTimestamp = state.earliestTimestamp == null
|
|
1392
|
+
? milliseconds
|
|
1393
|
+
: Math.min(state.earliestTimestamp, milliseconds);
|
|
1394
|
+
state.latestTimestamp = state.latestTimestamp == null
|
|
1395
|
+
? milliseconds
|
|
1396
|
+
: Math.max(state.latestTimestamp, milliseconds);
|
|
1397
|
+
}
|
|
1398
|
+
return timestamp;
|
|
1399
|
+
}
|
|
1400
|
+
function normalizeTimestamp(value) {
|
|
1401
|
+
let milliseconds;
|
|
1402
|
+
if (typeof value === 'number' && Number.isFinite(value)) {
|
|
1403
|
+
milliseconds = value < 1_000_000_000_000 ? value * 1_000 : value;
|
|
1404
|
+
}
|
|
1405
|
+
else if (typeof value === 'string' && value.trim()) {
|
|
1406
|
+
milliseconds = Date.parse(value);
|
|
1407
|
+
}
|
|
1408
|
+
else {
|
|
1409
|
+
return undefined;
|
|
1410
|
+
}
|
|
1411
|
+
return Number.isFinite(milliseconds) ? new Date(milliseconds).toISOString() : undefined;
|
|
1412
|
+
}
|
|
1413
|
+
function normalizeTitle(value) {
|
|
1414
|
+
const normalized = value.replace(/\s+/gu, ' ').trim();
|
|
1415
|
+
return normalized.length > 160 ? `${normalized.slice(0, 157)}...` : normalized;
|
|
1416
|
+
}
|
|
1417
|
+
function sessionIdFromFileName(filePath) {
|
|
1418
|
+
const fileName = path.basename(filePath, path.extname(filePath));
|
|
1419
|
+
return fileName.match(/([0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12})$/iu)?.[1] ?? fileName;
|
|
1420
|
+
}
|
|
1421
|
+
function normalizeRole(value) {
|
|
1422
|
+
if (value === 'user' || value === 'assistant' || value === 'system' || value === 'tool') {
|
|
1423
|
+
return value;
|
|
1424
|
+
}
|
|
1425
|
+
return value === 'developer' ? 'system' : undefined;
|
|
1426
|
+
}
|
|
1427
|
+
function stringValue(value) {
|
|
1428
|
+
return typeof value === 'string' && value.length > 0 ? value : undefined;
|
|
1429
|
+
}
|
|
1430
|
+
function booleanValue(value) {
|
|
1431
|
+
return typeof value === 'boolean' ? value : undefined;
|
|
1432
|
+
}
|
|
1433
|
+
function isRecord(value) {
|
|
1434
|
+
return typeof value === 'object' && value !== null;
|
|
1435
|
+
}
|
|
1436
|
+
//# sourceMappingURL=externalCliSessions.js.map
|