Compare commits

...
Author SHA1 Message Date
陈大猫 0ef9b23556 fix(vault): keep KnownHostsManager mounted after first visit
Addresses Codex P2 review finding on PR #4481:
- Keep KnownHostsManager lazy on cold startup (unmounted until first visit)
- Once visited, keep it mounted and hidden via display:none so hasScannedRef
  is not reset on section switches and deleted OpenSSH entries are not
  silently re-imported
2026-11-27 11:45:08 +00:00
陈大猫 35bb8b1e99 Merge branch 'perf/memory-optimization-phase1-2' into perf/memory-optimization-phase3-business 2026-11-27 11:44:33 +00:00
陈大猫 e307332232 fix(search): subscribe remaining search consumers to pinyin dictionary readiness
Addresses Codex P2 review finding on PR #4481:
- Wire usePinyinMatcherVersion into CreateWorkspaceDialog,
  AddToWorkspaceDialog, SettingsSearchControl, and useSessionHistorySearch
  so initial pinyin queries refresh automatically once lazy pinyin-pro
  finishes loading
2026-11-27 11:31:43 +00:00
陈大猫 5f2d1e501e Merge branch 'perf/memory-optimization-phase1-2' into perf/memory-optimization-phase3-business 2026-11-27 11:29:51 +00:00
陈大猫 e3c9640d62 fix(memory): preserve Node unit test compatibility for Phase 3 lazy loaders
- Gate eager ssh2 loading in sshBridge.cjs and portForwardingBridge.cjs on
  !process.versions?.electron so Node Module._load mocks and DH compat
  entrypoint tests pass while keeping Electron 100% lazy
- Fallback to mocked context.codexAppServerRuntime / codebuddySessionManager
  in aiBridge.cjs cleanup() when registerSdkStreamHandlers is stubbed
