@causyne/agent 1.20.118 → 1.20.121

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.
Files changed (101) hide show
  1. package/package.json +1 -1
  2. package/src/agent/errorClassifier.js +113 -0
  3. package/src/agent/errorClassifier.ts +161 -0
  4. package/src/agent/promptIntent.js +200 -0
  5. package/src/agent/promptIntent.ts +203 -0
  6. package/src/agent/toolArgValidator.js +97 -0
  7. package/src/agent/toolArgValidator.ts +112 -0
  8. package/src/agentLoop.js +51 -351
  9. package/src/agentLoop.ts +69 -363
  10. package/src/autoUpdate.js +111 -8
  11. package/src/autoUpdate.ts +144 -8
  12. package/src/browser/causyneBrowser.js +231 -136
  13. package/src/browser/causyneBrowser.ts +229 -140
  14. package/src/browser/searchProviders.js +41 -30
  15. package/src/browser/searchProviders.ts +24 -14
  16. package/src/browser/workspacePathSafety.js +50 -0
  17. package/src/browser/workspacePathSafety.ts +50 -0
  18. package/src/browser/workspacePreview.js +27 -4
  19. package/src/browser/workspacePreview.ts +28 -4
  20. package/src/cliMode.js +17 -3
  21. package/src/commands.js +15 -22
  22. package/src/config.js +42 -63
  23. package/src/configVault.js +204 -0
  24. package/src/configVault.ts +213 -0
  25. package/src/core/contextCompactor.js +70 -11
  26. package/src/core/contextCompactor.ts +83 -11
  27. package/src/creative/liveBridge.js +34 -1
  28. package/src/creative/liveBridge.ts +28 -1
  29. package/src/dynamicCatalogue.js +42 -73
  30. package/src/dynamicCatalogue.ts +74 -60
  31. package/src/entrypoint.js +77 -4
  32. package/src/headlessCli.js +304 -0
  33. package/src/headlessCli.ts +380 -0
  34. package/src/mcp/mcpClient.js +38 -11
  35. package/src/mcp/mcpClient.ts +44 -11
  36. package/src/mcp/mcpRegistry.js +2 -5
  37. package/src/mcp/mcpRegistry.ts +2 -5
  38. package/src/mcp/mcpSecurity.js +189 -0
  39. package/src/mcp/mcpSecurity.ts +190 -0
  40. package/src/observer/evidence.js +23 -0
  41. package/src/observer/evidence.ts +21 -0
  42. package/src/osKeychain.js +209 -0
  43. package/src/osKeychain.ts +245 -0
  44. package/src/providers/anthropic.js +61 -28
  45. package/src/providers/base.js +14 -0
  46. package/src/providers/byokHttp.js +354 -0
  47. package/src/providers/byokHttp.ts +454 -0
  48. package/src/providers/byokStream.js +657 -0
  49. package/src/providers/byokStream.ts +759 -0
  50. package/src/providers/dashscope-byok.js +47 -32
  51. package/src/providers/deepseek.js +43 -39
  52. package/src/providers/gemini.js +73 -38
  53. package/src/providers/moonshot.js +43 -33
  54. package/src/providers/muse.js +10 -10
  55. package/src/providers/ollama.js +46 -31
  56. package/src/providers/openai-compatible.js +57 -32
  57. package/src/providers/openrouter.js +77 -113
  58. package/src/providers/openrouter.ts +99 -118
  59. package/src/providers/qwen-byok.js +46 -23
  60. package/src/providers/toolContracts.js +9 -3
  61. package/src/providers/toolContracts.ts +9 -3
  62. package/src/providers/wireNormalizer.js +238 -0
  63. package/src/providers/wireNormalizer.ts +279 -0
  64. package/src/providers/xai.js +43 -33
  65. package/src/sandbox.js +77 -56
  66. package/src/sandboxPolicy.js +1208 -0
  67. package/src/sandboxPolicy.ts +1300 -0
  68. package/src/sessionJournal.js +47 -0
  69. package/src/sessionJournal.ts +49 -0
  70. package/src/tools/browserAutomator.js +13 -1
  71. package/src/tools/browserAutomator.ts +13 -0
  72. package/src/tools/creativeApps.js +2 -1
  73. package/src/tools/creativeApps.ts +2 -1
  74. package/src/tools/gameAssetFetcher.js +130 -26
  75. package/src/tools/gameAssetHarvester.js +80 -58
  76. package/src/tools/nativeEngine.js +1 -1
  77. package/src/tools/nativeEngine.ts +1 -1
  78. package/src/tools/osSandbox.js +473 -0
  79. package/src/tools/osSandbox.ts +554 -0
  80. package/src/tools/persistentShell.js +8 -3
  81. package/src/tools/registry.js +13 -0
  82. package/src/tools/subprocessEnv.js +197 -0
  83. package/src/tools/subprocessEnv.ts +212 -0
  84. package/src/tools/sysRun.js +39 -6
  85. package/src/tools/sysRun.ts +53 -7
  86. package/src/tools/toolScanner.js +596 -140
  87. package/src/tools/toolScanner.ts +665 -147
  88. package/src/tools/toolSelfRepair.js +243 -114
  89. package/src/tools/toolSelfRepair.ts +262 -111
  90. package/src/tools/webFetch.js +161 -24
  91. package/src/tools/webFetch.ts +157 -22
  92. package/src/tools/webSearch.js +33 -4
  93. package/src/tools/webSearch.ts +27 -4
  94. package/src/tui/sessionPicker.js +132 -35
  95. package/src/tui/sessionPicker.ts +153 -32
  96. package/src/tui/sessionPickerView.js +277 -34
  97. package/src/tui/sessionPickerView.ts +328 -34
  98. package/src/tui/statusLine.js +3 -0
  99. package/src/tui/statusLine.ts +5 -0
  100. package/src/tui/workspaceIdentity.js +133 -0
  101. package/src/tui/workspaceIdentity.ts +146 -0
