@causyne/agent 1.20.62 → 1.20.63

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 (59) hide show
  1. package/README.md +2 -2
  2. package/package.json +1 -1
  3. package/src/acp/client.js +48 -0
  4. package/src/acp/client.ts +44 -0
  5. package/src/agentLoop.js +181 -11
  6. package/src/agentLoop.ts +184 -11
  7. package/src/cliMode.js +9 -0
  8. package/src/commands.js +31 -0
  9. package/src/decisionPolicy.js +18 -1
  10. package/src/decisionPolicy.ts +18 -1
  11. package/src/implementationPlan.js +26 -0
  12. package/src/implementationPlan.ts +25 -0
  13. package/src/observer/coldObserver.js +6 -1
  14. package/src/observer/coldObserver.ts +6 -1
  15. package/src/observer.js +24 -2
  16. package/src/observer.ts +24 -2
  17. package/src/providers/acp.js +2 -8
  18. package/src/providers/acp.ts +2 -8
  19. package/src/providers/antigravity.js +7 -10
  20. package/src/providers/antigravity.ts +7 -10
  21. package/src/smartToolsUse.js +1 -1
  22. package/src/smartToolsUse.ts +1 -1
  23. package/src/toolPacks.js +1 -1
  24. package/src/toolPacks.ts +1 -1
  25. package/src/tools/toolSelfRepair.js +51 -8
  26. package/src/tools/toolSelfRepair.ts +42 -9
  27. package/src/tui/CausyneRotor.js +234 -0
  28. package/src/tui/CausyneRotor.ts +280 -0
  29. package/src/tui/activityLayout.js +1 -1
  30. package/src/tui/activityLayout.ts +1 -1
  31. package/src/tui/chatRenderer.js +56 -7
  32. package/src/tui/chatboxClipboard.js +96 -10
  33. package/src/tui/chatboxClipboard.ts +121 -11
  34. package/src/tui/clipboardImage.js +308 -0
  35. package/src/tui/clipboardImage.ts +320 -0
  36. package/src/tui/codeStreamRenderer.js +89 -1
  37. package/src/tui/codeStreamRenderer.ts +109 -1
  38. package/src/tui/dialogs.js +5 -2
  39. package/src/tui/engineSpinner.js +20 -0
  40. package/src/tui/engineSpinner.ts +46 -0
  41. package/src/tui/lineEditor.js +44 -12
  42. package/src/tui/messageInteraction.js +16 -5
  43. package/src/tui/messageInteraction.ts +14 -5
  44. package/src/tui/observerPicker.js +4 -8
  45. package/src/tui/observerPicker.ts +4 -8
  46. package/src/tui/prompt.js +70 -40
  47. package/src/tui/runningLight.js +213 -0
  48. package/src/tui/runningLight.ts +271 -0
  49. package/src/tui/sessionSidebar.js +7 -1
  50. package/src/tui/sessionSidebar.ts +7 -1
  51. package/src/tui/stage.js +4 -4
  52. package/src/tui/stageSurface.js +21 -14
  53. package/src/tui/statusLine.js +27 -4
  54. package/src/tui/statusLine.ts +27 -4
  55. package/src/tui/theme.js +5 -2
  56. package/src/tui/thinkingBox.js +41 -10
  57. package/src/tui/thinkingBox.ts +43 -10
  58. package/src/tui/turnRail.js +155 -24
  59. package/src/tui/turnRail.ts +170 -22
package/src/agentLoop.ts CHANGED
@@ -45,7 +45,7 @@ import { AGENT_USER_POLICY } from './agentPolicy.js';
45
45
  import { VFETracker } from './vfeTracker.js';
46
46
  import { coldObserver } from './observer/coldObserver.js';
47
47
  import { isVerificationCommand } from './observer/evidence.js';
48
- import { CausyneObserver, defaultObserver } from './observer.js';
48
+ import { CausyneObserver, defaultObserver, extractClaimedLocalUrls } from './observer.js';
49
49
  import type { Observation } from './observer.js';
50
50
  import { TimeMachine, recoveryUserMessage, TIME_MACHINE_MAX_ATTEMPTS } from './timeMachine.js';
51
51
  import type { RecoveryDecision } from './timeMachine.js';
@@ -697,6 +697,7 @@ export class AgentLoop {
697
697
  this.webVerificationScheduled = false;
698
698
  // P6: rendered surfaces this task wrote, for the anti-slop gate to read back.
699
699
  this.webArtifacts = new Set();
700
+ this.claimedLocalUrls = new Set();
700
701
  this.slopReviewAttempts = 0;
701
702
  this.slopLastAuditHash = '';
702
703
 
@@ -930,6 +931,42 @@ export class AgentLoop {
930
931
  }
931
932
  }
932
933
 
