@causyne/agent 1.20.120 → 1.20.122
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -3
- package/package.json +1 -1
- package/src/acp/agentCatalog.js +81 -26
- package/src/acp/agentCatalog.ts +73 -29
- package/src/acp/client.js +210 -53
- package/src/acp/client.ts +202 -52
- package/src/acp/peerProfiles.js +55 -22
- package/src/acp/peerProfiles.ts +51 -22
- package/src/acp/protocol.js +37 -8
- package/src/acp/protocol.ts +30 -8
- package/src/acp/server.js +123 -25
- package/src/acp/server.ts +124 -24
- package/src/agent/errorClassifier.js +117 -0
- package/src/agent/errorClassifier.ts +165 -0
- package/src/agent/promptIntent.js +200 -0
- package/src/agent/promptIntent.ts +203 -0
- package/src/agent/toolArgValidator.js +97 -0
- package/src/agent/toolArgValidator.ts +112 -0
- package/src/agentLoop.js +33 -344
- package/src/agentLoop.ts +51 -352
- package/src/approvalGrants.js +19 -7
- package/src/approvalGrants.ts +20 -7
- package/src/approvalPolicy.js +48 -15
- package/src/approvalPolicy.ts +46 -15
- package/src/autoUpdate.js +116 -10
- package/src/autoUpdate.ts +149 -10
- package/src/browser/causyneBrowser.js +3 -2
- package/src/browser/causyneBrowser.ts +3 -2
- package/src/browser/searchProviders.js +1 -1
- package/src/browser/searchProviders.ts +1 -1
- package/src/cliMode.js +16 -2
- package/src/commands.js +10 -9
- package/src/config.js +288 -272
- package/src/config.ts +342 -0
- package/src/configVault.js +271 -0
- package/src/configVault.ts +273 -0
- package/src/continuum/compactor.js +2 -1
- package/src/continuum/compactor.ts +2 -1
- package/src/continuum/sanitizer.js +10 -3
- package/src/continuum/sanitizer.ts +9 -3
- package/src/continuum/ui/continuumPickerView.js +3 -2
- package/src/continuum/ui/continuumPickerView.ts +3 -2
- package/src/core/contextCompactor.js +70 -11
- package/src/core/contextCompactor.ts +83 -11
- package/src/cortex/vectorDb.js +26 -15
- package/src/cortex/vectorDb.ts +26 -16
- package/src/creative/liveBridge.js +7 -5
- package/src/creative/liveBridge.ts +7 -5
- package/src/creative/studioScripts.js +16 -5
- package/src/creative/studioScripts.ts +14 -5
- package/src/decisionPolicy.js +16 -4
- package/src/decisionPolicy.ts +14 -4
- package/src/documentEngine/antiSlopAuditor.js +10 -5
- package/src/documentEngine/antiSlopAuditor.ts +11 -5
- package/src/documentEngine/documentForge.js +47 -15
- package/src/documentEngine/documentForge.ts +43 -14
- package/src/dynamicCatalogue.js +42 -73
- package/src/dynamicCatalogue.ts +74 -60
- package/src/engines/design.js +2 -1
- package/src/engines/design.ts +2 -1
- package/src/engines/film.js +4 -4
- package/src/engines/film.ts +2 -2
- package/src/engines/light.js +2 -1
- package/src/engines/light.ts +2 -1
- package/src/engines/registry.js +1 -1
- package/src/engines/registry.ts +1 -1
- package/src/engines/reverseHarness.js +4 -3
- package/src/engines/reverseHarness.ts +4 -3
- package/src/entrypoint.js +77 -4
- package/src/headlessCli.js +305 -0
- package/src/headlessCli.ts +381 -0
- package/src/historyPruner.js +3 -2
- package/src/historyPruner.ts +3 -2
- package/src/hooks.js +3 -0
- package/src/hooks.ts +3 -0
- package/src/implementationPlan.js +21 -11
- package/src/implementationPlan.ts +21 -11
- package/src/infra/atomicWriter.js +4 -1
- package/src/infra/atomicWriter.ts +4 -1
- package/src/launchIntent.js +1 -1
- package/src/launchIntent.ts +1 -1
- package/src/mcp/mcpClient.js +38 -11
- package/src/mcp/mcpClient.ts +44 -11
- package/src/mcp/mcpRegistry.js +2 -5
- package/src/mcp/mcpRegistry.ts +2 -5
- package/src/mcp/mcpSecurity.js +189 -0
- package/src/mcp/mcpSecurity.ts +190 -0
- package/src/memory/scopedFacts.js +1 -1
- package/src/memory/scopedFacts.ts +1 -1
- package/src/memory/symbolFolder.js +1 -1
- package/src/memory/symbolFolder.ts +1 -1
- package/src/modelRouter.js +1 -1
- package/src/modelRouter.ts +1 -1
- package/src/observer/evidence.js +10 -4
- package/src/observer/evidence.ts +10 -4
- package/src/osKeychain.js +263 -0
- package/src/osKeychain.ts +287 -0
- package/src/perception.js +3 -2
- package/src/perception.ts +3 -2
- package/src/planCache.js +2 -2
- package/src/planCache.ts +2 -2
- package/src/pluginsFactory/pluginsFactory.js +19 -11
- package/src/pluginsFactory/pluginsFactory.ts +18 -11
- package/src/promptMentions.js +2 -2
- package/src/promptMentions.ts +2 -2
- package/src/providers/acp.js +1 -1
- package/src/providers/acp.ts +1 -1
- package/src/providers/anthropic.js +328 -385
- package/src/providers/anthropic.ts +386 -0
- package/src/providers/antigravity.js +10 -4
- package/src/providers/antigravity.ts +10 -4
- package/src/providers/base.js +221 -319
- package/src/providers/base.ts +340 -0
- package/src/providers/byokHttp.js +397 -0
- package/src/providers/byokHttp.ts +497 -0
- package/src/providers/byokStream.js +748 -0
- package/src/providers/byokStream.ts +863 -0
- package/src/providers/dashscope-byok.js +98 -81
- package/src/providers/dashscope-byok.ts +114 -0
- package/src/providers/deepseek.js +74 -64
- package/src/providers/deepseek.ts +99 -0
- package/src/providers/factory.js +35 -28
- package/src/providers/factory.ts +40 -0
- package/src/providers/gemini.js +229 -253
- package/src/providers/gemini.ts +261 -0
- package/src/providers/loopGuard.js +9 -5
- package/src/providers/loopGuard.ts +10 -5
- package/src/providers/moonshot.js +71 -64
- package/src/providers/moonshot.ts +93 -0
- package/src/providers/muse.js +82 -152
- package/src/providers/muse.ts +122 -0
- package/src/providers/ollama.js +116 -93
- package/src/providers/ollama.ts +135 -0
- package/src/providers/openai-compatible.js +114 -65
- package/src/providers/openai-compatible.ts +139 -0
- package/src/providers/openai.js +22 -15
- package/src/providers/openai.ts +30 -0
- package/src/providers/openrouter.js +194 -98
- package/src/providers/openrouter.ts +202 -97
- package/src/providers/pi.js +6 -0
- package/src/providers/pi.ts +6 -0
- package/src/providers/qwen-byok.js +97 -71
- package/src/providers/qwen-byok.ts +113 -0
- package/src/providers/toolContracts.js +40 -14
- package/src/providers/toolContracts.ts +35 -14
- package/src/providers/wireNormalizer.js +78 -11
- package/src/providers/wireNormalizer.ts +68 -12
- package/src/providers/xai.js +74 -64
- package/src/providers/xai.ts +97 -0
- package/src/reliability/assetEvidence.js +4 -2
- package/src/reliability/assetEvidence.ts +4 -2
- package/src/sandbox.js +486 -530
- package/src/sandbox.ts +552 -0
- package/src/sandboxPolicy.js +1287 -0
- package/src/sandboxPolicy.ts +1381 -0
- package/src/sessionJournal.js +55 -3
- package/src/sessionJournal.ts +58 -3
- package/src/skills/skillResourceSafety.js +19 -8
- package/src/skills/skillResourceSafety.ts +16 -7
- package/src/skillsManager.js +3 -3
- package/src/skillsManager.ts +3 -3
- package/src/smartToolsUse.js +28 -4
- package/src/smartToolsUse.ts +29 -7
- package/src/stallGuard.js +45 -22
- package/src/stallGuard.ts +46 -22
- package/src/subagentJournal.js +6 -4
- package/src/subagentJournal.ts +6 -4
- package/src/textDiff.js +6 -1
- package/src/textDiff.ts +6 -1
- package/src/timeMachine.js +7 -1
- package/src/timeMachine.ts +7 -1
- package/src/tokenTracker.js +43 -28
- package/src/tokenTracker.ts +44 -30
- package/src/toolPacks.js +3 -1
- package/src/toolPacks.ts +3 -1
- package/src/tools/archive.js +245 -35
- package/src/tools/archive.ts +244 -35
- package/src/tools/computerUse.js +7 -3
- package/src/tools/computerUse.ts +7 -3
- package/src/tools/creativeApps.js +13 -8
- package/src/tools/creativeApps.ts +22 -9
- package/src/tools/deferredMcpSearch.js +26 -14
- package/src/tools/deferredMcpSearch.ts +26 -14
- package/src/tools/desktopOpen.js +69 -10
- package/src/tools/desktopOpen.ts +70 -11
- package/src/tools/documentForge.js +167 -82
- package/src/tools/documentForge.ts +169 -84
- package/src/tools/fsEdit.js +101 -30
- package/src/tools/fsEdit.ts +105 -32
- package/src/tools/fsFind.js +8 -5
- package/src/tools/fsFind.ts +7 -4
- package/src/tools/fsRead.js +119 -13
- package/src/tools/fsRead.ts +124 -13
- package/src/tools/fsWrite.js +17 -5
- package/src/tools/fsWrite.ts +17 -7
- package/src/tools/generateMediaViaApi.js +82 -19
- package/src/tools/generateMediaViaApi.ts +80 -19
- package/src/tools/memoryRecall.js +62 -11
- package/src/tools/memoryRecall.ts +70 -13
- package/src/tools/memoryWrite.js +27 -14
- package/src/tools/memoryWrite.ts +30 -14
- package/src/tools/multiEdit.js +100 -30
- package/src/tools/multiEdit.ts +104 -32
- package/src/tools/nativeEngine.js +33 -18
- package/src/tools/nativeEngine.ts +31 -18
- package/src/tools/openSourceToolProvisioner.js +49 -14
- package/src/tools/openSourceToolProvisioner.ts +54 -15
- package/src/tools/osSandbox.js +513 -0
- package/src/tools/osSandbox.ts +588 -0
- package/src/tools/payloadSanitizer.js +40 -8
- package/src/tools/payloadSanitizer.ts +39 -8
- package/src/tools/peerAgent.js +96 -34
- package/src/tools/peerAgent.ts +114 -37
- package/src/tools/persistentShell.js +8 -3
- package/src/tools/pluginsFactory.js +38 -6
- package/src/tools/pluginsFactory.ts +42 -6
- package/src/tools/readNativeSkill.js +10 -8
- package/src/tools/readNativeSkill.ts +10 -8
- package/src/tools/requestDecision.js +10 -3
- package/src/tools/requestDecision.ts +10 -3
- package/src/tools/resolveAutomator.js +91 -17
- package/src/tools/resolveAutomator.ts +102 -17
- package/src/tools/reverseEngineering.js +168 -41
- package/src/tools/reverseEngineering.ts +161 -41
- package/src/tools/subprocessEnv.js +197 -0
- package/src/tools/subprocessEnv.ts +212 -0
- package/src/tools/sysRun.js +108 -35
- package/src/tools/sysRun.ts +119 -31
- package/src/tools/toolDispatch.js +24 -1
- package/src/tools/toolDispatch.ts +21 -1
- package/src/tools/toolOutputStore.js +62 -23
- package/src/tools/toolOutputStore.ts +56 -23
- package/src/tools/toolScanner.js +13 -10
- package/src/tools/toolScanner.ts +13 -10
- package/src/tools/toolSelfRepair.js +94 -28
- package/src/tools/toolSelfRepair.ts +96 -28
- package/src/tools/uiForge.js +71 -6
- package/src/tools/uiForge.ts +74 -6
- package/src/tools/viewImage.js +62 -17
- package/src/tools/viewImage.ts +57 -12
- package/src/tools/visionInspector.js +15 -3
- package/src/tools/visionInspector.ts +15 -3
- package/src/tools/walkerSafety.js +2 -0
- package/src/tools/walkerSafety.ts +1 -0
- package/src/tools/webFetch.js +105 -10
- package/src/tools/webFetch.ts +105 -11
- package/src/tui/banner.js +3 -2
- package/src/tui/banner.ts +3 -2
- package/src/tui/consoleGuard.js +12 -4
- package/src/tui/consoleGuard.ts +9 -4
- package/src/tui/messageInteraction.js +2 -3
- package/src/tui/messageInteraction.ts +2 -3
- package/src/tui/modelPicker.js +1 -0
- package/src/tui/modelPicker.ts +1 -0
- package/src/tui/overlay.js +3 -1
- package/src/tui/overlay.ts +3 -1
- package/src/tui/sessionPicker.js +3 -2
- package/src/tui/sessionPicker.ts +3 -2
- package/src/tui/sessionPickerView.js +7 -1
- package/src/tui/sessionPickerView.ts +6 -1
- package/src/tui/toolOutputNormalizer.js +2 -3
- package/src/tui/toolOutputNormalizer.ts +4 -3
- package/src/tui/viewport.js +4 -4
- package/src/tui/viewport.ts +5 -5
- package/src/tui/workspaceIdentity.js +2 -1
- package/src/tui/workspaceIdentity.ts +2 -1
- package/src/uncertainty.js +8 -3
- package/src/uncertainty.ts +8 -3
- package/src/utils/paths.js +8 -5
- package/src/utils/paths.ts +9 -7
- package/src/vfeTracker.js +9 -3
- package/src/vfeTracker.ts +9 -3
- package/src/config.d.ts +0 -2
- package/src/providers/base.d.ts +0 -94
- package/src/providers/factory.d.ts +0 -1
- package/src/sandbox.d.ts +0 -1
package/src/acp/client.ts
CHANGED
|
@@ -4,6 +4,9 @@ import fsSync from 'node:fs';
|
|
|
4
4
|
import fs from 'node:fs/promises';
|
|
5
5
|
import os from 'node:os';
|
|
6
6
|
import path from 'node:path';
|
|
7
|
+
import { isPhysicalPathAllowed } from '../agent/workspaceBoundary.js';
|
|
8
|
+
import { isCredentialPath } from '../sandbox.js';
|
|
9
|
+
import { redactProviderSecrets } from '../providers/byokHttp.js';
|
|
7
10
|
import {
|
|
8
11
|
ACP_ERROR_CODES,
|
|
9
12
|
ACP_METHODS,
|
|
@@ -73,11 +76,16 @@ function createAbortError(message = 'ACP operation aborted by user'): Error {
|
|
|
73
76
|
|
|
74
77
|
const MAX_STDERR_CHARS = 4000;
|
|
75
78
|
const MAX_UPDATE_CHARS = 200_000;
|
|
79
|
+
const MAX_HOST_FILE_BYTES = 4 * 1024 * 1024;
|
|
80
|
+
const MAX_JSONRPC_BUFFER_BYTES = 16 * 1024 * 1024;
|
|
81
|
+
const MAX_TRACKED_SESSIONS = 128;
|
|
82
|
+
const MAX_OPEN_TOOL_CALLS = 512;
|
|
76
83
|
|
|
77
84
|
export class AcpClient {
|
|
78
85
|
private readonly options: AcpClientOptions;
|
|
79
86
|
private child: ChildProcessWithoutNullStreams | null = null;
|
|
80
87
|
private buffer = '';
|
|
88
|
+
private draining = false;
|
|
81
89
|
private stderrTail = '';
|
|
82
90
|
private readonly pending = new Map<string | number, PendingRequest>();
|
|
83
91
|
private readonly openToolCalls = new Map<string, number>();
|
|
@@ -159,6 +167,10 @@ export class AcpClient {
|
|
|
159
167
|
usesConfigOption: extracted.usesConfigOption || Boolean(existing?.usesConfigOption),
|
|
160
168
|
configOptionId: extracted.configOptionId ?? existing?.configOptionId
|
|
161
169
|
};
|
|
170
|
+
if (!this.sessionModels.has(sessionId) && this.sessionModels.size >= MAX_TRACKED_SESSIONS) {
|
|
171
|
+
const oldest = this.sessionModels.keys().next().value;
|
|
172
|
+
if (oldest !== undefined) this.sessionModels.delete(oldest);
|
|
173
|
+
}
|
|
162
174
|
this.sessionModels.set(sessionId, merged);
|
|
163
175
|
this.latestSessionModels = merged;
|
|
164
176
|
}
|
|
@@ -167,9 +179,17 @@ export class AcpClient {
|
|
|
167
179
|
if (signal?.aborted) throw createAbortError();
|
|
168
180
|
if (this.child) throw new Error('client already started');
|
|
169
181
|
const args = this.options.args ?? [];
|
|
182
|
+
let childEnv: NodeJS.ProcessEnv;
|
|
183
|
+
if (this.options.env) {
|
|
184
|
+
childEnv = this.options.env;
|
|
185
|
+
} else {
|
|
186
|
+
childEnv = { ...process.env };
|
|
187
|
+
delete childEnv.CAUSYNE_VAULT_KEY;
|
|
188
|
+
delete childEnv.CAUSYNE_DEV_SECRET;
|
|
189
|
+
}
|
|
170
190
|
const child = spawn(this.options.command, args, {
|
|
171
191
|
cwd: this.options.cwd,
|
|
172
|
-
env:
|
|
192
|
+
env: childEnv,
|
|
173
193
|
stdio: ['pipe', 'pipe', 'pipe'],
|
|
174
194
|
windowsHide: true
|
|
175
195
|
});
|
|
@@ -179,6 +199,11 @@ export class AcpClient {
|
|
|
179
199
|
child.stdout.on('data', (chunk: string) => {
|
|
180
200
|
if (this.closed) return;
|
|
181
201
|
this.buffer += chunk;
|
|
202
|
+
if (this.buffer.length > MAX_JSONRPC_BUFFER_BYTES) {
|
|
203
|
+
this.buffer = '';
|
|
204
|
+
this.failAll(new Error('agent output frame exceeded maximum size'));
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
182
207
|
this.notifyPendingActivity();
|
|
183
208
|
void this.drain();
|
|
184
209
|
});
|
|
@@ -189,7 +214,8 @@ export class AcpClient {
|
|
|
189
214
|
});
|
|
190
215
|
child.on('error', (error) => this.failAll(new Error(`agent process failed: ${error.message}`)));
|
|
191
216
|
child.on('exit', (code, exitSignal) => {
|
|
192
|
-
const
|
|
217
|
+
const cleanTail = redactProviderSecrets(this.stderrTail).trim();
|
|
218
|
+
const detail = cleanTail || `exit code ${code ?? 'null'}${exitSignal ? ` signal ${exitSignal}` : ''}`;
|
|
193
219
|
this.failAll(new Error(`agent process exited: ${detail}`));
|
|
194
220
|
});
|
|
195
221
|
|
|
@@ -212,6 +238,9 @@ export class AcpClient {
|
|
|
212
238
|
}
|
|
213
239
|
|
|
214
240
|
async newSession(cwd: string, mcpServers: unknown[] = [], signal?: AbortSignal): Promise<string> {
|
|
241
|
+
if (typeof cwd !== 'string' || !cwd.trim() || cwd.includes('\0')) {
|
|
242
|
+
throw new Error('newSession requires a valid cwd');
|
|
243
|
+
}
|
|
215
244
|
const result = await this.request<{ sessionId?: unknown }>(ACP_METHODS.NEW_SESSION, {
|
|
216
245
|
cwd,
|
|
217
246
|
mcpServers
|
|
@@ -223,14 +252,20 @@ export class AcpClient {
|
|
|
223
252
|
return result.sessionId;
|
|
224
253
|
}
|
|
225
254
|
|
|
226
|
-
async authenticate(methodId: string, params: Record<string, unknown> = {}): Promise<unknown> {
|
|
255
|
+
async authenticate(methodId: string, params: Record<string, unknown> = {}, signal?: AbortSignal): Promise<unknown> {
|
|
256
|
+
if (typeof methodId !== 'string' || !methodId.trim()) {
|
|
257
|
+
throw new Error('authenticate requires a non-empty methodId');
|
|
258
|
+
}
|
|
227
259
|
return await this.request<unknown>(ACP_METHODS.AUTHENTICATE, {
|
|
228
|
-
methodId,
|
|
260
|
+
methodId: methodId.trim(),
|
|
229
261
|
params
|
|
230
|
-
}, 30_000);
|
|
262
|
+
}, 30_000, signal);
|
|
231
263
|
}
|
|
232
264
|
|
|
233
265
|
async setSessionModel(sessionId: string, modelId: string, signal?: AbortSignal): Promise<void> {
|
|
266
|
+
if (typeof sessionId !== 'string' || !sessionId.trim() || typeof modelId !== 'string' || !modelId.trim()) {
|
|
267
|
+
throw new Error('setSessionModel requires non-empty sessionId and modelId');
|
|
268
|
+
}
|
|
234
269
|
const state = this.sessionModels.get(sessionId) ?? this.latestSessionModels;
|
|
235
270
|
try {
|
|
236
271
|
const res = await this.request<unknown>(ACP_METHODS.SET_MODEL, {
|
|
@@ -261,18 +296,24 @@ export class AcpClient {
|
|
|
261
296
|
}
|
|
262
297
|
}
|
|
263
298
|
|
|
264
|
-
async setSessionMode(sessionId: string, modeId: string): Promise<void> {
|
|
299
|
+
async setSessionMode(sessionId: string, modeId: string, signal?: AbortSignal): Promise<void> {
|
|
300
|
+
if (typeof sessionId !== 'string' || !sessionId.trim() || typeof modeId !== 'string' || !modeId.trim()) {
|
|
301
|
+
throw new Error('setSessionMode requires non-empty sessionId and modeId');
|
|
302
|
+
}
|
|
265
303
|
await this.request<void>(ACP_METHODS.SET_MODE, {
|
|
266
304
|
sessionId,
|
|
267
305
|
modeId
|
|
268
|
-
}, 30_000);
|
|
306
|
+
}, 30_000, signal);
|
|
269
307
|
}
|
|
270
308
|
|
|
271
|
-
async loadSession(sessionId: string, cwd?: string): Promise<unknown> {
|
|
309
|
+
async loadSession(sessionId: string, cwd?: string, signal?: AbortSignal): Promise<unknown> {
|
|
310
|
+
if (typeof sessionId !== 'string' || !sessionId.trim()) {
|
|
311
|
+
throw new Error('loadSession requires a non-empty sessionId');
|
|
312
|
+
}
|
|
272
313
|
const res = await this.request<unknown>(ACP_METHODS.LOAD, {
|
|
273
314
|
sessionId,
|
|
274
315
|
cwd: cwd || this.options.cwd
|
|
275
|
-
}, 30_000);
|
|
316
|
+
}, 30_000, signal);
|
|
276
317
|
this.recordSessionModels(sessionId, res);
|
|
277
318
|
return res;
|
|
278
319
|
}
|
|
@@ -286,17 +327,22 @@ export class AcpClient {
|
|
|
286
327
|
this.notifyPendingActivity();
|
|
287
328
|
// handleLine already notifies options.onUpdate for this session. Calling
|
|
288
329
|
// it again here duplicated every live chunk and file-action frame.
|
|
289
|
-
if (
|
|
330
|
+
if (
|
|
331
|
+
update.sessionUpdate === 'agent_message_chunk' &&
|
|
332
|
+
update.content !== null &&
|
|
333
|
+
typeof update.content === 'object' &&
|
|
334
|
+
update.content.type === 'text' &&
|
|
335
|
+
typeof update.content.text === 'string'
|
|
336
|
+
) {
|
|
290
337
|
collected = `${collected}${update.content.text}`.slice(0, MAX_UPDATE_CHARS);
|
|
291
338
|
}
|
|
292
339
|
};
|
|
293
|
-
const
|
|
294
|
-
this.updateListener = (sessionIdFromEvent, update) => {
|
|
340
|
+
const listener = (sessionIdFromEvent: string, update: SessionUpdate): void => {
|
|
295
341
|
if (signal?.aborted) return;
|
|
296
342
|
this.notifyPendingActivity();
|
|
297
|
-
previous?.(sessionIdFromEvent, update);
|
|
298
343
|
if (sessionIdFromEvent === sessionId) collector(update);
|
|
299
344
|
};
|
|
345
|
+
this.updateListeners.add(listener);
|
|
300
346
|
const onAbort = (): void => {
|
|
301
347
|
try {
|
|
302
348
|
this.notifyCancel(sessionId);
|
|
@@ -306,12 +352,20 @@ export class AcpClient {
|
|
|
306
352
|
};
|
|
307
353
|
signal?.addEventListener('abort', onAbort, { once: true });
|
|
308
354
|
try {
|
|
355
|
+
const rawPromptTimeout = this.options.promptTimeoutMs;
|
|
356
|
+
const promptTimeoutMs = typeof rawPromptTimeout === 'number' && Number.isFinite(rawPromptTimeout) && rawPromptTimeout > 0
|
|
357
|
+
? Math.max(10, Math.min(3_600_000, Math.round(rawPromptTimeout)))
|
|
358
|
+
: 15 * 60 * 1000;
|
|
359
|
+
const rawInactivityTimeout = this.options.inactivityTimeoutMs;
|
|
360
|
+
const inactivityTimeoutMs = typeof rawInactivityTimeout === 'number' && Number.isFinite(rawInactivityTimeout) && rawInactivityTimeout > 0
|
|
361
|
+
? Math.max(10, Math.min(3_600_000, Math.round(rawInactivityTimeout)))
|
|
362
|
+
: 120_000;
|
|
309
363
|
const response = await this.request<PromptResponse>(ACP_METHODS.PROMPT, {
|
|
310
364
|
sessionId,
|
|
311
365
|
prompt: blocks
|
|
312
|
-
},
|
|
366
|
+
}, promptTimeoutMs, signal, {
|
|
313
367
|
sessionId,
|
|
314
|
-
inactivityTimeoutMs
|
|
368
|
+
inactivityTimeoutMs
|
|
315
369
|
});
|
|
316
370
|
return {
|
|
317
371
|
stopReason: response?.stopReason ?? 'end_turn',
|
|
@@ -320,7 +374,7 @@ export class AcpClient {
|
|
|
320
374
|
};
|
|
321
375
|
} finally {
|
|
322
376
|
signal?.removeEventListener('abort', onAbort);
|
|
323
|
-
this.
|
|
377
|
+
this.updateListeners.delete(listener);
|
|
324
378
|
this.clearOpenToolCalls(sessionId);
|
|
325
379
|
}
|
|
326
380
|
}
|
|
@@ -342,7 +396,13 @@ export class AcpClient {
|
|
|
342
396
|
if (status === 'completed' || status === 'failed' || status === 'cancelled') {
|
|
343
397
|
this.openToolCalls.delete(key);
|
|
344
398
|
} else if (record.sessionUpdate === 'tool_call' || status === 'pending' || status === 'in_progress') {
|
|
345
|
-
if (!this.openToolCalls.has(key))
|
|
399
|
+
if (!this.openToolCalls.has(key)) {
|
|
400
|
+
if (this.openToolCalls.size >= MAX_OPEN_TOOL_CALLS) {
|
|
401
|
+
const oldest = this.openToolCalls.keys().next().value;
|
|
402
|
+
if (oldest !== undefined) this.openToolCalls.delete(oldest);
|
|
403
|
+
}
|
|
404
|
+
this.openToolCalls.set(key, Date.now());
|
|
405
|
+
}
|
|
346
406
|
}
|
|
347
407
|
}
|
|
348
408
|
|
|
@@ -375,6 +435,9 @@ export class AcpClient {
|
|
|
375
435
|
this.closed = true;
|
|
376
436
|
const child = this.child;
|
|
377
437
|
this.child = null;
|
|
438
|
+
this.buffer = '';
|
|
439
|
+
this.openToolCalls.clear();
|
|
440
|
+
this.updateListeners.clear();
|
|
378
441
|
this.failAll(new Error('client closed'));
|
|
379
442
|
if (!child) return;
|
|
380
443
|
if (child.exitCode !== null || child.signalCode !== null) return;
|
|
@@ -407,7 +470,7 @@ export class AcpClient {
|
|
|
407
470
|
});
|
|
408
471
|
}
|
|
409
472
|
|
|
410
|
-
private
|
|
473
|
+
private readonly updateListeners = new Set<(sessionId: string, update: SessionUpdate) => void>();
|
|
411
474
|
|
|
412
475
|
private write(message: JsonRpcRequest<unknown> | JsonRpcResponse | JsonRpcNotification<unknown>): void {
|
|
413
476
|
if (!this.child || this.closed) return;
|
|
@@ -419,12 +482,18 @@ export class AcpClient {
|
|
|
419
482
|
}
|
|
420
483
|
|
|
421
484
|
private async drain(): Promise<void> {
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
485
|
+
if (this.draining) return;
|
|
486
|
+
this.draining = true;
|
|
487
|
+
try {
|
|
488
|
+
let index = this.buffer.indexOf('\n');
|
|
489
|
+
while (index >= 0 && !this.closed) {
|
|
490
|
+
const line = this.buffer.slice(0, index).replace(/^\uFEFF/, '').trim();
|
|
491
|
+
this.buffer = this.buffer.slice(index + 1);
|
|
492
|
+
if (line) await this.handleLine(line);
|
|
493
|
+
index = this.buffer.indexOf('\n');
|
|
494
|
+
}
|
|
495
|
+
} finally {
|
|
496
|
+
this.draining = false;
|
|
428
497
|
}
|
|
429
498
|
}
|
|
430
499
|
|
|
@@ -446,10 +515,18 @@ export class AcpClient {
|
|
|
446
515
|
const method = (parsed as { method?: unknown }).method;
|
|
447
516
|
if (method === ACP_METHODS.UPDATE) {
|
|
448
517
|
const params = (parsed as { params?: SessionNotification }).params;
|
|
449
|
-
if (
|
|
518
|
+
if (
|
|
519
|
+
params &&
|
|
520
|
+
typeof params.sessionId === 'string' &&
|
|
521
|
+
params.update !== null &&
|
|
522
|
+
typeof params.update === 'object' &&
|
|
523
|
+
!Array.isArray(params.update)
|
|
524
|
+
) {
|
|
450
525
|
this.recordSessionModels(params.sessionId, params.update);
|
|
451
526
|
this.trackToolCall(params.sessionId, params.update);
|
|
452
|
-
|
|
527
|
+
for (const listener of [...this.updateListeners]) {
|
|
528
|
+
listener(params.sessionId, params.update);
|
|
529
|
+
}
|
|
453
530
|
this.options.onUpdate?.(params.sessionId, params.update);
|
|
454
531
|
}
|
|
455
532
|
}
|
|
@@ -473,8 +550,12 @@ export class AcpClient {
|
|
|
473
550
|
return;
|
|
474
551
|
}
|
|
475
552
|
try {
|
|
476
|
-
const
|
|
477
|
-
|
|
553
|
+
const rawOutcome = await handler(request.params as unknown as RequestPermissionRequest);
|
|
554
|
+
const validOutcome: RequestPermissionResponse['outcome'] =
|
|
555
|
+
rawOutcome && typeof rawOutcome === 'object' && rawOutcome.outcome === 'selected' && typeof rawOutcome.optionId === 'string'
|
|
556
|
+
? { outcome: 'selected', optionId: rawOutcome.optionId }
|
|
557
|
+
: { outcome: 'cancelled' };
|
|
558
|
+
this.write({ jsonrpc: '2.0', id: request.id, result: { outcome: validOutcome } });
|
|
478
559
|
} catch {
|
|
479
560
|
this.write({ jsonrpc: '2.0', id: request.id, result: { outcome: { outcome: 'cancelled' } } });
|
|
480
561
|
}
|
|
@@ -501,8 +582,36 @@ export class AcpClient {
|
|
|
501
582
|
if (params?.limit !== undefined) readOpts.limit = params.limit;
|
|
502
583
|
content = await this.options.fsReadHandler(targetPath, readOpts);
|
|
503
584
|
} else {
|
|
585
|
+
if (targetPath.includes('\0')) {
|
|
586
|
+
throw new Error('File path contains invalid NUL byte');
|
|
587
|
+
}
|
|
504
588
|
const resolved = path.resolve(this.options.cwd, targetPath);
|
|
505
|
-
|
|
589
|
+
if (!isPhysicalPathAllowed(resolved, [this.options.cwd], false)) {
|
|
590
|
+
throw new Error('File path is outside the allowed workspace');
|
|
591
|
+
}
|
|
592
|
+
if (isCredentialPath(resolved)) {
|
|
593
|
+
throw new Error('Reading credential files via ACP host bridge is prohibited');
|
|
594
|
+
}
|
|
595
|
+
const stat = await fs.lstat(resolved);
|
|
596
|
+
if (stat.isSymbolicLink() || !stat.isFile()) {
|
|
597
|
+
throw new Error('Refusing to read symlink or non-regular file');
|
|
598
|
+
}
|
|
599
|
+
if (stat.size > MAX_HOST_FILE_BYTES) {
|
|
600
|
+
throw new Error(`File exceeds maximum readable size (${MAX_HOST_FILE_BYTES} bytes)`);
|
|
601
|
+
}
|
|
602
|
+
const rawContent = await fs.readFile(resolved, 'utf8');
|
|
603
|
+
if (typeof params?.line === 'number' || typeof params?.limit === 'number') {
|
|
604
|
+
const lines = rawContent.split(/\r?\n/);
|
|
605
|
+
const start = typeof params?.line === 'number' && Number.isFinite(params.line)
|
|
606
|
+
? Math.max(0, Math.floor(params.line) - 1)
|
|
607
|
+
: 0;
|
|
608
|
+
const count = typeof params?.limit === 'number' && Number.isFinite(params.limit) && params.limit > 0
|
|
609
|
+
? Math.floor(params.limit)
|
|
610
|
+
: lines.length;
|
|
611
|
+
content = lines.slice(start, start + count).join('\n');
|
|
612
|
+
} else {
|
|
613
|
+
content = rawContent;
|
|
614
|
+
}
|
|
506
615
|
}
|
|
507
616
|
this.write({
|
|
508
617
|
jsonrpc: '2.0',
|
|
@@ -537,7 +646,28 @@ export class AcpClient {
|
|
|
537
646
|
if (this.options.fsWriteHandler) {
|
|
538
647
|
await this.options.fsWriteHandler(targetPath, content);
|
|
539
648
|
} else {
|
|
649
|
+
if (targetPath.includes('\0')) {
|
|
650
|
+
throw new Error('File path contains invalid NUL byte');
|
|
651
|
+
}
|
|
652
|
+
if (Buffer.byteLength(content, 'utf8') > MAX_HOST_FILE_BYTES) {
|
|
653
|
+
throw new Error(`File content exceeds maximum writable size (${MAX_HOST_FILE_BYTES} bytes)`);
|
|
654
|
+
}
|
|
540
655
|
const resolved = path.resolve(this.options.cwd, targetPath);
|
|
656
|
+
if (!isPhysicalPathAllowed(resolved, [this.options.cwd], false)) {
|
|
657
|
+
throw new Error('File path is outside the allowed workspace');
|
|
658
|
+
}
|
|
659
|
+
if (isCredentialPath(resolved)) {
|
|
660
|
+
throw new Error('Writing credential files via ACP host bridge is prohibited');
|
|
661
|
+
}
|
|
662
|
+
try {
|
|
663
|
+
const existing = await fs.lstat(resolved);
|
|
664
|
+
if (existing.isSymbolicLink() || !existing.isFile()) {
|
|
665
|
+
throw new Error('Refusing to overwrite symlink or non-regular file');
|
|
666
|
+
}
|
|
667
|
+
} catch (statErr: unknown) {
|
|
668
|
+
const code = typeof statErr === 'object' && statErr !== null && 'code' in statErr ? String(statErr.code) : '';
|
|
669
|
+
if (code !== 'ENOENT') throw statErr;
|
|
670
|
+
}
|
|
541
671
|
await fs.mkdir(path.dirname(resolved), { recursive: true });
|
|
542
672
|
await fs.writeFile(resolved, content, 'utf8');
|
|
543
673
|
}
|
|
@@ -612,7 +742,7 @@ export class AcpClient {
|
|
|
612
742
|
for (const pat of fatalPatterns) {
|
|
613
743
|
if (pat.test(this.stderrTail)) {
|
|
614
744
|
const match = this.stderrTail.split('\n').find(l => pat.test(l));
|
|
615
|
-
if (match) return match.trim();
|
|
745
|
+
if (match) return redactProviderSecrets(match).trim();
|
|
616
746
|
}
|
|
617
747
|
}
|
|
618
748
|
}
|
|
@@ -628,10 +758,12 @@ export class AcpClient {
|
|
|
628
758
|
|
|
629
759
|
private inspectOpencodeLog(sessionId?: string, sinceEpochMs?: number): string | null {
|
|
630
760
|
try {
|
|
631
|
-
const
|
|
761
|
+
const home = os.homedir();
|
|
762
|
+
if (!home) return null;
|
|
763
|
+
const logPath = path.join(home, '.local', 'share', 'opencode', 'log', 'opencode.log');
|
|
632
764
|
if (!fsSync.existsSync(logPath)) return null;
|
|
633
|
-
const stat = fsSync.
|
|
634
|
-
if (stat.size === 0) return null;
|
|
765
|
+
const stat = fsSync.lstatSync(logPath);
|
|
766
|
+
if (stat.isSymbolicLink() || !stat.isFile() || stat.size === 0) return null;
|
|
635
767
|
const readBytes = Math.min(stat.size, 65536);
|
|
636
768
|
const buffer = Buffer.alloc(readBytes);
|
|
637
769
|
const fd = fsSync.openSync(logPath, 'r');
|
|
@@ -662,9 +794,9 @@ export class AcpClient {
|
|
|
662
794
|
if (line.includes('level=ERROR') || line.includes('AI_APICallError') || line.includes('Free usage limit reached') || line.includes('AI_RetryError')) {
|
|
663
795
|
const match = line.match(/error\.error="([^"]+)"/) || line.match(/message="([^"]+)"/);
|
|
664
796
|
if (match && match[1]) {
|
|
665
|
-
return match[1].replace(/\\n/g, ' ').trim();
|
|
797
|
+
return redactProviderSecrets(match[1].replace(/\\n/g, ' ')).trim();
|
|
666
798
|
}
|
|
667
|
-
return line.trim();
|
|
799
|
+
return redactProviderSecrets(line).trim();
|
|
668
800
|
}
|
|
669
801
|
}
|
|
670
802
|
} catch {
|
|
@@ -686,63 +818,81 @@ export class AcpClient {
|
|
|
686
818
|
const id = this.nextId++;
|
|
687
819
|
const requestStartMs = Date.now();
|
|
688
820
|
return new Promise<T>((resolve, reject) => {
|
|
821
|
+
let settled = false;
|
|
689
822
|
let inactivityTimer: NodeJS.Timeout | undefined;
|
|
690
823
|
let snifferInterval: NodeJS.Timeout | undefined;
|
|
691
824
|
|
|
692
825
|
const cleanup = (): void => {
|
|
693
826
|
signal?.removeEventListener('abort', onAbort);
|
|
694
|
-
if (inactivityTimer)
|
|
695
|
-
|
|
827
|
+
if (inactivityTimer) {
|
|
828
|
+
clearTimeout(inactivityTimer);
|
|
829
|
+
inactivityTimer = undefined;
|
|
830
|
+
}
|
|
831
|
+
if (snifferInterval) {
|
|
832
|
+
clearInterval(snifferInterval);
|
|
833
|
+
snifferInterval = undefined;
|
|
834
|
+
}
|
|
696
835
|
};
|
|
697
|
-
const
|
|
836
|
+
const settleResolve = (value: unknown): void => {
|
|
837
|
+
if (settled) return;
|
|
838
|
+
settled = true;
|
|
698
839
|
clearTimeout(timer);
|
|
699
840
|
cleanup();
|
|
700
841
|
this.pending.delete(id);
|
|
701
|
-
|
|
842
|
+
resolve(value as T);
|
|
702
843
|
};
|
|
703
|
-
const
|
|
844
|
+
const settleReject = (error: Error): void => {
|
|
845
|
+
if (settled) return;
|
|
846
|
+
settled = true;
|
|
847
|
+
clearTimeout(timer);
|
|
704
848
|
cleanup();
|
|
705
849
|
this.pending.delete(id);
|
|
850
|
+
reject(error);
|
|
851
|
+
};
|
|
852
|
+
const onAbort = (): void => {
|
|
853
|
+
settleReject(createAbortError());
|
|
854
|
+
};
|
|
855
|
+
const timer = setTimeout(() => {
|
|
706
856
|
const diag = this.inspectPeerDiagnostics(options?.sessionId, requestStartMs);
|
|
707
857
|
if (diag) {
|
|
708
|
-
|
|
858
|
+
settleReject(new Error(`ACP Peer Agent (${this.options.command}) Error: ${diag}`));
|
|
709
859
|
} else {
|
|
710
|
-
|
|
860
|
+
settleReject(new Error(`${method} timed out after ${timeoutMs}ms`));
|
|
711
861
|
}
|
|
712
862
|
}, timeoutMs);
|
|
713
863
|
if (typeof timer.unref === 'function') timer.unref();
|
|
714
864
|
|
|
715
865
|
const resetInactivity = (): void => {
|
|
866
|
+
if (settled) return;
|
|
716
867
|
const timeoutMsInact = options?.inactivityTimeoutMs;
|
|
717
868
|
if (!timeoutMsInact) return;
|
|
718
869
|
if (inactivityTimer) clearTimeout(inactivityTimer);
|
|
719
870
|
inactivityTimer = setTimeout(() => {
|
|
871
|
+
if (settled) return;
|
|
720
872
|
if (this.hasOpenToolCall(options?.sessionId) && !this.inspectPeerDiagnostics(options?.sessionId, requestStartMs)) {
|
|
721
873
|
resetInactivity();
|
|
722
874
|
return;
|
|
723
875
|
}
|
|
724
|
-
cleanup();
|
|
725
|
-
this.pending.delete(id);
|
|
726
876
|
const diag = this.inspectPeerDiagnostics(options?.sessionId, requestStartMs);
|
|
727
877
|
if (diag) {
|
|
728
|
-
|
|
878
|
+
settleReject(new Error(`ACP Peer Agent (${this.options.command}) Error: ${diag}`));
|
|
729
879
|
} else {
|
|
730
|
-
|
|
880
|
+
settleReject(new Error(`${method} stalled: no activity from peer in ${Math.round(timeoutMsInact / 1000)}s`));
|
|
731
881
|
}
|
|
732
882
|
}, timeoutMsInact);
|
|
733
883
|
if (typeof inactivityTimer.unref === 'function') inactivityTimer.unref();
|
|
884
|
+
const entry = this.pending.get(id);
|
|
885
|
+
if (entry) entry.inactivityTimer = inactivityTimer;
|
|
734
886
|
};
|
|
735
887
|
|
|
736
888
|
const sid = options?.sessionId;
|
|
737
889
|
if (sid) {
|
|
738
890
|
snifferInterval = setInterval(() => {
|
|
891
|
+
if (settled) return;
|
|
739
892
|
const fatalDiag = this.inspectPeerDiagnostics(sid, requestStartMs);
|
|
740
893
|
if (fatalDiag) {
|
|
741
|
-
cleanup();
|
|
742
|
-
clearTimeout(timer);
|
|
743
|
-
this.pending.delete(id);
|
|
744
894
|
try { this.notifyCancel(sid); } catch { /* ignore */ }
|
|
745
|
-
|
|
895
|
+
settleReject(new Error(`ACP Peer Agent (${this.options.command}) Error: ${fatalDiag}`));
|
|
746
896
|
}
|
|
747
897
|
}, 1500);
|
|
748
898
|
if (typeof snifferInterval.unref === 'function') snifferInterval.unref();
|
|
@@ -751,8 +901,8 @@ export class AcpClient {
|
|
|
751
901
|
resetInactivity();
|
|
752
902
|
signal?.addEventListener('abort', onAbort, { once: true });
|
|
753
903
|
this.pending.set(id, {
|
|
754
|
-
resolve:
|
|
755
|
-
reject,
|
|
904
|
+
resolve: settleResolve,
|
|
905
|
+
reject: settleReject,
|
|
756
906
|
timer,
|
|
757
907
|
inactivityTimer,
|
|
758
908
|
snifferInterval,
|
package/src/acp/peerProfiles.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import fs from 'node:fs';
|
|
2
2
|
import path from 'node:path';
|
|
3
3
|
import { causyneHome } from '../utils/paths.js';
|
|
4
|
+
import { isBlockedWorkspaceRoot } from '../sandboxPolicy.js';
|
|
5
|
+
import { atomicWriteSecretFileSync } from '../configVault.js';
|
|
4
6
|
import { getPresetProfile, BUILTIN_PEER_PRESETS } from './agentCatalog.js';
|
|
5
7
|
const PROFILE_ID = /^[a-z0-9][a-z0-9._-]{0,63}$/;
|
|
6
8
|
const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
|
|
@@ -19,7 +21,7 @@ function asStringArray(value, limit, maxChars) {
|
|
|
19
21
|
return null;
|
|
20
22
|
const result = [];
|
|
21
23
|
for (const item of value) {
|
|
22
|
-
if (typeof item !== 'string')
|
|
24
|
+
if (typeof item !== 'string' || /[\r\n\0]/.test(item))
|
|
23
25
|
return null;
|
|
24
26
|
result.push(item.slice(0, maxChars));
|
|
25
27
|
}
|
|
@@ -35,7 +37,7 @@ function asEnv(value) {
|
|
|
35
37
|
break;
|
|
36
38
|
if (!ENV_NAME.test(name))
|
|
37
39
|
continue;
|
|
38
|
-
if (typeof raw !== 'string')
|
|
40
|
+
if (typeof raw !== 'string' || raw.includes('\0'))
|
|
39
41
|
continue;
|
|
40
42
|
result[name] = raw.slice(0, MAX_ENV_VALUE_CHARS);
|
|
41
43
|
count += 1;
|
|
@@ -50,38 +52,48 @@ function parseProfile(raw) {
|
|
|
50
52
|
if (!PROFILE_ID.test(id))
|
|
51
53
|
return null;
|
|
52
54
|
const command = typeof record.command === 'string' ? record.command.trim() : '';
|
|
53
|
-
if (!command || command.length > 500)
|
|
55
|
+
if (!command || command.length > 500 || /[\r\n\0]/.test(command))
|
|
54
56
|
return null;
|
|
55
57
|
const args = asStringArray(record.args ?? [], MAX_ARGS, MAX_ARG_CHARS);
|
|
56
58
|
if (args === null)
|
|
57
59
|
return null;
|
|
58
60
|
let cwd = null;
|
|
59
61
|
if (typeof record.cwd === 'string' && record.cwd.trim()) {
|
|
62
|
+
if (/[\r\n\0]/.test(record.cwd))
|
|
63
|
+
return null;
|
|
60
64
|
const resolved = path.resolve(record.cwd.trim());
|
|
65
|
+
if (isBlockedWorkspaceRoot(resolved))
|
|
66
|
+
return null;
|
|
61
67
|
try {
|
|
62
|
-
|
|
68
|
+
const real = fs.realpathSync(resolved);
|
|
69
|
+
if (isBlockedWorkspaceRoot(real))
|
|
63
70
|
return null;
|
|
64
|
-
|
|
71
|
+
if (!fs.statSync(real).isDirectory())
|
|
72
|
+
return null;
|
|
73
|
+
cwd = real;
|
|
65
74
|
}
|
|
66
75
|
catch {
|
|
67
76
|
return null;
|
|
68
77
|
}
|
|
69
78
|
}
|
|
70
|
-
const policy = record.policy ===
|
|
71
|
-
? '
|
|
72
|
-
: (record.policy === '
|
|
79
|
+
const policy = record.policy === undefined
|
|
80
|
+
? 'workspace'
|
|
81
|
+
: (record.policy === 'read-only' ? 'read-only' : (record.policy === 'workspace' ? 'workspace' : 'ask'));
|
|
73
82
|
const timeoutSeconds = typeof record.timeoutSeconds === 'number' && Number.isFinite(record.timeoutSeconds)
|
|
74
83
|
? Math.max(5, Math.min(1800, Math.round(record.timeoutSeconds)))
|
|
75
84
|
: 120;
|
|
76
|
-
const
|
|
77
|
-
|
|
78
|
-
: id;
|
|
85
|
+
const rawLabel = typeof record.label === 'string' ? record.label.replace(/[\r\n\0]+/g, ' ').trim() : '';
|
|
86
|
+
const label = rawLabel ? rawLabel.slice(0, 100) : id;
|
|
79
87
|
return { id, label, command, args, cwd, policy, timeoutSeconds, env: asEnv(record.env) };
|
|
80
88
|
}
|
|
81
89
|
export function loadPeerProfiles() {
|
|
82
90
|
let raw;
|
|
83
91
|
try {
|
|
84
|
-
|
|
92
|
+
const file = peerProfilesPath();
|
|
93
|
+
const stat = fs.lstatSync(file);
|
|
94
|
+
if (stat.isSymbolicLink() || !stat.isFile() || stat.size > 1024 * 1024)
|
|
95
|
+
return [];
|
|
96
|
+
raw = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
85
97
|
}
|
|
86
98
|
catch {
|
|
87
99
|
return [];
|
|
@@ -111,27 +123,27 @@ export function loadPeerProfiles() {
|
|
|
111
123
|
}
|
|
112
124
|
export function savePeerProfiles(profiles) {
|
|
113
125
|
const file = peerProfilesPath();
|
|
114
|
-
const dir = path.dirname(file);
|
|
115
|
-
if (!fs.existsSync(dir)) {
|
|
116
|
-
fs.mkdirSync(dir, { recursive: true });
|
|
117
|
-
}
|
|
118
126
|
const content = {
|
|
119
127
|
schemaVersion: 1,
|
|
120
128
|
peers: profiles
|
|
121
129
|
};
|
|
122
|
-
|
|
130
|
+
atomicWriteSecretFileSync(file, JSON.stringify(content, null, 2));
|
|
123
131
|
}
|
|
124
132
|
export function addPeerProfile(profile) {
|
|
133
|
+
const validated = parseProfile(profile);
|
|
134
|
+
if (!validated) {
|
|
135
|
+
return { ok: false, error: 'Invalid peer profile configuration.' };
|
|
136
|
+
}
|
|
125
137
|
const current = loadPeerProfiles();
|
|
126
|
-
const idx = current.findIndex((p) => p.id ===
|
|
138
|
+
const idx = current.findIndex((p) => p.id === validated.id);
|
|
127
139
|
if (idx >= 0) {
|
|
128
|
-
current[idx] =
|
|
140
|
+
current[idx] = validated;
|
|
129
141
|
}
|
|
130
142
|
else {
|
|
131
143
|
if (current.length >= MAX_PEERS) {
|
|
132
144
|
return { ok: false, error: `Maximum of ${MAX_PEERS} peer profiles exceeded.` };
|
|
133
145
|
}
|
|
134
|
-
current.push(
|
|
146
|
+
current.push(validated);
|
|
135
147
|
}
|
|
136
148
|
try {
|
|
137
149
|
savePeerProfiles(current);
|
|
@@ -187,14 +199,35 @@ export function listAllPeers() {
|
|
|
187
199
|
}
|
|
188
200
|
return all;
|
|
189
201
|
}
|
|
202
|
+
const BLOCKED_PEER_ENV_KEYS = new Set([
|
|
203
|
+
'LD_PRELOAD',
|
|
204
|
+
'LD_LIBRARY_PATH',
|
|
205
|
+
'DYLD_INSERT_LIBRARIES',
|
|
206
|
+
'DYLD_LIBRARY_PATH',
|
|
207
|
+
'DYLD_FRAMEWORK_PATH',
|
|
208
|
+
'NODE_OPTIONS',
|
|
209
|
+
'BASH_ENV',
|
|
210
|
+
'ENV',
|
|
211
|
+
'PYTHONSTARTUP'
|
|
212
|
+
]);
|
|
190
213
|
export function peerEnvironment(profile) {
|
|
191
214
|
const env = {};
|
|
192
|
-
|
|
215
|
+
const baseKeys = [
|
|
216
|
+
'PATH', 'Path', 'PATHEXT', 'HOME', 'USERPROFILE', 'APPDATA', 'LOCALAPPDATA',
|
|
217
|
+
'USER', 'LOGNAME', 'TMPDIR', 'TMP', 'TEMP', 'LANG', 'LC_ALL',
|
|
218
|
+
'SYSTEMROOT', 'SystemRoot', 'COMSPEC', 'ComSpec', 'ProgramData'
|
|
219
|
+
];
|
|
220
|
+
for (const name of baseKeys) {
|
|
193
221
|
const value = process.env[name];
|
|
194
222
|
if (typeof value === 'string')
|
|
195
223
|
env[name] = value;
|
|
196
224
|
}
|
|
197
|
-
for (const [name, value] of Object.entries(profile.env))
|
|
225
|
+
for (const [name, value] of Object.entries(profile.env)) {
|
|
226
|
+
if (BLOCKED_PEER_ENV_KEYS.has(name.toUpperCase()))
|
|
227
|
+
continue;
|
|
228
|
+
if (!ENV_NAME.test(name) || typeof value !== 'string' || value.includes('\0'))
|
|
229
|
+
continue;
|
|
198
230
|
env[name] = value;
|
|
231
|
+
}
|
|
199
232
|
return env;
|
|
200
233
|
}
|