@causyne/agent 1.20.87 → 1.20.91
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/package.json +1 -1
- package/src/agent/abortableDelay.js +37 -0
- package/src/agent/abortableDelay.ts +38 -0
- package/src/agent/providerFailure.js +30 -0
- package/src/agent/providerFailure.ts +33 -0
- package/src/agent/toolTurnIntegrity.js +139 -0
- package/src/agent/toolTurnIntegrity.ts +165 -0
- package/src/agent/workspaceBoundary.js +79 -0
- package/src/agent/workspaceBoundary.ts +83 -0
- package/src/agentLoop.js +113 -28
- package/src/agentLoop.ts +109 -26
- package/src/providers/acp.js +41 -6
- package/src/providers/acp.ts +46 -6
- package/src/sandbox.js +9 -43
- package/src/skills/skillResourceSafety.js +174 -0
- package/src/skills/skillResourceSafety.ts +174 -0
- package/src/skills/skillSearchSafety.js +31 -0
- package/src/skills/skillSearchSafety.ts +33 -0
- package/src/tools/deferredMcpSearch.js +11 -12
- package/src/tools/deferredMcpSearch.ts +11 -11
- package/src/tools/readNativeSkill.js +146 -35
- package/src/tools/readNativeSkill.ts +156 -0
- package/src/tools/toolDispatch.js +83 -119
- package/src/tools/toolDispatch.ts +142 -0
- package/src/tools/toolSelfRepair.js +8 -0
- package/src/tools/toolSelfRepair.ts +8 -0
- package/src/tui/chatRenderer.js +19 -11
- package/src/tui/skillAuthoring.js +0 -1
- package/src/tui/skillAuthoring.ts +1 -2
- package/src/tui/transcript.js +16 -0
- package/src/userSkills.d.ts +26 -0
- package/src/userSkills.js +21 -1
package/src/providers/acp.ts
CHANGED
|
@@ -11,6 +11,7 @@ import { createHash } from 'node:crypto';
|
|
|
11
11
|
import path from 'node:path';
|
|
12
12
|
import { PEER_COLLABORATION_POLICY } from './collaborationPolicy.js';
|
|
13
13
|
import { extractToolCallJsonObjects, stripToolCallMarkup, resolveToolCallEnvelopeArguments } from '../implementationPlan.js';
|
|
14
|
+
import { canonicalizeToolName } from '../tools/toolSelfRepair.js';
|
|
14
15
|
|
|
15
16
|
interface AcpTransportSnapshot {
|
|
16
17
|
conversationId: string;
|
|
@@ -109,7 +110,8 @@ export class AcpProvider extends LLMProvider {
|
|
|
109
110
|
'\n\n[ACP Tool Routing & Workspace Boundary Rules]\n' +
|
|
110
111
|
'1. NATIVE FUNCTION CHANNEL vs CAUSYNE HOST XML CHANNEL:\n' +
|
|
111
112
|
' - Your native function-calling channel ONLY accepts your own native tools (such as `read`, `write`, `edit`, `bash`, `glob`, `grep`, `todowrite`, and configured MCP tools). Use your native tools directly for workspace file reads/writes, shell commands, and todo checklists (use `todowrite` if available instead of calling `update_plan` as a native function).\n' +
|
|
112
|
-
' - Causyne host tools listed under [Available Tools] / [Current Available Tools] (such as `browser_act`, `screenshot`, `vision_inspect_ui`, `update_plan`, `memory_write`, `ui_forge`, `astryx_oracle`, `tool_search`) are NOT registered in your native function-calling schema. NEVER invoke them as native function calls (`to=browser_act` or `to=update_plan`), NEVER call `tool_call` as a native tool, and NEVER emit dummy `bash` (`echo`) calls while trying to invoke them.\n' +
|
|
113
|
+
' - Causyne host tools listed under [Available Tools] / [Current Available Tools] (such as `browser_act`, `screenshot`, `vision_inspect_ui`, `update_plan`, `memory_write`, `ui_forge`, `astryx_oracle`, `tool_search`, `fs_read_skill`) are NOT registered in your native function-calling schema. NEVER invoke them as native function calls (`to=browser_act` or `to=update_plan`), NEVER call `tool_call` as a native tool, and NEVER emit dummy `bash` (`echo`) calls while trying to invoke them.\n' +
|
|
114
|
+
' - Bundled Causyne skills must be read via the host tool `fs_read_skill`. Do NOT call peer-native `skill` or functions for Causyne skills. To read a skill, write `<tool_call>{"name": "fs_read_skill", "arguments": {"skill_id": "domain/name"}}</tool_call>` directly in your assistant text response.\n' +
|
|
113
115
|
' - To invoke a Causyne host tool, write `<tool_call>{"name": "tool_name", "arguments": { ... }}</tool_call>` directly in your assistant text response with NO native function call in that step; Causyne will execute the host tool and return the result on the next turn.\n' +
|
|
114
116
|
'2. WORKSPACE PATH BOUNDARY (NO /tmp):\n' +
|
|
115
117
|
' - Keep ALL temporary files, server logs, and headless browser screenshots inside the active workspace directory (for example, `./.shots/preview.png` or `./server.log`). NEVER write to, read from, or `cp`/`mv` paths in `/tmp` or outside the workspace root, as the host sandbox rejects `/tmp` access.\n\n[Language & Communication Directive]\nDynamically reflect and match the exact language used by the user in their prompt. Respond naturally in that same language.'
|
|
@@ -183,7 +185,8 @@ export class AcpProvider extends LLMProvider {
|
|
|
183
185
|
'\n\n[ACP Tool Routing & Workspace Boundary Rules]\n' +
|
|
184
186
|
'1. NATIVE FUNCTION CHANNEL vs CAUSYNE HOST XML CHANNEL:\n' +
|
|
185
187
|
' - Your native function-calling channel ONLY accepts your own native tools (such as `read`, `write`, `edit`, `bash`, `glob`, `grep`, `todowrite`, and configured MCP tools). Use your native tools directly for workspace file reads/writes, shell commands, and todo checklists (use `todowrite` if available instead of calling `update_plan` as a native function).\n' +
|
|
186
|
-
' - Causyne host tools listed under [Current Available Tools] (such as `browser_act`, `screenshot`, `vision_inspect_ui`, `update_plan`, `memory_write`, `ui_forge`, `astryx_oracle`, `tool_search`) are NOT registered in your native function-calling schema. NEVER invoke them as native function calls (`to=browser_act` or `to=update_plan`), NEVER call `tool_call` as a native tool, and NEVER emit dummy `bash` (`echo`) calls while trying to invoke them.\n' +
|
|
188
|
+
' - Causyne host tools listed under [Current Available Tools] (such as `browser_act`, `screenshot`, `vision_inspect_ui`, `update_plan`, `memory_write`, `ui_forge`, `astryx_oracle`, `tool_search`, `fs_read_skill`) are NOT registered in your native function-calling schema. NEVER invoke them as native function calls (`to=browser_act` or `to=update_plan`), NEVER call `tool_call` as a native tool, and NEVER emit dummy `bash` (`echo`) calls while trying to invoke them.\n' +
|
|
189
|
+
' - Bundled Causyne skills must be read via the host tool `fs_read_skill`. Do NOT call peer-native `skill` or functions for Causyne skills. To read a skill, write `<tool_call>{"name": "fs_read_skill", "arguments": {"skill_id": "domain/name"}}</tool_call>` directly in your assistant text response.\n' +
|
|
187
190
|
' - To invoke a Causyne host tool, write `<tool_call>{"name": "tool_name", "arguments": { ... }}</tool_call>` directly in your assistant text response with NO native function call in that step; Causyne will execute the host tool and return the result on the next turn.\n' +
|
|
188
191
|
'2. WORKSPACE PATH BOUNDARY (NO /tmp):\n' +
|
|
189
192
|
' - Keep ALL temporary files, server logs, and headless browser screenshots inside the active workspace directory (for example, `./.shots/preview.png` or `./server.log`). NEVER write to, read from, or `cp`/`mv` paths in `/tmp` or outside the workspace root, as the host sandbox rejects `/tmp` access.'
|
|
@@ -479,12 +482,22 @@ export class AcpProvider extends LLMProvider {
|
|
|
479
482
|
|| earlier?.parameters?.__invalidTool === true
|
|
480
483
|
|| (typeof input.error === 'string' && input.error.length > 0 && typeof input.tool === 'string');
|
|
481
484
|
if (isInvalidPseudoTool) {
|
|
482
|
-
const
|
|
483
|
-
|
|
484
|
-
|
|
485
|
+
const rawRequested = typeof input.tool === 'string' ? input.tool : '';
|
|
486
|
+
const canonicalRequested = canonicalizeToolName(rawRequested);
|
|
487
|
+
const hasDirectMatch = normalizeToolContracts(this.peerServices?.tools || []).some(tool => tool.name === rawRequested);
|
|
488
|
+
const hasCanonicalMatch = normalizeToolContracts(this.peerServices?.tools || []).some(tool => tool.name === canonicalRequested);
|
|
489
|
+
const requested = hasDirectMatch ? rawRequested : (hasCanonicalMatch ? canonicalRequested : '');
|
|
490
|
+
if (!this.toolRoutingError && requested) {
|
|
491
|
+
let rawArgs = (input.args && typeof input.args === 'object') ? input.args
|
|
485
492
|
: (input.parameters && typeof input.parameters === 'object') ? input.parameters
|
|
486
|
-
: (earlier?.parameters && typeof earlier.parameters === 'object') ? earlier.parameters
|
|
493
|
+
: (earlier?.parameters && typeof earlier.parameters === 'object' && !earlier.parameters.__pendingStub) ? earlier.parameters
|
|
487
494
|
: undefined;
|
|
495
|
+
if (rawArgs && typeof rawArgs === 'object') {
|
|
496
|
+
const cleanArgs = { ...rawArgs };
|
|
497
|
+
delete (cleanArgs as any).__pendingStub;
|
|
498
|
+
delete (cleanArgs as any).__invalidTool;
|
|
499
|
+
rawArgs = Object.keys(cleanArgs).length > 0 ? cleanArgs : undefined;
|
|
500
|
+
}
|
|
488
501
|
this.toolRoutingError = {
|
|
489
502
|
tool: requested,
|
|
490
503
|
message: typeof input.error === 'string' ? input.error : 'Host tool requested through the peer-native channel',
|
|
@@ -496,6 +509,33 @@ export class AcpProvider extends LLMProvider {
|
|
|
496
509
|
this.turnActions.delete(id);
|
|
497
510
|
return;
|
|
498
511
|
}
|
|
512
|
+
|
|
513
|
+
const isPeerNativeSkill = rawTitle.toLowerCase() === 'skill'
|
|
514
|
+
|| name.toLowerCase() === 'skill'
|
|
515
|
+
|| earlier?.name === 'skill';
|
|
516
|
+
const isFailedSkill = isPeerNativeSkill && (
|
|
517
|
+
updateObj.status === 'failed'
|
|
518
|
+
|| (typeof input.error === 'string' && /Skill\s+.*not found/i.test(input.error))
|
|
519
|
+
|| (typeof (updateObj as any).error === 'string' && /Skill\s+.*not found/i.test((updateObj as any).error))
|
|
520
|
+
|| (typeof rawOutputObj?.error === 'string' && /Skill\s+.*not found/i.test(rawOutputObj.error))
|
|
521
|
+
);
|
|
522
|
+
if (isFailedSkill) {
|
|
523
|
+
if (!this.toolRoutingError) {
|
|
524
|
+
const requestedSkill = String(
|
|
525
|
+
input.name || input.id || input.skill_id || input.skill || input.path
|
|
526
|
+
|| (earlier?.parameters as any)?.name || (earlier?.parameters as any)?.id || (earlier?.parameters as any)?.skill_id || ''
|
|
527
|
+
).trim();
|
|
528
|
+
this.toolRoutingError = {
|
|
529
|
+
tool: 'fs_read_skill',
|
|
530
|
+
message: `Peer-native skill not found in peer catalog; routed to Causyne host tool fs_read_skill`,
|
|
531
|
+
parameters: requestedSkill ? { skill_id: requestedSkill } : undefined
|
|
532
|
+
};
|
|
533
|
+
client.notifyCancel(sessionId);
|
|
534
|
+
}
|
|
535
|
+
this.liveFileActions.delete(id);
|
|
536
|
+
this.turnActions.delete(id);
|
|
537
|
+
return;
|
|
538
|
+
}
|
|
499
539
|
const locationPath = updateObj.locations?.[0]?.path;
|
|
500
540
|
const inputPath = typeof input.path === 'string' ? input.path
|
|
501
541
|
: typeof input.filePath === 'string' ? input.filePath
|
package/src/sandbox.js
CHANGED
|
@@ -4,6 +4,7 @@ import { isIP } from 'node:net';
|
|
|
4
4
|
import { loadConfig } from './config.js';
|
|
5
5
|
import { isDevEmulator } from './devMode.js';
|
|
6
6
|
import { validateBrowserActSandbox } from './browser/causyneBrowser.js';
|
|
7
|
+
import { isPhysicalPathAllowed } from './agent/workspaceBoundary.js';
|
|
7
8
|
|
|
8
9
|
|
|
9
10
|
function maskQuotedSpans(text) {
|
|
@@ -374,49 +375,14 @@ export class Sandbox {
|
|
|
374
375
|
}
|
|
375
376
|
|
|
376
377
|
isPathAllowed(targetPath) {
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
const isWindows = os.platform() === 'win32';
|
|
386
|
-
let isBlocked = false;
|
|
387
|
-
|
|
388
|
-
if (isWindows) {
|
|
389
|
-
const WIN_BLOCKED = ['C:\\Windows', 'C:\\Program Files', 'C:\\ProgramData'];
|
|
390
|
-
isBlocked = WIN_BLOCKED.some(blocked => resolved.toLowerCase().startsWith(blocked.toLowerCase()));
|
|
391
|
-
} else {
|
|
392
|
-
const UNIX_BLOCKED = ['/etc', '/usr/bin', '/usr/sbin', '/sbin', '/bin', '/System', '/private/var'];
|
|
393
|
-
isBlocked = UNIX_BLOCKED.some(blocked => resolved.startsWith(blocked));
|
|
394
|
-
}
|
|
395
|
-
|
|
396
|
-
if (isBlocked) {
|
|
397
|
-
return false;
|
|
398
|
-
}
|
|
399
|
-
|
|
400
|
-
// V6: Override workspace limits if grantAllAccess is active
|
|
401
|
-
if (this.grantAllAccess) {
|
|
402
|
-
return true;
|
|
403
|
-
}
|
|
404
|
-
|
|
405
|
-
// Check if resolved path is inside any allowed workspace path.
|
|
406
|
-
//
|
|
407
|
-
// L2 (local-path audit): this was a bare `resolved.startsWith(allowedBase)`,
|
|
408
|
-
// which is a STRING prefix test, not a PATH containment test. With the scope
|
|
409
|
-
// set to /Users/x/Projects it also accepted /Users/x/Projects-secret and
|
|
410
|
-
// /Users/x/ProjectsBACKUP — any sibling whose name merely begins with the
|
|
411
|
-
// workspace name. The separator check is what makes it a directory boundary.
|
|
412
|
-
return this.workspacePaths.some(workspace => {
|
|
413
|
-
let allowedBase = workspace;
|
|
414
|
-
if (allowedBase.startsWith('~/')) {
|
|
415
|
-
allowedBase = path.join(os.homedir(), allowedBase.slice(2));
|
|
416
|
-
}
|
|
417
|
-
allowedBase = path.resolve(allowedBase);
|
|
418
|
-
return resolved === allowedBase || resolved.startsWith(allowedBase + path.sep);
|
|
419
|
-
});
|
|
378
|
+
if (typeof targetPath !== 'string' || targetPath.length === 0) return false;
|
|
379
|
+
const expand = (value) => value.startsWith('~/')
|
|
380
|
+
? path.join(os.homedir(), value.slice(2)) : value;
|
|
381
|
+
const workspaces = Array.isArray(this.workspacePaths)
|
|
382
|
+
? this.workspacePaths.filter(item => typeof item === 'string').map(expand) : [];
|
|
383
|
+
// Resolve physical ancestors, including symlinks, before checking the scope.
|
|
384
|
+
// Missing destination files remain possible inside a valid workspace.
|
|
385
|
+
return isPhysicalPathAllowed(expand(targetPath), workspaces, this.grantAllAccess === true);
|
|
420
386
|
}
|
|
421
387
|
|
|
422
388
|
isInternalUrl(urlString, { allowLoopback = false } = {}) {
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Causyne Agent — skill file boundaries and progressive resource disclosure.
|
|
3
|
+
*
|
|
4
|
+
* Purely local, synchronous, bounded, cross-platform. The user-skill loader,
|
|
5
|
+
* mutation API, and fs_read_skill all use this same security boundary.
|
|
6
|
+
*
|
|
7
|
+
* This is application-level containment, not a substitute for OS isolation.
|
|
8
|
+
* No skill code is executed here.
|
|
9
|
+
*/
|
|
10
|
+
import fs from 'node:fs';
|
|
11
|
+
import path from 'node:path';
|
|
12
|
+
export const MAX_SKILL_RESOURCE_BYTES = 12 * 1024;
|
|
13
|
+
export const MAX_ADVERTISED_SKILL_RESOURCES = 12;
|
|
14
|
+
const SKILL_SEGMENT = /^[a-z0-9][a-z0-9-]{0,63}$/;
|
|
15
|
+
const RESERVED_WINDOWS = /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])$/i;
|
|
16
|
+
const RESOURCE_GROUPS = new Set(['references', 'templates', 'scripts', 'assets']);
|
|
17
|
+
const TEXT_EXTENSIONS = new Set([
|
|
18
|
+
'.md', '.mdx', '.txt', '.json', '.yaml', '.yml', '.toml', '.sql',
|
|
19
|
+
'.py', '.js', '.mjs', '.cjs', '.ts', '.tsx', '.sh', '.css', '.html',
|
|
20
|
+
'.xml', '.csv', '.svg'
|
|
21
|
+
]);
|
|
22
|
+
function checkSkillSegment(segment) {
|
|
23
|
+
if (!SKILL_SEGMENT.test(segment) || RESERVED_WINDOWS.test(segment)) {
|
|
24
|
+
throw new Error(`Invalid skill path segment ${JSON.stringify(segment)}.`);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
function inspectDirectory(directory, allowMissing) {
|
|
28
|
+
let stat;
|
|
29
|
+
try {
|
|
30
|
+
stat = fs.lstatSync(directory);
|
|
31
|
+
}
|
|
32
|
+
catch (error) {
|
|
33
|
+
if (allowMissing && error?.code === 'ENOENT')
|
|
34
|
+
return false;
|
|
35
|
+
throw error;
|
|
36
|
+
}
|
|
37
|
+
if (stat.isSymbolicLink() || !stat.isDirectory()) {
|
|
38
|
+
throw new Error(`Skill directory is not a real directory: ${directory}`);
|
|
39
|
+
}
|
|
40
|
+
return true;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Check each directory segment. In particular, do not let a skill author
|
|
44
|
+
* place a symlink at ~/.causyne/skills/<domain> or <name> and redirect writes
|
|
45
|
+
* into an unrelated folder. `path.resolve()` alone does NOT provide this.
|
|
46
|
+
*/
|
|
47
|
+
export function assertSkillTreeSafe(root, domain, name, allowMissing = false) {
|
|
48
|
+
checkSkillSegment(domain);
|
|
49
|
+
checkSkillSegment(name);
|
|
50
|
+
const base = path.resolve(root);
|
|
51
|
+
const domainDir = path.join(base, domain);
|
|
52
|
+
const skillDir = path.join(domainDir, name);
|
|
53
|
+
if (!inspectDirectory(base, allowMissing))
|
|
54
|
+
return skillDir;
|
|
55
|
+
if (!inspectDirectory(domainDir, allowMissing))
|
|
56
|
+
return skillDir;
|
|
57
|
+
inspectDirectory(skillDir, allowMissing);
|
|
58
|
+
return skillDir;
|
|
59
|
+
}
|
|
60
|
+
function checkRelativeResource(relativePath) {
|
|
61
|
+
if (typeof relativePath !== 'string' || relativePath.length < 3 || relativePath.length > 240) {
|
|
62
|
+
throw new Error('Skill resource path must be a short relative string.');
|
|
63
|
+
}
|
|
64
|
+
// The API uses portable POSIX-relative names, including on Windows.
|
|
65
|
+
if (/^[A-Za-z]:/.test(relativePath) || relativePath.startsWith('/') ||
|
|
66
|
+
relativePath.includes('\\') || /[\x00-\x1f\x7f<>"']/.test(relativePath)) {
|
|
67
|
+
throw new Error('Absolute, Windows, or control-character resource paths are not permitted.');
|
|
68
|
+
}
|
|
69
|
+
const parts = relativePath.split('/');
|
|
70
|
+
if (parts.length < 2 || parts.length > 5 || !RESOURCE_GROUPS.has(parts[0] ?? '')) {
|
|
71
|
+
throw new Error('Use a relative file within references/, templates/, scripts/, or assets/.');
|
|
72
|
+
}
|
|
73
|
+
for (const segment of parts) {
|
|
74
|
+
if (!segment || segment === '.' || segment === '..' || segment.startsWith('.')) {
|
|
75
|
+
throw new Error('Hidden and traversal components are not permitted in skill resources.');
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
if (!TEXT_EXTENSIONS.has(path.posix.extname(relativePath).toLowerCase())) {
|
|
79
|
+
throw new Error('Only text skill resources may be loaded into the model context.');
|
|
80
|
+
}
|
|
81
|
+
return parts;
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Read one supporting text document without touching unrelated files.
|
|
85
|
+
* Rejects symlinks in every path component, large files, invalid UTF-8 and
|
|
86
|
+
* binary content. Note: a concurrently hostile local process can still race
|
|
87
|
+
* parent-directory replacement; the agent's OS sandbox is the final boundary.
|
|
88
|
+
*/
|
|
89
|
+
export function readSkillTextResource(root, domain, name, relativePath) {
|
|
90
|
+
const components = checkRelativeResource(relativePath);
|
|
91
|
+
const skillDir = assertSkillTreeSafe(root, domain, name);
|
|
92
|
+
let cursor = skillDir;
|
|
93
|
+
for (const component of components.slice(0, -1)) {
|
|
94
|
+
cursor = path.join(cursor, component);
|
|
95
|
+
inspectDirectory(cursor, false);
|
|
96
|
+
}
|
|
97
|
+
const target = path.join(cursor, components[components.length - 1]);
|
|
98
|
+
const physicalRoot = fs.realpathSync(skillDir);
|
|
99
|
+
const physicalFile = fs.realpathSync(target);
|
|
100
|
+
if (!physicalFile.startsWith(`${physicalRoot}${path.sep}`)) {
|
|
101
|
+
throw new Error('Skill resource escapes its own directory.');
|
|
102
|
+
}
|
|
103
|
+
const nofollow = typeof fs.constants.O_NOFOLLOW === 'number' ? fs.constants.O_NOFOLLOW : 0;
|
|
104
|
+
const fd = fs.openSync(target, fs.constants.O_RDONLY | nofollow);
|
|
105
|
+
try {
|
|
106
|
+
const stat = fs.fstatSync(fd);
|
|
107
|
+
if (!stat.isFile())
|
|
108
|
+
throw new Error('Skill resource must be a regular file.');
|
|
109
|
+
if (stat.size > MAX_SKILL_RESOURCE_BYTES) {
|
|
110
|
+
throw new Error(`Skill resource exceeds ${MAX_SKILL_RESOURCE_BYTES} bytes.`);
|
|
111
|
+
}
|
|
112
|
+
const chunks = [];
|
|
113
|
+
let bytes = 0;
|
|
114
|
+
while (bytes <= MAX_SKILL_RESOURCE_BYTES) {
|
|
115
|
+
const remaining = MAX_SKILL_RESOURCE_BYTES + 1 - bytes;
|
|
116
|
+
const buffer = Buffer.alloc(Math.min(8192, remaining));
|
|
117
|
+
const count = fs.readSync(fd, buffer, 0, buffer.length, null);
|
|
118
|
+
if (count === 0)
|
|
119
|
+
break;
|
|
120
|
+
chunks.push(buffer.subarray(0, count));
|
|
121
|
+
bytes += count;
|
|
122
|
+
}
|
|
123
|
+
if (bytes > MAX_SKILL_RESOURCE_BYTES)
|
|
124
|
+
throw new Error('Skill resource grew beyond size limit.');
|
|
125
|
+
const text = new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks));
|
|
126
|
+
if (text.includes('\0'))
|
|
127
|
+
throw new Error('Binary skill resource is not valid model context.');
|
|
128
|
+
// Terminal control bytes are not useful skill instructions.
|
|
129
|
+
return text.replace(/[\x01-\x08\x0b\x0c\x0e-\x1f\x7f]/g, '');
|
|
130
|
+
}
|
|
131
|
+
finally {
|
|
132
|
+
fs.closeSync(fd);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* Offer a bounded, deterministic list of resource names, not their bodies.
|
|
137
|
+
* Never follow symlinked support directories or files.
|
|
138
|
+
*/
|
|
139
|
+
export function listSkillResourcePaths(root, domain, name, limit = MAX_ADVERTISED_SKILL_RESOURCES) {
|
|
140
|
+
const skillDir = assertSkillTreeSafe(root, domain, name);
|
|
141
|
+
const out = [];
|
|
142
|
+
const bound = Number.isInteger(limit)
|
|
143
|
+
? Math.max(0, Math.min(limit, MAX_ADVERTISED_SKILL_RESOURCES)) : MAX_ADVERTISED_SKILL_RESOURCES;
|
|
144
|
+
const walk = (relative, depth) => {
|
|
145
|
+
if (out.length >= bound || depth > 3)
|
|
146
|
+
return;
|
|
147
|
+
const directory = path.join(skillDir, ...relative.split('/'));
|
|
148
|
+
if (!inspectDirectory(directory, true))
|
|
149
|
+
return;
|
|
150
|
+
const entries = fs.readdirSync(directory, { withFileTypes: true })
|
|
151
|
+
.filter(item => !item.name.startsWith('.'))
|
|
152
|
+
.sort((a, b) => a.name.localeCompare(b.name))
|
|
153
|
+
.slice(0, 128);
|
|
154
|
+
for (const entry of entries) {
|
|
155
|
+
if (out.length >= bound)
|
|
156
|
+
break;
|
|
157
|
+
if (entry.isSymbolicLink())
|
|
158
|
+
continue;
|
|
159
|
+
const next = `${relative}/${entry.name}`;
|
|
160
|
+
if (entry.isDirectory())
|
|
161
|
+
walk(next, depth + 1);
|
|
162
|
+
else if (entry.isFile() && TEXT_EXTENSIONS.has(path.posix.extname(next).toLowerCase())) {
|
|
163
|
+
const stat = fs.lstatSync(path.join(directory, entry.name));
|
|
164
|
+
if (stat.size <= MAX_SKILL_RESOURCE_BYTES && !stat.isSymbolicLink())
|
|
165
|
+
out.push(next);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
};
|
|
169
|
+
if (bound === 0)
|
|
170
|
+
return out;
|
|
171
|
+
for (const group of RESOURCE_GROUPS)
|
|
172
|
+
walk(group, 1);
|
|
173
|
+
return out;
|
|
174
|
+
}
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Causyne Agent — skill file boundaries and progressive resource disclosure.
|
|
3
|
+
*
|
|
4
|
+
* Purely local, synchronous, bounded, cross-platform. The user-skill loader,
|
|
5
|
+
* mutation API, and fs_read_skill all use this same security boundary.
|
|
6
|
+
*
|
|
7
|
+
* This is application-level containment, not a substitute for OS isolation.
|
|
8
|
+
* No skill code is executed here.
|
|
9
|
+
*/
|
|
10
|
+
import fs from 'node:fs';
|
|
11
|
+
import path from 'node:path';
|
|
12
|
+
|
|
13
|
+
export const MAX_SKILL_RESOURCE_BYTES = 12 * 1024;
|
|
14
|
+
export const MAX_ADVERTISED_SKILL_RESOURCES = 12;
|
|
15
|
+
const SKILL_SEGMENT = /^[a-z0-9][a-z0-9-]{0,63}$/;
|
|
16
|
+
const RESERVED_WINDOWS = /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])$/i;
|
|
17
|
+
const RESOURCE_GROUPS = new Set(['references', 'templates', 'scripts', 'assets']);
|
|
18
|
+
const TEXT_EXTENSIONS = new Set([
|
|
19
|
+
'.md', '.mdx', '.txt', '.json', '.yaml', '.yml', '.toml', '.sql',
|
|
20
|
+
'.py', '.js', '.mjs', '.cjs', '.ts', '.tsx', '.sh', '.css', '.html',
|
|
21
|
+
'.xml', '.csv', '.svg'
|
|
22
|
+
]);
|
|
23
|
+
|
|
24
|
+
function checkSkillSegment(segment: string): void {
|
|
25
|
+
if (!SKILL_SEGMENT.test(segment) || RESERVED_WINDOWS.test(segment)) {
|
|
26
|
+
throw new Error(`Invalid skill path segment ${JSON.stringify(segment)}.`);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function inspectDirectory(directory: string, allowMissing: boolean): boolean {
|
|
31
|
+
let stat: fs.Stats;
|
|
32
|
+
try {
|
|
33
|
+
stat = fs.lstatSync(directory);
|
|
34
|
+
} catch (error: unknown) {
|
|
35
|
+
if (allowMissing && (error as NodeJS.ErrnoException)?.code === 'ENOENT') return false;
|
|
36
|
+
throw error;
|
|
37
|
+
}
|
|
38
|
+
if (stat.isSymbolicLink() || !stat.isDirectory()) {
|
|
39
|
+
throw new Error(`Skill directory is not a real directory: ${directory}`);
|
|
40
|
+
}
|
|
41
|
+
return true;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Check each directory segment. In particular, do not let a skill author
|
|
46
|
+
* place a symlink at ~/.causyne/skills/<domain> or <name> and redirect writes
|
|
47
|
+
* into an unrelated folder. `path.resolve()` alone does NOT provide this.
|
|
48
|
+
*/
|
|
49
|
+
export function assertSkillTreeSafe(
|
|
50
|
+
root: string,
|
|
51
|
+
domain: string,
|
|
52
|
+
name: string,
|
|
53
|
+
allowMissing = false
|
|
54
|
+
): string {
|
|
55
|
+
checkSkillSegment(domain);
|
|
56
|
+
checkSkillSegment(name);
|
|
57
|
+
const base = path.resolve(root);
|
|
58
|
+
const domainDir = path.join(base, domain);
|
|
59
|
+
const skillDir = path.join(domainDir, name);
|
|
60
|
+
if (!inspectDirectory(base, allowMissing)) return skillDir;
|
|
61
|
+
if (!inspectDirectory(domainDir, allowMissing)) return skillDir;
|
|
62
|
+
inspectDirectory(skillDir, allowMissing);
|
|
63
|
+
return skillDir;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function checkRelativeResource(relativePath: unknown): string[] {
|
|
67
|
+
if (typeof relativePath !== 'string' || relativePath.length < 3 || relativePath.length > 240) {
|
|
68
|
+
throw new Error('Skill resource path must be a short relative string.');
|
|
69
|
+
}
|
|
70
|
+
// The API uses portable POSIX-relative names, including on Windows.
|
|
71
|
+
if (/^[A-Za-z]:/.test(relativePath) || relativePath.startsWith('/') ||
|
|
72
|
+
relativePath.includes('\\') || /[\x00-\x1f\x7f<>"']/.test(relativePath)) {
|
|
73
|
+
throw new Error('Absolute, Windows, or control-character resource paths are not permitted.');
|
|
74
|
+
}
|
|
75
|
+
const parts = relativePath.split('/');
|
|
76
|
+
if (parts.length < 2 || parts.length > 5 || !RESOURCE_GROUPS.has(parts[0] ?? '')) {
|
|
77
|
+
throw new Error('Use a relative file within references/, templates/, scripts/, or assets/.');
|
|
78
|
+
}
|
|
79
|
+
for (const segment of parts) {
|
|
80
|
+
if (!segment || segment === '.' || segment === '..' || segment.startsWith('.')) {
|
|
81
|
+
throw new Error('Hidden and traversal components are not permitted in skill resources.');
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
if (!TEXT_EXTENSIONS.has(path.posix.extname(relativePath).toLowerCase())) {
|
|
85
|
+
throw new Error('Only text skill resources may be loaded into the model context.');
|
|
86
|
+
}
|
|
87
|
+
return parts;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Read one supporting text document without touching unrelated files.
|
|
92
|
+
* Rejects symlinks in every path component, large files, invalid UTF-8 and
|
|
93
|
+
* binary content. Note: a concurrently hostile local process can still race
|
|
94
|
+
* parent-directory replacement; the agent's OS sandbox is the final boundary.
|
|
95
|
+
*/
|
|
96
|
+
export function readSkillTextResource(
|
|
97
|
+
root: string, domain: string, name: string, relativePath: string
|
|
98
|
+
): string {
|
|
99
|
+
const components = checkRelativeResource(relativePath);
|
|
100
|
+
const skillDir = assertSkillTreeSafe(root, domain, name);
|
|
101
|
+
let cursor = skillDir;
|
|
102
|
+
for (const component of components.slice(0, -1)) {
|
|
103
|
+
cursor = path.join(cursor, component);
|
|
104
|
+
inspectDirectory(cursor, false);
|
|
105
|
+
}
|
|
106
|
+
const target = path.join(cursor, components[components.length - 1]!);
|
|
107
|
+
const physicalRoot = fs.realpathSync(skillDir);
|
|
108
|
+
const physicalFile = fs.realpathSync(target);
|
|
109
|
+
if (!physicalFile.startsWith(`${physicalRoot}${path.sep}`)) {
|
|
110
|
+
throw new Error('Skill resource escapes its own directory.');
|
|
111
|
+
}
|
|
112
|
+
const nofollow = typeof fs.constants.O_NOFOLLOW === 'number' ? fs.constants.O_NOFOLLOW : 0;
|
|
113
|
+
const fd = fs.openSync(target, fs.constants.O_RDONLY | nofollow);
|
|
114
|
+
try {
|
|
115
|
+
const stat = fs.fstatSync(fd);
|
|
116
|
+
if (!stat.isFile()) throw new Error('Skill resource must be a regular file.');
|
|
117
|
+
if (stat.size > MAX_SKILL_RESOURCE_BYTES) {
|
|
118
|
+
throw new Error(`Skill resource exceeds ${MAX_SKILL_RESOURCE_BYTES} bytes.`);
|
|
119
|
+
}
|
|
120
|
+
const chunks: Buffer[] = [];
|
|
121
|
+
let bytes = 0;
|
|
122
|
+
while (bytes <= MAX_SKILL_RESOURCE_BYTES) {
|
|
123
|
+
const remaining = MAX_SKILL_RESOURCE_BYTES + 1 - bytes;
|
|
124
|
+
const buffer = Buffer.alloc(Math.min(8192, remaining));
|
|
125
|
+
const count = fs.readSync(fd, buffer, 0, buffer.length, null);
|
|
126
|
+
if (count === 0) break;
|
|
127
|
+
chunks.push(buffer.subarray(0, count));
|
|
128
|
+
bytes += count;
|
|
129
|
+
}
|
|
130
|
+
if (bytes > MAX_SKILL_RESOURCE_BYTES) throw new Error('Skill resource grew beyond size limit.');
|
|
131
|
+
const text = new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks));
|
|
132
|
+
if (text.includes('\0')) throw new Error('Binary skill resource is not valid model context.');
|
|
133
|
+
// Terminal control bytes are not useful skill instructions.
|
|
134
|
+
return text.replace(/[\x01-\x08\x0b\x0c\x0e-\x1f\x7f]/g, '');
|
|
135
|
+
} finally {
|
|
136
|
+
fs.closeSync(fd);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Offer a bounded, deterministic list of resource names, not their bodies.
|
|
142
|
+
* Never follow symlinked support directories or files.
|
|
143
|
+
*/
|
|
144
|
+
export function listSkillResourcePaths(
|
|
145
|
+
root: string, domain: string, name: string,
|
|
146
|
+
limit = MAX_ADVERTISED_SKILL_RESOURCES
|
|
147
|
+
): string[] {
|
|
148
|
+
const skillDir = assertSkillTreeSafe(root, domain, name);
|
|
149
|
+
const out: string[] = [];
|
|
150
|
+
const bound = Number.isInteger(limit)
|
|
151
|
+
? Math.max(0, Math.min(limit, MAX_ADVERTISED_SKILL_RESOURCES)) : MAX_ADVERTISED_SKILL_RESOURCES;
|
|
152
|
+
const walk = (relative: string, depth: number): void => {
|
|
153
|
+
if (out.length >= bound || depth > 3) return;
|
|
154
|
+
const directory = path.join(skillDir, ...relative.split('/'));
|
|
155
|
+
if (!inspectDirectory(directory, true)) return;
|
|
156
|
+
const entries = fs.readdirSync(directory, { withFileTypes: true })
|
|
157
|
+
.filter(item => !item.name.startsWith('.'))
|
|
158
|
+
.sort((a, b) => a.name.localeCompare(b.name))
|
|
159
|
+
.slice(0, 128);
|
|
160
|
+
for (const entry of entries) {
|
|
161
|
+
if (out.length >= bound) break;
|
|
162
|
+
if (entry.isSymbolicLink()) continue;
|
|
163
|
+
const next = `${relative}/${entry.name}`;
|
|
164
|
+
if (entry.isDirectory()) walk(next, depth + 1);
|
|
165
|
+
else if (entry.isFile() && TEXT_EXTENSIONS.has(path.posix.extname(next).toLowerCase())) {
|
|
166
|
+
const stat = fs.lstatSync(path.join(directory, entry.name));
|
|
167
|
+
if (stat.size <= MAX_SKILL_RESOURCE_BYTES && !stat.isSymbolicLink()) out.push(next);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
};
|
|
171
|
+
if (bound === 0) return out;
|
|
172
|
+
for (const group of RESOURCE_GROUPS) walk(group, 1);
|
|
173
|
+
return out;
|
|
174
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The tool_search query is written by a model or a user, not trusted code.
|
|
3
|
+
* Node's RegExp engine can spend unbounded CPU on catastrophic backtracking.
|
|
4
|
+
* Search is literal by default; token scoring still handles natural language.
|
|
5
|
+
* This changes the old regex-query behavior intentionally to keep the agent's
|
|
6
|
+
* event loop responsive under malformed or adversarial inputs.
|
|
7
|
+
*/
|
|
8
|
+
export const MAX_TOOL_SEARCH_QUERY = 240;
|
|
9
|
+
export const MAX_SKILL_SEARCH_DESCRIPTION = 180;
|
|
10
|
+
export function literalSearchPattern(query) {
|
|
11
|
+
if (typeof query !== 'string')
|
|
12
|
+
return null;
|
|
13
|
+
const text = query.trim();
|
|
14
|
+
if (text.length === 0 || text.length > MAX_TOOL_SEARCH_QUERY)
|
|
15
|
+
return null;
|
|
16
|
+
const escaped = text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
17
|
+
return new RegExp(escaped, 'i');
|
|
18
|
+
}
|
|
19
|
+
/** Only display metadata in a tool search result; not raw multiline skill text. */
|
|
20
|
+
export function formatSkillSearchLine(skill) {
|
|
21
|
+
const clean = (value, limit) => value
|
|
22
|
+
.replace(/[\x00-\x1f\x7f]/g, ' ')
|
|
23
|
+
.replace(/[<>]/g, '')
|
|
24
|
+
.replace(/\s+/g, ' ')
|
|
25
|
+
.trim().slice(0, limit);
|
|
26
|
+
const id = `${skill.domain}/${skill.id}`;
|
|
27
|
+
const name = clean(skill.name || skill.id, 80);
|
|
28
|
+
const description = clean(skill.description || '', MAX_SKILL_SEARCH_DESCRIPTION);
|
|
29
|
+
const source = ['native', 'user', 'plugin'].includes(skill.source || '') ? skill.source : 'unknown';
|
|
30
|
+
return `- ${id} [${source}] — ${name}: ${description}`;
|
|
31
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The tool_search query is written by a model or a user, not trusted code.
|
|
3
|
+
* Node's RegExp engine can spend unbounded CPU on catastrophic backtracking.
|
|
4
|
+
* Search is literal by default; token scoring still handles natural language.
|
|
5
|
+
* This changes the old regex-query behavior intentionally to keep the agent's
|
|
6
|
+
* event loop responsive under malformed or adversarial inputs.
|
|
7
|
+
*/
|
|
8
|
+
export const MAX_TOOL_SEARCH_QUERY = 240;
|
|
9
|
+
export const MAX_SKILL_SEARCH_DESCRIPTION = 180;
|
|
10
|
+
|
|
11
|
+
export function literalSearchPattern(query: unknown): RegExp | null {
|
|
12
|
+
if (typeof query !== 'string') return null;
|
|
13
|
+
const text = query.trim();
|
|
14
|
+
if (text.length === 0 || text.length > MAX_TOOL_SEARCH_QUERY) return null;
|
|
15
|
+
const escaped = text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
16
|
+
return new RegExp(escaped, 'i');
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Only display metadata in a tool search result; not raw multiline skill text. */
|
|
20
|
+
export function formatSkillSearchLine(skill: {
|
|
21
|
+
domain: string; id: string; name: string; description?: string; source?: string;
|
|
22
|
+
}): string {
|
|
23
|
+
const clean = (value: string, limit: number) => value
|
|
24
|
+
.replace(/[\x00-\x1f\x7f]/g, ' ')
|
|
25
|
+
.replace(/[<>]/g, '')
|
|
26
|
+
.replace(/\s+/g, ' ')
|
|
27
|
+
.trim().slice(0, limit);
|
|
28
|
+
const id = `${skill.domain}/${skill.id}`;
|
|
29
|
+
const name = clean(skill.name || skill.id, 80);
|
|
30
|
+
const description = clean(skill.description || '', MAX_SKILL_SEARCH_DESCRIPTION);
|
|
31
|
+
const source = ['native', 'user', 'plugin'].includes(skill.source || '') ? skill.source : 'unknown';
|
|
32
|
+
return `- ${id} [${source}] — ${name}: ${description}`;
|
|
33
|
+
}
|
|
@@ -9,6 +9,7 @@ async function toolDefinitions() {
|
|
|
9
9
|
}
|
|
10
10
|
import { buildToolsList } from '../toolsList.js';
|
|
11
11
|
import { PACKS, PACK_NAMES, packForTool, isCoreTool, isResidentTool } from '../toolPacks.js';
|
|
12
|
+
import { literalSearchPattern, formatSkillSearchLine, MAX_TOOL_SEARCH_QUERY } from '../skills/skillSearchSafety.js';
|
|
12
13
|
/** Max skills returned alongside the tool matches, so one search stays cheap. */
|
|
13
14
|
const MAX_SKILL_HITS = 5;
|
|
14
15
|
/**
|
|
@@ -57,7 +58,7 @@ async function searchSkills(terms, pattern) {
|
|
|
57
58
|
return scored
|
|
58
59
|
.sort((a, b) => b.score - a.score)
|
|
59
60
|
.slice(0, MAX_SKILL_HITS)
|
|
60
|
-
.map(({ skill }) =>
|
|
61
|
+
.map(({ skill }) => formatSkillSearchLine(skill));
|
|
61
62
|
}
|
|
62
63
|
// Real progressive-disclosure tool search.
|
|
63
64
|
//
|
|
@@ -103,15 +104,10 @@ function scoreTool(definition, terms, pattern) {
|
|
|
103
104
|
return score;
|
|
104
105
|
}
|
|
105
106
|
function buildPattern(query) {
|
|
106
|
-
//
|
|
107
|
-
//
|
|
108
|
-
//
|
|
109
|
-
|
|
110
|
-
return new RegExp(query, 'i');
|
|
111
|
-
}
|
|
112
|
-
catch (e) {
|
|
113
|
-
return null;
|
|
114
|
-
}
|
|
107
|
+
// Never compile LLM-generated regex. A pattern such as (a+)+$ can freeze
|
|
108
|
+
// Node's single-threaded event loop. Natural-language token scoring is
|
|
109
|
+
// preserved; the phrase match is literal and bounded.
|
|
110
|
+
return literalSearchPattern(query);
|
|
115
111
|
}
|
|
116
112
|
export const deferredMcpSearch = {
|
|
117
113
|
schema: {
|
|
@@ -122,7 +118,7 @@ export const deferredMcpSearch = {
|
|
|
122
118
|
properties: {
|
|
123
119
|
query: {
|
|
124
120
|
type: 'string',
|
|
125
|
-
description: 'What capability you need.
|
|
121
|
+
description: 'What capability you need. Use natural language or exact tool/skill names. Special regex characters are treated literally.'
|
|
126
122
|
},
|
|
127
123
|
names: { type: 'array', items: { type: 'string' }, description: 'Exact tool names selected from the compact catalog. Loads only these schemas.' },
|
|
128
124
|
pack: {
|
|
@@ -139,7 +135,10 @@ export const deferredMcpSearch = {
|
|
|
139
135
|
},
|
|
140
136
|
async execute(args, context = {}) {
|
|
141
137
|
try {
|
|
142
|
-
const query = String(args.query
|
|
138
|
+
const query = String(args.query ?? args.q ?? args.search ?? args.description ?? args.pattern ?? '').trim();
|
|
139
|
+
if (query.length > MAX_TOOL_SEARCH_QUERY) {
|
|
140
|
+
return { success: false, error: `Search query exceeds ${MAX_TOOL_SEARCH_QUERY} characters. Use a shorter capability description.` };
|
|
141
|
+
}
|
|
143
142
|
const requestedPack = args.pack ? String(args.pack).toLowerCase() : null;
|
|
144
143
|
const definitions = context.parentLoop?.searchableTools
|
|
145
144
|
? await context.parentLoop.searchableTools() : await toolDefinitions();
|