@causyne/agent 1.20.112 → 1.20.116

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 (151) hide show
  1. package/docs/ARCHITECTURE.md +29 -0
  2. package/package.json +1 -1
  3. package/src/agentLoop.js +72 -37
  4. package/src/agentLoop.ts +70 -38
  5. package/src/browser/browserRuntime.js +13 -8
  6. package/src/browser/browserRuntime.ts +16 -8
  7. package/src/browser/causyneBrowser.js +7 -2
  8. package/src/browser/causyneBrowser.ts +8 -2
  9. package/src/browser/searchProviders.js +18 -7
  10. package/src/browser/searchProviders.ts +17 -5
  11. package/src/browser/snapshotWindow.js +1 -1
  12. package/src/browser/snapshotWindow.ts +1 -1
  13. package/src/browser/urlPolicy.js +21 -10
  14. package/src/browser/urlPolicy.ts +19 -10
  15. package/src/browser/workspacePreview.js +13 -1
  16. package/src/browser/workspacePreview.ts +11 -1
  17. package/src/computerUse/visionGrounding.js +31 -27
  18. package/src/computerUse/visionGrounding.ts +27 -27
  19. package/src/continuum/ui/continuumPicker.js +14 -6
  20. package/src/continuum/ui/continuumPicker.ts +13 -6
  21. package/src/continuum/ui/continuumPickerView.js +24 -15
  22. package/src/continuum/ui/continuumPickerView.ts +24 -16
  23. package/src/observer/advisory.js +32 -22
  24. package/src/observer/advisory.ts +30 -18
  25. package/src/observer/coldObserver.js +21 -33
  26. package/src/observer/coldObserver.ts +20 -33
  27. package/src/observer/evidence.js +20 -13
  28. package/src/observer/evidence.ts +21 -13
  29. package/src/observer.js +47 -12
  30. package/src/observer.ts +50 -18
  31. package/src/pluginsFactory/discovery.js +28 -16
  32. package/src/pluginsFactory/discovery.ts +29 -16
  33. package/src/pluginsFactory/pluginsFactory.js +213 -38
  34. package/src/pluginsFactory/pluginsFactory.ts +218 -39
  35. package/src/pluginsFactory/strategy.js +26 -16
  36. package/src/pluginsFactory/strategy.ts +34 -19
  37. package/src/pluginsFactory/templates.js +183 -62
  38. package/src/pluginsFactory/templates.ts +174 -54
  39. package/src/timeMachine.js +43 -22
  40. package/src/timeMachine.ts +44 -22
  41. package/src/tool-scripts/desktop_act.applescript +1 -0
  42. package/src/tools/computerUse.js +23 -10
  43. package/src/tools/computerUse.ts +19 -8
  44. package/src/tools/desktopAct.js +12 -1
  45. package/src/tools/pluginsFactory.js +108 -5
  46. package/src/tools/pluginsFactory.ts +115 -5
  47. package/src/tui/CausyneRotor.js +24 -10
  48. package/src/tui/CausyneRotor.ts +25 -10
  49. package/src/tui/activityLayout.js +9 -5
  50. package/src/tui/activityLayout.ts +9 -5
  51. package/src/tui/ask.js +34 -14
  52. package/src/tui/banner.js +55 -18
  53. package/src/tui/banner.ts +52 -17
  54. package/src/tui/block.js +47 -20
  55. package/src/tui/block.ts +54 -27
  56. package/src/tui/chatRenderer.js +135 -83
  57. package/src/tui/chatboxClipboard.js +12 -5
  58. package/src/tui/chatboxClipboard.ts +10 -4
  59. package/src/tui/clipboardImage.js +52 -42
  60. package/src/tui/clipboardImage.ts +50 -39
  61. package/src/tui/clipboardSync.js +12 -1
  62. package/src/tui/clipboardSync.ts +9 -1
  63. package/src/tui/codeProgress.js +57 -26
  64. package/src/tui/codeProgress.ts +57 -25
  65. package/src/tui/codeStreamRenderer.js +59 -14
  66. package/src/tui/codeStreamRenderer.ts +58 -14
  67. package/src/tui/commandPresentation.js +9 -2
  68. package/src/tui/commandPresentation.ts +9 -2
  69. package/src/tui/completion.js +45 -23
  70. package/src/tui/composerControls.js +21 -10
  71. package/src/tui/composerControls.ts +18 -10
  72. package/src/tui/composerGeometry.js +6 -4
  73. package/src/tui/composerGeometry.ts +6 -4
  74. package/src/tui/consoleGuard.js +29 -7
  75. package/src/tui/consoleGuard.ts +28 -7
  76. package/src/tui/dialogs.js +134 -71
  77. package/src/tui/diff.js +8 -4
  78. package/src/tui/history.js +6 -5
  79. package/src/tui/home.js +25 -13
  80. package/src/tui/homeView.js +37 -18
  81. package/src/tui/homeView.ts +38 -18
  82. package/src/tui/inlineSlash.js +6 -5
  83. package/src/tui/inlineSlash.ts +6 -5
  84. package/src/tui/keys.js +33 -17
  85. package/src/tui/layout.js +27 -9
  86. package/src/tui/layout.ts +26 -9
  87. package/src/tui/lineEditor.js +49 -23
  88. package/src/tui/markdownMath.js +64 -14
  89. package/src/tui/markdownMath.ts +69 -13
  90. package/src/tui/messageActionPlacement.js +28 -13
  91. package/src/tui/messageActionPlacement.ts +28 -13
  92. package/src/tui/messageInteraction.js +111 -46
  93. package/src/tui/messageInteraction.ts +115 -47
  94. package/src/tui/modelPicker.js +44 -15
  95. package/src/tui/modelPicker.ts +48 -15
  96. package/src/tui/observerPicker.js +56 -13
  97. package/src/tui/observerPicker.ts +73 -30
  98. package/src/tui/overlay.js +79 -35
  99. package/src/tui/overlay.ts +81 -34
  100. package/src/tui/prompt.js +162 -94
  101. package/src/tui/runningLight.js +1 -1
  102. package/src/tui/runningLight.ts +1 -1
  103. package/src/tui/scrollInteraction.js +64 -36
  104. package/src/tui/scrollInteraction.ts +70 -37
  105. package/src/tui/selectList.js +60 -32
  106. package/src/tui/sessionLayout.js +11 -3
  107. package/src/tui/sessionLayout.ts +10 -3
  108. package/src/tui/sessionPicker.js +74 -46
  109. package/src/tui/sessionPicker.ts +73 -48
  110. package/src/tui/sessionPickerView.js +32 -19
  111. package/src/tui/sessionPickerView.ts +31 -18
  112. package/src/tui/sessionSidebar.js +87 -57
  113. package/src/tui/sessionSidebar.ts +90 -54
  114. package/src/tui/setup.js +28 -3
  115. package/src/tui/setup.ts +27 -3
  116. package/src/tui/skillAuthoring.js +11 -5
  117. package/src/tui/skillAuthoring.ts +11 -5
  118. package/src/tui/smartLinkClick.js +75 -23
  119. package/src/tui/smartLinkClick.ts +86 -26
  120. package/src/tui/stage.js +47 -16
  121. package/src/tui/stage.ts +53 -18
  122. package/src/tui/stageSurface.js +120 -49
  123. package/src/tui/statusLine.js +85 -53
  124. package/src/tui/statusLine.ts +82 -46
  125. package/src/tui/terminalInputFramer.js +5 -2
  126. package/src/tui/text.js +117 -46
  127. package/src/tui/text.ts +113 -43
  128. package/src/tui/textLayout.js +6 -4
  129. package/src/tui/textLayout.ts +11 -5
  130. package/src/tui/theme.js +17 -8
  131. package/src/tui/thinkingBox.js +95 -95
  132. package/src/tui/thinkingBox.ts +105 -80
  133. package/src/tui/toolActivityPolicy.js +8 -1
  134. package/src/tui/toolActivityPolicy.ts +7 -1
  135. package/src/tui/toolDisplay.js +15 -6
  136. package/src/tui/toolDisplay.ts +16 -6
  137. package/src/tui/toolOutputNormalizer.js +16 -3
  138. package/src/tui/toolOutputNormalizer.ts +13 -3
  139. package/src/tui/transcript.js +15 -9
  140. package/src/tui/turnRail.js +156 -67
  141. package/src/tui/turnRail.ts +155 -58
  142. package/src/tui/usageCard.js +80 -45
  143. package/src/tui/usageCard.ts +81 -46
  144. package/src/tui/viewport.js +48 -23
  145. package/src/tui/viewport.ts +48 -27
  146. package/src/tui/viewportAnchor.js +2 -2
  147. package/src/tui/viewportAnchor.ts +2 -2
  148. package/src/tui/workspaceFileIndex.js +8 -6
  149. package/src/tui/workspaceFileIndex.ts +8 -6
  150. package/src/tui/workspaceSwitch.js +13 -10
  151. package/src/tui/workspaceSwitch.ts +11 -7
