@causyne/agent 1.20.117 → 1.20.120

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 (82) hide show
  1. package/package.json +7 -2
  2. package/src/agentLoop.js +29 -12
  3. package/src/agentLoop.ts +29 -16
  4. package/src/browser/causyneBrowser.js +231 -136
  5. package/src/browser/causyneBrowser.ts +229 -140
  6. package/src/browser/searchProviders.js +41 -30
  7. package/src/browser/searchProviders.ts +24 -14
  8. package/src/browser/workspacePathSafety.js +50 -0
  9. package/src/browser/workspacePathSafety.ts +50 -0
  10. package/src/browser/workspacePreview.js +27 -4
  11. package/src/browser/workspacePreview.ts +28 -4
  12. package/src/cliMode.js +20 -4
  13. package/src/commands.js +12 -14
  14. package/src/creative/liveBridge.js +34 -1
  15. package/src/creative/liveBridge.ts +28 -1
  16. package/src/observer/evidence.js +23 -0
  17. package/src/observer/evidence.ts +21 -0
  18. package/src/plugins/pluginManager.js +74 -0
  19. package/src/providers/anthropic.js +33 -17
  20. package/src/providers/base.js +14 -0
  21. package/src/providers/dashscope-byok.js +13 -7
  22. package/src/providers/deepseek.js +13 -18
  23. package/src/providers/gemini.js +33 -25
  24. package/src/providers/moonshot.js +13 -12
  25. package/src/providers/ollama.js +21 -21
  26. package/src/providers/openai-compatible.js +12 -19
  27. package/src/providers/openrouter.js +20 -90
  28. package/src/providers/openrouter.ts +31 -94
  29. package/src/providers/qwen-byok.js +13 -7
  30. package/src/providers/toolContracts.js +9 -3
  31. package/src/providers/toolContracts.ts +9 -3
  32. package/src/providers/wireNormalizer.js +238 -0
  33. package/src/providers/wireNormalizer.ts +279 -0
  34. package/src/providers/xai.js +13 -12
  35. package/src/reporting.js +12 -4
  36. package/src/skillsManager.js +3 -2
  37. package/src/skillsManager.ts +3 -2
  38. package/src/tools/browserAutomator.js +13 -1
  39. package/src/tools/browserAutomator.ts +13 -0
  40. package/src/tools/creativeApps.js +2 -1
  41. package/src/tools/creativeApps.ts +2 -1
  42. package/src/tools/gameAssetFetcher.js +130 -26
  43. package/src/tools/gameAssetHarvester.js +80 -58
  44. package/src/tools/nativeEngine.js +1 -1
  45. package/src/tools/nativeEngine.ts +1 -1
  46. package/src/tools/pluginManager.js +17 -2
  47. package/src/tools/registry.js +13 -0
  48. package/src/tools/toolScanner.js +596 -140
  49. package/src/tools/toolScanner.ts +665 -147
  50. package/src/tools/toolSelfRepair.js +243 -114
  51. package/src/tools/toolSelfRepair.ts +262 -111
  52. package/src/tools/webFetch.js +161 -24
  53. package/src/tools/webFetch.ts +157 -22
  54. package/src/tools/webSearch.js +33 -4
  55. package/src/tools/webSearch.ts +27 -4
  56. package/src/tui/composerControls.js +16 -3
  57. package/src/tui/composerControls.ts +14 -3
  58. package/src/tui/prompt.js +122 -16
  59. package/src/tui/sessionPicker.js +132 -35
  60. package/src/tui/sessionPicker.ts +153 -32
  61. package/src/tui/sessionPickerView.js +277 -34
  62. package/src/tui/sessionPickerView.ts +328 -34
  63. package/src/tui/statusLine.js +3 -0
  64. package/src/tui/statusLine.ts +5 -0
  65. package/src/tui/usageCard.js +119 -47
  66. package/src/tui/usageCard.ts +133 -49
  67. package/src/tui/workspaceIdentity.js +133 -0
  68. package/src/tui/workspaceIdentity.ts +146 -0
  69. package/src/tui/workspaceSwitch.js +2 -0
  70. package/src/tui/workspaceSwitch.ts +1 -0
  71. package/src/verification/boundedExplorer.js +119 -0
  72. package/src/verification/cliProbe.js +116 -0
  73. package/src/verification/featureMap.js +78 -0
  74. package/src/verification/interactivePty.js +188 -0
  75. package/src/verification/propertyProbe.js +121 -0
  76. package/src/verification/ptyProbe.js +125 -0
  77. package/src/verification/skillCatalog.d.ts +1 -0
  78. package/src/verification/skillCatalog.js +60 -0
  79. package/src/verification/statechart.js +143 -0
  80. package/src/verification/uiRuntime.js +57 -0
  81. package/src/verificationPlan.js +1 -1
  82. package/src/verificationPlan.ts +1 -1