@@ -19,17 +19,22 @@ function decodeEntities(value) {
19
19
  }
20
20
  function cleanMarkup(value) {
21
21
  return decodeEntities(value.replace(/<!\[CDATA\[([\s\S]*?)\]\]>/g, '$1').replace(/<[^>]+>/g, ' '))
22
+ .replace(/[\x00-\x1f\x7f-\x9f\u202a-\u202e\u2066-\u2069]/g, ' ')
22
23
  .replace(/\s+/g, ' ')
23
24
  .trim();
24
25
  }
25
- function publicResultUrl(value) {
26
+ export function publicResultUrl(value) {
26
27
  try {
28
+ if (value.length > 4_096)
29
+ return null;
27
30
  const parsed = new URL(decodeEntities(value));
28
31
  if (!['http:', 'https:'].includes(parsed.protocol))
29
32
  return null;
30
33
  const host = parsed.hostname.toLowerCase().replace(/^\[|\]$/g, '').replace(/\.$/, '');
31
34
  if (parsed.username || parsed.password || host === 'localhost' ||
32
35
  host.endsWith('.localhost') || host.endsWith('.local') || host.endsWith('.internal') ||
36
+ host.endsWith('.invalid') || host.endsWith('.test') || host.endsWith('.example') ||
37
+ host.endsWith('.onion') || host === 'localhost.localdomain' ||
33
38
  (isIP(host) !== 0 && isPrivateAddress(host)))
34
39
  return null;
35
40
  if (/(^|\.)(bing|duckduckgo)\.com$/i.test(parsed.hostname))
@@ -87,8 +92,10 @@ export function parseDuckDuckGoHtml(html) {
87
92
  }
88
93
  async function readBoundedText(response) {
89
94
  const declared = Number(response.headers.get('content-length') ?? '0');
90
- if (Number.isFinite(declared) && declared > MAX_PROVIDER_BYTES)
95
+ if (Number.isFinite(declared) && declared > MAX_PROVIDER_BYTES) {
96
+ await response.body?.cancel().catch(() => { });
91
97
  throw new Error('search response is too large');
98
+ }
92
99
  if (!response.body)
93
100
  return '';
94
101
  const reader = response.body.getReader();
@@ -117,9 +124,6 @@ export async function searchPublicWeb(query, options = {}) {
117
124
  if (!cleaned || cleaned.length > 1_000)
118
125
  throw new Error('Search query must contain 1-1000 characters');
119
126
  const fetchImpl = options.fetchImpl ?? fetch;
120
- const controller = new AbortController();
121
- const timeout = setTimeout(() => controller.abort(), SEARCH_TIMEOUT_MS);
122
- const signal = options.signal ? AbortSignal.any([controller.signal, options.signal]) : controller.signal;
123
127
  const providers = [
124
128
  {
125
129
  engine: 'duckduckgo-html',
@@ -135,33 +139,40 @@ export async function searchPublicWeb(query, options = {}) {
135
139
  }
136
140
  ];
137
141
  const failures = [];
138
- try {
139
- for (const provider of providers) {
140
- try {
141
- const response = await fetchImpl(provider.url, {
142
- method: 'GET',
143
- redirect: 'error',
144
- signal,
145
- headers: {
146
- Accept: provider.accept,
147
- 'Accept-Language': 'en-US,en;q=0.8',
148
- 'User-Agent': 'Causyne-Agent/1.10 (+https://causyne.com)'
149
- }
150
- });
151
- if (!response.ok)
152
- throw new Error(`HTTP ${response.status}`);
153
- const results = provider.parse(await readBoundedText(response));
154
- if (results.length > 0)
155
- return results;
156
- failures.push(`${provider.engine}: no results`);
157
- }
158
- catch (error) {
159
- failures.push(`${provider.engine}: ${error instanceof Error ? error.message : String(error)}`);
142
+ for (const provider of providers) {
143
+ if (options.signal?.aborted)
144
+ throw options.signal.reason ?? new Error('Search cancelled');
145
+ const controller = new AbortController();
146
+ const timeout = setTimeout(() => controller.abort(), SEARCH_TIMEOUT_MS);
147
+ const signal = options.signal ? AbortSignal.any([controller.signal, options.signal]) : controller.signal;
148
+ try {
149
+ const response = await fetchImpl(provider.url, {
150
+ method: 'GET',
151
+ redirect: 'error',
152
+ signal,
153
+ headers: {
154
+ Accept: provider.accept,
155
+ 'Accept-Language': 'en-US,en;q=0.8',
156
+ 'User-Agent': 'Causyne-Agent/1.10 (+https://causyne.com)'
157
+ }
158
+ });
159
+ if (!response.ok) {
160
+ await response.body?.cancel().catch(() => { });
161
+ throw new Error(`HTTP ${response.status}`);
160
162
  }
163
+ const results = provider.parse(await readBoundedText(response));
164
+ if (results.length > 0)
165
+ return results;
166
+ failures.push(`${provider.engine}: no results`);
167
+ }
168
+ catch (error) {
169
+ if (options.signal?.aborted)
170
+ throw error;
171
+ failures.push(`${provider.engine}: ${error instanceof Error ? error.message : String(error)}`);
172
+ }
173
+ finally {
174
+ clearTimeout(timeout);
161
175
  }
162
- }
163
- finally {
164
- clearTimeout(timeout);
165
176
  }
166
177
  throw new Error(`Lightweight search providers exhausted. ${failures.join('; ')}`);
167
178
  }
@@ -33,17 +33,21 @@ function decodeEntities(value: string): string {
33
33
 
34
34
  function cleanMarkup(value: string): string {
35
35
  return decodeEntities(value.replace(/<!\[CDATA\[([\s\S]*?)\]\]>/g, '$1').replace(/<[^>]+>/g, ' '))
36
+ .replace(/[\x00-\x1f\x7f-\x9f\u202a-\u202e\u2066-\u2069]/g, ' ')
36
37
  .replace(/\s+/g, ' ')
37
38
  .trim();
38
39
  }
39
40
 
40
- function publicResultUrl(value: string): string | null {
41
+ export function publicResultUrl(value: string): string | null {
41
42
  try {
43
+ if (value.length > 4_096) return null;
42
44
  const parsed = new URL(decodeEntities(value));
43
45
  if (!['http:', 'https:'].includes(parsed.protocol)) return null;
44
46
  const host = parsed.hostname.toLowerCase().replace(/^\[|\]$/g, '').replace(/\.$/, '');
45
47
  if (parsed.username || parsed.password || host === 'localhost' ||
46
48
  host.endsWith('.localhost') || host.endsWith('.local') || host.endsWith('.internal') ||
49
+ host.endsWith('.invalid') || host.endsWith('.test') || host.endsWith('.example') ||
50
+ host.endsWith('.onion') || host === 'localhost.localdomain' ||
47
51
  (isIP(host) !== 0 && isPrivateAddress(host))) return null;
48
52
  if (/(^|\.)(bing|duckduckgo)\.com$/i.test(parsed.hostname)) return null;
49
53
  return parsed.href;
@@ -96,7 +100,10 @@ export function parseDuckDuckGoHtml(html: string): SearchResult[] {
96
100
 
97
101
  async function readBoundedText(response: Response): Promise<string> {
98
102
  const declared = Number(response.headers.get('content-length') ?? '0');
99
- if (Number.isFinite(declared) && declared > MAX_PROVIDER_BYTES) throw new Error('search response is too large');
103
+ if (Number.isFinite(declared) && declared > MAX_PROVIDER_BYTES) {
104
+ await response.body?.cancel().catch(() => {});
105
+ throw new Error('search response is too large');
106
+ }
100
107
  if (!response.body) return '';
101
108
  const reader = response.body.getReader();
102
109
  const chunks: Uint8Array[] = [];
@@ -122,9 +129,6 @@ export async function searchPublicWeb(query: string, options: SearchOptions = {}
122
129
  const cleaned = String(query ?? '').trim();
123
130
  if (!cleaned || cleaned.length > 1_000) throw new Error('Search query must contain 1-1000 characters');
124
131
  const fetchImpl = options.fetchImpl ?? fetch;
125
- const controller = new AbortController();
126
- const timeout = setTimeout(() => controller.abort(), SEARCH_TIMEOUT_MS);
127
- const signal = options.signal ? AbortSignal.any([controller.signal, options.signal]) : controller.signal;
128
132
  const providers = [
129
133
  {
130
134
  engine: 'duckduckgo-html',
@@ -140,9 +144,12 @@ export async function searchPublicWeb(query: string, options: SearchOptions = {}
140
144
  }
141
145
  ];
142
146
  const failures: string[] = [];
143
- try {
144
- for (const provider of providers) {
145
- try {
147
+ for (const provider of providers) {
148
+ if (options.signal?.aborted) throw options.signal.reason ?? new Error('Search cancelled');
149
+ const controller = new AbortController();
150
+ const timeout = setTimeout(() => controller.abort(), SEARCH_TIMEOUT_MS);
151
+ const signal = options.signal ? AbortSignal.any([controller.signal, options.signal]) : controller.signal;
152
+ try {
146
153
  const response = await fetchImpl(provider.url, {
147
154
  method: 'GET',
148
155
  redirect: 'error',
@@ -153,16 +160,19 @@ export async function searchPublicWeb(query: string, options: SearchOptions = {}
153
160
  'User-Agent': 'Causyne-Agent/1.10 (+https://causyne.com)'
154
161
  }
155
162
  });
156
- if (!response.ok) throw new Error(`HTTP ${response.status}`);
163
+ if (!response.ok) {
164
+ await response.body?.cancel().catch(() => {});
165
+ throw new Error(`HTTP ${response.status}`);
166
+ }
157
167
  const results = provider.parse(await readBoundedText(response));
158
168
  if (results.length > 0) return results;
159
169
  failures.push(`${provider.engine}: no results`);
160
- } catch (error) {
161
- failures.push(`${provider.engine}: ${error instanceof Error ? error.message : String(error)}`);
162
- }
170
+ } catch (error) {
171
+ if (options.signal?.aborted) throw error;
172
+ failures.push(`${provider.engine}: ${error instanceof Error ? error.message : String(error)}`);
173
+ } finally {
174
+ clearTimeout(timeout);
163
175
  }
164
- } finally {
165
- clearTimeout(timeout);
166
176
  }
167
177
  throw new Error(`Lightweight search providers exhausted. ${failures.join('; ')}`);
168
178
  }
@@ -0,0 +1,50 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ function within(root, target) {
4
+ const relative = path.relative(root, target);
5
+ return relative === '' || (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));
6
+ }
7
+ function scopedTarget(workspace, target) {
8
+ const root = path.resolve(workspace);
9
+ const resolved = path.resolve(target);
10
+ if (root === resolved || !within(root, resolved))
11
+ throw new Error('File target must stay inside the selected workspace');
12
+ return { root, resolved };
13
+ }
14
+ export async function ensureSafeWorkspaceOutputPath(workspace, target) {
15
+ const { root, resolved } = scopedTarget(workspace, target);
16
+ const realRoot = await fs.realpath(root);
17
+ const relativeParent = path.relative(root, path.dirname(resolved));
18
+ let current = root;
19
+ for (const part of relativeParent.split(path.sep).filter(Boolean)) {
20
+ current = path.join(current, part);
21
+ try {
22
+ await fs.lstat(current);
23
+ }
24
+ catch (error) {
25
+ if (error.code !== 'ENOENT')
26
+ throw error;
27
+ await fs.mkdir(current);
28
+ }
29
+ const realCurrent = await fs.realpath(current);
30
+ if (!within(realRoot, realCurrent) || !(await fs.stat(current)).isDirectory()) {
31
+ throw new Error('Output directory resolves outside the selected workspace');
32
+ }
33
+ }
34
+ const existing = await fs.lstat(resolved).catch((error) => {
35
+ if (error.code === 'ENOENT')
36
+ return null;
37
+ throw error;
38
+ });
39
+ if (existing?.isSymbolicLink() || (existing && !existing.isFile())) {
40
+ throw new Error('Output target cannot be a symlink or directory');
41
+ }
42
+ }
43
+ export async function ensureSafeWorkspaceInputPath(workspace, target) {
44
+ const { root, resolved } = scopedTarget(workspace, target);
45
+ const realRoot = await fs.realpath(root);
46
+ const realTarget = await fs.realpath(resolved);
47
+ if (!within(realRoot, realTarget) || !(await fs.stat(realTarget)).isFile()) {
48
+ throw new Error('Upload file resolves outside the selected workspace or is not regular');
49
+ }
50
+ }
@@ -0,0 +1,50 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+
4
+ function within(root: string, target: string): boolean {
5
+ const relative = path.relative(root, target);
6
+ return relative === '' || (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));
7
+ }
8
+
9
+ function scopedTarget(workspace: string, target: string): { root: string; resolved: string } {
10
+ const root = path.resolve(workspace);
11
+ const resolved = path.resolve(target);
12
+ if (root === resolved || !within(root, resolved)) throw new Error('File target must stay inside the selected workspace');
13
+ return { root, resolved };
14
+ }
15
+
16
+ export async function ensureSafeWorkspaceOutputPath(workspace: string, target: string): Promise<void> {
17
+ const { root, resolved } = scopedTarget(workspace, target);
18
+ const realRoot = await fs.realpath(root);
19
+ const relativeParent = path.relative(root, path.dirname(resolved));
20
+ let current = root;
21
+ for (const part of relativeParent.split(path.sep).filter(Boolean)) {
22
+ current = path.join(current, part);
23
+ try {
24
+ await fs.lstat(current);
25
+ } catch (error) {
26
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
27
+ await fs.mkdir(current);
28
+ }
29
+ const realCurrent = await fs.realpath(current);
30
+ if (!within(realRoot, realCurrent) || !(await fs.stat(current)).isDirectory()) {
31
+ throw new Error('Output directory resolves outside the selected workspace');
32
+ }
33
+ }
34
+ const existing = await fs.lstat(resolved).catch((error: NodeJS.ErrnoException) => {
35
+ if (error.code === 'ENOENT') return null;
36
+ throw error;
37
+ });
38
+ if (existing?.isSymbolicLink() || (existing && !existing.isFile())) {
39
+ throw new Error('Output target cannot be a symlink or directory');
40
+ }
41
+ }
42
+
43
+ export async function ensureSafeWorkspaceInputPath(workspace: string, target: string): Promise<void> {
44
+ const { root, resolved } = scopedTarget(workspace, target);
45
+ const realRoot = await fs.realpath(root);
46
+ const realTarget = await fs.realpath(resolved);
47
+ if (!within(realRoot, realTarget) || !(await fs.stat(realTarget)).isFile()) {
48
+ throw new Error('Upload file resolves outside the selected workspace or is not regular');
49
+ }
50
+ }
@@ -2,6 +2,27 @@ import fs from 'node:fs/promises';
2
2
  import path from 'node:path';
3
3
  import { randomUUID } from 'node:crypto';
4
4
  const MAX_ACTIVE_PREVIEWS = 128;
5
+ const MAX_PREVIEW_BYTES = 25 * 1024 * 1024;
6
+ export async function readBoundedPreviewFile(file, maxBytes = MAX_PREVIEW_BYTES, openFile = fs.open) {
7
+ const handle = await openFile(file, 'r');
8
+ try {
9
+ const stat = await handle.stat();
10
+ if (!stat.isFile() || stat.size > maxBytes || stat.size < 0)
11
+ return null;
12
+ const body = Buffer.alloc(stat.size);
13
+ let total = 0;
14
+ while (total < body.length) {
15
+ const { bytesRead } = await handle.read(body, total, body.length - total, total);
16
+ if (bytesRead === 0)
17
+ break;
18
+ total += bytesRead;
19
+ }
20
+ return total === body.length ? body : null;
21
+ }
22
+ finally {
23
+ await handle.close();
24
+ }
25
+ }
5
26
  const MIME = {
6
27
  '.html': 'text/html', '.htm': 'text/html', '.js': 'text/javascript', '.mjs': 'text/javascript',
7
28
  '.css': 'text/css', '.json': 'application/json', '.svg': 'image/svg+xml', '.png': 'image/png',
@@ -23,6 +44,8 @@ export class WorkspacePreview {
23
44
  const target = await fs.realpath(path.resolve(root, file));
24
45
  if (!within(root, target) || !/\.html?$/i.test(target))
25
46
  throw new Error('Preview requires an HTML file inside the selected workspace');
47
+ if (!(await fs.stat(target)).isFile())
48
+ throw new Error('Preview target must be a regular HTML file');
26
49
  const origin = `https://${randomUUID()}.causyne-preview.invalid`;
27
50
  this.roots.set(origin, path.dirname(target));
28
51
  if (this.roots.size > MAX_ACTIVE_PREVIEWS) {
@@ -46,16 +69,16 @@ export class WorkspacePreview {
46
69
  const deny = { status: 403, contentType: 'text/plain', body: Buffer.from('Preview asset is outside the allowed scope') };
47
70
  try {
48
71
  const parts = decodeURIComponent(url.pathname).replace(/\\/g, '/').split('/').filter(Boolean);
49
- if (parts.some(part => part.startsWith('.') || /^(credentials|secrets?|id_rsa|id_ed25519)(\.|$)/i.test(part)))
72
+ if (parts.some(part => part.startsWith('.') || /^(credentials|secrets?|private|tokens?|id_rsa|id_ed25519)([._-]|$)/i.test(part)))
50
73
  return deny;
51
74
  const file = await fs.realpath(path.resolve(root, ...parts));
52
75
  const contentType = MIME[path.extname(file).toLowerCase()];
53
76
  if (!within(root, file) || !contentType)
54
77
  return deny;
55
- const stat = await fs.stat(file);
56
- if (!stat.isFile() || stat.size > 25 * 1024 * 1024)
78
+ const body = await readBoundedPreviewFile(file);
79
+ if (body === null)
57
80
  return deny;
58
- return { status: 200, contentType, body: await fs.readFile(file) };
81
+ return { status: 200, contentType, body };
59
82
  }
60
83
  catch {
61
84
  return { ...deny, status: 404 };
@@ -3,6 +3,29 @@ import path from 'node:path';
3
3
  import { randomUUID } from 'node:crypto';
4
4
 
5
5
  const MAX_ACTIVE_PREVIEWS = 128;
6
+ const MAX_PREVIEW_BYTES = 25 * 1024 * 1024;
7
+
8
+ export async function readBoundedPreviewFile(
9
+ file: string, maxBytes = MAX_PREVIEW_BYTES, openFile: typeof fs.open = fs.open
10
+ ): Promise<Buffer | null> {
11
+ const handle = await openFile(file, 'r');
12
+ try {
13
+ const stat = await handle.stat();
14
+ if (!stat.isFile() || stat.size > maxBytes || stat.size < 0) return null;
15
+ const body = Buffer.alloc(stat.size);
16
+ let total = 0;
17
+ while (total < body.length) {
18
+ const { bytesRead } = await handle.read(body, total, body.length - total, total);
19
+ if (bytesRead === 0) break;
20
+ total += bytesRead;
21
+ }
22
+ return total === body.length ? body : null;
23
+ } finally {
24
+ await handle.close();
25
+ }
26
+ }
27
+
28
+
6
29
  const MIME: Record<string, string> = {
7
30
  '.html': 'text/html', '.htm': 'text/html', '.js': 'text/javascript', '.mjs': 'text/javascript',
8
31
  '.css': 'text/css', '.json': 'application/json', '.svg': 'image/svg+xml', '.png': 'image/png',
@@ -26,6 +49,7 @@ export class WorkspacePreview {
26
49
  const root = await fs.realpath(workspace);
27
50
  const target = await fs.realpath(path.resolve(root, file));
28
51
  if (!within(root, target) || !/\.html?$/i.test(target)) throw new Error('Preview requires an HTML file inside the selected workspace');
52
+ if (!(await fs.stat(target)).isFile()) throw new Error('Preview target must be a regular HTML file');
29
53
  const origin = `https://${randomUUID()}.causyne-preview.invalid`;
30
54
  this.roots.set(origin, path.dirname(target));
31
55
  if (this.roots.size > MAX_ACTIVE_PREVIEWS) {
@@ -47,13 +71,13 @@ export class WorkspacePreview {
47
71
  const deny = { status: 403, contentType: 'text/plain', body: Buffer.from('Preview asset is outside the allowed scope') };
48
72
  try {
49
73
  const parts = decodeURIComponent(url.pathname).replace(/\\/g, '/').split('/').filter(Boolean);
50
- if (parts.some(part => part.startsWith('.') || /^(credentials|secrets?|id_rsa|id_ed25519)(\.|$)/i.test(part))) return deny;
74
+ if (parts.some(part => part.startsWith('.') || /^(credentials|secrets?|private|tokens?|id_rsa|id_ed25519)([._-]|$)/i.test(part))) return deny;
51
75
  const file = await fs.realpath(path.resolve(root, ...parts));
52
76
  const contentType = MIME[path.extname(file).toLowerCase()];
53
77
  if (!within(root, file) || !contentType) return deny;
54
- const stat = await fs.stat(file);
55
- if (!stat.isFile() || stat.size > 25 * 1024 * 1024) return deny;
56
- return { status: 200, contentType, body: await fs.readFile(file) };
78
+ const body = await readBoundedPreviewFile(file);
79
+ if (body === null) return deny;
80
+ return { status: 200, contentType, body };
57
81
  } catch { return { ...deny, status: 404 }; }
58
82
  }
59
83
  }
package/src/cliMode.js CHANGED
@@ -27,6 +27,7 @@ import { isAcpProvider } from './providers/acp.js';
27
27
  import { isPiProvider } from './providers/pi.js';
28
28
  import { isAntigravityProvider } from './providers/antigravity.js';
29
29
  import { loadLocalImageAttachment } from './tui/clipboardImage.js';
30
+ import { runHeadlessTask, parsePermissionMode, parseMaxTurns } from './headlessCli.js';
30
31
 
31
32
  // One themed source for the art.
32
33
  //
@@ -255,13 +256,26 @@ async function runHomeAction(action, { prompt, conn, finish, loop }) {
255
256
  }
256
257
  }
257
258
 
258
- export async function runTask(task) {
259
+ export async function runTask(task, options = {}) {
260
+ if (options && (options.print || options.outputFormat)) {
261
+ await runHeadlessTask(task, options);
262
+ return;
263
+ }
264
+
259
265
  console.log(`\x1b[1m\x1b[36m[TASK]\x1b[0m Executing...\nTask: ${task}`);
260
266
 
261
267
  const conn = new LocalCLIConnection();
262
268
  const taskId = `cli_task_${Date.now()}`;
263
269
 
264
- const loop = new AgentLoop(conn, taskId, task);
270
+ const loopOptions = {};
271
+ if (options?.provider) loopOptions.provider = options.provider;
272
+ if (options?.model) loopOptions.model = options.model;
273
+ const loop = new AgentLoop(conn, taskId, task, loopOptions);
274
+
275
+ const permMode = parsePermissionMode(options?.permissionMode);
276
+ if (permMode) loop.autonomyOverride = permMode;
277
+ const maxTurns = parseMaxTurns(options?.maxTurns);
278
+ if (maxTurns !== undefined) loop.maxStepsCeiling = maxTurns;
265
279
 
266
280
  // Local human-in-the-loop, showing WHAT is being approved (see L6).
267
281
  loop.waitForApproval = makeApprovalHandler(conn);
@@ -595,7 +609,7 @@ export async function chatMode({ home = false } = {}) {
595
609
  const { runInteractiveSessionPicker } = await import('./tui/sessionPicker.js');
596
610
  await runInteractiveSessionPicker(prompt, {
597
611
  loop,
598
- workspace: loop?.workspaceRoot || process.cwd()
612
+ workspace: loop?.workspaceRoot || prompt?.root || process.cwd()
599
613
  });
600
614
  if (prompt && typeof prompt.draw === 'function') prompt.draw();
601
615
  continue;
package/src/commands.js CHANGED
@@ -45,7 +45,7 @@ import {
45
45
  import fs from 'fs';
46
46
  import os from 'os';
47
47
  import path from 'path';
48
- import { execSync } from 'child_process';
48
+ import { execFileSync } from 'child_process';
49
49
  import { runCopyCommand, runPasteCommand } from './tui/chatboxClipboard.js';
50
50
  import { loadLocalImageAttachment, formatByteSize } from './tui/clipboardImage.js';
51
51
  import { getPackageVersion } from './version.js';
@@ -539,7 +539,7 @@ export const COMMANDS = [
539
539
  let isGit = fs.existsSync(path.join(ws, '.git'));
540
540
  if (!isGit) {
541
541
  try {
542
- execSync('git rev-parse --is-inside-work-tree', { cwd: ws, stdio: 'pipe' });
542
+ execFileSync('git', ['rev-parse', '--is-inside-work-tree'], { cwd: ws, stdio: 'pipe' });
543
543
  isGit = true;
544
544
  } catch {
545
545
  isGit = false;
@@ -550,19 +550,20 @@ export const COMMANDS = [
550
550
  return ok(`Workspace "${ws}" is not a git repository.`);
551
551
  }
552
552
 
553
- const status = execSync('git status --short', { cwd: ws, encoding: 'utf8' }).trim();
553
+ const status = execFileSync('git', ['status', '--short'], { cwd: ws, encoding: 'utf8' }).trim();
554
554
  if (!status) {
555
555
  return ok('Working tree is clean. No uncommitted changes in this workspace.');
556
556
  }
557
557
 
558
- let diffCmd = 'git diff';
558
+ let diffArgs = ['diff'];
559
559
  if (sub === 'staged' || sub === '--cached') {
560
- diffCmd = 'git diff --cached';
560
+ diffArgs = ['diff', '--cached'];
561
561
  } else if (sub === 'stat') {
562
- diffCmd = 'git diff --stat HEAD';
562
+ diffArgs = ['diff', '--stat', 'HEAD'];
563
563
  }
564
+ const diffCmd = `git ${diffArgs.join(' ')}`;
564
565
 
565
- const diffOutput = execSync(diffCmd, { cwd: ws, encoding: 'utf8', maxBuffer: 1024 * 1024 }).trim();
566
+ const diffOutput = execFileSync('git', diffArgs, { cwd: ws, encoding: 'utf8', maxBuffer: 1024 * 1024 }).trim();
566
567
  const header = `Git Status (${ws}):\n${status}\n\n${'─'.repeat(50)}\n${diffCmd}:\n`;
567
568
  return ok(diffOutput ? `${header}\n${diffOutput}` : `${header}\n(no file diff for ${diffCmd})`);
568
569
  } catch (err) {
@@ -692,7 +693,7 @@ export const COMMANDS = [
692
693
  run: async (_args = [], context = {}) => {
693
694
  const store = await import('./sessionStore.js');
694
695
  const memory = context.loop && context.loop.memoryManager;
695
- const workspace = context.loop?.workspaceRoot || process.cwd();
696
+ const workspace = context.loop?.workspaceRoot || context.prompt?.root || process.cwd();
696
697
  const next = memory ? memory.startNewSession('Untitled') : store.createSession(workspace, 'Untitled', true);
697
698
  if (context.loop) {
698
699
  context.loop.messages = [];
@@ -742,7 +743,7 @@ export const COMMANDS = [
742
743
  const store = await import('./sessionStore.js');
743
744
  const verb = String(args[0] || '').toLowerCase();
744
745
  const memory = context.loop && context.loop.memoryManager;
745
- const workspace = context.loop?.workspaceRoot || process.cwd();
746
+ const workspace = context.loop?.workspaceRoot || context.prompt?.root || process.cwd();
746
747
 
747
748
  // If interactive TUI prompt is available and no sub-arguments are given, open interactive picker modal
748
749
  if ((!args || args.length === 0 || (args.length === 1 && args[0] === '')) && context.prompt) {
@@ -850,19 +851,11 @@ export const COMMANDS = [
850
851
  return ok('No sessions yet. This conversation becomes one as soon as you send something.');
851
852
  }
852
853
 
853
- const active = store.getActiveSessionId();
854
- const home = process.env.HOME || '';
855
- const lines = rows.slice(0, 20).map((s) => {
856
- const when = new Date(s.updatedAt).toISOString().slice(0, 16).replace('T', ' ');
857
- const where = s.workspace ? (home ? s.workspace.replace(home, '~') : s.workspace) : '(no workspace)';
858
- const mark = s.id === active ? '*' : ' ';
859
- return ` ${mark} ${s.id} ${when} ${String(s.messageCount).padStart(4)} msg ${where}\n ${s.title}`;
860
- });
854
+ const active = memory?.sessionId || store.getActiveSessionId();
855
+ const { formatSessionsTextReport } = await import('./tui/sessionPicker.js');
861
856
 
862
857
  return ok(
863
- `${rows.length} session${rows.length === 1 ? '' : 's'} (* = active):\n`
864
- + lines.join('\n')
865
- + '\n\nSwitch with /sessions switch <id>, fork with /fork [id], or run /sessions to open interactive modal picker.',
858
+ formatSessionsTextReport(rows, active, workspace),
866
859
  { effect: 'pick-session', items: rows, active }
867
860
  );
868
861
  }
@@ -2296,7 +2289,7 @@ export const COMMANDS = [
2296
2289
  promptText = `Please review ${target} for security vulnerabilities, logic correctness, performance, and best practices.`;
2297
2290
  } else {
2298
2291
  try {
2299
- const status = execSync('git status --short', { cwd: ws, encoding: 'utf8' }).trim();
2292
+ const status = execFileSync('git', ['status', '--short'], { cwd: ws, encoding: 'utf8' }).trim();
2300
2293
  if (!status) {
2301
2294
  return ok('Working tree is clean. To review a specific file, run: /review <path>');
2302
2295
  }
@@ -2437,7 +2430,7 @@ export const COMMANDS = [
2437
2430
  const ws = ctx.loop?.workspaceRoot || process.cwd();
2438
2431
  let isGit = false;
2439
2432
  try {
2440
- execSync('git rev-parse --is-inside-work-tree', { cwd: ws, stdio: 'pipe' });
2433
+ execFileSync('git', ['rev-parse', '--is-inside-work-tree'], { cwd: ws, stdio: 'pipe' });
2441
2434
  isGit = true;
2442
2435
  } catch {}
2443
2436
  lines.push(` ✓ Workspace root : ${ws}`);