@@ -30,7 +30,8 @@ export function recoveryUserMessage(decision: RecoveryDecision, tool: string): s
30
30
  if (decision.kind === 'human') {
31
31
  return `${tool} needs approval or authentication. Review the last tool error, then provide the needed access or choose another route. No success is claimed.`;
32
32
  }
33
- if (decision.attempt <= TIME_MACHINE_CONSENT_AT && decision.kind === 'stop') {
33
+ // A stop before the hard maximum only happens when further attempts were not approved.
34
+ if (decision.attempt < TIME_MACHINE_MAX_ATTEMPTS && decision.kind === 'stop') {
34
35
  return `${tool} failed ${decision.attempt} times (${decision.failureClass}) and more attempts were not approved. The task stopped without verified success.`;
35
36
  }
36
37
  return `${tool} still failed after ${decision.attempt} attempts (${decision.failureClass}). The task stopped without verified success.`;
@@ -41,32 +42,48 @@ function record(value: unknown): Record<string, unknown> {
41
42
  ? value as Record<string, unknown> : {};
42
43
  }
43
44
 
45
+ function firstText(values: readonly unknown[]): string {
46
+ return values.find((value): value is string => typeof value === 'string' && value.trim().length > 0) ?? '';
47
+ }
48
+
49
+ function commandText(args: Record<string, unknown>): string {
50
+ return firstText([args.command, args.cmd, args.CommandLine, args.commandLine, args.script]);
51
+ }
52
+
44
53
  function operationFamily(args: Record<string, unknown>): string {
45
- const command = typeof args.command === 'string' ? args.command
46
- : typeof args.cmd === 'string' ? args.cmd
47
- : typeof args.CommandLine === 'string' ? args.CommandLine
48
- : typeof args.commandLine === 'string' ? args.commandLine
49
- : typeof args.script === 'string' ? args.script : '';
54
+ const command = commandText(args);
50
55
  if (!command) {
51
- const endpoint = typeof args.url === 'string' ? args.url : typeof args.endpoint === 'string' ? args.endpoint : '';
56
+ const endpoint = firstText([args.url, args.endpoint]);
52
57
  if (endpoint) {
53
58
  try { return new URL(endpoint).hostname.toLowerCase(); } catch { return ''; }
54
59
  }
55
60
  return '';
56
61
  }
57
- const words = command.trim().split(/\s+/).slice(0, 3);
62
+ const tokens = command.trim().split(/\s+/);
63
+ // Leading VAR=value assignments do not change which operation is retried, so
64
+ // `CI=1 npm test` must share the retry budget of `npm test`.
65
+ while (tokens.length > 1 && /^[A-Za-z_][A-Za-z0-9_]*=/.test(tokens[0] || '')) tokens.shift();
66
+ const words = tokens.slice(0, 3);
67
+ // Windows shims (`npm.cmd`, `bun.exe`) are the same tools as their bare names.
68
+ const executable = (words[0] || '').replace(/^.*[\\/]/, '').replace(/\.(cmd|exe|bat|ps1)$/i, '').toLowerCase();
58
69
  // Keep common verification commands distinct without retaining paths,
59
70
  // source text, environment variables, or credentials in the journal.
60
- if (/^(npm|pnpm|yarn|bun)$/.test(words[0] || '')) {
61
- return words.slice(0, words[1] === 'run' ? 3 : 2).join(' ').toLowerCase();
71
+ if (/^(npm|pnpm|yarn|bun)$/.test(executable)) {
72
+ // Script names are case-sensitive; a passing `build` cannot resolve `Build`.
73
+ return [executable, ...words.slice(1, words[1] === 'run' ? 3 : 2)].join(' ');
74
+ }
75
+ if (/^(git|gh|docker|podman|kubectl)$/.test(executable)) {
76
+ // Distinct subcommands must have distinct recovery histories: a passing
77
+ // git status is not evidence that an earlier git push succeeded.
78
+ return [executable, (words[1] || '').toLowerCase().slice(0, 32)].filter(Boolean).join(' ');
62
79
  }
63
- return (words[0] || '').replace(/^.*[\\/]/, '').toLowerCase().slice(0, 32);
80
+ return executable.slice(0, 32);
64
81
  }
65
82
 
66
83
  function issueKey(tool: string, args: Record<string, unknown>): string {
67
84
  const family = operationFamily(args);
68
- const target = String(args.path ?? args.file_path ?? args.filePath ?? args.target ?? args.endpoint ?? args.url ?? '');
69
- const workspace = String(args.cwd ?? '');
85
+ const target = firstText([args.path, args.file_path, args.filePath, args.target, args.endpoint, args.url]);
86
+ const workspace = String(args.cwd ?? args.workingDirectory ?? args.workingDir ?? args.workspaceRoot ?? '');
70
87
  // Changing error text/class does not buy another three attempts at the same
71
88
  // operation. Targets are hashed and never included in recovery messages.
72
89
  return createHash('sha256').update(`${tool}\0${family}\0${target}\0${workspace}`).digest('hex');
@@ -116,12 +133,16 @@ export class TimeMachine {
116
133
 
117
134
  observe(tool: string, args: Record<string, unknown>, result: unknown,
118
135
  outcomes: readonly ToolOutcome[] = []): RecoveryDecision {
136
+ const safeArgs = record(args);
119
137
  const value = record(result);
120
- const failed = value.success === false || (typeof value.error === 'string' && value.error.trim().length > 0)
121
- || (typeof value.exitCode === 'number' && (!Number.isFinite(value.exitCode) || value.exitCode !== 0))
122
- || value.failureKind === 'site_refusal';
123
- const classification = failed ? failureClass(value) || 'failed' : '';
124
- const key = issueKey(tool, args);
138
+ const exitStatus = value.exitCode ?? value.exit_code;
139
+ const failed = result instanceof Error || value.success === false || value.ok === false || value.isError === true || value.requiresConsent === true || value.requiresApproval === true || value.authenticationRequired === true || (typeof value.error === 'string' && value.error.trim().length > 0)
140
+ || (typeof exitStatus === 'number' && (!Number.isFinite(exitStatus) || exitStatus !== 0))
141
+ || value.failureKind === 'site_refusal' || value.status === 'error' || value.status === 'failed'
142
+ || (typeof value.status === 'number' && (!Number.isFinite(value.status) || value.status >= 400))
143
+ || (value.error !== null && typeof value.error === 'object');
144
+ const classification = failed ? (value.status === 429 ? 'rate_limited' : value.status === 401 ? 'permission' : failureClass(value) || 'failed') : '';
145
+ const key = issueKey(tool, safeArgs);
125
146
  const good = lastGoodTool(outcomes);
126
147
 
127
148
  if (!failed) {
@@ -138,7 +159,7 @@ export class TimeMachine {
138
159
  issueKey: '',
139
160
  lastGoodTool: good,
140
161
  guidance: hadFailure
141
- ? isVerificationCommand(String(args.command || args.cmd || ''))
162
+ ? isVerificationCommand(commandText(safeArgs))
142
163
  ? 'The same verification command now passed. Report that check as evidence; assess the rest of the task separately.'
143
164
  : 'This tool call succeeded. Verify the intended task outcome before reporting success.'
144
165
  : ''
@@ -146,7 +167,8 @@ export class TimeMachine {
146
167
  }
147
168
 
148
169
  const error = typeof value.error === 'string' ? value.error : '';
149
- const needsHuman = classification === 'permission' || /user denied|approval required|authentication required/i.test(error);
170
+ const needsHuman = value.failureKind !== 'site_refusal'
171
+ && (classification === 'permission' || value.requiresConsent === true || value.requiresApproval === true || value.authenticationRequired === true || /user denied|approval required|authentication required/i.test(error));
150
172
  const attempt = Math.min(TIME_MACHINE_MAX_ATTEMPTS, (this.failures.get(key) || 0) + 1);
151
173
  this.failures.set(key, attempt);
152
174
  const checkpoint = good ? ` Last successful tool: ${good}.` : '';
@@ -160,7 +182,7 @@ export class TimeMachine {
160
182
  if (attempt >= TIME_MACHINE_MAX_ATTEMPTS) {
161
183
  return { kind: 'stop', attempt, maxAttempts: TIME_MACHINE_MAX_ATTEMPTS, issueKey: key,
162
184
  failureClass: classification, lastGoodTool: good,
163
- guidance: `The same failure class persisted through ${TIME_MACHINE_MAX_ATTEMPTS} attempts. Stop this task. Give a brief evidence-based report, state what remains unresolved, and ask for input only if needed. Put a detailed report in a Markdown file only if the user requests one.${checkpoint}` };
185
+ guidance: `The same operation failed through ${TIME_MACHINE_MAX_ATTEMPTS} attempts. Stop this task. Give a brief evidence-based report, state what remains unresolved, and ask for input only if needed. Put a detailed report in a Markdown file only if the user requests one.${checkpoint}` };
164
186
  }
165
187
  // The agent may spend three attempts alone. The fourth through sixth belong
166
188
  // to the user: without an explicit grant the budget ends here.
@@ -174,7 +196,7 @@ export class TimeMachine {
174
196
  failureClass: classification, lastGoodTool: good,
175
197
  guidance: `Further attempts were not approved. Stop this task. Give a brief evidence-based report and state what remains unresolved.${checkpoint}` };
176
198
  }
177
- if (classification === 'rate_limited' && attempt < TIME_MACHINE_CONSENT_AT) {
199
+ if (classification === 'rate_limited' && attempt < TIME_MACHINE_MAX_ATTEMPTS) {
178
200
  return { kind: 'replan', attempt, maxAttempts: TIME_MACHINE_MAX_ATTEMPTS, issueKey: key,
179
201
  failureClass: classification, lastGoodTool: good,
180
202
  guidance: `Rate limit reached. Respect the provider's retry/reset window; do not immediately resend the same request.${checkpoint}` };
@@ -34,6 +34,7 @@ on run argv
34
34
  set report to report & "ok|press|" & elemName & linefeed
35
35
  else
36
36
  set report to report & "miss|press|" & elemName & linefeed
37
+ exit repeat -- Never type/click elsewhere after a required target is missing.
37
38
  end if
38
39
  else if verb is "clickxy" then
39
40
  set px to (item 2 of parts) as integer
@@ -7,6 +7,10 @@
7
7
  import { parseVisionGroundingPrediction, visionGroundingToDesktopAct, groundBoxCenter } from '../computerUse/visionGrounding.js';
8
8
  import { desktopAct } from './desktopAct.js';
9
9
  import { auditLog } from '../auditLog.js';
10
+ function hasValidCoordinates(value) {
11
+ return Array.isArray(value) && (value.length === 2 || value.length === 4)
12
+ && value.every(coord => typeof coord === 'number' && Number.isFinite(coord));
13
+ }
10
14
  export const computerUse = {
11
15
  schema: {
12
16
  name: 'computer_use',
@@ -76,38 +80,47 @@ export const computerUse = {
76
80
  // Mode 2: Direct action request
77
81
  const actionType = args.action || 'click';
78
82
  if (actionType === 'click') {
79
- const coords = args.coordinates || [];
83
+ const coords = args.coordinates;
84
+ if (!hasValidCoordinates(coords))
85
+ return { success: false, error: 'Click requires finite coordinates [x, y] or [x1, y1, x2, y2].' };
80
86
  const point = groundBoxCenter(coords, screen);
81
- if (!point)
82
- return { success: false, error: 'Click requires valid coordinates [x, y].' };
87
+ if (!point || !Number.isFinite(point.x) || !Number.isFinite(point.y))
88
+ return { success: false, error: 'Click coordinates are outside the supported screen context.' };
83
89
  desktopActions.push({ verb: 'clickxy', x: point.x, y: point.y });
84
90
  }
85
91
  else if (actionType === 'type') {
86
- if (args.coordinates && args.coordinates.length >= 2) {
92
+ if (args.coordinates !== undefined) {
93
+ if (!hasValidCoordinates(args.coordinates))
94
+ return { success: false, error: 'Type target requires finite coordinates [x, y] or [x1, y1, x2, y2].' };
87
95
  const point = groundBoxCenter(args.coordinates, screen);
88
- if (point)
89
- desktopActions.push({ verb: 'clickxy', x: point.x, y: point.y });
96
+ if (!point || !Number.isFinite(point.x) || !Number.isFinite(point.y))
97
+ return { success: false, error: 'Type target coordinates are outside the supported screen context.' };
98
+ desktopActions.push({ verb: 'clickxy', x: point.x, y: point.y });
90
99
  }
91
100
  if (!args.text)
92
101
  return { success: false, error: 'Type action requires "text" parameter.' };
93
102
  desktopActions.push({ verb: 'type', text: args.text });
94
103
  }
95
104
  else if (actionType === 'key') {
96
- if (!args.key)
105
+ const keyName = typeof args.key === 'string' ? args.key.trim() : '';
106
+ if (!keyName)
97
107
  return { success: false, error: 'Key action requires "key" parameter.' };
98
108
  const keyMap = {
99
109
  return: 36, enter: 36, tab: 48, space: 49, backspace: 51, escape: 53, esc: 53
100
110
  };
101
- const keyCode = keyMap[args.key.toLowerCase()];
111
+ const keyCode = keyMap[keyName.toLowerCase()];
102
112
  if (keyCode !== undefined) {
103
113
  desktopActions.push({ verb: 'key', keyCode });
104
114
  }
115
+ else if (/^[a-z0-9]$/i.test(keyName)) {
116
+ desktopActions.push({ verb: 'type', text: keyName });
117
+ }
105
118
  else {
106
- desktopActions.push({ verb: 'type', text: args.key });
119
+ return { success: false, error: 'Unsupported key name or chord. Use action "type" for text; compound hotkeys require supported key actuation.' };
107
120
  }
108
121
  }
109
122
  else if (actionType === 'wait') {
110
- desktopActions.push({ verb: 'wait', seconds: Math.min(10, Math.max(0.1, args.seconds || 1)) });
123
+ desktopActions.push({ verb: 'wait', seconds: Math.min(10, Math.max(0.1, Number.isFinite(args.seconds) ? args.seconds : 1)) });
111
124
  }
112
125
  else {
113
126
  return { success: false, error: `Unsupported computer_use action: ${actionType}` };
@@ -20,6 +20,11 @@ export interface ComputerUseArgs {
20
20
  screenContext?: ScreenContext;
21
21
  }
22
22
 
23
+ function hasValidCoordinates(value: unknown): value is number[] {
24
+ return Array.isArray(value) && (value.length === 2 || value.length === 4)
25
+ && value.every(coord => typeof coord === 'number' && Number.isFinite(coord));
26
+ }
27
+
23
28
  export const computerUse = {
24
29
  schema: {
25
30
  name: 'computer_use',
@@ -91,30 +96,36 @@ export const computerUse = {
91
96
  // Mode 2: Direct action request
92
97
  const actionType = args.action || 'click';
93
98
  if (actionType === 'click') {
94
- const coords = args.coordinates || [];
99
+ const coords = args.coordinates;
100
+ if (!hasValidCoordinates(coords)) return { success: false, error: 'Click requires finite coordinates [x, y] or [x1, y1, x2, y2].' };
95
101
  const point = groundBoxCenter(coords, screen);
96
- if (!point) return { success: false, error: 'Click requires valid coordinates [x, y].' };
102
+ if (!point || !Number.isFinite(point.x) || !Number.isFinite(point.y)) return { success: false, error: 'Click coordinates are outside the supported screen context.' };
97
103
  desktopActions.push({ verb: 'clickxy', x: point.x, y: point.y });
98
104
  } else if (actionType === 'type') {
99
- if (args.coordinates && args.coordinates.length >= 2) {
105
+ if (args.coordinates !== undefined) {
106
+ if (!hasValidCoordinates(args.coordinates)) return { success: false, error: 'Type target requires finite coordinates [x, y] or [x1, y1, x2, y2].' };
100
107
  const point = groundBoxCenter(args.coordinates, screen);
101
- if (point) desktopActions.push({ verb: 'clickxy', x: point.x, y: point.y });
108
+ if (!point || !Number.isFinite(point.x) || !Number.isFinite(point.y)) return { success: false, error: 'Type target coordinates are outside the supported screen context.' };
109
+ desktopActions.push({ verb: 'clickxy', x: point.x, y: point.y });
102
110
  }
103
111
  if (!args.text) return { success: false, error: 'Type action requires "text" parameter.' };
104
112
  desktopActions.push({ verb: 'type', text: args.text });
105
113
  } else if (actionType === 'key') {
106
- if (!args.key) return { success: false, error: 'Key action requires "key" parameter.' };
114
+ const keyName = typeof args.key === 'string' ? args.key.trim() : '';
115
+ if (!keyName) return { success: false, error: 'Key action requires "key" parameter.' };
107
116
  const keyMap: Record<string, number> = {
108
117
  return: 36, enter: 36, tab: 48, space: 49, backspace: 51, escape: 53, esc: 53
109
118
  };
110
- const keyCode = keyMap[args.key.toLowerCase()];
119
+ const keyCode = keyMap[keyName.toLowerCase()];
111
120
  if (keyCode !== undefined) {
112
121
  desktopActions.push({ verb: 'key', keyCode });
122
+ } else if (/^[a-z0-9]$/i.test(keyName)) {
123
+ desktopActions.push({ verb: 'type', text: keyName });
113
124
  } else {
114
- desktopActions.push({ verb: 'type', text: args.key });
125
+ return { success: false, error: 'Unsupported key name or chord. Use action "type" for text; compound hotkeys require supported key actuation.' };
115
126
  }
116
127
  } else if (actionType === 'wait') {
117
- desktopActions.push({ verb: 'wait', seconds: Math.min(10, Math.max(0.1, args.seconds || 1)) });
128
+ desktopActions.push({ verb: 'wait', seconds: Math.min(10, Math.max(0.1, Number.isFinite(args.seconds) ? args.seconds! : 1)) });
118
129
  } else {
119
130
  return { success: false, error: `Unsupported computer_use action: ${actionType}` };
120
131
  }
@@ -77,6 +77,16 @@ function encodeAction(action, index) {
77
77
  return { ok: true, argv: `clickxy::${Math.round(x)}::${Math.round(y)}` };
78
78
  }
79
79
 
80
+ if (verb === 'key') {
81
+ if ((Array.isArray(action.modifiers) && action.modifiers.length > 0) || action.chord) {
82
+ return { ok: false, error: `action ${index}: modifier key chords are not supported by this actuator; do not send an unmodified keystroke` };
83
+ }
84
+ const code = Number(action.keyCode);
85
+ if (!Number.isInteger(code) || code < 0 || code > 127) {
86
+ return { ok: false, error: `action ${index}: key requires a valid macOS virtual key code (0-127)` };
87
+ }
88
+ }
89
+
80
90
  const value = verb === 'press' ? action.target
81
91
  : verb === 'type' ? action.text
82
92
  : verb === 'key' ? action.keyCode
@@ -198,7 +208,8 @@ export const desktopAct = {
198
208
  const report = String(result.stdout || '').trim();
199
209
  const missed = (report.match(/^miss\|/gm) || []).length;
200
210
  return {
201
- success: true,
211
+ success: missed === 0,
212
+ ...(missed > 0 ? { error: `${missed} element(s) not found; remaining actions were not executed.` } : {}),
202
213
  output: (report || 'No output.')
203
214
  + (missed > 0
204
215
  ? `\n\n${missed} element(s) were not found by name. Run ax_snapshot to see the current element names before retrying.`
@@ -6,9 +6,85 @@
6
6
  * user choices if MCP is preferred.
7
7
  */
8
8
  import { PluginsFactory } from '../pluginsFactory/index.js';
9
+ const SERVICE_KINDS = new Set(['http_api', 'cli', 'python_sdk', 'mcp_only', 'custom']);
10
+ const AUTH_TYPES = new Set(['none', 'bearer', 'apiKey', 'basic', 'env']);
11
+ const HTTP_METHODS = new Set(['GET', 'POST', 'PUT', 'DELETE', 'PATCH']);
12
+ const ROUTE_KINDS = new Set(['native_plugin', 'python_bridge', 'mcp_server']);
13
+ const CAPABILITY_NAMES = new Set(['workspace:read', 'workspace:write', 'network', 'subprocess']);
14
+ const ACTIONS = new Set(['assess', 'estimate_cost', 'scaffold']);
15
+ function assertOptionalString(value, field) {
16
+ if (value !== undefined && typeof value !== 'string') {
17
+ throw new Error(`"${field}" must be a string.`);
18
+ }
19
+ }
9
20
  function normalizeServiceDescriptor(args) {
21
+ if (typeof args.action !== 'string' || !ACTIONS.has(args.action)) {
22
+ throw new Error(`Unrecognized action: "${String(args.action)}". Allowed: assess, estimate_cost, scaffold`);
23
+ }
24
+ if (typeof args.serviceName !== 'string' || !args.serviceName.trim()) {
25
+ throw new Error('"serviceName" must be a non-empty string.');
26
+ }
27
+ assertOptionalString(args.serviceDescription, 'serviceDescription');
28
+ assertOptionalString(args.endpoint, 'endpoint');
29
+ assertOptionalString(args.authEnvVar, 'authEnvVar');
30
+ if (args.authEnvVar !== undefined && !/^[A-Za-z_][A-Za-z0-9_]*$/.test(args.authEnvVar)) {
31
+ throw new Error('"authEnvVar" must be a valid environment variable name.');
32
+ }
33
+ assertOptionalString(args.cliBinary, 'cliBinary');
34
+ assertOptionalString(args.pythonModule, 'pythonModule');
35
+ if (args.capabilities !== undefined) {
36
+ if (!Array.isArray(args.capabilities)) {
37
+ throw new Error('"capabilities" must be an array.');
38
+ }
39
+ for (const capability of args.capabilities) {
40
+ if (!CAPABILITY_NAMES.has(capability)) {
41
+ throw new Error(`Unknown capability "${String(capability)}".`);
42
+ }
43
+ }
44
+ }
45
+ if (args.serviceKind !== undefined && !SERVICE_KINDS.has(args.serviceKind)) {
46
+ throw new Error(`Invalid serviceKind "${String(args.serviceKind)}".`);
47
+ }
48
+ if (args.authType !== undefined && !AUTH_TYPES.has(args.authType)) {
49
+ throw new Error(`Invalid authType "${String(args.authType)}".`);
50
+ }
51
+ if (args.userPreferredRoute !== undefined && !ROUTE_KINDS.has(args.userPreferredRoute)) {
52
+ throw new Error(`Invalid userPreferredRoute "${String(args.userPreferredRoute)}".`);
53
+ }
54
+ if (args.tools !== undefined && !Array.isArray(args.tools)) {
55
+ throw new Error('"tools" must be an array of tool descriptors.');
56
+ }
10
57
  const tools = (args.tools || []).map((t, idx) => {
11
- const rawParams = (t.parameters && typeof t.parameters === 'object') ? t.parameters : {};
58
+ if (!t || typeof t !== 'object' || Array.isArray(t)) {
59
+ throw new Error(`Tool at index ${idx} must be an object.`);
60
+ }
61
+ if (typeof t.name !== 'string' || !t.name.trim()) {
62
+ throw new Error(`Tool at index ${idx} requires a non-empty name.`);
63
+ }
64
+ if (typeof t.description !== 'string' || !t.description.trim()) {
65
+ throw new Error(`Tool "${t.name}" requires a non-empty description.`);
66
+ }
67
+ if (t.parameters !== undefined &&
68
+ (t.parameters === null || typeof t.parameters !== 'object' || Array.isArray(t.parameters))) {
69
+ throw new Error(`Tool "${t.name}" parameters must be an object JSON schema.`);
70
+ }
71
+ if (t.httpMethod !== undefined && !HTTP_METHODS.has(t.httpMethod)) {
72
+ throw new Error(`Tool "${t.name}" has invalid httpMethod "${String(t.httpMethod)}".`);
73
+ }
74
+ for (const field of ['httpPath', 'cliSubcommand', 'pythonMethod']) {
75
+ const value = t[field];
76
+ if (value !== undefined && typeof value !== 'string') {
77
+ throw new Error(`Tool "${t.name}" field "${field}" must be a string.`);
78
+ }
79
+ }
80
+ const rawParams = t.parameters ?? {};
81
+ if (rawParams['type'] !== undefined && rawParams['type'] !== 'object') {
82
+ throw new Error(`Tool "${t.name}" parameters must declare type "object".`);
83
+ }
84
+ if (rawParams['properties'] !== undefined &&
85
+ (rawParams['properties'] === null || typeof rawParams['properties'] !== 'object' || Array.isArray(rawParams['properties']))) {
86
+ throw new Error(`Tool "${t.name}" parameters.properties must be an object.`);
87
+ }
12
88
  const { type: _discardType, ...restParams } = rawParams;
13
89
  const parameters = {
14
90
  ...restParams,
@@ -18,8 +94,8 @@ function normalizeServiceDescriptor(args) {
18
94
  : {}
19
95
  };
20
96
  const tool = {
21
- name: t.name || `tool_${idx + 1}`,
22
- description: t.description || `Tool ${t.name || idx + 1}`,
97
+ name: t.name.trim(),
98
+ description: t.description.trim(),
23
99
  parameters
24
100
  };
25
101
  if (t.httpMethod !== undefined)
@@ -75,6 +151,9 @@ export const pluginsFactoryTool = {
75
151
  },
76
152
  serviceName: {
77
153
  type: 'string',
154
+ minLength: 1,
155
+ maxLength: 64,
156
+ pattern: '^[a-zA-Z0-9][a-zA-Z0-9-]{0,63}$',
78
157
  description: 'Name of the service or plugin (lowercase alphanumeric and hyphens, e.g. "notion-api", "blender-cycles").'
79
158
  },
80
159
  serviceDescription: {
@@ -97,6 +176,7 @@ export const pluginsFactoryTool = {
97
176
  },
98
177
  authEnvVar: {
99
178
  type: 'string',
179
+ pattern: '^[A-Za-z_][A-Za-z0-9_]*$',
100
180
  description: 'Environment variable name holding the API token (e.g. "NOTION_API_KEY").'
101
181
  },
102
182
  cliBinary: {
@@ -109,11 +189,18 @@ export const pluginsFactoryTool = {
109
189
  },
110
190
  tools: {
111
191
  type: 'array',
192
+ maxItems: 32,
112
193
  items: {
113
194
  type: 'object',
114
195
  properties: {
115
- name: { type: 'string', description: 'Tool name' },
116
- description: { type: 'string', description: 'What the tool does' },
196
+ name: {
197
+ type: 'string',
198
+ minLength: 1,
199
+ maxLength: 64,
200
+ pattern: '^[a-z][a-z0-9_-]{0,63}$',
201
+ description: 'Tool name'
202
+ },
203
+ description: { type: 'string', minLength: 1, description: 'What the tool does' },
117
204
  parameters: { type: 'object', description: 'JSON schema for tool parameters' },
118
205
  httpMethod: { type: 'string', enum: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'] },
119
206
  httpPath: { type: 'string', description: 'HTTP relative path' },
@@ -158,10 +245,25 @@ export const pluginsFactoryTool = {
158
245
  error: 'Missing required arguments: "action" and "serviceName" are required.'
159
246
  };
160
247
  }
248
+ if (args.force !== undefined && typeof args.force !== 'boolean') {
249
+ return { success: false, action: args.action, error: '"force" must be a boolean.' };
250
+ }
251
+ if (args.dryRun !== undefined && typeof args.dryRun !== 'boolean') {
252
+ return { success: false, action: args.action, error: '"dryRun" must be a boolean.' };
253
+ }
161
254
  const factory = new PluginsFactory();
162
255
  const service = normalizeServiceDescriptor(args);
163
256
  const proposal = factory.assess(service, args.userPreferredRoute);
164
257
  if (args.action === 'assess' || args.action === 'estimate_cost') {
258
+ const cost = proposal.costComparison;
259
+ const costLines = args.action === 'estimate_cost'
260
+ ? [
261
+ `Token cost estimate for service '${service.name}' (schema tokens / per-call tokens / relative cost):`,
262
+ `- native_plugin: ${cost.nativePlugin.estimatedSchemaTokens} / ${cost.nativePlugin.estimatedPerCallTokens} / ${cost.nativePlugin.relativeCostMultiplier}x`,
263
+ `- python_bridge: ${cost.pythonBridge.estimatedSchemaTokens} / ${cost.pythonBridge.estimatedPerCallTokens} / ${cost.pythonBridge.relativeCostMultiplier}x`,
264
+ `- mcp_server: ${cost.mcpServer.estimatedSchemaTokens} / ${cost.mcpServer.estimatedPerCallTokens} / ${cost.mcpServer.relativeCostMultiplier}x`
265
+ ]
266
+ : [];
165
267
  const res = {
166
268
  success: true,
167
269
  action: args.action,
@@ -169,6 +271,7 @@ export const pluginsFactoryTool = {
169
271
  message: [
170
272
  `Assessment complete for service '${service.name}'.`,
171
273
  `Recommended Route: ${proposal.recommendedRoute} (${proposal.reason})`,
274
+ ...costLines,
172
275
  proposal.mcpDisclosure ? `\n${proposal.mcpDisclosure}` : ''
173
276
  ].filter(Boolean).join('\n')
174
277
  };
@@ -52,9 +52,91 @@ export interface PluginsFactoryToolResult {
52
52
  error?: string | undefined;
53
53
  }
54
54
 
55
+ const SERVICE_KINDS = new Set(['http_api', 'cli', 'python_sdk', 'mcp_only', 'custom']);
56
+ const AUTH_TYPES = new Set(['none', 'bearer', 'apiKey', 'basic', 'env']);
57
+ const HTTP_METHODS = new Set(['GET', 'POST', 'PUT', 'DELETE', 'PATCH']);
58
+ const ROUTE_KINDS = new Set(['native_plugin', 'python_bridge', 'mcp_server']);
59
+ const CAPABILITY_NAMES = new Set(['workspace:read', 'workspace:write', 'network', 'subprocess']);
60
+ const ACTIONS = new Set(['assess', 'estimate_cost', 'scaffold']);
61
+
62
+ function assertOptionalString(value: unknown, field: string): void {
63
+ if (value !== undefined && typeof value !== 'string') {
64
+ throw new Error(`"${field}" must be a string.`);
65
+ }
66
+ }
67
+
55
68
  function normalizeServiceDescriptor(args: PluginsFactoryArgs): ServiceDescriptor {
69
+ if (typeof args.action !== 'string' || !ACTIONS.has(args.action)) {
70
+ throw new Error(`Unrecognized action: "${String(args.action)}". Allowed: assess, estimate_cost, scaffold`);
71
+ }
72
+ if (typeof args.serviceName !== 'string' || !args.serviceName.trim()) {
73
+ throw new Error('"serviceName" must be a non-empty string.');
74
+ }
75
+ assertOptionalString(args.serviceDescription, 'serviceDescription');
76
+ assertOptionalString(args.endpoint, 'endpoint');
77
+ assertOptionalString(args.authEnvVar, 'authEnvVar');
78
+ if (args.authEnvVar !== undefined && !/^[A-Za-z_][A-Za-z0-9_]*$/.test(args.authEnvVar)) {
79
+ throw new Error('"authEnvVar" must be a valid environment variable name.');
80
+ }
81
+ assertOptionalString(args.cliBinary, 'cliBinary');
82
+ assertOptionalString(args.pythonModule, 'pythonModule');
83
+ if (args.capabilities !== undefined) {
84
+ if (!Array.isArray(args.capabilities)) {
85
+ throw new Error('"capabilities" must be an array.');
86
+ }
87
+ for (const capability of args.capabilities) {
88
+ if (!CAPABILITY_NAMES.has(capability)) {
89
+ throw new Error(`Unknown capability "${String(capability)}".`);
90
+ }
91
+ }
92
+ }
93
+ if (args.serviceKind !== undefined && !SERVICE_KINDS.has(args.serviceKind)) {
94
+ throw new Error(`Invalid serviceKind "${String(args.serviceKind)}".`);
95
+ }
96
+ if (args.authType !== undefined && !AUTH_TYPES.has(args.authType)) {
97
+ throw new Error(`Invalid authType "${String(args.authType)}".`);
98
+ }
99
+ if (args.userPreferredRoute !== undefined && !ROUTE_KINDS.has(args.userPreferredRoute)) {
100
+ throw new Error(`Invalid userPreferredRoute "${String(args.userPreferredRoute)}".`);
101
+ }
102
+ if (args.tools !== undefined && !Array.isArray(args.tools)) {
103
+ throw new Error('"tools" must be an array of tool descriptors.');
104
+ }
56
105
  const tools: ServiceToolDescriptor[] = (args.tools || []).map((t, idx) => {
57
- const rawParams = (t.parameters && typeof t.parameters === 'object') ? (t.parameters as Record<string, unknown>) : {};
106
+ if (!t || typeof t !== 'object' || Array.isArray(t)) {
107
+ throw new Error(`Tool at index ${idx} must be an object.`);
108
+ }
109
+ if (typeof t.name !== 'string' || !t.name.trim()) {
110
+ throw new Error(`Tool at index ${idx} requires a non-empty name.`);
111
+ }
112
+ if (typeof t.description !== 'string' || !t.description.trim()) {
113
+ throw new Error(`Tool "${t.name}" requires a non-empty description.`);
114
+ }
115
+ if (
116
+ t.parameters !== undefined &&
117
+ (t.parameters === null || typeof t.parameters !== 'object' || Array.isArray(t.parameters))
118
+ ) {
119
+ throw new Error(`Tool "${t.name}" parameters must be an object JSON schema.`);
120
+ }
121
+ if (t.httpMethod !== undefined && !HTTP_METHODS.has(t.httpMethod)) {
122
+ throw new Error(`Tool "${t.name}" has invalid httpMethod "${String(t.httpMethod)}".`);
123
+ }
124
+ for (const field of ['httpPath', 'cliSubcommand', 'pythonMethod'] as const) {
125
+ const value = t[field];
126
+ if (value !== undefined && typeof value !== 'string') {
127
+ throw new Error(`Tool "${t.name}" field "${field}" must be a string.`);
128
+ }
129
+ }
130
+ const rawParams = t.parameters ?? {};
131
+ if (rawParams['type'] !== undefined && rawParams['type'] !== 'object') {
132
+ throw new Error(`Tool "${t.name}" parameters must declare type "object".`);
133
+ }
134
+ if (
135
+ rawParams['properties'] !== undefined &&
136
+ (rawParams['properties'] === null || typeof rawParams['properties'] !== 'object' || Array.isArray(rawParams['properties']))
137
+ ) {
138
+ throw new Error(`Tool "${t.name}" parameters.properties must be an object.`);
139
+ }
58
140
  const { type: _discardType, ...restParams } = rawParams;
59
141
  const parameters: ToolParameterSchema = {
60
142
  ...restParams,
@@ -64,8 +146,8 @@ function normalizeServiceDescriptor(args: PluginsFactoryArgs): ServiceDescriptor
64
146
  : {}
65
147
  };
66
148
  const tool: ServiceToolDescriptor = {
67
- name: t.name || `tool_${idx + 1}`,
68
- description: t.description || `Tool ${t.name || idx + 1}`,
149
+ name: t.name.trim(),
150
+ description: t.description.trim(),
69
151
  parameters
70
152
  };
71
153
  if (t.httpMethod !== undefined) tool.httpMethod = t.httpMethod;
@@ -117,6 +199,9 @@ export const pluginsFactoryTool = {
117
199
  },
118
200
  serviceName: {
119
201
  type: 'string',
202
+ minLength: 1,
203
+ maxLength: 64,
204
+ pattern: '^[a-zA-Z0-9][a-zA-Z0-9-]{0,63}$',
120
205
  description: 'Name of the service or plugin (lowercase alphanumeric and hyphens, e.g. "notion-api", "blender-cycles").'
121
206
  },
122
207
  serviceDescription: {
@@ -139,6 +224,7 @@ export const pluginsFactoryTool = {
139
224
  },
140
225
  authEnvVar: {
141
226
  type: 'string',
227
+ pattern: '^[A-Za-z_][A-Za-z0-9_]*$',
142
228
  description: 'Environment variable name holding the API token (e.g. "NOTION_API_KEY").'
143
229
  },
144
230
  cliBinary: {
@@ -151,11 +237,18 @@ export const pluginsFactoryTool = {
151
237
  },
152
238
  tools: {
153
239
  type: 'array',
240
+ maxItems: 32,
154
241
  items: {
155
242
  type: 'object',
156
243
  properties: {
157
- name: { type: 'string', description: 'Tool name' },
158
- description: { type: 'string', description: 'What the tool does' },
244
+ name: {
245
+ type: 'string',
246
+ minLength: 1,
247
+ maxLength: 64,
248
+ pattern: '^[a-z][a-z0-9_-]{0,63}$',
249
+ description: 'Tool name'
250
+ },
251
+ description: { type: 'string', minLength: 1, description: 'What the tool does' },
159
252
  parameters: { type: 'object', description: 'JSON schema for tool parameters' },
160
253
  httpMethod: { type: 'string', enum: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'] },
161
254
  httpPath: { type: 'string', description: 'HTTP relative path' },
@@ -202,11 +295,27 @@ export const pluginsFactoryTool = {
202
295
  };
203
296
  }
204
297
 
298
+ if (args.force !== undefined && typeof args.force !== 'boolean') {
299
+ return { success: false, action: args.action, error: '"force" must be a boolean.' };
300
+ }
301
+ if (args.dryRun !== undefined && typeof args.dryRun !== 'boolean') {
302
+ return { success: false, action: args.action, error: '"dryRun" must be a boolean.' };
303
+ }
304
+
205
305
  const factory = new PluginsFactory();
206
306
  const service = normalizeServiceDescriptor(args);
207
307
  const proposal = factory.assess(service, args.userPreferredRoute);
208
308
 
209
309
  if (args.action === 'assess' || args.action === 'estimate_cost') {
310
+ const cost = proposal.costComparison;
311
+ const costLines = args.action === 'estimate_cost'
312
+ ? [
313
+ `Token cost estimate for service '${service.name}' (schema tokens / per-call tokens / relative cost):`,
314
+ `- native_plugin: ${cost.nativePlugin.estimatedSchemaTokens} / ${cost.nativePlugin.estimatedPerCallTokens} / ${cost.nativePlugin.relativeCostMultiplier}x`,
315
+ `- python_bridge: ${cost.pythonBridge.estimatedSchemaTokens} / ${cost.pythonBridge.estimatedPerCallTokens} / ${cost.pythonBridge.relativeCostMultiplier}x`,
316
+ `- mcp_server: ${cost.mcpServer.estimatedSchemaTokens} / ${cost.mcpServer.estimatedPerCallTokens} / ${cost.mcpServer.relativeCostMultiplier}x`
317
+ ]
318
+ : [];
210
319
  const res: PluginsFactoryToolResult = {
211
320
  success: true,
212
321
  action: args.action,
@@ -214,6 +323,7 @@ export const pluginsFactoryTool = {
214
323
  message: [
215
324
  `Assessment complete for service '${service.name}'.`,
216
325
  `Recommended Route: ${proposal.recommendedRoute} (${proposal.reason})`,
326
+ ...costLines,
217
327
  proposal.mcpDisclosure ? `\n${proposal.mcpDisclosure}` : ''
218
328
  ].filter(Boolean).join('\n')
219
329
  };