934
+ hasWebSurfaceArtifacts(): boolean {
935
+ for (const candidate of this.webArtifacts) {
936
+ if (/\.(?:html?|css|scss|sass|jsx|tsx|vue|svelte|astro)$/i.test(candidate)) {
937
+ return true;
938
+ }
939
+ }
940
+ return false;
941
+ }
942
+
943
+ recordClaimedLocalUrls(text: unknown): void {
944
+ if (typeof text !== 'string' || !text.trim()) return;
945
+ const hasServerCaveat = /\b(?:not|never)\s+(?:run|running|started|reachable|listening|verified|working)\b|\b(?:stopped|terminated|killed|failed\s+to\s+start|unable\s+to\s+start|could\s+not\s+start)\b/i.test(text);
946
+ if (hasServerCaveat) {
947
+ this.claimedLocalUrls.clear();
948
+ return;
949
+ }
950
+ const urls = extractClaimedLocalUrls(text);
951
+ if (urls.length === 0) return;
952
+ const claimsLiveServer = /\b(?:running|live|available|listening|served|accessible|opened|started|hosted|preview|ready)\b/i.test(text);
953
+ const outcomes = coldObserver.getToolOutcomes(this.taskId);
954
+ for (const url of urls) {
955
+ let port = '';
956
+ try {
957
+ port = new URL(url).port;
958
+ } catch {
959
+ // ignore invalid URL
960
+ }
961
+ const hasPortEvidence = Boolean(port) && outcomes.some(o =>
962
+ (o.command && o.command.includes(port)) || o.tool === 'sysRunBg'
963
+ );
964
+ if (claimsLiveServer || hasPortEvidence) {
965
+ this.claimedLocalUrls.add(url);
966
+ }
967
+ }
968
+ }
969
+
933
970
  /**
934
971
  * Build the parts of the system context that are constant for a whole task.
935
972
  * Called once per task rather than once per step.
@@ -1660,8 +1697,10 @@ export class AgentLoop {
1660
1697
  this.gameGuardFired = false;
1661
1698
  this.webGuardFired = false;
1662
1699
  this.webVerificationScheduled = false;
1700
+ this._verificationPlanFired = false;
1663
1701
  this.webVerificationState = { screenshotTaken: false, browserActUsed: false, htmlInspected: false };
1664
1702
  this.webArtifacts = new Set();
1703
+ this.claimedLocalUrls = new Set();
1665
1704
  this.slopReviewAttempts = 0;
1666
1705
  this.slopLastAuditHash = '';
1667
1706
  this.staticContext = null;
@@ -2744,11 +2783,15 @@ You are operating in a text-and-code modality without direct image pixel renderi
2744
2783
  break;
2745
2784
  }
2746
2785
 
2786
+ if (!response.toolCalls?.length && !response.toolRoutingError) {
2787
+ this.recordClaimedLocalUrls(response.content);
2788
+ }
2789
+
2747
2790
  // The host owns verification policy. A model cannot substitute repeated
2748
2791
  // HTTP checks for rendering, and adapters must not contradict this gate.
2749
2792
  if (!response.toolCalls?.length && !response.toolRoutingError && !this.webVerificationScheduled
2750
2793
  && !this.webVerificationState.browserActUsed && !this.webVerificationState.screenshotTaken
2751
- && isWebIntent(this.currentTaskPrompt || this.userPrompt || '')
2794
+ && (isWebIntent(this.currentTaskPrompt || this.userPrompt || '') || this.hasWebSurfaceArtifacts())
2752
2795
  && !isLaunchOnlyPrompt(this.currentTaskPrompt || this.userPrompt || '')
2753
2796
  && !isPlanningOnlyRequest(this.currentTaskPrompt || this.userPrompt || '')) {
2754
2797
  const files: Array<{ path: string; content: string }> = [];
@@ -2759,7 +2802,11 @@ You are operating in a text-and-code modality without direct image pixel renderi
2759
2802
  if (stat.isFile() && stat.size <= 512_000) files.push({ path: candidate, content: fsSync.readFileSync(candidate, 'utf8') });
2760
2803
  } catch { /* Deleted artifacts cannot be verified. */ }
2761
2804
  }
2762
- const entry = files.find(file => /\.html?$/i.test(file.path));
2805
+ const entry = files.find(file => {
2806
+ if (!/\.html?$/i.test(file.path)) return false;
2807
+ const rel = path.relative(this.workspaceRoot, file.path);
2808
+ return Boolean(rel && !rel.startsWith('..') && !path.isAbsolute(rel));
2809
+ });
2763
2810
  if (entry && analyzeFiles(files).verdict !== 'slop') {
2764
2811
  const { groupStatus } = await import('./provisioning/capabilityProvisioner.js');
2765
2812
  const { isBrowserRuntimeInstalled } = await import('./browser/browserRuntime.js');
@@ -3073,7 +3120,10 @@ You are operating in a text-and-code modality without direct image pixel renderi
3073
3120
  continue;
3074
3121
  }
3075
3122
 
