@causyne/agent 1.20.103 → 1.20.104

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.103",
3
+ "version": "1.20.104",
4
4
  "description": "Agentic AI for software, tools, and computer workflows",
5
5
  "main": "bin/causyne.js",
6
6
  "type": "module",
package/src/agentLoop.js CHANGED
@@ -270,7 +270,7 @@ export function isMidTaskProgressText(text) {
270
270
  "i'm going to ",
271
271
  'going to '
272
272
  ];
273
- if (intentPrefixes.some(prefix => lastLower.startsWith(prefix) || lower.startsWith(prefix))) {
273
+ if (intentPrefixes.some(prefix => lastLower.startsWith(prefix) || (trimmed.length <= 280 && lower.startsWith(prefix)))) {
274
274
  if (!/\b(?:task completed|all done|everything is ready|finished|complete\.)\b/i.test(lastSentence)) {
275
275
  return true;
276
276
  }
@@ -576,6 +576,7 @@ export class AgentLoop {
576
576
  static MAX_CONSECUTIVE_FAILURES = 3;
577
577
  constructor(eventSink, taskId, userPrompt, options = {}) {
578
578
  this.eventSink = eventSink;
579
+ this._deliveredAgentMessages = new Set();
579
580
  this.taskId = taskId;
580
581
  this.userPrompt = userPrompt;
581
582
  // User intent must remain independent of injected @-file contents.
@@ -1354,6 +1355,22 @@ export class AgentLoop {
1354
1355
  return typeof result.output === 'string' ? result.output : '';
1355
1356
  }
1356
1357
  emitEvent(messageObj) {
1358
+ if (messageObj.type === 'agent_message' && typeof messageObj.content === 'string') {
1359
+ const content = messageObj.content.trim().replace(/\s+/g, ' ');
1360
+ if (content) {
1361
+ const streaming = messageObj.streaming === true;
1362
+ if ([...this._deliveredAgentMessages].some((prior) => prior === content || (streaming && prior.startsWith(content))))
1363
+ return;
1364
+ if (!streaming) {
1365
+ if (this._deliveredAgentMessages.size >= 32) {
1366
+ const oldest = this._deliveredAgentMessages.values().next().value;
1367
+ if (typeof oldest === 'string')
1368
+ this._deliveredAgentMessages.delete(oldest);
1369
+ }
1370
+ this._deliveredAgentMessages.add(content);
1371
+ }
1372
+ }
1373
+ }
1357
1374
  if (this.eventSink && this.eventSink.readyState === 1) {
1358
1375
  this.eventSink.send(JSON.stringify({ taskId: this.taskId, ...messageObj }));
1359
1376
  }
@@ -2058,6 +2075,7 @@ export class AgentLoop {
2058
2075
  }
2059
2076
  }
2060
2077
  this.stepsCompleted = 0;
2078
+ this._deliveredAgentMessages.clear();
2061
2079
  // Fresh per task. A digest from a previous task would point at a step
2062
2080
  // number the model can no longer see, which is worse than paying twice.
2063
2081
  this._observationDigests = new Map();
@@ -3303,31 +3321,13 @@ You are operating in a text-and-code modality without direct image pixel renderi
3303
3321
  continue;
3304
3322
  }
3305
3323
  }
3306
- const allPlanCompleted = this._implementationPlan?.length > 0
3307
- && this._implementationPlan.every((s) => s.status === 'completed' || s.completed);
3308
- if (!hasExternalActions && this.stepsCompleted === 0 && isActionable && !allPlanCompleted) {
3324
+ if (!hasExternalActions && this.stepsCompleted === 0 && isActionable) {
3309
3325
  this.messages.pop();
3310
3326
  this.emitEvent({ type: 'error', message: 'The selected model returned text without taking any action. No work was completed.' });
3311
3327
  this.memoryManager.saveHistory(this.messages);
3312
3328
  break;
3313
3329
  }
3314
3330
  if (!hasExternalActions && (isIncompleteTurn || failedExternalActions.length > 0 || !contentText.trim())) {
3315
- if (allPlanCompleted) {
3316
- const planSummary = ` All ${this._implementationPlan.length} plan steps have been completed and verified:\n\n`
3317
- + this._implementationPlan.map((s, idx) => ` ✓ ${s.step || s.text || s.content || `Step ${idx + 1}`}`).join('\n');
3318
- const summary = `Task completed successfully.${planSummary}`;
3319
- this.emitEvent({
3320
- type: 'agent_message',
3321
- content: summary
3322
- });
3323
- this.emitEvent({
3324
- type: 'status',
3325
- message: 'Task completed with verified deliverables.'
3326
- });
3327
- this._causyneTaskOutcome = 'completed';
3328
- this.memoryManager.saveHistory(this.messages);
3329
- break;
3330
- }
3331
3331
  if (this.stepsCompleted > 0 && incompleteTurnContinuations < 2 && failedExternalActions.length === 0) {
3332
3332
  incompleteTurnContinuations++;
3333
3333
  this.emitEvent({ type: 'status', message: 'Requesting the missing final response…' });
package/src/agentLoop.ts CHANGED
@@ -345,7 +345,7 @@ export function isMidTaskProgressText(text: string): boolean {
345
345
  "i'm going to ",
346
346
  'going to '
347
347
  ];
348
- if (intentPrefixes.some(prefix => lastLower.startsWith(prefix) || lower.startsWith(prefix))) {
348
+ if (intentPrefixes.some(prefix => lastLower.startsWith(prefix) || (trimmed.length <= 280 && lower.startsWith(prefix)))) {
349
349
  if (!/\b(?:task completed|all done|everything is ready|finished|complete\.)\b/i.test(lastSentence)) {
350
350
  return true;
351
351
  }
@@ -678,6 +678,7 @@ export class AgentLoop {
678
678
  static MAX_CONSECUTIVE_FAILURES = 3;
679
679
  constructor(eventSink: AgentLoopEventSink | null, taskId: string, userPrompt: string | null, options: AgentLoopOptions = {}) {
680
680
  this.eventSink = eventSink;
681
+ this._deliveredAgentMessages = new Set<string>();
681
682
  this.taskId = taskId;
682
683
  this.userPrompt = userPrompt;
683
684
  // User intent must remain independent of injected @-file contents.
@@ -1434,6 +1435,20 @@ export class AgentLoop {
1434
1435
  }
1435
1436
 
1436
1437
  emitEvent(messageObj: AgentLoopEvent) {
1438
+ if (messageObj.type === 'agent_message' && typeof (messageObj as any).content === 'string') {
1439
+ const content = (messageObj as any).content.trim().replace(/\s+/g, ' ');
1440
+ if (content) {
1441
+ const streaming = (messageObj as any).streaming === true;
1442
+ if ([...this._deliveredAgentMessages].some((prior: string) => prior === content || (streaming && prior.startsWith(content)))) return;
1443
+ if (!streaming) {
1444
+ if (this._deliveredAgentMessages.size >= 32) {
1445
+ const oldest = this._deliveredAgentMessages.values().next().value;
1446
+ if (typeof oldest === 'string') this._deliveredAgentMessages.delete(oldest);
1447
+ }
1448
+ this._deliveredAgentMessages.add(content);
1449
+ }
1450
+ }
1451
+ }
1437
1452
  if (this.eventSink && this.eventSink.readyState === 1) {
1438
1453
  this.eventSink.send(JSON.stringify({ taskId: this.taskId, ...messageObj }));
1439
1454
  }
@@ -2133,6 +2148,7 @@ export class AgentLoop {
2133
2148
  }
2134
2149
 
2135
2150
  this.stepsCompleted = 0;
2151
+ this._deliveredAgentMessages.clear();
2136
2152
  // Fresh per task. A digest from a previous task would point at a step
2137
2153
  // number the model can no longer see, which is worse than paying twice.
2138
2154
  this._observationDigests = new Map();
@@ -3443,10 +3459,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
3443
3459
  }
3444
3460
  }
3445
3461
 
3446
- const allPlanCompleted = this._implementationPlan?.length > 0
3447
- && this._implementationPlan.every((s: any) => s.status === 'completed' || s.completed);
3448
-
3449
- if (!hasExternalActions && this.stepsCompleted === 0 && isActionable && !allPlanCompleted) {
3462
+ if (!hasExternalActions && this.stepsCompleted === 0 && isActionable) {
3450
3463
  this.messages.pop();
3451
3464
  this.emitEvent({ type: 'error', message: 'The selected model returned text without taking any action. No work was completed.' });
3452
3465
  this.memoryManager.saveHistory(this.messages);
@@ -3454,22 +3467,6 @@ You are operating in a text-and-code modality without direct image pixel renderi
3454
3467
  }
3455
3468
 
3456
3469
  if (!hasExternalActions && (isIncompleteTurn || failedExternalActions.length > 0 || !contentText.trim())) {
3457
- if (allPlanCompleted) {
3458
- const planSummary = ` All ${this._implementationPlan.length} plan steps have been completed and verified:\n\n`
3459
- + this._implementationPlan.map((s: any, idx: number) => ` ✓ ${s.step || s.text || s.content || `Step ${idx + 1}`}`).join('\n');
3460
- const summary = `Task completed successfully.${planSummary}`;
3461
- this.emitEvent({
3462
- type: 'agent_message',
3463
- content: summary
3464
- });
3465
- this.emitEvent({
3466
- type: 'status',
3467
- message: 'Task completed with verified deliverables.'
3468
- });
3469
- this._causyneTaskOutcome = 'completed';
3470
- this.memoryManager.saveHistory(this.messages);
3471
- break;
3472
- }
3473
3470
  if (this.stepsCompleted > 0 && incompleteTurnContinuations < 2 && failedExternalActions.length === 0) {
3474
3471
  incompleteTurnContinuations++;
3475
3472
  this.emitEvent({ type: 'status', message: 'Requesting the missing final response…' });
@@ -8,19 +8,22 @@ const URL_OR_FILE_LAUNCH = /^\s*(?:open|preview)\s+(?:https?:\/\/|\/|~\/|\.\/|[a
8
8
  const BROWSER_LAUNCH = /\b(?:open|view)\s+(?:in\s+)?(?:browser|chrome|safari)\b/i;
9
9
  const SERVER_COMMAND = /^\s*(?:python(?:3(?:\.\d+)?)?\s+(?:-u\s+)?(?:\S*\/)?server\.py\b|python(?:3(?:\.\d+)?)?\s+-m\s+http\.server\b|(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:dev|start|serve)\b|(?:npx|bunx)\s+(?:vite|next\s+dev|http-server)\b|uvicorn\b|gunicorn\b|flask\s+run\b)/i;
10
10
  const READ_ONLY_COMMAND = /^\s*(?:pwd|ls|rg|grep|cat|head|tail|find|which|where|ps|pgrep|lsof|netstat|ss|git\s+(?:status|diff|log|show)|node\s+(?:-v|--version)|python(?:3(?:\.\d+)?)?\s+(?:-V|--version))\b/i;
11
+ // Some inspection executables have flags that write files or execute commands.
12
+ const MUTATING_INSPECTION_OPTIONS = /(?:^|\s)(?:-delete|-exec(?:dir)?|-ok(?:dir)?|-fprint(?:f|0)?|-fprintf|-fls)(?=\s|$)|(?:^|\s)--(?:output|pre)(?==|\s|$|-)/i;
11
13
  const OPEN_COMMAND = /^\s*(?:open|xdg-open|start)\s+\S+/i;
12
14
  const LOCAL_HEALTH_CHECK = /^\s*curl\b[^;&|><`$()]*https?:\/\/(?:localhost|127\.0\.0\.1):\d+(?:\/\S*)?\s*$/i;
13
- const PORT_CLEANUP_COMMAND = /^\s*(?:pkill|kill|fuser)\b/i;
14
15
  export const MUTATION_TOOLS = new Set([
15
16
  'fs_write', 'fs_edit', 'fs_delete', 'fs_move',
16
17
  'multi_edit', 'MultiEdit', 'edit_file', 'write_to_file', 'delete_file',
17
- 'create_skill', 'manage_local_dependencies'
18
+ 'create_skill', 'manage_local_dependencies', 'skill_create', 'memory_write', 'archive', 'tool.forge', 'proc.term'
18
19
  ]);
19
20
  const NO_EXECUTION_PHRASES = /\b(?:don'?t|do\s+not|never|without)\s+(?:execute|run|modify|mutate|apply|touch|write|change|edit|delete)\b|\b(?:no|without)\s+(?:execution|tools?|actions?)\b|\bjust\s+explain\b|\bread[\s-]only\b/i;
21
+ // 'Do not run tests' is a scoped restriction, not a prohibition on editing code.
22
+ const SCOPED_TEST_PROHIBITION = /\b(?:don'?t|do\s+not|never|without)\s+(?:run|execute)\s+(?:the\s+)?(?:unit\s+|integration\s+|e2e\s+)?(?:tests?|checks?|lint(?:ing|ers?)?|benchmarks?|test\s+suite)\b/gi;
20
23
  export function isNoExecutionPrompt(prompt) {
21
24
  if (!prompt || typeof prompt !== 'string')
22
25
  return false;
23
- return NO_EXECUTION_PHRASES.test(prompt);
26
+ return NO_EXECUTION_PHRASES.test(prompt.replace(SCOPED_TEST_PROHIBITION, ''));
24
27
  }
25
28
  export function isReadOnlyOrExplanatoryPrompt(prompt) {
26
29
  if (!prompt || typeof prompt !== 'string')
@@ -32,11 +35,28 @@ export function isReadOnlyOrExplanatoryPrompt(prompt) {
32
35
  return true;
33
36
  if (!INQUIRY_WORDS.test(trimmed))
34
37
  return false;
35
- // If the inquiry also explicitly commands creation/modification, it's not read-only
38
+ // Questions about *how to modify* are still requests for information.
39
+ if (/^(?:please\s+)?(?:how|why|what|where|when|who)\b/i.test(trimmed))
40
+ return true;
41
+ if (/^(?:please\s+)?(?:explain|describe|summarize|analy[sz]e|review|tell\s+me)\b/i.test(trimmed)) {
42
+ const followUp = /\b(?:and|then|also|afterwards)\s+(?:please\s+)?(.+)/i.exec(trimmed)?.[1] ?? '';
43
+ if (!CHANGE_VERBS.test(followUp) && !/^(?:run|execute|test|launch|open|start)\b/i.test(followUp))
44
+ return true;
45
+ }
46
+ // An inquiry that also commands implementation must not be forced read-only.
36
47
  if (CHANGE_VERBS.test(trimmed))
37
48
  return false;
38
49
  return true;
39
50
  }
51
+ const READ_ONLY_GIT_COMMAND = /^(?:status|diff|log|show|rev-parse|ls-files)(?=\s|$)/i;
52
+ const RISKY_GIT_INSPECTION_OPTIONS = /(?:^|\s)--(?:ext-diff|textconv|config-env)(?=\s|$|=)/i;
53
+ function isGitInspectionCommand(rawCommand) {
54
+ const command = String(rawCommand ?? '').trim();
55
+ return READ_ONLY_GIT_COMMAND.test(command)
56
+ && !hasShellControlOperators(command)
57
+ && !MUTATING_INSPECTION_OPTIONS.test(command)
58
+ && !RISKY_GIT_INSPECTION_OPTIONS.test(command);
59
+ }
40
60
  /** Enforces scope boundaries when the user's intent is explanatory or forbids execution. */
41
61
  export function readOnlyScopeError(tool, args, prompt) {
42
62
  const p = prompt || '';
@@ -50,16 +70,20 @@ export function readOnlyScopeError(tool, args, prompt) {
50
70
  if (MUTATION_TOOLS.has(tool) || tool === 'desktop_act' || tool === 'computer_use') {
51
71
  return 'The user requested an explanation/read-only inquiry, not workspace modifications or desktop actions.';
52
72
  }
73
+ if (tool === 'creative_apps' && !['status', 'verify_bridge'].includes(String(args.action ?? '').toLowerCase())) {
74
+ return 'A read-only inquiry does not authorize creative application mutations.';
75
+ }
76
+ if (tool === 'plugin.manager' && String(args.action ?? '').toLowerCase() !== 'list') {
77
+ return 'A read-only inquiry does not authorize modifying installed plugins.';
78
+ }
53
79
  if (tool === 'gitOp') {
54
- const command = String(args.command || '');
55
- if (/\b(?:commit|push|reset|rebase|merge|checkout\s+-b|branch\s+-[dD])\b/i.test(command)) {
56
- return 'A read-only inquiry does not authorize modifying git history or branches.';
57
- }
58
- return null;
80
+ return isGitInspectionCommand(args.command)
81
+ ? null
82
+ : 'A read-only inquiry authorizes inspection of Git status and history, not repository mutations.';
59
83
  }
60
84
  if (tool === 'sysRun' || tool === 'sysRunBg' || tool === 'terminal_persistent_shell') {
61
85
  const command = String(args.command ?? args.input ?? '').trim();
62
- if (READ_ONLY_COMMAND.test(command) && !/[;&|><`$()]/.test(command)) {
86
+ if (READ_ONLY_COMMAND.test(command) && !MUTATING_INSPECTION_OPTIONS.test(command) && !/[;&|><`$()]/.test(command)) {
63
87
  return null;
64
88
  }
65
89
  return 'A read-only inquiry authorizes only non-mutating status inspection commands (e.g. pwd, git status, cat), not arbitrary execution.';
@@ -95,23 +119,59 @@ export function isLaunchOnlyPrompt(prompt) {
95
119
  export function isServerLaunchCommand(command) {
96
120
  return SERVER_COMMAND.test(command.trim());
97
121
  }
122
+ function hasShellControlOperators(command) {
123
+ let quote = null;
124
+ for (let i = 0; i < command.length; i++) {
125
+ const ch = command.charAt(i);
126
+ if (ch === '\\') {
127
+ if (i === command.length - 1)
128
+ return true;
129
+ i++;
130
+ continue;
131
+ }
132
+ if (ch === '"' || ch === "'") {
133
+ if (quote === null)
134
+ quote = ch;
135
+ else if (quote === ch)
136
+ quote = null;
137
+ continue;
138
+ }
139
+ // Shell substitution is active inside double quotes.
140
+ if (ch === '`' || ch === '$' || ch === '\n' || ch === '\r')
141
+ return true;
142
+ if (quote === null && /[;&|><()]/.test(ch))
143
+ return true;
144
+ }
145
+ return quote !== null;
146
+ }
98
147
  /** A launch-only request authorizes inspection, starting the app, and opening it. */
99
148
  export function launchScopeError(tool, args) {
100
149
  if (MUTATION_TOOLS.has(tool)) {
101
150
  return 'The user asked to open the existing project, not change its files or configuration.';
102
151
  }
152
+ if (tool === 'creative_apps' && !['status', 'verify_bridge'].includes(String(args.action ?? '').toLowerCase())) {
153
+ return 'A launch-only request does not authorize creative application mutations.';
154
+ }
155
+ if (tool === 'plugin.manager' && String(args.action ?? '').toLowerCase() !== 'list') {
156
+ return 'A launch-only request does not authorize modifying installed plugins.';
157
+ }
158
+ if (tool === 'gitOp') {
159
+ return isGitInspectionCommand(args.command)
160
+ ? null
161
+ : 'A launch-only request allows Git inspection, not working-tree or history changes.';
162
+ }
103
163
  if (tool === 'sysRun' || tool === 'sysRunBg' || tool === 'terminal_persistent_shell') {
104
164
  const command = String(args.command ?? args.input ?? '').trim();
105
- if (OPEN_COMMAND.test(command) || isServerLaunchCommand(command) || LOCAL_HEALTH_CHECK.test(command) || PORT_CLEANUP_COMMAND.test(command)) {
106
- return null;
107
- }
108
- if (/[;&|><`$()]/.test(command)) {
165
+ if (hasShellControlOperators(command)) {
109
166
  return 'A launch-only request does not authorize chained shell commands. Use one scoped command per tool call.';
110
167
  }
111
- if (READ_ONLY_COMMAND.test(command)) {
168
+ if (OPEN_COMMAND.test(command) || isServerLaunchCommand(command) || LOCAL_HEALTH_CHECK.test(command)) {
169
+ return null;
170
+ }
171
+ if (READ_ONLY_COMMAND.test(command) && !MUTATING_INSPECTION_OPTIONS.test(command)) {
112
172
  return null;
113
173
  }
114
- return 'The user asked to open the existing project. Use read-only inspection, a background server, or desktop.open; do not run unrelated commands.';
174
+ return 'A launch-only request does not authorize unrelated commands. Use read-only inspection, a background server, or desktop.open; do not run unrelated commands.';
115
175
  }
116
176
  return null;
117
177
  }
@@ -9,21 +9,24 @@ const URL_OR_FILE_LAUNCH = /^\s*(?:open|preview)\s+(?:https?:\/\/|\/|~\/|\.\/|[a
9
9
  const BROWSER_LAUNCH = /\b(?:open|view)\s+(?:in\s+)?(?:browser|chrome|safari)\b/i;
10
10
  const SERVER_COMMAND = /^\s*(?:python(?:3(?:\.\d+)?)?\s+(?:-u\s+)?(?:\S*\/)?server\.py\b|python(?:3(?:\.\d+)?)?\s+-m\s+http\.server\b|(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:dev|start|serve)\b|(?:npx|bunx)\s+(?:vite|next\s+dev|http-server)\b|uvicorn\b|gunicorn\b|flask\s+run\b)/i;
11
11
  const READ_ONLY_COMMAND = /^\s*(?:pwd|ls|rg|grep|cat|head|tail|find|which|where|ps|pgrep|lsof|netstat|ss|git\s+(?:status|diff|log|show)|node\s+(?:-v|--version)|python(?:3(?:\.\d+)?)?\s+(?:-V|--version))\b/i;
12
+ // Some inspection executables have flags that write files or execute commands.
13
+ const MUTATING_INSPECTION_OPTIONS = /(?:^|\s)(?:-delete|-exec(?:dir)?|-ok(?:dir)?|-fprint(?:f|0)?|-fprintf|-fls)(?=\s|$)|(?:^|\s)--(?:output|pre)(?==|\s|$|-)/i;
12
14
  const OPEN_COMMAND = /^\s*(?:open|xdg-open|start)\s+\S+/i;
13
15
  const LOCAL_HEALTH_CHECK = /^\s*curl\b[^;&|><`$()]*https?:\/\/(?:localhost|127\.0\.0\.1):\d+(?:\/\S*)?\s*$/i;
14
- const PORT_CLEANUP_COMMAND = /^\s*(?:pkill|kill|fuser)\b/i;
15
16
 
16
17
  export const MUTATION_TOOLS = new Set([
17
18
  'fs_write', 'fs_edit', 'fs_delete', 'fs_move',
18
19
  'multi_edit', 'MultiEdit', 'edit_file', 'write_to_file', 'delete_file',
19
- 'create_skill', 'manage_local_dependencies'
20
+ 'create_skill', 'manage_local_dependencies', 'skill_create', 'memory_write', 'archive', 'tool.forge', 'proc.term'
20
21
  ]);
21
22
 
22
23
  const NO_EXECUTION_PHRASES = /\b(?:don'?t|do\s+not|never|without)\s+(?:execute|run|modify|mutate|apply|touch|write|change|edit|delete)\b|\b(?:no|without)\s+(?:execution|tools?|actions?)\b|\bjust\s+explain\b|\bread[\s-]only\b/i;
24
+ // 'Do not run tests' is a scoped restriction, not a prohibition on editing code.
25
+ const SCOPED_TEST_PROHIBITION = /\b(?:don'?t|do\s+not|never|without)\s+(?:run|execute)\s+(?:the\s+)?(?:unit\s+|integration\s+|e2e\s+)?(?:tests?|checks?|lint(?:ing|ers?)?|benchmarks?|test\s+suite)\b/gi;
23
26
 
24
27
  export function isNoExecutionPrompt(prompt?: string | null): boolean {
25
28
  if (!prompt || typeof prompt !== 'string') return false;
26
- return NO_EXECUTION_PHRASES.test(prompt);
29
+ return NO_EXECUTION_PHRASES.test(prompt.replace(SCOPED_TEST_PROHIBITION, ''));
27
30
  }
28
31
 
29
32
  export function isReadOnlyOrExplanatoryPrompt(prompt?: string | null): boolean {
@@ -32,11 +35,28 @@ export function isReadOnlyOrExplanatoryPrompt(prompt?: string | null): boolean {
32
35
  if (trimmed.length === 0) return false;
33
36
  if (isNoExecutionPrompt(trimmed)) return true;
34
37
  if (!INQUIRY_WORDS.test(trimmed)) return false;
35
- // If the inquiry also explicitly commands creation/modification, it's not read-only
38
+ // Questions about *how to modify* are still requests for information.
39
+ if (/^(?:please\s+)?(?:how|why|what|where|when|who)\b/i.test(trimmed)) return true;
40
+ if (/^(?:please\s+)?(?:explain|describe|summarize|analy[sz]e|review|tell\s+me)\b/i.test(trimmed)) {
41
+ const followUp = /\b(?:and|then|also|afterwards)\s+(?:please\s+)?(.+)/i.exec(trimmed)?.[1] ?? '';
42
+ if (!CHANGE_VERBS.test(followUp) && !/^(?:run|execute|test|launch|open|start)\b/i.test(followUp)) return true;
43
+ }
44
+ // An inquiry that also commands implementation must not be forced read-only.
36
45
  if (CHANGE_VERBS.test(trimmed)) return false;
37
46
  return true;
38
47
  }
39
48
 
49
+ const READ_ONLY_GIT_COMMAND = /^(?:status|diff|log|show|rev-parse|ls-files)(?=\s|$)/i;
50
+ const RISKY_GIT_INSPECTION_OPTIONS = /(?:^|\s)--(?:ext-diff|textconv|config-env)(?=\s|$|=)/i;
51
+
52
+ function isGitInspectionCommand(rawCommand: unknown): boolean {
53
+ const command = String(rawCommand ?? '').trim();
54
+ return READ_ONLY_GIT_COMMAND.test(command)
55
+ && !hasShellControlOperators(command)
56
+ && !MUTATING_INSPECTION_OPTIONS.test(command)
57
+ && !RISKY_GIT_INSPECTION_OPTIONS.test(command);
58
+ }
59
+
40
60
  /** Enforces scope boundaries when the user's intent is explanatory or forbids execution. */
41
61
  export function readOnlyScopeError(
42
62
  tool: string,
@@ -55,16 +75,20 @@ export function readOnlyScopeError(
55
75
  if (MUTATION_TOOLS.has(tool) || tool === 'desktop_act' || tool === 'computer_use') {
56
76
  return 'The user requested an explanation/read-only inquiry, not workspace modifications or desktop actions.';
57
77
  }
78
+ if (tool === 'creative_apps' && !['status', 'verify_bridge'].includes(String(args.action ?? '').toLowerCase())) {
79
+ return 'A read-only inquiry does not authorize creative application mutations.';
80
+ }
81
+ if (tool === 'plugin.manager' && String(args.action ?? '').toLowerCase() !== 'list') {
82
+ return 'A read-only inquiry does not authorize modifying installed plugins.';
83
+ }
58
84
  if (tool === 'gitOp') {
59
- const command = String(args.command || '');
60
- if (/\b(?:commit|push|reset|rebase|merge|checkout\s+-b|branch\s+-[dD])\b/i.test(command)) {
61
- return 'A read-only inquiry does not authorize modifying git history or branches.';
62
- }
63
- return null;
85
+ return isGitInspectionCommand(args.command)
86
+ ? null
87
+ : 'A read-only inquiry authorizes inspection of Git status and history, not repository mutations.';
64
88
  }
65
89
  if (tool === 'sysRun' || tool === 'sysRunBg' || tool === 'terminal_persistent_shell') {
66
90
  const command = String(args.command ?? args.input ?? '').trim();
67
- if (READ_ONLY_COMMAND.test(command) && !/[;&|><`$()]/.test(command)) {
91
+ if (READ_ONLY_COMMAND.test(command) && !MUTATING_INSPECTION_OPTIONS.test(command) && !/[;&|><`$()]/.test(command)) {
68
92
  return null;
69
93
  }
70
94
  return 'A read-only inquiry authorizes only non-mutating status inspection commands (e.g. pwd, git status, cat), not arbitrary execution.';
@@ -98,28 +122,63 @@ export function isServerLaunchCommand(command: string): boolean {
98
122
  return SERVER_COMMAND.test(command.trim());
99
123
  }
100
124
 
125
+ function hasShellControlOperators(command: string): boolean {
126
+ let quote: '"' | "'" | null = null;
127
+ for (let i = 0; i < command.length; i++) {
128
+ const ch = command.charAt(i);
129
+ if (ch === '\\') {
130
+ if (i === command.length - 1) return true;
131
+ i++;
132
+ continue;
133
+ }
134
+ if (ch === '"' || ch === "'") {
135
+ if (quote === null) quote = ch;
136
+ else if (quote === ch) quote = null;
137
+ continue;
138
+ }
139
+ // Shell substitution is active inside double quotes.
140
+ if (ch === '`' || ch === '$' || ch === '\n' || ch === '\r') return true;
141
+ if (quote === null && /[;&|><()]/.test(ch)) return true;
142
+ }
143
+ return quote !== null;
144
+ }
145
+
101
146
  /** A launch-only request authorizes inspection, starting the app, and opening it. */
102
147
  export function launchScopeError(tool: string, args: Record<string, unknown>): string | null {
103
148
  if (MUTATION_TOOLS.has(tool)) {
104
149
  return 'The user asked to open the existing project, not change its files or configuration.';
105
150
  }
106
151
 
152
+ if (tool === 'creative_apps' && !['status', 'verify_bridge'].includes(String(args.action ?? '').toLowerCase())) {
153
+ return 'A launch-only request does not authorize creative application mutations.';
154
+ }
155
+
156
+ if (tool === 'plugin.manager' && String(args.action ?? '').toLowerCase() !== 'list') {
157
+ return 'A launch-only request does not authorize modifying installed plugins.';
158
+ }
159
+
160
+ if (tool === 'gitOp') {
161
+ return isGitInspectionCommand(args.command)
162
+ ? null
163
+ : 'A launch-only request allows Git inspection, not working-tree or history changes.';
164
+ }
165
+
107
166
  if (tool === 'sysRun' || tool === 'sysRunBg' || tool === 'terminal_persistent_shell') {
108
167
  const command = String(args.command ?? args.input ?? '').trim();
109
168
 
110
- if (OPEN_COMMAND.test(command) || isServerLaunchCommand(command) || LOCAL_HEALTH_CHECK.test(command) || PORT_CLEANUP_COMMAND.test(command)) {
111
- return null;
169
+ if (hasShellControlOperators(command)) {
170
+ return 'A launch-only request does not authorize chained shell commands. Use one scoped command per tool call.';
112
171
  }
113
172
 
114
- if (/[;&|><`$()]/.test(command)) {
115
- return 'A launch-only request does not authorize chained shell commands. Use one scoped command per tool call.';
173
+ if (OPEN_COMMAND.test(command) || isServerLaunchCommand(command) || LOCAL_HEALTH_CHECK.test(command)) {
174
+ return null;
116
175
  }
117
176
 
118
- if (READ_ONLY_COMMAND.test(command)) {
177
+ if (READ_ONLY_COMMAND.test(command) && !MUTATING_INSPECTION_OPTIONS.test(command)) {
119
178
  return null;
120
179
  }
121
180
 
122
- return 'The user asked to open the existing project. Use read-only inspection, a background server, or desktop.open; do not run unrelated commands.';
181
+ return 'A launch-only request does not authorize unrelated commands. Use read-only inspection, a background server, or desktop.open; do not run unrelated commands.';
123
182
  }
124
183
 
125
184
  return null;
@@ -422,7 +422,8 @@ export function outcomeFromResult(tool, args, result, at) {
422
422
  const record = result !== null && typeof result === 'object' && !Array.isArray(result)
423
423
  ? result
424
424
  : {};
425
- const success = record.success !== false && typeof record.error !== 'string';
425
+ const success = record.success !== false && !(typeof record.error === 'string' && record.error.trim().length > 0)
426
+ && !(typeof record.exitCode === 'number' && (!Number.isFinite(record.exitCode) || record.exitCode !== 0));
426
427
  const rawError = typeof record.error === 'string' ? record.error : '';
427
428
  const exitCode = typeof record.exitCode === 'number' && Number.isFinite(record.exitCode) ? record.exitCode : null;
428
429
  const rawCommand = typeof args.command === 'string' ? args.command
@@ -486,7 +486,8 @@ export function outcomeFromResult(tool: string, args: Record<string, unknown>, r
486
486
  const record = result !== null && typeof result === 'object' && !Array.isArray(result)
487
487
  ? result as Record<string, unknown>
488
488
  : {};
489
- const success = record.success !== false && typeof record.error !== 'string';
489
+ const success = record.success !== false && !(typeof record.error === 'string' && record.error.trim().length > 0)
490
+ && !(typeof record.exitCode === 'number' && (!Number.isFinite(record.exitCode) || record.exitCode !== 0));
490
491
  const rawError = typeof record.error === 'string' ? record.error : '';
491
492
  const exitCode = typeof record.exitCode === 'number' && Number.isFinite(record.exitCode) ? record.exitCode : null;
492
493
  const rawCommand = typeof args.command === 'string' ? args.command
package/src/observer.js CHANGED
@@ -19,6 +19,17 @@ export function extractClaimedLocalUrls(text) {
19
19
  }
20
20
  return [...unique];
21
21
  }
22
+ function isWorkspaceArtifact(workspaceRoot, targetPath) {
23
+ try {
24
+ const root = fs.realpathSync(workspaceRoot);
25
+ const target = fs.realpathSync(targetPath);
26
+ const relative = path.relative(root, target);
27
+ return relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
28
+ }
29
+ catch {
30
+ return false;
31
+ }
32
+ }
22
33
  export class CausyneObserver {
23
34
  /**
24
35
  * Evaluates the current state of a task after a tool outcome or at a step boundary.
@@ -79,13 +90,13 @@ export class CausyneObserver {
79
90
  }
80
91
  // Check if the agent claims completion
81
92
  if (context.agentClaim && context.agentClaim.trim()) {
82
- const claim = context.agentClaim.toLowerCase();
93
+ // Negative completion statements must not be promoted to verified outcomes.
94
+ const claim = context.agentClaim.toLowerCase().replace(/\b(?:not|never|isn't|wasn't|haven't|hasn't)\s+(?:(?:yet|fully|actually|successfully)\s+)?(?:done|complete|completed|finished|implemented|fixed|verified)\b/gi, '');
83
95
  const claimsCompletion = /\b(?:done|complete|completed|finished|implemented|fixed|verified)\b|\b(?:is\s+(?:running|live|available|listening|served)\s+(?:at|on)|application\s+is\s+running)\b/i.test(claim);
84
96
  if (claimsCompletion) {
85
97
  // Run deterministic verification checks based on domain
86
98
  const hasMutations = outcomes.some(o => ['fs_write', 'fs_edit', 'MultiEdit', 'write_file', 'edit_file'].includes(o.tool));
87
- const hasPassingVerification = outcomes.some(o => o.success && (o.rendered === true ||
88
- o.tool === 'browser_act' ||
99
+ const hasPassingVerification = outcomes.slice(outcomes.findLastIndex(o => ['fs_write', 'fs_edit', 'MultiEdit', 'write_file', 'edit_file'].includes(o.tool)) + 1).some(o => o.success && (o.exitCode == null || o.exitCode === 0) && (o.rendered === true ||
89
100
  o.tool === 'verify_local_web' ||
90
101
  (o.command && /\b(?:test|build|check|typecheck|vitest|jest|pytest)\b/i.test(o.command))));
91
102
  if (hasMutations && !hasPassingVerification) {
@@ -119,6 +130,8 @@ export class CausyneObserver {
119
130
  * Deterministically verifies code deliverables (targeted test, build, syntax).
120
131
  */
121
132
  verifyCode(req) {
133
+ if (!req.changedFiles?.length)
134
+ return { verified: false, error: 'No code deliverables supplied.', evidence: 'no_files' };
122
135
  if (req.changedFiles && req.changedFiles.length > 0) {
123
136
  for (const file of req.changedFiles) {
124
137
  const fullPath = path.isAbsolute(file) ? file : path.join(req.workspaceRoot, file);
@@ -129,6 +142,12 @@ export class CausyneObserver {
129
142
  evidence: 'file_missing'
130
143
  };
131
144
  }
145
+ if (!isWorkspaceArtifact(req.workspaceRoot, fullPath)) {
146
+ return { verified: false, error: `Target deliverable ${file} is outside the workspace.`, evidence: 'outside_workspace' };
147
+ }
148
+ if (!fs.statSync(fullPath).isFile() || fs.statSync(fullPath).size === 0) {
149
+ return { verified: false, error: `Target deliverable ${file} is not a non-empty file.`, evidence: 'invalid_file' };
150
+ }
132
151
  }
133
152
  }
134
153
  return {
@@ -144,6 +163,10 @@ export class CausyneObserver {
144
163
  if (!fs.existsSync(fullPath)) {
145
164
  return { verified: false, missingHeadings: req.requiredHeadings || [] };
146
165
  }
166
+ if (!isWorkspaceArtifact(req.workspaceRoot, fullPath))
167
+ return { verified: false, missingHeadings: req.requiredHeadings || [] };
168
+ if (!fs.statSync(fullPath).isFile())
169
+ return { verified: false, missingHeadings: req.requiredHeadings || [] };
147
170
  const content = fs.readFileSync(fullPath, 'utf8');
148
171
  const missing = [];
149
172
  for (const heading of req.requiredHeadings || []) {
@@ -165,8 +188,14 @@ export class CausyneObserver {
165
188
  if (!fs.existsSync(fullPath)) {
166
189
  return { verified: false, bytes: 0, error: `Media asset not found: ${req.artifactPath}` };
167
190
  }
191
+ if (!isWorkspaceArtifact(req.workspaceRoot, fullPath))
192
+ return { verified: false, bytes: 0, error: 'Media artifact is outside the workspace.' };
168
193
  const stat = fs.statSync(fullPath);
194
+ if (!stat.isFile())
195
+ return { verified: false, bytes: 0, error: 'Media artifact must be a regular file.' };
169
196
  const minBytes = req.minBytes ?? 100;
197
+ if (!Number.isSafeInteger(minBytes) || minBytes < 0)
198
+ return { verified: false, bytes: stat.size, error: 'Invalid minimum artifact size.' };
170
199
  if (stat.size < minBytes) {
171
200
  return { verified: false, bytes: stat.size, error: `Media asset too small (${stat.size} bytes < ${minBytes} bytes)` };
172
201
  }
@@ -184,10 +213,16 @@ export class CausyneObserver {
184
213
  resolve({ verified: false, error: 'Only local loopback endpoints (127.0.0.1, localhost) may be verified.' });
185
214
  return;
186
215
  }
216
+ if (url.username || url.password) {
217
+ resolve({ verified: false, error: 'Local verification URL must not contain credentials.' });
218
+ return;
219
+ }
187
220
  const clientReq = http.get(req.endpoint, { timeout: req.timeoutMs ?? 3000 }, (res) => {
188
221
  res.resume();
189
222
  const expected = req.expectedStatus ?? 200;
190
- const ok = res.statusCode === expected || (res.statusCode !== undefined && res.statusCode >= 200 && res.statusCode < 400);
223
+ const ok = req.expectedStatus === undefined
224
+ ? (res.statusCode !== undefined && res.statusCode >= 200 && res.statusCode < 300)
225
+ : res.statusCode === expected;
191
226
  const result = { verified: Boolean(ok) };
192
227
  if (typeof res.statusCode === 'number')
193
228
  result.statusCode = res.statusCode;
package/src/observer.ts CHANGED
@@ -76,6 +76,17 @@ export function extractClaimedLocalUrls(text: string): string[] {
76
76
  return [...unique];
77
77
  }
78
78
 
79
+ function isWorkspaceArtifact(workspaceRoot: string, targetPath: string): boolean {
80
+ try {
81
+ const root = fs.realpathSync(workspaceRoot);
82
+ const target = fs.realpathSync(targetPath);
83
+ const relative = path.relative(root, target);
84
+ return relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
85
+ } catch {
86
+ return false;
87
+ }
88
+ }
89
+
79
90
  export class CausyneObserver {
80
91
  /**
81
92
  * Evaluates the current state of a task after a tool outcome or at a step boundary.
@@ -141,7 +152,8 @@ export class CausyneObserver {
141
152
 
142
153
  // Check if the agent claims completion
143
154
  if (context.agentClaim && context.agentClaim.trim()) {
144
- const claim = context.agentClaim.toLowerCase();
155
+ // Negative completion statements must not be promoted to verified outcomes.
156
+ const claim = context.agentClaim.toLowerCase().replace(/\b(?:not|never|isn't|wasn't|haven't|hasn't)\s+(?:(?:yet|fully|actually|successfully)\s+)?(?:done|complete|completed|finished|implemented|fixed|verified)\b/gi, '');
145
157
  const claimsCompletion = /\b(?:done|complete|completed|finished|implemented|fixed|verified)\b|\b(?:is\s+(?:running|live|available|listening|served)\s+(?:at|on)|application\s+is\s+running)\b/i.test(claim);
146
158
 
147
159
  if (claimsCompletion) {
@@ -149,10 +161,9 @@ export class CausyneObserver {
149
161
  const hasMutations = outcomes.some(o =>
150
162
  ['fs_write', 'fs_edit', 'MultiEdit', 'write_file', 'edit_file'].includes(o.tool)
151
163
  );
152
- const hasPassingVerification = outcomes.some(o =>
153
- o.success && (
164
+ const hasPassingVerification = outcomes.slice(outcomes.findLastIndex(o => ['fs_write', 'fs_edit', 'MultiEdit', 'write_file', 'edit_file'].includes(o.tool)) + 1).some(o =>
165
+ o.success && (o.exitCode == null || o.exitCode === 0) && (
154
166
  o.rendered === true ||
155
- o.tool === 'browser_act' ||
156
167
  o.tool === 'verify_local_web' ||
157
168
  (o.command && /\b(?:test|build|check|typecheck|vitest|jest|pytest)\b/i.test(o.command))
158
169
  )
@@ -192,6 +203,7 @@ export class CausyneObserver {
192
203
  * Deterministically verifies code deliverables (targeted test, build, syntax).
193
204
  */
194
205
  public verifyCode(req: CodeVerificationRequest): { verified: boolean; error?: string; evidence: string } {
206
+ if (!req.changedFiles?.length) return { verified: false, error: 'No code deliverables supplied.', evidence: 'no_files' };
195
207
  if (req.changedFiles && req.changedFiles.length > 0) {
196
208
  for (const file of req.changedFiles) {
197
209
  const fullPath = path.isAbsolute(file) ? file : path.join(req.workspaceRoot, file);
@@ -202,6 +214,12 @@ export class CausyneObserver {
202
214
  evidence: 'file_missing'
203
215
  };
204
216
  }
217
+ if (!isWorkspaceArtifact(req.workspaceRoot, fullPath)) {
218
+ return { verified: false, error: `Target deliverable ${file} is outside the workspace.`, evidence: 'outside_workspace' };
219
+ }
220
+ if (!fs.statSync(fullPath).isFile() || fs.statSync(fullPath).size === 0) {
221
+ return { verified: false, error: `Target deliverable ${file} is not a non-empty file.`, evidence: 'invalid_file' };
222
+ }
205
223
  }
206
224
  }
207
225
 
@@ -220,6 +238,8 @@ export class CausyneObserver {
220
238
  return { verified: false, missingHeadings: req.requiredHeadings || [] };
221
239
  }
222
240
 
241
+ if (!isWorkspaceArtifact(req.workspaceRoot, fullPath)) return { verified: false, missingHeadings: req.requiredHeadings || [] };
242
+ if (!fs.statSync(fullPath).isFile()) return { verified: false, missingHeadings: req.requiredHeadings || [] };
223
243
  const content = fs.readFileSync(fullPath, 'utf8');
224
244
  const missing: string[] = [];
225
245
 
@@ -245,8 +265,11 @@ export class CausyneObserver {
245
265
  return { verified: false, bytes: 0, error: `Media asset not found: ${req.artifactPath}` };
246
266
  }
247
267
 
268
+ if (!isWorkspaceArtifact(req.workspaceRoot, fullPath)) return { verified: false, bytes: 0, error: 'Media artifact is outside the workspace.' };
248
269
  const stat = fs.statSync(fullPath);
270
+ if (!stat.isFile()) return { verified: false, bytes: 0, error: 'Media artifact must be a regular file.' };
249
271
  const minBytes = req.minBytes ?? 100;
272
+ if (!Number.isSafeInteger(minBytes) || minBytes < 0) return { verified: false, bytes: stat.size, error: 'Invalid minimum artifact size.' };
250
273
  if (stat.size < minBytes) {
251
274
  return { verified: false, bytes: stat.size, error: `Media asset too small (${stat.size} bytes < ${minBytes} bytes)` };
252
275
  }
@@ -267,10 +290,17 @@ export class CausyneObserver {
267
290
  return;
268
291
  }
269
292
 
293
+ if (url.username || url.password) {
294
+ resolve({ verified: false, error: 'Local verification URL must not contain credentials.' });
295
+ return;
296
+ }
297
+
270
298
  const clientReq = http.get(req.endpoint, { timeout: req.timeoutMs ?? 3000 }, (res) => {
271
299
  res.resume();
272
300
  const expected = req.expectedStatus ?? 200;
273
- const ok = res.statusCode === expected || (res.statusCode !== undefined && res.statusCode >= 200 && res.statusCode < 400);
301
+ const ok = req.expectedStatus === undefined
302
+ ? (res.statusCode !== undefined && res.statusCode >= 200 && res.statusCode < 300)
303
+ : res.statusCode === expected;
274
304
  const result: { verified: boolean; statusCode?: number; error?: string } = { verified: Boolean(ok) };
275
305
  if (typeof res.statusCode === 'number') result.statusCode = res.statusCode;
276
306
  if (!ok) result.error = `HTTP ${res.statusCode ?? 'unknown'}`;
@@ -24,11 +24,15 @@ function record(value) {
24
24
  }
25
25
  function operationFamily(args) {
26
26
  const command = typeof args.command === 'string' ? args.command
27
- : typeof args.cmd === 'string' ? args.cmd : '';
27
+ : typeof args.cmd === 'string' ? args.cmd
28
+ : typeof args.CommandLine === 'string' ? args.CommandLine
29
+ : typeof args.commandLine === 'string' ? args.commandLine
30
+ : typeof args.script === 'string' ? args.script : '';
28
31
  if (!command) {
29
- if (typeof args.url === 'string') {
32
+ const endpoint = typeof args.url === 'string' ? args.url : typeof args.endpoint === 'string' ? args.endpoint : '';
33
+ if (endpoint) {
30
34
  try {
31
- return new URL(args.url).hostname.toLowerCase();
35
+ return new URL(endpoint).hostname.toLowerCase();
32
36
  }
33
37
  catch {
34
38
  return '';
@@ -46,15 +50,16 @@ function operationFamily(args) {
46
50
  }
47
51
  function issueKey(tool, args) {
48
52
  const family = operationFamily(args);
49
- const target = String(args.path ?? args.file_path ?? args.filePath ?? '');
53
+ const target = String(args.path ?? args.file_path ?? args.filePath ?? args.target ?? args.endpoint ?? args.url ?? '');
54
+ const workspace = String(args.cwd ?? '');
50
55
  // Changing error text/class does not buy another three attempts at the same
51
56
  // operation. Targets are hashed and never included in recovery messages.
52
- return createHash('sha256').update(`${tool}\0${family}\0${target}`).digest('hex');
57
+ return createHash('sha256').update(`${tool}\0${family}\0${target}\0${workspace}`).digest('hex');
53
58
  }
54
59
  function lastGoodTool(outcomes) {
55
60
  for (let index = outcomes.length - 1; index >= 0; index--) {
56
61
  const outcome = outcomes[index];
57
- if (outcome?.success)
62
+ if (outcome?.success && (outcome.exitCode == null || outcome.exitCode === 0) && !outcome.error?.trim())
58
63
  return outcome.tool;
59
64
  }
60
65
  return null;
@@ -91,7 +96,9 @@ export class TimeMachine {
91
96
  }
92
97
  observe(tool, args, result, outcomes = []) {
93
98
  const value = record(result);
94
- const failed = value.success === false || typeof value.error === 'string';
99
+ const failed = value.success === false || (typeof value.error === 'string' && value.error.trim().length > 0)
100
+ || (typeof value.exitCode === 'number' && (!Number.isFinite(value.exitCode) || value.exitCode !== 0))
101
+ || value.failureKind === 'site_refusal';
95
102
  const classification = failed ? failureClass(value) || 'failed' : '';
96
103
  const key = issueKey(tool, args);
97
104
  const good = lastGoodTool(outcomes);
@@ -117,7 +124,7 @@ export class TimeMachine {
117
124
  }
118
125
  const error = typeof value.error === 'string' ? value.error : '';
119
126
  const needsHuman = classification === 'permission' || /user denied|approval required|authentication required/i.test(error);
120
- const attempt = (this.failures.get(key) || 0) + 1;
127
+ const attempt = Math.min(TIME_MACHINE_MAX_ATTEMPTS, (this.failures.get(key) || 0) + 1);
121
128
  this.failures.set(key, attempt);
122
129
  const checkpoint = good ? ` Last successful tool: ${good}.` : '';
123
130
  if (needsHuman) {
@@ -142,6 +149,11 @@ export class TimeMachine {
142
149
  failureClass: classification, lastGoodTool: good,
143
150
  guidance: `Further attempts were not approved. Stop this task. Give a brief evidence-based report and state what remains unresolved.${checkpoint}` };
144
151
  }
152
+ if (classification === 'rate_limited' && attempt < TIME_MACHINE_CONSENT_AT) {
153
+ return { kind: 'replan', attempt, maxAttempts: TIME_MACHINE_MAX_ATTEMPTS, issueKey: key,
154
+ failureClass: classification, lastGoodTool: good,
155
+ guidance: `Rate limit reached. Respect the provider's retry/reset window; do not immediately resend the same request.${checkpoint}` };
156
+ }
145
157
  if (value.failureKind === 'site_refusal' && attempt < TIME_MACHINE_MAX_ATTEMPTS) {
146
158
  return { kind: 'replan', attempt, maxAttempts: TIME_MACHINE_MAX_ATTEMPTS, issueKey: key,
147
159
  failureClass: classification, lastGoodTool: good,
@@ -43,10 +43,14 @@ function record(value: unknown): Record<string, unknown> {
43
43
 
44
44
  function operationFamily(args: Record<string, unknown>): string {
45
45
  const command = typeof args.command === 'string' ? args.command
46
- : typeof args.cmd === 'string' ? args.cmd : '';
46
+ : typeof args.cmd === 'string' ? args.cmd
47
+ : typeof args.CommandLine === 'string' ? args.CommandLine
48
+ : typeof args.commandLine === 'string' ? args.commandLine
49
+ : typeof args.script === 'string' ? args.script : '';
47
50
  if (!command) {
48
- if (typeof args.url === 'string') {
49
- try { return new URL(args.url).hostname.toLowerCase(); } catch { return ''; }
51
+ const endpoint = typeof args.url === 'string' ? args.url : typeof args.endpoint === 'string' ? args.endpoint : '';
52
+ if (endpoint) {
53
+ try { return new URL(endpoint).hostname.toLowerCase(); } catch { return ''; }
50
54
  }
51
55
  return '';
52
56
  }
@@ -61,16 +65,17 @@ function operationFamily(args: Record<string, unknown>): string {
61
65
 
62
66
  function issueKey(tool: string, args: Record<string, unknown>): string {
63
67
  const family = operationFamily(args);
64
- const target = String(args.path ?? args.file_path ?? args.filePath ?? '');
68
+ const target = String(args.path ?? args.file_path ?? args.filePath ?? args.target ?? args.endpoint ?? args.url ?? '');
69
+ const workspace = String(args.cwd ?? '');
65
70
  // Changing error text/class does not buy another three attempts at the same
66
71
  // operation. Targets are hashed and never included in recovery messages.
67
- return createHash('sha256').update(`${tool}\0${family}\0${target}`).digest('hex');
72
+ return createHash('sha256').update(`${tool}\0${family}\0${target}\0${workspace}`).digest('hex');
68
73
  }
69
74
 
70
75
  function lastGoodTool(outcomes: readonly ToolOutcome[]): string | null {
71
76
  for (let index = outcomes.length - 1; index >= 0; index--) {
72
77
  const outcome = outcomes[index];
73
- if (outcome?.success) return outcome.tool;
78
+ if (outcome?.success && (outcome.exitCode == null || outcome.exitCode === 0) && !outcome.error?.trim()) return outcome.tool;
74
79
  }
75
80
  return null;
76
81
  }
@@ -112,7 +117,9 @@ export class TimeMachine {
112
117
  observe(tool: string, args: Record<string, unknown>, result: unknown,
113
118
  outcomes: readonly ToolOutcome[] = []): RecoveryDecision {
114
119
  const value = record(result);
115
- const failed = value.success === false || typeof value.error === 'string';
120
+ const failed = value.success === false || (typeof value.error === 'string' && value.error.trim().length > 0)
121
+ || (typeof value.exitCode === 'number' && (!Number.isFinite(value.exitCode) || value.exitCode !== 0))
122
+ || value.failureKind === 'site_refusal';
116
123
  const classification = failed ? failureClass(value) || 'failed' : '';
117
124
  const key = issueKey(tool, args);
118
125
  const good = lastGoodTool(outcomes);
@@ -140,7 +147,7 @@ export class TimeMachine {
140
147
 
141
148
  const error = typeof value.error === 'string' ? value.error : '';
142
149
  const needsHuman = classification === 'permission' || /user denied|approval required|authentication required/i.test(error);
143
- const attempt = (this.failures.get(key) || 0) + 1;
150
+ const attempt = Math.min(TIME_MACHINE_MAX_ATTEMPTS, (this.failures.get(key) || 0) + 1);
144
151
  this.failures.set(key, attempt);
145
152
  const checkpoint = good ? ` Last successful tool: ${good}.` : '';
146
153
 
@@ -167,6 +174,11 @@ export class TimeMachine {
167
174
  failureClass: classification, lastGoodTool: good,
168
175
  guidance: `Further attempts were not approved. Stop this task. Give a brief evidence-based report and state what remains unresolved.${checkpoint}` };
169
176
  }
177
+ if (classification === 'rate_limited' && attempt < TIME_MACHINE_CONSENT_AT) {
178
+ return { kind: 'replan', attempt, maxAttempts: TIME_MACHINE_MAX_ATTEMPTS, issueKey: key,
179
+ failureClass: classification, lastGoodTool: good,
180
+ guidance: `Rate limit reached. Respect the provider's retry/reset window; do not immediately resend the same request.${checkpoint}` };
181
+ }
170
182
  if (value.failureKind === 'site_refusal' && attempt < TIME_MACHINE_MAX_ATTEMPTS) {
171
183
  return { kind: 'replan', attempt, maxAttempts: TIME_MACHINE_MAX_ATTEMPTS, issueKey: key,
172
184
  failureClass: classification, lastGoodTool: good,
@@ -1,7 +1,46 @@
1
- import { exec } from 'child_process';
2
- import os from 'os';
1
+ import { execFile } from 'node:child_process';
2
+ import os from 'node:os';
3
3
  import { currentToolAutonomyMode } from '../approvalPolicy.js';
4
4
 
5
+ /**
6
+ * Parse the documented Git subcommand syntax without invoking a shell.
7
+ * Quoted commit messages and filenames are preserved as single arguments.
8
+ */
9
+ export function parseGitArguments(raw) {
10
+ if (typeof raw !== 'string' || !raw.trim()) throw new Error('A Git subcommand is required.');
11
+ const argv = [];
12
+ let token = '';
13
+ let quote = null;
14
+ let started = false;
15
+ for (let i = 0; i < raw.length; i++) {
16
+ const char = raw.charAt(i);
17
+ const next = raw.charAt(i + 1);
18
+ if (char === '\\' && quote !== "'" && next && /[\\\s"'\\]/.test(next)) {
19
+ token += next;
20
+ started = true;
21
+ i++;
22
+ continue;
23
+ }
24
+ if (char === '"' || char === "'") {
25
+ if (!quote) { quote = char; started = true; continue; }
26
+ if (quote === char) { quote = null; continue; }
27
+ }
28
+ if (!quote && /[;&|><`$()\r\n]/.test(char)) {
29
+ throw new Error('Git commands must contain one subcommand, without shell operators or substitution.');
30
+ }
31
+ if (!quote && /\s/.test(char)) {
32
+ if (started) { argv.push(token); token = ''; started = false; }
33
+ continue;
34
+ }
35
+ token += char;
36
+ started = true;
37
+ }
38
+ if (quote) throw new Error('Unterminated quote in Git command.');
39
+ if (started) argv.push(token);
40
+ if (!argv.length) throw new Error('A Git subcommand is required.');
41
+ return argv;
42
+ }
43
+
5
44
  export const gitExec = {
6
45
  schema: {
7
46
  name: 'gitOp',
@@ -16,39 +55,40 @@ export const gitExec = {
16
55
  }
17
56
  },
18
57
  async execute(args) {
19
- const cwd = (args.cwd || process.cwd()).replace(/^~\//, os.homedir() + '/');
20
- let cmdString = args.command;
21
-
22
- // Phase 5 AGI Upgrade: Boundary Conditions
23
- if (cmdString.includes('-i') || cmdString.includes('interactive')) {
24
- return { success: false, error: 'Interactive workflows (e.g., rebase -i) are strictly forbidden in AGI automation. Use precise non-interactive commands.' };
25
- }
26
-
27
- if ((cmdString.includes('push -f') || cmdString.includes('push --force') || cmdString.includes('branch -D'))
28
- && currentToolAutonomyMode() === undefined) {
58
+ const cwd = String(args?.cwd || process.cwd()).replace(/^~\//, os.homedir() + '/');
59
+ let argv;
60
+ try {
61
+ argv = parseGitArguments(args?.command);
62
+ } catch (error) {
63
+ return { success: false, error: error.message };
64
+ }
65
+
66
+ const subcommand = argv[0];
67
+ if (subcommand === 'rebase' && argv.some(arg => arg === '-i' || arg === '--interactive')) {
68
+ return { success: false, error: 'Interactive Git rebase is not supported. Use precise non-interactive commands.' };
69
+ }
70
+ const forcingPush = subcommand === 'push' && argv.slice(1).some(arg => arg === '-f' || arg === '--force' || arg.startsWith('--force-with-lease'));
71
+ const forcingBranch = subcommand === 'branch' && argv.includes('-D');
72
+ if ((forcingPush || forcingBranch) && currentToolAutonomyMode() === undefined) {
29
73
  return { success: false, error: 'Destructive Git action requires the agent session approval and sandbox policy.' };
30
74
  }
31
75
 
32
- const command = `git ${cmdString}`;
33
-
34
- return new Promise((resolve) => {
35
- exec(command, { cwd, maxBuffer: 5 * 1024 * 1024 }, (error, stdout, stderr) => {
76
+ return new Promise(resolve => {
77
+ // Never use a shell here: gitOp is a structured tool, not an arbitrary shell.
78
+ execFile('git', argv, { cwd, maxBuffer: 5 * 1024 * 1024 }, (error, stdout, stderr) => {
36
79
  const fullOutput = (stdout || '') + '\n' + (stderr || '');
37
-
38
- // Phase 5 AGI Upgrade: Autonomous Conflict Detection
39
80
  if (fullOutput.includes('CONFLICT (content): Merge conflict')) {
40
- resolve({
41
- success: false,
42
- error: `[AUTONOMOUS CONFLICT DETECTED]\nGit merge conflict occurred. DO NOT PANIC.\n1. Use fs.read to read the conflicted files.\n2. Analyze the <<<<<<< HEAD markers.\n3. Use fs.edit to surgically resolve the conflict.\n4. Run git add and git commit.`,
43
- output: fullOutput
81
+ resolve({
82
+ success: false,
83
+ error: '[AUTONOMOUS CONFLICT DETECTED] Git merge conflict occurred. Inspect conflicted files, resolve exact markers and verify before continuing.',
84
+ output: fullOutput
44
85
  });
45
86
  return;
46
87
  }
47
-
48
88
  if (error) {
49
89
  resolve({ success: false, output: stdout, error: stderr || error.message, exitCode: error.code });
50
90
  } else {
51
- resolve({ success: true, output: stdout || stderr, exitCode: 0 });
91
+ resolve({ success: true, output: stdout || stderr, exitCode: 0 });
52
92
  }
53
93
  });
54
94
  });
@@ -84,14 +84,18 @@ function renderMarkdown(text, width) {
84
84
  continue;
85
85
  }
86
86
  if (inFence) {
87
- lines.push(paint('accent', ' ' + truncate(line, width - 2, '')));
87
+ for (const codeRow of wrapBlock(' ' + line, Math.max(8, width), { hang: 0 })) {
88
+ lines.push(paint('accent', codeRow));
89
+ }
88
90
  continue;
89
91
  }
90
92
 
91
93
  const heading = line.match(/^(#{1,6})\s+(.*)$/);
92
94
  if (heading) {
93
95
  lines.push('');
94
- lines.push(bold(paint('ink', heading[2])));
96
+ for (const headingRow of wrap(heading[2], Math.max(8, width))) {
97
+ lines.push(bold(paint('ink', headingRow)));
98
+ }
95
99
  continue;
96
100
  }
97
101
 
@@ -138,8 +142,10 @@ function renderMarkdown(text, width) {
138
142
 
139
143
  const tableRow = line.match(/^\s*\|(.+)\|\s*$/);
140
144
  if (tableRow) {
141
- const cells = tableRow[1].split('|').map(c => inline(c.trim()));
142
- lines.push(' ' + cells.join(paint('muted', ' │ ')));
145
+ const cells = tableRow[1].split('|').map(c => c.trim());
146
+ for (const tableLine of wrapBlock(' ' + cells.join(' │ '), Math.max(8, width), { hang: 0 })) {
147
+ lines.push(inline(tableLine));
148
+ }
143
149
  continue;
144
150
  }
145
151
 
@@ -824,9 +830,11 @@ export class ChatRenderer {
824
830
 
825
831
  formatAssistantMessage(content, { streaming = false } = {}) {
826
832
  const width = this.measure();
827
- this.write();
833
+ // The frame already ends with a blank separator. A leading blank row on the
834
+ // first assistant response leaves a visible void in compact chat view.
828
835
  this.write(`${paint('agent', GLYPHS.arrow)} ${bold(paint('agent', 'Causyne'))}${streaming ? ' ' + dim('…') : ''}`);
829
- for (const line of renderMarkdown(content, width - 2)) {
836
+ // Reserve the transcript's three-column inset and final safety cell.
837
+ for (const line of renderMarkdown(content, Math.max(8, width - 4))) {
830
838
  this.write(line ? ' ' + line : '');
831
839
  }
832
840
  this.write();
@@ -3,7 +3,9 @@ import { padEnd, safeDisplay, truncate } from './text.js';
3
3
  // @ts-expect-error theme.js has no TypeScript declaration yet.
4
4
  import { bold, dim, fill, paint } from './theme.js';
5
5
  export const SIDEBAR_WIDTH = 42;
6
- export const SIDEBAR_THRESHOLD = 120;
6
+ // A 42-column sidebar is only useful if the conversation retains a readable width.
7
+ // Narrow IDE terminals should prioritize the user's complete message over metadata.
8
+ export const SIDEBAR_THRESHOLD = 160;
7
9
  /** A side panel is useful only when a readable conversation column remains. */
8
10
  export function sidebarVisible(columns, home = false) {
9
11
  if (typeof process !== 'undefined' && process.env) {
@@ -22,11 +24,11 @@ export function sessionMainWidth(columns, home = false) {
22
24
  export function sessionComposerWidth(columns) {
23
25
  const available = Number.isFinite(columns) ? Math.max(20, Math.floor(columns)) : 80;
24
26
  if (available <= 112) {
25
- return Math.max(20, available - 3);
27
+ return Math.max(20, available - 4);
26
28
  }
27
29
  // Dynamic readable measure scaling on wide terminals:
28
30
  const readableMeasure = Math.round(109 + 20 * Math.log2(available / 112));
29
- return Math.min(available - 3, Math.max(20, readableMeasure));
31
+ return Math.min(available - 4, Math.max(20, readableMeasure));
30
32
  }
31
33
  /** Render only facts the runtime can actually report. */
32
34
  export function sessionSidebarRows(facts, height) {
@@ -4,7 +4,9 @@ import { padEnd, safeDisplay, truncate } from './text.js';
4
4
  import { bold, dim, fill, paint } from './theme.js';
5
5
 
6
6
  export const SIDEBAR_WIDTH = 42;
7
- export const SIDEBAR_THRESHOLD = 120;
7
+ // A 42-column sidebar is only useful if the conversation retains a readable width.
8
+ // Narrow IDE terminals should prioritize the user's complete message over metadata.
9
+ export const SIDEBAR_THRESHOLD = 160;
8
10
 
9
11
  export interface SidebarFacts {
10
12
  title?: string;
@@ -37,11 +39,11 @@ export function sessionMainWidth(columns: number, home = false): number {
37
39
  export function sessionComposerWidth(columns: number): number {
38
40
  const available = Number.isFinite(columns) ? Math.max(20, Math.floor(columns)) : 80;
39
41
  if (available <= 112) {
40
- return Math.max(20, available - 3);
42
+ return Math.max(20, available - 4);
41
43
  }
42
44
  // Dynamic readable measure scaling on wide terminals:
43
45
  const readableMeasure = Math.round(109 + 20 * Math.log2(available / 112));
44
- return Math.min(available - 3, Math.max(20, readableMeasure));
46
+ return Math.min(available - 4, Math.max(20, readableMeasure));
45
47
  }
46
48
 
47
49
  /** Render only facts the runtime can actually report. */
@@ -60,6 +60,44 @@ const RAIL_BUDGET = RAIL_WIDTH + 1;
60
60
  // The interactive turn rail takes three columns at the left of each row.
61
61
  const TURN_RAIL_BUDGET = 3;
62
62
 
63
+ // Count a prefix of terminal control sequences with a deterministic scan.
64
+ // This preserves CSI, OSC (BEL/ST), and two-byte ESC codes without regex
65
+ // backtracking on long or malformed terminal output.
66
+ export function leadingAnsiControlEnd(row) {
67
+ if (typeof row !== 'string') return 0;
68
+ let index = 0;
69
+ while (row.charCodeAt(index) === 27) {
70
+ let cursor = index + 1;
71
+ const kind = row.charCodeAt(cursor);
72
+ if (kind === 91) { // ESC [
73
+ cursor++;
74
+ while (row.charCodeAt(cursor) >= 48 && row.charCodeAt(cursor) <= 63) cursor++;
75
+ while (row.charCodeAt(cursor) >= 32 && row.charCodeAt(cursor) <= 47) cursor++;
76
+ const final = row.charCodeAt(cursor);
77
+ if (final >= 64 && final <= 126) {
78
+ index = cursor + 1;
79
+ continue;
80
+ }
81
+ } else if (kind === 93) { // ESC ] ... BEL or ESC backslash
82
+ cursor++;
83
+ while (cursor < row.length && row.charCodeAt(cursor) !== 7 && row.charCodeAt(cursor) !== 27) cursor++;
84
+ if (row.charCodeAt(cursor) === 7) {
85
+ index = cursor + 1;
86
+ continue;
87
+ }
88
+ if (row.charCodeAt(cursor) === 27 && row.charCodeAt(cursor + 1) === 92) {
89
+ index = cursor + 2;
90
+ continue;
91
+ }
92
+ } else if ((kind >= 64 && kind <= 90) || (kind >= 92 && kind <= 95)) {
93
+ index = cursor + 1;
94
+ continue;
95
+ }
96
+ break;
97
+ }
98
+ return index;
99
+ }
100
+
63
101
  // Which marker wins when several frames fall in the same rail row. A proportional
64
102
  // rail on a long session compresses dozens of frames per row, and what you want
65
103
  // to see at a glance is the thing that went wrong or the thing you can roll back
@@ -478,6 +516,16 @@ export class StageSurface {
478
516
  if (budget > 0) {
479
517
  this.viewport.resize({ height: budget, width: contentWidth });
480
518
  rows = alignTranscriptRows(this.viewport.rows(), contentRows);
519
+ // In follow mode, the viewport can land on the blank separator between
520
+ // two assistant frames after enough replies to fill the band. Show a
521
+ // subtle boundary marker in that same row instead of a visible void.
522
+ // Do not shift row indices: rails, hover targets and reading anchors
523
+ // are keyed to the original transcript row positions.
524
+ if (this.viewport.following && this.viewport.maxScrollTop() > 0
525
+ && rows.length > 0 && stripAnsi(rows[0] || '').trim() === ''
526
+ && rows.some(row => stripAnsi(row).trim() !== '')) {
527
+ rows[0] = paint('rule', ` ${GLYPHS.dot} `);
528
+ }
481
529
  this.decorate(rows, contentWidth);
482
530
  markHoveredMessage(rows, this, contentWidth);
483
531
  if (rail) this.attachRail(rows, contentWidth);
@@ -728,10 +776,10 @@ export class StageSurface {
728
776
  let row = rows[i] || '';
729
777
  if (hasTurns && railResult) {
730
778
  const leftCell = railResult.cells[i] || ' ';
731
- const leadMatch = row.match(/^((?:\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[@-Z\\-_])*)[ ]{3}/);
732
- if (leadMatch) {
733
- const leadEscapes = leadMatch[1] || '';
734
- row = `${leadEscapes} ${leftCell} ${row.slice(leadMatch[0].length)}`;
779
+ const leadEnd = leadingAnsiControlEnd(row);
780
+ if (row.slice(leadEnd, leadEnd + 3) === ' ') {
781
+ const leadEscapes = row.slice(0, leadEnd);
782
+ row = `${leadEscapes} ${leftCell} ${row.slice(leadEnd + 3)}`;
735
783
  } else if (stripAnsi(row).length === 0) {
736
784
  row = leftCell !== ' ' ? ` ${leftCell} ` : '';
737
785
  } else {