@causyne/agent 1.20.78 → 1.20.81
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/agentLoop.js +75 -94
- package/src/agentLoop.ts +86 -106
- package/src/cliMode.js +33 -3
- package/src/commands.js +10 -8
- package/src/reliability/assetEvidence.js +112 -0
- package/src/reliability/assetEvidence.ts +109 -0
- package/src/reliability/networkHostGuard.js +56 -0
- package/src/reliability/networkHostGuard.ts +68 -0
- package/src/reliability/visualEvidence.js +21 -0
- package/src/reliability/visualEvidence.ts +35 -0
- package/src/tools/fsWrite.js +131 -22
- package/src/tools/fsWrite.ts +129 -26
- package/src/tui/completion.js +35 -7
- package/src/tui/prompt.js +27 -18
- package/src/tui/workspaceSwitch.js +52 -0
- package/src/tui/workspaceSwitch.ts +79 -0
package/src/tools/fsWrite.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import fs from 'node:fs/promises';
|
|
2
2
|
import path from 'node:path';
|
|
3
3
|
import os from 'node:os';
|
|
4
|
+
import { randomUUID } from 'node:crypto';
|
|
4
5
|
|
|
5
6
|
export interface FsWriteArgs {
|
|
6
7
|
path: string;
|
|
@@ -8,16 +9,81 @@ export interface FsWriteArgs {
|
|
|
8
9
|
createDirectories?: boolean;
|
|
9
10
|
}
|
|
10
11
|
|
|
12
|
+
export interface FsWriteContext {
|
|
13
|
+
workspaceRoot?: string;
|
|
14
|
+
workspacePaths?: string[];
|
|
15
|
+
grantAllAccess?: boolean;
|
|
16
|
+
parentLoop?: { workspaceRoot?: string };
|
|
17
|
+
}
|
|
18
|
+
|
|
11
19
|
export interface FsWriteResult {
|
|
12
20
|
success: boolean;
|
|
13
21
|
output?: string;
|
|
14
22
|
error?: string;
|
|
15
23
|
}
|
|
16
24
|
|
|
25
|
+
function expandHome(value: string): string {
|
|
26
|
+
return value === '~' ? os.homedir()
|
|
27
|
+
: value.startsWith('~/') || value.startsWith('~\\')
|
|
28
|
+
? path.join(os.homedir(), value.slice(2))
|
|
29
|
+
: value;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function inside(root: string, target: string): boolean {
|
|
33
|
+
const relative = path.relative(root, target);
|
|
34
|
+
return relative === '' || (relative !== '..' && !relative.startsWith(`..${path.sep}`)
|
|
35
|
+
&& !path.isAbsolute(relative));
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
async function physicalTarget(target: string): Promise<string> {
|
|
39
|
+
// Resolves symlinks in the longest existing ancestor, including a symlinked
|
|
40
|
+
// parent of a new file. It is not a substitute for OS-level isolation.
|
|
41
|
+
let current = target;
|
|
42
|
+
const missing: string[] = [];
|
|
43
|
+
while (true) {
|
|
44
|
+
try {
|
|
45
|
+
const resolved = await fs.realpath(current);
|
|
46
|
+
return path.join(resolved, ...missing.reverse());
|
|
47
|
+
} catch (error: unknown) {
|
|
48
|
+
if ((error as NodeJS.ErrnoException)?.code !== 'ENOENT') throw error;
|
|
49
|
+
const parent = path.dirname(current);
|
|
50
|
+
if (parent === current) throw new Error('Could not resolve target ancestry');
|
|
51
|
+
missing.push(path.basename(current));
|
|
52
|
+
current = parent;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
async function checkScope(target: string, context?: FsWriteContext): Promise<void> {
|
|
58
|
+
if (!context || context.grantAllAccess === true) return;
|
|
59
|
+
const roots = Array.isArray(context.workspacePaths) && context.workspacePaths.length > 0
|
|
60
|
+
? context.workspacePaths
|
|
61
|
+
: [context.parentLoop?.workspaceRoot, context.workspaceRoot].filter(
|
|
62
|
+
(value): value is string => typeof value === 'string' && value.length > 0
|
|
63
|
+
);
|
|
64
|
+
if (roots.length === 0) return;
|
|
65
|
+
const physical = await physicalTarget(target);
|
|
66
|
+
for (const root of roots) {
|
|
67
|
+
try {
|
|
68
|
+
const resolvedRoot = await fs.realpath(path.resolve(expandHome(root)));
|
|
69
|
+
if (inside(resolvedRoot, physical)) return;
|
|
70
|
+
} catch { /* A non-existent authorized root is not permission to escape. */ }
|
|
71
|
+
}
|
|
72
|
+
throw new Error(`Target resolves outside the selected workspace: ${target}`);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function writeError(error: unknown, target: string): string {
|
|
76
|
+
const code = (error as NodeJS.ErrnoException)?.code;
|
|
77
|
+
if (code === 'EISDIR' || code === 'ENOTEMPTY') {
|
|
78
|
+
return `Cannot write file: "${target}" is an existing directory. Supply a filename inside it, such as ${path.join(target, 'index.html')}.`;
|
|
79
|
+
}
|
|
80
|
+
return `Atomic file write failed: ${error instanceof Error ? error.message : String(error)}`;
|
|
81
|
+
}
|
|
82
|
+
|
|
17
83
|
export const fsWrite = {
|
|
18
84
|
schema: {
|
|
19
85
|
name: 'fs.write',
|
|
20
|
-
description: '
|
|
86
|
+
description: 'Write a complete UTF-8 file using atomic rename. Path must be a file, not a directory.',
|
|
21
87
|
parameters: {
|
|
22
88
|
type: 'object',
|
|
23
89
|
properties: {
|
|
@@ -28,39 +94,76 @@ export const fsWrite = {
|
|
|
28
94
|
required: ['path', 'content']
|
|
29
95
|
}
|
|
30
96
|
},
|
|
31
|
-
async execute(args: FsWriteArgs): Promise<FsWriteResult> {
|
|
32
|
-
try {
|
|
33
|
-
const target = args.path.replace(/^~\//, os.homedir() + '/');
|
|
34
97
|
|
|
35
|
-
|
|
98
|
+
async execute(args: FsWriteArgs, context?: FsWriteContext): Promise<FsWriteResult> {
|
|
99
|
+
if (!args || typeof args.path !== 'string' || !args.path.trim()) {
|
|
100
|
+
return { success: false, error: 'fs_write requires a nonempty path pointing to a FILE.' };
|
|
101
|
+
}
|
|
102
|
+
if (typeof args.content !== 'string') {
|
|
103
|
+
return { success: false, error: 'fs_write requires content as a string. Do not infer or invent missing file content.' };
|
|
104
|
+
}
|
|
105
|
+
if (args.path.endsWith('/') || args.path.endsWith('\\')) {
|
|
106
|
+
return { success: false, error: `Target ${args.path} ends in a directory separator. Add a filename such as index.html.` };
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const target = path.resolve(expandHome(args.path.trim()));
|
|
110
|
+
let temporary = '';
|
|
111
|
+
try {
|
|
112
|
+
await checkScope(target, context);
|
|
113
|
+
let originalMode: number | undefined;
|
|
36
114
|
try {
|
|
37
|
-
const stat = await fs.
|
|
115
|
+
const stat = await fs.lstat(target);
|
|
38
116
|
if (stat.isDirectory()) {
|
|
39
|
-
return {
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
};
|
|
117
|
+
return { success: false, error: `Cannot write file: "${target}" is an existing directory. Specify a target file path inside this directory (e.g. "${path.join(target, 'index.html')}").` };
|
|
118
|
+
}
|
|
119
|
+
if (stat.isSymbolicLink()) {
|
|
120
|
+
return { success: false, error: `Refusing to replace symbolic link ${target}; use a regular file in the selected workspace.` };
|
|
43
121
|
}
|
|
44
|
-
|
|
45
|
-
|
|
122
|
+
if (!stat.isFile()) {
|
|
123
|
+
return { success: false, error: `Target ${target} is not a regular file.` };
|
|
124
|
+
}
|
|
125
|
+
originalMode = stat.mode & 0o777;
|
|
126
|
+
} catch (error: unknown) {
|
|
127
|
+
if ((error as NodeJS.ErrnoException)?.code !== 'ENOENT') throw error;
|
|
46
128
|
}
|
|
47
129
|
|
|
48
130
|
if (args.createDirectories !== false) {
|
|
49
131
|
await fs.mkdir(path.dirname(target), { recursive: true });
|
|
50
132
|
}
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
const
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
const
|
|
63
|
-
|
|
133
|
+
// Re-check after creating parents: an existing parent might be a symlink.
|
|
134
|
+
await checkScope(target, context);
|
|
135
|
+
temporary = path.join(path.dirname(target), `.${path.basename(target)}.causyne-${randomUUID()}.tmp`);
|
|
136
|
+
const file = await fs.open(temporary, 'wx', originalMode ?? 0o600);
|
|
137
|
+
try {
|
|
138
|
+
await file.writeFile(args.content, { encoding: 'utf8' });
|
|
139
|
+
await file.sync();
|
|
140
|
+
} finally {
|
|
141
|
+
await file.close();
|
|
142
|
+
}
|
|
143
|
+
// Never reinterpret a directory as a file if the destination changed.
|
|
144
|
+
const destinationStat = await fs.lstat(target).catch((error: NodeJS.ErrnoException) => {
|
|
145
|
+
if (error.code === 'ENOENT') return null;
|
|
146
|
+
throw error;
|
|
147
|
+
});
|
|
148
|
+
if (destinationStat && !destinationStat.isFile()) {
|
|
149
|
+
throw new Error(`Destination is no longer a regular file: ${target}`);
|
|
150
|
+
}
|
|
151
|
+
await checkScope(target, context);
|
|
152
|
+
await fs.rename(temporary, target);
|
|
153
|
+
temporary = '';
|
|
154
|
+
// Flushing the parent directory is best effort: some platforms disallow it.
|
|
155
|
+
try {
|
|
156
|
+
const directory = await fs.open(path.dirname(target), 'r');
|
|
157
|
+
try { await directory.sync(); } finally { await directory.close(); }
|
|
158
|
+
} catch { /* Do not claim crash-durable guarantees on unsupported FS. */ }
|
|
159
|
+
return {
|
|
160
|
+
success: true,
|
|
161
|
+
output: `Wrote ${Buffer.byteLength(args.content, 'utf8')} bytes to ${target}`
|
|
162
|
+
};
|
|
163
|
+
} catch (error: unknown) {
|
|
164
|
+
return { success: false, error: writeError(error, target) };
|
|
165
|
+
} finally {
|
|
166
|
+
if (temporary) await fs.unlink(temporary).catch(() => {});
|
|
64
167
|
}
|
|
65
168
|
}
|
|
66
|
-
};
|
|
169
|
+
};
|
package/src/tui/completion.js
CHANGED
|
@@ -269,9 +269,10 @@ export class FileIndex {
|
|
|
269
269
|
async walk() {
|
|
270
270
|
const found = [];
|
|
271
271
|
const queue = [{ dir: this.root, depth: 0 }];
|
|
272
|
+
let next = 0;
|
|
272
273
|
|
|
273
|
-
while (queue.length
|
|
274
|
-
const { dir, depth } = queue
|
|
274
|
+
while (next < queue.length && found.length < MAX_INDEX_ENTRIES) {
|
|
275
|
+
const { dir, depth } = queue[next++];
|
|
275
276
|
let listing;
|
|
276
277
|
try {
|
|
277
278
|
listing = await fsp.readdir(dir, { withFileTypes: true });
|
|
@@ -305,6 +306,23 @@ export class FileIndex {
|
|
|
305
306
|
}
|
|
306
307
|
}
|
|
307
308
|
|
|
309
|
+
/**
|
|
310
|
+
* Resolve both the authorized root and candidate to physical paths before
|
|
311
|
+
* touching a directory. Lexical path.resolve() alone follows symlinks outside
|
|
312
|
+
* the workspace and can leak private filenames through @ completion.
|
|
313
|
+
*/
|
|
314
|
+
function isPhysicalChild(root, candidate) {
|
|
315
|
+
try {
|
|
316
|
+
const base = fs.realpathSync(root);
|
|
317
|
+
const target = fs.realpathSync(candidate);
|
|
318
|
+
const relative = path.relative(base, target);
|
|
319
|
+
return relative === '' || (relative !== '..' &&
|
|
320
|
+
!relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));
|
|
321
|
+
} catch {
|
|
322
|
+
return false;
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
|
|
308
326
|
/** Instant, shell-style completion of one directory level. */
|
|
309
327
|
function directoryItems(root, partial) {
|
|
310
328
|
const slash = partial.lastIndexOf('/');
|
|
@@ -313,7 +331,8 @@ function directoryItems(root, partial) {
|
|
|
313
331
|
|
|
314
332
|
// Never offer paths outside the workspace root, whatever the user typed.
|
|
315
333
|
const relativeToRoot = path.relative(root, target);
|
|
316
|
-
if (relativeToRoot
|
|
334
|
+
if (relativeToRoot === '..' || relativeToRoot.startsWith(`..${path.sep}`) ||
|
|
335
|
+
path.isAbsolute(relativeToRoot) || !isPhysicalChild(root, target)) return [];
|
|
317
336
|
|
|
318
337
|
let listing;
|
|
319
338
|
try {
|
|
@@ -325,14 +344,23 @@ function directoryItems(root, partial) {
|
|
|
325
344
|
const items = [];
|
|
326
345
|
for (const entry of listing) {
|
|
327
346
|
if (entry.name.startsWith('.')) continue;
|
|
328
|
-
|
|
329
|
-
|
|
347
|
+
const candidate = path.join(target, entry.name);
|
|
348
|
+
// A lexical entry can be a symlink to a private directory. Do not offer
|
|
349
|
+
// any symlink whose physical target leaves the active workspace.
|
|
350
|
+
if (entry.isSymbolicLink() && !isPhysicalChild(root, candidate)) continue;
|
|
351
|
+
let isDirectory = entry.isDirectory();
|
|
352
|
+
if (entry.isSymbolicLink()) {
|
|
353
|
+
try { isDirectory = fs.statSync(candidate).isDirectory(); }
|
|
354
|
+
catch { continue; }
|
|
355
|
+
}
|
|
356
|
+
if (isDirectory && SKIP_DIRECTORIES.has(entry.name)) continue;
|
|
357
|
+
const value = dirPart + entry.name + (isDirectory ? '/' : '');
|
|
330
358
|
if (!isTerminalSafe(value)) continue;
|
|
331
359
|
items.push({
|
|
332
360
|
value,
|
|
333
361
|
match: value,
|
|
334
362
|
label: value,
|
|
335
|
-
description:
|
|
363
|
+
description: isDirectory ? 'directory' : ''
|
|
336
364
|
});
|
|
337
365
|
}
|
|
338
366
|
return items;
|
|
@@ -449,7 +477,7 @@ export function suggest(text, cursor, options = {}) {
|
|
|
449
477
|
if (focusDir) {
|
|
450
478
|
const focusTarget = path.resolve(root, focusDir);
|
|
451
479
|
try {
|
|
452
|
-
if (
|
|
480
|
+
if (isPhysicalChild(root, focusTarget) && fs.statSync(focusTarget).isDirectory()) {
|
|
453
481
|
const focusedItems = directoryItems(focusTarget, trigger.query).map((item) => ({
|
|
454
482
|
...item,
|
|
455
483
|
value: `${focusDir}/${item.value}`,
|
package/src/tui/prompt.js
CHANGED
|
@@ -785,15 +785,13 @@ export class ChatPrompt {
|
|
|
785
785
|
// Control commands take priority over busy turns so the user is never locked out.
|
|
786
786
|
// Commands like /stop, /new, /model, /session, /sessions, /continuum, /clear can interrupt
|
|
787
787
|
// a stalled/long-running turn and execute immediately.
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
text === '/clear'
|
|
796
|
-
);
|
|
788
|
+
// Match a COMPLETE command token. Prefix tests made unrelated
|
|
789
|
+
// commands such as /newsletter interrupt an active agent turn.
|
|
790
|
+
const commandToken = text.trim().split(/\s+/, 1)[0].toLowerCase();
|
|
791
|
+
const isControlCommand = this.isCommand(text) && new Set([
|
|
792
|
+
'/stop', '/interrupt', '/new', '/model', '/models',
|
|
793
|
+
'/session', '/sessions', '/continuum', '/clear'
|
|
794
|
+
]).has(commandToken);
|
|
797
795
|
|
|
798
796
|
// Immediate abort signals interrupt the running turn directly without queuing as a future task.
|
|
799
797
|
if ((text === '/stop' || text === '/interrupt') && this.busy) {
|
|
@@ -1265,10 +1263,12 @@ export class ChatPrompt {
|
|
|
1265
1263
|
}
|
|
1266
1264
|
|
|
1267
1265
|
cursorOffset() {
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1266
|
+
// The editor stores Unicode code points; String.slice() in the completion
|
|
1267
|
+
// provider expects UTF-16 code units. Count units at this API boundary.
|
|
1268
|
+
const before = this.editor.lines.slice(0, this.editor.line)
|
|
1269
|
+
.reduce((total, line) => total + line.join('').length + 1, 0);
|
|
1270
|
+
return before + this.editor.lines[this.editor.line]
|
|
1271
|
+
.slice(0, this.editor.col).join('').length;
|
|
1272
1272
|
}
|
|
1273
1273
|
|
|
1274
1274
|
openCompletion(force = false) {
|
|
@@ -1465,15 +1465,24 @@ export class ChatPrompt {
|
|
|
1465
1465
|
}
|
|
1466
1466
|
|
|
1467
1467
|
setCursorOffset(offset) {
|
|
1468
|
-
|
|
1468
|
+
// Convert completion's UTF-16 offset back into the editor's code-point
|
|
1469
|
+
// column, never splitting a surrogate pair or moving to the wrong row.
|
|
1470
|
+
let remaining = Math.max(0, Number.isFinite(offset) ? offset : 0);
|
|
1469
1471
|
for (let index = 0; index < this.editor.lines.length; index++) {
|
|
1470
|
-
const
|
|
1471
|
-
|
|
1472
|
+
const line = this.editor.lines[index];
|
|
1473
|
+
const units = line.join('').length;
|
|
1474
|
+
if (remaining <= units || index === this.editor.lines.length - 1) {
|
|
1475
|
+
let column = 0;
|
|
1476
|
+
let consumed = 0;
|
|
1477
|
+
while (column < line.length && consumed + line[column].length <= remaining) {
|
|
1478
|
+
consumed += line[column].length;
|
|
1479
|
+
column++;
|
|
1480
|
+
}
|
|
1472
1481
|
this.editor.line = index;
|
|
1473
|
-
this.editor.col =
|
|
1482
|
+
this.editor.col = column;
|
|
1474
1483
|
return;
|
|
1475
1484
|
}
|
|
1476
|
-
remaining -=
|
|
1485
|
+
remaining -= units + 1;
|
|
1477
1486
|
}
|
|
1478
1487
|
}
|
|
1479
1488
|
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Rebind a chat session to a different workspace without mutating the previous
|
|
3
|
+
* agent's sandbox or mixing old workspace memory into the new session.
|
|
4
|
+
*
|
|
5
|
+
* This module owns no disk changes or CLI command parsing. createLoop() is the
|
|
6
|
+
* existing AgentLoop constructor, injected by cliMode for deterministic tests.
|
|
7
|
+
*/
|
|
8
|
+
export function switchChatWorkspace({ workspaceRoot, createLoop, prompt = null, surface = null, renderer = null, headerInfo = null, approvalHandler, decisionHandler }) {
|
|
9
|
+
if (typeof workspaceRoot !== 'string' || !workspaceRoot) {
|
|
10
|
+
throw new TypeError('A nonempty workspace root is required');
|
|
11
|
+
}
|
|
12
|
+
if (typeof createLoop !== 'function') {
|
|
13
|
+
throw new TypeError('createLoop must construct a new AgentLoop');
|
|
14
|
+
}
|
|
15
|
+
// Build the replacement before updating any displayed state. If construction
|
|
16
|
+
// fails, the previous loop and prompt remain intact for caller rollback.
|
|
17
|
+
const replacement = createLoop(workspaceRoot);
|
|
18
|
+
if (!replacement || replacement.workspaceRoot !== workspaceRoot) {
|
|
19
|
+
throw new Error('New agent loop did not adopt the requested workspace root');
|
|
20
|
+
}
|
|
21
|
+
const paths = replacement.sandbox?.workspacePaths;
|
|
22
|
+
if (!replacement.sandbox?.grantAllAccess &&
|
|
23
|
+
(!Array.isArray(paths) || !paths.includes(workspaceRoot))) {
|
|
24
|
+
throw new Error('New agent sandbox did not adopt the requested workspace root');
|
|
25
|
+
}
|
|
26
|
+
replacement.waitForApproval = approvalHandler;
|
|
27
|
+
replacement.waitForDecision = decisionHandler;
|
|
28
|
+
if (prompt) {
|
|
29
|
+
prompt.setWorkingRoot(workspaceRoot);
|
|
30
|
+
prompt.messageActionLoop = replacement;
|
|
31
|
+
// A workspace switch is also a change of task context. Do not transfer
|
|
32
|
+
// queued attachments or active skills from the previous workspace.
|
|
33
|
+
prompt.pendingAttachments = [];
|
|
34
|
+
prompt.completion = null;
|
|
35
|
+
if (typeof prompt.scheduleDraw === 'function')
|
|
36
|
+
prompt.scheduleDraw();
|
|
37
|
+
}
|
|
38
|
+
if (headerInfo) {
|
|
39
|
+
headerInfo.cwd = workspaceRoot;
|
|
40
|
+
headerInfo.workspace = replacement.sandbox?.grantAllAccess
|
|
41
|
+
? 'ALL ACCESS'
|
|
42
|
+
: replacement.sandbox?.workspacePaths?.join(', ') ?? '';
|
|
43
|
+
if (renderer?.status?.setSession)
|
|
44
|
+
renderer.status.setSession(headerInfo);
|
|
45
|
+
if (surface?.setSessionInfo)
|
|
46
|
+
surface.setSessionInfo({
|
|
47
|
+
...headerInfo,
|
|
48
|
+
activeSkill: null
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
return replacement;
|
|
52
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
export interface SwitchChatWorkspaceOptions<TLoop = any> {
|
|
2
|
+
workspaceRoot: string;
|
|
3
|
+
createLoop: (workspaceRoot: string) => TLoop;
|
|
4
|
+
prompt?: any;
|
|
5
|
+
surface?: any;
|
|
6
|
+
renderer?: any;
|
|
7
|
+
headerInfo?: any;
|
|
8
|
+
approvalHandler?: any;
|
|
9
|
+
decisionHandler?: any;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Rebind a chat session to a different workspace without mutating the previous
|
|
14
|
+
* agent's sandbox or mixing old workspace memory into the new session.
|
|
15
|
+
*
|
|
16
|
+
* This module owns no disk changes or CLI command parsing. createLoop() is the
|
|
17
|
+
* existing AgentLoop constructor, injected by cliMode for deterministic tests.
|
|
18
|
+
*/
|
|
19
|
+
export function switchChatWorkspace<TLoop extends {
|
|
20
|
+
workspaceRoot?: string;
|
|
21
|
+
sandbox?: { grantAllAccess?: boolean; workspacePaths?: string[] };
|
|
22
|
+
waitForApproval?: any;
|
|
23
|
+
waitForDecision?: any;
|
|
24
|
+
} = any>({
|
|
25
|
+
workspaceRoot,
|
|
26
|
+
createLoop,
|
|
27
|
+
prompt = null,
|
|
28
|
+
surface = null,
|
|
29
|
+
renderer = null,
|
|
30
|
+
headerInfo = null,
|
|
31
|
+
approvalHandler,
|
|
32
|
+
decisionHandler
|
|
33
|
+
}: SwitchChatWorkspaceOptions<TLoop>): TLoop {
|
|
34
|
+
if (typeof workspaceRoot !== 'string' || !workspaceRoot) {
|
|
35
|
+
throw new TypeError('A nonempty workspace root is required');
|
|
36
|
+
}
|
|
37
|
+
if (typeof createLoop !== 'function') {
|
|
38
|
+
throw new TypeError('createLoop must construct a new AgentLoop');
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// Build the replacement before updating any displayed state. If construction
|
|
42
|
+
// fails, the previous loop and prompt remain intact for caller rollback.
|
|
43
|
+
const replacement = createLoop(workspaceRoot);
|
|
44
|
+
if (!replacement || replacement.workspaceRoot !== workspaceRoot) {
|
|
45
|
+
throw new Error('New agent loop did not adopt the requested workspace root');
|
|
46
|
+
}
|
|
47
|
+
const paths = replacement.sandbox?.workspacePaths;
|
|
48
|
+
if (!replacement.sandbox?.grantAllAccess &&
|
|
49
|
+
(!Array.isArray(paths) || !paths.includes(workspaceRoot))) {
|
|
50
|
+
throw new Error('New agent sandbox did not adopt the requested workspace root');
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
replacement.waitForApproval = approvalHandler;
|
|
54
|
+
replacement.waitForDecision = decisionHandler;
|
|
55
|
+
|
|
56
|
+
if (prompt) {
|
|
57
|
+
prompt.setWorkingRoot(workspaceRoot);
|
|
58
|
+
prompt.messageActionLoop = replacement;
|
|
59
|
+
// A workspace switch is also a change of task context. Do not transfer
|
|
60
|
+
// queued attachments or active skills from the previous workspace.
|
|
61
|
+
prompt.pendingAttachments = [];
|
|
62
|
+
prompt.completion = null;
|
|
63
|
+
if (typeof prompt.scheduleDraw === 'function') prompt.scheduleDraw();
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
if (headerInfo) {
|
|
67
|
+
headerInfo.cwd = workspaceRoot;
|
|
68
|
+
headerInfo.workspace = replacement.sandbox?.grantAllAccess
|
|
69
|
+
? 'ALL ACCESS'
|
|
70
|
+
: replacement.sandbox?.workspacePaths?.join(', ') ?? '';
|
|
71
|
+
if (renderer?.status?.setSession) renderer.status.setSession(headerInfo);
|
|
72
|
+
if (surface?.setSessionInfo) surface.setSessionInfo({
|
|
73
|
+
...headerInfo,
|
|
74
|
+
activeSkill: null
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
return replacement;
|
|
79
|
+
}
|