@@ -0,0 +1,146 @@
1
+ // Dynamic canonical workspace identity & display helpers for Causyne Agent TUI.
2
+ // Authored in Strict TypeScript. Never hardcodes user or project workspace names.
3
+ // Source-available under BUSL-1.1.
4
+
5
+ import fs from 'node:fs';
6
+ import os from 'node:os';
7
+ import path from 'node:path';
8
+ import { safeDisplay } from './text.js';
9
+
10
+ function cleanInlineText(value: unknown): string {
11
+ return safeDisplay(typeof value === 'string' ? value : String(value ?? ''))
12
+ .replace(/[\r\n\t]+/g, ' ')
13
+ .trim();
14
+ }
15
+
16
+ function getUserHomeDir(): string {
17
+ const fromEnv = process.env.HOME || process.env.USERPROFILE || '';
18
+ if (fromEnv && fromEnv.trim()) return fromEnv.trim();
19
+ try {
20
+ return os.homedir() || '';
21
+ } catch {
22
+ return '';
23
+ }
24
+ }
25
+
26
+ function isDriveRoot(value: string): boolean {
27
+ return value.length >= 2
28
+ && value.length <= 3
29
+ && ((value[0]! >= 'A' && value[0]! <= 'Z') || (value[0]! >= 'a' && value[0]! <= 'z'))
30
+ && value[1] === ':'
31
+ && (value.length === 2 || value[2] === '\\' || value[2] === '/');
32
+ }
33
+
34
+ /**
35
+ * Resolve a workspace path into a canonical comparison key.
36
+ * Resolves symlinks (for example `/tmp` vs `/private/tmp` on macOS) when the
37
+ * directory exists on disk, falling back to `path.resolve()` otherwise.
38
+ */
39
+ export function canonicalWorkspacePath(
40
+ workspacePath: string | undefined,
41
+ cache?: Map<string, string>
42
+ ): string {
43
+ if (typeof workspacePath !== 'string') return '';
44
+ const trimmed = workspacePath.trim();
45
+ if (!trimmed) return '';
46
+
47
+ const resolved = path.resolve(trimmed);
48
+ const cached = cache?.get(resolved);
49
+ if (cached !== undefined) return cached;
50
+
51
+ let canonical = resolved;
52
+ try {
53
+ canonical = typeof fs.realpathSync.native === 'function'
54
+ ? fs.realpathSync.native(resolved)
55
+ : fs.realpathSync(resolved);
56
+ } catch {
57
+ // Missing or synthetic paths keep their lexical resolved form.
58
+ }
59
+
60
+ const normalized = process.platform === 'win32' ? canonical.toLowerCase() : canonical;
61
+ if (cache) cache.set(resolved, normalized);
62
+ return normalized;
63
+ }
64
+
65
+ /**
66
+ * True when two workspace paths refer to the same canonical directory.
67
+ */
68
+ export function sameWorkspace(
69
+ first: string | undefined,
70
+ second: string | undefined,
71
+ cache?: Map<string, string>
72
+ ): boolean {
73
+ const a = canonicalWorkspacePath(first, cache);
74
+ const b = canonicalWorkspacePath(second, cache);
75
+ return a.length > 0 && a === b;
76
+ }
77
+
78
+ /**
79
+ * Shorten a workspace path for display by replacing the exact home prefix with `~`.
80
+ * Always sanitized for safe single-line terminal rendering.
81
+ */
82
+ export function shortenWorkspacePath(workspacePath: string | undefined): string {
83
+ if (typeof workspacePath !== 'string' || !workspacePath.trim()) return '(default)';
84
+ const trimmed = workspacePath.trim();
85
+ const home = getUserHomeDir();
86
+ if (home) {
87
+ const resolved = path.resolve(trimmed);
88
+ const resolvedHome = path.resolve(home);
89
+ const cmpResolved = process.platform === 'win32' ? resolved.toLowerCase() : resolved;
90
+ const cmpHome = process.platform === 'win32' ? resolvedHome.toLowerCase() : resolvedHome;
91
+ if (cmpResolved === cmpHome) return '~';
92
+ const prefix = cmpHome.endsWith(path.sep) ? cmpHome : `${cmpHome}${path.sep}`;
93
+ if (cmpResolved.startsWith(prefix)) {
94
+ const tail = resolved.slice(resolvedHome.length);
95
+ return cleanInlineText(`~${tail}`) || '~';
96
+ }
97
+ }
98
+ return cleanInlineText(trimmed) || '(default)';
99
+ }
100
+
101
+ /**
102
+ * Dynamically derive the human-readable workspace folder name from any path
103
+ * without hardcoding user or repository names.
104
+ */
105
+ export function workspaceDisplayName(
106
+ workspacePath: string | undefined,
107
+ cache?: Map<string, string>
108
+ ): string {
109
+ if (typeof workspacePath !== 'string' || !workspacePath.trim()) return 'Current Workspace';
110
+ const trimmed = workspacePath.trim();
111
+ const resolved = path.resolve(trimmed);
112
+ const home = getUserHomeDir();
113
+ if (home && sameWorkspace(resolved, home, cache)) {
114
+ return '~';
115
+ }
116
+ const base = path.basename(resolved);
117
+ const cleanBase = cleanInlineText(base);
118
+ if (cleanBase) return cleanBase;
119
+ const cleanRoot = cleanInlineText(resolved);
120
+ return cleanRoot || 'Current Workspace';
121
+ }
122
+
123
+ /**
124
+ * Format the dynamic section header label for the active workspace's sessions.
125
+ * Preserves the user's folder casing (for example `suika-game SESSIONS (2)` or
126
+ * `causyne-agent SESSIONS (0)`) while handling home and filesystem roots cleanly.
127
+ */
128
+ export function formatWorkspaceSectionTitle(
129
+ workspacePath: string | undefined,
130
+ sessionCount?: number,
131
+ cache?: Map<string, string>
132
+ ): string {
133
+ const name = workspaceDisplayName(workspacePath, cache);
134
+ let base: string;
135
+ if (name === '~') {
136
+ base = 'HOME (~) SESSIONS';
137
+ } else if (name === '/' || isDriveRoot(name)) {
138
+ base = `WORKSPACE (${name}) SESSIONS`;
139
+ } else {
140
+ base = `${name} SESSIONS`;
141
+ }
142
+ if (typeof sessionCount === 'number' && Number.isFinite(sessionCount) && sessionCount >= 0) {
143
+ return `${base} (${Math.floor(sessionCount)})`;
144
+ }
145
+ return base;
146
+ }
@@ -33,6 +33,8 @@ export function switchChatWorkspace({ workspaceRoot, createLoop, prompt = null,
33
33
  // queued attachments or active skills from the previous workspace.
34
34
  prompt.pendingAttachments = [];
35
35
  prompt.completion = null;
36
+ if (typeof prompt.refreshPinnedPanels === 'function')
37
+ prompt.refreshPinnedPanels(replacement);
36
38
  if (typeof prompt.scheduleDraw === 'function')
37
39
  prompt.scheduleDraw();
38
40
  }
@@ -60,6 +60,7 @@ export function switchChatWorkspace<TLoop extends {
60
60
  // queued attachments or active skills from the previous workspace.
61
61
  prompt.pendingAttachments = [];
62
62
  prompt.completion = null;
63
+ if (typeof prompt.refreshPinnedPanels === 'function') prompt.refreshPinnedPanels(replacement);
63
64
  if (typeof prompt.scheduleDraw === 'function') prompt.scheduleDraw();
64
65
  }
65
66
 
@@ -0,0 +1,119 @@
1
+ const DEFAULT_DEPTH = 6;
2
+ const DEFAULT_STATES = 10_000;
3
+
4
+ function boundedInteger(value, fallback, maximum) {
5
+ if (value === undefined) return fallback;
6
+ if (!Number.isSafeInteger(value) || value < 0 || value > maximum) {
7
+ throw new RangeError('Invalid exploration bound');
8
+ }
9
+ return value;
10
+ }
11
+
12
+ export function exploreStateMachine(options) {
13
+ const { initial, actions, transition, invariant } = options || {};
14
+ if (!Array.isArray(actions) || actions.length === 0) throw new TypeError('actions must be nonempty');
15
+ if (actions.length > 10000) throw new RangeError('Too many actions to explore safely');
16
+ if (typeof transition !== 'function') throw new TypeError('transition must be a function');
17
+ if (typeof invariant !== 'function') throw new TypeError('invariant must be a function');
18
+
19
+ if (initial && typeof initial.then === 'function') {
20
+ throw new TypeError('Async initial state is not supported by synchronous model exploration');
21
+ }
22
+ const maxDepth = boundedInteger(options.maxDepth, DEFAULT_DEPTH, 32);
23
+ const maxStates = boundedInteger(options.maxStates, DEFAULT_STATES, 100_000);
24
+ if (maxStates === 0) throw new RangeError('maxStates must be positive');
25
+ const key = options.stateKey || JSON.stringify;
26
+ if (typeof key !== 'function') throw new TypeError('stateKey must be a function');
27
+
28
+ const checkedState = value => {
29
+ try { return structuredClone(value); }
30
+ catch { throw new TypeError('State must be structured-cloneable for sound bounded exploration'); }
31
+ };
32
+ const checkedAction = value => {
33
+ try { return structuredClone(value); }
34
+ catch { throw new TypeError('Actions must be structured-cloneable for sound bounded exploration'); }
35
+ };
36
+ const stableActions = actions.map(checkedAction);
37
+ const startState = checkedState(initial);
38
+ const startKey = key(checkedState(startState));
39
+ if (startKey && typeof startKey.then === 'function') {
40
+ throw new TypeError('Async stateKey is not supported');
41
+ }
42
+ if (typeof startKey !== 'string') throw new TypeError('stateKey must produce a string');
43
+ let nodesVisited = 1;
44
+ let transitions = 0;
45
+ let deepest = 0;
46
+ const root = { state: startState, trace: [] };
47
+ const queue = [root];
48
+ const seen = new Set([startKey]);
49
+
50
+ function failed(node) {
51
+ const result = invariant(checkedState(node.state));
52
+ if (result && typeof result.then === 'function') {
53
+ throw new TypeError('Async invariants are not supported');
54
+ }
55
+ if (result === true) return null;
56
+ return {
57
+ status: 'counterexample',
58
+ depthLimit: maxDepth,
59
+ statesExplored: nodesVisited,
60
+ transitionsExplored: transitions,
61
+ exploredDepth: node.trace.length,
62
+ trace: node.trace,
63
+ state: node.state,
64
+ reason: typeof result === 'string' ? result : 'Invariant returned false'
65
+ };
66
+ }
67
+
68
+ const initialFailure = failed(root);
69
+ if (initialFailure) return initialFailure;
70
+ for (let head = 0; head < queue.length; head++) {
71
+ const current = queue[head];
72
+ deepest = Math.max(deepest, current.trace.length);
73
+ if (current.trace.length >= maxDepth) continue;
74
+ for (const action of stableActions) {
75
+ // Each branch must start from the same immutable snapshot. A mutating
76
+ // transition otherwise poisons later siblings and can produce false proofs.
77
+ const isolated = checkedState(current.state);
78
+ const next = transition(isolated, checkedAction(action));
79
+ if (next && typeof next.then === 'function') {
80
+ throw new TypeError('Async transitions are not supported');
81
+ }
82
+ transitions++;
83
+ if (next === null || next === undefined) continue;
84
+ const trace = current.trace.concat(action);
85
+ const nextNode = { state: next, trace };
86
+ const failure = failed(nextNode);
87
+ if (failure) return failure;
88
+ const identity = key(checkedState(next));
89
+ if (identity && typeof identity.then === 'function') {
90
+ throw new TypeError('Async stateKey is not supported');
91
+ }
92
+ if (typeof identity !== 'string') throw new TypeError('stateKey must produce a string');
93
+ if (seen.has(identity)) continue;
94
+ if (nodesVisited >= maxStates) {
95
+ return {
96
+ status: 'incomplete',
97
+ depthLimit: maxDepth,
98
+ statesExplored: nodesVisited,
99
+ transitionsExplored: transitions,
100
+ exploredDepth: trace.length,
101
+ trace: [],
102
+ reason: 'Exploration reached maxStates before completing the bound'
103
+ };
104
+ }
105
+ seen.add(identity);
106
+ nodesVisited++;
107
+ queue.push(nextNode);
108
+ }
109
+ }
110
+ return {
111
+ status: 'bounded-pass',
112
+ depthLimit: maxDepth,
113
+ statesExplored: nodesVisited,
114
+ transitionsExplored: transitions,
115
+ exploredDepth: deepest,
116
+ trace: [],
117
+ reason: 'Invariant holds for reachable states within the stated bound; not an unbounded proof'
118
+ };
119
+ }
@@ -0,0 +1,116 @@
1
+ import { spawn } from 'node:child_process';
2
+ import path from 'node:path';
3
+ import { realpathSync } from 'node:fs';
4
+
5
+ function inside(root, candidate) {
6
+ const lexicalRoot = path.resolve(root);
7
+ const base = realpathSync(root);
8
+ const lexical = path.relative(lexicalRoot, path.resolve(candidate));
9
+ if (lexical === '..' || lexical.startsWith('..' + path.sep) || path.isAbsolute(lexical)) return false;
10
+ let target;
11
+ try {
12
+ target = realpathSync(candidate);
13
+ } catch (error) {
14
+ if (error?.code === 'ENOENT') return true;
15
+ throw error;
16
+ }
17
+ const relative = path.relative(base, target);
18
+ return relative === '' || (relative !== '..' && !relative.startsWith('..' + path.sep) && !path.isAbsolute(relative));
19
+ }
20
+
21
+ export async function runCliProbe(options) {
22
+ const { workspace, program, args = [], timeoutMs = 8_000, outputLimit = 32_768,
23
+ expectedExitCode = 0, contains = null } = options || {};
24
+ if (typeof workspace !== 'string' || typeof program !== 'string'
25
+ || !Array.isArray(args) || !args.every(a => typeof a === 'string')) {
26
+ throw new TypeError('workspace, program, and string argv are required');
27
+ }
28
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 10 || timeoutMs > 60_000) {
29
+ throw new RangeError('timeoutMs must be between 10 and 60000');
30
+ }
31
+ if (!Number.isSafeInteger(outputLimit) || outputLimit < 64 || outputLimit > 1_048_576) {
32
+ throw new RangeError('outputLimit must be between 64 and 1048576');
33
+ }
34
+ if (!Number.isInteger(expectedExitCode) || expectedExitCode < 0 || expectedExitCode > 255) {
35
+ throw new RangeError('invalid expectedExitCode');
36
+ }
37
+ if (contains !== null && (typeof contains !== 'string' || contains.length > 1000)) {
38
+ throw new TypeError('contains must be a bounded string');
39
+ }
40
+ const cwd = path.resolve(workspace);
41
+ if (program !== 'node' && !path.isAbsolute(program)
42
+ && !program.includes('/') && !program.includes('\\')) {
43
+ throw new Error('Executable must be an explicit workspace path or node');
44
+ }
45
+ const executable = program === 'node' ? process.execPath : program;
46
+ const resolvedProgram = path.isAbsolute(executable) ? executable
47
+ : executable.includes('/') || executable.includes('\\') ? path.resolve(cwd, executable) : executable;
48
+ if (!inside(cwd, cwd)) throw new Error('Invalid workspace');
49
+ if ((executable.includes('/') || executable.includes('\\')) && !inside(cwd, resolvedProgram)
50
+ && resolvedProgram !== process.execPath) {
51
+ throw new Error('Executable must remain inside workspace');
52
+ }
53
+
54
+ const started = Date.now();
55
+ return new Promise(resolve => {
56
+ let stdout = '';
57
+ let stderr = '';
58
+ let usedBytes = 0;
59
+ let truncated = false;
60
+ let timedOut = false;
61
+ let exitCode = null;
62
+ let signal = null;
63
+ let spawnError = null;
64
+ let settled = false;
65
+ let child;
66
+ let timer;
67
+ const finish = () => {
68
+ if (settled) return;
69
+ settled = true;
70
+ if (timer) clearTimeout(timer);
71
+ const success = !timedOut && !spawnError && exitCode === expectedExitCode
72
+ && !truncated && (contains === null || (stdout + stderr).includes(contains));
73
+ resolve({
74
+ status: success ? 'observed-pass' : 'observed-fail',
75
+ success, command: { program, args, workspace: cwd },
76
+ exitCode, signal, timedOut, truncated, stdout, stderr,
77
+ error: spawnError, durationMs: Math.max(0, Date.now() - started),
78
+ surface: 'cli-pipe',
79
+ limitation: 'A pipe subprocess does not verify terminal rendering, mouse events, or desktop UI behavior'
80
+ });
81
+ };
82
+ const collect = (field, chunk) => {
83
+ const data = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk));
84
+ const available = Math.max(0, outputLimit - usedBytes);
85
+ if (data.length > available) truncated = true;
86
+ if (available) {
87
+ const safe = data.subarray(0, available).toString('utf8');
88
+ if (field === 'stdout') stdout += safe;
89
+ else stderr += safe;
90
+ usedBytes += Math.min(available, data.length);
91
+ }
92
+ };
93
+ try {
94
+ child = spawn(resolvedProgram, args, {
95
+ cwd, shell: false, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true,
96
+ env: { ...process.env, CAUSYNE_VERIFY_PROBE: '1' }
97
+ });
98
+ child.stdout?.on('data', chunk => collect('stdout', chunk));
99
+ child.stderr?.on('data', chunk => collect('stderr', chunk));
100
+ child.on('error', error => { spawnError = String(error.message || error); finish(); });
101
+ child.on('close', (code, sig) => {
102
+ exitCode = code;
103
+ signal = sig;
104
+ finish();
105
+ });
106
+ timer = setTimeout(() => {
107
+ timedOut = true;
108
+ child.kill('SIGKILL');
109
+ }, timeoutMs);
110
+ timer.unref?.();
111
+ } catch (error) {
112
+ spawnError = String(error?.message || error);
113
+ finish();
114
+ }
115
+ });
116
+ }
@@ -0,0 +1,78 @@
1
+ export const FEATURE_MAP = Object.freeze({
2
+ 'tui-usage': {
3
+ surface: 'terminal',
4
+ entry: '/usage and /status',
5
+ action: 'Open the panel, submit a message, switch busy state, close with Escape',
6
+ assertion: 'The panel stays visible until explicitly dismissed',
7
+ automated: ['tests/tuiPinnedUsageStatus.test.ts', 'tests/usageCard.test.ts'],
8
+ liveDriver: 'posix-pty-chat',
9
+ liveRequired: 'Drive ChatPrompt, StageSurface, and chatMode in isolated PTYs; packaged launcher and host mouse pixels remain separate'
10
+ },
11
+ 'tui-turn-rail': {
12
+ surface: 'terminal',
13
+ entry: 'Left conversation navigation rail',
14
+ action: 'Hover grouped dots, choose a turn, scroll its timeline preview',
15
+ assertion: 'The selected turn opens without scrolling terminal scrollback',
16
+ automated: ['tests/tuiTurnTimelineVideoParity.test.ts', 'tests/tuiTurnTimelineWheel.test.ts'],
17
+ liveRequired: 'Inspect pointer movement, popup geometry and wheel handling in a real terminal'
18
+ },
19
+ 'agent-loop': {
20
+ surface: 'agent',
21
+ entry: 'Submit a task with tool calls and retry conditions',
22
+ action: 'Execute, interrupt, resume, and inspect evidence-gated completion',
23
+ assertion: 'No fabricated completion or unhandled failed tool response',
24
+ automated: ['tests/agentLoopFixes.test.ts', 'tests/agentLoopHookSeams.test.js'],
25
+ liveRequired: 'Run a real task in the selected workspace with explicitly permitted tools'
26
+ },
27
+ 'web-preview': {
28
+ surface: 'browser',
29
+ entry: 'browser_act preview, snapshot and screenshot',
30
+ action: 'Open the built page and inspect the DOM and rendered pixels',
31
+ assertion: 'The page is reachable and its actual visual state matches the request',
32
+ automated: ['tests/webVerificationState.test.ts'],
33
+ liveRequired: 'Use the Causyne Browser to capture a fresh screenshot after the latest edit'
34
+ },
35
+ 'plugin-safety': {
36
+ surface: 'plugin',
37
+ entry: 'Enabled plugin skills via the plugin manager',
38
+ action: 'Read a permitted skill and reject an unapproved or invalid plugin',
39
+ assertion: 'Digest-pinned plugin permissions remain mandatory',
40
+ automated: ['tests/plugins.test.js', 'tests/skillsReliability.test.js'],
41
+ liveRequired: 'Check a separately approved plugin against the current permission record'
42
+ },
43
+ 'terminal-pty': {
44
+ surface: 'terminal',
45
+ entry: 'An explicitly selected interactive program and input sequence',
46
+ action: 'Launch the real program in a pseudo-terminal and capture exit, input and output evidence',
47
+ assertion: 'A PTY pass requires observed terminal output and the expected process exit',
48
+ automated: ['tests/verificationPtyProbe.test.ts'],
49
+ liveRequired: 'The smoke fixture only tests the PTY driver; user-app behavior needs a separate real app session'
50
+ },
51
+ 'ui-properties': {
52
+ surface: 'terminal',
53
+ entry: 'Seeded UI interaction and runtime state handlers',
54
+ action: 'Generate bounded action sequences, shrink counterexamples and replay real prompt transitions',
55
+ assertion: 'Panels persist until explicit close; counterexamples retain their original failure identity',
56
+ automated: ['tests/verificationPropertyProbe.test.ts'],
57
+ liveRequired: 'Seeded handler checks do not establish terminal rendering or cross-process races'
58
+ },
59
+ 'formal-state': {
60
+ surface: 'model',
61
+ entry: 'verification/formal-verification',
62
+ action: 'Explore bounded state transitions and inject a deliberately broken variant',
63
+ assertion: 'Counterexamples are reproducible and a bounded pass is not claimed as a proof',
64
+ automated: ['tests/boundedExplorer.test.ts', 'tests/cliProbe.test.ts'],
65
+ liveRequired: 'For unbounded guarantees, run a real external model checker or proof assistant'
66
+ }
67
+ });
68
+
69
+ export function selectFeatures(names) {
70
+ if (!Array.isArray(names) || names.length === 0) throw new Error('At least one feature is required');
71
+ const selected = [...new Set(names)];
72
+ for (const name of selected) {
73
+ if (!Object.hasOwn(FEATURE_MAP, name)) {
74
+ throw new Error('Unknown feature: ' + String(name));
75
+ }
76
+ }
77
+ return selected.map(name => ({ id: name, ...FEATURE_MAP[name] }));
78
+ }
@@ -0,0 +1,188 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { realpathSync } from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+
6
+ const DRIVER = String.raw`import base64, fcntl, json, os, pty, select, signal, struct, sys, termios, time
7
+ cfg=json.loads(sys.argv[1])
8
+ pid,fd=pty.fork()
9
+ if pid==0:
10
+ os.chdir(cfg["cwd"])
11
+ os.environ["TERM"]="xterm-256color"
12
+ os.environ["COLUMNS"]=str(cfg["cols"])
13
+ os.environ["LINES"]=str(cfg["rows"])
14
+ os.execv(cfg["exec"],cfg["argv"])
15
+ fcntl.ioctl(fd,termios.TIOCSWINSZ,struct.pack("HHHH",cfg["rows"],cfg["cols"],0,0))
16
+ started=time.monotonic()
17
+ out=bytearray()
18
+ observations=[]
19
+ cursor=0
20
+ since=0
21
+ pending_enter=None
22
+ done=False
23
+ closed=False
24
+ timeout=False
25
+ overflow=False
26
+ exit_code=None
27
+ while True:
28
+ elapsed=(time.monotonic()-started)*1000
29
+ if pending_enter is not None and elapsed>=pending_enter[0]:
30
+ try: os.write(fd,pending_enter[1])
31
+ except OSError: pass
32
+ pending_enter=None
33
+ readable,_,_=select.select([fd],[],[],0.025)
34
+ if readable and not closed:
35
+ try: chunk=os.read(fd,16384)
36
+ except OSError: chunk=b""
37
+ if not chunk: closed=True
38
+ else:
39
+ room=max(0,cfg["limit"]-len(out))
40
+ if len(chunk)>room: overflow=True
41
+ out.extend(chunk[:room])
42
+ if cursor<len(cfg["steps"]) and not done and pending_enter is None:
43
+ step=cfg["steps"][cursor]
44
+ match=step["waitFor"]
45
+ segment=bytes(out[since:]).decode("utf-8",errors="replace")
46
+ if match in segment:
47
+ observation={"name":step["name"],"offset":len(out),"expected":step["contains"]}
48
+ observations.append(observation)
49
+ payload=base64.b64decode(step["input"])
50
+ # A real keyboard sends text then Enter. Combining both in one
51
+ # PTY write makes Causyne correctly classify it as a bulk paste.
52
+ if payload.endswith(b"\r") and len(payload)>1:
53
+ try: os.write(fd,payload[:-1])
54
+ except OSError: pass
55
+ pending_enter=((time.monotonic()-started)*1000+65,b"\r")
56
+ else:
57
+ try: os.write(fd,payload)
58
+ except OSError: pass
59
+ since=len(out)
60
+ cursor+=1
61
+ if not done:
62
+ got,status=os.waitpid(pid,os.WNOHANG)
63
+ if got:
64
+ done=True
65
+ exit_code=os.waitstatus_to_exitcode(status)
66
+ if done and closed: break
67
+ if elapsed>cfg["timeout"]:
68
+ timeout=True
69
+ if not done:
70
+ try: os.killpg(pid,signal.SIGKILL)
71
+ except ProcessLookupError: pass
72
+ try:
73
+ got,status=os.waitpid(pid,0)
74
+ exit_code=os.waitstatus_to_exitcode(status)
75
+ except ChildProcessError: pass
76
+ break
77
+ for n,item in enumerate(observations):
78
+ end=observations[n+1]["offset"] if n+1<len(observations) else len(out)
79
+ segment=bytes(out[item["offset"]:end]).decode("utf-8",errors="replace")
80
+ item["matched"]=item["expected"] in segment
81
+ item["bytes"]=end-item["offset"]
82
+ result={"exit":exit_code,"timeout":timeout,"truncated":overflow,
83
+ "completed":cursor==len(cfg["steps"]),"steps":observations,
84
+ "requested":len(cfg["steps"])}
85
+ os.write(1,bytes(out))
86
+ os.write(2,("CAUSYNE_UI_PTY_RESULT:"+json.dumps(result)+"\n").encode("utf-8"))`;
87
+
88
+ function bounded(value, min, max, label) {
89
+ if (!Number.isSafeInteger(value) || value < min || value > max) {
90
+ throw new RangeError('Invalid ' + label);
91
+ }
92
+ return value;
93
+ }
94
+
95
+ export async function runInteractivePty(options = {}) {
96
+ const {
97
+ workspace, script, steps, timeoutMs = 15000,
98
+ outputLimit = 1048576, rows = 42, columns = 126, env = {}
99
+ } = options;
100
+ if (typeof workspace !== 'string' || typeof script !== 'string'
101
+ || !Array.isArray(steps) || steps.length < 1 || steps.length > 12) {
102
+ throw new TypeError('workspace, script, and 1..12 interaction steps are required');
103
+ }
104
+ bounded(timeoutMs, 1000, 60000, 'timeoutMs');
105
+ bounded(outputLimit, 1024, 2097152, 'outputLimit');
106
+ bounded(rows, 20, 100, 'rows');
107
+ bounded(columns, 48, 240, 'columns');
108
+ for (const step of steps) {
109
+ if (!step || typeof step.name !== 'string' || !/^[\w-]{1,50}$/.test(step.name)
110
+ || typeof step.input !== 'string' || step.input.length > 2048
111
+ || typeof step.waitFor !== 'string' || !step.waitFor
112
+ || step.waitFor.length > 200 || typeof step.contains !== 'string'
113
+ || step.contains.length > 200) {
114
+ throw new TypeError('Each step requires bounded name, input, waitFor and contains strings');
115
+ }
116
+ }
117
+ if (!env || typeof env !== 'object' || Array.isArray(env)
118
+ || Object.keys(env).some(key => !['CAUSYNE_HOME'].includes(key))) {
119
+ throw new TypeError('Only an isolated CAUSYNE_HOME environment override is permitted');
120
+ }
121
+ if (typeof env.CAUSYNE_HOME !== 'string' || !path.isAbsolute(env.CAUSYNE_HOME)) {
122
+ throw new TypeError('An explicit isolated CAUSYNE_HOME path is required');
123
+ }
124
+ const tempRoot = realpathSync(os.tmpdir());
125
+ const isolatedHome = realpathSync(env.CAUSYNE_HOME);
126
+ const relativeHome = path.relative(tempRoot, isolatedHome);
127
+ if (!relativeHome || relativeHome === '..' || relativeHome.startsWith('..' + path.sep)
128
+ || path.isAbsolute(relativeHome)) {
129
+ throw new Error('Verification CAUSYNE_HOME must be an isolated temporary directory');
130
+ }
131
+ const cwd = realpathSync(workspace);
132
+ const target = realpathSync(path.resolve(cwd, script));
133
+ const relative = path.relative(cwd, target);
134
+ if (!relative || relative === '..' || relative.startsWith('..' + path.sep)
135
+ || path.isAbsolute(relative) || !/\.[cm]?js$/.test(target)) {
136
+ throw new Error('Interactive verification target must be a workspace JavaScript file');
137
+ }
138
+ if (process.platform === 'win32') {
139
+ return { status: 'unavailable', success: false, surface: 'none',
140
+ reason: 'A Windows ConPTY adapter has not been implemented' };
141
+ }
142
+ const cfg = {
143
+ cwd, exec: process.execPath, argv: [process.execPath, target],
144
+ rows, cols: columns, timeout: timeoutMs, limit: outputLimit,
145
+ steps: steps.map(step => ({
146
+ name: step.name, input: Buffer.from(step.input, 'utf8').toString('base64'),
147
+ waitFor: step.waitFor, contains: step.contains
148
+ }))
149
+ };
150
+ return new Promise(resolve => {
151
+ let stdout = '';
152
+ let stderr = '';
153
+ let spawnError = null;
154
+ const child = spawn('python3', ['-c', DRIVER, JSON.stringify(cfg)], {
155
+ cwd, shell: false, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'],
156
+ env: { ...process.env, ...env, TERM: 'xterm-256color',
157
+ COLUMNS: String(columns), LINES: String(rows), CAUSYNE_VERIFY_PROBE: '1' }
158
+ });
159
+ child.stdout.on('data', data => { stdout += data.toString('utf8'); });
160
+ child.stderr.on('data', data => { stderr += data.toString('utf8'); });
161
+ child.on('error', e => { spawnError = e; });
162
+ child.on('close', () => {
163
+ if (spawnError?.code === 'ENOENT') {
164
+ resolve({ status: 'unavailable', success: false, surface: 'none',
165
+ reason: 'python3 is required for POSIX terminal verification' });
166
+ return;
167
+ }
168
+ const marker = stderr.match(/CAUSYNE_UI_PTY_RESULT:(\{[^\r\n]+\})/);
169
+ let detail = null;
170
+ try { if (marker) detail = JSON.parse(marker[1]); } catch {}
171
+ const observations = Array.isArray(detail?.steps) ? detail.steps : [];
172
+ const success = Boolean(detail && !detail.timeout && !detail.truncated
173
+ && detail.completed && detail.exit === 0
174
+ && observations.length === steps.length
175
+ && observations.every(item => item.matched));
176
+ resolve({
177
+ status: success ? 'observed-pass' : 'observed-fail', success,
178
+ surface: detail ? 'posix-pty' : 'unverified',
179
+ exitCode: detail?.exit ?? null, timedOut: detail?.timeout ?? null,
180
+ truncated: detail?.truncated ?? null,
181
+ completed: detail?.completed ?? false, observations,
182
+ stdout, stderr: stderr.replace(/CAUSYNE_UI_PTY_RESULT:\{[^\r\n]+\}\r?\n?/, ''),
183
+ reason: detail ? null : (spawnError?.message || 'No valid PTY evidence'),
184
+ limitation: 'Actual TUI components run in a PTY; host screenshots, mouse forwarding, and the full CLI launch are separate checks'
185
+ });
186
+ });
187
+ });
188
+ }