@causyne/agent 1.20.76 → 1.20.78

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.76",
3
+ "version": "1.20.78",
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
@@ -1,4 +1,5 @@
1
1
  import { clearSysRunCache } from './tools/sysRun.js';
2
+ import { getProcessEntitlementGate, EntitlementAccessError } from './licensing/entitlements.js';
2
3
  import { PEER_COLLABORATION_POLICY } from './providers/collaborationPolicy.js';
3
4
  import { createHash, randomUUID } from 'crypto';
4
5
  import { execFileSync } from 'node:child_process';
@@ -1484,7 +1485,15 @@ export class AgentLoop {
1484
1485
  return remembered;
1485
1486
  this.emitEvent({ type: 'decision_request', request });
1486
1487
  auditLog.log({ event: 'decision_requested', taskId: this.taskId, kind: request.kind, optionCount: request.options.length });
1487
- const answer = await this.waitForDecision(request);
1488
+ // CAUSYNE_ENTITLEMENT_V1: unresolved durable decisions do not consume fresh leases.
1489
+ this._entitlementGate?.pause();
1490
+ let answer;
1491
+ try {
1492
+ answer = await this.waitForDecision(request);
1493
+ }
1494
+ finally {
1495
+ this._entitlementGate?.resume();
1496
+ }
1488
1497
  if (!answer || typeof answer.label !== 'string' || !answer.label.trim()) {
1489
1498
  this.emitEvent({ type: 'decision_result', request, answer: null });
1490
1499
  return null;
@@ -1561,7 +1570,38 @@ export class AgentLoop {
1561
1570
  }
1562
1571
  this.maxCircuitBreaker = this.maxSteps;
1563
1572
  }
1573
+ // CAUSYNE_ENTITLEMENT_V1: outer lifecycle wrapper, no agent-orchestration rewrite.
1564
1574
  async run() {
1575
+ this.rearmAbortController();
1576
+ const gate = getProcessEntitlementGate();
1577
+ const onEntitlementBlocked = (error) => {
1578
+ if (this.stopRequested)
1579
+ return;
1580
+ this.stopRequested = true;
1581
+ const explanation = error instanceof Error ? error.message : 'Entitlement check failed.';
1582
+ this.emitEvent({ type: 'error', message: `Causyne access paused: ${explanation} No workspace state was removed.` });
1583
+ };
1584
+ try {
1585
+ await gate.begin(onEntitlementBlocked);
1586
+ }
1587
+ catch (error) {
1588
+ if (error instanceof EntitlementAccessError) {
1589
+ this.emitEvent({ type: 'error', message: `Causyne access unavailable: ${error.message}` });
1590
+ return;
1591
+ }
1592
+ throw error;
1593
+ }
1594
+ this._entitlementGate = gate;
1595
+ try {
1596
+ await this.runLicensedCore();
1597
+ }
1598
+ finally {
1599
+ this._entitlementGate = null;
1600
+ gate.end(onEntitlementBlocked);
1601
+ }
1602
+ }
1603
+ /** Existing run implementation moved unchanged; wrapper above owns metering. */
1604
+ async runLicensedCore() {
1565
1605
  this.stopRequested = false;
1566
1606
  // A task that was stopped must not poison the next one — see
1567
1607
  // rearmAbortController(). This has to happen before any tool can run.
@@ -1907,6 +1947,15 @@ export class AgentLoop {
1907
1947
  let emptyResponseRecoveries = 0;
1908
1948
  // The core loop governed by Sovereign Human-in-the-Loop Checkpoints
1909
1949
  while (!this.stopRequested) {
1950
+ // CAUSYNE_ENTITLEMENT_V1: verify an authorized lease before each model step.
1951
+ try {
1952
+ await this._entitlementGate?.beforeStep();
1953
+ }
1954
+ catch (error) {
1955
+ this.emitEvent({ type: 'error', message: error instanceof Error
1956
+ ? `Causyne access paused: ${error.message}` : 'Causyne access paused.' });
1957
+ break;
1958
+ }
1910
1959
  if (this.stopRequested) {
1911
1960
  this.emitEvent({ type: 'error', message: 'Task killed by user.' });
1912
1961
  auditLog.log({ event: 'task_killed', taskId: this.taskId });
@@ -3343,7 +3392,6 @@ You are operating in a text-and-code modality without direct image pixel renderi
3343
3392
  }
3344
3393
  const hasVisionCapability = this.llm.supportsVision !== false && visionReady && !visionDeclined;
3345
3394
  const isVerified = Boolean(this.webVerificationState.browserActUsed ||
3346
- hasBrowserActOutcome ||
3347
3395
  this.webVerificationState.screenshotTaken ||
3348
3396
  ((!browserReady || !hasVisionCapability) && this.webVerificationState.htmlInspected) ||
3349
3397
  hasPassingTests ||
@@ -4644,25 +4692,31 @@ You are operating in a text-and-code modality without direct image pixel renderi
4644
4692
  const signal = this.abortController?.signal;
4645
4693
  if (this.stopRequested || signal?.aborted)
4646
4694
  return false;
4647
- return new Promise((resolve) => {
4648
- let settled = false;
4649
- const finish = (approved) => {
4650
- if (settled)
4651
- return;
4652
- settled = true;
4653
- clearTimeout(timer);
4654
- signal?.removeEventListener('abort', onAbort);
4655
- this.pendingApprovals.delete(toolCallId);
4656
- resolve(approved === true);
4657
- };
4658
- const onAbort = () => finish(false);
4659
- const timer = setTimeout(() => finish(false), 3600000);
4660
- timer.unref();
4661
- this.pendingApprovals.set(toolCallId, finish);
4662
- signal?.addEventListener('abort', onAbort, { once: true });
4663
- if (signal?.aborted)
4664
- finish(false);
4665
- });
4695
+ this._entitlementGate?.pause();
4696
+ try {
4697
+ return await new Promise((resolve) => {
4698
+ let settled = false;
4699
+ const finish = (approved) => {
4700
+ if (settled)
4701
+ return;
4702
+ settled = true;
4703
+ clearTimeout(timer);
4704
+ signal?.removeEventListener('abort', onAbort);
4705
+ this.pendingApprovals.delete(toolCallId);
4706
+ resolve(approved === true);
4707
+ };
4708
+ const onAbort = () => finish(false);
4709
+ const timer = setTimeout(() => finish(false), 3600000);
4710
+ timer.unref();
4711
+ this.pendingApprovals.set(toolCallId, finish);
4712
+ signal?.addEventListener('abort', onAbort, { once: true });
4713
+ if (signal?.aborted)
4714
+ finish(false);
4715
+ });
4716
+ }
4717
+ finally {
4718
+ this._entitlementGate?.resume();
4719
+ }
4666
4720
  }
4667
4721
  /**
4668
4722
  * Wait before retrying, and stay interruptible while waiting.
@@ -4697,6 +4751,11 @@ You are operating in a text-and-code modality without direct image pixel renderi
4697
4751
  if (spent > 0)
4698
4752
  return 'fatal';
4699
4753
  const msg = (error.message || '').toLowerCase();
4754
+ if (error?.name === 'OpenRouterPrivacyConstraintError'
4755
+ || msg.includes('matching the privacy policy')
4756
+ || msg.includes('data_collection=')) {
4757
+ return 'fatal';
4758
+ }
4700
4759
  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')) {
4701
4760
  return 'fatal';
4702
4761
  }
package/src/agentLoop.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { clearSysRunCache } from './tools/sysRun.js';
2
+ import { getProcessEntitlementGate, EntitlementAccessError } from './licensing/entitlements.js';
2
3
  import { PEER_COLLABORATION_POLICY } from './providers/collaborationPolicy.js';
3
4
  import type { RequestPermissionRequest, RequestPermissionResponse } from './acp/protocol.js';
4
5
  import { createHash, randomUUID } from 'crypto';
@@ -1556,7 +1557,14 @@ export class AgentLoop {
1556
1557
 
1557
1558
  this.emitEvent({ type: 'decision_request', request });
1558
1559
  auditLog.log({ event: 'decision_requested', taskId: this.taskId, kind: request.kind, optionCount: request.options.length });
1559
- const answer = await this.waitForDecision(request);
1560
+ // CAUSYNE_ENTITLEMENT_V1: unresolved durable decisions do not consume fresh leases.
1561
+ this._entitlementGate?.pause();
1562
+ let answer: any;
1563
+ try {
1564
+ answer = await this.waitForDecision(request);
1565
+ } finally {
1566
+ this._entitlementGate?.resume();
1567
+ }
1560
1568
  if (!answer || typeof answer.label !== 'string' || !answer.label.trim()) {
1561
1569
  this.emitEvent({ type: 'decision_result', request, answer: null });
1562
1570
  return null;
@@ -1629,7 +1637,36 @@ export class AgentLoop {
1629
1637
  this.maxCircuitBreaker = this.maxSteps;
1630
1638
  }
1631
1639
 
1640
+ // CAUSYNE_ENTITLEMENT_V1: outer lifecycle wrapper, no agent-orchestration rewrite.
1632
1641
  async run() {
1642
+ this.rearmAbortController();
1643
+ const gate = getProcessEntitlementGate();
1644
+ const onEntitlementBlocked = (error: unknown): void => {
1645
+ if (this.stopRequested) return;
1646
+ this.stopRequested = true;
1647
+ const explanation = error instanceof Error ? error.message : 'Entitlement check failed.';
1648
+ this.emitEvent({ type: 'error', message: `Causyne access paused: ${explanation} No workspace state was removed.` });
1649
+ };
1650
+ try {
1651
+ await gate.begin(onEntitlementBlocked);
1652
+ } catch (error: unknown) {
1653
+ if (error instanceof EntitlementAccessError) {
1654
+ this.emitEvent({ type: 'error', message: `Causyne access unavailable: ${error.message}` });
1655
+ return;
1656
+ }
1657
+ throw error;
1658
+ }
1659
+ this._entitlementGate = gate;
1660
+ try {
1661
+ await this.runLicensedCore();
1662
+ } finally {
1663
+ this._entitlementGate = null;
1664
+ gate.end(onEntitlementBlocked);
1665
+ }
1666
+ }
1667
+
1668
+ /** Existing run implementation moved unchanged; wrapper above owns metering. */
1669
+ async runLicensedCore() {
1633
1670
  this.stopRequested = false;
1634
1671
  // A task that was stopped must not poison the next one — see
1635
1672
  // rearmAbortController(). This has to happen before any tool can run.
@@ -1995,6 +2032,14 @@ export class AgentLoop {
1995
2032
 
1996
2033
  // The core loop governed by Sovereign Human-in-the-Loop Checkpoints
1997
2034
  while (!this.stopRequested) {
2035
+ // CAUSYNE_ENTITLEMENT_V1: verify an authorized lease before each model step.
2036
+ try {
2037
+ await this._entitlementGate?.beforeStep();
2038
+ } catch (error: unknown) {
2039
+ this.emitEvent({ type: 'error', message: error instanceof Error
2040
+ ? `Causyne access paused: ${error.message}` : 'Causyne access paused.' });
2041
+ break;
2042
+ }
1998
2043
  if (this.stopRequested) {
1999
2044
  this.emitEvent({ type: 'error', message: 'Task killed by user.' });
2000
2045
  auditLog.log({ event: 'task_killed', taskId: this.taskId });
@@ -3513,7 +3558,6 @@ You are operating in a text-and-code modality without direct image pixel renderi
3513
3558
  const hasVisionCapability = this.llm.supportsVision !== false && visionReady && !visionDeclined;
3514
3559
  const isVerified = Boolean(
3515
3560
  this.webVerificationState.browserActUsed ||
3516
- hasBrowserActOutcome ||
3517
3561
  this.webVerificationState.screenshotTaken ||
3518
3562
  ((!browserReady || !hasVisionCapability) && this.webVerificationState.htmlInspected) ||
3519
3563
  hasPassingTests ||
@@ -4907,7 +4951,9 @@ You are operating in a text-and-code modality without direct image pixel renderi
4907
4951
  async waitForApproval(toolCallId: string): Promise<boolean> {
4908
4952
  const signal = this.abortController?.signal;
4909
4953
  if (this.stopRequested || signal?.aborted) return false;
4910
- return new Promise<boolean>((resolve) => {
4954
+ this._entitlementGate?.pause();
4955
+ try {
4956
+ return await new Promise<boolean>((resolve) => {
4911
4957
  let settled = false;
4912
4958
  const finish = (approved: boolean): void => {
4913
4959
  if (settled) return;
@@ -4924,6 +4970,9 @@ You are operating in a text-and-code modality without direct image pixel renderi
4924
4970
  signal?.addEventListener('abort', onAbort, { once: true });
4925
4971
  if (signal?.aborted) finish(false);
4926
4972
  });
4973
+ } finally {
4974
+ this._entitlementGate?.resume();
4975
+ }
4927
4976
  }
4928
4977
 
4929
4978
  /**
@@ -4957,6 +5006,11 @@ You are operating in a text-and-code modality without direct image pixel renderi
4957
5006
  if (spent > 0) return 'fatal';
4958
5007
  const msg = (error.message || '').toLowerCase();
4959
5008
 
5009
+ if (error?.name === 'OpenRouterPrivacyConstraintError'
5010
+ || msg.includes('matching the privacy policy')
5011
+ || msg.includes('data_collection=')) {
5012
+ return 'fatal';
5013
+ }
4960
5014
  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
5015
  return 'fatal';
4962
5016
  }
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';
@@ -656,6 +657,17 @@ export async function chatMode({ home = false } = {}) {
656
657
  }
657
658
 
658
659
  export async function execCommand(command) {
660
+ // CAUSYNE_ENTITLEMENT_V1: non-agent CLI shell entry must not bypass access checks.
661
+ const entitlementGate = getProcessEntitlementGate();
662
+ try {
663
+ await entitlementGate.begin((error) => {
664
+ console.error('Causyne access paused:', error instanceof Error ? error.message : String(error));
665
+ });
666
+ } catch (error) {
667
+ console.error('Causyne access unavailable:', error instanceof Error ? error.message : String(error));
668
+ process.exitCode = 2;
669
+ return;
670
+ }
659
671
  // L1 (local-path audit): this used to call sysRun.execute() DIRECTLY, so
660
672
  // `causyne-agent exec` was the one path into the shell with no sandbox at all —
661
673
  // 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>;
@@ -0,0 +1,264 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import crypto from 'node:crypto';
4
+ import { causyneHome } from '../utils/paths.js';
5
+ import { LICENSE_API_BASE, LICENSE_ENFORCEMENT_ENABLED, LICENSE_PLAN_KEYS } from './policy.js';
6
+
7
+ const TOKEN_FILE = 'installation-identity.json';
8
+ const USER_AGENT = 'Causyne-Agent/entitlements-v1';
9
+ const AUTH_TIMEOUT_MS = 10000;
10
+
11
+ export class EntitlementAccessError extends Error {
12
+ constructor(code, message) {
13
+ super(message);
14
+ this.name = 'EntitlementAccessError';
15
+ this.code = code;
16
+ }
17
+ }
18
+
19
+ function base64url(input) { return Buffer.from(input).toString('base64url'); }
20
+ function digest(input) { return base64url(crypto.createHash('sha256').update(input).digest()); }
21
+ function sign(text, privateKey) { return base64url(crypto.sign(null, Buffer.from(text), privateKey)); }
22
+ function requestText(method, pathname, timestamp, nonce, hash) {
23
+ return ['CAUSYNE_API_V1', method.toUpperCase(), pathname, timestamp, nonce, hash].join('\n');
24
+ }
25
+ function registrationText(key, nonce) { return ['CAUSYNE_REGISTER_V1', key, nonce].join('\n'); }
26
+
27
+ function requireIdentityFields(value) {
28
+ if (!value || typeof value !== 'object' ||
29
+ typeof value.privateKeyPem !== 'string' || typeof value.publicKey !== 'string') {
30
+ throw new EntitlementAccessError('IDENTITY_CORRUPT',
31
+ 'The local Causyne installation identity is damaged. Contact support; do not delete it while recovering a paid license.');
32
+ }
33
+ const key = crypto.createPrivateKey(value.privateKeyPem);
34
+ const derived = base64url(crypto.createPublicKey(key).export({ type: 'spki', format: 'der' }));
35
+ if (derived !== value.publicKey) throw new EntitlementAccessError('IDENTITY_CORRUPT', 'Installation public/private keys disagree.');
36
+ if (value.installationId && !/^[\da-f-]{36}$/i.test(value.installationId)) {
37
+ throw new EntitlementAccessError('IDENTITY_CORRUPT', 'Installation ID is invalid.');
38
+ }
39
+ return value;
40
+ }
41
+
42
+ /** No hardware serials, MAC addresses, device fingerprint or email required. */
43
+ export function loadInstallationIdentity(stateRoot = causyneHome()) {
44
+ fs.mkdirSync(stateRoot, { recursive: true, mode: 0o700 });
45
+ const file = path.join(stateRoot, TOKEN_FILE);
46
+ try {
47
+ const value = requireIdentityFields(JSON.parse(fs.readFileSync(file, 'utf8')));
48
+ return { ...value, file };
49
+ } catch (error) {
50
+ if (error.code !== 'ENOENT') throw error;
51
+ }
52
+ const pair = crypto.generateKeyPairSync('ed25519');
53
+ const privateKeyPem = pair.privateKey.export({ type: 'pkcs8', format: 'pem' }).toString();
54
+ const publicKey = base64url(pair.publicKey.export({ type: 'spki', format: 'der' }));
55
+ const identity = { version: 1, publicKey, privateKeyPem, installationId: null };
56
+ // Exclusive create prevents a second running CLI from replacing this identity.
57
+ let fd;
58
+ try {
59
+ fd = fs.openSync(file, 'wx', 0o600);
60
+ fs.writeFileSync(fd, JSON.stringify(identity), 'utf8');
61
+ } catch (error) {
62
+ if (error.code === 'EEXIST') return loadInstallationIdentity(stateRoot);
63
+ throw error;
64
+ } finally { if (fd !== undefined) fs.closeSync(fd); }
65
+ return { ...identity, file };
66
+ }
67
+
68
+ function saveInstallationIdentity(identity) {
69
+ const value = { version: 1, privateKeyPem: identity.privateKeyPem,
70
+ publicKey: identity.publicKey, installationId: identity.installationId };
71
+ const file = identity.file;
72
+ const temp = `${file}.${process.pid}.${crypto.randomUUID()}.tmp`;
73
+ try {
74
+ fs.writeFileSync(temp, JSON.stringify(value), { mode: 0o600 });
75
+ fs.renameSync(temp, file);
76
+ try { fs.chmodSync(file, 0o600); } catch { /* Windows ACLs differ */ }
77
+ } finally { try { fs.unlinkSync(temp); } catch { /* rename removed it */ } }
78
+ }
79
+
80
+ export class EntitlementClient {
81
+ constructor({ apiBase = LICENSE_API_BASE, stateRoot = causyneHome(), fetchFn = globalThis.fetch } = {}) {
82
+ const url = new URL(apiBase);
83
+ if (url.protocol !== 'https:' && url.hostname !== '127.0.0.1' && url.hostname !== 'localhost') {
84
+ throw new Error('Entitlement service requires HTTPS.');
85
+ }
86
+ this.apiBase = url.origin;
87
+ this.stateRoot = stateRoot;
88
+ this.fetchFn = fetchFn;
89
+ this.identity = null;
90
+ }
91
+
92
+ async call(pathname, body, { register = false } = {}) {
93
+ const identity = this.identity ||= loadInstallationIdentity(this.stateRoot);
94
+ const method = body === undefined ? 'GET' : 'POST';
95
+ const raw = body === undefined ? '' : JSON.stringify(body);
96
+ const headers = { 'user-agent': USER_AGENT, 'accept': 'application/json',
97
+ 'content-type': 'application/json' };
98
+ if (!register) {
99
+ if (!identity.installationId) await this.register();
100
+ const timestamp = String(Math.floor(Date.now() / 1000));
101
+ const nonce = crypto.randomBytes(24).toString('base64url');
102
+ headers['x-causyne-installation'] = identity.installationId;
103
+ headers['x-causyne-timestamp'] = timestamp;
104
+ headers['x-causyne-nonce'] = nonce;
105
+ headers['x-causyne-signature'] = sign(requestText(method, pathname, timestamp, nonce, digest(raw)), identity.privateKeyPem);
106
+ }
107
+ const controller = new AbortController();
108
+ const timeout = setTimeout(() => controller.abort(), AUTH_TIMEOUT_MS);
109
+ timeout.unref?.();
110
+ try {
111
+ const response = await this.fetchFn(`${this.apiBase}${pathname}`, {
112
+ method, headers, ...(body !== undefined ? { body: raw } : {}), signal: controller.signal
113
+ });
114
+ const parsed = await response.json().catch(() => ({}));
115
+ if (!response.ok) {
116
+ throw new EntitlementAccessError(parsed?.error || 'SERVICE_ERROR',
117
+ typeof parsed?.message === 'string' ? parsed.message : `Entitlement service returned HTTP ${response.status}.`);
118
+ }
119
+ return parsed;
120
+ } catch (error) {
121
+ if (error instanceof EntitlementAccessError) throw error;
122
+ throw new EntitlementAccessError('NETWORK_UNAVAILABLE',
123
+ 'Cannot reach the Causyne licensing service. The current task is preserved; retry when connected.');
124
+ } finally { clearTimeout(timeout); }
125
+ }
126
+
127
+ async register() {
128
+ const identity = this.identity ||= loadInstallationIdentity(this.stateRoot);
129
+ if (identity.installationId) return identity.installationId;
130
+ const nonce = crypto.randomBytes(24).toString('base64url');
131
+ const response = await this.call('/v1/installations', {
132
+ publicKey: identity.publicKey, nonce,
133
+ proof: sign(registrationText(identity.publicKey, nonce), identity.privateKeyPem)
134
+ }, { register: true });
135
+ if (!/^[\da-f-]{36}$/i.test(response.installationId || '')) {
136
+ throw new EntitlementAccessError('REGISTRATION_ERROR', 'Licensing service returned an invalid installation ID.');
137
+ }
138
+ identity.installationId = response.installationId;
139
+ saveInstallationIdentity(identity);
140
+ return identity.installationId;
141
+ }
142
+
143
+ status() { return this.call('/v1/status'); }
144
+ lease(requestId, sessionId) { return this.call('/v1/leases', { requestId, sessionId }); }
145
+ async checkout(plan) {
146
+ if (!LICENSE_PLAN_KEYS.includes(plan)) throw new EntitlementAccessError('INVALID_PLAN', 'Unknown Causyne plan.');
147
+ const result = await this.call('/v1/checkout', { plan });
148
+ const url = new URL(result.url);
149
+ if (url.protocol !== 'https:' || !/(^|\.)lemonsqueezy\.com$/i.test(url.hostname)) {
150
+ throw new EntitlementAccessError('BAD_CHECKOUT_URL', 'Invalid checkout destination returned by server.');
151
+ }
152
+ return result;
153
+ }
154
+ }
155
+
156
+ /** Process-local gate. All AgentLoop instances in this process share one session. */
157
+ export class EntitlementGate {
158
+ constructor({ enabled = LICENSE_ENFORCEMENT_ENABLED, client = new EntitlementClient() } = {}) {
159
+ this.enabled = enabled;
160
+ this.client = client;
161
+ this.sessionId = crypto.randomUUID();
162
+ this.activeRuns = 0;
163
+ this.pausedRuns = 0;
164
+ this.leaseUntil = 0;
165
+ this.leasePlan = null;
166
+ this.blockedError = null;
167
+ this.timer = null;
168
+ this.pending = null;
169
+ this.listeners = new Set();
170
+ }
171
+
172
+ async ensureLease() {
173
+ if (!this.enabled) return { plan: 'development-disabled' };
174
+ if (this.blockedError) throw this.blockedError;
175
+ if (Date.now() + 500 < this.leaseUntil) return { plan: this.leasePlan };
176
+ if (this.pending) return this.pending;
177
+ this.pending = (async () => {
178
+ const requestId = crypto.randomUUID();
179
+ const result = await this.client.lease(requestId, this.sessionId);
180
+ const expiration = Date.parse(result.expiresAt || '');
181
+ if (!Number.isFinite(expiration) || expiration <= Date.now()) {
182
+ throw new EntitlementAccessError('INVALID_LEASE', 'Licensing service returned an expired or invalid lease.');
183
+ }
184
+ this.leaseUntil = expiration;
185
+ this.leasePlan = result.plan;
186
+ this.blockedError = null;
187
+ return result;
188
+ })().finally(() => { this.pending = null; });
189
+ return this.pending;
190
+ }
191
+
192
+ async begin(onBlocked = () => {}) {
193
+ if (!this.enabled) return;
194
+ await this.ensureLease();
195
+ this.activeRuns++;
196
+ this.listeners.add(onBlocked);
197
+ if (this.activeRuns === 1) {
198
+ // In-process only while tasks run. No daemon or remotely accessible port.
199
+ this.timer = setInterval(async () => {
200
+ if (this.pausedRuns >= this.activeRuns || Date.now() < this.leaseUntil) return;
201
+ try { await this.ensureLease(); }
202
+ catch (error) {
203
+ this.blockedError = error;
204
+ for (const listener of this.listeners) {
205
+ try { listener(error); } catch { /* do not crash current tool */ }
206
+ }
207
+ }
208
+ }, 1000);
209
+ this.timer.unref?.();
210
+ }
211
+ }
212
+
213
+ pause() { if (this.enabled) this.pausedRuns++; }
214
+ resume() { if (this.enabled) this.pausedRuns = Math.max(0, this.pausedRuns - 1); }
215
+
216
+ async beforeStep() {
217
+ if (!this.enabled) return;
218
+ await this.ensureLease();
219
+ }
220
+
221
+ end(onBlocked) {
222
+ if (!this.enabled) return;
223
+ this.listeners.delete(onBlocked);
224
+ this.activeRuns = Math.max(0, this.activeRuns - 1);
225
+ this.pausedRuns = Math.min(this.pausedRuns, this.activeRuns);
226
+ if (this.activeRuns === 0 && this.timer) {
227
+ clearInterval(this.timer);
228
+ this.timer = null;
229
+ }
230
+ }
231
+ }
232
+
233
+ let processGate;
234
+ export function getProcessEntitlementGate() {
235
+ return processGate ||= new EntitlementGate();
236
+ }
237
+
238
+ export async function runLicenseCommand(action = 'status', plan = '') {
239
+ const client = new EntitlementClient();
240
+ if (action === 'plans') {
241
+ console.log('Causyne Go plans: monthly, annual, two_month_pass, two_year_pass');
242
+ console.log('Paid access does not include paid model inference.');
243
+ console.log('One-time passes are non-recurring; pricing is shown at merchant checkout.');
244
+ return;
245
+ }
246
+ if (action === 'status') {
247
+ const data = await client.status();
248
+ console.log(`Causyne software entitlement: ${data.entitlement}`);
249
+ if (data.paidUntil) console.log(`Paid through: ${data.paidUntil}`);
250
+ else {
251
+ console.log(`Free allowance remaining: ${Math.floor(data.remainingSeconds / 60)} of ${Math.floor(data.dailySeconds / 60)} minutes`);
252
+ console.log(`UTC reset: ${data.resetsAt}`);
253
+ }
254
+ console.log('Model-provider inference has separate limits and costs.');
255
+ return;
256
+ }
257
+ if (action === 'buy') {
258
+ const result = await client.checkout(plan);
259
+ console.log(`Checkout: ${result.url}`);
260
+ console.log('Your entitlement activates only after the provider confirms payment.');
261
+ return;
262
+ }
263
+ throw new EntitlementAccessError('UNKNOWN_COMMAND', 'Use: causyne license status | plans | buy <plan>.');
264
+ }
@@ -0,0 +1,9 @@
1
+ // Release-switch. Keep FALSE in development until the licensing terms, backend,
2
+ // payment provider, recovery process, and staged release have been approved.
3
+ // Changing this client flag is not a DRM boundary: the authoritative quota is
4
+ // enforced by the private service when the client connects.
5
+ export const LICENSE_ENFORCEMENT_ENABLED = false;
6
+ export const LICENSE_API_BASE = 'https://license.causyne.com';
7
+ export const LICENSE_PLAN_KEYS = Object.freeze([
8
+ 'monthly', 'annual', 'two_month_pass', 'two_year_pass'
9
+ ]);
@@ -1,41 +1,50 @@
1
- import fs from 'fs/promises';
2
- import path from 'path';
3
- import os from 'os';
4
-
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import os from 'node:os';
5
4
  export const fsWrite = {
6
- schema: {
7
- name: 'fs.write',
8
- description: 'Create or overwrite a file with content using Zero-Corruption Atomic Swap. Guarantees safe file writing.',
9
- parameters: {
10
- type: 'object',
11
- properties: {
12
- path: { type: 'string' },
13
- content: { type: 'string' },
14
- createDirectories: { type: 'boolean' }
15
- },
16
- required: ['path', 'content']
5
+ schema: {
6
+ name: 'fs.write',
7
+ description: 'Create or overwrite a file with content using Zero-Corruption Atomic Swap. Guarantees safe file writing.',
8
+ parameters: {
9
+ type: 'object',
10
+ properties: {
11
+ path: { type: 'string' },
12
+ content: { type: 'string' },
13
+ createDirectories: { type: 'boolean' }
14
+ },
15
+ required: ['path', 'content']
16
+ }
17
+ },
18
+ async execute(args) {
19
+ try {
20
+ const target = args.path.replace(/^~\//, os.homedir() + '/');
21
+ // Prevent EISDIR if target path is already an existing directory
22
+ try {
23
+ const stat = await fs.stat(target);
24
+ if (stat.isDirectory()) {
25
+ return {
26
+ success: false,
27
+ error: `Cannot write file: "${args.path}" is an existing directory. Specify a target file path inside this directory (e.g. "${args.path}/index.js").`
28
+ };
29
+ }
30
+ }
31
+ catch {
32
+ // Target does not exist yet, safe to proceed
33
+ }
34
+ if (args.createDirectories !== false) {
35
+ await fs.mkdir(path.dirname(target), { recursive: true });
36
+ }
37
+ // Phase 4 AGI Upgrade: Atomic File Swap
38
+ // Prevent zero-byte file corruption if Node crashes during a huge write.
39
+ const tempPath = `${target}.causyne_tmp_${Date.now()}`;
40
+ await fs.writeFile(tempPath, args.content, 'utf8');
41
+ // Atomic rename (POSIX standard guarantee)
42
+ await fs.rename(tempPath, target);
43
+ return { success: true, output: `Atomically wrote ${Buffer.byteLength(args.content, 'utf8')} bytes to ${args.path}` };
44
+ }
45
+ catch (e) {
46
+ const msg = e instanceof Error ? e.message : String(e);
47
+ return { success: false, error: `Atomic Write Failed: ${msg}` };
48
+ }
17
49
  }
18
- },
19
- async execute(args) {
20
- try {
21
- const target = args.path.replace(/^~\//, os.homedir() + '/');
22
-
23
- if (args.createDirectories !== false) {
24
- await fs.mkdir(path.dirname(target), { recursive: true });
25
- }
26
-
27
- // Phase 4 AGI Upgrade: Atomic File Swap
28
- // Prevent zero-byte file corruption if Node crashes during a huge write.
29
- const tempPath = `${target}.causyne_tmp_${Date.now()}`;
30
-
31
- await fs.writeFile(tempPath, args.content, 'utf8');
32
-
33
- // Atomic rename (POSIX standard guarantee)
34
- await fs.rename(tempPath, target);
35
-
36
- return { success: true, output: `Atomically wrote ${Buffer.byteLength(args.content, 'utf8')} bytes to ${args.path}` };
37
- } catch (e) {
38
- return { success: false, error: `Atomic Write Failed: ${e.message}` };
39
- }
40
- }
41
50
  };
@@ -0,0 +1,66 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import os from 'node:os';
4
+
5
+ export interface FsWriteArgs {
6
+ path: string;
7
+ content: string;
8
+ createDirectories?: boolean;
9
+ }
10
+
11
+ export interface FsWriteResult {
12
+ success: boolean;
13
+ output?: string;
14
+ error?: string;
15
+ }
16
+
17
+ export const fsWrite = {
18
+ schema: {
19
+ name: 'fs.write',
20
+ description: 'Create or overwrite a file with content using Zero-Corruption Atomic Swap. Guarantees safe file writing.',
21
+ parameters: {
22
+ type: 'object',
23
+ properties: {
24
+ path: { type: 'string' },
25
+ content: { type: 'string' },
26
+ createDirectories: { type: 'boolean' }
27
+ },
28
+ required: ['path', 'content']
29
+ }
30
+ },
31
+ async execute(args: FsWriteArgs): Promise<FsWriteResult> {
32
+ try {
33
+ const target = args.path.replace(/^~\//, os.homedir() + '/');
34
+
35
+ // Prevent EISDIR if target path is already an existing directory
36
+ try {
37
+ const stat = await fs.stat(target);
38
+ if (stat.isDirectory()) {
39
+ return {
40
+ success: false,
41
+ error: `Cannot write file: "${args.path}" is an existing directory. Specify a target file path inside this directory (e.g. "${args.path}/index.js").`
42
+ };
43
+ }
44
+ } catch {
45
+ // Target does not exist yet, safe to proceed
46
+ }
47
+
48
+ if (args.createDirectories !== false) {
49
+ await fs.mkdir(path.dirname(target), { recursive: true });
50
+ }
51
+
52
+ // Phase 4 AGI Upgrade: Atomic File Swap
53
+ // Prevent zero-byte file corruption if Node crashes during a huge write.
54
+ const tempPath = `${target}.causyne_tmp_${Date.now()}`;
55
+ await fs.writeFile(tempPath, args.content, 'utf8');
56
+
57
+ // Atomic rename (POSIX standard guarantee)
58
+ await fs.rename(tempPath, target);
59
+
60
+ return { success: true, output: `Atomically wrote ${Buffer.byteLength(args.content, 'utf8')} bytes to ${args.path}` };
61
+ } catch (e: unknown) {
62
+ const msg = e instanceof Error ? e.message : String(e);
63
+ return { success: false, error: `Atomic Write Failed: ${msg}` };
64
+ }
65
+ }
66
+ };
@@ -331,6 +331,21 @@ export function repairJsonArguments(rawInput) {
331
331
  }
332
332
  }
333
333
  catch (err) {
334
+ const trimmed = trimExtraneousTrailingJsonTokens(healed);
335
+ if (trimmed !== healed) {
336
+ try {
337
+ const parsed = JSON.parse(trimmed);
338
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
339
+ return { args: parsed, repaired: true, repairs: [...repairs, 'Trimmed extraneous trailing tokens'] };
340
+ }
341
+ if (Array.isArray(parsed)) {
342
+ return { args: { items: parsed }, repaired: true, repairs: [...repairs, 'Wrapped array payload into items'] };
343
+ }
344
+ }
345
+ catch {
346
+ // Fall through to error
347
+ }
348
+ }
334
349
  const errorMsg = err instanceof Error ? err.message : String(err);
335
350
  return {
336
351
  args: {},
@@ -342,22 +357,65 @@ export function repairJsonArguments(rawInput) {
342
357
  return { args: {}, repaired: false, repairs };
343
358
  }
344
359
  /**
345
- * Handle unescaped newlines/tabs inside string literals without breaking valid JSON escapes.
360
+ * Trim extraneous trailing braces, brackets, or tokens after the root JSON object/array closes.
361
+ */
362
+ function trimExtraneousTrailingJsonTokens(input) {
363
+ const str = input.trim();
364
+ if (!str.startsWith('{') && !str.startsWith('['))
365
+ return input;
366
+ let depth = 0;
367
+ let inString = false;
368
+ let escapeNext = false;
369
+ for (let i = 0; i < str.length; i++) {
370
+ const char = str[i] ?? '';
371
+ if (escapeNext) {
372
+ escapeNext = false;
373
+ continue;
374
+ }
375
+ if (char === '\\') {
376
+ escapeNext = true;
377
+ continue;
378
+ }
379
+ if (char === '"') {
380
+ inString = !inString;
381
+ continue;
382
+ }
383
+ if (inString)
384
+ continue;
385
+ if (char === '{' || char === '[') {
386
+ depth++;
387
+ }
388
+ else if (char === '}' || char === ']') {
389
+ depth--;
390
+ if (depth === 0) {
391
+ return str.slice(0, i + 1);
392
+ }
393
+ }
394
+ }
395
+ return input;
396
+ }
397
+ /**
398
+ * Handle unescaped newlines/tabs and invalid backslash escapes inside string literals without breaking valid JSON escapes.
346
399
  */
347
400
  function sanitizeUnescapedStringLiterals(input) {
348
401
  let result = '';
349
402
  let inString = false;
350
403
  let escapeNext = false;
404
+ const validEscapes = new Set(['"', '\\', '/', 'b', 'f', 'n', 'r', 't', 'u']);
351
405
  for (let i = 0; i < input.length; i++) {
352
- const char = input[i];
406
+ const char = input[i] ?? '';
353
407
  if (escapeNext) {
354
- result += char;
408
+ if (validEscapes.has(char)) {
409
+ result += '\\' + char;
410
+ }
411
+ else {
412
+ result += '\\\\' + char;
413
+ }
355
414
  escapeNext = false;
356
415
  continue;
357
416
  }
358
417
  if (char === '\\') {
359
418
  escapeNext = true;
360
- result += char;
361
419
  continue;
362
420
  }
363
421
  if (char === '"') {
@@ -381,6 +439,9 @@ function sanitizeUnescapedStringLiterals(input) {
381
439
  }
382
440
  result += char;
383
441
  }
442
+ if (escapeNext) {
443
+ result += '\\\\';
444
+ }
384
445
  return result;
385
446
  }
386
447
  /**
@@ -404,7 +465,7 @@ function balanceTruncatedJson(input, repairs) {
404
465
  let inString = false;
405
466
  let escapeNext = false;
406
467
  for (let i = 0; i < str.length; i++) {
407
- const char = str[i];
468
+ const char = str[i] ?? '';
408
469
  if (escapeNext) {
409
470
  escapeNext = false;
410
471
  continue;
@@ -375,6 +375,20 @@ export function repairJsonArguments(rawInput: unknown): RepairResult {
375
375
  return { args: { items: parsed }, repaired: true, repairs: [...repairs, 'Wrapped array payload into items'] };
376
376
  }
377
377
  } catch (err: unknown) {
378
+ const trimmed = trimExtraneousTrailingJsonTokens(healed);
379
+ if (trimmed !== healed) {
380
+ try {
381
+ const parsed = JSON.parse(trimmed);
382
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
383
+ return { args: parsed as Record<string, unknown>, repaired: true, repairs: [...repairs, 'Trimmed extraneous trailing tokens'] };
384
+ }
385
+ if (Array.isArray(parsed)) {
386
+ return { args: { items: parsed }, repaired: true, repairs: [...repairs, 'Wrapped array payload into items'] };
387
+ }
388
+ } catch {
389
+ // Fall through to error
390
+ }
391
+ }
378
392
  const errorMsg = err instanceof Error ? err.message : String(err);
379
393
  return {
380
394
  args: {},
@@ -388,25 +402,65 @@ export function repairJsonArguments(rawInput: unknown): RepairResult {
388
402
  }
389
403
 
390
404
  /**
391
- * Handle unescaped newlines/tabs inside string literals without breaking valid JSON escapes.
405
+ * Trim extraneous trailing braces, brackets, or tokens after the root JSON object/array closes.
406
+ */
407
+ function trimExtraneousTrailingJsonTokens(input: string): string {
408
+ const str = input.trim();
409
+ if (!str.startsWith('{') && !str.startsWith('[')) return input;
410
+ let depth = 0;
411
+ let inString = false;
412
+ let escapeNext = false;
413
+ for (let i = 0; i < str.length; i++) {
414
+ const char = str[i] ?? '';
415
+ if (escapeNext) {
416
+ escapeNext = false;
417
+ continue;
418
+ }
419
+ if (char === '\\') {
420
+ escapeNext = true;
421
+ continue;
422
+ }
423
+ if (char === '"') {
424
+ inString = !inString;
425
+ continue;
426
+ }
427
+ if (inString) continue;
428
+ if (char === '{' || char === '[') {
429
+ depth++;
430
+ } else if (char === '}' || char === ']') {
431
+ depth--;
432
+ if (depth === 0) {
433
+ return str.slice(0, i + 1);
434
+ }
435
+ }
436
+ }
437
+ return input;
438
+ }
439
+
440
+ /**
441
+ * Handle unescaped newlines/tabs and invalid backslash escapes inside string literals without breaking valid JSON escapes.
392
442
  */
393
443
  function sanitizeUnescapedStringLiterals(input: string): string {
394
444
  let result = '';
395
445
  let inString = false;
396
446
  let escapeNext = false;
447
+ const validEscapes = new Set(['"', '\\', '/', 'b', 'f', 'n', 'r', 't', 'u']);
397
448
 
398
449
  for (let i = 0; i < input.length; i++) {
399
- const char = input[i];
450
+ const char = input[i] ?? '';
400
451
 
401
452
  if (escapeNext) {
402
- result += char;
453
+ if (validEscapes.has(char)) {
454
+ result += '\\' + char;
455
+ } else {
456
+ result += '\\\\' + char;
457
+ }
403
458
  escapeNext = false;
404
459
  continue;
405
460
  }
406
461
 
407
462
  if (char === '\\') {
408
463
  escapeNext = true;
409
- result += char;
410
464
  continue;
411
465
  }
412
466
 
@@ -434,6 +488,10 @@ function sanitizeUnescapedStringLiterals(input: string): string {
434
488
  result += char;
435
489
  }
436
490
 
491
+ if (escapeNext) {
492
+ result += '\\\\';
493
+ }
494
+
437
495
  return result;
438
496
  }
439
497
 
@@ -460,7 +518,7 @@ function balanceTruncatedJson(input: string, repairs: string[]): string {
460
518
  let escapeNext = false;
461
519
 
462
520
  for (let i = 0; i < str.length; i++) {
463
- const char = str[i];
521
+ const char = str[i] ?? '';
464
522
  if (escapeNext) {
465
523
  escapeNext = false;
466
524
  continue;