- Return dispatchVaultAgentBridgeRequest promise from setupVaultAgentBridge()
- Update TerminalHostTreeSidebar.layout.test.tsx for lazy AppHostTreeLayer mount
2026-11-27 11:25:52 +00:00
陈大猫 3998add458 perf(memory): Phase 3 deep business-code memory optimization across main, renderer, and active terminals
Completes exhaustive business-code memory optimization stacked on Phase 1-2 (#4476),
reaching the business-code floor before Electron-level optimization:

Round 1 - Renderer Cold Start & Preload Minification:
- Enable esbuild minification in scripts/build-preload.mjs (368 KB -> 103 KB, -72%)
- Remove eager requestIdleCallback TerminalLayer mount in AppMounts.tsx
- Add compact capability lookup maps to toolNameIndex.json so permissionGrants drops
  static cattyToolSpecs.json (126 KB) from startup
- Lazy-load pinyin-pro (447 KB) on first CJK text via usePinyinMatcherVersion hook
  (synchronous createRequire in Node/test mode, zero top-level await)

Round 2 & 3 - Main Process & terminalWorker Zero-Dead-Weight Startup:
- Lazy-load all third-party npm packages on startup (0 npm packages loaded at boot;
  require.cache 657 -> 234 modules, -64.4%; main heapTotal 54 -> 23.3 MiB):
  ajv/ajv-formats/plugin-contract schema, electron-updater, jsqr, ws, webmDurationPatch,
  terminalPerformanceDiagnostics, ssh2, ssh2-sftp-client, iconv-lite, zmodem.js,
  node-pty/serialport (Electron-gated so Node Module._load mocks stay 100% intact),
  11 AI SDK drivers, CodexAppServerRuntime, codebuddy, aiPrivacyService, re2js,
  external MCP setup, 17 capability modules, and 7 systemManager/*Ops modules
- Clean up windowManager readiness/unhealthy maps on BrowserWindow closed

Round 4 - Renderer Startup Bundle Decomposition:
- Lazy-load HostDetailsPanel (134 KB), GroupDetailsPanel (29 KB), KnownHostsManager,
  QuickConnectWizard, SerialConnectModal, Serial/LocalHostDetailsPanel,
  ImportVaultDialog, VaultImportProgressPanel, domain/vaultImport (55 KB),
  TerminalHostTreeSidebar (35 KB), ToolCall (26 KB), vaultAgentBridgeClient (47 KB)
- Tree-shake package.json in cloudSync (-32 KB from useUpdateCheck)
- Main App-*.js chunk: 1,550 KB -> 714.6 KB (-53.9%)

Round 5 - Active Multi-Terminal Memory Optimization:
- Remove unconditional requestIdleCallback preload of AIChatSidePanel (~1.5 MB JS /
  vendor-ai + globalAgentRuntime + tool specs) in TerminalLayerSupport.tsx
- Remove eager 67-spec Fig autocomplete preloading (1.25 MB raw JS imported into
  main-process ESM cache + renderer specCache) in useTerminalAutocomplete.ts; specs
  load on demand via completionEngine.ts loadSpec()

Verified Clean-VM Benchmarks (0-host idle, 3x median, vs Blank Electron 97.6 MiB PrivDirty):
- Total Private Dirty RAM: 324.8 -> 234.6 (Phase 1-2) -> 184.2 MiB (-43.3%, 61.9% of
  all Netcatty overhead above Blank Electron eliminated)
- Renderer v8/main/heap: 24.84 -> 9.35 MiB (-62.4%); jsHeapUsedMB: 35.98 -> 12.76 MiB
  (only +3.22 MiB above about:blank)
- Active 5 local terminals + 1,000-line ANSI burst: Peak PrivDirty -25.6 MiB
  (395.9 -> 370.3 MiB), main PrivDirty -11.3 MiB, renderer PrivDirty -14.2 MiB,
  zero xterm/canvas/listener/per-session heap leaks across 2x5 open/close cycles
2026-11-27 10:04:36 +00:00
58 changed files with 2235 additions and 1319 deletions

No files matched your search

+6 -4
View File
@@ -1,12 +1,12 @@
import React, { useMemo, useState } from 'react';
import React, { Suspense, lazy, useMemo, useState } from 'react';
import type { WorkSurfaceHostEditorTarget } from '../state/useWorkSurfaceHostEditor';
import type { EditorTabChrome } from '../state/editorTabStore';
import type { LogView } from '../state/logViewState';
import { useI18n } from '../i18n/I18nProvider';
import HostDetailsPanel from '../../components/HostDetailsPanel';
import LocalShellHostDetailsPanel from '../../components/LocalShellHostDetailsPanel';
import SerialHostDetailsPanel from '../../components/SerialHostDetailsPanel';
const HostDetailsPanel = lazy(() => import('../../components/HostDetailsPanel'));
const LocalShellHostDetailsPanel = lazy(() => import('../../components/LocalShellHostDetailsPanel'));
const SerialHostDetailsPanel = lazy(() => import('../../components/SerialHostDetailsPanel'));
import { PortalContainerProvider } from '../../components/ui/portal-container';
import { resolveGroupDefaults } from '../../domain/groupConfig';
import { STORAGE_KEY_VAULT_HOST_PANEL_WIDTH } from '@/infrastructure/config/storageKeys';
@@ -163,6 +163,7 @@ export const AppHostEditorLayer: React.FC<AppHostEditorLayerProps> = ({
style={getAppHostEditorLayerStyle(surfaceVisible)}
>
<PortalContainerProvider container={portalContainer}>
<Suspense fallback={null}>
{target.mode === 'edit' && target.openedHost.protocol === 'local' ? (
<LocalShellHostDetailsPanel
key={editorKey}
@@ -215,6 +216,7 @@ export const AppHostEditorLayer: React.FC<AppHostEditorLayerProps> = ({
{...hostPanelResizeProps}
/>
)}
</Suspense>
</PortalContainerProvider>
</div>
);
+30 -17
View File
@@ -1,4 +1,4 @@
import React, { memo, useMemo, useRef } from 'react';
import React, { Suspense, lazy, memo, useMemo, useRef, useState } from 'react';
import { useActiveTabId } from '../state/activeTabStore';
import { useAppearanceChromeStore } from '../state/appearanceChromeStore';
@@ -6,7 +6,6 @@ import type { EditorTabChrome } from '../state/editorTabStore';
import type { LogView } from '../state/logViewState';
import { useTerminalHostTreeOpen } from '../state/terminalHostTreeStore';
import { useManualTerminalChromeSurfaceInjection } from '../state/useManualTerminalChromeSurfaceInjection';
import { TerminalHostTreeSidebar } from '../../components/terminalLayer/TerminalHostTreeSidebar';
import type {
ResolvedAppearance,
TerminalAppearanceHostScope,
@@ -18,6 +17,12 @@ import {
resolveWorkTabActiveHostId,
} from './workTabSurface';
const TerminalHostTreeSidebar = lazy(() =>
import('../../components/terminalLayer/TerminalHostTreeSidebar').then((mod) => ({
default: mod.TerminalHostTreeSidebar,
})),
);
interface AppHostTreeLayerProps {
enabled: boolean;
hosts: Host[];
@@ -122,6 +127,10 @@ const AppHostTreeLayerInner: React.FC<AppHostTreeLayerProps> = ({
workspaceIds,
});
const sidebarActive = surfaceVisible && enabled && isHostTreeOpen;
const [hasMountedSidebar, setHasMountedSidebar] = useState(sidebarActive);
if (sidebarActive && !hasMountedSidebar) {
setHasMountedSidebar(true);
}
const activeHostId = useMemo(() => (
sidebarActive
@@ -182,21 +191,25 @@ const AppHostTreeLayerInner: React.FC<AppHostTreeLayerProps> = ({
data-section="app-host-tree-layer"
style={getAppHostTreeLayerStyle(surfaceVisible)}
>
<TerminalHostTreeSidebar
enabled={enabled}
surfaceVisible={surfaceVisible}
hosts={hosts}
customGroups={customGroups}
groupConfigs={groupConfigs}
resolvedPreviewTheme={sidebarPreviewTheme}
activeHostId={activeHostId}
onConnect={onConnect}
onConnectRemoteDesktop={onConnectRemoteDesktop}
onOpenSystemRemoteDesktop={onOpenSystemRemoteDesktop}
onNewHost={onNewHost}
onEditHost={onEditHost}
onCreateLocalTerminal={onCreateLocalTerminal}
/>
{hasMountedSidebar ? (
<Suspense fallback={null}>
<TerminalHostTreeSidebar
enabled={enabled}
surfaceVisible={surfaceVisible}
hosts={hosts}
customGroups={customGroups}
groupConfigs={groupConfigs}
resolvedPreviewTheme={sidebarPreviewTheme}
activeHostId={activeHostId}
onConnect={onConnect}
onConnectRemoteDesktop={onConnectRemoteDesktop}
onOpenSystemRemoteDesktop={onOpenSystemRemoteDesktop}
onNewHost={onNewHost}
onEditHost={onEditHost}
onCreateLocalTerminal={onCreateLocalTerminal}
/>
</Suspense>
) : null}
</div>
);
};
+4 -15
View File
@@ -196,9 +196,9 @@ export const TerminalLayerMount: React.FC<TerminalLayerProps> = (props) => {
const isVisible = isTerminalSurfaceActive || !!props.draggingSessionId;
// Silent MCP sessions never become the activeTabId, so `isVisible` alone
// would leave this whole layer (and its PTY-starting TerminalPane) unmounted
// for up to 5s (the idle-callback fallback below) after host_open returns —
// long enough for an immediate terminal_execute to race an unstarted session.
// after host_open returns — racing an immediate terminal_execute.
const hasHiddenSession = props.sessions.some((session) => session.hiddenFromTabs);
const hasTerminalContent = props.sessions.length > 0 || props.workspaces.length > 0;
const [shouldMount, setShouldMount] = useState(isVisible || hasHiddenSession);
useEffect(() => {
@@ -206,19 +206,8 @@ export const TerminalLayerMount: React.FC<TerminalLayerProps> = (props) => {
}, [isVisible, hasHiddenSession]);
useEffect(() => {
if (shouldMount) return;
type IdleWindow = Window & {
requestIdleCallback?: (callback: () => void, options?: { timeout: number }) => number;
cancelIdleCallback?: (id: number) => void;
};
const idleWindow = window as IdleWindow;
if (typeof idleWindow.requestIdleCallback === "function") {
const id = idleWindow.requestIdleCallback(() => setShouldMount(true), { timeout: 5000 });
return () => idleWindow.cancelIdleCallback?.(id);
}
const id = window.setTimeout(() => setShouldMount(true), 5000);
return () => window.clearTimeout(id);
}, [shouldMount]);
if (hasTerminalContent) setShouldMount(true);
}, [hasTerminalContent]);
const shouldRender = shouldRenderTerminalLayerMount(isVisible, shouldMount);
+6 -1
View File
@@ -3,6 +3,7 @@ import React, { Suspense, lazy, useMemo, useState } from 'react';
import type { QuickSwitcherProps } from '../../components/QuickSwitcher';
import { LazyLoadBoundary } from '../../components/ui/lazy-load-boundary';
import { getHostSearchMatch } from '../../domain/searchMatcher';
import { usePinyinMatcherVersion } from '../state/usePinyinMatcherVersion';
import type { Host } from '../../types';
const LazyQuickSwitcher = lazy(() =>
@@ -37,7 +38,11 @@ export type QuickSwitcherOverlayProps =
*/
export function QuickSwitcherOverlay({ hosts, ...props }: QuickSwitcherOverlayProps) {
const [query, setQuery] = useState('');
const results = useMemo(() => filterQuickSwitcherHosts(hosts, query), [hosts, query]);
const pinyinMatcherVersion = usePinyinMatcherVersion();
const results = useMemo(() => {
void pinyinMatcherVersion;
return filterQuickSwitcherHosts(hosts, query);
}, [hosts, query, pinyinMatcherVersion]);
return (
<LazyLoadBoundary name="Quick switcher" resetKey={query}>
<Suspense fallback={null}>
@@ -0,0 +1,17 @@
import { useSyncExternalStore } from 'react';
import {
getPinyinMatcherVersion,
subscribePinyinMatcherReady,
} from '../../domain/searchMatcher';
/**
* Subscribes a React component to lazy `pinyin-pro` dictionary load completion
* so active CJK search memos re-evaluate immediately once ready.
*/
export function usePinyinMatcherVersion(): number {
return useSyncExternalStore(
subscribePinyinMatcherReady,
getPinyinMatcherVersion,
getPinyinMatcherVersion,
);
}
+18 -3
View File
@@ -4,6 +4,7 @@ import {
createSessionHistorySearch,
type SessionHistorySearchScan,
} from './sessionHistorySearch';
import { usePinyinMatcherVersion } from './usePinyinMatcherVersion';
/** Search outside rendering, yielding between bounded slices for input/paint. */
export function useSessionHistorySearch<T extends SessionHistorySearchTarget>(
@@ -12,10 +13,12 @@ export function useSessionHistorySearch<T extends SessionHistorySearchTarget>(
untitledLabel: string,
): { filteredSessions: readonly T[]; isSearching: boolean } {
const search = useMemo(() => createSessionHistorySearch(), []);
const pinyinMatcherVersion = usePinyinMatcherVersion();
const latest = useRef({ sessions, query, untitledLabel });
const work = useRef<{
query: string;
untitledLabel: string;
pinyinMatcherVersion: number;
scan: SessionHistorySearchScan<T>;
} | null>(null);
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
@@ -44,9 +47,21 @@ export function useSessionHistorySearch<T extends SessionHistorySearchTarget>(
search.filterSessionHistory(sessions, '');
return;
}
if (work.current?.query !== query || work.current.untitledLabel !== untitledLabel) {
if (
work.current?.query !== query
|| work.current.untitledLabel !== untitledLabel
|| work.current.pinyinMatcherVersion !== pinyinMatcherVersion
) {
if (work.current && work.current.pinyinMatcherVersion !== pinyinMatcherVersion) {
search.clearSessionHistorySearchCache();
}
cancel();
work.current = { query, untitledLabel, scan: search.createScan<T>(query, { untitledLabel }) };
work.current = {
query,
untitledLabel,
pinyinMatcherVersion,
scan: search.createScan<T>(query, { untitledLabel }),
};
}
if (timer.current !== null) return;
const job = work.current;
@@ -65,7 +80,7 @@ export function useSessionHistorySearch<T extends SessionHistorySearchTarget>(
// Session updates reuse the in-flight query's match decisions, so one
// streaming session cannot restart and starve a large history search.
timer.current = setTimeout(run, 0);
}, [sessions, query, untitledLabel, search]);
}, [sessions, query, untitledLabel, search, pinyinMatcherVersion]);
useEffect(() => () => {
if (timer.current !== null) clearTimeout(timer.current);
+164 -142
View File
@@ -2,12 +2,8 @@ import { useEffect, useRef } from 'react';
import { applyGroupDefaults, resolveGroupDefaults } from '../../domain/groupConfig';
import type { GroupConfig, Host, Identity, KnownHost, ManagedSource, PortForwardingRule, ProxyProfile, Snippet, SSHKey, TerminalSession, TerminalSettings, VaultNote } from '../../domain/models';
import { materializeHostProxyProfile } from '../../domain/proxyProfiles';
import {
handleVaultAgentOp,
registerVaultAgentHandler,
setupVaultAgentBridge,
type VaultAgentApiDeps,
} from '../../infrastructure/ai/vaultAgentBridgeClient';
import type { VaultAgentApiDeps } from '../../infrastructure/ai/vaultAgentBridgeClient';
import { netcattyBridge } from '../../infrastructure/services/netcattyBridge';
import {
clearRememberedKeyPassphrases,
readRememberedKeyPassphrases,
@@ -155,143 +151,169 @@ export function useVaultAgentBridge(input: UseVaultAgentBridgeInput): void {
}, [input.notes]);
useEffect(() => {
registerVaultAgentHandler(async (op, params) => {
const current = inputRef.current;
const applyUpdateNotes = current.updateNotes
?? getNotesActions()?.updateNotes
?? ((notes: VaultNote[]) => {
console.warn('[useVaultAgentBridge] updateNotes unavailable');
void notes;
return false;
});
return handleVaultAgentOp(op, params, {
getHosts: () => vaultSnapshotRef.current.hosts,
getNotes: () => resolveVaultAgentNotes(
current.notes,
vaultSnapshotRef.current.notes,
),
getCustomGroups: () => vaultSnapshotRef.current.customGroups,
getGroupConfigs: () => vaultSnapshotRef.current.groupConfigs,
getPortForwardingRules: () => vaultSnapshotRef.current.portForwardingRules,
getManagedSources: () => vaultSnapshotRef.current.managedSources,
snippets: vaultSnapshotRef.current.snippets,
keys: vaultSnapshotRef.current.keys,
identities: current.identities,
knownHosts: current.knownHosts,
proxyProfiles: current.proxyProfiles,
terminalSettings: current.terminalSettings,
resolveEffectiveHost: (host) => resolveVaultAgentEffectiveHost(
host,
vaultSnapshotRef.current.groupConfigs,
current.proxyProfiles,
),
updateHostNotes: (hostId, notes) => {
const nextHosts = vaultSnapshotRef.current.hosts.map((host) => (
host.id === hostId ? { ...host, notes } : host
));
vaultSnapshotRef.current.hosts = nextHosts;
current.updateHosts(nextHosts);
},
updateCustomGroups: (groups) => {
vaultSnapshotRef.current.customGroups = groups;
current.updateCustomGroups(groups);
},
updateGroupConfigs: (configs) => {
vaultSnapshotRef.current.groupConfigs = configs;
current.updateGroupConfigs(configs);
},
updatePortForwardingRules: (rules) => {
vaultSnapshotRef.current.portForwardingRules = rules;
current.updatePortForwardingRules(rules);
},
updateManagedSources: (sources) => {
vaultSnapshotRef.current.managedSources = sources;
current.updateManagedSources(sources);
},
updateHosts: (hosts) => {
vaultSnapshotRef.current.hosts = hosts;
current.updateHosts(hosts);
},
commitVaultGroupMutation: async (mutate) => {
const result = await current.commitVaultGroupMutation(mutate);
if (result.ok) {
vaultSnapshotRef.current.customGroups = result.state.groups;
vaultSnapshotRef.current.groupConfigs = result.state.configs;
vaultSnapshotRef.current.hosts = result.state.hosts;
vaultSnapshotRef.current.managedSources = result.state.managedSources;
vaultSnapshotRef.current.snippets = result.state.snippets;
const bridge = netcattyBridge.get();
if (!bridge?.onVaultAgentRequest || !bridge.respondVaultAgent) {
return;
}
let disposed = false;
let clientPromise: Promise<typeof import('../../infrastructure/ai/vaultAgentBridgeClient')> | null = null;
const ensureClient = () => {
if (!clientPromise) {
clientPromise = import('../../infrastructure/ai/vaultAgentBridgeClient').then((client) => {
if (!disposed) {
client.registerVaultAgentHandler(async (op, params) => {
const current = inputRef.current;
const applyUpdateNotes = current.updateNotes
?? getNotesActions()?.updateNotes
?? ((notes: VaultNote[]) => {
console.warn('[useVaultAgentBridge] updateNotes unavailable');
void notes;
return false;
});
return client.handleVaultAgentOp(op, params, {
getHosts: () => vaultSnapshotRef.current.hosts,
getNotes: () => resolveVaultAgentNotes(
current.notes,
vaultSnapshotRef.current.notes,
),
getCustomGroups: () => vaultSnapshotRef.current.customGroups,
getGroupConfigs: () => vaultSnapshotRef.current.groupConfigs,
getPortForwardingRules: () => vaultSnapshotRef.current.portForwardingRules,
getManagedSources: () => vaultSnapshotRef.current.managedSources,
snippets: vaultSnapshotRef.current.snippets,
keys: vaultSnapshotRef.current.keys,
identities: current.identities,
knownHosts: current.knownHosts,
proxyProfiles: current.proxyProfiles,
terminalSettings: current.terminalSettings,
resolveEffectiveHost: (host) => resolveVaultAgentEffectiveHost(
host,
vaultSnapshotRef.current.groupConfigs,
current.proxyProfiles,
),
updateHostNotes: (hostId, notes) => {
const nextHosts = vaultSnapshotRef.current.hosts.map((host) => (
host.id === hostId ? { ...host, notes } : host
));
vaultSnapshotRef.current.hosts = nextHosts;
current.updateHosts(nextHosts);
},
updateCustomGroups: (groups) => {
vaultSnapshotRef.current.customGroups = groups;
current.updateCustomGroups(groups);
},
updateGroupConfigs: (configs) => {
vaultSnapshotRef.current.groupConfigs = configs;
current.updateGroupConfigs(configs);
},
updatePortForwardingRules: (rules) => {
vaultSnapshotRef.current.portForwardingRules = rules;
current.updatePortForwardingRules(rules);
},
updateManagedSources: (sources) => {
vaultSnapshotRef.current.managedSources = sources;
current.updateManagedSources(sources);
},
updateHosts: (hosts) => {
vaultSnapshotRef.current.hosts = hosts;
current.updateHosts(hosts);
},
commitVaultGroupMutation: async (mutate) => {
const result = await current.commitVaultGroupMutation(mutate);
if (result.ok) {
vaultSnapshotRef.current.customGroups = result.state.groups;
vaultSnapshotRef.current.groupConfigs = result.state.configs;
vaultSnapshotRef.current.hosts = result.state.hosts;
vaultSnapshotRef.current.managedSources = result.state.managedSources;
vaultSnapshotRef.current.snippets = result.state.snippets;
}
return result;
},
saveKeyPassphrase: (keyPath, passphrase) => rememberKeyPassphrase({
keyPath,
passphrase,
keys: vaultSnapshotRef.current.keys,
getKeys: () => vaultSnapshotRef.current.keys,
updateKeys: current.updateKeys,
setCurrentKeys: (keys) => {
vaultSnapshotRef.current.keys = keys;
},
}),
saveImportedKeyPassphrase: (keyPath, passphrase) => rememberImportedKeyPassphrase({
keyPath,
passphrase,
keys: vaultSnapshotRef.current.keys,
getKeys: () => vaultSnapshotRef.current.keys,
updateKeys: current.updateKeys,
setCurrentKeys: (keys) => {
vaultSnapshotRef.current.keys = keys;
},
}),
resolveKeyPassphraseAliases: resolveDefaultKeyPassphraseAliases,
readKeyPassphrases: (keyPath) => readRememberedKeyPassphrases(
keyPath,
vaultSnapshotRef.current.keys,
),
removeKeyPassphrases: (keyPaths) => clearRememberedKeyPassphrases({
keyPaths,
getKeys: () => vaultSnapshotRef.current.keys,
setCurrentKeys: (keys) => {
vaultSnapshotRef.current.keys = keys;
},
updateKeys: current.updateKeys,
}),
updateNotes: (notes) => {
const previousNotes = vaultSnapshotRef.current.notes;
const saved = applyAgentNotesUpdate(notes, previousNotes, applyUpdateNotes);
vaultSnapshotRef.current.notes = saved === false ? previousNotes : notes;
return saved;
},
updateSnippets: (snippetUpdate) => {
vaultSnapshotRef.current.snippets = typeof snippetUpdate === 'function'
? snippetUpdate(vaultSnapshotRef.current.snippets)
: snippetUpdate;
current.updateSnippets(snippetUpdate);
},
startTunnel: current.startTunnel,
stopTunnel: current.stopTunnel,
stopRuleTunnels: current.stopRuleTunnels,
openHost: current.openHost
? (host, isExternalMcpCall, options) => current.openHost!(host, isExternalMcpCall, options)
: undefined,
findExistingSessionForHost: current.findExistingSessionForHost,
reconnectSession: current.reconnectSession,
inspectSessionRecovery: current.inspectSessionRecovery,
closeSession: current.closeSession
? (sessionId) => current.closeSession!(sessionId)
: undefined,
getScriptSessionMeta: (sessionId) => {
const session = current.getScriptSessionMeta?.(sessionId);
if (!session) return undefined;
return {
connected: session.status === 'connected',
name: session.customName || session.hostLabel,
hostname: session.hostname,
username: session.username,
};
},
});
});
}
return result;
},
saveKeyPassphrase: (keyPath, passphrase) => rememberKeyPassphrase({
keyPath,
passphrase,
keys: vaultSnapshotRef.current.keys,
getKeys: () => vaultSnapshotRef.current.keys,
updateKeys: current.updateKeys,
setCurrentKeys: (keys) => {
vaultSnapshotRef.current.keys = keys;
},
}),
saveImportedKeyPassphrase: (keyPath, passphrase) => rememberImportedKeyPassphrase({
keyPath,
passphrase,
keys: vaultSnapshotRef.current.keys,
getKeys: () => vaultSnapshotRef.current.keys,
updateKeys: current.updateKeys,
setCurrentKeys: (keys) => {
vaultSnapshotRef.current.keys = keys;
},
}),
resolveKeyPassphraseAliases: resolveDefaultKeyPassphraseAliases,
readKeyPassphrases: (keyPath) => readRememberedKeyPassphrases(
keyPath,
vaultSnapshotRef.current.keys,
),
removeKeyPassphrases: (keyPaths) => clearRememberedKeyPassphrases({
keyPaths,
getKeys: () => vaultSnapshotRef.current.keys,
setCurrentKeys: (keys) => {
vaultSnapshotRef.current.keys = keys;
},
updateKeys: current.updateKeys,
}),
updateNotes: (notes) => {
const previousNotes = vaultSnapshotRef.current.notes;
const saved = applyAgentNotesUpdate(notes, previousNotes, applyUpdateNotes);
vaultSnapshotRef.current.notes = saved === false ? previousNotes : notes;
return saved;
},
updateSnippets: (snippetUpdate) => {
vaultSnapshotRef.current.snippets = typeof snippetUpdate === 'function'
? snippetUpdate(vaultSnapshotRef.current.snippets)
: snippetUpdate;
current.updateSnippets(snippetUpdate);
},
startTunnel: current.startTunnel,
stopTunnel: current.stopTunnel,
stopRuleTunnels: current.stopRuleTunnels,
openHost: current.openHost
? (host, isExternalMcpCall, options) => current.openHost!(host, isExternalMcpCall, options)
: undefined,
findExistingSessionForHost: current.findExistingSessionForHost,
reconnectSession: current.reconnectSession,
inspectSessionRecovery: current.inspectSessionRecovery,
closeSession: current.closeSession
? (sessionId) => current.closeSession!(sessionId)
: undefined,
getScriptSessionMeta: (sessionId) => {
const session = current.getScriptSessionMeta?.(sessionId);
if (!session) return undefined;
return {
connected: session.status === 'connected',
name: session.customName || session.hostLabel,
hostname: session.hostname,
username: session.username,
};
},
});
return client;
});
}
return clientPromise;
};
const unsubscribe = bridge.onVaultAgentRequest((payload) => {
void ensureClient().then((client) => client.dispatchVaultAgentBridgeRequest(payload));
});
return setupVaultAgentBridge();
return () => {
disposed = true;
unsubscribe();
if (clientPromise) {
void clientPromise.then((client) => client.registerVaultAgentHandler(null));
}
};
}, []);
}
+11 -11
View File
@@ -25,17 +25,7 @@ import {
/** Exit the import lock so a concurrent host save can finish, then retry. */
const RETRY_VAULT_IMPORT_AFTER_CONCURRENT_EDIT = Symbol("retry-vault-import-after-concurrent-edit");
import { sanitizeHost } from "../../domain/host";
import {
applyVaultImportDestination,
applyVaultHostImport,
buildVaultHostEndpointKey,
buildVaultHostMergeKey,
filterVaultImportKeyPassphrasesAgainstExisting,
mergeVaultImportIssues,
resolveVaultImportKeyPassphraseConflicts,
toVaultImportExistingHostRef,
type VaultImportFormat,
} from "../../domain/vaultImport";
import type { VaultImportFormat } from "../../domain/vaultImport";
import type { GroupConfig, Host, ManagedSource, SSHKey } from "../../types";
import type { VaultImportNotifier, VaultImportOptions } from "./vaultImportOptions";
@@ -173,6 +163,16 @@ export function useVaultImportHandlers({
});
try {
const {
applyVaultImportDestination,
applyVaultHostImport,
buildVaultHostEndpointKey,
buildVaultHostMergeKey,
filterVaultImportKeyPassphrasesAgainstExisting,
mergeVaultImportIssues,
resolveVaultImportKeyPassphraseConflicts,
toVaultImportExistingHostRef,
} = await import("../../domain/vaultImport");
let result = await importVaultHostsInWorker({
format,
files,
+4 -1
View File
@@ -1,6 +1,7 @@
import { Search } from 'lucide-react';
import React, { useMemo, useState, useEffect, useCallback } from 'react';
import { useI18n } from '../application/i18n/I18nProvider';
import { usePinyinMatcherVersion } from '../application/state/usePinyinMatcherVersion';
import { matchesWorkspaceHostPickerQuery } from '../domain/searchMatcher';
import { Host } from '../types';
import { DistroAvatar } from './DistroAvatar';
@@ -29,12 +30,14 @@ export const CreateWorkspaceDialog: React.FC<CreateWorkspaceDialogProps> = ({
const [name, setName] = useState('');
const [search, setSearch] = useState('');
const [selectedHostIds, setSelectedHostIds] = useState<Set<string>>(new Set());
const pinyinMatcherVersion = usePinyinMatcherVersion();
const filteredHosts = useMemo(() => {
void pinyinMatcherVersion;
const term = search.trim();
if (!term) return hosts;
return hosts.filter((host) => matchesWorkspaceHostPickerQuery(term, host));
}, [hosts, search]);
}, [hosts, search, pinyinMatcherVersion]);
const toggleHost = useCallback((hostId: string) => {
setSelectedHostIds(prev => {
+15 -7
View File
@@ -24,6 +24,7 @@ import {
isVncProtocol,
} from "../domain/remoteDesktop";
import { matchesSearchQuery } from "../domain/searchMatcher";
import { usePinyinMatcherVersion } from "../application/state/usePinyinMatcherVersion";
import { getProtocolBadgeClass } from "./protocolVisuals";
import { buildQuickSwitcherShells, useDiscoveredShells, getShellIconPath, isMonochromeShellIcon } from "../lib/useDiscoveredShells";
import { usePluginContributions } from "../application/state/usePluginContributions";
@@ -214,7 +215,9 @@ const QuickSwitcherInner: React.FC<QuickSwitcherProps> = ({
)
), [discoveredShells, terminalSettings?.localShell, terminalSettings?.localShellArgs]);
const pinyinMatcherVersion = usePinyinMatcherVersion();
const filteredShells = useMemo(() => {
void pinyinMatcherVersion;
const list = !query.trim()
? quickSwitcherShells
: quickSwitcherShells.filter(
@@ -222,7 +225,7 @@ const QuickSwitcherInner: React.FC<QuickSwitcherProps> = ({
);
// Default shell first
return [...list].sort((a, b) => (a.isDefault === b.isDefault ? 0 : a.isDefault ? -1 : 1));
}, [quickSwitcherShells, query]);
}, [quickSwitcherShells, query, pinyinMatcherVersion]);
// Get hotkey display strings
const getHotkeyLabel = useCallback((actionId: string) => {
@@ -302,6 +305,7 @@ const QuickSwitcherInner: React.FC<QuickSwitcherProps> = ({
return matched;
}, [showSftpTab, trimmedQuery]);
const filteredOrphanSessions = useMemo(() => {
void pinyinMatcherVersion;
if (!trimmedQuery) return orphanSessions;
return orphanSessions.filter((session) =>
matchesSearchQuery(
@@ -311,18 +315,22 @@ const QuickSwitcherInner: React.FC<QuickSwitcherProps> = ({
session.id,
),
);
}, [orphanSessions, trimmedQuery]);
}, [orphanSessions, trimmedQuery, pinyinMatcherVersion]);
const filteredWorkspaces = useMemo(() => {
void pinyinMatcherVersion;
if (!trimmedQuery) return workspaces;
return workspaces.filter((workspace) =>
matchesSearchQuery(trimmedQuery, workspace.title, workspace.id),
);
}, [trimmedQuery, workspaces]);
}, [trimmedQuery, workspaces, pinyinMatcherVersion]);
const shouldShowLocalTerminalFallback = filteredShells.length === 0 && !!onCreateLocalTerminal && !trimmedQuery;
const pluginPaletteItems = useMemo(() => buildPluginPaletteItems(
pluginContributions.snapshot.plugins,
trimmedQuery,
), [pluginContributions.snapshot.plugins, trimmedQuery]);
const pluginPaletteItems = useMemo(() => {
void pinyinMatcherVersion;
return buildPluginPaletteItems(
pluginContributions.snapshot.plugins,
trimmedQuery,
);
}, [pluginContributions.snapshot.plugins, trimmedQuery, pinyinMatcherVersion]);
const paneMagnificationAction = useMemo(
() => buildPaneMagnificationPaletteAction(paneMagnificationState, t),
[paneMagnificationState, t],
+23 -18
View File
@@ -9,10 +9,11 @@ import {
Search,
Square,
} from 'lucide-react';
import React, { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react';
import React, { Suspense, lazy, useCallback, useEffect, useId, useMemo, useRef, useState } from 'react';
import { cn } from '../lib/utils';
import { matchesHostSearchQuery, matchesSearchQuery } from '../domain/searchMatcher';
import { useI18n } from '../application/i18n/I18nProvider';
import { usePinyinMatcherVersion } from '../application/state/usePinyinMatcherVersion';
import {
collectSelectableHostIdsInGroup,
getGroupSelectionState,
@@ -21,7 +22,7 @@ import {
import { Host, ProxyProfile, SSHKey } from '../types';
import { ManagedSource } from '../domain/models';
import { DistroAvatar } from './DistroAvatar';
import HostDetailsPanel from './HostDetailsPanel';
const HostDetailsPanel = lazy(() => import('./HostDetailsPanel'));
import { Button } from './ui/button';
import { Input } from './ui/input';
import { SortDropdown, SortMode } from './ui/sort-dropdown';
@@ -186,7 +187,9 @@ export const SelectHostPanelContent: React.FC<SelectHostPanelContentProps> = ({
return groups;
}, [allGroupPaths, currentPath, groupHostCounts]);
const pinyinMatcherVersion = usePinyinMatcherVersion();
const filteredHosts = useMemo(() => {
void pinyinMatcherVersion;
let result = selectableHosts;
if (currentPath) {
@@ -227,7 +230,7 @@ export const SelectHostPanelContent: React.FC<SelectHostPanelContentProps> = ({
});
return result;
}, [selectableHosts, currentPath, searchQuery, selectedTags, sortMode]);
}, [selectableHosts, currentPath, searchQuery, selectedTags, sortMode, pinyinMatcherVersion]);
const breadcrumbs = useMemo(() => {
if (!currentPath) return [];
@@ -655,21 +658,23 @@ export const SelectHostPanelContent: React.FC<SelectHostPanelContentProps> = ({
</div>
{showNewHostPanel && onSaveHost ? (
<HostDetailsPanel
initialData={null}
availableKeys={availableKeys}
identities={identities}
proxyProfiles={proxyProfiles}
groups={customGroups}
managedSources={managedSources}
allHosts={hosts}
onSave={(host) => {
onSaveHost(host);
setShowNewHostPanel(false);
}}
onCancel={() => setShowNewHostPanel(false)}
onCreateGroup={onCreateGroup}
/>
<Suspense fallback={null}>
<HostDetailsPanel
initialData={null}
availableKeys={availableKeys}
identities={identities}
proxyProfiles={proxyProfiles}
groups={customGroups}
managedSources={managedSources}
allHosts={hosts}
onSave={(host) => {
onSaveHost(host);
setShowNewHostPanel(false);
}}
onCancel={() => setShowNewHostPanel(false)}
onCreateGroup={onCreateGroup}
/>
</Suspense>
) : null}
</div>
</TooltipProvider>
+12 -8
View File
@@ -61,7 +61,6 @@ import type {
VaultGroupMutationState,
} from "../domain/vaultGroupMutation";
import type { PluginImporterCommitRequest } from "../application/state/usePluginImporterCommit";
import { buildVaultCsvCredentialOptions } from "../application/vaultCsvExportCredentials";
import { sanitizeCredentialValue } from "../domain/credentials";
import {
resolveGroupDefaults,
@@ -81,7 +80,6 @@ import {
buildHostForProtocolOverride,
shouldPromptHostProtocolOnConnect,
} from "../domain/remoteDesktop";
import { exportHostsToCsvWithStats } from "../domain/vaultImport";
import { saveWorkSurfaceHostDraft, type WorkSurfaceHostEditorTarget } from "../application/state/useWorkSurfaceHostEditor";
import { upsertKnownHost } from "../domain/knownHosts";
import {
@@ -117,19 +115,13 @@ import {
import { AppLogo } from "./AppLogo";
import { connectHostsStaggered } from "./connectHostsStaggered";
import { DistroAvatar } from "./DistroAvatar";
import GroupDetailsPanel from "./GroupDetailsPanel";
import { getVaultHostGridColumnCount } from "./vault/vaultHostGridLayout";
import HostDetailsPanel from "./HostDetailsPanel";
import { HostTreeView } from "./HostTreeView";
import QuickConnectWizard from "./QuickConnectWizard";
import {
isQuickConnectInput,
parseQuickConnectInputWithWarnings,
} from "../domain/quickConnect";
import SerialConnectModal from "./SerialConnectModal";
import SerialHostDetailsPanel from "./SerialHostDetailsPanel";
import { LazyNotesManager as NotesManager } from "./notes/LazyNotesManager";
import { ImportVaultDialog } from "./vault/ImportVaultDialog";
import { HostTreeGroupDeleteDialog } from "./host/HostTreeGroupDeleteDialog";
import { useHostTreeInlineGroupActions } from "./vault/useHostTreeInlineGroupActions";
import { useHostTreeInlineHostActions } from "./vault/useHostTreeInlineHostActions";
@@ -170,6 +162,14 @@ import { useVaultImportHandlers } from "../application/state/useVaultImportHandl
import { useVaultGroupDragHandlers } from "./vault/useVaultGroupDragHandlers";
import { usePluginVaultPages } from "../application/state/usePluginVaultPages";
const GroupDetailsPanel = lazy(() => import("./GroupDetailsPanel"));
const HostDetailsPanel = lazy(() => import("./HostDetailsPanel"));
const QuickConnectWizard = lazy(() => import("./QuickConnectWizard"));
const SerialConnectModal = lazy(() => import("./SerialConnectModal"));
const SerialHostDetailsPanel = lazy(() => import("./SerialHostDetailsPanel"));
const ImportVaultDialog = lazy(() =>
import("./vault/ImportVaultDialog").then((mod) => ({ default: mod.ImportVaultDialog })),
);
const LazyProtocolSelectDialog = lazy(() => import("./ProtocolSelectDialog"));
const LazyConnectionLogsManager = lazy(() => import("./ConnectionLogsManager"));
const KeychainManager = lazy(() => import("./KeychainManager"));
@@ -839,6 +839,10 @@ const VaultViewInner: React.FC<VaultViewProps> = ({
return;
}
const [{ buildVaultCsvCredentialOptions }, { exportHostsToCsvWithStats }] = await Promise.all([
import("../application/vaultCsvExportCredentials"),
import("../domain/vaultImport"),
]);
const {
keyPathsById,
keyPassphrasesById,
+20 -16
View File
@@ -4,8 +4,10 @@
* even when the Catty AI side panel has never been opened.
*/
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { ToolCall } from '../ai-elements/tool-call';
import React, { Suspense, lazy, useCallback, useEffect, useRef, useState } from 'react';
const ToolCall = lazy(() =>
import('../ai-elements/tool-call').then((mod) => ({ default: mod.ToolCall })),
);
import { Button } from '../ui/button';
import {
onApprovalCleared,
@@ -153,20 +155,22 @@ export const ExternalMcpApprovalsHost: React.FC = () => {
<div className="space-y-2">
{entries.map(([id, req]) => (
<div key={id} className="space-y-1.5">
<ToolCall
name={externalMcpApprovalToolLabel(req.toolName)}
args={req.args}
approvalTarget={req.target}
isLoading={false}
isInterrupted={false}
approvalStatus="pending"
approvalId={id}
onApproveOnce={() => handleApproveOnce(id)}
onAlwaysAllow={req.target && !req.target.hostId ? undefined : () => handleAlwaysAllow(id, req)}
onReject={() => handleReject(id)}
alwaysAllowLabel={req.target?.hostId ? t('ai.externalMcp.allowCommandOnHost') : undefined}
alwaysAllowTitle={req.target?.hostId ? t('ai.externalMcp.allowCommandOnHostHint') : undefined}
/>
<Suspense fallback={null}>
<ToolCall
name={externalMcpApprovalToolLabel(req.toolName)}
args={req.args}
approvalTarget={req.target}
isLoading={false}
isInterrupted={false}
approvalStatus="pending"
approvalId={id}
onApproveOnce={() => handleApproveOnce(id)}
onAlwaysAllow={req.target && !req.target.hostId ? undefined : () => handleAlwaysAllow(id, req)}
onReject={() => handleReject(id)}
alwaysAllowLabel={req.target?.hostId ? t('ai.externalMcp.allowCommandOnHost') : undefined}
alwaysAllowTitle={req.target?.hostId ? t('ai.externalMcp.allowCommandOnHostHint') : undefined}
/>
</Suspense>
{(req.allowSession || req.target?.hostId) && (
<div className="space-y-1.5">
<div className="text-[10px] font-medium uppercase tracking-wide text-muted-foreground/60">
@@ -1,6 +1,7 @@
import { Search, X } from "lucide-react";
import React, { useCallback, useEffect, useId, useMemo, useRef, useState } from "react";
import { useI18n } from "../../application/i18n/I18nProvider";
import { usePinyinMatcherVersion } from "../../application/state/usePinyinMatcherVersion";
import { filterSettingsSearchCatalog, type SettingsSearchHit } from "../../domain/settingsSearch";
import { cn } from "../../lib/utils";
import { Input } from "../ui/input";
@@ -26,11 +27,12 @@ export function SettingsSearchControl({
const [query, setQuery] = useState("");
const [activeIndex, setActiveIndex] = useState(0);
const [restoreOpenFocus, setRestoreOpenFocus] = useState(false);
const pinyinMatcherVersion = usePinyinMatcherVersion();
const hits = useMemo(
() => filterSettingsSearchCatalog(query, t, { includePlugins, limit: 12 }),
[query, t, includePlugins],
);
const hits = useMemo(() => {
void pinyinMatcherVersion;
return filterSettingsSearchCatalog(query, t, { includePlugins, limit: 12 });
}, [query, t, includePlugins, pinyinMatcherVersion]);
const collapseSearch = useCallback((restoreFocus = false) => {
setExpanded(false);
@@ -20,7 +20,6 @@ import type { Snippet } from "../../../domain/models";
import { recordCommand, subscribeCommandHistoryCleared } from "../../../application/state/commandHistoryStore";
import { seedLocalShellHistoryFromHistfiles } from "./localShellHistorySeed";
import { shellEscape } from "./completionEngine";
import { preloadCommonSpecs } from "./figSpecLoader";
import {
listDirectoryEntries,
normalizePathTokenForLookup,
@@ -390,12 +389,9 @@ export function useTerminalAutocomplete(
*/
const typedBufferReliableRef = useRef<boolean>(true);
// Warm the cache for this session's target OS, including when it changes.
useEffect(() => {
if (settings.enabled) {
preloadCommonSpecs(hostOs);
}
}, [settings.enabled, hostOs]);
// Fig command specs are loaded on demand in completionEngine.ts via loadSpec()
// when a command is typed, avoiding ~25 MiB of permanent main-process ESM
// cache and renderer specCache overhead from eagerly importing 67 specs.
// Local Terminal: seed autocomplete history from ~/.zsh_history (etc.) once
// per stable hostId so prefix suggestions match Ghostty-style histfile recall
@@ -345,28 +345,30 @@ test('AppHostTreeLayer does not re-render closed TerminalHostTreeSidebar when sw
env.drainFrames();
});
const sidebar = document.querySelector('[data-section="terminal-host-tree-sidebar"]') as HTMLElement;
assert.ok(sidebar);
const initialBg = sidebar.style.backgroundColor;
assert.equal(document.querySelector('[data-section="terminal-host-tree-sidebar"]'), null);
// Switching s1 -> s2 while host tree is closed keeps sidebar preview theme frozen
// and avoids activeHostId churn (memo bails out).
// Switching s1 -> s2 while host tree is closed keeps sidebar unmounted
// and avoids activeHostId/theme churn.
await act(async () => {
activeTabStore.setActiveTabId('s2');
});
await act(async () => {
env.drainFrames();
});
assert.equal(sidebar.style.backgroundColor, initialBg);
assert.equal(document.querySelector('[data-section="terminal-host-tree-sidebar"]'), null);
// Opening the host tree immediately applies the live host theme (theme-b).
// Opening the host tree lazily mounts the sidebar directly with the live host theme (theme-b).
await act(async () => {
terminalHostTreeStore.setIsOpen(true);
await import('./TerminalHostTreeSidebar');
});
await act(async () => {
env.drainFrames();
});
assert.notEqual(sidebar.style.backgroundColor, initialBg);
const sidebar = document.querySelector('[data-section="terminal-host-tree-sidebar"]') as HTMLElement;
assert.ok(sidebar);
assert.notEqual(sidebar.style.backgroundColor, 'rgb(16, 16, 16)');
assert.equal(sidebar.style.backgroundColor, 'rgb(32, 32, 32)');
} finally {
await act(async () => {
root.unmount();
@@ -48,6 +48,7 @@ import { themeFingerprint } from '../../application/state/useActiveChromeTheme';
import { buildHostTreeThemeFromTerminalTheme } from '../../infrastructure/theme/terminalAppearanceTokens';
import { cn } from '../../lib/utils';
import { matchesHostSearchQuery, matchesSearchQuery } from '../../domain/searchMatcher';
import { usePinyinMatcherVersion } from '../../application/state/usePinyinMatcherVersion';
import type { GroupConfig, GroupNode, Host, TerminalTheme } from '../../types';
import { HostTreeGroupContextMenuContent, HostTreeHostContextMenuContent } from '../host/HostTreeContextMenus';
import { HostTreeGroupInlineRenameInput } from '../host/HostTreeGroupInlineRenameInput';
@@ -839,7 +840,9 @@ const TerminalHostTreeSidebarInner: React.FC<TerminalHostTreeSidebarProps> = ({
return new Set([inlineEdit.groupPath]);
}, [inlineEdit?.groupPath]);
const pinyinMatcherVersion = usePinyinMatcherVersion();
const filteredTree = useMemo(() => {
void pinyinMatcherVersion;
let tree = groupTree;
if (tagsActive) {
tree = tree
@@ -850,12 +853,13 @@ const TerminalHostTreeSidebarInner: React.FC<TerminalHostTreeSidebarProps> = ({
return tree
.map((node) => filterGroupNode(node, searchTerm, preservePaths))
.filter((node): node is GroupNode => node !== null);
}, [groupTree, preservePaths, searchActive, searchTerm, tagsActive]);
}, [groupTree, preservePaths, searchActive, searchTerm, tagsActive, pinyinMatcherVersion]);
const filteredUngrouped = useMemo(() => {
void pinyinMatcherVersion;
if (!searchActive) return ungroupedHosts;
return ungroupedHosts.filter((host) => hostMatchesSearch(host, searchTerm));
}, [searchActive, searchTerm, ungroupedHosts]);
}, [searchActive, searchTerm, ungroupedHosts, pinyinMatcherVersion]);
const flatRows = useMemo(() => {
return flattenHostGroupTree({
@@ -81,11 +81,9 @@ const LazyRemoteDesktopPane = lazy(() =>
import('../remoteDesktop/RemoteDesktopPane').then((module) => ({ default: module.RemoteDesktopPane })),
);
if (typeof requestIdleCallback === 'function') {
requestIdleCallback(() => {
void import('../AIChatSidePanel');
});
}
// AIChatSidePanel (along with vendor-ai, globalAgentRuntime, and capability
// tool specs) is loaded on demand via LazyAIChatSidePanel when the user opens
// the AI side panel, avoiding ~15-20 MiB of V8 heap on terminal-only sessions.
const AIChatSidePanelFallback = memo(function AIChatSidePanelFallback() {
return (
+191 -161
View File
@@ -19,8 +19,12 @@ import {
import { STORAGE_KEY_VAULT_HOST_PANEL_WIDTH } from "@/infrastructure/config/storageKeys.ts";
import { VaultHostListSection } from "./VaultHostListSection";
import { VAULT_HOST_GRID_MIN_CARD_WIDTH } from "./vaultHostGridLayout";
import { LocalShellHostDetailsPanel } from "../LocalShellHostDetailsPanel";
import { VaultImportProgressPanel } from "./ImportVaultDialog";
const LocalShellHostDetailsPanel = React.lazy(() =>
import("../LocalShellHostDetailsPanel").then((mod) => ({ default: mod.LocalShellHostDetailsPanel })),
);
const VaultImportProgressPanel = React.lazy(() =>
import("./ImportVaultDialog").then((mod) => ({ default: mod.VaultImportProgressPanel })),
);
import {
VaultHeaderSearch,
VaultPageHeader,
@@ -566,6 +570,12 @@ export function VaultViewLayout({ ctx }: { ctx: VaultViewLayoutContext }) {
const [isMoveHostsOpen, setIsMoveHostsOpen] = React.useState(false);
const [moveTargetGroup, setMoveTargetGroup] = React.useState("");
const [isSidebarResizing, setIsSidebarResizing] = React.useState(false);
const [hasMountedKnownHosts, setHasMountedKnownHosts] = React.useState(
currentSection === "knownhosts",
);
if (currentSection === "knownhosts" && !hasMountedKnownHosts) {
setHasMountedKnownHosts(true);
}
const keyListRef = React.useRef(keys);
keyListRef.current = keys;
const newHostActionsRef = React.useRef<HTMLDivElement>(null);
@@ -1576,14 +1586,14 @@ export function VaultViewLayout({ ctx }: { ctx: VaultViewLayoutContext }) {
</Suspense>
</LazyLoadBoundary>
)}
{/* Always render KnownHostsManager but hide with CSS to prevent unmounting */}
<div
style={{
display: currentSection === "knownhosts" ? "contents" : "none",
}}
>
{knownHostsManagerElement}
</div>
{/* Mount KnownHostsManager lazily on first visit, then keep hidden with CSS */}
{hasMountedKnownHosts ? (
<div style={{ display: currentSection === "knownhosts" ? "contents" : "none" }}>
<Suspense fallback={<VaultSectionLoading />}>
{knownHostsManagerElement}
</Suspense>
</div>
) : null}
{/* Connection Logs */}
{currentSection === "logs" && (
<LazyLoadBoundary
@@ -1605,134 +1615,142 @@ export function VaultViewLayout({ ctx }: { ctx: VaultViewLayoutContext }) {
{currentSection === "hosts" &&
isGroupPanelOpen &&
editingGroupPath && (
<GroupDetailsPanel
key={editingGroupPath}
groupPath={editingGroupPath}
config={groupConfigs.find((c) => c.path === editingGroupPath)}
availableKeys={keys}
identities={identities}
proxyProfiles={proxyProfiles}
allHosts={hosts}
groups={allGroupPaths}
terminalThemeId={terminalThemeId}
groupConfigs={groupConfigs}
terminalFontSize={terminalFontSize}
onSave={handleSaveGroupConfig}
onCancel={() => {
setIsGroupPanelOpen(false);
setEditingGroupPath(null);
}}
layout="inline"
{...vaultHostPanelResizeProps}
/>
<Suspense fallback={null}>
<GroupDetailsPanel
key={editingGroupPath}
groupPath={editingGroupPath}
config={groupConfigs.find((c) => c.path === editingGroupPath)}
availableKeys={keys}
identities={identities}
proxyProfiles={proxyProfiles}
allHosts={hosts}
groups={allGroupPaths}
terminalThemeId={terminalThemeId}
groupConfigs={groupConfigs}
terminalFontSize={terminalFontSize}
onSave={handleSaveGroupConfig}
onCancel={() => {
setIsGroupPanelOpen(false);
setEditingGroupPath(null);
}}
layout="inline"
{...vaultHostPanelResizeProps}
/>
</Suspense>
)}
{/* Host Details Panel */}
{currentSection === "hosts" &&
isHostPanelOpen &&
editingHost?.protocol !== "serial" && (
<HostDetailsPanel
key={editingHost?.id ?? `new-${newHostProtocol || "ssh"}`}
initialData={editingHost}
initialProtocol={editingHost ? undefined : newHostProtocol}
availableKeys={keys}
identities={identities}
onCreateIdentity={(identity) =>
onUpdateIdentities([...identities, identity])
}
proxyProfiles={proxyProfiles}
groups={allGroupPaths}
managedSources={managedSources}
allTags={allTags}
allHosts={hosts}
defaultGroup={
editingHost
? undefined
: newHostGroupPath || selectedGroupPath
}
terminalThemeId={terminalThemeId}
terminalFontSize={terminalFontSize}
groupDefaults={editingHostGroupDefaults}
groupConfigs={groupConfigs}
snippets={snippets}
onSnippetsChange={onUpdateSnippets}
onHostsChange={onUpdateHosts}
onImportKey={onImportOrReuseKey}
knownHosts={knownHosts}
onAddKnownHost={onAddKnownHost}
terminalSettings={terminalSettings}
onSave={(host) => {
const latestHost = hosts.find(
(entry: { id: string }) => entry.id === host.id,
);
const nextHost = preserveConcurrentHostLineTimestampUpdate({
draft: host,
openedHost: editingHost,
latestHost,
});
onUpdateHosts((prevHosts) => upsertHostById(prevHosts, nextHost));
setIsHostPanelOpen(false);
setEditingHost(null);
setNewHostGroupPath(null);
}}
onCancel={() => {
setIsHostPanelOpen(false);
setEditingHost(null);
setNewHostGroupPath(null);
}}
onCreateGroup={(groupPath) => {
onUpdateCustomGroups(
Array.from(new Set([...customGroups, groupPath])),
);
}}
layout="inline"
{...vaultHostPanelResizeProps}
/>
<Suspense fallback={null}>
<HostDetailsPanel
key={editingHost?.id ?? `new-${newHostProtocol || "ssh"}`}
initialData={editingHost}
initialProtocol={editingHost ? undefined : newHostProtocol}
availableKeys={keys}
identities={identities}
onCreateIdentity={(identity) =>
onUpdateIdentities([...identities, identity])
}
proxyProfiles={proxyProfiles}
groups={allGroupPaths}
managedSources={managedSources}
allTags={allTags}
allHosts={hosts}
defaultGroup={
editingHost
? undefined
: newHostGroupPath || selectedGroupPath
}
terminalThemeId={terminalThemeId}
terminalFontSize={terminalFontSize}
groupDefaults={editingHostGroupDefaults}
groupConfigs={groupConfigs}
snippets={snippets}
onSnippetsChange={onUpdateSnippets}
onHostsChange={onUpdateHosts}
onImportKey={onImportOrReuseKey}
knownHosts={knownHosts}
onAddKnownHost={onAddKnownHost}
terminalSettings={terminalSettings}
onSave={(host) => {
const latestHost = hosts.find(
(entry: { id: string }) => entry.id === host.id,
);
const nextHost = preserveConcurrentHostLineTimestampUpdate({
draft: host,
openedHost: editingHost,
latestHost,
});
onUpdateHosts((prevHosts) => upsertHostById(prevHosts, nextHost));
setIsHostPanelOpen(false);
setEditingHost(null);
setNewHostGroupPath(null);
}}
onCancel={() => {
setIsHostPanelOpen(false);
setEditingHost(null);
setNewHostGroupPath(null);
}}
onCreateGroup={(groupPath) => {
onUpdateCustomGroups(
Array.from(new Set([...customGroups, groupPath])),
);
}}
layout="inline"
{...vaultHostPanelResizeProps}
/>
</Suspense>
)}
{/* Serial Host Details Panel - for editing serial port hosts */}
{currentSection === "hosts" &&
isHostPanelOpen &&
editingHost?.protocol === "serial" && (
<SerialHostDetailsPanel
initialData={editingHost}
allTags={allTags}
groups={allGroupPaths}
groupDefaults={editingHostGroupDefaults}
onSave={(host) => {
onUpdateHosts(upsertHostById(hosts, host));
setIsHostPanelOpen(false);
setEditingHost(null);
setNewHostGroupPath(null);
}}
onCancel={() => {
setIsHostPanelOpen(false);
setEditingHost(null);
setNewHostGroupPath(null);
}}
layout="inline"
{...vaultHostPanelResizeProps}
/>
<Suspense fallback={null}>
<SerialHostDetailsPanel
initialData={editingHost}
allTags={allTags}
groups={allGroupPaths}
groupDefaults={editingHostGroupDefaults}
onSave={(host) => {
onUpdateHosts(upsertHostById(hosts, host));
setIsHostPanelOpen(false);
setEditingHost(null);
setNewHostGroupPath(null);
}}
onCancel={() => {
setIsHostPanelOpen(false);
setEditingHost(null);
setNewHostGroupPath(null);
}}
layout="inline"
{...vaultHostPanelResizeProps}
/>
</Suspense>
)}
{/* Local Shell Host Details Panel - for editing/saving local shell (CMD) hosts */}
{currentSection === "hosts" &&
isLocalShellHostPanelOpen && (
<LocalShellHostDetailsPanel
key={editingLocalShellHost?.id ?? "local-shell-new"}
initialData={editingLocalShellHost}
groups={allGroupPaths}
defaultGroup={
editingLocalShellHost
? undefined
: newHostGroupPath || selectedGroupPath
}
onSave={(host) => handleSaveLocalShellHost(host)}
onSaveAndConnect={(host) => handleSaveLocalShellHost(host, true)}
onCancel={handleCancelLocalShellHost}
layout="inline"
{...vaultHostPanelResizeProps}
/>
<Suspense fallback={null}>
<LocalShellHostDetailsPanel
key={editingLocalShellHost?.id ?? "local-shell-new"}
initialData={editingLocalShellHost}
groups={allGroupPaths}
defaultGroup={
editingLocalShellHost
? undefined
: newHostGroupPath || selectedGroupPath
}
onSave={(host) => handleSaveLocalShellHost(host)}
onSaveAndConnect={(host) => handleSaveLocalShellHost(host, true)}
onCancel={handleCancelLocalShellHost}
layout="inline"
{...vaultHostPanelResizeProps}
/>
</Suspense>
)}
</div>
</div>
@@ -2002,39 +2020,47 @@ export function VaultViewLayout({ ctx }: { ctx: VaultViewLayoutContext }) {
</DialogContent>
</Dialog>
<ImportVaultDialog
open={isImportOpen}
onOpenChange={setIsImportOpen}
onFileSelected={handleImportFileSelected}
onPluginPreviewCommit={handlePluginPreviewCommit}
getPluginPreviewAnalysis={getPluginPreviewAnalysis}
groups={allGroupPaths}
/>
{isImportOpen && (
<Suspense fallback={null}>
<ImportVaultDialog
open={isImportOpen}
onOpenChange={setIsImportOpen}
onFileSelected={handleImportFileSelected}
onPluginPreviewCommit={handlePluginPreviewCommit}
getPluginPreviewAnalysis={getPluginPreviewAnalysis}
groups={allGroupPaths}
/>
</Suspense>
)}
{importProgress && (
<VaultImportProgressPanel
progress={importProgress}
onCancel={cancelImport}
onClose={resetImportProgress}
t={t}
/>
<Suspense fallback={null}>
<VaultImportProgressPanel
progress={importProgress}
onCancel={cancelImport}
onClose={resetImportProgress}
t={t}
/>
</Suspense>
)}
{/* Quick Connect Wizard */}
{isQuickConnectOpen && quickConnectTarget && (
<QuickConnectWizard
open={isQuickConnectOpen}
target={quickConnectTarget}
keys={keys}
identities={identities}
onConnect={handleQuickConnect}
onSaveHost={handleQuickConnectSaveHost}
onClose={() => {
setIsQuickConnectOpen(false);
setQuickConnectTarget(null);
setQuickConnectWarnings([]);
}}
warnings={quickConnectWarnings}
/>
<Suspense fallback={null}>
<QuickConnectWizard
open={isQuickConnectOpen}
target={quickConnectTarget}
keys={keys}
identities={identities}
onConnect={handleQuickConnect}
onSaveHost={handleQuickConnectSaveHost}
onClose={() => {
setIsQuickConnectOpen(false);
setQuickConnectTarget(null);
setQuickConnectWarnings([]);
}}
warnings={quickConnectWarnings}
/>
</Suspense>
)}
{/* Protocol Select Dialog */}
@@ -2054,18 +2080,22 @@ export function VaultViewLayout({ ctx }: { ctx: VaultViewLayoutContext }) {
)}
{/* Serial Connect Modal */}
<SerialConnectModal
open={isSerialModalOpen}
onClose={() => setIsSerialModalOpen(false)}
onConnect={(config, options) => {
if (onConnectSerial) {
onConnectSerial(config, options);
}
}}
onSaveHost={(host) => {
onUpdateHosts([...hosts, host]);
}}
/>
{isSerialModalOpen && (
<Suspense fallback={null}>
<SerialConnectModal
open={isSerialModalOpen}
onClose={() => setIsSerialModalOpen(false)}
onConnect={(config, options) => {
if (onConnectSerial) {
onConnectSerial(config, options);
}
}}
onSaveHost={(host) => {
onUpdateHosts([...hosts, host]);
}}
/>
</Suspense>
)}
</div>
);
}
+15 -4
View File
@@ -1,4 +1,4 @@
import React, { useCallback, useMemo } from "react";
import React, { useCallback, useMemo, useSyncExternalStore } from "react";
import { compareHostAddresses } from "../../domain/hostAddressSort";
import { upsertKnownHost } from "../../domain/knownHosts";
@@ -9,9 +9,14 @@ import {
isVncProtocol,
} from "../../domain/remoteDesktop";
import { sortByVaultOrder, sortVaultStringsByOrder } from "../../domain/vaultOrder";
import { matchesHostSearchQuery, matchesSearchQuery } from "../../domain/searchMatcher";
import {
getPinyinMatcherVersion,
matchesHostSearchQuery,
matchesSearchQuery,
subscribePinyinMatcherReady,
} from "../../domain/searchMatcher";
import type { GroupConfig, GroupNode, Host, KnownHost } from "../../types";
import KnownHostsManager from "../KnownHostsManager";
const KnownHostsManager = React.lazy(() => import("../KnownHostsManager"));
import type { SortMode } from "../ui/sort-dropdown";
const PROTO_TOKEN_RE = /(?:^|\s)proto:([a-z0-9:_-]+)(?=\s|$)/gi;
@@ -130,11 +135,17 @@ export function useVaultHostCollections({
);
}, [groupConfigs]);
const pinyinVersion = useSyncExternalStore(
subscribePinyinMatcherReady,
getPinyinMatcherVersion,
getPinyinMatcherVersion,
);
const searchTerm = useMemo(() => search.trim(), [search]);
const selectedTagSet = useMemo(() => new Set(selectedTags), [selectedTags]);
const hasSelectedTags = selectedTags.length > 0;
const hostMatchesSearchAndTags = useCallback((host: Host): boolean => {
void pinyinVersion;
if (searchTerm && !matchesVaultHostSearch(host, searchTerm)) {
return false;
}
@@ -142,7 +153,7 @@ export function useVaultHostCollections({
return false;
}
return true;
}, [hasSelectedTags, searchTerm, selectedTagSet]);
}, [hasSelectedTags, pinyinVersion, searchTerm, selectedTagSet]);
const filteredHosts = useMemo(
() => hosts.filter(hostMatchesSearchAndTags),
@@ -6,6 +6,7 @@
*/
import { Check, Search, Terminal } from 'lucide-react';
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { usePinyinMatcherVersion } from '../../application/state/usePinyinMatcherVersion';
import { matchesWorkspaceHostPickerQuery } from '../../domain/searchMatcher';
import { Host } from '../../types';
import { DistroAvatar } from '../DistroAvatar';
@@ -112,11 +113,13 @@ export const AddToWorkspaceDialog: React.FC<AddToWorkspaceDialogProps> = ({
return 'local terminal localhost'.includes(term);
}, [query]);
const pinyinMatcherVersion = usePinyinMatcherVersion();
const filteredHosts = useMemo(() => {
void pinyinMatcherVersion;
const term = query.trim();
if (!term) return selectableHosts;
return selectableHosts.filter((host) => matchesWorkspaceHostPickerQuery(term, host));
}, [selectableHosts, query]);
}, [selectableHosts, query, pinyinMatcherVersion]);
const { items, visualRows, itemIndexToVisualIndex } = useMemo(() => {
const list: Item[] = [];
+75 -3
View File
@@ -1,4 +1,67 @@
import { pinyin } from "pinyin-pro";
type PinyinFn = (text: string, options?: { pattern?: string; toneType?: string }) => string;
const CJK_CHAR_REGEX = /[\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff]/;
let pinyinImpl: PinyinFn | null = null;
let pinyinLoadPromise: Promise<void> | null = null;
let pinyinReadyVersion = 0;
const pinyinReadyListeners = new Set<() => void>();
const shouldEagerLoadPinyin = typeof window === "undefined"
|| (typeof process !== "undefined" && Boolean(
process.env?.NODE_TEST_CONTEXT
|| process.argv?.some((arg) => arg.includes("--test")),
));
if (shouldEagerLoadPinyin && typeof process !== "undefined") {
try {
const getBuiltinModule = (process as unknown as {
getBuiltinModule?: (id: string) => { createRequire?: (filename: string) => NodeRequire };
}).getBuiltinModule;
const nodeModule = getBuiltinModule?.("node:module");
const req = nodeModule?.createRequire?.(`${process.cwd()}/package.json`);
const mod = req?.("pinyin-pro") as { pinyin?: PinyinFn } | undefined;
if (typeof mod?.pinyin === "function") {
pinyinImpl = mod.pinyin;
}
} catch {
// Fall back to async dynamic import on first CJK query.
}
}
/**
* Trigger loading the 447 KB `pinyin-pro` dictionary on demand in browser
* builds when CJK search text is encountered. Notifies subscribers once ready
* so active search views can re-run matching without blocking cold startup.
*/
export function ensurePinyinMatcherLoaded(): void {
if (pinyinImpl || pinyinLoadPromise) return;
pinyinLoadPromise = import("pinyin-pro")
.then((mod) => {
pinyinImpl = mod.pinyin as PinyinFn;
pinyinReadyVersion += 1;
for (const listener of pinyinReadyListeners) {
try {
listener();
} catch {
// ignore listener errors
}
}
})
.catch(() => {
pinyinLoadPromise = null;
});
}
export function subscribePinyinMatcherReady(listener: () => void): () => void {
pinyinReadyListeners.add(listener);
return () => {
pinyinReadyListeners.delete(listener);
};
}
export function getPinyinMatcherVersion(): number {
return pinyinReadyVersion;
}
const SEARCH_SPLIT_REGEX = /[\s\p{Pd}_/\\|.,,。;;::!!??()()[\]{}<>《》、"'`~·]+/u;
const SEARCH_REMOVE_REGEX = /[\s\p{Pd}_/\\|.,,。;;::!!??()()[\]{}<>《》、"'`~·]+/gu;
@@ -53,6 +116,10 @@ function pinyinCacheEntryChars(
}
function getPinyinVariants(sourceText: string): { full: string; initials: string } {
// Pure non-CJK strings need neither pinyin transliteration nor cache entries.
if (!CJK_CHAR_REGEX.test(sourceText)) {
return { full: "", initials: "" };
}
const cacheKey = normalizeText(sourceText);
const cached = PINYIN_CACHE.get(cacheKey);
if (cached) {
@@ -61,17 +128,22 @@ function getPinyinVariants(sourceText: string): { full: string; initials: string
return cached;
}
if (!pinyinImpl) {
ensurePinyinMatcherLoaded();
return { full: "", initials: "" };
}
let full = "";
let initials = "";
try {
full = compactText(
pinyin(sourceText, {
pinyinImpl(sourceText, {
toneType: "none",
}),
);
initials = compactText(
pinyin(sourceText, {
pinyinImpl(sourceText, {
pattern: "first",
toneType: "none",
}),
+11 -3
View File
@@ -226,7 +226,7 @@ function buildExternalAgentContextualPrompt({ mode, prompt, chatSessionId, defau
return `${systemContext}\n\n${prompt}`;
}
const { execViaPty } = require("./ai/ptyExec.cjs");
const execViaPty = (...args) => require("./ai/ptyExec.cjs").execViaPty(...args);
let externalMcpController = null;
let userDataDir = null;
@@ -1065,10 +1065,18 @@ function cleanup() {
registeredContext.sdkActiveStreams.clear();
}
try {
registeredContext?.codexAppServerRuntime?.close?.();
if (typeof registeredContext?.closeCodexAppServerRuntimeIfLoaded === "function") {
registeredContext.closeCodexAppServerRuntimeIfLoaded();
} else {
registeredContext?.codexAppServerRuntime?.close?.();
}
} catch {}
try {
registeredContext?.codebuddySessionManager?.closeAll?.();
if (typeof registeredContext?.closeCodebuddySessionsIfLoaded === "function") {
registeredContext.closeCodebuddySessionsIfLoaded();
} else {
registeredContext?.codebuddySessionManager?.closeAll?.();
}
} catch {}
for (const [id, session] of codexLoginSessions) {
@@ -7,7 +7,8 @@ const { formatSyntheticEcho, getVisibleIdlePrompt } = require("../ai/shellUtils.
const { classifyShellReadiness } = require("../ai/shellReadinessState.cjs");
const { clearSessionFlowState } = require("../terminalFlowAck.cjs");
const { remoteDisallowsExecChannelProbe, sessionDisallowsExtraSshChannel, ensureSessionShellKindForExec } = require("../ai/sessionShellKind.cjs");
const defaultAiPrivacyService = require("../../shared/aiPrivacyService.cjs");
let _defaultAiPrivacyService = null;
const getDefaultAiPrivacyService = () => (_defaultAiPrivacyService ??= require("../../shared/aiPrivacyService.cjs"));
function assertCattyPrivacySession(privacyService, chatSessionId) {
if (chatSessionId) {
@@ -86,7 +87,13 @@ async function proxyCattyExecToWorker({
}
function registerCattyExecHandlers(ctx) {
const privacyService = ctx.aiPrivacyService || defaultAiPrivacyService;
const privacyService = ctx.aiPrivacyService || {
isEnabled: () => getDefaultAiPrivacyService().isEnabled(),
restore: (...args) => getDefaultAiPrivacyService().restore(...args),
redact: (...args) => getDefaultAiPrivacyService().redact(...args),
checkSession: (...args) => getDefaultAiPrivacyService().checkSession(...args),
createPolicyGuard: (...args) => getDefaultAiPrivacyService().createPolicyGuard(...args),
};
with (ctx) {
ipcMain.handle("netcatty:ai:exec", async (event, { sessionId, command, chatSessionId, delegationTag }) => {
// Validate IPC sender (Issue #17)
+12 -5
View File
@@ -1,12 +1,19 @@
"use strict";
const privacyService = require("../../shared/aiPrivacyService.cjs");
let _defaultPrivacyService = null;
function getDefaultPrivacyService() {
if (!_defaultPrivacyService) {
_defaultPrivacyService = require("../../shared/aiPrivacyService.cjs");
}
return _defaultPrivacyService;
}
function registerPrivacyHandlers({ ipcMain, validateSender, aiPrivacyService = privacyService }) {
function registerPrivacyHandlers({ ipcMain, validateSender, aiPrivacyService }) {
const resolveService = () => aiPrivacyService || getDefaultPrivacyService();
ipcMain.handle("netcatty:ai:privacy:status", (event) => {
if (!validateSender(event)) return { ok: false, error: "Unauthorized" };
try {
return { ok: true, enabled: aiPrivacyService.isEnabled() };
return { ok: true, enabled: resolveService().isEnabled() };
} catch (error) {
return { ok: false, error: error.message };
}
@@ -19,7 +26,7 @@ function registerPrivacyHandlers({ ipcMain, validateSender, aiPrivacyService = p
}
return {
ok: true,
value: aiPrivacyService[request.operation](request.chatSessionId, request.value),
value: resolveService()[request.operation](request.chatSessionId, request.value),
};
} catch (error) {
return { ok: false, error: error.message };
@@ -27,7 +34,7 @@ function registerPrivacyHandlers({ ipcMain, validateSender, aiPrivacyService = p
});
ipcMain.handle("netcatty:ai:privacy:clear", (event, chatSessionId) => {
if (!validateSender(event)) return { ok: false, error: "Unauthorized" };
aiPrivacyService.clearSession(chatSessionId);
resolveService().clearSession(chatSessionId);
return { ok: true };
});
}
+32 -24
View File
@@ -9,17 +9,17 @@
* { prompt, attachments, cwd, model, env, binPath, injectedMcpServers, emitter,
* signal, resumeSessionId, apiKey, baseUrl }
*/
const claude = require("./claudeDriver.cjs");
const codex = require("./codexDriver.cjs");
const copilot = require("./copilotDriver.cjs");
const cursor = require("./cursorDriver.cjs");
const cursorCli = require("./cursorCliDriver.cjs");
const codebuddy = require("./codebuddyDriver.cjs");
const opencode = require("./opencodeDriver.cjs");
const grok = require("./grokDriver.cjs");
const grokAcp = require("./grokAcpDriver.cjs");
const mimo = require("./mimoDriver.cjs");
const { codebuddySessionManager } = require("./codebuddySessionManager.cjs");
const getClaude = () => require("./claudeDriver.cjs");
const getCodex = () => require("./codexDriver.cjs");
const getCopilot = () => require("./copilotDriver.cjs");
const getCursor = () => require("./cursorDriver.cjs");
const getCursorCli = () => require("./cursorCliDriver.cjs");
const getCodebuddy = () => require("./codebuddyDriver.cjs");
const getOpencode = () => require("./opencodeDriver.cjs");
const getGrok = () => require("./grokDriver.cjs");
const getGrokAcp = () => require("./grokAcpDriver.cjs");
const getMimo = () => require("./mimoDriver.cjs");
const getCodebuddySessionManager = () => require("./codebuddySessionManager.cjs").codebuddySessionManager;
function hasCodebuddyQueryOnlyOptions(options) {
return Boolean(
@@ -34,6 +34,7 @@ function hasCodebuddyQueryOnlyOptions(options) {
const DRIVER_REGISTRY = {
claude: {
async runTurn(ctx) {
const claude = getClaude();
const options = claude.buildClaudeQueryOptions({
cwd: ctx.cwd,
model: ctx.model,
@@ -50,7 +51,7 @@ const DRIVER_REGISTRY = {
assertSessionValid: ctx.assertSessionValid, delegatedAgent: ctx.delegatedAgent === true });
},
async listModels(ctx) {
return claude.listClaudeModels({
return getClaude().listClaudeModels({
pathToClaudeCodeExecutable: ctx.binPath,
env: ctx.env,
abortController: ctx.abortController,
@@ -60,6 +61,7 @@ const DRIVER_REGISTRY = {
},
codex: {
async runTurn(ctx) {
const codex = getCodex();
const constructorOptions = codex.buildCodexConstructorOptions({
codexPath: ctx.binPath,
env: ctx.env,
@@ -86,6 +88,7 @@ const DRIVER_REGISTRY = {
},
copilot: {
async runTurn(ctx) {
const copilot = getCopilot();
const clientOptions = copilot.buildCopilotClientOptions({ cliPath: ctx.binPath });
const sessionOptions = copilot.buildCopilotSessionOptions({
model: ctx.model,
@@ -106,7 +109,7 @@ const DRIVER_REGISTRY = {
});
},
async listModels(ctx) {
return copilot.listCopilotModels({
return getCopilot().listCopilotModels({
cliPath: ctx.binPath,
runtimeEnv: ctx.env,
abortController: ctx.abortController,
@@ -118,7 +121,7 @@ const DRIVER_REGISTRY = {
async runTurn(ctx) {
const authMode = ctx.cursorAuthMode === "cli-login" ? "cli-login" : "api-key";
if (authMode === "cli-login") {
return cursorCli.runCursorCliTurn({
return getCursorCli().runCursorCliTurn({
prompt: ctx.prompt,
assertSessionValid: ctx.assertSessionValid,
binPath: ctx.cursorCliBinPath || ctx.binPath,
@@ -134,6 +137,7 @@ const DRIVER_REGISTRY = {
signal: ctx.signal,
});
}
const cursor = getCursor();
const agentOptions = cursor.buildCursorAgentOptions({
apiKey: ctx.apiKey,
env: ctx.env,
@@ -154,14 +158,14 @@ const DRIVER_REGISTRY = {
},
async listModels(ctx) {
if (ctx.cursorAuthMode === "cli-login") {
return cursorCli.listCursorCliModels({
return getCursorCli().listCursorCliModels({
binPath: ctx.cursorCliBinPath || ctx.binPath,
env: ctx.env,
abortController: ctx.abortController,
signal: ctx.signal,
});
}
return cursor.listCursorModels({
return getCursor().listCursorModels({
env: ctx.env,
abortController: ctx.abortController,
signal: ctx.signal,
@@ -170,6 +174,8 @@ const DRIVER_REGISTRY = {
},
codebuddy: {
async runTurn(ctx) {
const codebuddy = getCodebuddy();
const codebuddySessionManager = getCodebuddySessionManager();
// Build the permission handler: when the CLI hits a security restriction,
// auto-confirm (auto mode) or prompt the user (confirm mode) instead of
// throwing an error.
@@ -287,7 +293,7 @@ const DRIVER_REGISTRY = {
String(ctx.binPath || ""),
"sdk",
].join("\u0000");
return codebuddySessionManager.steer({
return getCodebuddySessionManager().steer({
sessionKey,
prompt: ctx.prompt,
assertSessionValid: ctx.assertSessionValid,
@@ -295,7 +301,7 @@ const DRIVER_REGISTRY = {
});
},
async listModels(ctx) {
return codebuddy.listCodebuddyModels({
return getCodebuddy().listCodebuddyModels({
pathToCodebuddyCode: ctx.binPath,
env: ctx.env,
abortController: ctx.abortController,
@@ -305,7 +311,7 @@ const DRIVER_REGISTRY = {
},
opencode: {
async runTurn(ctx) {
return opencode.runOpenCodeTurn({
return getOpencode().runOpenCodeTurn({
prompt: ctx.prompt,
assertSessionValid: ctx.assertSessionValid,
systemPrompt: ctx.systemPrompt,
@@ -323,7 +329,7 @@ const DRIVER_REGISTRY = {
});
},
async listModels(ctx) {
return opencode.listOpenCodeModels({
return getOpencode().listOpenCodeModels({
env: ctx.env,
binPath: ctx.binPath,
abortController: ctx.abortController,
@@ -345,7 +351,7 @@ const DRIVER_REGISTRY = {
// Headless cannot know if -r restored history before the prompt is sent.
// Prefer native -r without seed (common success path). Stale-id fallback
// is handled on ACP (default runtime) via historySeed + session/new.
return grok.runGrokTurn({
return getGrok().runGrokTurn({
prompt: ctx.prompt,
assertSessionValid: ctx.assertSessionValid,
binPath: ctx.binPath,
@@ -360,7 +366,7 @@ const DRIVER_REGISTRY = {
signal: ctx.signal || ctx.abortController?.signal,
});
}
return grokAcp.runGrokAcpTurn({
return getGrokAcp().runGrokAcpTurn({
prompt: ctx.prompt,
assertSessionValid: ctx.assertSessionValid,
systemPrompt: ctx.systemPrompt,
@@ -378,6 +384,8 @@ const DRIVER_REGISTRY = {
});
},
async listModels(ctx) {
const grok = getGrok();
const grokAcp = getGrokAcp();
// Run both probes together and union the results. ACP's
// `_meta.modelState` reflects the negotiated agent session and can
// advertise a subset of the account's models (observed: only
@@ -441,7 +449,7 @@ const DRIVER_REGISTRY = {
// mimoDriver.cjs for the details.
mimo: {
async runTurn(ctx) {
return mimo.runMimoTurn({
return getMimo().runMimoTurn({
prompt: ctx.prompt,
assertSessionValid: ctx.assertSessionValid,
systemPrompt: ctx.systemPrompt,
@@ -463,7 +471,7 @@ const DRIVER_REGISTRY = {
});
},
async listModels(ctx) {
return mimo.listMimoModels({
return getMimo().listMimoModels({
env: ctx.env,
binPath: ctx.binPath,
cwd: ctx.cwd,
@@ -2,18 +2,11 @@
const { getDriver, listBackends } = require("./index.cjs");
const { buildSdkAgentEnv } = require("./env.cjs");
const { buildInjectedMcpServers } = require("./injectMcp.cjs");
const { createStreamEmitter } = require("./emit.cjs");
const { buildNetcattySkillsOpenCodePathAllowlist } = require("./netcattySkillsOpenCodePermissions.cjs");
const { getToolCliStateDir } = require("../../../cli/discoveryPath.cjs");
const tempDirBridge = require("../../tempDirBridge.cjs");
const { realpathSync } = require("node:fs");
const { createHash } = require("node:crypto");
const { CodexAppServerRuntime } = require("../codexAppServer/runtime.cjs");
const { probeCodexAppServer } = require("../codexAppServer/probe.cjs");
const { codebuddySessionManager } = require("./codebuddySessionManager.cjs");
const codebuddyDriver = require("./codebuddyDriver.cjs");
const { OPENCODE_SERVER_START_TIMEOUT_MS } = require("./opencodeDriver.cjs");
const {
buildLastKnownCatalogPath,
readLastKnownCatalogAlias,
@@ -24,6 +17,21 @@ const {
writeLastKnownCatalogEntry,
} = require("./modelCatalogLastKnown.cjs");
const buildInjectedMcpServers = (...args) => require("./injectMcp.cjs").buildInjectedMcpServers(...args);
const buildNetcattySkillsOpenCodePathAllowlist = (...args) =>
require("./netcattySkillsOpenCodePermissions.cjs").buildNetcattySkillsOpenCodePathAllowlist(...args);
const probeCodexAppServer = (...args) => require("../codexAppServer/probe.cjs").probeCodexAppServer(...args);
const getCodebuddyDriver = () => require("./codebuddyDriver.cjs");
const getCodebuddySessionManager = () => require("./codebuddySessionManager.cjs").codebuddySessionManager;
function getCodebuddySessionManagerIfLoaded() {
try {
const resolved = require.resolve("./codebuddySessionManager.cjs");
return require.cache[resolved]?.exports?.codebuddySessionManager || null;
} catch {
return null;
}
}
const VALID_BACKENDS = new Set(listBackends());
// Pre-flight model catalog cache. SDK listModels often spawns a CLI/server
@@ -727,7 +735,13 @@ function redactSdkAnswerContent(privacyService, chatSessionId, value) {
}
function registerSdkStreamHandlers(ctx) {
const privacyService = ctx.aiPrivacyService || require("../../../shared/aiPrivacyService.cjs");
let _privacyService = ctx.aiPrivacyService || null;
const getPrivacyService = () => (_privacyService ??= require("../../../shared/aiPrivacyService.cjs"));
const privacyService = {
checkSession: (...args) => getPrivacyService().checkSession(...args),
redact: (...args) => getPrivacyService().redact(...args),
restore: (...args) => getPrivacyService().restore(...args),
};
const injectCliEnv = typeof ctx.withCliDiscoveryEnv === "function"
? ctx.withCliDiscoveryEnv
: (env) => env;
@@ -741,44 +755,51 @@ function registerSdkStreamHandlers(ctx) {
// Only native IDs observed in this process under the current chat mapping
// are eligible for a protected resume.
const sdkPrivateSessionIds = new Map();
const codexAppServerRuntime = new CodexAppServerRuntime({
appVersion: electronModule?.app?.getVersion?.() || "0.0.0",
transformUserInputAnswers(answers, context) {
privacyService.checkSession(context.chatSessionId);
return redactSdkAnswerContent(privacyService, context.chatSessionId, answers);
},
sendInteractionRequest(payload, context) {
const sender = context?.sender;
if (!sender || sender.isDestroyed?.()) return false;
// Native approval arguments must remain exact: accepting them cannot
// replace the command/path that Codex will actually execute.
const displayed = { ...payload };
if (privacyService.checkSession(context.chatSessionId)) {
const restore = (value) => privacyService.restore(context.chatSessionId, value);
if (Array.isArray(displayed.questions)) {
displayed.questions = displayed.questions.map((question) => ({
...question,
...(typeof question.question === "string" ? { question: restore(question.question) } : {}),
...(typeof question.header === "string" ? { header: restore(question.header) } : {}),
...(Array.isArray(question.options) ? {
options: question.options.map((option) => ({
...option,
...(typeof option.label === "string" ? { label: restore(option.label) } : {}),
...(typeof option.description === "string" ? { description: restore(option.description) } : {}),
})),
} : {}),
}));
}
}
safeSend(sender, "netcatty:ai:codex-app-server:interaction-request", displayed);
return true;
},
sendInteractionCleared(payload, context) {
const sender = context?.sender;
if (!sender || sender.isDestroyed?.()) return;
safeSend(sender, "netcatty:ai:codex-app-server:interaction-cleared", payload);
},
});
let _codexAppServerRuntime = null;
const getCodexAppServerRuntime = () => {
if (!_codexAppServerRuntime) {
const { CodexAppServerRuntime } = require("../codexAppServer/runtime.cjs");
_codexAppServerRuntime = new CodexAppServerRuntime({
appVersion: electronModule?.app?.getVersion?.() || "0.0.0",
transformUserInputAnswers(answers, context) {
privacyService.checkSession(context.chatSessionId);
return redactSdkAnswerContent(privacyService, context.chatSessionId, answers);
},
sendInteractionRequest(payload, context) {
const sender = context?.sender;
if (!sender || sender.isDestroyed?.()) return false;
// Native approval arguments must remain exact: accepting them cannot
// replace the command/path that Codex will actually execute.
const displayed = { ...payload };
if (privacyService.checkSession(context.chatSessionId)) {
const restore = (value) => privacyService.restore(context.chatSessionId, value);
if (Array.isArray(displayed.questions)) {
displayed.questions = displayed.questions.map((question) => ({
...question,
...(typeof question.question === "string" ? { question: restore(question.question) } : {}),
...(typeof question.header === "string" ? { header: restore(question.header) } : {}),
...(Array.isArray(question.options) ? {
options: question.options.map((option) => ({
...option,
...(typeof option.label === "string" ? { label: restore(option.label) } : {}),
...(typeof option.description === "string" ? { description: restore(option.description) } : {}),
})),
} : {}),
}));
}
}
safeSend(sender, "netcatty:ai:codex-app-server:interaction-request", displayed);
return true;
},
sendInteractionCleared(payload, context) {
const sender = context?.sender;
if (!sender || sender.isDestroyed?.()) return;
safeSend(sender, "netcatty:ai:codex-app-server:interaction-cleared", payload);
},
});
}
return _codexAppServerRuntime;
};
ipcMain.handle(
"netcatty:ai:sdk-agent:stream",
@@ -1149,7 +1170,7 @@ function registerSdkStreamHandlers(ctx) {
persistSession: persistSession != null ? persistSession : undefined,
};
const result = codexRuntime === "app-server"
? await codexAppServerRuntime.runTurn(commonTurnContext)
? await getCodexAppServerRuntime().runTurn(commonTurnContext)
: await driver.runTurn(commonTurnContext);
// Persist any new session id for resume on the next turn.
@@ -1549,7 +1570,7 @@ function registerSdkStreamHandlers(ctx) {
// win over both the shared default and OpenCode's budget.
const catalogBudgetMs = MODEL_LIST_TIMEOUT_OVERRIDES_MS[backendKey]
?? (backendKey === "opencode"
? OPENCODE_SERVER_START_TIMEOUT_MS + MODEL_LIST_TIMEOUT_MS
? require("./opencodeDriver.cjs").OPENCODE_SERVER_START_TIMEOUT_MS + MODEL_LIST_TIMEOUT_MS
: MODEL_LIST_TIMEOUT_MS);
const raw = await withTimeout(
fetchSdkModelCatalog({
@@ -1562,7 +1583,7 @@ function registerSdkStreamHandlers(ctx) {
catalogDeadlineTs: Date.now() + catalogBudgetMs - MODEL_LIST_DEADLINE_HEADROOM_MS,
cursorAuthMode: backendKey === "cursor" ? cursorAuthMode : undefined,
cursorCliBinPath: backendKey === "cursor" ? cursorCliBinPath : undefined,
codexAppServerRuntime,
codexAppServerRuntime: backendKey === "codex" ? getCodexAppServerRuntime() : null,
}),
catalogBudgetMs,
abortController,
@@ -1754,7 +1775,7 @@ function registerSdkStreamHandlers(ctx) {
} catch (error) {
return { status: "failed", message: error.message };
}
const result = await codexAppServerRuntime.steerTurn(requestId, {
const result = await getCodexAppServerRuntime().steerTurn(requestId, {
chatSessionId,
prompt: protectedSteerPrompt,
attachments: stagedAttachments,
@@ -1785,7 +1806,7 @@ function registerSdkStreamHandlers(ctx) {
mcpServerBridge.cancelWorkerBackgroundJobsForSession?.(effectiveChatSessionId);
mcpServerBridge.clearPendingApprovals(effectiveChatSessionId);
void mcpServerBridge.cancelSftpOpsForSession?.(effectiveChatSessionId);
await codexAppServerRuntime.cancelTurn(requestId);
await _codexAppServerRuntime?.cancelTurn(requestId);
const controller = sdkActiveStreams.get(requestId);
if (controller) {
controller.abort();
@@ -1820,8 +1841,8 @@ function registerSdkStreamHandlers(ctx) {
// Keep privacy mappings and native-history provenance until explicit chat
// deletion clears the shared privacy service. Its tombstone then prevents
// any stale native ID from being reused.
codebuddySessionManager.closeForChat(chatSessionId);
await codexAppServerRuntime.cleanupChatSession(chatSessionId);
getCodebuddySessionManagerIfLoaded()?.closeForChat(chatSessionId);
await _codexAppServerRuntime?.cleanupChatSession(chatSessionId);
await mcpServerBridge.cleanupScopedMetadata(chatSessionId);
return { ok: true };
});
@@ -1829,7 +1850,7 @@ function registerSdkStreamHandlers(ctx) {
ipcMain.handle("netcatty:ai:codex-app-server:interaction-response", async (event, payload) => {
if (!validateSender(event)) return { ok: false, error: "Unauthorized IPC sender" };
try {
const ok = codexAppServerRuntime.respondInteraction(payload?.interactionId, payload, event.sender);
const ok = _codexAppServerRuntime?.respondInteraction(payload?.interactionId, payload, event.sender) === true;
return ok ? { ok: true } : { ok: false, error: "Interaction not found" };
} catch (error) {
return { ok: false, error: error.message };
@@ -1838,7 +1859,7 @@ function registerSdkStreamHandlers(ctx) {
ipcMain.handle("netcatty:ai:codex-app-server:interaction-cancel-timeout", async (event, payload) => {
if (!validateSender(event)) return { ok: false, error: "Unauthorized IPC sender" };
const cancelled = codexAppServerRuntime.cancelInteractionTimeout(
const cancelled = _codexAppServerRuntime?.cancelInteractionTimeout(
payload?.interactionId,
event.sender,
) === true;
@@ -1894,7 +1915,7 @@ function registerSdkStreamHandlers(ctx) {
resolveCliFromPath, normalizeCliPathForPlatform, resolveSdkBinPath,
resolveClaudeCodeExecutableForSdk, resolveCodexExecutableForSdk, resolveCodebuddyExecutableForSdk,
});
const status = await codebuddyDriver.getCodebuddyMcpStatus({ pathToCodebuddyCode: binPath, env });
const status = await getCodebuddyDriver().getCodebuddyMcpStatus({ pathToCodebuddyCode: binPath, env });
return { ok: true, servers: status };
} catch (err) {
return { ok: false, error: err?.message || String(err) };
@@ -1918,7 +1939,7 @@ function registerSdkStreamHandlers(ctx) {
resolveCliFromPath, normalizeCliPathForPlatform, resolveSdkBinPath,
resolveClaudeCodeExecutableForSdk, resolveCodexExecutableForSdk, resolveCodebuddyExecutableForSdk,
});
const info = await codebuddyDriver.getCodebuddyAccountInfo({ pathToCodebuddyCode: binPath, env });
const info = await getCodebuddyDriver().getCodebuddyAccountInfo({ pathToCodebuddyCode: binPath, env });
return { ok: true, account: info };
} catch (err) {
return { ok: false, error: err?.message || String(err) };
@@ -1929,7 +1950,8 @@ function registerSdkStreamHandlers(ctx) {
if (!validateSender(event)) return { ok: false, error: "Unauthorized IPC sender" };
const { elicitationId, action, content } = payload || {};
if (!elicitationId) return { ok: false, error: "Missing elicitationId" };
const pending = codebuddySessionManager.elicitationPending.get(elicitationId);
const sessionManager = getCodebuddySessionManagerIfLoaded();
const pending = sessionManager?.elicitationPending?.get(elicitationId);
if (!pending) return { ok: false, error: "Elicitation not found or already resolved" };
let protectedContent = content;
if (content !== undefined && content !== null) {
@@ -1940,7 +1962,7 @@ function registerSdkStreamHandlers(ctx) {
return { ok: false, error: error.message };
}
}
const resolved = codebuddySessionManager.resolveElicitation(elicitationId, {
const resolved = sessionManager.resolveElicitation(elicitationId, {
action: action || "cancel",
content: protectedContent || undefined,
});
@@ -1950,7 +1972,7 @@ function registerSdkStreamHandlers(ctx) {
ipcMain.handle("netcatty:ai:sdk-agent:plugin-install", async (event, payload) => {
if (!validateSender(event)) return { ok: false, error: "Unauthorized IPC sender" };
try {
const result = await codebuddyDriver.codebuddyInstallPlugin(payload?.options || {});
const result = await getCodebuddyDriver().codebuddyInstallPlugin(payload?.options || {});
return { ok: true, result };
} catch (err) {
return { ok: false, error: err?.message || String(err) };
@@ -1960,7 +1982,7 @@ function registerSdkStreamHandlers(ctx) {
ipcMain.handle("netcatty:ai:sdk-agent:plugin-enable", async (event, payload) => {
if (!validateSender(event)) return { ok: false, error: "Unauthorized IPC sender" };
try {
const result = await codebuddyDriver.codebuddyEnablePlugin(payload?.name, payload?.marketplace);
const result = await getCodebuddyDriver().codebuddyEnablePlugin(payload?.name, payload?.marketplace);
return { ok: true, result };
} catch (err) {
return { ok: false, error: err?.message || String(err) };
@@ -1970,7 +1992,7 @@ function registerSdkStreamHandlers(ctx) {
ipcMain.handle("netcatty:ai:sdk-agent:plugin-disable", async (event, payload) => {
if (!validateSender(event)) return { ok: false, error: "Unauthorized IPC sender" };
try {
const result = await codebuddyDriver.codebuddyDisablePlugin(payload?.name, payload?.marketplace);
const result = await getCodebuddyDriver().codebuddyDisablePlugin(payload?.name, payload?.marketplace);
return { ok: true, result };
} catch (err) {
return { ok: false, error: err?.message || String(err) };
@@ -1980,7 +2002,7 @@ function registerSdkStreamHandlers(ctx) {
ipcMain.handle("netcatty:ai:sdk-agent:marketplace-install", async (event, payload) => {
if (!validateSender(event)) return { ok: false, error: "Unauthorized IPC sender" };
try {
const result = await codebuddyDriver.codebuddyInstallMarketplace(payload?.options || {});
const result = await getCodebuddyDriver().codebuddyInstallMarketplace(payload?.options || {});
return { ok: true, result };
} catch (err) {
return { ok: false, error: err?.message || String(err) };
@@ -1990,7 +2012,7 @@ function registerSdkStreamHandlers(ctx) {
ipcMain.handle("netcatty:ai:sdk-agent:marketplace-remove", async (event, payload) => {
if (!validateSender(event)) return { ok: false, error: "Unauthorized IPC sender" };
try {
const result = await codebuddyDriver.codebuddyRemoveMarketplace(payload?.options || {});
const result = await getCodebuddyDriver().codebuddyRemoveMarketplace(payload?.options || {});
return { ok: true, result };
} catch (err) {
return { ok: false, error: err?.message || String(err) };
@@ -2007,8 +2029,22 @@ function registerSdkStreamHandlers(ctx) {
ctx.sdkModelRefreshFailures = sdkModelRefreshFailures; // exposed for catalog tests
ctx.sdkModelKeyAliases = sdkModelKeyAliases; // exposed for catalog tests
ctx.cursorCliBinCache = cursorCliBinCache; // exposed for catalog tests
ctx.codexAppServerRuntime = codexAppServerRuntime;
ctx.codebuddySessionManager = codebuddySessionManager;
Object.defineProperty(ctx, "codexAppServerRuntime", {
enumerable: true,
configurable: true,
get() {
return getCodexAppServerRuntime();
},
});
Object.defineProperty(ctx, "codebuddySessionManager", {
enumerable: true,
configurable: true,
get() {
return getCodebuddySessionManager();
},
});
ctx.closeCodexAppServerRuntimeIfLoaded = () => _codexAppServerRuntime?.close?.();
ctx.closeCodebuddySessionsIfLoaded = () => getCodebuddySessionManagerIfLoaded()?.closeAll?.();
}
}
+13 -7
View File
@@ -110,6 +110,7 @@ function getAutoUpdater() {
// Silence the default electron-log transport (we log ourselves).
autoUpdater.logger = null;
_autoUpdater = autoUpdater;
setupGlobalListeners();
return autoUpdater;
} catch (err) {
console.error("[AutoUpdate] Failed to load electron-updater:", err?.message || err);
@@ -119,12 +120,13 @@ function getAutoUpdater() {
/**
* Register persistent global IPC event listeners for auto-download flow.
* Called once in init(). Forwards electron-updater events to the renderer
* even when no manual download was initiated.
* Called lazily the first time electron-updater is loaded so startup does not
* eagerly require electron-updater (141 modules / ~5.7 MiB) when unsupported
* or before an update check actually runs.
*/
function setupGlobalListeners() {
if (_listenersRegistered) return;
const updater = getAutoUpdater();
const updater = _autoUpdater;
if (!updater) return;
_listenersRegistered = true;
@@ -385,7 +387,9 @@ function cancelPendingInstall() {
function init(deps) {
_deps = deps;
setupGlobalListeners();
// Global updater listeners attach lazily inside getAutoUpdater() on the
// first actual update check/download so startup avoids loading 141 modules
// of electron-updater when unsupported or idle.
}
/**
@@ -415,6 +419,9 @@ function broadcastToAllWindows(channel, payload) {
}
function registerHandlers(ipcMain) {
if (!process.versions?.electron) {
getAutoUpdater();
}
// ---- Check for updates ------------------------------------------------
ipcMain.handle("netcatty:update:check", async () => {
// Cancel any pending auto-check to prevent concurrent checkForUpdates()
@@ -621,9 +628,8 @@ function registerHandlers(ipcMain) {
ipcMain.handle("netcatty:update:setAutoUpdate", (_event, { enabled }) => {
const wasEnabled = _prevAutoDownloadEnabled;
_prevAutoDownloadEnabled = !!enabled;
const updater = getAutoUpdater();
if (updater) {
updater.autoDownload = !!enabled;
if (_autoUpdater) {
_autoUpdater.autoDownload = !!enabled;
console.log("[AutoUpdate] autoDownload set to:", !!enabled);
}
// Persist so the preference survives app restarts
+22 -6
View File
@@ -11,10 +11,23 @@
const fs = require("node:fs");
const path = require("node:path");
const os = require("node:os");
const {
appendTerminalPerfLogLine,
configureTerminalPerformanceDiagnostics,
} = require("./terminalPerformanceDiagnostics.cjs");
let terminalPerfDiagUserDataPath = null;
let terminalPerfDiagModule = null;
function getTerminalPerfDiag() {
if (!terminalPerfDiagModule) {
terminalPerfDiagModule = require("./terminalPerformanceDiagnostics.cjs");
if (terminalPerfDiagUserDataPath) {
try {
terminalPerfDiagModule.configureTerminalPerformanceDiagnostics({
userDataPath: terminalPerfDiagUserDataPath,
});
} catch {
// ignore
}
}
}
return terminalPerfDiagModule;
}
// ---------------------------------------------------------------------------
// State
@@ -490,7 +503,10 @@ function init(deps) {
ensureLogDir();
try {
const userDataPath = electronApp?.getPath?.("userData");
configureTerminalPerformanceDiagnostics({ userDataPath });
terminalPerfDiagUserDataPath = userDataPath || null;
if (terminalPerfDiagModule && userDataPath) {
terminalPerfDiagModule.configureTerminalPerformanceDiagnostics({ userDataPath });
}
} catch {
// ignore
}
@@ -513,7 +529,7 @@ function registerHandlers(ipcMain) {
? payload.message.trim()
: "diagnostic";
if (source === "terminal-perf" && message.startsWith(TERMINAL_PERF_LOG_PREFIX)) {
appendTerminalPerfLogLine(message);
getTerminalPerfDiag().appendTerminalPerfLogLine(message);
if (shouldMirrorTerminalPerfDiagnostics()) {
console.info(message);
}
+19 -16
View File
@@ -1,8 +1,9 @@
"use strict";
const crypto = require("node:crypto");
const { normalizeRedactionConfig } = require("../mcp/externalMcpRedaction.cjs");
const aiPrivacyService = require("../shared/aiPrivacyService.cjs");
const normalizeRedactionConfig = (...args) =>
require("../mcp/externalMcpRedaction.cjs").normalizeRedactionConfig(...args);
const getAiPrivacyService = () => require("../shared/aiPrivacyService.cjs");
const {
getExternalMcpDiscoveryFilePath,
@@ -14,20 +15,22 @@ const {
writeExternalDiscovery,
removeExternalDiscovery,
} = require("../cli/externalMcpDiscovery.cjs");
const { createExternalMcpCodexSetup } = require("./externalMcp/codexSetup.cjs");
const { createExternalMcpClaudeSetup } = require("./externalMcp/claudeSetup.cjs");
const { createExternalMcpGrokSetup } = require("./externalMcp/grokSetup.cjs");
const {
readBundledNetcattySkillContent,
} = require("./externalMcp/netcattySkillInstaller.cjs");
const {
buildUniversalSetupPrompt,
} = require("./externalMcp/universalSetupPrompt.cjs");
const createExternalMcpCodexSetup = (...args) =>
require("./externalMcp/codexSetup.cjs").createExternalMcpCodexSetup(...args);
const createExternalMcpClaudeSetup = (...args) =>
require("./externalMcp/claudeSetup.cjs").createExternalMcpClaudeSetup(...args);
const createExternalMcpGrokSetup = (...args) =>
require("./externalMcp/grokSetup.cjs").createExternalMcpGrokSetup(...args);
const readBundledNetcattySkillContent = (...args) =>
require("./externalMcp/netcattySkillInstaller.cjs").readBundledNetcattySkillContent(...args);
const buildUniversalSetupPrompt = (...args) =>
require("./externalMcp/universalSetupPrompt.cjs").buildUniversalSetupPrompt(...args);
const {
DEFAULT_SESSION_IDLE_TIMEOUT_MINUTES,
normalizeSessionIdleTimeoutMinutes,
} = require("./mcpServerBridge/sessionIdleManager.cjs");
const { createExternalMcpHttpServer } = require("./externalMcp/httpServer.cjs");
const createExternalMcpHttpServer = (...args) =>
require("./externalMcp/httpServer.cjs").createExternalMcpHttpServer(...args);
const {
DEFAULT_EXTERNAL_MCP_HTTP_HOST,
DEFAULT_EXTERNAL_MCP_HTTP_PORT,
@@ -83,7 +86,7 @@ function createExternalMcpController(options = {}) {
let discoveryFilePath = null;
let enabled = false;
let redaction = normalizeRedactionConfig();
let redaction = { enabled: false, redactPrivateIps: false, cidrs: [], patterns: [] };
let state = "disabled";
let error = null;
let mode = EXTERNAL_MCP_MODE_TEMPORARY;
@@ -196,7 +199,7 @@ function createExternalMcpController(options = {}) {
chatSessionId: deps.chatSessionId,
}, {
externalSocket: context?.externalClient || null,
beforeExecute: aiPrivacyService.createPolicyGuard(),
beforeExecute: getAiPrivacyService().createPolicyGuard(),
});
},
});
@@ -554,7 +557,7 @@ function createExternalMcpController(options = {}) {
try {
nextRedaction = normalizeRedactionConfig(config.redaction);
} catch {
if (config.redaction === null) aiPrivacyService.invalidateConfiguration();
if (config.redaction === null) getAiPrivacyService().invalidateConfiguration();
return { ...buildStatus(), ok: false, error: "Invalid privacy rules. Check CIDRs and regular expressions." };
}
if (JSON.stringify(nextRedaction) !== JSON.stringify(redaction)) {
@@ -567,7 +570,7 @@ function createExternalMcpController(options = {}) {
return { ...buildStatus(), ok: false, error: "Privacy settings could not be saved. Retry before reconnecting clients." };
}
}
aiPrivacyService.configure(nextRedaction);
getAiPrivacyService().configure(nextRedaction);
}
const nextMode = config.mode == null ? mode : normalizeMode(config.mode);
const nextIdleTimeoutMinutes = config.idleTimeoutMinutes == null
+1 -1
View File
@@ -1,6 +1,5 @@
const crypto = require("node:crypto");
const { randomUUID } = require("node:crypto");
const { utils: sshUtils } = require("ssh2");
const { extractCertificatePublicKey } = require("../../domain/sshPublicKey.shared.cjs");
const REQUEST_TTL_MS = 2 * 60 * 1000;
@@ -158,6 +157,7 @@ const describeHostKey = (rawKey) => {
}
try {
const { utils: sshUtils } = require("ssh2");
const parsed = sshUtils.parseKey(key);
const parsedKey = Array.isArray(parsed) ? parsed[0] : parsed;
// Keep the presented certificate identity, even if a parser returns its
+325 -249
View File
@@ -10,18 +10,47 @@ const net = require("node:net");
const crypto = require("node:crypto");
const fs = require("node:fs");
const path = require("node:path");
const { PluginAgentMcpDelegations } = require("../plugins/agent/mcpDelegation.cjs");
const pluginAgentDelegations = new PluginAgentMcpDelegations();
let _pluginAgentDelegations = null;
function getPluginAgentDelegations() {
if (!_pluginAgentDelegations) {
const { PluginAgentMcpDelegations } = require("../plugins/agent/mcpDelegation.cjs");
_pluginAgentDelegations = new PluginAgentMcpDelegations();
}
return _pluginAgentDelegations;
}
const pluginAgentDelegations = {
authenticate: (token, socket) => _pluginAgentDelegations?.authenticate(token, socket) ?? false,
boundChat: (socket) => _pluginAgentDelegations?.boundChat(socket) ?? null,
isReserved: (chatSessionId) => _pluginAgentDelegations?.isReserved(chatSessionId) ?? false,
isApproved: (context) => _pluginAgentDelegations?.isApproved(context) ?? false,
dispatch: (...args) => getPluginAgentDelegations().dispatch(...args),
shutdown: () => _pluginAgentDelegations?.shutdown(),
register: (...args) => getPluginAgentDelegations().register(...args),
configuration: (...args) => getPluginAgentDelegations().configuration(...args),
assertCaller: (...args) => getPluginAgentDelegations().assertCaller(...args),
onRelease: (...args) => getPluginAgentDelegations().onRelease(...args),
beginModelRequest: (...args) => getPluginAgentDelegations().beginModelRequest(...args),
};
const { existsSync } = require("node:fs");
const { toUnpackedAsarPath, getFreshIdlePrompt, getVisibleIdlePrompt, formatSyntheticEcho } = require("./ai/shellUtils.cjs");
let _shellUtils = null;
const getShellUtils = () => (_shellUtils ??= require("./ai/shellUtils.cjs"));
const toUnpackedAsarPath = (...args) => getShellUtils().toUnpackedAsarPath(...args);
const getFreshIdlePrompt = (...args) => getShellUtils().getFreshIdlePrompt(...args);
const getVisibleIdlePrompt = (...args) => getShellUtils().getVisibleIdlePrompt(...args);
const formatSyntheticEcho = (...args) => getShellUtils().formatSyntheticEcho(...args);
const { appendVaultAgentGuidance } = require("../shared/vaultAgentGuidance.cjs");
const {
checkBlocklistForShell,
checkBlocklistCommonOnly,
resolveSessionBlocklistShellKind,
} = require("./ai/commandSafety.cjs");
const { execViaPty, startPtyJob, execViaChannel, execViaRawPty } = require("./ai/ptyExec.cjs");
let _commandSafety = null;
const getCommandSafety = () => (_commandSafety ??= require("./ai/commandSafety.cjs"));
const checkBlocklistForShell = (...args) => getCommandSafety().checkBlocklistForShell(...args);
const checkBlocklistCommonOnly = (...args) => getCommandSafety().checkBlocklistCommonOnly(...args);
const resolveSessionBlocklistShellKind = (...args) => getCommandSafety().resolveSessionBlocklistShellKind(...args);
let _ptyExec = null;
const getPtyExec = () => (_ptyExec ??= require("./ai/ptyExec.cjs"));
const execViaPty = (...args) => getPtyExec().execViaPty(...args);
const startPtyJob = (...args) => getPtyExec().startPtyJob(...args);
const execViaChannel = (...args) => getPtyExec().execViaChannel(...args);
const execViaRawPty = (...args) => getPtyExec().execViaRawPty(...args);
const { emitJobDiag } = require("./ai/jobStartupDiagnostics.cjs");
const { safeSend } = require("./ipcUtils.cjs");
const { emitTerminalSessionData } = require("./emitTerminalSessionData.cjs");
@@ -66,7 +95,11 @@ const DISCOVERY_SELF_HEAL_INTERVAL_MS = 15000;
// Track which sockets have completed authentication
const authenticatedSockets = new WeakSet();
const managedPrivacyScopes = new WeakMap();
const aiPrivacyService = require("../shared/aiPrivacyService.cjs");
let _aiPrivacyService = null;
function getAiPrivacyService() {
if (!_aiPrivacyService) _aiPrivacyService = require("../shared/aiPrivacyService.cjs");
return _aiPrivacyService;
}
const { createManagedPrivacyBoundary } = require("../shared/managedPrivacyBoundary.cjs");
// Sockets authenticated with the External MCP token (or that used the reserved scope).
const externalMcpSockets = new Set();
@@ -1585,6 +1618,7 @@ async function handleMessage(socket, line) {
);
}
notifyExternalMcpActivity(method, callParams);
const aiPrivacyService = getAiPrivacyService();
let result;
if (isExternalScope || externalMcpSockets.has(socket)) {
result = await dispatch(method, callParams, {
@@ -1618,21 +1652,18 @@ async function handleMessage(socket, line) {
// ── RPC Dispatch ──
const {
evaluateRpcPermission,
evaluatePermissionWithGrants,
USER_DENIED_MESSAGE,
CHAT_SESSION_CANCELLED_MESSAGE,
} = require("../capabilities/policy.cjs");
const { CAPABILITY_SURFACES } = require("../capabilities/constants.cjs");
const { getCapabilityByRpcMethod } = require("../capabilities/registry.cjs");
const { listMcpTools } = require("../capabilities/codegen/toolSurfaces.cjs");
const {
createCapabilityRpcDispatcher,
UNROUTED,
} = require("./mcpServerBridge/capabilityRpcDispatch.cjs");
const { buildBuiltinRpcHandlerRegistry } = require("./mcpServerBridge/builtinRpcHandlers.cjs");
const { createSessionService } = require("../capabilities/services/sessionService.cjs");
let _capabilitiesPolicy = null;
const getCapabilitiesPolicy = () => (_capabilitiesPolicy ??= require("../capabilities/policy.cjs"));
const evaluateRpcPermission = (...args) => getCapabilitiesPolicy().evaluateRpcPermission(...args);
const evaluatePermissionWithGrants = (...args) => getCapabilitiesPolicy().evaluatePermissionWithGrants(...args);
let _capabilitiesConstants = null;
const getCapabilitySurfaces = () => (_capabilitiesConstants ??= require("../capabilities/constants.cjs")).CAPABILITY_SURFACES;
const getCapabilityByRpcMethod = (...args) => require("../capabilities/registry.cjs").getCapabilityByRpcMethod(...args);
const listMcpTools = (...args) => require("../capabilities/codegen/toolSurfaces.cjs").listMcpTools(...args);
let _capabilityRpcDispatchMod = null;
const getCapabilityRpcDispatchMod = () => (_capabilityRpcDispatchMod ??= require("./mcpServerBridge/capabilityRpcDispatch.cjs"));
const buildBuiltinRpcHandlerRegistry = (...args) =>
require("./mcpServerBridge/builtinRpcHandlers.cjs").buildBuiltinRpcHandlerRegistry(...args);
let invokeVaultAgentFn = null;
@@ -1654,7 +1685,7 @@ const sessionIdleManager = createSessionIdleManager({
if (!sessionIdleManager.beginIdleClose(sessionId, activityVersion)) {
return;
}
await sessionService?.closeTracked({ chatSessionId, sessionId });
await getSessionService().closeTracked({ chatSessionId, sessionId });
},
});
@@ -1712,98 +1743,108 @@ async function queryWorkerShellReadiness(sessionId, status) {
}
}
sessionService = createSessionService({
validateReconnect: (params = {}) => {
const scopeErr = validateSessionScope(params.sessionId, params.chatSessionId, params.scopedSessionIds);
if (scopeErr) return { ok: false, error: scopeErr };
if (isChatSessionCancelled(params.chatSessionId)) return { ok: false, error: "Chat session is cancelled." };
if (permissionMode === "observer") return { ok: false, error: "Recovery is unavailable in observer mode." };
if (sessionIdleManager.isClosing(params.sessionId)) return { ok: false, error: "Session is closing." };
return { ok: true };
},
inspectRecovery: async (params, timeoutMs) => {
if (typeof invokeVaultAgentFn !== "function") return { ok: false, error: "Session recovery bridge is unavailable." };
sessionIdleManager.touch(null, params.sessionId);
const state = await invokeVaultAgentFn("session.inspectRecovery", { sessionId: params.sessionId }, { timeoutMs });
if (state?.ok !== true) return state;
const runtime = sessions?.get(params.sessionId);
const meta = getSessionMeta(params.sessionId, params.chatSessionId);
const probe = runtime ? {
trackedShell: typeof runtime._promptTrackTail === "string",
ready: Boolean(getFreshIdlePrompt(runtime) || getVisibleIdlePrompt(runtime)),
} : await queryWorkerShellReadiness(params.sessionId, state.status);
const trackedShell = Boolean(probe?.trackedShell) && !isNetworkDeviceLikeMeta(meta);
// shellReady semantics: transport not connected → false; connected but
// the shell is untracked or the probe missed/timed out → null (unknown);
// a tracked shell reports its observed readiness. It is advisory for
// callers: recovery never writes to the PTY, so an unknown or false
// readiness only asks for an inspect_shell step, never blocks.
const shellReady = state.status !== "connected" ? false : !probe ? null : trackedShell
? Boolean(probe.ready) : null;
return { ...state, shellReady, busy: Boolean(getSessionBusyError(params.sessionId)) };
},
invokeSessionAgent: (...args) => {
if (typeof invokeVaultAgentFn !== "function") {
return Promise.resolve({ ok: false, error: "Vault agent bridge is unavailable." });
}
return invokeVaultAgentFn(...args);
},
validateClose: (params = {}) => {
const scopeErr = validateSessionScope(
params.sessionId,
params.chatSessionId,
params.scopedSessionIds,
);
if (scopeErr) return { ok: false, error: scopeErr };
if (sessionIdleManager.isClosing(params.sessionId)) {
return { ok: false, error: `Session "${params.sessionId}" is closing.` };
}
return openedSessionOwnership.validate(params.chatSessionId, params.sessionId);
},
beforeClose: async (params = {}) => {
sessionIdleManager.beginClose(params.sessionId);
beginTerminalSessionClose(params.sessionId);
cancelBackgroundJobsForTerminalSession(params.sessionId);
await cancelWorkerBackgroundJobsForTerminalSession(params.sessionId);
await cancelSftpOpsForTerminalSession(params.sessionId);
},
afterClose: (params = {}, outcome = {}) => {
endTerminalSessionClose(params.sessionId);
if (outcome.closed) return;
if (outcome.notFound) {
forgetClosedTerminalSession(params.sessionId);
return;
}
sessionIdleManager.resume(params.sessionId);
},
onClosed: async (sessionId) => {
await settleBackgroundJobsForTerminalSession(sessionId);
forgetClosedTerminalSession(sessionId);
},
});
function getSessionService() {
if (!sessionService) {
const { createSessionService } = require("../capabilities/services/sessionService.cjs");
sessionService = createSessionService({
validateReconnect: (params = {}) => {
const scopeErr = validateSessionScope(params.sessionId, params.chatSessionId, params.scopedSessionIds);
if (scopeErr) return { ok: false, error: scopeErr };
if (isChatSessionCancelled(params.chatSessionId)) return { ok: false, error: "Chat session is cancelled." };
if (permissionMode === "observer") return { ok: false, error: "Recovery is unavailable in observer mode." };
if (sessionIdleManager.isClosing(params.sessionId)) return { ok: false, error: "Session is closing." };
return { ok: true };
},
inspectRecovery: async (params, timeoutMs) => {
if (typeof invokeVaultAgentFn !== "function") return { ok: false, error: "Session recovery bridge is unavailable." };
sessionIdleManager.touch(null, params.sessionId);
const state = await invokeVaultAgentFn("session.inspectRecovery", { sessionId: params.sessionId }, { timeoutMs });
if (state?.ok !== true) return state;
const runtime = sessions?.get(params.sessionId);
const meta = getSessionMeta(params.sessionId, params.chatSessionId);
const probe = runtime ? {
trackedShell: typeof runtime._promptTrackTail === "string",
ready: Boolean(getFreshIdlePrompt(runtime) || getVisibleIdlePrompt(runtime)),
} : await queryWorkerShellReadiness(params.sessionId, state.status);
const trackedShell = Boolean(probe?.trackedShell) && !isNetworkDeviceLikeMeta(meta);
// shellReady semantics: transport not connected → false; connected but
// the shell is untracked or the probe missed/timed out → null (unknown);
// a tracked shell reports its observed readiness. It is advisory for
// callers: recovery never writes to the PTY, so an unknown or false
// readiness only asks for an inspect_shell step, never blocks.
const shellReady = state.status !== "connected" ? false : !probe ? null : trackedShell
? Boolean(probe.ready) : null;
return { ...state, shellReady, busy: Boolean(getSessionBusyError(params.sessionId)) };
},
invokeSessionAgent: (...args) => {
if (typeof invokeVaultAgentFn !== "function") {
return Promise.resolve({ ok: false, error: "Vault agent bridge is unavailable." });
}
return invokeVaultAgentFn(...args);
},
validateClose: (params = {}) => {
const scopeErr = validateSessionScope(
params.sessionId,
params.chatSessionId,
params.scopedSessionIds,
);
if (scopeErr) return { ok: false, error: scopeErr };
if (sessionIdleManager.isClosing(params.sessionId)) {
return { ok: false, error: `Session "${params.sessionId}" is closing.` };
}
return openedSessionOwnership.validate(params.chatSessionId, params.sessionId);
},
beforeClose: async (params = {}) => {
sessionIdleManager.beginClose(params.sessionId);
beginTerminalSessionClose(params.sessionId);
cancelBackgroundJobsForTerminalSession(params.sessionId);
await cancelWorkerBackgroundJobsForTerminalSession(params.sessionId);
await cancelSftpOpsForTerminalSession(params.sessionId);
},
afterClose: (params = {}, outcome = {}) => {
endTerminalSessionClose(params.sessionId);
if (outcome.closed) return;
if (outcome.notFound) {
forgetClosedTerminalSession(params.sessionId);
return;
}
sessionIdleManager.resume(params.sessionId);
},
onClosed: async (sessionId) => {
await settleBackgroundJobsForTerminalSession(sessionId);
forgetClosedTerminalSession(sessionId);
},
});
}
return sessionService;
}
const dispatchCapabilityRpc = createCapabilityRpcDispatcher({
invokeVaultAgent: (...args) => {
if (typeof invokeVaultAgentFn !== "function") {
return Promise.resolve({ ok: false, error: "Vault agent bridge is unavailable." });
}
return invokeVaultAgentFn(...args);
},
evaluatePermissionWithGrants,
isDelegatedApproval: (context) => pluginAgentDelegations.isApproved(context),
get permissionMode() {
return permissionMode;
},
get permissionGrantsSnapshot() {
return permissionGrantsSnapshot;
},
isChatSessionCancelled,
requestApprovalFromRenderer,
getApprovalTarget,
hasSessionApproval: (socket) => Boolean(socket && sessionApprovedExternalSockets.has(socket)),
USER_DENIED_MESSAGE,
listPortForwards: () => listActivePortForwards(),
sessionService,
let _dispatchCapabilityRpc = null;
function getDispatchCapabilityRpc() {
if (!_dispatchCapabilityRpc) {
const { createCapabilityRpcDispatcher } = getCapabilityRpcDispatchMod();
_dispatchCapabilityRpc = createCapabilityRpcDispatcher({
invokeVaultAgent: (...args) => {
if (typeof invokeVaultAgentFn !== "function") {
return Promise.resolve({ ok: false, error: "Vault agent bridge is unavailable." });
}
return invokeVaultAgentFn(...args);
},
evaluatePermissionWithGrants,
isDelegatedApproval: (context) => pluginAgentDelegations.isApproved(context),
get permissionMode() {
return permissionMode;
},
get permissionGrantsSnapshot() {
return permissionGrantsSnapshot;
},
isChatSessionCancelled,
requestApprovalFromRenderer,
getApprovalTarget,
hasSessionApproval: (socket) => Boolean(socket && sessionApprovedExternalSockets.has(socket)),
USER_DENIED_MESSAGE: getCapabilitiesPolicy().USER_DENIED_MESSAGE,
listPortForwards: () => listActivePortForwards(),
sessionService: getSessionService(),
captureHostOpenScope: (chatSessionId) => ({
ownershipGeneration: openedSessionOwnership.captureGeneration(chatSessionId),
closeRevision: terminalSessionCloseRevision,
@@ -1852,7 +1893,11 @@ const dispatchCapabilityRpc = createCapabilityRpcDispatcher({
sessionIdleManager.track(chatSessionId, sessionId);
return true;
},
});
});
}
return _dispatchCapabilityRpc;
}
const dispatchCapabilityRpc = (...args) => getDispatchCapabilityRpc()(...args);
/**
* Validate that a sessionId is allowed in the current scope.
@@ -2479,8 +2524,8 @@ function getBuiltinRpcHandlerRegistry() {
ok: false,
error: "terminal_start_bulk must be dispatched through the bulk job starter.",
}),
"terminal.pollBulk": (params) => jobBulkHandler.poll(params),
"terminal.stopBulk": (params) => jobBulkHandler.stop(params),
"terminal.pollBulk": (params) => getJobBulkHandler().poll(params),
"terminal.stopBulk": (params) => getJobBulkHandler().stop(params),
});
}
return builtinRpcHandlerRegistry;
@@ -2501,11 +2546,12 @@ async function dispatchCore(method, params, approvalContext = {}) {
if (!method.startsWith("netcatty/")) {
const capabilityResult = await dispatchCapabilityRpc(method, params || {}, approvalContext);
if (capabilityResult !== UNROUTED) {
if (capabilityResult !== getCapabilityRpcDispatchMod().UNROUTED) {
return capabilityResult;
}
}
const CAPABILITY_SURFACES = getCapabilitySurfaces();
const capability = getCapabilityByRpcMethod(method, CAPABILITY_SURFACES.BUILTIN);
const sessionWriteLockId = (capability?.id === "terminal.execute" || capability?.id === "terminal.start")
? params?.sessionId
@@ -2532,13 +2578,13 @@ async function dispatchCore(method, params, approvalContext = {}) {
if (capability?.id === "terminal.executeBulk") {
// Plugin-delegated agents never get fan-out execution.
if (delegated) return { ok: false, error: "terminal_execute_bulk is not available to this client." };
return execBulkHandler.run(params, approvalContext, permission);
return getExecBulkHandler().run(params, approvalContext, permission);
}
if (capability?.id === "terminal.startBulk" || capability?.id === "terminal.pollBulk" || capability?.id === "terminal.stopBulk") {
// Plugin-delegated agents never get fan-out execution.
if (delegated) return { ok: false, error: `${capability.surfaces?.builtin?.mcpTool || method} is not available to this client.` };
if (capability.id === "terminal.startBulk") return jobBulkHandler.start(params, approvalContext, permission);
if (capability.id === "terminal.startBulk") return getJobBulkHandler().start(params, approvalContext, permission);
}
// Validate session scope *first* so out-of-scope callers cannot infer the
@@ -2598,7 +2644,7 @@ async function dispatchCore(method, params, approvalContext = {}) {
target: approvalTarget,
});
if (!approved) {
return { ok: false, error: USER_DENIED_MESSAGE };
return { ok: false, error: getCapabilitiesPolicy().USER_DENIED_MESSAGE };
}
}
if (
@@ -2841,58 +2887,65 @@ async function handleSetCancelled(params) {
return applyChatSessionCancelled(chatSessionId, cancelled);
}
const { createSftpHandlerApi } = require("./mcpServerBridge/sftpHandlers.cjs");
const sftpHandlerApi = createSftpHandlerApi({
get commandTimeoutMs() { return commandTimeoutMs; },
get sessions() { return sessions; },
get terminalWorkerManager() { return terminalWorkerManager; },
sftpBridge, registerSftpOp, setTimeout, clearTimeout, AbortController, Promise, Error,
createTransferId: () => require("node:crypto").randomUUID(),
reportTransferEvent: (payload) => broadcastApprovalEvent("netcatty:sftp:global-transfer", payload),
get transferBridge() { return fileTransferBridge; },
});
const {
getSessionSftpEncodingStateKey,
withSessionBackedSftp,
handleSftpList,
handleSftpRead,
handleSftpWrite,
handleSftpDownload,
handleSftpUpload,
handleSftpMkdir,
handleSftpDelete,
handleSftpRename,
handleSftpStat,
handleSftpChmod,
handleSftpHome,
} = sftpHandlerApi;
let _sftpHandlerApi = null;
function getSftpHandlerApi() {
if (!_sftpHandlerApi) {
const { createSftpHandlerApi } = require("./mcpServerBridge/sftpHandlers.cjs");
_sftpHandlerApi = createSftpHandlerApi({
get commandTimeoutMs() { return commandTimeoutMs; },
get sessions() { return sessions; },
get terminalWorkerManager() { return terminalWorkerManager; },
sftpBridge, registerSftpOp, setTimeout, clearTimeout, AbortController, Promise, Error,
createTransferId: () => require("node:crypto").randomUUID(),
reportTransferEvent: (payload) => broadcastApprovalEvent("netcatty:sftp:global-transfer", payload),
get transferBridge() { return fileTransferBridge; },
});
}
return _sftpHandlerApi;
}
const getSessionSftpEncodingStateKey = (...args) => getSftpHandlerApi().getSessionSftpEncodingStateKey(...args);
const withSessionBackedSftp = (...args) => getSftpHandlerApi().withSessionBackedSftp(...args);
const handleSftpList = (...args) => getSftpHandlerApi().handleSftpList(...args);
const handleSftpRead = (...args) => getSftpHandlerApi().handleSftpRead(...args);
const handleSftpWrite = (...args) => getSftpHandlerApi().handleSftpWrite(...args);
const handleSftpDownload = (...args) => getSftpHandlerApi().handleSftpDownload(...args);
const handleSftpUpload = (...args) => getSftpHandlerApi().handleSftpUpload(...args);
const handleSftpMkdir = (...args) => getSftpHandlerApi().handleSftpMkdir(...args);
const handleSftpDelete = (...args) => getSftpHandlerApi().handleSftpDelete(...args);
const handleSftpRename = (...args) => getSftpHandlerApi().handleSftpRename(...args);
const handleSftpStat = (...args) => getSftpHandlerApi().handleSftpStat(...args);
const handleSftpChmod = (...args) => getSftpHandlerApi().handleSftpChmod(...args);
const handleSftpHome = (...args) => getSftpHandlerApi().handleSftpHome(...args);
// ── Handler: exec ──
const { createExecHandlerApi } = require("./mcpServerBridge/execHandlers.cjs");
const execHandlerApi = createExecHandlerApi({
get sessions() { return sessions; },
get commandTimeoutMs() { return commandTimeoutMs; },
DEFAULT_BACKGROUND_JOB_TIMEOUT_MS, DEFAULT_BACKGROUND_JOB_POLL_INTERVAL_MS, MAX_BACKGROUND_JOB_OUTPUT_CHARS,
backgroundJobs, activePtyExecs,
debugLog, getSessionMeta, checkCommandSafetyForShell, checkCommandSafetyCommonOnly, resolveSessionBlocklistShellKind, reserveSessionExecution, releaseSessionExecution,
beginChatExecution, execViaRawPty, execViaPty, execViaChannel, startPtyJob,
getFreshIdlePrompt, echoCommandToSession, createBackgroundJobId, storeCompletedJobOutput,
serializeBackgroundJob, validateSessionScope, Date, Error,
});
const {
resolveExecContext,
preflightExec,
preflightJobStart,
handleExec,
handleJobStart,
getScopedJob,
handleJobPoll,
handleJobStop,
} = execHandlerApi;
let _execHandlerApi = null;
function getExecHandlerApi() {
if (!_execHandlerApi) {
const { createExecHandlerApi } = require("./mcpServerBridge/execHandlers.cjs");
_execHandlerApi = createExecHandlerApi({
get sessions() { return sessions; },
get commandTimeoutMs() { return commandTimeoutMs; },
DEFAULT_BACKGROUND_JOB_TIMEOUT_MS, DEFAULT_BACKGROUND_JOB_POLL_INTERVAL_MS, MAX_BACKGROUND_JOB_OUTPUT_CHARS,
backgroundJobs, activePtyExecs,
debugLog, getSessionMeta, checkCommandSafetyForShell, checkCommandSafetyCommonOnly, resolveSessionBlocklistShellKind, reserveSessionExecution, releaseSessionExecution,
beginChatExecution, execViaRawPty, execViaPty, execViaChannel, startPtyJob,
getFreshIdlePrompt, echoCommandToSession, createBackgroundJobId, storeCompletedJobOutput,
serializeBackgroundJob, validateSessionScope, Date, Error,
});
}
return _execHandlerApi;
}
const resolveExecContext = (...args) => getExecHandlerApi().resolveExecContext(...args);
const preflightExec = (...args) => getExecHandlerApi().preflightExec(...args);
const preflightJobStart = (...args) => getExecHandlerApi().preflightJobStart(...args);
const handleExec = (...args) => getExecHandlerApi().handleExec(...args);
const handleJobStart = (...args) => getExecHandlerApi().handleJobStart(...args);
const getScopedJob = (...args) => getExecHandlerApi().getScopedJob(...args);
const handleJobPoll = (...args) => getExecHandlerApi().handleJobPoll(...args);
const handleJobStop = (...args) => getExecHandlerApi().handleJobStop(...args);
// terminal_execute_bulk: validate every target, ask once, then fan out.
const { createExecBulkHandler } = require("./mcpServerBridge/execBulk.cjs");
function execOnSessionForBulk(params, executionContext) {
// Mirrors dispatchCore: sessions not in the main-process map live in the terminal worker.
if (!sessions?.get?.(params.sessionId)) {
@@ -2900,85 +2953,108 @@ function execOnSessionForBulk(params, executionContext) {
}
return handleExec(params, executionContext);
}
const execBulkHandler = createExecBulkHandler({
getSessions: () => sessions,
getSessionMeta,
validateSessionScope,
closingTerminalSessions,
getSessionBusyError,
pendingSessionWriteApprovals,
getActiveChatExecution,
beginChatExecution,
isChatSessionCancelled,
preflightMainExec: preflightExec,
preflightWorkerExec,
execOnSession: execOnSessionForBulk,
requestApproval: requestApprovalFromRenderer,
sessionIdleManager,
getCommandTimeoutMs: () => commandTimeoutMs,
getLivePermission: (params) => evaluateRpcPermission({
rpcMethod: "netcatty/execBulk",
surface: CAPABILITY_SURFACES.BUILTIN,
permissionMode,
params,
context: { chatSessionCancelled: isChatSessionCancelled(params?.chatSessionId) },
}),
cancelExecsForChat: (chatSessionId) => {
cancelPtyExecsForSession(chatSessionId);
cancelWorkerExecsForChat(chatSessionId);
},
USER_DENIED_MESSAGE,
CHAT_SESSION_CANCELLED_MESSAGE,
debugLog,
});
let _execBulkHandler = null;
function getExecBulkHandler() {
if (!_execBulkHandler) {
const { createExecBulkHandler } = require("./mcpServerBridge/execBulk.cjs");
const { USER_DENIED_MESSAGE, CHAT_SESSION_CANCELLED_MESSAGE } = getCapabilitiesPolicy();
_execBulkHandler = createExecBulkHandler({
getSessions: () => sessions,
getSessionMeta,
validateSessionScope,
closingTerminalSessions,
getSessionBusyError,
pendingSessionWriteApprovals,
getActiveChatExecution,
beginChatExecution,
isChatSessionCancelled,
preflightMainExec: preflightExec,
preflightWorkerExec,
execOnSession: execOnSessionForBulk,
requestApproval: requestApprovalFromRenderer,
sessionIdleManager,
getCommandTimeoutMs: () => commandTimeoutMs,
getLivePermission: (params) => evaluateRpcPermission({
rpcMethod: "netcatty/execBulk",
surface: getCapabilitySurfaces().BUILTIN,
permissionMode,
params,
context: { chatSessionCancelled: isChatSessionCancelled(params?.chatSessionId) },
}),
cancelExecsForChat: (chatSessionId) => {
cancelPtyExecsForSession(chatSessionId);
cancelWorkerExecsForChat(chatSessionId);
},
USER_DENIED_MESSAGE,
CHAT_SESSION_CANCELLED_MESSAGE,
debugLog,
});
}
return _execBulkHandler;
}
// terminal_start_bulk / terminal_poll_bulk / terminal_stop_bulk: background jobs on many sessions.
const { createJobBulkHandler } = require("./mcpServerBridge/jobBulk.cjs");
const jobBulkHandler = createJobBulkHandler({
getSessions: () => sessions,
getSessionMeta,
validateSessionScope,
closingTerminalSessions,
getSessionBusyError,
pendingSessionWriteApprovals,
isChatSessionCancelled,
preflightMainJobStart: preflightJobStart,
preflightWorkerJobStart,
// Mirrors dispatchCore: sessions not in the main-process map live in the terminal worker.
startJobOnSession: (params, beforeExecute) => (sessions?.get?.(params.sessionId)
? handleJobStart(params, { beforeExecute })
: handleWorkerJobStart(params, beforeExecute)),
pollJob: (params) => (workerBackgroundJobs.has(params.jobId)
? handleWorkerJobPoll(params)
: handleJobPoll(params)),
stopJob: (params) => (workerBackgroundJobs.has(params.jobId)
? handleWorkerJobStop(params)
: handleJobStop(params)),
requestApproval: requestApprovalFromRenderer,
sessionIdleManager,
getLivePermission: (params) => evaluateRpcPermission({
rpcMethod: "netcatty/jobStartBulk",
surface: CAPABILITY_SURFACES.BUILTIN,
permissionMode,
params,
context: { chatSessionCancelled: isChatSessionCancelled(params?.chatSessionId) },
}),
USER_DENIED_MESSAGE,
CHAT_SESSION_CANCELLED_MESSAGE,
});
const { createConfigAndCleanupApi } = require("./mcpServerBridge/configAndCleanup.cjs");
const configAndCleanupApi = createConfigAndCleanupApi({
get authToken() { return authToken; },
get permissionMode() { return permissionMode; },
process, existsSync, path, __dirname, toUnpackedAsarPath, DEBUG_MCP,
getScopedSessionIds, scopedMetadata, scopedAttachments, cancelledChatSessions, cancelBackgroundJobsForSession,
cancelWorkerBackgroundJobsForSession,
cancelWorkerBackgroundJobsForTerminalSession,
clearPendingApprovals, cancelSftpOpsForSession, sftpBridge,
get terminalWorkerManager() { return terminalWorkerManager; },
preserveIdleSessionCleanup: sessionIdleManager.scopeCleared,
clearOpenedSessionScope: openedSessionOwnership.clearScope,
});
const { resolveMcpServerRuntimeCommand, buildMcpServerConfig, cleanupScopedMetadata } = configAndCleanupApi;
let _jobBulkHandler = null;
function getJobBulkHandler() {
if (!_jobBulkHandler) {
const { createJobBulkHandler } = require("./mcpServerBridge/jobBulk.cjs");
const { USER_DENIED_MESSAGE, CHAT_SESSION_CANCELLED_MESSAGE } = getCapabilitiesPolicy();
_jobBulkHandler = createJobBulkHandler({
getSessions: () => sessions,
getSessionMeta,
validateSessionScope,
closingTerminalSessions,
getSessionBusyError,
pendingSessionWriteApprovals,
isChatSessionCancelled,
preflightMainJobStart: preflightJobStart,
preflightWorkerJobStart,
// Mirrors dispatchCore: sessions not in the main-process map live in the terminal worker.
startJobOnSession: (params, beforeExecute) => (sessions?.get?.(params.sessionId)
? handleJobStart(params, { beforeExecute })
: handleWorkerJobStart(params, beforeExecute)),
pollJob: (params) => (workerBackgroundJobs.has(params.jobId)
? handleWorkerJobPoll(params)
: handleJobPoll(params)),
stopJob: (params) => (workerBackgroundJobs.has(params.jobId)
? handleWorkerJobStop(params)
: handleJobStop(params)),
requestApproval: requestApprovalFromRenderer,
sessionIdleManager,
getLivePermission: (params) => evaluateRpcPermission({
rpcMethod: "netcatty/jobStartBulk",
surface: getCapabilitySurfaces().BUILTIN,
permissionMode,
params,
context: { chatSessionCancelled: isChatSessionCancelled(params?.chatSessionId) },
}),
USER_DENIED_MESSAGE,
CHAT_SESSION_CANCELLED_MESSAGE,
});
}
return _jobBulkHandler;
}
let _configAndCleanupApi = null;
function getConfigAndCleanupApi() {
if (!_configAndCleanupApi) {
const { createConfigAndCleanupApi } = require("./mcpServerBridge/configAndCleanup.cjs");
_configAndCleanupApi = createConfigAndCleanupApi({
get authToken() { return authToken; },
get permissionMode() { return permissionMode; },
process, existsSync, path, __dirname, toUnpackedAsarPath, DEBUG_MCP,
getScopedSessionIds, scopedMetadata, scopedAttachments, cancelledChatSessions, cancelBackgroundJobsForSession,
cancelWorkerBackgroundJobsForSession,
cancelWorkerBackgroundJobsForTerminalSession,
clearPendingApprovals, cancelSftpOpsForSession, sftpBridge,
get terminalWorkerManager() { return terminalWorkerManager; },
preserveIdleSessionCleanup: sessionIdleManager.scopeCleared,
clearOpenedSessionScope: openedSessionOwnership.clearScope,
});
}
return _configAndCleanupApi;
}
const resolveMcpServerRuntimeCommand = (...args) => getConfigAndCleanupApi().resolveMcpServerRuntimeCommand(...args);
const buildMcpServerConfig = (...args) => getConfigAndCleanupApi().buildMcpServerConfig(...args);
const cleanupScopedMetadata = (...args) => getConfigAndCleanupApi().cleanupScopedMetadata(...args);
function cleanup() {
pluginAgentDelegations.shutdown();
+55 -18
View File
@@ -5,31 +5,66 @@
const net = require("node:net");
const { createSocks5RequestParser } = require("./socks5Request.cjs");
require("./boringSslDhCompat.cjs").installBoringSslDhCompat();
const { Client: SSHClient } = require("ssh2");
const { NetcattyAgent } = require("./netcattyAgent.cjs");
const keyboardInteractiveHandler = require("./keyboardInteractiveHandler.cjs");
const { connectThroughChain, buildAlgorithms } = require("./sshBridge.cjs");
const { resolveSshConnectionTimeouts } = require("./sshBridge/startSession.cjs");
const { remoteSoftwareRequiresSingleChannel } = require("../../domain/singleChannelSshBanner.shared.cjs");
const hostKeyVerifier = require("./hostKeyVerifier.cjs");
const { createProxySocket, runWhenProxyConnectionReady } = require("./proxyUtils.cjs");
const {
openBoundedForwardInCallback,
openBoundedForwardOutCallback,
} = require("./boundedSshChannelOpen.cjs");
const {
buildAuthHandler,
createKeyboardInteractiveHandler,
applyAuthToConnOpts,
shouldSkipKiPasswordAutoFill,
findAllDefaultPrivateKeys: findAllDefaultPrivateKeysFromHelper,
preparePrivateKeyForAuth,
loadFirstIdentityFileForAuth,
getAvailableAgentSocket,
prepareSystemSshAgentForAuth,
isPassphraseCancelledError,
} = require("./sshAuthHelper.cjs");
let _ssh2ClientCtor = null;
function getSshClientCtor() {
if (!_ssh2ClientCtor) {
require("./boringSslDhCompat.cjs").installBoringSslDhCompat();
({ Client: _ssh2ClientCtor } = require("ssh2"));
}
return _ssh2ClientCtor;
}
if (!process.versions?.electron) {
getSshClientCtor();
}
let _netcattyAgentCtor = null;
function getNetcattyAgentCtor() {
if (!_netcattyAgentCtor) ({ NetcattyAgent: _netcattyAgentCtor } = require("./netcattyAgent.cjs"));
return _netcattyAgentCtor;
}
let _sshBridgeMod = null;
function getSshBridge() {
if (!_sshBridgeMod) _sshBridgeMod = require("./sshBridge.cjs");
return _sshBridgeMod;
}
let _startSessionMod = null;
function getStartSessionMod() {
if (!_startSessionMod) _startSessionMod = require("./sshBridge/startSession.cjs");
return _startSessionMod;
}
let _proxyUtilsMod = null;
function getProxyUtils() {
if (!_proxyUtilsMod) _proxyUtilsMod = require("./proxyUtils.cjs");
return _proxyUtilsMod;
}
let _sshAuthHelperMod = null;
function getSshAuthHelper() {
if (!_sshAuthHelperMod) _sshAuthHelperMod = require("./sshAuthHelper.cjs");
return _sshAuthHelperMod;
}
const connectThroughChain = (...args) => getSshBridge().connectThroughChain(...args);
const buildAlgorithms = (...args) => getSshBridge().buildAlgorithms(...args);
const resolveSshConnectionTimeouts = (...args) => getStartSessionMod().resolveSshConnectionTimeouts(...args);
const createProxySocket = (...args) => getProxyUtils().createProxySocket(...args);
const runWhenProxyConnectionReady = (...args) => getProxyUtils().runWhenProxyConnectionReady(...args);
const buildAuthHandler = (...args) => getSshAuthHelper().buildAuthHandler(...args);
const createKeyboardInteractiveHandler = (...args) => getSshAuthHelper().createKeyboardInteractiveHandler(...args);
const applyAuthToConnOpts = (...args) => getSshAuthHelper().applyAuthToConnOpts(...args);
const shouldSkipKiPasswordAutoFill = (...args) => getSshAuthHelper().shouldSkipKiPasswordAutoFill(...args);
const findAllDefaultPrivateKeysFromHelper = (...args) => getSshAuthHelper().findAllDefaultPrivateKeys(...args);
const preparePrivateKeyForAuth = (...args) => getSshAuthHelper().preparePrivateKeyForAuth(...args);
const loadFirstIdentityFileForAuth = (...args) => getSshAuthHelper().loadFirstIdentityFileForAuth(...args);
const getAvailableAgentSocket = (...args) => getSshAuthHelper().getAvailableAgentSocket(...args);
const prepareSystemSshAgentForAuth = (...args) => getSshAuthHelper().prepareSystemSshAgentForAuth(...args);
const isPassphraseCancelledError = (...args) => getSshAuthHelper().isPassphraseCancelledError(...args);
const {
createTransport,
borrowTransport,
@@ -1374,6 +1409,7 @@ async function startPortForward(event, payload, { bindChannels = bindPortForward
}
}
const SSHClient = getSshClientCtor();
const conn = new SSHClient();
tunnelState.conn = conn;
tunnelState.chainConnections = chainConnections;
@@ -1496,6 +1532,7 @@ async function startPortForward(event, payload, { bindChannels = bindPortForward
connectOpts.agent = systemAuthAgent;
}
if (hasCertificate && !isFido) {
const NetcattyAgent = getNetcattyAgentCtor();
connectOpts.agent = new NetcattyAgent({
mode: "certificate",
webContents: sender,
+1 -1
View File
@@ -6,7 +6,6 @@ const http = require("node:http");
const net = require("node:net");
const path = require("node:path");
const { performance } = require("node:perf_hooks");
const { WebSocketServer } = require("ws");
const {
computeCertSha256Fingerprint,
extractPeerCertInfo,
@@ -1382,6 +1381,7 @@ function createRemoteDesktopService(options = {}) {
res.writeHead(426, { "Content-Type": "text/plain" });
res.end("Upgrade Required");
});
const { WebSocketServer } = require("ws");
const wsServer = new WebSocketServer({
noServer: true,
perMessageDeflate: false,
@@ -15,7 +15,6 @@ const crypto = require("node:crypto");
const fs = require("node:fs");
const path = require("node:path");
const { Readable } = require("node:stream");
const { patchWebmDurationFile } = require("./webmDurationPatch.cjs");
const RECORDING_MEDIA_SCHEME = "netcatty-media";
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
@@ -280,6 +279,7 @@ function createRemoteDesktopRecordingsBridge(options = {}) {
if (safeDurationMs > 0) {
try {
const { patchWebmDurationFile } = require("./webmDurationPatch.cjs");
await patchWebmDurationFile(writer.partPath, safeDurationMs);
} catch (err) {
console.warn("[Recordings] EBML duration patch skipped:", err?.message || err);
+109 -53
View File
@@ -14,38 +14,78 @@ const { executeBoundedSshCommand } = require("./boundedSshExec.cjs");
const { remoteSoftwareRequiresSingleChannel } = require("../../domain/singleChannelSshBanner.shared.cjs");
const { openBoundedSftpChannel } = require("./boundedSftpOpen.cjs");
const { invalidateSshTransport } = require("./sshTransportInvalidation.cjs");
require("./boringSslDhCompat.cjs").installBoringSslDhCompat();
const SftpClient = require("ssh2-sftp-client");
const { Client: SSHClient } = require("ssh2");
const iconv = require("iconv-lite");
let SFTPWrapper;
try {
// Try to load SFTPWrapper from ssh2 internals for sudo support
const sftpModule = require("ssh2/lib/protocol/SFTP");
SFTPWrapper = sftpModule.SFTP || sftpModule;
} catch (e) {
console.warn("[SFTP] Failed to load SFTPWrapper from ssh2, sudo mode will not work:", e.message);
const _isElectronRuntime = Boolean(process.versions?.electron);
let _sftpClientCtor = _isElectronRuntime ? null : (require("./boringSslDhCompat.cjs").installBoringSslDhCompat(), require("ssh2-sftp-client"));
function getSftpClientCtor() {
if (!_sftpClientCtor) {
require("./boringSslDhCompat.cjs").installBoringSslDhCompat();
_sftpClientCtor = require("ssh2-sftp-client");
}
return _sftpClientCtor;
}
let _sshClientCtor = _isElectronRuntime ? null : require("ssh2").Client;
function getSshClientCtor() {
if (!_sshClientCtor) {
require("./boringSslDhCompat.cjs").installBoringSslDhCompat();
({ Client: _sshClientCtor } = require("ssh2"));
}
return _sshClientCtor;
}
let _iconv = null;
function getIconv() {
if (!_iconv) _iconv = require("iconv-lite");
return _iconv;
}
let _sftpWrapperResolved = false;
let _sftpWrapper = undefined;
function getSftpWrapper() {
if (!_sftpWrapperResolved) {
_sftpWrapperResolved = true;
try {
// Try to load SFTPWrapper from ssh2 internals for sudo support
const sftpModule = require("ssh2/lib/protocol/SFTP");
_sftpWrapper = sftpModule.SFTP || sftpModule;
} catch (e) {
console.warn("[SFTP] Failed to load SFTPWrapper from ssh2, sudo mode will not work:", e.message);
}
}
return _sftpWrapper;
}
if (!_isElectronRuntime) {
getSftpWrapper();
}
let _netcattyAgentCtor = null;
function getNetcattyAgentCtor() {
if (!_netcattyAgentCtor) ({ NetcattyAgent: _netcattyAgentCtor } = require("./netcattyAgent.cjs"));
return _netcattyAgentCtor;
}
let _proxyUtilsMod = _isElectronRuntime ? null : require("./proxyUtils.cjs");
function getProxyUtils() {
if (!_proxyUtilsMod) _proxyUtilsMod = require("./proxyUtils.cjs");
return _proxyUtilsMod;
}
let _sshAuthHelperMod = _isElectronRuntime ? null : require("./sshAuthHelper.cjs");
function getSshAuthHelper() {
if (!_sshAuthHelperMod) _sshAuthHelperMod = require("./sshAuthHelper.cjs");
return _sshAuthHelperMod;
}
const { NetcattyAgent } = require("./netcattyAgent.cjs");
const fileWatcherBridge = require("./fileWatcherBridge.cjs");
const keyboardInteractiveHandler = require("./keyboardInteractiveHandler.cjs");
const passphraseHandler = require("./passphraseHandler.cjs");
const hostKeyVerifier = require("./hostKeyVerifier.cjs");
const tempDirBridge = require("./tempDirBridge.cjs");
const { createProxySocket } = require("./proxyUtils.cjs");
const {
buildAuthHandler,
createKeyboardInteractiveHandler,
applyAuthToConnOpts,
shouldSkipKiPasswordAutoFill,
safeSend: authSafeSend,
isKeyEncrypted,
findAllDefaultPrivateKeys: findAllDefaultPrivateKeysFromHelper,
getAvailableAgentSocket,
prepareSystemSshAgentForAuth,
preparePrivateKeyForAuth,
loadFirstIdentityFileForAuth,
} = require("./sshAuthHelper.cjs");
const createProxySocket = (...args) => getProxyUtils().createProxySocket(...args);
const buildAuthHandler = (...args) => getSshAuthHelper().buildAuthHandler(...args);
const createKeyboardInteractiveHandler = (...args) => getSshAuthHelper().createKeyboardInteractiveHandler(...args);
const applyAuthToConnOpts = (...args) => getSshAuthHelper().applyAuthToConnOpts(...args);
const shouldSkipKiPasswordAutoFill = (...args) => getSshAuthHelper().shouldSkipKiPasswordAutoFill(...args);
const authSafeSend = (...args) => getSshAuthHelper().safeSend(...args);
const isKeyEncrypted = (...args) => getSshAuthHelper().isKeyEncrypted(...args);
const findAllDefaultPrivateKeysFromHelper = (...args) => getSshAuthHelper().findAllDefaultPrivateKeys(...args);
const getAvailableAgentSocket = (...args) => getSshAuthHelper().getAvailableAgentSocket(...args);
const prepareSystemSshAgentForAuth = (...args) => getSshAuthHelper().prepareSystemSshAgentForAuth(...args);
const preparePrivateKeyForAuth = (...args) => getSshAuthHelper().preparePrivateKeyForAuth(...args);
const loadFirstIdentityFileForAuth = (...args) => getSshAuthHelper().loadFirstIdentityFileForAuth(...args);
const {
buildSftpAlgorithms,
_resetAlgorithmSupportCacheForTests,
@@ -165,13 +205,13 @@ const encodePath = (input, encoding) => {
if (encoding === "utf-8") return input;
// Avoid Buffer paths when ASCII-only; keeps compatibility with unpatched ssh2
if (isAsciiString(input)) return input;
return iconv.encode(input, encoding);
return getIconv().encode(input, encoding);
};
const decodeName = (raw, encoding) => {
if (!raw) return "";
if (Buffer.isBuffer(raw)) {
return encoding === "utf-8" ? raw.toString("utf8") : iconv.decode(raw, encoding);
return encoding === "utf-8" ? raw.toString("utf8") : getIconv().decode(raw, encoding);
}
return raw;
};
@@ -2439,7 +2479,44 @@ function sendSftpProgress(sender, sessionId, label, status, detail) {
/**
* Connect through a chain of jump hosts for SFTP
*/
const { createOpenConnectionApi } = require("./sftpBridge/openConnection.cjs");
const _createOpenConnectionApi = _isElectronRuntime
? null
: require("./sftpBridge/openConnection.cjs").createOpenConnectionApi;
let _openConnectionApi = null;
function getOpenConnectionApi() {
if (!_openConnectionApi) {
const createOpenConnectionApi = _createOpenConnectionApi
|| require("./sftpBridge/openConnection.cjs").createOpenConnectionApi;
_openConnectionApi = createOpenConnectionApi({
get sftpClients() { return sftpClients; },
get sessions() { return sessions; },
get electronModule() { return electronModule; },
jumpConnectionsMap,
get SftpClient() { return getSftpClientCtor(); },
get SSHClient() { return getSshClientCtor(); },
get NetcattyAgent() { return getNetcattyAgentCtor(); },
keyboardInteractiveHandler, passphraseHandler,
hostKeyVerifier,
fs, path, net, Buffer, process, console, setTimeout, clearTimeout,
get SFTPWrapper() { return getSftpWrapper(); },
createProxySocket, buildSftpAlgorithms, getAvailableAgentSocket,
preparePrivateKeyForAuth, loadFirstIdentityFileForAuth, prepareSystemSshAgentForAuth, findAllDefaultPrivateKeysFromHelper,
buildAuthHandler, applyAuthToConnOpts, createKeyboardInteractiveHandler, shouldSkipKiPasswordAutoFill,
isKeyEncrypted, randomUUID,
sendSftpProgress, safeSend, authSafeSend, copySftpEncodingState, clearSftpEncodingState, normalizeEncoding,
resolveEncodingForRequest, updateResolvedEncoding, requireSftpChannel, realpathAsync,
connectSudoSftp: undefined,
acquireConnectionRef, releaseConnectionRef, findReusableSession, createSessionBackedSftpClient,
createTransport, borrowTransport, findTransportByEndpoint,
beginTransportDial, waitForTransportDial, completeTransportDial, failTransportDial,
buildEndpointKey,
buildChannelAdoptionKey,
buildConnectionReuseEndpoint,
resolveConnectionKeepalivePolicy,
});
}
return _openConnectionApi;
}
const {
acquireConnectionRef,
releaseConnectionRef,
@@ -2457,29 +2534,8 @@ const {
resolveConnectionKeepalivePolicy,
endpointAllowsReuse,
} = require("./sshConnectionPool.cjs");
const openConnectionApi = createOpenConnectionApi({
get sftpClients() { return sftpClients; },
get sessions() { return sessions; },
get electronModule() { return electronModule; },
jumpConnectionsMap, SftpClient, SSHClient, NetcattyAgent, keyboardInteractiveHandler, passphraseHandler,
hostKeyVerifier,
fs, path, net, Buffer, process, console, setTimeout, clearTimeout,
SFTPWrapper, createProxySocket, buildSftpAlgorithms, getAvailableAgentSocket,
preparePrivateKeyForAuth, loadFirstIdentityFileForAuth, prepareSystemSshAgentForAuth, findAllDefaultPrivateKeysFromHelper,
buildAuthHandler, applyAuthToConnOpts, createKeyboardInteractiveHandler, shouldSkipKiPasswordAutoFill, passphraseHandler,
isKeyEncrypted, randomUUID,
sendSftpProgress, safeSend, authSafeSend, copySftpEncodingState, clearSftpEncodingState, normalizeEncoding,
resolveEncodingForRequest, updateResolvedEncoding, requireSftpChannel, realpathAsync,
connectSudoSftp: undefined,
acquireConnectionRef, releaseConnectionRef, findReusableSession, createSessionBackedSftpClient,
createTransport, borrowTransport, findTransportByEndpoint,
beginTransportDial, waitForTransportDial, completeTransportDial, failTransportDial,
buildEndpointKey,
buildChannelAdoptionKey,
buildConnectionReuseEndpoint,
resolveConnectionKeepalivePolicy,
});
const { connectThroughChainForSftp, connectSudoSftp } = openConnectionApi;
const connectThroughChainForSftp = (...args) => getOpenConnectionApi().connectThroughChainForSftp(...args);
const connectSudoSftp = (...args) => getOpenConnectionApi().connectSudoSftp(...args);
async function openSftp(event, options) {
// The main SFTP page has no explicit terminal hint. Look for the original
// profile of a live, temporarily authenticated terminal before dialing.
@@ -2504,7 +2560,7 @@ async function openSftp(event, options) {
}
}
}
return openConnectionApi.openSftp(event, options);
return getOpenConnectionApi().openSftp(event, options);
}
const { createFileOpsApi } = require("./sftpBridge/fileOps.cjs");
const fileOpsApi = createFileOpsApi({
+200 -121
View File
@@ -10,53 +10,88 @@ const { randomUUID } = require("node:crypto");
const os = require("node:os");
const crypto = require("node:crypto");
const { exec } = require("node:child_process");
require("./boringSslDhCompat.cjs").installBoringSslDhCompat();
const { Client: SSHClient, utils: sshUtils } = require("ssh2");
const { NetcattyAgent } = require("./netcattyAgent.cjs");
let _ssh2 = null;
function getSsh2() {
if (!_ssh2) {
require("./boringSslDhCompat.cjs").installBoringSslDhCompat();
_ssh2 = require("ssh2");
}
return _ssh2;
}
if (!process.versions?.electron) {
getSsh2();
}
let _netcattyAgentCtor = null;
function getNetcattyAgentCtor() {
if (!_netcattyAgentCtor) ({ NetcattyAgent: _netcattyAgentCtor } = require("./netcattyAgent.cjs"));
return _netcattyAgentCtor;
}
const keyboardInteractiveHandler = require("./keyboardInteractiveHandler.cjs");
const passphraseHandler = require("./passphraseHandler.cjs");
const fidoPromptHandler = require("./fidoPromptHandler.cjs");
const hostKeyVerifier = require("./hostKeyVerifier.cjs");
const { createProxySocket, runWhenProxyConnectionReady } = require("./proxyUtils.cjs");
const { attachX11Forwarding } = require("./x11Forwarding.cjs");
let _proxyUtilsMod = null;
function getProxyUtils() {
if (!_proxyUtilsMod) _proxyUtilsMod = require("./proxyUtils.cjs");
return _proxyUtilsMod;
}
const createProxySocket = (...args) => getProxyUtils().createProxySocket(...args);
const runWhenProxyConnectionReady = (...args) => getProxyUtils().runWhenProxyConnectionReady(...args);
const attachX11Forwarding = (...args) => require("./x11Forwarding.cjs").attachX11Forwarding(...args);
const { createPtyOutputBuffer } = require("./ptyOutputBuffer.cjs");
const {
PREFERRED_KEY_NAMES,
SSH_KEY_PATTERN,
buildAuthHandler,
createKeyboardInteractiveHandler,
createOrderedStringAuthHandler,
createAuthPhase,
markAuthPhasePartialSuccess,
canRepeatKeyboardInteractive,
shouldSkipKiPasswordAutoFill,
applyAuthToConnOpts,
safeSend: authSafeSend,
requestPassphrasesForEncryptedKeys,
isKeyEncrypted,
findDefaultPrivateKey,
findAllDefaultPrivateKeys,
findAllDefaultPrivateKeys: findAllDefaultPrivateKeysFromHelper,
getSshAgentSocket,
getAvailableAgentSocket: getAvailableSystemAgentSocket,
getAvailableForwardingAgentSocket,
prepareSystemSshAgentForAuth,
readFileNoFollow,
expandIdentityFilePath,
isAutoFillablePasswordChallenge,
preparePrivateKeyForAuth,
loadIdentityFileForAuth,
loadFirstIdentityFileForAuth,
hasUserConfiguredKey,
isPasswordProvided,
looksLikeSkOpenSshMaterial,
identityFilesLookLikeSk,
PassphraseCancelledError,
isPassphraseCancelledError,
} = require("./sshAuthHelper.cjs");
const PREFERRED_KEY_NAMES = ["id_ed25519", "id_ecdsa", "id_rsa", "id_dsa"];
const SSH_KEY_PATTERN = /^id_[a-z0-9_-]+$/i;
let _sshAuthHelperMod = null;
function getSshAuthHelper() {
if (!_sshAuthHelperMod) _sshAuthHelperMod = require("./sshAuthHelper.cjs");
return _sshAuthHelperMod;
}
const buildAuthHandler = (...args) => getSshAuthHelper().buildAuthHandler(...args);
const createKeyboardInteractiveHandler = (...args) => getSshAuthHelper().createKeyboardInteractiveHandler(...args);
const createOrderedStringAuthHandler = (...args) => getSshAuthHelper().createOrderedStringAuthHandler(...args);
const createAuthPhase = (...args) => getSshAuthHelper().createAuthPhase(...args);
const markAuthPhasePartialSuccess = (...args) => getSshAuthHelper().markAuthPhasePartialSuccess(...args);
const canRepeatKeyboardInteractive = (...args) => getSshAuthHelper().canRepeatKeyboardInteractive(...args);
const shouldSkipKiPasswordAutoFill = (...args) => getSshAuthHelper().shouldSkipKiPasswordAutoFill(...args);
const applyAuthToConnOpts = (...args) => getSshAuthHelper().applyAuthToConnOpts(...args);
const authSafeSend = (...args) => getSshAuthHelper().safeSend(...args);
const requestPassphrasesForEncryptedKeys = (...args) => getSshAuthHelper().requestPassphrasesForEncryptedKeys(...args);
const isKeyEncrypted = (...args) => getSshAuthHelper().isKeyEncrypted(...args);
const findDefaultPrivateKey = (...args) => getSshAuthHelper().findDefaultPrivateKey(...args);
const findAllDefaultPrivateKeys = (...args) => getSshAuthHelper().findAllDefaultPrivateKeys(...args);
const findAllDefaultPrivateKeysFromHelper = (...args) => getSshAuthHelper().findAllDefaultPrivateKeys(...args);
const getSshAgentSocket = (...args) => getSshAuthHelper().getSshAgentSocket(...args);
const getAvailableSystemAgentSocket = (...args) => getSshAuthHelper().getAvailableAgentSocket(...args);
const getAvailableForwardingAgentSocket = (...args) => getSshAuthHelper().getAvailableForwardingAgentSocket(...args);
const prepareSystemSshAgentForAuth = (...args) => getSshAuthHelper().prepareSystemSshAgentForAuth(...args);
const readFileNoFollow = (...args) => getSshAuthHelper().readFileNoFollow(...args);
const expandIdentityFilePath = (...args) => getSshAuthHelper().expandIdentityFilePath(...args);
const isAutoFillablePasswordChallenge = (...args) => getSshAuthHelper().isAutoFillablePasswordChallenge(...args);
const preparePrivateKeyForAuth = (...args) => getSshAuthHelper().preparePrivateKeyForAuth(...args);
const loadIdentityFileForAuth = (...args) => getSshAuthHelper().loadIdentityFileForAuth(...args);
const loadFirstIdentityFileForAuth = (...args) => getSshAuthHelper().loadFirstIdentityFileForAuth(...args);
const hasUserConfiguredKey = (...args) => getSshAuthHelper().hasUserConfiguredKey(...args);
const isPasswordProvided = (...args) => getSshAuthHelper().isPasswordProvided(...args);
const looksLikeSkOpenSshMaterial = (...args) => getSshAuthHelper().looksLikeSkOpenSshMaterial(...args);
const identityFilesLookLikeSk = (...args) => getSshAuthHelper().identityFilesLookLikeSk(...args);
const isPassphraseCancelledError = (...args) => getSshAuthHelper().isPassphraseCancelledError(...args);
const sessionLogStreamManager = require("./sessionLogStreamManager.cjs");
const { trackSessionIdlePrompt, looksLikeIdleAutoLogout } = require("./ai/shellUtils.cjs");
const { createZmodemSentry, waitForWritableDrain } = require("./zmodemHelper.cjs");
let _shellUtilsMod = null;
function getShellUtils() {
if (!_shellUtilsMod) _shellUtilsMod = require("./ai/shellUtils.cjs");
return _shellUtilsMod;
}
const trackSessionIdlePrompt = (...args) => getShellUtils().trackSessionIdlePrompt(...args);
const looksLikeIdleAutoLogout = (...args) => getShellUtils().looksLikeIdleAutoLogout(...args);
let _zmodemHelperMod = null;
function getZmodemHelper() {
if (!_zmodemHelperMod) _zmodemHelperMod = require("./zmodemHelper.cjs");
return _zmodemHelperMod;
}
const createZmodemSentry = (...args) => getZmodemHelper().createZmodemSentry(...args);
const waitForWritableDrain = (...args) => getZmodemHelper().waitForWritableDrain(...args);
const tempDirBridge = require("./tempDirBridge.cjs");
const {
buildAlgorithms,
@@ -71,11 +106,13 @@ const {
const {
configureTerminalSessionDataEmitter,
} = require("./emitTerminalSessionData.cjs");
const {
createStartSessionApi,
cancelTestConnection,
resolveSshConnectionTimeouts,
} = require("./sshBridge/startSession.cjs");
let _startSessionMod = null;
function getStartSessionMod() {
if (!_startSessionMod) _startSessionMod = require("./sshBridge/startSession.cjs");
return _startSessionMod;
}
const cancelTestConnection = (...args) => getStartSessionMod().cancelTestConnection(...args);
const resolveSshConnectionTimeouts = (...args) => getStartSessionMod().resolveSshConnectionTimeouts(...args);
const { ensureMacLocalNetworkAccess, attachMacLocalNetworkProbeResult } = require("./macLocalNetworkAccess.cjs");
function quoteShellArg(value) {
@@ -261,7 +298,11 @@ const authMethodCache = createSshAuthMethodCache();
const sessionEncodings = new Map();
// Per-session stateful iconv decoders (keyed by sessionId, value: { stdout, stderr })
const sessionDecoders = new Map();
const iconv = require("iconv-lite");
let _iconv = null;
function getIconv() {
if (!_iconv) _iconv = require("iconv-lite");
return _iconv;
}
const { encodeTerminalInput, normalizeTerminalEncoding } = require("./terminalEncoding.cjs");
function getSessionDecoder(sessionId, stream) {
@@ -272,14 +313,14 @@ function getSessionDecoder(sessionId, stream) {
}
if (!decoders[stream]) {
const enc = sessionEncodings.get(sessionId) || "utf-8";
decoders[stream] = iconv.getDecoder(enc);
decoders[stream] = getIconv().getDecoder(enc);
}
return decoders[stream];
}
function resetSessionDecoders(sessionId) {
const enc = sessionEncodings.get(sessionId) || "utf-8";
const decoders = { stdout: iconv.getDecoder(enc), stderr: iconv.getDecoder(enc) };
const decoders = { stdout: getIconv().getDecoder(enc), stderr: getIconv().getDecoder(enc) };
sessionDecoders.set(sessionId, decoders);
}
@@ -397,6 +438,7 @@ async function connectThroughChain(event, options, jumpHosts, targetHost, target
sendProgress(i + 1, totalHops + 1, hopLabel, 'connecting');
const SSHClient = getSsh2().Client;
const conn = new SSHClient();
if (options?._tunnelRef) {
options._tunnelRef.pendingConn = conn;
@@ -565,6 +607,7 @@ async function connectThroughChain(event, options, jumpHosts, targetHost, target
require("./attachFidoAgentRelease.cjs").attachFidoAgentRelease(conn, systemAuthAgent);
}
if (hasCertificate && !forceJumpFidoAgent) {
const NetcattyAgent = getNetcattyAgentCtor();
authAgent = new NetcattyAgent({
mode: "certificate",
webContents: event.sender,
@@ -605,6 +648,7 @@ async function connectThroughChain(event, options, jumpHosts, targetHost, target
// key so buildAuthHandler won't try it and stall auth.
delete connOpts.privateKey;
if (result?.cancelled) {
const { PassphraseCancelledError } = getSshAuthHelper();
throw new PassphraseCancelledError(hopLabel);
}
}
@@ -860,45 +904,64 @@ async function connectThroughChain(event, options, jumpHosts, targetHost, target
/**
* Start an SSH session
*/
const startSessionApi = createStartSessionApi({
get sessions() { return sessions; },
get electronModule() { return electronModule; },
SSHClient, sshUtils, NetcattyAgent, keyboardInteractiveHandler, passphraseHandler, hostKeyVerifier,
quoteShellArg,
fs, path, os, net, crypto, Buffer, process, console, setTimeout, clearTimeout,
createProxySocket, attachX11Forwarding, createPtyOutputBuffer, sessionLogStreamManager,
trackSessionIdlePrompt, looksLikeIdleAutoLogout, createZmodemSentry, waitForWritableDrain, enableSshNoDelay, enableTcpNoDelay,
iconv, getSessionDecoder, resetSessionDecoders, sessionEncodings, sessionDecoders, encodeTerminalInput,
normalizeTerminalEncoding,
connectThroughChain, getAvailableAgentSocket, getAvailableForwardingAgentSocket, getCachedAuthMethod, setCachedAuthMethod, clearCachedAuthMethod,
attachSshDebugLogger, logSshAlgorithms, safeSend, zmodemOverwritePending,
shouldLogSshDebugMessage, log, createSshDiagnosticLogger,
buildAlgorithms, randomUUID, findDefaultPrivateKey, findAllDefaultPrivateKeys,
openTerminalOutputSession, closeTerminalOutputSession,
get selectZmodemUploadFiles() { return selectZmodemUploadFiles; },
get selectZmodemDownloadDirectory() { return selectZmodemDownloadDirectory; },
preparePrivateKeyForAuth, loadFirstIdentityFileForAuth, prepareSystemSshAgentForAuth, hasUserConfiguredKey, isPasswordProvided, createKeyboardInteractiveHandler, createOrderedStringAuthHandler, createAuthPhase, markAuthPhasePartialSuccess, canRepeatKeyboardInteractive, shouldSkipKiPasswordAutoFill,
createConnectionRef, acquireConnectionRef, releaseConnectionRef, transferConnectionRef,
consumePendingShellReconnectRisk, markEndpointNoIdlePark,
findReusableSession, findTransportByEndpoint, resolveTransportForReuse, discardAllTransports,
beginTransportDial, waitForTransportDial, completeTransportDial, failTransportDial,
buildConnectionReuseEndpoint,
resolveConnectionKeepalivePolicy,
normalizeEndpoint,
get probeReceiveConflicts() { return probeReceiveConflicts; },
get removeRemoteFiles() { return removeRemoteFiles; },
get restoreRemoteModes() { return restoreRemoteModes; },
});
const { startSSHSession } = startSessionApi;
const { createExecCommandApi } = require("./sshBridge/execCommand.cjs");
const execCommandApi = createExecCommandApi({
SSHClient, NetcattyAgent, randomUUID, console, setTimeout, clearTimeout, Error,
findAllDefaultPrivateKeysFromHelper, preparePrivateKeyForAuth, loadIdentityFileForAuth,
prepareSystemSshAgentForAuth, getAvailableAgentSocket,
isPassphraseCancelledError, buildAlgorithms, buildAuthHandler, applyAuthToConnOpts,
createKeyboardInteractiveHandler, shouldSkipKiPasswordAutoFill, resolveSshConnectionTimeouts,
});
const { execCommand } = execCommandApi;
let _startSessionApi = null;
function getStartSessionApi() {
if (!_startSessionApi) {
_startSessionApi = getStartSessionMod().createStartSessionApi({
get sessions() { return sessions; },
get electronModule() { return electronModule; },
get SSHClient() { return getSsh2().Client; },
get sshUtils() { return getSsh2().utils; },
get NetcattyAgent() { return getNetcattyAgentCtor(); },
get iconv() { return getIconv(); },
keyboardInteractiveHandler, passphraseHandler, hostKeyVerifier,
quoteShellArg,
fs, path, os, net, crypto, Buffer, process, console, setTimeout, clearTimeout,
createProxySocket, attachX11Forwarding, createPtyOutputBuffer, sessionLogStreamManager,
trackSessionIdlePrompt, looksLikeIdleAutoLogout, createZmodemSentry, waitForWritableDrain, enableSshNoDelay, enableTcpNoDelay,
getSessionDecoder, resetSessionDecoders, sessionEncodings, sessionDecoders, encodeTerminalInput,
normalizeTerminalEncoding,
connectThroughChain, getAvailableAgentSocket, getAvailableForwardingAgentSocket, getCachedAuthMethod, setCachedAuthMethod, clearCachedAuthMethod,
attachSshDebugLogger, logSshAlgorithms, safeSend, zmodemOverwritePending,
shouldLogSshDebugMessage, log, createSshDiagnosticLogger,
buildAlgorithms, randomUUID, findDefaultPrivateKey, findAllDefaultPrivateKeys,
openTerminalOutputSession, closeTerminalOutputSession,
get selectZmodemUploadFiles() { return selectZmodemUploadFiles; },
get selectZmodemDownloadDirectory() { return selectZmodemDownloadDirectory; },
preparePrivateKeyForAuth, loadFirstIdentityFileForAuth, prepareSystemSshAgentForAuth, hasUserConfiguredKey, isPasswordProvided, createKeyboardInteractiveHandler, createOrderedStringAuthHandler, createAuthPhase, markAuthPhasePartialSuccess, canRepeatKeyboardInteractive, shouldSkipKiPasswordAutoFill,
createConnectionRef, acquireConnectionRef, releaseConnectionRef, transferConnectionRef,
consumePendingShellReconnectRisk, markEndpointNoIdlePark,
findReusableSession, findTransportByEndpoint, resolveTransportForReuse, discardAllTransports,
beginTransportDial, waitForTransportDial, completeTransportDial, failTransportDial,
buildConnectionReuseEndpoint,
resolveConnectionKeepalivePolicy,
normalizeEndpoint,
get probeReceiveConflicts() { return probeReceiveConflicts; },
get removeRemoteFiles() { return removeRemoteFiles; },
get restoreRemoteModes() { return restoreRemoteModes; },
});
}
return _startSessionApi;
}
const startSSHSession = (...args) => getStartSessionApi().startSSHSession(...args);
let _execCommandApi = null;
function getExecCommandApi() {
if (!_execCommandApi) {
const { createExecCommandApi } = require("./sshBridge/execCommand.cjs");
_execCommandApi = createExecCommandApi({
get SSHClient() { return getSsh2().Client; },
get NetcattyAgent() { return getNetcattyAgentCtor(); },
randomUUID, console, setTimeout, clearTimeout, Error,
findAllDefaultPrivateKeysFromHelper, preparePrivateKeyForAuth, loadIdentityFileForAuth,
prepareSystemSshAgentForAuth, getAvailableAgentSocket,
isPassphraseCancelledError, buildAlgorithms, buildAuthHandler, applyAuthToConnOpts,
createKeyboardInteractiveHandler, shouldSkipKiPasswordAutoFill, resolveSshConnectionTimeouts,
});
}
return _execCommandApi;
}
const execCommand = (...args) => getExecCommandApi().execCommand(...args);
/**
* Generate SSH key pair
@@ -945,7 +1008,7 @@ async function generateKeyPair(event, options) {
break;
}
const result = sshUtils.generateKeyPairSync(keyType, {
const result = getSsh2().utils.generateKeyPairSync(keyType, {
bits: keyBits,
comment: comment || 'netcatty-generated-key',
});
@@ -1328,40 +1391,56 @@ const { isHostKeyTrustedBySystem } = createSystemKnownHostsApi({
fs, path, os, crypto, log,
});
const { createMoshStatsConnectionApi } = require("./sshBridge/moshStatsConnection.cjs");
const { ensureMoshStatsConnection, ensureEtStatsConnection } = createMoshStatsConnectionApi({
get sessions() { return sessions; },
SSHClient, sshUtils, NetcattyAgent, buildAlgorithms, getSshAgentSocket, prepareSystemSshAgentForAuth,
readFileNoFollow, expandIdentityFilePath, isAutoFillablePasswordChallenge,
hostKeyVerifier, isHostKeyTrustedBySystem, log,
});
let _moshStatsApi = null;
function getMoshStatsApi() {
if (!_moshStatsApi) {
const { createMoshStatsConnectionApi } = require("./sshBridge/moshStatsConnection.cjs");
_moshStatsApi = createMoshStatsConnectionApi({
get sessions() { return sessions; },
get SSHClient() { return getSsh2().Client; },
get sshUtils() { return getSsh2().utils; },
get NetcattyAgent() { return getNetcattyAgentCtor(); },
buildAlgorithms, getSshAgentSocket, prepareSystemSshAgentForAuth,
readFileNoFollow, expandIdentityFilePath, isAutoFillablePasswordChallenge,
hostKeyVerifier, isHostKeyTrustedBySystem, log,
});
}
return _moshStatsApi;
}
const ensureMoshStatsConnection = (...args) => getMoshStatsApi().ensureMoshStatsConnection(...args);
const ensureEtStatsConnection = (...args) => getMoshStatsApi().ensureEtStatsConnection(...args);
const { createSessionOpsApi } = require("./sshBridge/sessionOps.cjs");
const measureSshPingLatency = createSshPingLatencyProbe();
const sessionOpsApi = createSessionOpsApi({
get sessions() { return sessions; },
get electronModule() { return electronModule; },
fs, path, os, exec, randomUUID, iconv, Buffer, process, console, setTimeout, clearTimeout,
getSessionDecoder, resetSessionDecoders, sessionEncodings, normalizeTerminalEncoding,
safeSend,
quoteShellArg, log, ensureMoshStatsConnection, ensureEtStatsConnection,
measureSshPingLatency,
execOnEtSession: (...args) => require("./terminalBridge.cjs").execOnEtSession(...args),
getServerStats: undefined,
});
const {
getStatsForContext,
getSessionRemoteInfo,
getSessionDistroInfo,
readRemoteHistory,
getSessionPwd,
probeReceiveConflicts,
removeRemoteFiles,
restoreRemoteModes,
listSessionDir,
getServerStats,
setSessionEncoding,
} = sessionOpsApi;
let _sessionOpsApi = null;
function getSessionOpsApi() {
if (!_sessionOpsApi) {
const { createSessionOpsApi } = require("./sshBridge/sessionOps.cjs");
_sessionOpsApi = createSessionOpsApi({
get sessions() { return sessions; },
get electronModule() { return electronModule; },
get iconv() { return getIconv(); },
fs, path, os, exec, randomUUID, Buffer, process, console, setTimeout, clearTimeout,
getSessionDecoder, resetSessionDecoders, sessionEncodings, normalizeTerminalEncoding,
safeSend,
quoteShellArg, log, ensureMoshStatsConnection, ensureEtStatsConnection,
measureSshPingLatency,
execOnEtSession: (...args) => require("./terminalBridge.cjs").execOnEtSession(...args),
getServerStats: undefined,
});
}
return _sessionOpsApi;
}
const getStatsForContext = (...args) => getSessionOpsApi().getStatsForContext(...args);
const getSessionRemoteInfo = (...args) => getSessionOpsApi().getSessionRemoteInfo(...args);
const getSessionDistroInfo = (...args) => getSessionOpsApi().getSessionDistroInfo(...args);
const readRemoteHistory = (...args) => getSessionOpsApi().readRemoteHistory(...args);
const getSessionPwd = (...args) => getSessionOpsApi().getSessionPwd(...args);
const probeReceiveConflicts = (...args) => getSessionOpsApi().probeReceiveConflicts(...args);
const removeRemoteFiles = (...args) => getSessionOpsApi().removeRemoteFiles(...args);
const restoreRemoteModes = (...args) => getSessionOpsApi().restoreRemoteModes(...args);
const listSessionDir = (...args) => getSessionOpsApi().listSessionDir(...args);
const getServerStats = (...args) => getSessionOpsApi().getServerStats(...args);
const setSessionEncoding = (...args) => getSessionOpsApi().setSessionEncoding(...args);
const { createMonitorService } = require("./monitorBridge.cjs");
const monitorService = createMonitorService({ startConnection: startSSHSession, cancelConnection: cancelTestConnection, getStats: getStatsForContext,
+39 -37
View File
@@ -1,13 +1,6 @@
"use strict";
const { createExecOnSessionApi } = require("./systemManager/execOnSession.cjs");
const { createTmuxOpsApi } = require("./systemManager/tmuxOps.cjs");
const { createDockerOpsApi } = require("./systemManager/dockerOps.cjs");
const { createKubectlOpsApi } = require("./systemManager/kubectlOps.cjs");
const { parseRuntimeProbe } = require("../../domain/systemManager/containerRuntime.shared.cjs");
const { createGpuOpsApi } = require("./systemManager/gpuOps.cjs");
const { createPortOpsApi } = require("./systemManager/portOps.cjs");
const { createServiceOpsApi } = require("./systemManager/serviceOps.cjs");
const { registerWorkerHandle } = require("./workerIpcProxy.cjs");
function nerdctlUsableClause(markCommand) {
@@ -202,30 +195,39 @@ function createSystemManagerBridge(deps) {
process,
} = deps;
const execApi = createExecOnSessionApi({
let _execApi = null;
const getExecApi = () => (_execApi ??= require("./systemManager/execOnSession.cjs").createExecOnSessionApi({
sessions: { get: (id) => getSessions()?.get(id) },
execOnEtSession,
ensureMoshStatsConnection,
});
}));
const execOnSession = (...args) => getExecApi().execOnSession(...args);
const execOnLocalMachine = (...args) => getExecApi().execOnLocalMachine(...args);
const isLocalSession = (...args) => getExecApi().isLocalSession(...args);
const getSession = (...args) => getExecApi().getSession(...args);
const { execOnSession, execOnLocalMachine, isLocalSession, getSession } = execApi;
const tmuxOps = createTmuxOpsApi({ execOnSession });
const dockerOps = createDockerOpsApi({ execOnSession, getSession });
const kubectlOps = createKubectlOpsApi({ execOnSession, isLocalSession, process });
const gpuOps = createGpuOpsApi({
let _tmuxOps = null;
const getTmuxOps = () => (_tmuxOps ??= require("./systemManager/tmuxOps.cjs").createTmuxOpsApi({ execOnSession }));
let _dockerOps = null;
const getDockerOps = () => (_dockerOps ??= require("./systemManager/dockerOps.cjs").createDockerOpsApi({ execOnSession, getSession }));
let _kubectlOps = null;
const getKubectlOps = () => (_kubectlOps ??= require("./systemManager/kubectlOps.cjs").createKubectlOpsApi({ execOnSession, isLocalSession, process }));
let _gpuOps = null;
const getGpuOps = () => (_gpuOps ??= require("./systemManager/gpuOps.cjs").createGpuOpsApi({
execOnSession,
execOnLocalMachine,
isLocalSession,
process,
});
const portOps = createPortOpsApi({
}));
let _portOps = null;
const getPortOps = () => (_portOps ??= require("./systemManager/portOps.cjs").createPortOpsApi({
execOnSession,
execOnLocalMachine,
isLocalSession,
process,
});
const serviceOps = createServiceOpsApi({ execOnSession, getSession });
}));
let _serviceOps = null;
const getServiceOps = () => (_serviceOps ??= require("./systemManager/serviceOps.cjs").createServiceOpsApi({ execOnSession, getSession }));
async function probeCapabilities(event, payload) {
const sessionId = payload?.sessionId;
@@ -430,27 +432,27 @@ function createSystemManagerBridge(deps) {
async function listTmuxSessions(event, payload) {
const sessionId = typeof payload === "string" ? payload : payload?.sessionId;
if (!sessionId) return { success: false, error: "Missing sessionId" };
return tmuxOps.listSessions(event, sessionId);
return getTmuxOps().listSessions(event, sessionId);
}
async function createTmuxSession(event, payload) {
return tmuxOps.createSession(event, payload);
return getTmuxOps().createSession(event, payload);
}
async function listTmuxWindows(event, payload) {
return tmuxOps.listWindows(event, payload);
return getTmuxOps().listWindows(event, payload);
}
async function listTmuxPanes(event, payload) {
return tmuxOps.listPanes(event, payload);
return getTmuxOps().listPanes(event, payload);
}
async function listTmuxClients(event, payload) {
return tmuxOps.listClients(event, payload);
return getTmuxOps().listClients(event, payload);
}
async function tmuxAction(event, payload) {
const result = await tmuxOps.tmuxAction(event, payload);
const result = await getTmuxOps().tmuxAction(event, payload);
if (result.success === false && result.error) {
return { success: false, error: result.error || result.stderr };
}
@@ -463,29 +465,29 @@ function createSystemManagerBridge(deps) {
async function listDockerContainers(event, payload) {
const sessionId = payload?.sessionId;
if (!sessionId) return { success: false, error: "Missing sessionId" };
return dockerOps.listContainers(event, sessionId, payload?.runtime);
return getDockerOps().listContainers(event, sessionId, payload?.runtime);
}
async function listDockerImages(event, payload) {
const sessionId = payload?.sessionId;
if (!sessionId) return { success: false, error: "Missing sessionId" };
return dockerOps.listImages(event, sessionId, payload?.runtime);
return getDockerOps().listImages(event, sessionId, payload?.runtime);
}
async function dockerStats(event, payload) {
return dockerOps.getStats(event, payload);
return getDockerOps().getStats(event, payload);
}
async function dockerInspect(event, payload) {
return dockerOps.inspectContainer(event, payload);
return getDockerOps().inspectContainer(event, payload);
}
async function dockerImageInspect(event, payload) {
return dockerOps.inspectImage(event, payload);
return getDockerOps().inspectImage(event, payload);
}
async function dockerAction(event, payload) {
const result = await dockerOps.containerAction(event, payload);
const result = await getDockerOps().containerAction(event, payload);
if (result.success === false) {
if (result.errorCode === "nerdctlUnreachable") {
return { success: false, errorCode: result.errorCode };
@@ -496,11 +498,11 @@ function createSystemManagerBridge(deps) {
}
async function kubectl(event, payload) {
return kubectlOps.run(event, payload);
return getKubectlOps().run(event, payload);
}
async function dockerImageAction(event, payload) {
const result = await dockerOps.imageAction(event, payload);
const result = await getDockerOps().imageAction(event, payload);
if (result.success === false) {
if (result.errorCode === "nerdctlUnreachable") {
return { success: false, errorCode: result.errorCode };
@@ -513,23 +515,23 @@ function createSystemManagerBridge(deps) {
async function listAccelerators(event, payload) {
const sessionId = payload?.sessionId;
if (!sessionId) return { success: false, error: "Missing sessionId" };
return gpuOps.listAccelerators(event, sessionId);
return getGpuOps().listAccelerators(event, sessionId);
}
async function listListeningPorts(event, payload) {
const sessionId = payload?.sessionId;
if (!sessionId) return { success: false, error: "Missing sessionId" };
return portOps.listListeningPorts(event, sessionId);
return getPortOps().listListeningPorts(event, sessionId);
}
async function listSystemServices(event, payload) {
const sessionId = payload?.sessionId;
if (!sessionId) return { success: false, error: "Missing sessionId" };
return serviceOps.listServices(event, sessionId);
return getServiceOps().listServices(event, sessionId);
}
async function systemServiceAction(event, payload) {
return serviceOps.serviceAction(event, payload);
return getServiceOps().serviceAction(event, payload);
}
function registerHandlers(ipcMain, options = {}) {
+150 -85
View File
@@ -15,15 +15,29 @@ const { ensureNodePtySpawnHelperExecutable } = require("./nodePtySpawnHelperPerm
const { createTerminalFlowPauseArbiter } = require("./terminalFlowPauseArbiter.cjs");
const { registerWorkerHandle } = require("./workerIpcProxy.cjs");
ensureNodePtySpawnHelperExecutable();
const isElectronRuntime = Boolean(process.versions?.electron);
const terminalFlowPauseArbiter = createTerminalFlowPauseArbiter();
const trackedFlowPauseSenders = new WeakSet();
const pty = require("node-pty");
const { SerialPort } = require("serialport");
function getPty() { return pty; }
function getSerialPort() { return SerialPort; }
let _pty = null;
let _serialPort = null;
if (!isElectronRuntime) {
ensureNodePtySpawnHelperExecutable();
_pty = require("node-pty");
({ SerialPort: _serialPort } = require("serialport"));
}
function getPty() {
if (!_pty) {
ensureNodePtySpawnHelperExecutable();
_pty = require("node-pty");
}
return _pty;
}
function getSerialPort() {
if (!_serialPort) ({ SerialPort: _serialPort } = require("serialport"));
return _serialPort;
}
const { createSerialTransport } = require("./serialNamedPipe.cjs");
const {
configureTerminalSessionDataEmitter,
@@ -55,16 +69,31 @@ const {
stashPendingInterruptOutputMeta,
takePendingInterruptOutputMeta,
} = require("./terminalInterruptOutputGate.cjs");
const iconv = require("iconv-lite");
let _iconv = null;
function getIconv() {
if (!_iconv) _iconv = require("iconv-lite");
return _iconv;
}
const ptyProcessTree = require("./ptyProcessTree.cjs");
const sessionLogStreamManager = require("./sessionLogStreamManager.cjs");
const { detectShellKind } = require("./ai/ptyExec.cjs");
const { stripAnsi, trackSessionIdlePrompt } = require("./ai/shellUtils.cjs");
let _ptyExecHelpers = null;
const detectShellKind = (...args) => (_ptyExecHelpers ??= require("./ai/ptyExecHelpers.cjs")).detectShellKind(...args);
let _shellUtils = null;
function getShellUtils() {
if (!_shellUtils) _shellUtils = require("./ai/shellUtils.cjs");
return _shellUtils;
}
const stripAnsi = (...args) => getShellUtils().stripAnsi(...args);
const trackSessionIdlePrompt = (...args) => getShellUtils().trackSessionIdlePrompt(...args);
const { createZmodemSentry } = require("./zmodemHelper.cjs");
const { discoverShells } = require("./shellDiscovery.cjs");
const { isWindowsAppExecutionAliasPath } = require("../../lib/localShell.cjs");
const moshHandshake = require("./moshHandshake.cjs");
let _moshHandshake = null;
function getMoshHandshake() {
if (!_moshHandshake) _moshHandshake = require("./moshHandshake.cjs");
return _moshHandshake;
}
const tempDirBridge = require("./tempDirBridge.cjs");
const { preparePowerShellDirectoryIntegration } = require('./powerShellDirectoryIntegration.cjs');
const { prepareCmdDirectoryIntegration } = require('./cmdDirectoryIntegration.cjs');
@@ -77,11 +106,14 @@ const { releaseConnectionRef } = require("./sshConnectionPool.cjs");
const { normalizeTerminalEncoding, encodeTerminalInput, expandSerialBackspace } = require("./terminalEncoding.cjs");
const { isTerminalReportSequence } = require("./terminalReportSequence.cjs");
const { receiveYmodemFiles, sendYmodemCancel, sendYmodemFile } = require("./ymodemTransfer.cjs");
const {
getNativeOpenSshAgentSocket,
getNativeOpenSshForwardingAgentSocket,
prepareSystemSshAgentForAuth,
} = require("./sshAuthHelper.cjs");
let _sshAuthHelper = null;
function getSshAuthHelper() {
if (!_sshAuthHelper) _sshAuthHelper = require("./sshAuthHelper.cjs");
return _sshAuthHelper;
}
const getNativeOpenSshAgentSocket = (...args) => getSshAuthHelper().getNativeOpenSshAgentSocket(...args);
const getNativeOpenSshForwardingAgentSocket = (...args) => getSshAuthHelper().getNativeOpenSshForwardingAgentSocket(...args);
const prepareSystemSshAgentForAuth = (...args) => getSshAuthHelper().prepareSystemSshAgentForAuth(...args);
const execFileAsync = promisify(execFile);
@@ -1315,86 +1347,119 @@ async function startLocalSession(event, payload) {
/**
* Start a Telnet session using native Node.js net module
*/
const { createTelnetSessionApi } = require("./terminalBridge/telnetSession.cjs");
const telnetSessionApi = createTelnetSessionApi({
get sessions() { return sessions; },
get electronModule() { return electronModule; },
net, randomUUID, StringDecoder, iconv, Buffer, console, setTimeout, clearTimeout,
normalizeTerminalEncoding, encodeTerminalInput, createTelnetAutoLogin, telnetProtocol,
createPtyOutputBuffer, sessionLogStreamManager, createZmodemSentry, ptyProcessTree,
enableTcpNoDelay, trackSessionIdlePrompt, stripAnsi, clearPendingAutomatedWrites,
openTerminalOutputSession, closeTerminalOutputSession,
get selectZmodemUploadFiles() { return selectZmodemUploadFiles; },
get selectZmodemDownloadDirectory() { return selectZmodemDownloadDirectory; },
});
const { startTelnetSession } = telnetSessionApi;
let _telnetSessionApi = null;
function getTelnetSessionApi() {
if (!_telnetSessionApi) {
const { createTelnetSessionApi } = require("./terminalBridge/telnetSession.cjs");
_telnetSessionApi = createTelnetSessionApi({
get sessions() { return sessions; },
get electronModule() { return electronModule; },
get iconv() { return getIconv(); },
net, randomUUID, StringDecoder, Buffer, console, setTimeout, clearTimeout,
normalizeTerminalEncoding, encodeTerminalInput, createTelnetAutoLogin, telnetProtocol,
createPtyOutputBuffer, sessionLogStreamManager, createZmodemSentry, ptyProcessTree,
enableTcpNoDelay, trackSessionIdlePrompt, stripAnsi, clearPendingAutomatedWrites,
openTerminalOutputSession, closeTerminalOutputSession,
get selectZmodemUploadFiles() { return selectZmodemUploadFiles; },
get selectZmodemDownloadDirectory() { return selectZmodemDownloadDirectory; },
});
}
return _telnetSessionApi;
}
const startTelnetSession = (...args) => getTelnetSessionApi().startTelnetSession(...args);
/**
* Resolve Netcatty's bundled bare `mosh-client` binary.
*
* Returns the absolute path or null.
*/
const { createMoshSessionApi } = require("./terminalBridge/moshSession.cjs");
const moshSessionApi = createMoshSessionApi({
get sessions() { return sessions; },
get electronModule() { return electronModule; },
get pty() { return getPty(); },
os, fs, net, path, iconv, Buffer, StringDecoder, process, console,
setTimeout, clearTimeout, setInterval, clearInterval,
randomUUID, execFileAsync, ptyProcessTree, sessionLogStreamManager,
stripAnsi, trackSessionIdlePrompt, createZmodemSentry, moshHandshake, tempDirBridge,
createPtyOutputBuffer, enableTcpNoDelay, normalizeTerminalEncoding,
resolvePosixExecutable, findExecutable, isExecutableFile,
openTerminalOutputSession, closeTerminalOutputSession,
get selectZmodemUploadFiles() { return selectZmodemUploadFiles; },
get selectZmodemDownloadDirectory() { return selectZmodemDownloadDirectory; },
ensureMoshStatsConnection: (...args) => require("./sshBridge.cjs").ensureMoshStatsConnection(...args),
getAvailableAgentSocket: getNativeOpenSshAgentSocket,
getAvailableForwardingAgentSocket: getNativeOpenSshForwardingAgentSocket,
prepareSystemSshAgentForAuth,
bundledMoshClient: (...args) => bundledMoshClient(...args),
});
const {
resolveBareMoshClient,
addBundledMoshRuntimeEnv,
createMoshUtf8Decoder,
buildMoshSshAuthArgs,
cleanupMoshAuthTempFiles,
startMoshSessionViaHandshake,
swapToMoshClient,
resolveLangFromCharsetForMosh,
startMoshSession,
} = moshSessionApi;
let _moshSessionApi = null;
function getMoshSessionApi() {
if (!_moshSessionApi) {
const { createMoshSessionApi } = require("./terminalBridge/moshSession.cjs");
_moshSessionApi = createMoshSessionApi({
get sessions() { return sessions; },
get electronModule() { return electronModule; },
get pty() { return getPty(); },
get iconv() { return getIconv(); },
get moshHandshake() { return getMoshHandshake(); },
os, fs, net, path, Buffer, StringDecoder, process, console,
setTimeout, clearTimeout, setInterval, clearInterval,
randomUUID, execFileAsync, ptyProcessTree, sessionLogStreamManager,
stripAnsi, trackSessionIdlePrompt, createZmodemSentry, tempDirBridge,
createPtyOutputBuffer, enableTcpNoDelay, normalizeTerminalEncoding,
resolvePosixExecutable, findExecutable, isExecutableFile,
openTerminalOutputSession, closeTerminalOutputSession,
get selectZmodemUploadFiles() { return selectZmodemUploadFiles; },
get selectZmodemDownloadDirectory() { return selectZmodemDownloadDirectory; },
ensureMoshStatsConnection: (...args) => require("./sshBridge.cjs").ensureMoshStatsConnection(...args),
getAvailableAgentSocket: getNativeOpenSshAgentSocket,
getAvailableForwardingAgentSocket: getNativeOpenSshForwardingAgentSocket,
prepareSystemSshAgentForAuth,
bundledMoshClient: (...args) => bundledMoshClient(...args),
});
}
return _moshSessionApi;
}
const resolveBareMoshClient = (...args) => getMoshSessionApi().resolveBareMoshClient(...args);
const addBundledMoshRuntimeEnv = (...args) => getMoshSessionApi().addBundledMoshRuntimeEnv(...args);
const createMoshUtf8Decoder = (...args) => getMoshSessionApi().createMoshUtf8Decoder(...args);
const buildMoshSshAuthArgs = (...args) => getMoshSessionApi().buildMoshSshAuthArgs(...args);
const cleanupMoshAuthTempFiles = (...args) => getMoshSessionApi().cleanupMoshAuthTempFiles(...args);
const startMoshSessionViaHandshake = (...args) => getMoshSessionApi().startMoshSessionViaHandshake(...args);
const swapToMoshClient = (...args) => getMoshSessionApi().swapToMoshClient(...args);
const resolveLangFromCharsetForMosh = (...args) => getMoshSessionApi().resolveLangFromCharsetForMosh(...args);
const startMoshSession = (...args) => getMoshSessionApi().startMoshSession(...args);
/**
* EternalTerminal session API. `et` is a self-contained client that performs
* its own SSH bootstrap + ET protocol handshake, so Netcatty just spawns the
* bundled `et` binary as a PTY (no Node handshake wrapper like Mosh needs).
*/
const { createEtSessionApi } = require("./terminalBridge/etSession.cjs");
const etSessionApi = createEtSessionApi({
get sessions() { return sessions; },
get electronModule() { return electronModule; },
get pty() { return getPty(); },
os, fs, path, process, console,
randomUUID, execFile, execFileSync, StringDecoder,
sessionLogStreamManager, tempDirBridge,
createZmodemSentry, trackSessionIdlePrompt, createPtyOutputBuffer,
findExecutable,
openTerminalOutputSession, closeTerminalOutputSession,
getAvailableAgentSocket: getNativeOpenSshAgentSocket,
getAvailableForwardingAgentSocket: getNativeOpenSshForwardingAgentSocket,
prepareSystemSshAgentForAuth,
get selectZmodemUploadFiles() { return selectZmodemUploadFiles; },
get selectZmodemDownloadDirectory() { return selectZmodemDownloadDirectory; },
bundledEtClient: (...args) => bundledEtClient(...args),
});
const {
startEtSession,
execOnEtSession,
cleanupStaleEtTempDirs,
cleanupSessionExternalAuthArtifacts,
} = etSessionApi;
let _etSessionApi = null;
function getEtSessionApi() {
if (!_etSessionApi) {
const { createEtSessionApi } = require("./terminalBridge/etSession.cjs");
_etSessionApi = createEtSessionApi({
get sessions() { return sessions; },
get electronModule() { return electronModule; },
get pty() { return getPty(); },
os, fs, path, process, console,
randomUUID, execFile, execFileSync, StringDecoder,
sessionLogStreamManager, tempDirBridge,
createZmodemSentry, trackSessionIdlePrompt, createPtyOutputBuffer,
findExecutable,
openTerminalOutputSession, closeTerminalOutputSession,
getAvailableAgentSocket: getNativeOpenSshAgentSocket,
getAvailableForwardingAgentSocket: getNativeOpenSshForwardingAgentSocket,
prepareSystemSshAgentForAuth,
get selectZmodemUploadFiles() { return selectZmodemUploadFiles; },
get selectZmodemDownloadDirectory() { return selectZmodemDownloadDirectory; },
bundledEtClient: (...args) => bundledEtClient(...args),
});
}
return _etSessionApi;
}
const startEtSession = (...args) => getEtSessionApi().startEtSession(...args);
const execOnEtSession = (...args) => getEtSessionApi().execOnEtSession(...args);
function cleanupStaleEtTempDirs() {
try {
const tempDir = tempDirBridge.getTempDir();
if (!fs.existsSync(tempDir)) return;
const entries = fs.readdirSync(tempDir);
for (const entry of entries) {
if (!entry.startsWith("et-ssh-home-")) continue;
try {
fs.rmSync(path.join(tempDir, entry), { recursive: true, force: true });
} catch {
// ignore per-entry cleanup failures
}
}
} catch {
// ignore — best-effort cleanup
}
}
const cleanupSessionExternalAuthArtifacts = (...args) => getEtSessionApi().cleanupSessionExternalAuthArtifacts(...args);
/**
* List available serial ports (hardware only)
@@ -1500,7 +1565,7 @@ async function startSerialSession(event, options) {
console.log(`[Serial] Connected to ${portPath}`);
const initialSerialEncoding = normalizeTerminalEncoding(options.charset);
const serialDecoderRef = { current: iconv.getDecoder(initialSerialEncoding) };
const serialDecoderRef = { current: getIconv().getDecoder(initialSerialEncoding) };
const session = {
serialPort,
@@ -2552,7 +2617,7 @@ function setSessionEncoding(_event, { sessionId, encoding }) {
return { ok: false, encoding: encoding || 'utf-8' };
}
const enc = normalizeTerminalEncoding(encoding);
if (!iconv.encodingExists(enc)) {
if (!getIconv().encodingExists(enc)) {
return { ok: false, encoding: enc };
}
session.encoding = enc;
@@ -2563,7 +2628,7 @@ function setSessionEncoding(_event, { sessionId, encoding }) {
}
// iconv stateful decoders carry partial-byte state from the previous
// encoding, so swap in a fresh decoder rather than reconfiguring.
session.decoderRef.current = iconv.getDecoder(enc);
session.decoderRef.current = getIconv().getDecoder(enc);
return { ok: true, encoding: enc };
}
+10 -6
View File
@@ -13,7 +13,11 @@
* with the *same* charset closes that gap.
*/
const iconv = require("iconv-lite");
let _iconv = null;
function getIconv() {
if (!_iconv) _iconv = require("iconv-lite");
return _iconv;
}
// Normalize user-facing charset names into an iconv-lite encoding identifier.
// iconv-lite accepts a wide range of aliases directly ("utf-8", "gbk", etc.),
@@ -32,7 +36,7 @@ function normalizeTerminalEncoding(charset) {
if (["gb18030", "gbk", "gb2312", "cp936", "ms936"].includes(normalized)) {
return "gb18030";
}
if (iconv.encodingExists(candidate)) return candidate;
if (getIconv().encodingExists(candidate)) return candidate;
}
return "utf-8";
@@ -67,8 +71,8 @@ function isAsciiCompatibleEncoding(encoding) {
try {
// \r and ESC cover the control bytes we care about; a single C0 probe is
// enough since ASCII-incompatible encodings widen every code point.
const cr = iconv.encode("\r", encoding);
const esc = iconv.encode("\x1b", encoding);
const cr = getIconv().encode("\r", encoding);
const esc = getIconv().encode("\x1b", encoding);
compatible = cr.length === 1 && cr[0] === 0x0d && esc.length === 1 && esc[0] === 0x1b;
} catch {
compatible = false;
@@ -95,9 +99,9 @@ function isAsciiCompatibleEncoding(encoding) {
function encodeTerminalInput(data, encoding) {
if (typeof data !== "string") return data;
if (isUtf8Encoding(encoding)) return data;
if (!iconv.encodingExists(encoding)) return data;
if (!getIconv().encodingExists(encoding)) return data;
if (!isAsciiCompatibleEncoding(encoding)) return data;
return iconv.encode(data, encoding);
return getIconv().encode(data, encoding);
}
// Only expand a single Backspace. Other input (including plugin replacements)
+4 -2
View File
@@ -1,6 +1,5 @@
"use strict";
const jsQR = require("jsqr");
const {
previewTotpText,
selectTotpFromQrPayloads,
@@ -142,7 +141,10 @@ async function scanScreensForTotp(deps = {}) {
}
return { ok: false, error: "not-found" };
}
const decode = deps.decode || ((data, width, height) => jsQR(data, width, height));
const decode = deps.decode || ((data, width, height) => {
const jsQR = require("jsqr");
return jsQR(data, width, height);
});
let payloads;
try {
payloads = decodeBitmaps(images, decode);
+10 -7
View File
@@ -9,13 +9,16 @@ const crypto = require("node:crypto");
const { Readable } = require("node:stream");
const tempDirBridge = require("./tempDirBridge.cjs");
const { registerWorkerHandle } = require("./workerIpcProxy.cjs");
const {
encodePathForSession,
ensureRemoteDirForSession,
runRemoteUploadTransaction,
requireSftpChannel,
resolveEncodingForRequest,
} = require("./sftpBridge.cjs");
let _sftpBridge = null;
function getSftpBridge() {
if (!_sftpBridge) _sftpBridge = require("./sftpBridge.cjs");
return _sftpBridge;
}
const encodePathForSession = (...args) => getSftpBridge().encodePathForSession(...args);
const ensureRemoteDirForSession = (...args) => getSftpBridge().ensureRemoteDirForSession(...args);
const runRemoteUploadTransaction = (...args) => getSftpBridge().runRemoteUploadTransaction(...args);
const requireSftpChannel = (...args) => getSftpBridge().requireSftpChannel(...args);
const resolveEncodingForRequest = (...args) => getSftpBridge().resolveEncodingForRequest(...args);
const { isScpModeClient, getScpBackendForClient } = require("./sftpBridge/scpBackend.cjs");
const {
statLocal,
+6 -1
View File
@@ -806,7 +806,12 @@ function setupDeferredShow(win, { timeoutMs = 3000, waitForRendererReady = true,
win.on("closed", () => {
if (timer) clearTimeout(timer);
timer = null;
if (webContentsId) rendererReadyCallbacksByWebContentsId.delete(webContentsId);
if (webContentsId) {
rendererReadyCallbacksByWebContentsId.delete(webContentsId);
rendererReadySeenByWebContentsId.delete(webContentsId);
unhealthyWebContentsIds.delete(webContentsId);
rendererReadyWaitersByWebContentsId.delete(webContentsId);
}
});
return { showOnce, markRendererReady };
+15 -8
View File
@@ -12,14 +12,20 @@
// Apply the Buffer fast paths to zmodem.js receive/send hot paths, plus the
// Send-session robustness fixes for `rz` uploads (see zmodemFastPath.cjs).
// NETCATTY_ZMODEM_FAST_PATH=0 disables only the performance paths.
const {
applyZmodemFastPath,
applyZmodemSendSessionFixes,
applyZmodemSendFastPath,
} = require("./zmodemFastPath.cjs");
const Zmodem = applyZmodemSendFastPath(
applyZmodemSendSessionFixes(applyZmodemFastPath(require("zmodem.js"))),
);
let _zmodem = null;
function getZmodem() {
if (!_zmodem) {
const {
applyZmodemFastPath,
applyZmodemSendSessionFixes,
applyZmodemSendFastPath,
} = require("./zmodemFastPath.cjs");
_zmodem = applyZmodemSendFastPath(
applyZmodemSendSessionFixes(applyZmodemFastPath(require("zmodem.js"))),
);
}
return _zmodem;
}
const fs = require("node:fs");
const path = require("node:path");
@@ -617,6 +623,7 @@ function createZmodemSentry(opts) {
}
const Zmodem = getZmodem();
const sentry = new Zmodem.Sentry({
to_terminal(octets) {
// Normal data – pass raw bytes to the caller for charset-aware decoding.
+15 -5
View File
@@ -2,7 +2,12 @@
const { randomBytes } = require("node:crypto");
const { BlockList, isIP } = require("node:net");
const { RE2JS } = require("re2js");
let _RE2JS = null;
function getRE2JS() {
if (!_RE2JS) ({ RE2JS: _RE2JS } = require("re2js"));
return _RE2JS;
}
const CONFIG_ERROR = "Invalid External MCP redaction configuration";
const VALUE_ERROR = "External MCP redaction could not safely process this value";
@@ -53,9 +58,12 @@ function normalizeRedactionConfig(input) {
}
config.cidrs.forEach(parseCidr);
// RE2 rejects backreferences/lookaround and has bounded execution time.
config.patterns.forEach((pattern) => {
if (RE2JS.compile(pattern).matcher("").find()) throw new Error(CONFIG_ERROR);
});
if (config.patterns.length > 0) {
const RE2JS = getRE2JS();
config.patterns.forEach((pattern) => {
if (RE2JS.compile(pattern).matcher("").find()) throw new Error(CONFIG_ERROR);
});
}
return { ...config, cidrs: [...config.cidrs], patterns: [...config.patterns] };
} catch {
throw new Error(CONFIG_ERROR);
@@ -118,7 +126,9 @@ function createRedactionSession(input) {
let exhausted = false;
const customRanges = new BlockList();
config.cidrs.forEach((cidr) => addSubnet(customRanges, cidr));
const patterns = config.patterns.map((pattern) => RE2JS.compile(pattern));
const patterns = config.patterns.length > 0
? config.patterns.map((pattern) => getRE2JS().compile(pattern))
: [];
function issue(value, namespace) {
// The first classification names a value; later contexts reuse its token.
+21 -10
View File
@@ -2,9 +2,6 @@
const path = require("node:path");
const Ajv2020 = require("ajv/dist/2020").default;
const addFormats = require("ajv-formats").default;
const schema = require("./generated/plugin-contract.schema.json");
const { assertPluginJsonValue } = require("./jsonBoundary.cjs");
const {
PLUGIN_RPC_MAX_JSON_BYTES,
@@ -12,18 +9,28 @@ const {
} = require("./constants.cjs");
let contractAjv = null;
let cachedSchema = null;
const compiledDefinitions = new Map();
function getContractSchema() {
if (!cachedSchema) {
cachedSchema = require("./generated/plugin-contract.schema.json");
}
return cachedSchema;
}
/**
* One Ajv instance per process with the generated plugin contract registered
* once. Compiling the 200 KB contract used to happen in a fresh Ajv for every
* validator (~17 ms each, ~90 validators across the plugin host at startup).
* once. Loading Ajv + schema is deferred until the first validation call so
* zero-plugin startups do not pay ~5 MiB of Ajv/schema compilation overhead.
*/
function getContractAjv() {
if (!contractAjv) {
const Ajv2020 = require("ajv/dist/2020").default;
const addFormats = require("ajv-formats").default;
contractAjv = new Ajv2020({ allErrors: true, strict: false, validateFormats: true });
addFormats(contractAjv);
contractAjv.addSchema(schema);
contractAjv.addSchema(getContractSchema());
}
return contractAjv;
}
@@ -31,6 +38,10 @@ function getContractAjv() {
function compileDefinition(definitionName) {
let compiled = compiledDefinitions.get(definitionName);
if (!compiled) {
const schema = getContractSchema();
if (!schema.$defs?.[definitionName]) {
throw new Error(`Unknown plugin contract definition: ${definitionName}`);
}
compiled = getContractAjv().getSchema(`${schema.$id}#/$defs/${definitionName}`);
if (typeof compiled !== "function") throw new Error(`Unable to compile plugin contract definition: ${definitionName}`);
compiledDefinitions.set(definitionName, compiled);
@@ -39,12 +50,12 @@ function compileDefinition(definitionName) {
}
/**
* Returns a validator for one contract definition. Compilation is deferred to
* the first call and shared by every validator of the same definition; each
* returned function still exposes its own `.errors` from its latest call.
* Returns a validator for one contract definition. Schema loading and
* compilation are deferred to the first call and shared by every validator of
* the same definition; each returned function still exposes its own `.errors`
* from its latest call.
*/
function createDefinitionValidator(definitionName) {
if (!schema.$defs?.[definitionName]) throw new Error(`Unknown plugin contract definition: ${definitionName}`);
let compiled = null;
const validate = (value) => {
compiled ??= compileDefinition(definitionName);
+85 -59
View File
@@ -13,7 +13,20 @@ const { assertPluginJsonValue } = require("./jsonBoundary.cjs");
const { PluginRpcError, RPC_ERRORS, raceWithAbort } = require("./rpcRouter.cjs");
const { invalidArgument, freezeJson } = require("./validationUtils.cjs");
const { compileRestrictedJsonSchema } = require("./restrictedJsonSchema.cjs");
const pluginContractSchema = require("./generated/plugin-contract.schema.json");
let _pluginContractSchema = null;
function getPluginContractSchema() {
if (!_pluginContractSchema) {
_pluginContractSchema = require("./generated/plugin-contract.schema.json");
}
return _pluginContractSchema;
}
function getImporterLimits() {
return getPluginContractSchema().$defs.ImporterLimits.const;
}
function getSyncLimits() {
return getPluginContractSchema().$defs.SyncLimits.const;
}
const EXTENSION_PROVIDER_KINDS = Object.freeze(["connection", "authentication", "importer", "sync"]);
const PROVIDER_PERMISSIONS = Object.freeze({
@@ -34,11 +47,6 @@ const STREAM_WINDOW_BYTES = 256 * 1024;
const MAX_AUTH_CHALLENGES = 32;
const AUTHENTICATION_SECRET_LEASE_TTL_MS = 30_000;
const AUTHENTICATION_CANCEL_DEADLINE_MS = 1_000;
const importerLimits = pluginContractSchema.$defs.ImporterLimits.const;
const MAX_IMPORT_BYTES = importerLimits.maxInputBytes;
const MAX_IMPORT_OUTPUT_BYTES = importerLimits.maxOutputBytes;
const MAX_IMPORT_RECORDS = importerLimits.maxRecords;
const MAX_IMPORT_RECORD_BYTES = importerLimits.maxRecordBytes;
const SYNC_SECRET_CONFIG_KEYS = new Set(["password", "token", "secret", "apiKey", "accessToken"]);
/** Drop known secret / writeOnly field names from required[] so stripped sync configs still validate. */
@@ -59,34 +67,37 @@ function schemaWithoutSyncSecretRequirements(schema) {
if (required.length === schema.required.length) return schema;
return { ...schema, required };
}
const syncLimits = pluginContractSchema.$defs.SyncLimits.const;
const MAX_SYNC_OBJECT_BYTES = syncLimits.maxObjectBytes;
const MAX_SYNC_OBJECT_KEY_LENGTH = syncLimits.maxObjectKeyLength;
const MAX_SYNC_REVISION_LENGTH = syncLimits.maxRevisionLength;
const INLINE_SYNC_OBJECT_BYTES = syncLimits.inlineObjectBytes;
// inlineObjectBytes is sized to fit under the 128 KiB provider JSON budget after
// base64 expansion (~4/3) with envelope headroom. Keep the runtime cutoff equal
// to the public SyncLimits constant so plugins that honor the schema are not
// rejected with dataLoss in the 90–96 KiB window.
const INLINE_SYNC_OBJECT_SAFE_BYTES = INLINE_SYNC_OBJECT_BYTES;
const definitionValidators = Object.freeze({
AuthenticationResult: createDefinitionValidator("AuthenticationResult"),
ConnectionOpenResult: createDefinitionValidator("ConnectionOpenResult"),
ConnectionProbeResult: createDefinitionValidator("ConnectionProbeResult"),
ConnectionStatusResult: createDefinitionValidator("ConnectionStatusResult"),
ConnectionControlResult: createDefinitionValidator("ConnectionControlResult"),
ConnectionValidateResult: createDefinitionValidator("ConnectionValidateResult"),
ImporterDetectResult: createDefinitionValidator("ImporterDetectResult"),
ImporterParseResult: createDefinitionValidator("ImporterParseResult"),
ImporterRecord: createDefinitionValidator("ImporterRecord"),
SyncConnectResult: createDefinitionValidator("SyncConnectResult"),
SyncDisconnectResult: createDefinitionValidator("SyncDisconnectResult"),
SyncGetAccountResult: createDefinitionValidator("SyncGetAccountResult"),
SyncCapabilitiesResult: createDefinitionValidator("SyncCapabilitiesResult"),
SyncReadObjectResult: createDefinitionValidator("SyncReadObjectResult"),
SyncWriteObjectResult: createDefinitionValidator("SyncWriteObjectResult"),
SyncDeleteObjectResult: createDefinitionValidator("SyncDeleteObjectResult"),
});
const DEFINITION_VALIDATOR_NAMES = new Set([
"AuthenticationResult",
"ConnectionOpenResult",
"ConnectionProbeResult",
"ConnectionStatusResult",
"ConnectionControlResult",
"ConnectionValidateResult",
"ImporterDetectResult",
"ImporterParseResult",
"ImporterRecord",
"SyncConnectResult",
"SyncDisconnectResult",
"SyncGetAccountResult",
"SyncCapabilitiesResult",
"SyncReadObjectResult",
"SyncWriteObjectResult",
"SyncDeleteObjectResult",
]);
const definitionValidators = new Map();
function getDefinitionValidator(name) {
if (!DEFINITION_VALIDATOR_NAMES.has(name)) {
throw new TypeError(`Unknown plugin definition validator: ${name}`);
}
let validator = definitionValidators.get(name);
if (!validator) {
validator = createDefinitionValidator(name);
definitionValidators.set(name, validator);
}
return validator;
}
function assertBoundedJson(value, label, maxBytes = MAX_PROVIDER_JSON_BYTES) {
try { assertPluginJsonValue(value, { maxBytes }); }
@@ -126,7 +137,7 @@ function buildImporterDetectPayload({ bytes, fileName, mediaType }) {
}
function assertDefinition(name, value, label = name) {
const validator = definitionValidators[name];
const validator = getDefinitionValidator(name);
if (!validator(value)) {
throw new TypeError(`${label} violates the plugin contract: ${formatValidationErrors(validator.errors)}`);
}
@@ -334,17 +345,17 @@ function normalizeImportRecord(value) {
} else {
throw new TypeError("Importer record type is invalid");
}
assertBoundedJson(value, "Importer record", MAX_IMPORT_RECORD_BYTES);
assertBoundedJson(value, "Importer record", getImporterLimits().maxRecordBytes);
return freezeJson(value);
}
function assertSyncObjectKey(value) {
return assertString(value, "Sync object key", MAX_SYNC_OBJECT_KEY_LENGTH);
return assertString(value, "Sync object key", getSyncLimits().maxObjectKeyLength);
}
function assertSyncRevision(value, label = "Sync object revision") {
if (value == null) return value;
return assertString(value, label, MAX_SYNC_REVISION_LENGTH);
return assertString(value, label, getSyncLimits().maxRevisionLength);
}
function assertSyncResult(operation, value) {
@@ -372,13 +383,13 @@ function assertSyncResult(operation, value) {
if (value.maxObjectBytes != null
&& (!Number.isSafeInteger(value.maxObjectBytes)
|| value.maxObjectBytes < 1
|| value.maxObjectBytes > MAX_SYNC_OBJECT_BYTES)) {
|| value.maxObjectBytes > getSyncLimits().maxObjectBytes)) {
throw new TypeError("Sync maxObjectBytes is invalid");
}
} else if (operation === "readObject") {
assertDefinition("SyncReadObjectResult", value, "Sync readObject result");
if (value.found === true) {
if (!Number.isSafeInteger(value.byteLength) || value.byteLength < 0 || value.byteLength > MAX_SYNC_OBJECT_BYTES) {
if (!Number.isSafeInteger(value.byteLength) || value.byteLength < 0 || value.byteLength > getSyncLimits().maxObjectBytes) {
throw new TypeError("Sync readObject byteLength is invalid");
}
if (value.streamed === true) {
@@ -387,7 +398,7 @@ function assertSyncResult(operation, value) {
if (typeof value.data !== "string") throw new TypeError("Sync readObject data is invalid");
const decoded = Buffer.byteLength(value.data, "base64");
// Use the safe inline cutoff (base64 + envelope must fit control-plane JSON).
if (value.byteLength > INLINE_SYNC_OBJECT_SAFE_BYTES) {
if (value.byteLength > getSyncLimits().inlineObjectBytes) {
throw new TypeError("Sync readObject inline payload exceeds the inline limit");
}
if (decoded < value.byteLength) {
@@ -438,11 +449,16 @@ class PluginExtensionProviderService {
this.permissionEngine = options.permissionEngine;
this.runtimeSupervisor = options.runtimeSupervisor;
this.leaseStore = options.leaseStore;
this.maxImportRecordBytes = options.maxImportRecordBytes ?? MAX_IMPORT_RECORD_BYTES;
if (!Number.isSafeInteger(this.maxImportRecordBytes)
|| this.maxImportRecordBytes < 1
|| this.maxImportRecordBytes > MAX_IMPORT_RECORD_BYTES) {
throw new TypeError("Extension Provider importer record limit is invalid");
if (options.maxImportRecordBytes !== undefined) {
const maxRecordBytes = getImporterLimits().maxRecordBytes;
if (!Number.isSafeInteger(options.maxImportRecordBytes)
|| options.maxImportRecordBytes < 1
|| options.maxImportRecordBytes > maxRecordBytes) {
throw new TypeError("Extension Provider importer record limit is invalid");
}
this._maxImportRecordBytes = options.maxImportRecordBytes;
} else {
this._maxImportRecordBytes = null;
}
this.expectations = new Map();
this.sessions = new Map();
@@ -815,9 +831,13 @@ class PluginExtensionProviderService {
}
}
get maxImportRecordBytes() {
return this._maxImportRecordBytes ?? getImporterLimits().maxRecordBytes;
}
async detectImporter(params, options = {}) {
const bytes = params?.sample instanceof Uint8Array ? params.sample : new Uint8Array(params?.sample ?? []);
if (bytes.byteLength < 1 || bytes.byteLength > MAX_IMPORT_BYTES) throw invalidArgument("Importer sample size is invalid");
if (bytes.byteLength < 1 || bytes.byteLength > getImporterLimits().maxInputBytes) throw invalidArgument("Importer sample size is invalid");
return this.invoke({
providerId: params.providerId,
kind: "importer",
@@ -833,11 +853,17 @@ class PluginExtensionProviderService {
async parseImporter(params, options = {}) {
const providerId = assertString(params?.providerId, "Importer Provider ID");
const {
maxInputBytes: maxImportBytes,
maxOutputBytes: maxImportOutputBytes,
maxRecords: maxImportRecords,
} = getImporterLimits();
const maxImportRecordBytes = this.maxImportRecordBytes;
const bufferedSource = params?.data === undefined
? null
: params.data instanceof Uint8Array ? params.data : new Uint8Array(params.data ?? []);
const sourceByteLength = bufferedSource?.byteLength ?? params?.sourceByteLength;
if (!Number.isSafeInteger(sourceByteLength) || sourceByteLength < 1 || sourceByteLength > MAX_IMPORT_BYTES) {
if (!Number.isSafeInteger(sourceByteLength) || sourceByteLength < 1 || sourceByteLength > maxImportBytes) {
throw invalidArgument("Importer input size is invalid");
}
const source = bufferedSource ? [bufferedSource] : params?.source;
@@ -864,7 +890,7 @@ class PluginExtensionProviderService {
void outputDone.catch(() => {});
const assertPendingLineWithinLimit = () => {
const line = pending.endsWith("\r") ? pending.slice(0, -1) : pending;
if (Buffer.byteLength(line, "utf8") > this.maxImportRecordBytes) {
if (Buffer.byteLength(line, "utf8") > maxImportRecordBytes) {
throw new PluginRpcError(RPC_ERRORS.resourceExhausted, "Importer output exceeds its record limits");
}
};
@@ -874,7 +900,7 @@ class PluginExtensionProviderService {
for (const raw of lines) {
const line = raw.endsWith("\r") ? raw.slice(0, -1) : raw;
if (!line) continue;
if (Buffer.byteLength(line, "utf8") > this.maxImportRecordBytes || records.length >= MAX_IMPORT_RECORDS) {
if (Buffer.byteLength(line, "utf8") > maxImportRecordBytes || records.length >= maxImportRecords) {
throw new PluginRpcError(RPC_ERRORS.resourceExhausted, "Importer output exceeds its record limits");
}
const record = normalizeImportRecord(JSON.parse(line));
@@ -888,7 +914,7 @@ class PluginExtensionProviderService {
try {
if (chunk.encoding !== "binary") throw new Error("Importer output must be UTF-8 JSONL bytes");
outputBytes += chunk.bytes.byteLength;
if (outputBytes > MAX_IMPORT_OUTPUT_BYTES) throw new PluginRpcError(RPC_ERRORS.resourceExhausted, "Importer output is too large");
if (outputBytes > maxImportOutputBytes) throw new PluginRpcError(RPC_ERRORS.resourceExhausted, "Importer output is too large");
pending += decoder.decode(chunk.bytes, { stream: true });
consumeLines(false);
assertPendingLineWithinLimit();
@@ -1121,7 +1147,7 @@ class PluginExtensionProviderService {
try {
if (chunk.encoding !== "binary") throw new Error("Sync object stream must be binary");
totalBytes += chunk.bytes.byteLength;
if (totalBytes > MAX_SYNC_OBJECT_BYTES) {
if (totalBytes > getSyncLimits().maxObjectBytes) {
throw new PluginRpcError(RPC_ERRORS.resourceExhausted, "Sync object exceeds its size limit");
}
chunks.push(Buffer.from(chunk.bytes));
@@ -1237,14 +1263,14 @@ class PluginExtensionProviderService {
? null
: new Uint8Array(params.bytes);
if (!rawBytes) throw invalidArgument("Sync writeObject bytes are required");
if (rawBytes.byteLength > MAX_SYNC_OBJECT_BYTES) {
if (rawBytes.byteLength > getSyncLimits().maxObjectBytes) {
throw invalidArgument("Sync writeObject payload exceeds the size limit");
}
const deadlineMs = normalizeDeadlineMs(params?.deadlineMs);
const deadlineAt = performance.now() + deadlineMs;
const activation = options.activation ?? await this.activate(providerId, "sync", options.signal);
const operationId = `sync:write:${randomUUID()}`;
const useStream = rawBytes.byteLength > INLINE_SYNC_OBJECT_SAFE_BYTES || params?.preferStream === true;
const useStream = rawBytes.byteLength > getSyncLimits().inlineObjectBytes || params?.preferStream === true;
const inputStreamId = useStream ? `${operationId}:input` : undefined;
const expectedRevision = params?.expectedRevision === undefined
? undefined
@@ -1341,11 +1367,11 @@ class PluginExtensionProviderService {
module.exports = {
DEFAULT_DEADLINE_MS,
EXTENSION_PROVIDER_KINDS,
INLINE_SYNC_OBJECT_BYTES,
INLINE_SYNC_OBJECT_SAFE_BYTES,
MAX_IMPORT_BYTES,
MAX_IMPORT_RECORDS,
MAX_SYNC_OBJECT_BYTES,
get INLINE_SYNC_OBJECT_BYTES() { return getSyncLimits().inlineObjectBytes; },
get INLINE_SYNC_OBJECT_SAFE_BYTES() { return getSyncLimits().inlineObjectBytes; },
get MAX_IMPORT_BYTES() { return getImporterLimits().maxInputBytes; },
get MAX_IMPORT_RECORDS() { return getImporterLimits().maxRecords; },
get MAX_SYNC_OBJECT_BYTES() { return getSyncLimits().maxObjectBytes; },
PluginExtensionProviderService,
STREAM_WINDOW_BYTES,
assertSyncResult,
+6 -9
View File
@@ -8,11 +8,8 @@ const validateManagedPluginId = createDefinitionValidator("PluginId");
const validatePluginViewResourceRequest = createDefinitionValidator("PluginViewResourceRequest");
const { raceWithAbort } = require("./rpcRouter.cjs");
const {
INLINE_SYNC_OBJECT_SAFE_BYTES,
MAX_SYNC_OBJECT_BYTES,
STREAM_WINDOW_BYTES,
} = require("./extensionProviderService.cjs");
const extensionProviderServiceModule = require("./extensionProviderService.cjs");
const { STREAM_WINDOW_BYTES } = extensionProviderServiceModule;
const { assertSecretKey } = require("./secretStore.cjs");
const CHANNELS = Object.freeze({
@@ -980,7 +977,7 @@ function registerPluginBridge(ipcMain, options) {
? result.bytes
: new Uint8Array(result.bytes);
const preferStream = payload?.preferStream === true;
if (!preferStream && bytes.byteLength <= INLINE_SYNC_OBJECT_SAFE_BYTES) {
if (!preferStream && bytes.byteLength <= extensionProviderServiceModule.INLINE_SYNC_OBJECT_SAFE_BYTES) {
extensionRequestMap(event.sender).delete(requestId);
return {
found: true,
@@ -1055,10 +1052,10 @@ function registerPluginBridge(ipcMain, options) {
ipcMain.handle(CHANNELS.syncWriteObject, async (event, payload) => runExtensionRequest(event, payload, async (signal) => {
if (!extensionProviderService) throw new Error("Plugin sync Providers are unavailable");
const data = coerceIpcBytes(payload?.data ?? payload?.bytes, "Sync writeObject data");
if (data.byteLength > INLINE_SYNC_OBJECT_SAFE_BYTES) {
if (data.byteLength > extensionProviderServiceModule.INLINE_SYNC_OBJECT_SAFE_BYTES) {
throw new Error("Sync writeObject payload requires the streamed write path");
}
if (data.byteLength > MAX_SYNC_OBJECT_BYTES) {
if (data.byteLength > extensionProviderServiceModule.MAX_SYNC_OBJECT_BYTES) {
throw new Error("Sync writeObject payload exceeds the size limit");
}
return extensionProviderService.writeSyncObject({
@@ -1079,7 +1076,7 @@ function registerPluginBridge(ipcMain, options) {
throw error;
};
const byteLength = payload?.byteLength;
if (!Number.isSafeInteger(byteLength) || byteLength < 1 || byteLength > MAX_SYNC_OBJECT_BYTES) {
if (!Number.isSafeInteger(byteLength) || byteLength < 1 || byteLength > extensionProviderServiceModule.MAX_SYNC_OBJECT_BYTES) {
failBegin(new TypeError("Sync writeObject byteLength is invalid"));
}
const providerId = payload?.providerId;
+13 -7
View File
@@ -1,6 +1,17 @@
"use strict";
const Ajv2020 = require("ajv/dist/2020").default;
let _ajv = null;
function getAjv() {
if (!_ajv) {
const Ajv2020 = require("ajv/dist/2020").default;
_ajv = new Ajv2020({
allErrors: true,
strict: true,
validateFormats: false,
});
}
return _ajv;
}
const MAX_SCHEMA_DEPTH = 8;
const MAX_SCHEMA_NODES = 256;
@@ -25,12 +36,6 @@ const ALLOWED_KEYWORDS = new Set([
"writeOnly",
]);
const ajv = new Ajv2020({
allErrors: true,
strict: true,
validateFormats: false,
});
function isPlainRecord(value) {
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
const prototype = Object.getPrototypeOf(value);
@@ -144,6 +149,7 @@ function assertRestrictedJsonSchema(root, options = {}) {
function compileRestrictedJsonSchema(schema, options = {}) {
assertRestrictedJsonSchema(schema, options);
const ajv = getAjv();
let validate;
try { validate = ajv.compile(schema); }
catch (error) { throw new TypeError(`Restricted setting schema is invalid: ${error?.message ?? error}`); }
@@ -145,5 +145,203 @@
"portforward/stop": "portforward_stop",
"netcatty/readContext": "terminal_read_context",
"netcatty/readRemoteScreen": "remote_desktop_read_screen"
}
},
"sidebarToolNameToCapability": {
"get_environment": "session.environment",
"list_attachments": "attachment.list",
"read_attachment": "attachment.read",
"session_reconnect": "session.reconnect",
"session_recover": "session.recover",
"session_close": "session.close",
"terminal_execute": "terminal.execute",
"terminal_start": "terminal.start",
"terminal_poll": "terminal.poll",
"terminal_stop": "terminal.stop",
"sftp_list": "sftp.list",
"sftp_read_file": "sftp.read",
"sftp_write_file": "sftp.write",
"sftp_download": "sftp.download",
"sftp_upload": "sftp.upload",
"sftp_stat": "sftp.stat",
"sftp_home": "sftp.home",
"sftp_mkdir": "sftp.mkdir",
"sftp_delete": "sftp.delete",
"sftp_rename": "sftp.rename",
"sftp_chmod": "sftp.chmod",
"host_get": "vault.host.get",
"vault_hosts_list": "vault.host.list",
"vault_hosts_create": "vault.hosts.create",
"vault_hosts_update": "vault.host.update",
"vault_hosts_delete": "vault.host.delete",
"vault_hosts_import": "vault.host.import",
"host_notes_get": "vault.host.notes.get",
"host_notes_set": "vault.host.notes.set",
"vault_notes_list": "vault.note.list",
"vault_notes_get": "vault.note.get",
"vault_notes_create": "vault.note.create",
"vault_notes_update": "vault.note.update",
"vault_notes_delete": "vault.note.delete",
"vault_notes_import": "vault.note.import",
"vault_identities_list": "vault.identity.list",
"vault_proxy_profiles_list": "vault.proxyProfile.list",
"vault_groups_list": "vault.group.list",
"vault_groups_create": "vault.group.create",
"vault_groups_update": "vault.group.update",
"vault_groups_delete": "vault.group.delete",
"snippets_list": "vault.snippets.list",
"snippets_get": "vault.snippets.get",
"snippets_run": "vault.snippets.run",
"snippets_create": "vault.snippets.create",
"snippets_update": "vault.snippets.update",
"snippets_delete": "vault.snippets.delete",
"scripts_list": "vault.scripts.list",
"scripts_get": "vault.scripts.get",
"scripts_create": "vault.scripts.create",
"scripts_update": "vault.scripts.update",
"scripts_delete": "vault.scripts.delete",
"scripts_run": "vault.scripts.run",
"scripts_reference": "vault.scripts.reference",
"scripts_runs_list": "vault.scripts.runs.list",
"scripts_run_stop": "vault.scripts.run.stop",
"scripts_run_pause": "vault.scripts.run.pause",
"scripts_run_resume": "vault.scripts.run.resume",
"scripts_targets_set": "vault.scripts.targets.set",
"host_connect_scripts_list": "vault.host.connectScripts.list",
"host_connect_scripts_set": "vault.host.connectScripts.set",
"portforward_rules_list": "portforward.rules.list",
"portforward_tunnels_list": "portforward.tunnels.list",
"portforward_rules_create": "portforward.rules.create",
"portforward_rules_update": "portforward.rules.update",
"portforward_rules_duplicate": "portforward.rules.duplicate",
"portforward_rules_delete": "portforward.rules.delete",
"portforward_start": "portforward.start",
"portforward_stop": "portforward.stop",
"tool_output_read": "harness.tool_output.read",
"workspace_get_info": "harness.workspace.get_info",
"workspace_get_session_info": "harness.workspace.get_session_info",
"terminal_read_context": "harness.terminal.read_context",
"remote_desktop_read_screen": "harness.remote_desktop.read_screen",
"remote_desktop_act": "harness.remote_desktop.act",
"web_search": "harness.web.search",
"url_fetch": "harness.url.fetch"
},
"sidebarRpcMethodToCapability": {
"netcatty/getContext": "session.environment",
"netcatty/listAttachments": "attachment.list",
"netcatty/readAttachment": "attachment.read",
"session/reconnect": "session.reconnect",
"session/recover": "session.recover",
"session/close": "session.close",
"netcatty/exec": "terminal.execute",
"netcatty/jobStart": "terminal.start",
"netcatty/jobPoll": "terminal.poll",
"netcatty/jobStop": "terminal.stop",
"netcatty/sftp/list": "sftp.list",
"netcatty/sftp/read": "sftp.read",
"netcatty/sftp/write": "sftp.write",
"netcatty/sftp/download": "sftp.download",
"netcatty/sftp/upload": "sftp.upload",
"netcatty/sftp/stat": "sftp.stat",
"netcatty/sftp/home": "sftp.home",
"netcatty/sftp/mkdir": "sftp.mkdir",
"netcatty/sftp/delete": "sftp.delete",
"netcatty/sftp/rename": "sftp.rename",
"netcatty/sftp/chmod": "sftp.chmod",
"vault/host/get": "vault.host.get",
"vault/hosts/list": "vault.host.list",
"vault/hosts/create": "vault.hosts.create",
"vault/hosts/update": "vault.host.update",
"vault/hosts/delete": "vault.host.delete",
"vault/hosts/import": "vault.host.import",
"vault/host/notes/get": "vault.host.notes.get",
"vault/host/notes/set": "vault.host.notes.set",
"vault/notes/list": "vault.note.list",
"vault/notes/get": "vault.note.get",
"vault/notes/create": "vault.note.create",
"vault/notes/update": "vault.note.update",
"vault/notes/delete": "vault.note.delete",
"vault/notes/import": "vault.note.import",
"vault/identities/list": "vault.identity.list",
"vault/proxyProfiles/list": "vault.proxyProfile.list",
"vault/groups/list": "vault.group.list",
"vault/groups/create": "vault.group.create",
"vault/groups/update": "vault.group.update",
"vault/groups/delete": "vault.group.delete",
"vault/snippets/list": "vault.snippets.list",
"vault/snippets/get": "vault.snippets.get",
"vault/snippets/run": "vault.snippets.run",
"vault/snippets/create": "vault.snippets.create",
"vault/snippets/update": "vault.snippets.update",
"vault/snippets/delete": "vault.snippets.delete",
"vault/scripts/list": "vault.scripts.list",
"vault/scripts/get": "vault.scripts.get",
"vault/scripts/create": "vault.scripts.create",
"vault/scripts/update": "vault.scripts.update",
"vault/scripts/delete": "vault.scripts.delete",
"vault/scripts/run": "vault.scripts.run",
"vault/scripts/reference": "vault.scripts.reference",
"vault/scripts/runs/list": "vault.scripts.runs.list",
"vault/scripts/run/stop": "vault.scripts.run.stop",
"vault/scripts/run/pause": "vault.scripts.run.pause",
"vault/scripts/run/resume": "vault.scripts.run.resume",
"vault/scripts/targets/set": "vault.scripts.targets.set",
"vault/host/connectScripts/list": "vault.host.connectScripts.list",
"vault/host/connectScripts/set": "vault.host.connectScripts.set",
"portforward/rules/list": "portforward.rules.list",
"portforward/tunnels/list": "portforward.tunnels.list",
"portforward/rules/create": "portforward.rules.create",
"portforward/rules/update": "portforward.rules.update",
"portforward/rules/duplicate": "portforward.rules.duplicate",
"portforward/rules/delete": "portforward.rules.delete",
"portforward/start": "portforward.start",
"portforward/stop": "portforward.stop",
"netcatty/readContext": "harness.terminal.read_context",
"netcatty/readRemoteScreen": "harness.remote_desktop.read_screen"
},
"freshApprovalOnlyCapabilities": [],
"grantableCapabilityIds": [
"harness.remote_desktop.act",
"portforward.rules.create",
"portforward.rules.delete",
"portforward.rules.duplicate",
"portforward.rules.update",
"portforward.start",
"portforward.stop",
"session.reconnect",
"session.recover",
"sftp.chmod",
"sftp.delete",
"sftp.download",
"sftp.mkdir",
"sftp.rename",
"sftp.upload",
"sftp.write",
"terminal.execute",
"terminal.start",
"vault.group.create",
"vault.group.delete",
"vault.group.update",
"vault.host.connectScripts.set",
"vault.host.delete",
"vault.host.import",
"vault.host.notes.set",
"vault.host.update",
"vault.hosts.create",
"vault.note.create",
"vault.note.delete",
"vault.note.import",
"vault.note.update",
"vault.scripts.create",
"vault.scripts.delete",
"vault.scripts.run",
"vault.scripts.run.pause",
"vault.scripts.run.resume",
"vault.scripts.run.stop",
"vault.scripts.targets.set",
"vault.scripts.update",
"vault.snippets.create",
"vault.snippets.delete",
"vault.snippets.run",
"vault.snippets.update"
]
}
+7 -31
View File
@@ -1,4 +1,4 @@
import cattyToolSpecs from './generated/cattyToolSpecs.json';
import toolNameIndex from './generated/toolNameIndex.json';
import {
buildAlwaysAllowCommandPatterns,
extractGrantableShellCommandSegments,
@@ -37,42 +37,22 @@ function ruleMatchesCapability(rule: PermissionGrantRule, ctx: PermissionGrantMa
&& ruleMatchesTarget(rule, ctx);
}
type CattyToolSpecRef = {
capabilityId: string;
toolName: string;
rpcMethod: string | null;
policy?: {
write?: boolean;
bypassesApproval?: boolean;
requiresFreshApproval?: boolean;
};
};
export const HIGH_RISK_REMOTE_DESKTOP_CAPABILITY_ID = 'harness.remote_desktop.act:high-risk';
const TOOL_NAME_TO_CAPABILITY = new Map<string, string>();
const RPC_METHOD_TO_CAPABILITY = new Map<string, string>();
const TOOL_NAME_TO_CAPABILITY = toolNameIndex.sidebarToolNameToCapability as Record<string, string>;
const RPC_METHOD_TO_CAPABILITY = toolNameIndex.sidebarRpcMethodToCapability as Record<string, string>;
const FRESH_APPROVAL_ONLY_CAPABILITIES = new Set<string>([
HIGH_RISK_REMOTE_DESKTOP_CAPABILITY_ID,
...toolNameIndex.freshApprovalOnlyCapabilities,
]);
for (const spec of cattyToolSpecs as CattyToolSpecRef[]) {
TOOL_NAME_TO_CAPABILITY.set(spec.toolName, spec.capabilityId);
if (spec.rpcMethod) {
RPC_METHOD_TO_CAPABILITY.set(spec.rpcMethod, spec.capabilityId);
}
if (spec.policy?.requiresFreshApproval) {
FRESH_APPROVAL_ONLY_CAPABILITIES.add(spec.capabilityId);
}
}
export function isFreshApprovalOnlyCapability(capabilityId: string | undefined): boolean {
return Boolean(capabilityId && FRESH_APPROVAL_ONLY_CAPABILITIES.has(capabilityId));
}
export function resolveCapabilityId(toolOrRpcName: string): string {
return TOOL_NAME_TO_CAPABILITY.get(toolOrRpcName)
?? RPC_METHOD_TO_CAPABILITY.get(toolOrRpcName)
return TOOL_NAME_TO_CAPABILITY[toolOrRpcName]
?? RPC_METHOD_TO_CAPABILITY[toolOrRpcName]
?? toolOrRpcName;
}
@@ -237,11 +217,7 @@ const COMMAND_GRANT_CAPABILITIES = new Set([
]);
const GRANTABLE_CAPABILITY_IDS: readonly string[] = Object.freeze(
[...new Set(
(cattyToolSpecs as CattyToolSpecRef[])
.filter((spec) => spec.policy?.write && !spec.policy?.bypassesApproval && !spec.policy?.requiresFreshApproval)
.map((spec) => spec.capabilityId),
)].sort(),
[...toolNameIndex.grantableCapabilityIds],
);
export function listGrantableCapabilityIds(): readonly string[] {
+33 -29
View File
@@ -1783,39 +1783,43 @@ export async function handleRemoteDesktopScreenRead(
};
}
export async function dispatchVaultAgentBridgeRequest(
payload: { requestId: string; op: string; params?: Record<string, unknown> },
): Promise<void> {
const bridge = netcattyBridge.get();
if (!bridge?.respondVaultAgent) return;
const { requestId, op, params } = payload;
const safeParams = params || {};
const runHandler = async () => {
try {
const result = op === 'terminal.readContext'
? await handleTerminalContextRead(safeParams)
: op === 'remoteDesktop.readScreen'
? await handleRemoteDesktopScreenRead(safeParams)
: activeHandler ? await activeHandler(op, safeParams)
: { ok: false, error: 'Vault agent bridge is not ready.' };
await bridge.respondVaultAgent?.(requestId, result);
} catch (err) {
await bridge.respondVaultAgent?.(requestId, {
ok: false,
error: err instanceof Error ? err.message : String(err),
});
}
};
if (shouldBypassVaultAgentSerialization(op, safeParams)) {
await runHandler();
return;
}
await runSerializedVaultAgentRequest(runHandler);
}
export function setupVaultAgentBridge(): () => void {
const bridge = netcattyBridge.get();
if (!bridge?.onVaultAgentRequest || !bridge.respondVaultAgent) {
return () => {};
}
const unsubscribe = bridge.onVaultAgentRequest(async (payload) => {
const { requestId, op, params } = payload;
const safeParams = params || {};
const runHandler = async () => {
try {
const result = op === 'terminal.readContext'
? await handleTerminalContextRead(safeParams)
: op === 'remoteDesktop.readScreen'
? await handleRemoteDesktopScreenRead(safeParams)
: activeHandler ? await activeHandler(op, safeParams)
: { ok: false, error: 'Vault agent bridge is not ready.' };
await bridge.respondVaultAgent?.(requestId, result);
} catch (err) {
await bridge.respondVaultAgent?.(requestId, {
ok: false,
error: err instanceof Error ? err.message : String(err),
});
}
};
if (shouldBypassVaultAgentSerialization(op, safeParams)) {
await runHandler();
return;
}
await runSerializedVaultAgentRequest(runHandler);
});
return unsubscribe;
return bridge.onVaultAgentRequest((payload) => dispatchVaultAgentBridgeRequest(payload));
}
@@ -1,6 +1,6 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import packageJson from '../../../package.json';
import { version as appVersion } from '../../../package.json';
import {
isProviderReadyForSync,
type CloudProvider,
@@ -701,7 +701,7 @@ export async function syncConvergentProvidersUnlockedImpl(
this.masterPassword,
this.state.deviceId,
this.state.deviceName,
packageJson.version,
appVersion,
remoteVersion,
);
assertSyncSecurityGeneration(this, syncSecurityGeneration);
@@ -1241,7 +1241,7 @@ export async function downgradeConvergentSyncImpl(
this.masterPassword,
this.state.deviceId,
this.state.deviceName,
packageJson.version,
appVersion,
before?.meta.version ?? this.state.localVersion,
);
assertSyncSecurityGeneration(this, syncSecurityGeneration);
@@ -1,7 +1,7 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import packageJson from '../../../package.json';
import { version as appVersion } from '../../../package.json';
import { EncryptionService } from '../EncryptionService';
import { mergeSyncPayloads } from '../../../domain/syncMerge';
import { stripSyncPayloadEncryptedCredentials, healPoisonedSecretsForMerge } from '../../../domain/credentials';
@@ -114,7 +114,7 @@ async function uploadLocalPayloadImpl(this: any,
this.masterPassword,
this.state.deviceId,
this.state.deviceName,
packageJson.version,
appVersion,
baseVersion,
);
assertSyncSecurityGeneration(this, syncSecurityGeneration);
@@ -564,7 +564,7 @@ export async function syncToProviderImpl(this: any,
this.masterPassword,
this.state.deviceId,
this.state.deviceName,
packageJson.version,
appVersion,
checkResult.remoteFile.meta.version, // base on remote version
);
assertSyncSecurityGeneration(this, syncSecurityGeneration);
@@ -4,7 +4,7 @@ import {
SYNC_STORAGE_KEYS,
isProviderReadyForSync,
} from '../../../domain/sync';
import packageJson from '../../../package.json';
import { version as appVersion } from '../../../package.json';
import { EncryptionService } from '../EncryptionService';
import { decryptProviderSecrets } from '../../persistence/secureFieldAdapter';
import { mergeAiSessionLists, mergeSyncPayloads } from '../../../domain/syncMerge';
@@ -913,7 +913,7 @@ export async function syncAllProvidersImpl(this: any,
this.masterPassword,
this.state.deviceId,
this.state.deviceName,
packageJson.version,
appVersion,
baseVersion
);
assertSyncSecurityGeneration(this, syncSecurityGeneration);
+1 -1
View File
@@ -18,7 +18,7 @@ await build({
platform: "browser",
target: "chrome140",
external: ["electron"],
minify: false,
minify: true,
legalComments: "none",
banner: {
js: "// Generated by scripts/build-preload.mjs for Electron sandbox: true. Do not edit directly.",
+29 -1
View File
@@ -30,15 +30,43 @@ for (const spec of globalAgentSpecs) {
}
}
const sidebarByRpcMethod = {};
const sidebarToolNameToCapability = {};
const sidebarRpcMethodToCapability = {};
const freshApprovalSet = new Set();
const grantableSet = new Set();
for (const spec of sidebarSpecs) {
if (spec.rpcMethod && spec.toolName && !sidebarByRpcMethod[spec.rpcMethod]) {
sidebarByRpcMethod[spec.rpcMethod] = spec.toolName;
}
if (spec.toolName && spec.capabilityId) {
sidebarToolNameToCapability[spec.toolName] = spec.capabilityId;
}
if (spec.rpcMethod && spec.capabilityId) {
sidebarRpcMethodToCapability[spec.rpcMethod] = spec.capabilityId;
}
if (spec.policy?.requiresFreshApproval && spec.capabilityId) {
freshApprovalSet.add(spec.capabilityId);
}
if (
spec.policy?.write
&& !spec.policy?.bypassesApproval
&& !spec.policy?.requiresFreshApproval
&& spec.capabilityId
) {
grantableSet.add(spec.capabilityId);
}
}
const indexOutputPath = path.join(generatedDir, "toolNameIndex.json");
fs.writeFileSync(
indexOutputPath,
`${JSON.stringify({ globalByCapabilityId, sidebarByRpcMethod }, null, 2)}\n`,
`${JSON.stringify({
globalByCapabilityId,
sidebarByRpcMethod,
sidebarToolNameToCapability,
sidebarRpcMethodToCapability,
freshApprovalOnlyCapabilities: [...freshApprovalSet].sort(),
grantableCapabilityIds: [...grantableSet].sort(),
}, null, 2)}\n`,
"utf8",
);
+29 -1
View File
@@ -43,11 +43,39 @@ test("committed toolNameIndex.json matches sidebar and global capability tool sp
}
}
const sidebarByRpcMethod = {};
const sidebarToolNameToCapability = {};
const sidebarRpcMethodToCapability = {};
const freshApprovalSet = new Set();
const grantableSet = new Set();
for (const spec of listCattyToolSpecs()) {
if (spec.rpcMethod && spec.toolName && !sidebarByRpcMethod[spec.rpcMethod]) {
sidebarByRpcMethod[spec.rpcMethod] = spec.toolName;
}
if (spec.toolName && spec.capabilityId) {
sidebarToolNameToCapability[spec.toolName] = spec.capabilityId;
}
if (spec.rpcMethod && spec.capabilityId) {
sidebarRpcMethodToCapability[spec.rpcMethod] = spec.capabilityId;
}
if (spec.policy?.requiresFreshApproval && spec.capabilityId) {
freshApprovalSet.add(spec.capabilityId);
}
if (
spec.policy?.write
&& !spec.policy?.bypassesApproval
&& !spec.policy?.requiresFreshApproval
&& spec.capabilityId
) {
grantableSet.add(spec.capabilityId);
}
}
assert.deepEqual(committed, { globalByCapabilityId, sidebarByRpcMethod });
assert.deepEqual(committed, {
globalByCapabilityId,
sidebarByRpcMethod,
sidebarToolNameToCapability,
sidebarRpcMethodToCapability,
freshApprovalOnlyCapabilities: [...freshApprovalSet].sort(),
grantableCapabilityIds: [...grantableSet].sort(),
});
});