@causyne/agent 1.20.76 → 1.20.79

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/src/agentLoop.ts CHANGED
@@ -1,4 +1,8 @@
1
1
  import { clearSysRunCache } from './tools/sysRun.js';
2
+ import { NetworkHostGuard } from './reliability/networkHostGuard.js';
3
+ import { inspectRequestedImageAssets } from './reliability/assetEvidence.js';
4
+ import { inspect3DVisualEvidence } from './reliability/visualEvidence.js';
5
+ import { getProcessEntitlementGate, EntitlementAccessError } from './licensing/entitlements.js';
2
6
  import { PEER_COLLABORATION_POLICY } from './providers/collaborationPolicy.js';
3
7
  import type { RequestPermissionRequest, RequestPermissionResponse } from './acp/protocol.js';
4
8
  import { createHash, randomUUID } from 'crypto';
@@ -639,6 +643,8 @@ export class AgentLoop {
639
643
  this.consecutiveCommands = 0;
640
644
  this.circuitBreakerUnlocked = false;
641
645
  this.stopRequested = false;
646
+ this._causyneTaskOutcome = 'incomplete';
647
+ this._networkHostGuard = new NetworkHostGuard();
642
648
  this.pendingApprovals = new Map(); // Maps toolCallId -> resolve function
643
649
  this.waitForDecision = async () => null;
644
650
  this._decisionAnswers = new Map();
@@ -1556,7 +1562,14 @@ export class AgentLoop {
1556
1562
 
1557
1563
  this.emitEvent({ type: 'decision_request', request });
1558
1564
  auditLog.log({ event: 'decision_requested', taskId: this.taskId, kind: request.kind, optionCount: request.options.length });
1559
- const answer = await this.waitForDecision(request);
1565
+ // CAUSYNE_ENTITLEMENT_V1: unresolved durable decisions do not consume fresh leases.
1566
+ this._entitlementGate?.pause();
1567
+ let answer: any;
1568
+ try {
1569
+ answer = await this.waitForDecision(request);
1570
+ } finally {
1571
+ this._entitlementGate?.resume();
1572
+ }
1560
1573
  if (!answer || typeof answer.label !== 'string' || !answer.label.trim()) {
1561
1574
  this.emitEvent({ type: 'decision_result', request, answer: null });
1562
1575
  return null;
@@ -1629,7 +1642,38 @@ export class AgentLoop {
1629
1642
  this.maxCircuitBreaker = this.maxSteps;
1630
1643
  }
1631
1644
 
1645
+ // CAUSYNE_ENTITLEMENT_V1: outer lifecycle wrapper, no agent-orchestration rewrite.
1632
1646
  async run() {
1647
+ this.rearmAbortController();
1648
+ this._causyneTaskOutcome = 'incomplete';
1649
+ this._networkHostGuard.reset();
1650
+ const gate = getProcessEntitlementGate();
1651
+ const onEntitlementBlocked = (error: unknown): void => {
1652
+ if (this.stopRequested) return;
1653
+ this.stopRequested = true;
1654
+ const explanation = error instanceof Error ? error.message : 'Entitlement check failed.';
1655
+ this.emitEvent({ type: 'error', message: `Causyne access paused: ${explanation} No workspace state was removed.` });
1656
+ };
1657
+ try {
1658
+ await gate.begin(onEntitlementBlocked);
1659
+ } catch (error: unknown) {
1660
+ if (error instanceof EntitlementAccessError) {
1661
+ this.emitEvent({ type: 'error', message: `Causyne access unavailable: ${error.message}` });
1662
+ return;
1663
+ }
1664
+ throw error;
1665
+ }
1666
+ this._entitlementGate = gate;
1667
+ try {
1668
+ await this.runLicensedCore();
1669
+ } finally {
1670
+ this._entitlementGate = null;
1671
+ gate.end(onEntitlementBlocked);
1672
+ }
1673
+ }
1674
+
1675
+ /** Existing run implementation moved unchanged; wrapper above owns metering. */
1676
+ async runLicensedCore() {
1633
1677
  this.stopRequested = false;
1634
1678
  // A task that was stopped must not poison the next one — see
1635
1679
  // rearmAbortController(). This has to happen before any tool can run.
@@ -1995,6 +2039,14 @@ export class AgentLoop {
1995
2039
 
1996
2040
  // The core loop governed by Sovereign Human-in-the-Loop Checkpoints
1997
2041
  while (!this.stopRequested) {
2042
+ // CAUSYNE_ENTITLEMENT_V1: verify an authorized lease before each model step.
2043
+ try {
2044
+ await this._entitlementGate?.beforeStep();
2045
+ } catch (error: unknown) {
2046
+ this.emitEvent({ type: 'error', message: error instanceof Error
2047
+ ? `Causyne access paused: ${error.message}` : 'Causyne access paused.' });
2048
+ break;
2049
+ }
1998
2050
  if (this.stopRequested) {
1999
2051
  this.emitEvent({ type: 'error', message: 'Task killed by user.' });
2000
2052
  auditLog.log({ event: 'task_killed', taskId: this.taskId });
@@ -3170,83 +3222,24 @@ You are operating in a text-and-code modality without direct image pixel renderi
3170
3222
  && (contentText.startsWith('Antigravity executed:') || /^Turn completed by .+ over ACP\.$/i.test(contentText.trim()));
3171
3223
 
3172
3224
  if ((hasExternalActions || isAcpTurnNotice) && (isIncompleteTurn || isMidTaskProgress || isAcpTurnNotice)) {
3173
- const cleanSubstantive = (text: unknown): string => {
3174
- if (typeof text !== 'string') return '';
3175
- return text
3225
+ if (isAcpTurnNotice && !isIncompleteTurn && !isMidTaskProgress) {
3226
+ // A completed peer turn must pass the normal host verification
3227
+ // gates below. The ACP notice itself is never completion proof.
3228
+ } else {
3229
+ const partial = String(contentText || '')
3176
3230
  .replace(/^Antigravity executed:[^\n]*\n*/i, '')
3177
3231
  .replace(/^Turn completed by [^\n]+ over ACP\.\s*/i, '')
3178
3232
  .trim();
3179
- };
3180
-
3181
- const currentSubstantive = cleanSubstantive(contentText);
3182
- if (currentSubstantive.length >= 60) {
3183
- this.emitEvent({
3184
- type: 'agent_message',
3185
- content: currentSubstantive
3186
- });
3187
- this.emitEvent({
3188
- type: 'status',
3189
- message: 'Task completed with verified deliverables.'
3190
- });
3191
- this.memoryManager.saveHistory(this.messages);
3192
- break;
3193
- }
3194
-
3195
- const recentSubstantiveAssistant = [...this.messages].reverse().find(m =>
3196
- m.role === 'assistant'
3197
- && typeof m.content === 'string'
3198
- && cleanSubstantive(m.content).length >= 60
3199
- );
3200
-
3201
- if (recentSubstantiveAssistant && typeof recentSubstantiveAssistant.content === 'string') {
3202
- this.emitEvent({
3203
- type: 'agent_message',
3204
- content: cleanSubstantive(recentSubstantiveAssistant.content)
3205
- });
3206
- this.emitEvent({
3207
- type: 'status',
3208
- message: 'Task completed with verified deliverables.'
3209
- });
3210
- this.memoryManager.saveHistory(this.messages);
3211
- break;
3212
- }
3213
-
3214
- if (isLaunchOnlyPrompt(taskPrompt) && this.stepsCompleted > 0) {
3215
- const launchSummary = 'Project opened in your default browser. Verification checks completed.';
3216
- this.emitEvent({
3217
- type: 'agent_message',
3218
- content: launchSummary
3219
- });
3220
- this.emitEvent({
3221
- type: 'status',
3222
- message: 'Task completed: project launched and verified.'
3223
- });
3224
- this.memoryManager.saveHistory(this.messages);
3225
- break;
3226
- }
3227
-
3228
- if (this.stepsCompleted > 0) {
3229
- const summary = `Task completed (${this.stepsCompleted} step${this.stepsCompleted === 1 ? '' : 's'} executed). All verified deliverables and actions are in place.`;
3230
- this.emitEvent({
3231
- type: 'agent_message',
3232
- content: summary
3233
- });
3234
- this.emitEvent({
3235
- type: 'status',
3236
- message: 'Task completed with verified deliverables.'
3237
- });
3233
+ if (partial.length >= 20) {
3234
+ this.emitEvent({ type: 'agent_message', content: partial });
3235
+ }
3236
+ this.emitEvent({ type: 'error', message:
3237
+ 'The peer ended with an incomplete or progress-only turn. ' +
3238
+ 'Actions may have changed files, but completion is not established.' });
3238
3239
  this.memoryManager.saveHistory(this.messages);
3239
3240
  break;
3240
3241
  }
3241
-
3242
- this.emitEvent({
3243
- type: 'error',
3244
- message: 'The task stopped before completion after repeated incomplete turns without a final response. Work remains unfinished.'
3245
- });
3246
- this.memoryManager.saveHistory(this.messages);
3247
- break;
3248
3242
  }
3249
-
3250
3243
  if (hasExternalActions && !isIncompleteTurn && !isMidTaskProgress) {
3251
3244
  incompleteTurnContinuations = 0;
3252
3245
  }
@@ -3276,11 +3269,9 @@ You are operating in a text-and-code modality without direct image pixel renderi
3276
3269
  }
3277
3270
 
3278
3271
  if (!hasExternalActions && (isIncompleteTurn || failedExternalActions.length > 0 || !contentText.trim())) {
3279
- if (allPlanCompleted || (this.stepsCompleted > 0 && !isIncompleteTurn && failedExternalActions.length === 0)) {
3280
- const planSummary = this._implementationPlan?.length > 0
3281
- ? ` All ${this._implementationPlan.length} plan steps have been executed and verified:\n\n`
3282
- + this._implementationPlan.map((s: any, idx: number) => ` ✓ ${s.step || s.text || s.content || `Step ${idx + 1}`}`).join('\n')
3283
- : ` All verified deliverables and actions are in place (${this.stepsCompleted} step${this.stepsCompleted === 1 ? '' : 's'} executed).`;
3272
+ if (allPlanCompleted) {
3273
+ const planSummary = ` All ${this._implementationPlan.length} plan steps have been completed and verified:\n\n`
3274
+ + this._implementationPlan.map((s: any, idx: number) => ` ✓ ${s.step || s.text || s.content || `Step ${idx + 1}`}`).join('\n');
3284
3275
  const summary = `Task completed successfully.${planSummary}`;
3285
3276
  this.emitEvent({
3286
3277
  type: 'agent_message',
@@ -3290,47 +3281,25 @@ You are operating in a text-and-code modality without direct image pixel renderi
3290
3281
  type: 'status',
3291
3282
  message: 'Task completed with verified deliverables.'
3292
3283
  });
3284
+ this._causyneTaskOutcome = 'completed';
3293
3285
  this.memoryManager.saveHistory(this.messages);
3294
3286
  break;
3295
3287
  }
3296
-
3297
- if (this.stepsCompleted > 0 && incompleteTurnContinuations < 2) {
3288
+ if (this.stepsCompleted > 0 && incompleteTurnContinuations < 2 && failedExternalActions.length === 0) {
3298
3289
  incompleteTurnContinuations++;
3299
- this.emitEvent({ type: 'status', message: 'Requesting final deliverable and response...' });
3300
- this.emitEvent({ type: 'agent_activity', activity: 'Synthesizing final deliverable…' });
3301
- this.messages.push({
3302
- role: 'system',
3303
- 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.]`
3304
- });
3290
+ this.emitEvent({ type: 'status', message: 'Requesting the missing final response…' });
3291
+ this.messages.push({ role: 'system', content:
3292
+ '[FINAL RESPONSE REQUIRED] Report actual completed and incomplete work from tool results. ' +
3293
+ 'Do not call plan steps or file writes proof of verification.' });
3305
3294
  this.memoryManager.saveHistory(this.messages);
3306
3295
  continue;
3307
3296
  }
3308
-
3309
- if (this.stepsCompleted > 0) {
3310
- const summary = `Task completed (${this.stepsCompleted} step${this.stepsCompleted === 1 ? '' : 's'} executed). All verified deliverables and actions are in place.`;
3311
- this.emitEvent({
3312
- type: 'agent_message',
3313
- content: summary
3314
- });
3315
- this.emitEvent({
3316
- type: 'status',
3317
- message: 'Task completed with verified deliverables.'
3318
- });
3319
- this.memoryManager.saveHistory(this.messages);
3320
- break;
3321
- }
3322
-
3323
- if (!contentText.trim()) {
3324
- this.messages.pop();
3325
- }
3326
- this.emitEvent({
3327
- type: 'error',
3328
- message: 'The task stopped before completion after repeated blocked or incomplete turns. Work remains unfinished.'
3329
- });
3297
+ this.emitEvent({ type: 'error', message:
3298
+ 'The task stopped with failed actions, an incomplete turn, or no final response. ' +
3299
+ 'Existing files were preserved; completion was not verified.' });
3330
3300
  this.memoryManager.saveHistory(this.messages);
3331
3301
  break;
3332
3302
  }
3333
-
3334
3303
  // --- COMPLETION GUARDS ---
3335
3304
  // Two hard rules learned the expensive way:
3336
3305
  // 1. Match on word boundaries. Substring matching made 'ui' fire on
@@ -3513,7 +3482,6 @@ You are operating in a text-and-code modality without direct image pixel renderi
3513
3482
  const hasVisionCapability = this.llm.supportsVision !== false && visionReady && !visionDeclined;
3514
3483
  const isVerified = Boolean(
3515
3484
  this.webVerificationState.browserActUsed ||
3516
- hasBrowserActOutcome ||
3517
3485
  this.webVerificationState.screenshotTaken ||
3518
3486
  ((!browserReady || !hasVisionCapability) && this.webVerificationState.htmlInspected) ||
3519
3487
  hasPassingTests ||
@@ -3667,6 +3635,43 @@ You are operating in a text-and-code modality without direct image pixel renderi
3667
3635
  }
3668
3636
  }
3669
3637
 
3638
+ // CAUSYNE_RELIABILITY_V1: require real downloaded images
3639
+ // if image acquisition was part of the user's explicit request.
3640
+ const imageAssetEvidence = await inspectRequestedImageAssets({
3641
+ prompt: taskPrompt,
3642
+ workspaceRoot: this.workspaceRoot,
3643
+ webArtifacts: [...this.webArtifacts]
3644
+ });
3645
+ if (!imageAssetEvidence.ok) {
3646
+ this.emitEvent({ type: 'error', message: imageAssetEvidence.reason ||
3647
+ 'Required downloaded website images were not verified.' });
3648
+ this.memoryManager.saveHistory(this.messages);
3649
+ break;
3650
+ }
3651
+
3652
+ // A preview or DOM snapshot is not proof that a Three.js/WebGL
3653
+ // rendering was actually examined by a vision-capable model.
3654
+ const visualEvidence = inspect3DVisualEvidence(
3655
+ taskPrompt,
3656
+ coldObserver.getToolOutcomes(this.taskId)
3657
+ );
3658
+ if (!visualEvidence.ok) {
3659
+ this.emitEvent({ type: 'error', message: visualEvidence.reason ||
3660
+ '3D visual output was not verified.' });
3661
+ this.memoryManager.saveHistory(this.messages);
3662
+ break;
3663
+ }
3664
+
3665
+ const finalToolOutcomes = coldObserver.getToolOutcomes(this.taskId);
3666
+ const finalToolOutcome = finalToolOutcomes[finalToolOutcomes.length - 1];
3667
+ if (this.stepsCompleted > 0 && finalToolOutcome && !finalToolOutcome.success) {
3668
+ this.emitEvent({ type: 'error', message:
3669
+ `The last observed tool action failed (${finalToolOutcome.tool}). ` +
3670
+ 'Resolve the error or report partial work; no success has been recorded.' });
3671
+ this.memoryManager.saveHistory(this.messages);
3672
+ break;
3673
+ }
3674
+
3670
3675
  const cleanTerminalContent = (text: unknown): string => {
3671
3676
  if (typeof text !== 'string') return '';
3672
3677
  return text
@@ -3751,6 +3756,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
3751
3756
  }
3752
3757
  } catch { /* never block completion on session summary recording */ }
3753
3758
 
3759
+ this._causyneTaskOutcome = 'completed';
3754
3760
  auditLog.log({ event: 'task_complete', taskId: this.taskId, steps: this.stepsCompleted });
3755
3761
  this.emitEvent({ type: 'task_complete', taskId: this.taskId });
3756
3762
  break;
@@ -4208,6 +4214,21 @@ You are operating in a text-and-code modality without direct image pixel renderi
4208
4214
  }
4209
4215
  }
4210
4216
 
4217
+ // CAUSYNE_RELIABILITY_V1: refuse repeated timeouts to one host.
4218
+ // This is not a network authorization rule; sandbox and approval ran above.
4219
+ const networkDecision = this._networkHostGuard.before(functionName, args);
4220
+ if (!networkDecision.allowed) {
4221
+ const error = String(networkDecision.error);
4222
+ const failure = { success: false, error, code: 'NETWORK_HOST_UNAVAILABLE' };
4223
+ coldObserver.recordToolOutcome(this.taskId, functionName, args, failure);
4224
+ this.messages.push({ role: 'tool', tool_call_id: toolCall.id,
4225
+ name: functionName, content: JSON.stringify(failure) });
4226
+ this.emitEvent({ type: 'step_error', tool: functionName,
4227
+ error, toolCallId: toolCall.id });
4228
+ this.memoryManager.saveHistory(this.messages);
4229
+ continue;
4230
+ }
4231
+
4211
4232
  // P2: snapshot the files this call is about to change, before it runs.
4212
4233
  // Only the mutating fs tools match; everything else returns immediately.
4213
4234
  // Fail-open by contract — this can never block or fail a tool call.
@@ -4259,6 +4280,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
4259
4280
  duration = 0;
4260
4281
  const errorType = this.classifyError(toolError);
4261
4282
  const failure = { success: false, error: String(toolError?.message || toolError) };
4283
+ this._networkHostGuard.after(functionName, args, failure);
4262
4284
  const alternativeRoute = lookupAlternativeStep({
4263
4285
  failedTool: functionName,
4264
4286
  why: failureClass(failure),
@@ -4314,6 +4336,8 @@ You are operating in a text-and-code modality without direct image pixel renderi
4314
4336
  };
4315
4337
  }
4316
4338
 
4339
+ this._networkHostGuard.after(functionName, args, result);
4340
+
4317
4341
  if (result && result.success !== false && !result.error && ['fs_write', 'fs_edit', 'MultiEdit'].includes(functionName)) {
4318
4342
  this.recordWebArtifact(args.path || args.file_path);
4319
4343
  }
@@ -4907,7 +4931,9 @@ You are operating in a text-and-code modality without direct image pixel renderi
4907
4931
  async waitForApproval(toolCallId: string): Promise<boolean> {
4908
4932
  const signal = this.abortController?.signal;
4909
4933
  if (this.stopRequested || signal?.aborted) return false;
4910
- return new Promise<boolean>((resolve) => {
4934
+ this._entitlementGate?.pause();
4935
+ try {
4936
+ return await new Promise<boolean>((resolve) => {
4911
4937
  let settled = false;
4912
4938
  const finish = (approved: boolean): void => {
4913
4939
  if (settled) return;
@@ -4924,6 +4950,9 @@ You are operating in a text-and-code modality without direct image pixel renderi
4924
4950
  signal?.addEventListener('abort', onAbort, { once: true });
4925
4951
  if (signal?.aborted) finish(false);
4926
4952
  });
4953
+ } finally {
4954
+ this._entitlementGate?.resume();
4955
+ }
4927
4956
  }
4928
4957
 
4929
4958
  /**
@@ -4957,6 +4986,11 @@ You are operating in a text-and-code modality without direct image pixel renderi
4957
4986
  if (spent > 0) return 'fatal';
4958
4987
  const msg = (error.message || '').toLowerCase();
4959
4988
 
4989
+ if (error?.name === 'OpenRouterPrivacyConstraintError'
4990
+ || msg.includes('matching the privacy policy')
4991
+ || msg.includes('data_collection=')) {
4992
+ return 'fatal';
4993
+ }
4960
4994
  if (msg.includes('free usage limit') || msg.includes('subscribe to opencode') || msg.includes('opencode.ai/go') || msg.includes('insufficient_quota') || msg.includes('credit balance is too low')) {
4961
4995
  return 'fatal';
4962
4996
  }
package/src/cliMode.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { runSetup } from './tui/setup.js';
2
2
  import { AgentLoop } from './agentLoop.js';
3
+ import { getProcessEntitlementGate } from './licensing/entitlements.js';
3
4
  import { loadConfig, saveConfig } from './config.js';
4
5
  import readline from 'readline';
5
6
  import { ChatPrompt, isInteractive } from './tui/prompt.js';
@@ -263,8 +264,13 @@ export async function runTask(task) {
263
264
  loop.waitForDecision = makeDecisionHandler(conn);
264
265
 
265
266
  await loop.run();
266
- console.log('\n\x1b[32m[DONE]\x1b[0m Task completed.\n');
267
- process.exit(0);
267
+ const completed = loop._causyneTaskOutcome === 'completed';
268
+ if (completed) {
269
+ console.log('\n\x1b[32m[DONE]\x1b[0m Task completed and verified.\n');
270
+ } else {
271
+ console.error('\n\x1b[31m[INCOMPLETE]\x1b[0m No verified task completion was recorded.\n');
272
+ }
273
+ process.exitCode = completed ? 0 : 1;
268
274
  }
269
275
 
270
276
 
@@ -656,6 +662,17 @@ export async function chatMode({ home = false } = {}) {
656
662
  }
657
663
 
658
664
  export async function execCommand(command) {
665
+ // CAUSYNE_ENTITLEMENT_V1: non-agent CLI shell entry must not bypass access checks.
666
+ const entitlementGate = getProcessEntitlementGate();
667
+ try {
668
+ await entitlementGate.begin((error) => {
669
+ console.error('Causyne access paused:', error instanceof Error ? error.message : String(error));
670
+ });
671
+ } catch (error) {
672
+ console.error('Causyne access unavailable:', error instanceof Error ? error.message : String(error));
673
+ process.exitCode = 2;
674
+ return;
675
+ }
659
676
  // L1 (local-path audit): this used to call sysRun.execute() DIRECTLY, so
660
677
  // `causyne-agent exec` was the one path into the shell with no sandbox at all —
661
678
  // no risk classification, no approval, not even the FORBIDDEN blocklist. A
package/src/entrypoint.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { program } from 'commander';
2
2
 
3
3
  import { runTask, chatMode, execCommand, interactiveConfig } from './cliMode.js';
4
+ import { runLicenseCommand } from './licensing/entitlements.js';
4
5
  import { runSelfUpdate, diagnoseInstallation, formatDoctorReport } from './autoUpdate.js';
5
6
  import { printContextReport, printUsageReport, printCheckpoints, printUndo, buildStatusText, printReport } from './reporting.js';
6
7
  import { runCommand } from './commands.js';
@@ -117,6 +118,14 @@ program
117
118
  await chatMode();
118
119
  });
119
120
 
121
+ // CAUSYNE_ENTITLEMENT_V1: software access is distinct from provider token usage.
122
+ program
123
+ .command('license [action] [plan]')
124
+ .description('Show software access or open an authenticated payment checkout')
125
+ .action(async (action = 'status', plan = '') => {
126
+ await runLicenseCommand(action, plan);
127
+ });
128
+
120
129
  program
121
130
  .command('context')
122
131
  .description('Show what fills the context window (tool schemas, window pool, spilled output)')
@@ -0,0 +1,14 @@
1
+ export declare class EntitlementAccessError extends Error {
2
+ code: string;
3
+ constructor(code: string, message: string);
4
+ }
5
+ export declare class EntitlementGate {
6
+ enabled: boolean;
7
+ begin(onBlocked?: (error: unknown) => void): Promise<void>;
8
+ beforeStep(): Promise<void>;
9
+ pause(): void;
10
+ resume(): void;
11
+ end(onBlocked?: (error: unknown) => void): void;
12
+ }
13
+ export declare function getProcessEntitlementGate(): EntitlementGate;
14
+ export declare function runLicenseCommand(action?: string, plan?: string): Promise<void>;