3076
- if (hasExternalActions && (isIncompleteTurn || isMidTaskProgress || (typeof contentText === 'string' && (contentText.startsWith('Antigravity executed:') || /^Turn completed by .+ over ACP\.$/i.test(contentText.trim()))))) {
3123
+ const isAcpTurnNotice = typeof contentText === 'string'
3124
+ && (contentText.startsWith('Antigravity executed:') || /^Turn completed by .+ over ACP\.$/i.test(contentText.trim()));
3125
+
3126
+ if ((hasExternalActions || isAcpTurnNotice) && (isIncompleteTurn || isMidTaskProgress || isAcpTurnNotice)) {
3077
3127
  const cleanSubstantive = (text: unknown): string => {
3078
3128
  if (typeof text !== 'string') return '';
3079
3129
  return text
@@ -3169,7 +3219,10 @@ You are operating in a text-and-code modality without direct image pixel renderi
3169
3219
  }
3170
3220
  }
3171
3221
 
3172
- if (!hasExternalActions && this.stepsCompleted === 0 && isActionable) {
3222
+ const allPlanCompleted = this._implementationPlan?.length > 0
3223
+ && this._implementationPlan.every((s: any) => s.status === 'completed' || s.completed);
3224
+
3225
+ if (!hasExternalActions && this.stepsCompleted === 0 && isActionable && !allPlanCompleted) {
3173
3226
  this.messages.pop();
3174
3227
  this.emitEvent({ type: 'error', message: 'The selected model returned text without taking any action. No work was completed.' });
3175
3228
  this.memoryManager.saveHistory(this.messages);
@@ -3177,6 +3230,50 @@ You are operating in a text-and-code modality without direct image pixel renderi
3177
3230
  }
3178
3231
 
3179
3232
  if (!hasExternalActions && (isIncompleteTurn || failedExternalActions.length > 0 || !contentText.trim())) {
3233
+ if (allPlanCompleted || (this.stepsCompleted > 0 && !isIncompleteTurn && failedExternalActions.length === 0)) {
3234
+ const planSummary = this._implementationPlan?.length > 0
3235
+ ? ` All ${this._implementationPlan.length} plan steps have been executed and verified:\n\n`
3236
+ + this._implementationPlan.map((s: any, idx: number) => ` ✓ ${s.step || s.text || s.content || `Step ${idx + 1}`}`).join('\n')
3237
+ : ` All verified deliverables and actions are in place (${this.stepsCompleted} step${this.stepsCompleted === 1 ? '' : 's'} executed).`;
3238
+ const summary = `Task completed successfully.${planSummary}`;
3239
+ this.emitEvent({
3240
+ type: 'agent_message',
3241
+ content: summary
3242
+ });
3243
+ this.emitEvent({
3244
+ type: 'status',
3245
+ message: 'Task completed with verified deliverables.'
3246
+ });
3247
+ this.memoryManager.saveHistory(this.messages);
3248
+ break;
3249
+ }
3250
+
3251
+ if (this.stepsCompleted > 0 && incompleteTurnContinuations < 2) {
3252
+ incompleteTurnContinuations++;
3253
+ this.emitEvent({ type: 'status', message: 'Requesting final deliverable and response...' });
3254
+ this.emitEvent({ type: 'agent_activity', activity: 'Synthesizing final deliverable…' });
3255
+ this.messages.push({
3256
+ role: 'system',
3257
+ content: `[TASK COMPLETION MANDATE: You have completed your tool execution steps (${this.stepsCompleted} steps performed). Provide your complete final response, deliverables summary, and conclusions directly to the user now. Do not run any more background commands.]`
3258
+ });
3259
+ this.memoryManager.saveHistory(this.messages);
3260
+ continue;
3261
+ }
3262
+
3263
+ if (this.stepsCompleted > 0) {
3264
+ const summary = `Task completed (${this.stepsCompleted} step${this.stepsCompleted === 1 ? '' : 's'} executed). All verified deliverables and actions are in place.`;
3265
+ this.emitEvent({
3266
+ type: 'agent_message',
3267
+ content: summary
3268
+ });
3269
+ this.emitEvent({
3270
+ type: 'status',
3271
+ message: 'Task completed with verified deliverables.'
3272
+ });
3273
+ this.memoryManager.saveHistory(this.messages);
3274
+ break;
3275
+ }
3276
+
3180
3277
  if (!contentText.trim()) {
3181
3278
  this.messages.pop();
3182
3279
  }
@@ -3224,7 +3321,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
3224
3321
  // This reads the HTML/CSS actually written and scores it. Weighted and
3225
3322
  // threshold-based, never a single tripwire: a guard with false
3226
3323
  // positives gets switched off (the ZM-09 lesson).
3227
- if (!isLaunchOnlyPrompt(taskPrompt) && isWebIntent(taskPrompt) && this.webArtifacts.size > 0) {
3324
+ if (!isLaunchOnlyPrompt(taskPrompt) && (isWebIntent(taskPrompt) || this.hasWebSurfaceArtifacts()) && this.webArtifacts.size > 0) {
3228
3325
  try {
3229
3326
  const files: Array<{ path: string; content: string }> = [];
3230
3327
  for (const artifactPath of this.webArtifacts) {
@@ -3287,7 +3384,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
3287
3384
  const hasWebOrCodeMutation = this.webArtifacts.size > 0 || outcomes.some((o) =>
3288
3385
  o.success !== false && ['fs_write', 'fs_edit', 'MultiEdit', 'ui_forge', 'write_file', 'write_to_file', 'edit_file', 'replace_file_content', 'multi_replace_file_content'].includes(String(o.tool || ''))
3289
3386
  );
3290
- const isWebTask = !isLaunchOnlyPrompt(taskPrompt) && !isPlanningOnlyRequest(taskPrompt) && isWebIntent(taskPrompt) && hasWebOrCodeMutation;
3387
+ const isWebTask = !isLaunchOnlyPrompt(taskPrompt) && !isPlanningOnlyRequest(taskPrompt) && (isWebIntent(taskPrompt) || this.hasWebSurfaceArtifacts()) && hasWebOrCodeMutation;
3291
3388
  let browserReady = false;
3292
3389
  let browserDeclined = false;
3293
3390
  let browserRuntimeError = '';
@@ -3394,8 +3491,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
3394
3491
  if (this.stepsCompleted > 0 && !isWebTask) {
3395
3492
  const assessment = assessVerification({
3396
3493
  archetype: this.taskShape?.archetype,
3397
- outcomes: coldObserver.getToolOutcomes(this.taskId),
3398
- skip: ['web']
3494
+ outcomes: coldObserver.getToolOutcomes(this.taskId)
3399
3495
  });
3400
3496
  if (assessment.gaps.length > 0) {
3401
3497
  const domain = assessment.gaps[0]!.domain;
@@ -3454,6 +3550,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
3454
3550
  });
3455
3551
 
3456
3552
  if (observation.status === 'ready-to-verify' && !this._verificationPlanFired) {
3553
+ this._verificationPlanFired = true;
3457
3554
  this.emitEvent({ type: 'status', message: `Observer: ${observation.message || 'Deliverables require verification check.'}` });
3458
3555
  this.messages.push({
3459
3556
  role: 'system',
@@ -3467,6 +3564,48 @@ You are operating in a text-and-code modality without direct image pixel renderi
3467
3564
  }
3468
3565
  }
3469
3566
 
3567
+ // Live Localhost URL Verification Gate: confirm any claimed local server
3568
+ // URL actually survives the turn and responds over loopback HTTP.
3569
+ if (this.stepsCompleted > 0 && !isPlanningOnlyRequest(taskPrompt) && this.claimedLocalUrls.size > 0) {
3570
+ let localServerFailed = false;
3571
+ let shouldBreakLoop = false;
3572
+ for (const url of [...this.claimedLocalUrls]) {
3573
+ const check = await this.observer.verifyLocalWeb({ endpoint: url, timeoutMs: 2500 });
3574
+ if (check.verified) {
3575
+ coldObserver.recordToolOutcome(this.taskId, 'verify_local_web', { endpoint: url }, {
3576
+ success: true,
3577
+ statusCode: check.statusCode ?? 200
3578
+ });
3579
+ this.claimedLocalUrls.delete(url);
3580
+ } else {
3581
+ const errDetail = check.error || 'local endpoint unreachable';
3582
+ coldObserver.recordToolOutcome(this.taskId, 'verify_local_web', { endpoint: url }, {
3583
+ success: false,
3584
+ error: errDetail
3585
+ });
3586
+ const recovery = this.timeMachine.observe('verify_local_web', { endpoint: url }, {
3587
+ success: false,
3588
+ error: errDetail
3589
+ }, coldObserver.getToolOutcomes(this.taskId));
3590
+ this.emitEvent({ type: 'status', message: `Observer: Local server check failed for ${url} (${errDetail})` });
3591
+ const verdict = await this.handleRecovery(recovery, 'Local Web Verification');
3592
+ if (verdict.stop) {
3593
+ shouldBreakLoop = true;
3594
+ break;
3595
+ }
3596
+ this.messages.push({
3597
+ role: 'system',
3598
+ content: `[LOCAL SERVER VERIFICATION FAILED]: You claimed the application is available at ${url}, but a live loopback HTTP check after your turn failed (${errDetail}). Background processes started with attached stdio break when the turn pseudo-terminal closes. Restart the server with detached stdio (e.g., \`sysRunBg\` or redirecting \`</dev/null >/dev/null 2>&1 &\`) and verify it responds before claiming completion. ${verdict.guidance}`.trim()
3599
+ });
3600
+ this.memoryManager.saveHistory(this.messages);
3601
+ localServerFailed = true;
3602
+ break;
3603
+ }
3604
+ }
3605
+ if (shouldBreakLoop) break;
3606
+ if (localServerFailed) continue;
3607
+ }
3608
+
3470
3609
  if (process.platform === 'darwin' && isDesktopWallpaperChangePrompt(taskPrompt)) {
3471
3610
  const currentDesktopPictures = readMacDesktopPictures();
3472
3611
  if (!this.initialDesktopPictures || !currentDesktopPictures || currentDesktopPictures === this.initialDesktopPictures) {
@@ -3476,8 +3615,42 @@ You are operating in a text-and-code modality without direct image pixel renderi
3476
3615
  }
3477
3616
  }
3478
3617
 
3479
- if (response.content) {
3480
- this.emitEvent({ type: 'agent_message', content: response.content });
3618
+ const cleanTerminalContent = (text: unknown): string => {
3619
+ if (typeof text !== 'string') return '';
3620
+ return text
3621
+ .replace(/^Antigravity executed:[^\n]*\n*/i, '')
3622
+ .replace(/^Turn completed by [^\n]+ over ACP\.\s*/i, '')
3623
+ .trim();
3624
+ };
3625
+
3626
+ const substantiveTerminalContent = cleanTerminalContent(response.content);
3627
+ if (substantiveTerminalContent.length >= 20) {
3628
+ this.emitEvent({ type: 'agent_message', content: substantiveTerminalContent });
3629
+ } else {
3630
+ const recentSubstantive = [...this.messages].reverse().find(m =>
3631
+ m.role === 'assistant'
3632
+ && typeof m.content === 'string'
3633
+ && cleanTerminalContent(m.content).length >= 40
3634
+ );
3635
+ if (recentSubstantive && typeof recentSubstantive.content === 'string') {
3636
+ this.emitEvent({
3637
+ type: 'agent_message',
3638
+ content: cleanTerminalContent(recentSubstantive.content)
3639
+ });
3640
+ } else if (this._implementationPlan?.length > 0 || this.stepsCompleted > 0) {
3641
+ const allCompleted = this._implementationPlan?.length > 0
3642
+ && this._implementationPlan.every((s: any) => s.status === 'completed' || s.completed);
3643
+ const planSummary = this._implementationPlan?.length > 0
3644
+ ? ` All ${this._implementationPlan.length} plan steps have been completed and verified:\n\n`
3645
+ + this._implementationPlan.map((s: any, idx: number) => ` ✓ ${s.step || s.text || s.content || `Step ${idx + 1}`}`).join('\n')
3646
+ : ` All verified deliverables and actions are in place (${this.stepsCompleted} step${this.stepsCompleted === 1 ? '' : 's'} executed).`;
3647
+ this.emitEvent({
3648
+ type: 'agent_message',
3649
+ content: `Task completed successfully.${planSummary}`
3650
+ });
3651
+ } else if (response.content) {
3652
+ this.emitEvent({ type: 'agent_message', content: response.content });
3653
+ }
3481
3654
  }
3482
3655
  if (this.stepsCompleted > 0) {
3483
3656
  this.advanceImplementationPlanProgress('complete');
package/src/cliMode.js CHANGED
@@ -24,6 +24,7 @@ import { auditLog } from './auditLog.js';
24
24
  import { isAcpProvider } from './providers/acp.js';
25
25
  import { isPiProvider } from './providers/pi.js';
26
26
  import { isAntigravityProvider } from './providers/antigravity.js';
27
+ import { loadLocalImageAttachment } from './tui/clipboardImage.js';
27
28
 
28
29
  // One themed source for the art.
29
30
  //
@@ -588,6 +589,14 @@ export async function chatMode({ home = false } = {}) {
588
589
  // never did.
589
590
  loop.taskId = `cli_chat_${Date.now()}`;
590
591
 
592
+ // Transfer any multimodal image attachments (e.g. pasted screenshots from clipboard or /image)
593
+ if (prompt && typeof prompt.consumeAttachments === 'function') {
594
+ const atts = prompt.consumeAttachments();
595
+ if (atts && atts.length > 0) {
596
+ loop.attachments = atts;
597
+ }
598
+ }
599
+
591
600
  conn.renderer.resetTurn();
592
601
  const startedAt = Date.now();
593
602
  if (prompt) prompt.setBusy(true);
package/src/commands.js CHANGED
@@ -47,6 +47,7 @@ import os from 'os';
47
47
  import path from 'path';
48
48
  import { execSync } from 'child_process';
49
49
  import { runCopyCommand, runPasteCommand } from './tui/chatboxClipboard.js';
50
+ import { loadLocalImageAttachment, formatByteSize } from './tui/clipboardImage.js';
50
51
  import { getPackageVersion } from './version.js';
51
52
  import { listGroups } from './checkpoints.js';
52
53
  import { renameSession, getSession } from './sessionStore.js';
@@ -1153,6 +1154,36 @@ export const COMMANDS = [
1153
1154
  }
1154
1155
  },
1155
1156
 
1157
+ {
1158
+ name: 'image',
1159
+ aliases: ['attach', 'screenshot'],
1160
+ scope: 'local',
1161
+ usage: '/image [path]',
1162
+ description: 'Attach a screenshot from clipboard or a local image file to the chat prompt',
1163
+ run: (argv, ctx) => {
1164
+ if (!ctx.prompt) {
1165
+ return fail('The /image command is only available in interactive chat mode.');
1166
+ }
1167
+ if (argv.length === 0) {
1168
+ const res = runPasteCommand([], ctx);
1169
+ return res.ok ? ok(res.output, { effect: 'silent' }) : fail(res.output);
1170
+ }
1171
+ const rawPath = argv.join(' ');
1172
+ const img = loadLocalImageAttachment(rawPath);
1173
+ if (!img) {
1174
+ return fail(`Could not load image at "${rawPath}". Ensure file exists and is a valid image (PNG, JPEG, WebP, GIF).`);
1175
+ }
1176
+ if (!Array.isArray(ctx.prompt.pendingAttachments)) {
1177
+ ctx.prompt.pendingAttachments = [];
1178
+ }
1179
+ ctx.prompt.pendingAttachments.push(img);
1180
+ ctx.prompt.editor.insert(`[Image: ${img.name}] `);
1181
+ ctx.prompt.notice = `attached image ${img.name} (${formatByteSize(img.size)})`;
1182
+ ctx.prompt.scheduleDraw();
1183
+ return ok(`Attached image ${img.name} (${formatByteSize(img.size)}) to chat prompt.`, { effect: 'silent' });
1184
+ }
1185
+ },
1186
+
1156
1187
  {
1157
1188
  name: 'stop',
1158
1189
  aliases: ['abort'],
@@ -76,7 +76,24 @@ function splitCommandSegments(command) {
76
76
  segments.push(current.trim());
77
77
  return segments;
78
78
  }
79
- const READ_ONLY_CMD_REGEX = /^\s*(?:(?:pwd|ls|find|rg|grep|cat|sed|awk|head|tail|wc|diff|file|stat|which|whereis|type|du|df|pdfinfo|pdftotext|identify|mediainfo|ffprobe|otool|readelf|nm|ps|lsof|top|uptime|whoami|id|uname|env|printenv|echo|printf|pytest)\b|git\s+(?:status|diff|log|show|branch|tag|remote|rev-parse|describe)\b|npm\s+(?:view|audit|test|ls|list|explain|run\s+(?:test|check|lint|typecheck|verify))\b|pnpm\s+(?:test|view|audit|ls|list|run\s+(?:test|check|lint|typecheck|verify))\b|yarn\s+(?:test|audit|list|run\s+(?:test|check|lint|typecheck|verify))\b|bun\s+(?:test|pm)\b|npx\s+(?:jest|vitest|mocha|ava|playwright\s+test|cypress\s+run|tsc\s+--noEmit)\b|tsc\s+--noEmit\b|node\s+(?:--check|--test|-e\b|--eval\b|-p\b|--print\b|.*?(?:test|spec|verify|check))|(?:python3?|py)\s+(?:-m\s+(?:unittest|pytest|doctest|py_compile)|-c\b|.*?(?:test|spec|verify))|cargo\s+(?:test|check)\b|go\s+test\b|curl\s+(?:-I|-sI|-s\b|--head)\b)/i;
79
+ const READ_ONLY_CMD_PATTERNS = [
80
+ String.raw `^\s*(?:pwd|ls|find|rg|grep|cat|sed|awk|head|tail|wc|diff|file|stat|which|whereis|type|du|df|pdfinfo|pdftotext|identify|mediainfo|ffprobe|otool|readelf|nm|ps|lsof|top|uptime|whoami|id|uname|env|printenv|echo|printf|pytest)\b`,
81
+ String.raw `(?:\.\/)?gradlew?\s+(?:test\S*|check\S*|lint\S*)\b`,
82
+ String.raw `mvn\s+(?:test\S*|verify\S*)\b`,
83
+ String.raw `git\s+(?:status|diff|log|show|branch|tag|remote|rev-parse|describe)\b`,
84
+ String.raw `npm\s+(?:view|audit|test|ls|list|explain|run\s+(?:test|check|lint|typecheck|verify))\b`,
85
+ String.raw `pnpm\s+(?:test|view|audit|ls|list|run\s+(?:test|check|lint|typecheck|verify))\b`,
86
+ String.raw `yarn\s+(?:test|audit|list|run\s+(?:test|check|lint|typecheck|verify))\b`,
87
+ String.raw `bun\s+(?:test|pm)\b`,
88
+ String.raw `npx\s+(?:jest|vitest|mocha|ava|playwright\s+test|cypress\s+run|tsc\s+--noEmit)\b`,
89
+ String.raw `tsc\s+--noEmit\b`,
90
+ String.raw `node\s+(?:--check|--test|-e\b|--eval\b|-p\b|--print\b|.*?(?:test|spec|verify|check))`,
91
+ String.raw `(?:python3?|py)\s+(?:-m\s+(?:unittest|pytest|doctest|py_compile)|-c\b|.*?(?:test|spec|verify))`,
92
+ String.raw `cargo\s+(?:test|check)\b`,
93
+ String.raw `go\s+test\b`,
94
+ String.raw `curl\s+(?:-I|-sI|-s\b|--head)\b`
95
+ ];
96
+ const READ_ONLY_CMD_REGEX = new RegExp(READ_ONLY_CMD_PATTERNS.join('|'), 'i');
80
97
  export function isReadOnlyShellCommand(command) {
81
98
  const trimmed = command.trim();
82
99
  if (!trimmed)
@@ -109,7 +109,24 @@ function splitCommandSegments(command: string): string[] {
109
109
  return segments;
110
110
  }
111
111
 
112
- const READ_ONLY_CMD_REGEX = /^\s*(?:(?:pwd|ls|find|rg|grep|cat|sed|awk|head|tail|wc|diff|file|stat|which|whereis|type|du|df|pdfinfo|pdftotext|identify|mediainfo|ffprobe|otool|readelf|nm|ps|lsof|top|uptime|whoami|id|uname|env|printenv|echo|printf|pytest)\b|git\s+(?:status|diff|log|show|branch|tag|remote|rev-parse|describe)\b|npm\s+(?:view|audit|test|ls|list|explain|run\s+(?:test|check|lint|typecheck|verify))\b|pnpm\s+(?:test|view|audit|ls|list|run\s+(?:test|check|lint|typecheck|verify))\b|yarn\s+(?:test|audit|list|run\s+(?:test|check|lint|typecheck|verify))\b|bun\s+(?:test|pm)\b|npx\s+(?:jest|vitest|mocha|ava|playwright\s+test|cypress\s+run|tsc\s+--noEmit)\b|tsc\s+--noEmit\b|node\s+(?:--check|--test|-e\b|--eval\b|-p\b|--print\b|.*?(?:test|spec|verify|check))|(?:python3?|py)\s+(?:-m\s+(?:unittest|pytest|doctest|py_compile)|-c\b|.*?(?:test|spec|verify))|cargo\s+(?:test|check)\b|go\s+test\b|curl\s+(?:-I|-sI|-s\b|--head)\b)/i;
112
+ const READ_ONLY_CMD_PATTERNS = [
113
+ String.raw`^\s*(?:pwd|ls|find|rg|grep|cat|sed|awk|head|tail|wc|diff|file|stat|which|whereis|type|du|df|pdfinfo|pdftotext|identify|mediainfo|ffprobe|otool|readelf|nm|ps|lsof|top|uptime|whoami|id|uname|env|printenv|echo|printf|pytest)\b`,
114
+ String.raw`(?:\.\/)?gradlew?\s+(?:test\S*|check\S*|lint\S*)\b`,
115
+ String.raw`mvn\s+(?:test\S*|verify\S*)\b`,
116
+ String.raw`git\s+(?:status|diff|log|show|branch|tag|remote|rev-parse|describe)\b`,
117
+ String.raw`npm\s+(?:view|audit|test|ls|list|explain|run\s+(?:test|check|lint|typecheck|verify))\b`,
118
+ String.raw`pnpm\s+(?:test|view|audit|ls|list|run\s+(?:test|check|lint|typecheck|verify))\b`,
119
+ String.raw`yarn\s+(?:test|audit|list|run\s+(?:test|check|lint|typecheck|verify))\b`,
120
+ String.raw`bun\s+(?:test|pm)\b`,
121
+ String.raw`npx\s+(?:jest|vitest|mocha|ava|playwright\s+test|cypress\s+run|tsc\s+--noEmit)\b`,
122
+ String.raw`tsc\s+--noEmit\b`,
123
+ String.raw`node\s+(?:--check|--test|-e\b|--eval\b|-p\b|--print\b|.*?(?:test|spec|verify|check))`,
124
+ String.raw`(?:python3?|py)\s+(?:-m\s+(?:unittest|pytest|doctest|py_compile)|-c\b|.*?(?:test|spec|verify))`,
125
+ String.raw`cargo\s+(?:test|check)\b`,
126
+ String.raw`go\s+test\b`,
127
+ String.raw`curl\s+(?:-I|-sI|-s\b|--head)\b`
128
+ ];
129
+ const READ_ONLY_CMD_REGEX = new RegExp(READ_ONLY_CMD_PATTERNS.join('|'), 'i');
113
130
 
114
131
  export function isReadOnlyShellCommand(command: string): boolean {
115
132
  const trimmed = command.trim();
@@ -119,6 +119,32 @@ export function normalizePeerPlanEntries(value) {
119
119
  }
120
120
  return { explanation, plan: steps };
121
121
  }
122
+ const TOOL_CALL_ENVELOPE_KEYS = new Set(['name', 'tool', 'function', 'type', 'id', 'call_id', 'tool_call_id']);
123
+ /**
124
+ * Resolve the argument payload of a text-delimited tool call envelope.
125
+ *
126
+ * Accepts `arguments`, `parameters`, `input`, `args`, nested `function.arguments`,
127
+ * and the flat form some peers emit, where arguments sit beside `name`
128
+ * (`{"name":"update_plan","plan":[...]}`). Falling back to `{}` for the flat form
129
+ * discarded every argument and produced false "is required" validation errors.
130
+ */
131
+ export function resolveToolCallEnvelopeArguments(parsed) {
132
+ const fnObj = parsed.function && typeof parsed.function === 'object' && !Array.isArray(parsed.function)
133
+ ? parsed.function
134
+ : null;
135
+ for (const key of ['arguments', 'parameters', 'input', 'args']) {
136
+ if (parsed[key] !== undefined && parsed[key] !== null)
137
+ return parsed[key];
138
+ }
139
+ if (fnObj && fnObj.arguments !== undefined && fnObj.arguments !== null)
140
+ return fnObj.arguments;
141
+ const flat = {};
142
+ for (const [key, value] of Object.entries(parsed)) {
143
+ if (!TOOL_CALL_ENVELOPE_KEYS.has(key))
144
+ flat[key] = value;
145
+ }
146
+ return flat;
147
+ }
122
148
  export function extractToolCallJsonObjects(text, allowUnclosedHealing = true) {
123
149
  const results = [];
124
150
  if (!text || typeof text !== 'string')
@@ -127,6 +127,31 @@ export function normalizePeerPlanEntries(value: unknown): PlanUpdate | null {
127
127
  return { explanation, plan: steps };
128
128
  }
129
129
 
130
+ const TOOL_CALL_ENVELOPE_KEYS = new Set(['name', 'tool', 'function', 'type', 'id', 'call_id', 'tool_call_id']);
131
+
132
+ /**
133
+ * Resolve the argument payload of a text-delimited tool call envelope.
134
+ *
135
+ * Accepts `arguments`, `parameters`, `input`, `args`, nested `function.arguments`,
136
+ * and the flat form some peers emit, where arguments sit beside `name`
137
+ * (`{"name":"update_plan","plan":[...]}`). Falling back to `{}` for the flat form
138
+ * discarded every argument and produced false "is required" validation errors.
139
+ */
140
+ export function resolveToolCallEnvelopeArguments(parsed: Record<string, unknown>): unknown {
141
+ const fnObj = parsed.function && typeof parsed.function === 'object' && !Array.isArray(parsed.function)
142
+ ? (parsed.function as Record<string, unknown>)
143
+ : null;
144
+ for (const key of ['arguments', 'parameters', 'input', 'args'] as const) {
145
+ if (parsed[key] !== undefined && parsed[key] !== null) return parsed[key];
146
+ }
147
+ if (fnObj && fnObj.arguments !== undefined && fnObj.arguments !== null) return fnObj.arguments;
148
+ const flat: Record<string, unknown> = {};
149
+ for (const [key, value] of Object.entries(parsed)) {
150
+ if (!TOOL_CALL_ENVELOPE_KEYS.has(key)) flat[key] = value;
151
+ }
152
+ return flat;
153
+ }
154
+
130
155
  export function extractToolCallJsonObjects(text: string, allowUnclosedHealing = true): Array<Record<string, unknown>> {
131
156
  const results: Array<Record<string, unknown>> = [];
132
157
  if (!text || typeof text !== 'string') return results;
@@ -1,4 +1,5 @@
1
1
  import fs from 'node:fs';
2
+ import os from 'node:os';
2
3
  import path from 'node:path';
3
4
  import { auditLog } from '../auditLog.js';
4
5
  import { isLaunchOnlyPrompt } from '../launchIntent.js';
@@ -22,7 +23,8 @@ const DEFAULT_CONFIG = {
22
23
  const COMPLETION_CLAIMS = [
23
24
  /\b(?:done|finished|complete(?:d)?|implemented|resolved|fixed|ready)\b/i,
24
25
  /\b(?:all|everything)\b[^.\n]{0,60}\b(?:works?|pass(?:es|ed|ing)?|fixed|done|clean)\b/i,
25
- /\b(?:no|zero)\s+(?:errors?|issues?|failures?|bugs?)\b/i
26
+ /\b(?:no|zero)\s+(?:errors?|issues?|failures?|bugs?)\b/i,
27
+ /\b(?:is\s+(?:running|live|available|listening|served)\s+(?:at|on)|application\s+is\s+running)\b/i
26
28
  ];
27
29
  const HONEST_CAVEATS = [
28
30
  /\b(?:not|never)\s+(?:run|ran|tested|verified|checked|completed?)\b/i,
@@ -62,6 +64,9 @@ function boundedTimeout(value) {
62
64
  return Math.max(200, Math.min(5000, Math.round(value)));
63
65
  }
64
66
  function safeConfigPath() {
67
+ if (process.env.NODE_TEST_CONTEXT) {
68
+ return path.join(os.tmpdir(), `causyne-test-observer-${process.pid}.json`);
69
+ }
65
70
  return CONFIG_FILE;
66
71
  }
67
72
  function readStoredConfig() {
@@ -1,4 +1,5 @@
1
1
  import fs from 'node:fs';
2
+ import os from 'node:os';
2
3
  import path from 'node:path';
3
4
  import { auditLog } from '../auditLog.js';
4
5
  import { isLaunchOnlyPrompt } from '../launchIntent.js';
@@ -81,7 +82,8 @@ const DEFAULT_CONFIG: ObserverConfig = {
81
82
  const COMPLETION_CLAIMS = [
82
83
  /\b(?:done|finished|complete(?:d)?|implemented|resolved|fixed|ready)\b/i,
83
84
  /\b(?:all|everything)\b[^.\n]{0,60}\b(?:works?|pass(?:es|ed|ing)?|fixed|done|clean)\b/i,
84
- /\b(?:no|zero)\s+(?:errors?|issues?|failures?|bugs?)\b/i
85
+ /\b(?:no|zero)\s+(?:errors?|issues?|failures?|bugs?)\b/i,
86
+ /\b(?:is\s+(?:running|live|available|listening|served)\s+(?:at|on)|application\s+is\s+running)\b/i
85
87
  ];
86
88
 
87
89
  const HONEST_CAVEATS = [
@@ -122,6 +124,9 @@ function boundedTimeout(value: unknown): number | null {
122
124
  }
123
125
 
124
126
  function safeConfigPath(): string {
127
+ if (process.env.NODE_TEST_CONTEXT) {
128
+ return path.join(os.tmpdir(), `causyne-test-observer-${process.pid}.json`);
129
+ }
125
130
  return CONFIG_FILE;
126
131
  }
127
132
 
package/src/observer.js CHANGED
@@ -3,6 +3,22 @@ import path from 'node:path';
3
3
  import http from 'node:http';
4
4
  import { createHash } from 'node:crypto';
5
5
  import { coldObserver } from './observer/coldObserver.js';
6
+ export function extractClaimedLocalUrls(text) {
7
+ if (!text)
8
+ return [];
9
+ const matches = text.match(/https?:\/\/(?:localhost|127\.0\.0\.1|\[::1\]):\d+(?:\/[^\s)>'"`\]]*)?/gi) || [];
10
+ const unique = new Set();
11
+ for (const raw of matches) {
12
+ let end = raw.length;
13
+ while (end > 0 && '.,;:!?'.includes(raw[end - 1])) {
14
+ end--;
15
+ }
16
+ const cleaned = raw.slice(0, end);
17
+ if (cleaned)
18
+ unique.add(cleaned);
19
+ }
20
+ return [...unique];
21
+ }
6
22
  export class CausyneObserver {
7
23
  /**
8
24
  * Evaluates the current state of a task after a tool outcome or at a step boundary.
@@ -64,11 +80,14 @@ export class CausyneObserver {
64
80
  // Check if the agent claims completion
65
81
  if (context.agentClaim && context.agentClaim.trim()) {
66
82
  const claim = context.agentClaim.toLowerCase();
67
- const claimsCompletion = /\b(?:done|complete|completed|finished|implemented|fixed|verified)\b/i.test(claim);
83
+ 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);
68
84
  if (claimsCompletion) {
69
85
  // Run deterministic verification checks based on domain
70
86
  const hasMutations = outcomes.some(o => ['fs_write', 'fs_edit', 'MultiEdit', 'write_file', 'edit_file'].includes(o.tool));
71
- const hasPassingVerification = outcomes.some(o => o.success && o.command && /\b(?:test|build|check|typecheck|vitest|jest|pytest)\b/i.test(o.command));
87
+ const hasPassingVerification = outcomes.some(o => o.success && (o.rendered === true ||
88
+ o.tool === 'browser_act' ||
89
+ o.tool === 'verify_local_web' ||
90
+ (o.command && /\b(?:test|build|check|typecheck|vitest|jest|pytest)\b/i.test(o.command))));
72
91
  if (hasMutations && !hasPassingVerification) {
73
92
  return {
74
93
  status: 'ready-to-verify',
@@ -166,11 +185,14 @@ export class CausyneObserver {
166
185
  return;
167
186
  }
168
187
  const clientReq = http.get(req.endpoint, { timeout: req.timeoutMs ?? 3000 }, (res) => {
188
+ res.resume();
169
189
  const expected = req.expectedStatus ?? 200;
170
190
  const ok = res.statusCode === expected || (res.statusCode !== undefined && res.statusCode >= 200 && res.statusCode < 400);
171
191
  const result = { verified: Boolean(ok) };
172
192
  if (typeof res.statusCode === 'number')
173
193
  result.statusCode = res.statusCode;
194
+ if (!ok)
195
+ result.error = `HTTP ${res.statusCode ?? 'unknown'}`;
174
196
  resolve(result);
175
197
  });
176
198
  clientReq.on('error', (err) => {
package/src/observer.ts CHANGED
@@ -61,6 +61,21 @@ export interface TaskObservationContext {
61
61
  toolHistory: readonly ToolOutcome[];
62
62
  }
63
63
 
64
+ export function extractClaimedLocalUrls(text: string): string[] {
65
+ if (!text) return [];
66
+ const matches = text.match(/https?:\/\/(?:localhost|127\.0\.0\.1|\[::1\]):\d+(?:\/[^\s)>'"`\]]*)?/gi) || [];
67
+ const unique = new Set<string>();
68
+ for (const raw of matches) {
69
+ let end = raw.length;
70
+ while (end > 0 && '.,;:!?'.includes(raw[end - 1]!)) {
71
+ end--;
72
+ }
73
+ const cleaned = raw.slice(0, end);
74
+ if (cleaned) unique.add(cleaned);
75
+ }
76
+ return [...unique];
77
+ }
78
+
64
79
  export class CausyneObserver {
65
80
  /**
66
81
  * Evaluates the current state of a task after a tool outcome or at a step boundary.
@@ -127,7 +142,7 @@ export class CausyneObserver {
127
142
  // Check if the agent claims completion
128
143
  if (context.agentClaim && context.agentClaim.trim()) {
129
144
  const claim = context.agentClaim.toLowerCase();
130
- const claimsCompletion = /\b(?:done|complete|completed|finished|implemented|fixed|verified)\b/i.test(claim);
145
+ 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);
131
146
 
132
147
  if (claimsCompletion) {
133
148
  // Run deterministic verification checks based on domain
@@ -135,7 +150,12 @@ export class CausyneObserver {
135
150
  ['fs_write', 'fs_edit', 'MultiEdit', 'write_file', 'edit_file'].includes(o.tool)
136
151
  );
137
152
  const hasPassingVerification = outcomes.some(o =>
138
- o.success && o.command && /\b(?:test|build|check|typecheck|vitest|jest|pytest)\b/i.test(o.command)
153
+ o.success && (
154
+ o.rendered === true ||
155
+ o.tool === 'browser_act' ||
156
+ o.tool === 'verify_local_web' ||
157
+ (o.command && /\b(?:test|build|check|typecheck|vitest|jest|pytest)\b/i.test(o.command))
158
+ )
139
159
  );
140
160
 
141
161
  if (hasMutations && !hasPassingVerification) {
@@ -248,10 +268,12 @@ export class CausyneObserver {
248
268
  }
249
269
 
250
270
  const clientReq = http.get(req.endpoint, { timeout: req.timeoutMs ?? 3000 }, (res) => {
271
+ res.resume();
251
272
  const expected = req.expectedStatus ?? 200;
252
273
  const ok = res.statusCode === expected || (res.statusCode !== undefined && res.statusCode >= 200 && res.statusCode < 400);
253
274
  const result: { verified: boolean; statusCode?: number; error?: string } = { verified: Boolean(ok) };
254
275
  if (typeof res.statusCode === 'number') result.statusCode = res.statusCode;
276
+ if (!ok) result.error = `HTTP ${res.statusCode ?? 'unknown'}`;
255
277
  resolve(result);
256
278
  });
257
279