@causyne/agent 1.20.87 → 1.20.90

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@causyne/agent",
3
- "version": "1.20.87",
3
+ "version": "1.20.90",
4
4
  "description": "Agentic AI for software, tools, and computer workflows",
5
5
  "main": "bin/causyne.js",
6
6
  "type": "module",
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Wait for a retry delay without retaining an AbortSignal listener afterwards.
3
+ *
4
+ * A native AbortSignal is also checked after listener registration; otherwise
5
+ * an abort occurring between the initial check and registration can be missed.
6
+ * The timer is kept referenced while the retry is pending so a CLI process does
7
+ * not exit with an unresolved task solely because there are no other handles.
8
+ */
9
+ export function waitForAbortableDelay(durationMs, signal) {
10
+ if (!Number.isFinite(durationMs) || durationMs < 0) {
11
+ return Promise.reject(new RangeError('Backoff duration must be a finite, nonnegative number'));
12
+ }
13
+ if (signal?.aborted)
14
+ return Promise.resolve('aborted');
15
+ if (durationMs === 0)
16
+ return Promise.resolve('elapsed');
17
+ return new Promise((resolve) => {
18
+ let timer;
19
+ let settled = false;
20
+ const finish = (outcome) => {
21
+ if (settled)
22
+ return;
23
+ settled = true;
24
+ if (timer !== undefined)
25
+ clearTimeout(timer);
26
+ signal?.removeEventListener('abort', onAbort);
27
+ resolve(outcome);
28
+ };
29
+ const onAbort = () => finish('aborted');
30
+ signal?.addEventListener('abort', onAbort, { once: true });
31
+ if (signal?.aborted) {
32
+ finish('aborted');
33
+ return;
34
+ }
35
+ timer = setTimeout(() => finish('elapsed'), durationMs);
36
+ });
37
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Wait for a retry delay without retaining an AbortSignal listener afterwards.
3
+ *
4
+ * A native AbortSignal is also checked after listener registration; otherwise
5
+ * an abort occurring between the initial check and registration can be missed.
6
+ * The timer is kept referenced while the retry is pending so a CLI process does
7
+ * not exit with an unresolved task solely because there are no other handles.
8
+ */
9
+ export function waitForAbortableDelay(
10
+ durationMs: number,
11
+ signal?: AbortSignal | null
12
+ ): Promise<'elapsed' | 'aborted'> {
13
+ if (!Number.isFinite(durationMs) || durationMs < 0) {
14
+ return Promise.reject(new RangeError('Backoff duration must be a finite, nonnegative number'));
15
+ }
16
+ if (signal?.aborted) return Promise.resolve('aborted');
17
+ if (durationMs === 0) return Promise.resolve('elapsed');
18
+
19
+ return new Promise<'elapsed' | 'aborted'>((resolve) => {
20
+ let timer: ReturnType<typeof setTimeout> | undefined;
21
+ let settled = false;
22
+ const finish = (outcome: 'elapsed' | 'aborted'): void => {
23
+ if (settled) return;
24
+ settled = true;
25
+ if (timer !== undefined) clearTimeout(timer);
26
+ signal?.removeEventListener('abort', onAbort);
27
+ resolve(outcome);
28
+ };
29
+ const onAbort = (): void => finish('aborted');
30
+
31
+ signal?.addEventListener('abort', onAbort, { once: true });
32
+ if (signal?.aborted) {
33
+ finish('aborted');
34
+ return;
35
+ }
36
+ timer = setTimeout(() => finish('elapsed'), durationMs);
37
+ });
38
+ }
@@ -0,0 +1,30 @@
1
+ function compactMessage(value) {
2
+ if (typeof value === 'string')
3
+ return value.slice(0, 4096);
4
+ if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint')
5
+ return String(value);
6
+ if (value === null || value === undefined)
7
+ return 'Unknown provider error';
8
+ try {
9
+ const text = String(value);
10
+ return text.length > 4096 ? `${text.slice(0, 4096)}…` : text;
11
+ }
12
+ catch {
13
+ return 'Provider threw a value that could not be stringified';
14
+ }
15
+ }
16
+ export function normalizeAgentFailure(value) {
17
+ if (value instanceof Error)
18
+ return value;
19
+ const candidate = value && typeof value === 'object'
20
+ ? value : {};
21
+ const sourceMessage = typeof candidate.message === 'string' ? candidate.message : value;
22
+ const error = new Error(compactMessage(sourceMessage));
23
+ for (const field of ['code', 'partialUsage', 'status', 'reason']) {
24
+ if (Object.hasOwn(candidate, field))
25
+ error[field] = candidate[field];
26
+ }
27
+ if (typeof candidate.name === 'string')
28
+ error.name = candidate.name;
29
+ return error;
30
+ }
@@ -0,0 +1,33 @@
1
+ /** Normalize arbitrary provider throws before the AgentLoop error handler. */
2
+ export interface AgentFailure extends Error {
3
+ code?: unknown;
4
+ partialUsage?: unknown;
5
+ status?: unknown;
6
+ reason?: unknown;
7
+ }
8
+
9
+ function compactMessage(value: unknown): string {
10
+ if (typeof value === 'string') return value.slice(0, 4096);
11
+ if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') return String(value);
12
+ if (value === null || value === undefined) return 'Unknown provider error';
13
+ try {
14
+ const text = String(value);
15
+ return text.length > 4096 ? `${text.slice(0, 4096)}…` : text;
16
+ } catch {
17
+ return 'Provider threw a value that could not be stringified';
18
+ }
19
+ }
20
+
21
+ export function normalizeAgentFailure(value: unknown): AgentFailure {
22
+ if (value instanceof Error) return value as AgentFailure;
23
+
24
+ const candidate: Record<string, unknown> = value && typeof value === 'object'
25
+ ? value as Record<string, unknown> : {};
26
+ const sourceMessage = typeof candidate.message === 'string' ? candidate.message : value;
27
+ const error = new Error(compactMessage(sourceMessage)) as AgentFailure;
28
+ for (const field of ['code', 'partialUsage', 'status', 'reason'] as const) {
29
+ if (Object.hasOwn(candidate, field)) error[field] = candidate[field];
30
+ }
31
+ if (typeof candidate.name === 'string') error.name = candidate.name;
32
+ return error;
33
+ }
@@ -0,0 +1,139 @@
1
+ /**
2
+ * Repair only *missing* replies to already-recorded assistant tool calls.
3
+ *
4
+ * The AgentLoop appends an assistant tool_calls message before dispatch. If a
5
+ * user aborts a multi-call batch (or the process rejects a later tool), history
6
+ * can contain an unanswered tool call. Providers may reject the next request.
7
+ * This utility never runs a tool, replays an edit, or claims that a missing
8
+ * outcome was a success. It records an explicit unknown/unfinished outcome.
9
+ *
10
+ * IMPORTANT: An image result may insert a `user` media message *between* two
11
+ * tool results. Consequently a turn ends at the NEXT assistant message, not
12
+ * the next user message; otherwise valid image-enabled batches get corrupted.
13
+ */
14
+ const UNCERTAIN_OUTCOME = JSON.stringify({
15
+ success: false,
16
+ code: 'TOOL_OUTCOME_UNRECORDED',
17
+ error: 'The conversation has no recorded outcome for this tool call. ' +
18
+ 'The operation may or may not have executed before interruption. ' +
19
+ 'Inspect actual workspace state before deciding whether to retry.'
20
+ });
21
+ function assistantToolCalls(message) {
22
+ if (message.role !== 'assistant' || !Array.isArray(message.tool_calls))
23
+ return [];
24
+ return message.tool_calls.filter((entry) => entry !== null && typeof entry === 'object');
25
+ }
26
+ function toolCallId(value) {
27
+ return typeof value === 'string' && value.length > 0 && value.length <= 256 ? value : null;
28
+ }
29
+ /**
30
+ * Mutates only the supplied history array. Returns the number of inserted
31
+ * uncertainty records; does not remove or rewrite a real result.
32
+ *
33
+ * `unresolved > 0` means malformed provider tool IDs or an oversized batch.
34
+ * The caller must stop before another provider request instead of presenting
35
+ * that history as complete.
36
+ */
37
+ export function repairUnansweredToolCalls(history, maxCallsPerTurn = 256) {
38
+ if (!Array.isArray(history))
39
+ throw new TypeError('History must be an array');
40
+ if (!Number.isSafeInteger(maxCallsPerTurn) || maxCallsPerTurn < 1) {
41
+ throw new RangeError('maxCallsPerTurn must be a positive integer');
42
+ }
43
+ let repaired = 0;
44
+ let affectedTurns = 0;
45
+ let unresolved = 0;
46
+ for (let i = 0; i < history.length; i++) {
47
+ const message = history[i];
48
+ if (!message)
49
+ continue;
50
+ const calls = assistantToolCalls(message);
51
+ if (calls.length === 0)
52
+ continue;
53
+ if (calls.length > maxCallsPerTurn) {
54
+ unresolved += calls.length;
55
+ continue;
56
+ }
57
+ const required = new Map();
58
+ for (const call of calls) {
59
+ const id = toolCallId(call.id);
60
+ if (!id) {
61
+ unresolved++;
62
+ continue;
63
+ }
64
+ const entry = required.get(id);
65
+ const name = typeof call.function?.name === 'string' && call.function.name
66
+ ? call.function.name
67
+ : 'unknown_tool';
68
+ if (entry) {
69
+ // Provider-issued IDs must be unique within one assistant turn.
70
+ // Do not silently relabel an ambiguous call.
71
+ entry.count++;
72
+ unresolved++;
73
+ }
74
+ else
75
+ required.set(id, { count: 1, name });
76
+ }
77
+ if (required.size === 0)
78
+ continue;
79
+ // This includes internal system notices and injected image observations.
80
+ // Neither constitutes a new assistant tool turn.
81
+ let end = i + 1;
82
+ while (end < history.length && history[end]?.role !== 'assistant')
83
+ end++;
84
+ const received = new Map();
85
+ let insertion = i + 1;
86
+ for (let k = i + 1; k < end; k++) {
87
+ const next = history[k];
88
+ if (next?.role !== 'tool')
89
+ continue;
90
+ insertion = k + 1;
91
+ const id = toolCallId(next.tool_call_id);
92
+ if (id && required.has(id))
93
+ received.set(id, (received.get(id) ?? 0) + 1);
94
+ }
95
+ const missing = [];
96
+ for (const [id, expected] of required) {
97
+ const count = Math.max(0, expected.count - (received.get(id) ?? 0));
98
+ for (let n = 0; n < count; n++) {
99
+ missing.push({ role: 'tool', tool_call_id: id, name: expected.name, content: UNCERTAIN_OUTCOME });
100
+ }
101
+ }
102
+ if (missing.length === 0)
103
+ continue;
104
+ history.splice(insertion, 0, ...missing);
105
+ repaired += missing.length;
106
+ affectedTurns++;
107
+ // Move on: inserted tool records are not assistant messages.
108
+ }
109
+ return { repaired, affectedTurns, unresolved };
110
+ }
111
+ /**
112
+ * Check a provider batch *before* prefetch or execution. Duplicate IDs can
113
+ * alias the prefetch map and break the one-result-per-call wire contract.
114
+ * We reject that batch rather than inventing replacement IDs for requests a
115
+ * remote provider might already have associated with the original IDs.
116
+ */
117
+ export function validateToolCallBatch(calls, maxCalls = 256) {
118
+ if (calls === undefined || calls === null)
119
+ return { valid: true, reason: '' };
120
+ if (!Array.isArray(calls))
121
+ return { valid: false, reason: 'toolCalls was not an array' };
122
+ if (calls.length > maxCalls)
123
+ return { valid: false, reason: `toolCalls exceeded the ${maxCalls}-call safety limit` };
124
+ const seen = new Set();
125
+ for (let index = 0; index < calls.length; index++) {
126
+ const call = calls[index];
127
+ const id = call && toolCallId(call.id);
128
+ if (!id)
129
+ return { valid: false, reason: `tool call ${index + 1} had no valid ID` };
130
+ if (seen.has(id))
131
+ return { valid: false, reason: `duplicate tool-call ID in one assistant turn` };
132
+ const name = call?.function?.name;
133
+ if (typeof name !== 'string' || name.length === 0) {
134
+ return { valid: false, reason: `tool call ${index + 1} had no function name` };
135
+ }
136
+ seen.add(id);
137
+ }
138
+ return { valid: true, reason: '' };
139
+ }
@@ -0,0 +1,165 @@
1
+ /**
2
+ * Repair only *missing* replies to already-recorded assistant tool calls.
3
+ *
4
+ * The AgentLoop appends an assistant tool_calls message before dispatch. If a
5
+ * user aborts a multi-call batch (or the process rejects a later tool), history
6
+ * can contain an unanswered tool call. Providers may reject the next request.
7
+ * This utility never runs a tool, replays an edit, or claims that a missing
8
+ * outcome was a success. It records an explicit unknown/unfinished outcome.
9
+ *
10
+ * IMPORTANT: An image result may insert a `user` media message *between* two
11
+ * tool results. Consequently a turn ends at the NEXT assistant message, not
12
+ * the next user message; otherwise valid image-enabled batches get corrupted.
13
+ */
14
+
15
+ export interface RecordedToolCall {
16
+ id?: unknown;
17
+ function?: { name?: unknown } | null;
18
+ [key: string]: unknown;
19
+ }
20
+
21
+ export interface RecordedMessage {
22
+ role?: unknown;
23
+ tool_calls?: unknown;
24
+ tool_call_id?: unknown;
25
+ name?: unknown;
26
+ content?: unknown;
27
+ [key: string]: unknown;
28
+ }
29
+
30
+ export interface ToolTurnRepairReport {
31
+ repaired: number;
32
+ affectedTurns: number;
33
+ unresolved: number;
34
+ }
35
+
36
+ const UNCERTAIN_OUTCOME = JSON.stringify({
37
+ success: false,
38
+ code: 'TOOL_OUTCOME_UNRECORDED',
39
+ error: 'The conversation has no recorded outcome for this tool call. ' +
40
+ 'The operation may or may not have executed before interruption. ' +
41
+ 'Inspect actual workspace state before deciding whether to retry.'
42
+ });
43
+
44
+ function assistantToolCalls(message: RecordedMessage): RecordedToolCall[] {
45
+ if (message.role !== 'assistant' || !Array.isArray(message.tool_calls)) return [];
46
+ return message.tool_calls.filter(
47
+ (entry: unknown): entry is RecordedToolCall => entry !== null && typeof entry === 'object'
48
+ );
49
+ }
50
+
51
+ function toolCallId(value: unknown): string | null {
52
+ return typeof value === 'string' && value.length > 0 && value.length <= 256 ? value : null;
53
+ }
54
+
55
+ /**
56
+ * Mutates only the supplied history array. Returns the number of inserted
57
+ * uncertainty records; does not remove or rewrite a real result.
58
+ *
59
+ * `unresolved > 0` means malformed provider tool IDs or an oversized batch.
60
+ * The caller must stop before another provider request instead of presenting
61
+ * that history as complete.
62
+ */
63
+ export function repairUnansweredToolCalls(
64
+ history: RecordedMessage[],
65
+ maxCallsPerTurn = 256
66
+ ): ToolTurnRepairReport {
67
+ if (!Array.isArray(history)) throw new TypeError('History must be an array');
68
+ if (!Number.isSafeInteger(maxCallsPerTurn) || maxCallsPerTurn < 1) {
69
+ throw new RangeError('maxCallsPerTurn must be a positive integer');
70
+ }
71
+
72
+ let repaired = 0;
73
+ let affectedTurns = 0;
74
+ let unresolved = 0;
75
+
76
+ for (let i = 0; i < history.length; i++) {
77
+ const message = history[i];
78
+ if (!message) continue;
79
+ const calls = assistantToolCalls(message);
80
+ if (calls.length === 0) continue;
81
+ if (calls.length > maxCallsPerTurn) {
82
+ unresolved += calls.length;
83
+ continue;
84
+ }
85
+
86
+ const required = new Map<string, { count: number; name: string }>();
87
+ for (const call of calls) {
88
+ const id = toolCallId(call.id);
89
+ if (!id) {
90
+ unresolved++;
91
+ continue;
92
+ }
93
+ const entry = required.get(id);
94
+ const name = typeof call.function?.name === 'string' && call.function.name
95
+ ? call.function.name
96
+ : 'unknown_tool';
97
+ if (entry) {
98
+ // Provider-issued IDs must be unique within one assistant turn.
99
+ // Do not silently relabel an ambiguous call.
100
+ entry.count++;
101
+ unresolved++;
102
+ } else required.set(id, { count: 1, name });
103
+ }
104
+ if (required.size === 0) continue;
105
+
106
+ // This includes internal system notices and injected image observations.
107
+ // Neither constitutes a new assistant tool turn.
108
+ let end = i + 1;
109
+ while (end < history.length && history[end]?.role !== 'assistant') end++;
110
+
111
+ const received = new Map<string, number>();
112
+ let insertion = i + 1;
113
+ for (let k = i + 1; k < end; k++) {
114
+ const next = history[k];
115
+ if (next?.role !== 'tool') continue;
116
+ insertion = k + 1;
117
+ const id = toolCallId(next.tool_call_id);
118
+ if (id && required.has(id)) received.set(id, (received.get(id) ?? 0) + 1);
119
+ }
120
+
121
+ const missing: RecordedMessage[] = [];
122
+ for (const [id, expected] of required) {
123
+ const count = Math.max(0, expected.count - (received.get(id) ?? 0));
124
+ for (let n = 0; n < count; n++) {
125
+ missing.push({ role: 'tool', tool_call_id: id, name: expected.name, content: UNCERTAIN_OUTCOME });
126
+ }
127
+ }
128
+ if (missing.length === 0) continue;
129
+ history.splice(insertion, 0, ...missing);
130
+ repaired += missing.length;
131
+ affectedTurns++;
132
+ // Move on: inserted tool records are not assistant messages.
133
+ }
134
+ return { repaired, affectedTurns, unresolved };
135
+ }
136
+
137
+ export interface ToolBatchValidation {
138
+ valid: boolean;
139
+ reason: string;
140
+ }
141
+
142
+ /**
143
+ * Check a provider batch *before* prefetch or execution. Duplicate IDs can
144
+ * alias the prefetch map and break the one-result-per-call wire contract.
145
+ * We reject that batch rather than inventing replacement IDs for requests a
146
+ * remote provider might already have associated with the original IDs.
147
+ */
148
+ export function validateToolCallBatch(calls: unknown, maxCalls = 256): ToolBatchValidation {
149
+ if (calls === undefined || calls === null) return { valid: true, reason: '' };
150
+ if (!Array.isArray(calls)) return { valid: false, reason: 'toolCalls was not an array' };
151
+ if (calls.length > maxCalls) return { valid: false, reason: `toolCalls exceeded the ${maxCalls}-call safety limit` };
152
+ const seen = new Set<string>();
153
+ for (let index = 0; index < calls.length; index++) {
154
+ const call = calls[index] as RecordedToolCall | null;
155
+ const id = call && toolCallId(call.id);
156
+ if (!id) return { valid: false, reason: `tool call ${index + 1} had no valid ID` };
157
+ if (seen.has(id)) return { valid: false, reason: `duplicate tool-call ID in one assistant turn` };
158
+ const name = call?.function?.name;
159
+ if (typeof name !== 'string' || name.length === 0) {
160
+ return { valid: false, reason: `tool call ${index + 1} had no function name` };
161
+ }
162
+ seen.add(id);
163
+ }
164
+ return { valid: true, reason: '' };
165
+ }
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Resolve the nearest existing ancestor before checking workspace containment.
3
+ *
4
+ * `path.resolve()` only removes lexical `..`; it does not follow symlinks. An
5
+ * allowed path like `<workspace>/linked/outside.txt` might actually write to an
6
+ * unrelated directory. This helper follows every *existing* path component,
7
+ * including symlinked directory ancestors, before evaluating the boundary.
8
+ *
9
+ * The final path is permitted to be absent (needed for fs_write / mkdir).
10
+ * A dangling symlink, inaccessible ancestor, or symlink cycle is denied.
11
+ * This protects the central path policy; it is not an OS sandbox and cannot
12
+ * eliminate TOCTOU races if an external actor retargets a link during I/O.
13
+ */
14
+ import fs from 'node:fs';
15
+ import path from 'node:path';
16
+ function errorCode(value) {
17
+ return typeof value === 'object' && value !== null && 'code' in value
18
+ ? String(value.code) : undefined;
19
+ }
20
+ export function physicalPath(target) {
21
+ if (typeof target !== 'string' || target.length === 0)
22
+ return null;
23
+ let candidate = path.resolve(target);
24
+ const missing = [];
25
+ for (let depth = 0; depth < 1024; depth++) {
26
+ try {
27
+ fs.lstatSync(candidate); // lstat also sees dangling symlinks.
28
+ }
29
+ catch (error) {
30
+ if (errorCode(error) !== 'ENOENT')
31
+ return null;
32
+ const parent = path.dirname(candidate);
33
+ if (parent === candidate)
34
+ return null;
35
+ missing.unshift(path.basename(candidate));
36
+ candidate = parent;
37
+ continue;
38
+ }
39
+ try {
40
+ const resolved = fs.realpathSync.native(candidate);
41
+ return path.resolve(resolved, ...missing);
42
+ }
43
+ catch {
44
+ return null; // dangling link, inaccessible target, or symlink loop
45
+ }
46
+ }
47
+ return null;
48
+ }
49
+ function normalizeCompare(value) {
50
+ return process.platform === 'win32' ? value.toLowerCase() : value;
51
+ }
52
+ export function isWithinPhysicalPath(child, parent) {
53
+ const relative = path.relative(normalizeCompare(parent), normalizeCompare(child));
54
+ return relative === '' || (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));
55
+ }
56
+ /** The current Sandbox OS hard-deny list, applied to physical paths as well. */
57
+ export function isProtectedPhysicalPath(target) {
58
+ if (process.platform === 'darwin') {
59
+ if (isWithinPhysicalPath(target, '/private/var/folders') || isWithinPhysicalPath(target, '/private/var/tmp') || isWithinPhysicalPath(target, '/tmp')) {
60
+ return false;
61
+ }
62
+ }
63
+ const blocked = process.platform === 'win32'
64
+ ? ['C:\\Windows', 'C:\\Program Files', 'C:\\ProgramData']
65
+ : ['/etc', '/private/etc', '/usr/bin', '/usr/sbin', '/sbin', '/bin', '/System', '/private/var'];
66
+ return blocked.some(root => isWithinPhysicalPath(target, root));
67
+ }
68
+ export function isPhysicalPathAllowed(target, workspaces, grantAllAccess = false) {
69
+ const realTarget = physicalPath(target);
70
+ if (!realTarget || isProtectedPhysicalPath(path.resolve(target)) || isProtectedPhysicalPath(realTarget)) {
71
+ return false;
72
+ }
73
+ if (grantAllAccess)
74
+ return true;
75
+ return workspaces.some(root => {
76
+ const realRoot = physicalPath(root);
77
+ return realRoot !== null && isWithinPhysicalPath(realTarget, realRoot);
78
+ });
79
+ }
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Resolve the nearest existing ancestor before checking workspace containment.
3
+ *
4
+ * `path.resolve()` only removes lexical `..`; it does not follow symlinks. An
5
+ * allowed path like `<workspace>/linked/outside.txt` might actually write to an
6
+ * unrelated directory. This helper follows every *existing* path component,
7
+ * including symlinked directory ancestors, before evaluating the boundary.
8
+ *
9
+ * The final path is permitted to be absent (needed for fs_write / mkdir).
10
+ * A dangling symlink, inaccessible ancestor, or symlink cycle is denied.
11
+ * This protects the central path policy; it is not an OS sandbox and cannot
12
+ * eliminate TOCTOU races if an external actor retargets a link during I/O.
13
+ */
14
+ import fs from 'node:fs';
15
+ import path from 'node:path';
16
+
17
+ function errorCode(value: unknown): string | undefined {
18
+ return typeof value === 'object' && value !== null && 'code' in value
19
+ ? String(value.code) : undefined;
20
+ }
21
+
22
+ export function physicalPath(target: string): string | null {
23
+ if (typeof target !== 'string' || target.length === 0) return null;
24
+ let candidate = path.resolve(target);
25
+ const missing: string[] = [];
26
+ for (let depth = 0; depth < 1024; depth++) {
27
+ try {
28
+ fs.lstatSync(candidate); // lstat also sees dangling symlinks.
29
+ } catch (error) {
30
+ if (errorCode(error) !== 'ENOENT') return null;
31
+ const parent = path.dirname(candidate);
32
+ if (parent === candidate) return null;
33
+ missing.unshift(path.basename(candidate));
34
+ candidate = parent;
35
+ continue;
36
+ }
37
+ try {
38
+ const resolved = fs.realpathSync.native(candidate);
39
+ return path.resolve(resolved, ...missing);
40
+ } catch {
41
+ return null; // dangling link, inaccessible target, or symlink loop
42
+ }
43
+ }
44
+ return null;
45
+ }
46
+
47
+ function normalizeCompare(value: string): string {
48
+ return process.platform === 'win32' ? value.toLowerCase() : value;
49
+ }
50
+
51
+ export function isWithinPhysicalPath(child: string, parent: string): boolean {
52
+ const relative = path.relative(normalizeCompare(parent), normalizeCompare(child));
53
+ return relative === '' || (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));
54
+ }
55
+
56
+ /** The current Sandbox OS hard-deny list, applied to physical paths as well. */
57
+ export function isProtectedPhysicalPath(target: string): boolean {
58
+ if (process.platform === 'darwin') {
59
+ if (isWithinPhysicalPath(target, '/private/var/folders') || isWithinPhysicalPath(target, '/private/var/tmp') || isWithinPhysicalPath(target, '/tmp')) {
60
+ return false;
61
+ }
62
+ }
63
+ const blocked = process.platform === 'win32'
64
+ ? ['C:\\Windows', 'C:\\Program Files', 'C:\\ProgramData']
65
+ : ['/etc', '/private/etc', '/usr/bin', '/usr/sbin', '/sbin', '/bin', '/System', '/private/var'];
66
+ return blocked.some(root => isWithinPhysicalPath(target, root));
67
+ }
68
+
69
+ export function isPhysicalPathAllowed(
70
+ target: string,
71
+ workspaces: readonly string[],
72
+ grantAllAccess = false
73
+ ): boolean {
74
+ const realTarget = physicalPath(target);
75
+ if (!realTarget || isProtectedPhysicalPath(path.resolve(target)) || isProtectedPhysicalPath(realTarget)) {
76
+ return false;
77
+ }
78
+ if (grantAllAccess) return true;
79
+ return workspaces.some(root => {
80
+ const realRoot = physicalPath(root);
81
+ return realRoot !== null && isWithinPhysicalPath(realTarget, realRoot);
82
+ });
83
+ }