@causyne/agent 1.20.112 → 1.20.117

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 (169) hide show
  1. package/docs/ARCHITECTURE.md +29 -0
  2. package/package.json +1 -1
  3. package/src/agentLoop.js +153 -68
  4. package/src/agentLoop.ts +152 -71
  5. package/src/browser/browserRuntime.js +13 -8
  6. package/src/browser/browserRuntime.ts +16 -8
  7. package/src/browser/causyneBrowser.js +37 -9
  8. package/src/browser/causyneBrowser.ts +37 -9
  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/cliMode.js +5 -1
  18. package/src/computerUse/visionGrounding.js +31 -27
  19. package/src/computerUse/visionGrounding.ts +27 -27
  20. package/src/continuum/ui/continuumPicker.js +14 -6
  21. package/src/continuum/ui/continuumPicker.ts +13 -6
  22. package/src/continuum/ui/continuumPickerView.js +24 -15
  23. package/src/continuum/ui/continuumPickerView.ts +24 -16
  24. package/src/memory/scopedFacts.js +171 -0
  25. package/src/memory/scopedFacts.ts +214 -0
  26. package/src/memory.d.ts +13 -1
  27. package/src/memory.js +9 -12
  28. package/src/observer/advisory.js +32 -22
  29. package/src/observer/advisory.ts +30 -18
  30. package/src/observer/coldObserver.js +21 -33
  31. package/src/observer/coldObserver.ts +20 -33
  32. package/src/observer/evidence.js +20 -13
  33. package/src/observer/evidence.ts +21 -13
  34. package/src/observer.js +47 -12
  35. package/src/observer.ts +50 -18
  36. package/src/perception.js +124 -3
  37. package/src/perception.ts +128 -4
  38. package/src/planCache.js +17 -3
  39. package/src/planCache.ts +17 -3
  40. package/src/pluginsFactory/discovery.js +28 -16
  41. package/src/pluginsFactory/discovery.ts +29 -16
  42. package/src/pluginsFactory/pluginsFactory.js +213 -38
  43. package/src/pluginsFactory/pluginsFactory.ts +218 -39
  44. package/src/pluginsFactory/strategy.js +26 -16
  45. package/src/pluginsFactory/strategy.ts +34 -19
  46. package/src/pluginsFactory/templates.js +183 -62
  47. package/src/pluginsFactory/templates.ts +174 -54
  48. package/src/smartToolsUse.js +4 -5
  49. package/src/smartToolsUse.ts +4 -6
  50. package/src/taskShape.js +49 -7
  51. package/src/taskShape.ts +55 -7
  52. package/src/timeMachine.js +43 -22
  53. package/src/timeMachine.ts +44 -22
  54. package/src/tool-scripts/desktop_act.applescript +1 -0
  55. package/src/toolPacks.js +27 -5
  56. package/src/toolPacks.ts +32 -5
  57. package/src/tools/computerUse.js +23 -10
  58. package/src/tools/computerUse.ts +19 -8
  59. package/src/tools/desktopAct.js +12 -1
  60. package/src/tools/memoryWrite.js +8 -10
  61. package/src/tools/memoryWrite.ts +13 -11
  62. package/src/tools/pluginsFactory.js +108 -5
  63. package/src/tools/pluginsFactory.ts +115 -5
  64. package/src/tui/CausyneRotor.js +24 -10
  65. package/src/tui/CausyneRotor.ts +25 -10
  66. package/src/tui/activityLayout.js +9 -5
  67. package/src/tui/activityLayout.ts +9 -5
  68. package/src/tui/ask.js +34 -14
  69. package/src/tui/banner.js +55 -18
  70. package/src/tui/banner.ts +52 -17
  71. package/src/tui/block.js +47 -20
  72. package/src/tui/block.ts +54 -27
  73. package/src/tui/chatRenderer.js +139 -84
  74. package/src/tui/chatboxClipboard.js +12 -5
  75. package/src/tui/chatboxClipboard.ts +10 -4
  76. package/src/tui/clipboardImage.js +52 -42
  77. package/src/tui/clipboardImage.ts +50 -39
  78. package/src/tui/clipboardSync.js +12 -1
  79. package/src/tui/clipboardSync.ts +9 -1
  80. package/src/tui/codeProgress.js +60 -28
  81. package/src/tui/codeProgress.ts +60 -27
  82. package/src/tui/codeStreamRenderer.js +94 -23
  83. package/src/tui/codeStreamRenderer.ts +92 -23
  84. package/src/tui/commandPresentation.js +9 -2
  85. package/src/tui/commandPresentation.ts +9 -2
  86. package/src/tui/completion.js +45 -23
  87. package/src/tui/composerControls.js +21 -10
  88. package/src/tui/composerControls.ts +18 -10
  89. package/src/tui/composerGeometry.js +6 -4
  90. package/src/tui/composerGeometry.ts +6 -4
  91. package/src/tui/consoleGuard.js +29 -7
  92. package/src/tui/consoleGuard.ts +28 -7
  93. package/src/tui/dialogs.js +134 -71
  94. package/src/tui/diff.js +8 -4
  95. package/src/tui/history.js +6 -5
  96. package/src/tui/home.js +25 -13
  97. package/src/tui/homeView.js +37 -18
  98. package/src/tui/homeView.ts +38 -18
  99. package/src/tui/inlineSlash.js +6 -5
  100. package/src/tui/inlineSlash.ts +6 -5
  101. package/src/tui/keys.js +36 -18
  102. package/src/tui/layout.js +27 -9
  103. package/src/tui/layout.ts +26 -9
  104. package/src/tui/lineEditor.js +49 -23
  105. package/src/tui/markdownMath.js +64 -14
  106. package/src/tui/markdownMath.ts +69 -13
  107. package/src/tui/messageActionPlacement.js +28 -13
  108. package/src/tui/messageActionPlacement.ts +28 -13
  109. package/src/tui/messageInteraction.js +111 -46
  110. package/src/tui/messageInteraction.ts +115 -47
  111. package/src/tui/modelPicker.js +44 -15
  112. package/src/tui/modelPicker.ts +48 -15
  113. package/src/tui/observerPicker.js +56 -13
  114. package/src/tui/observerPicker.ts +73 -30
  115. package/src/tui/overlay.js +79 -35
  116. package/src/tui/overlay.ts +81 -34
  117. package/src/tui/prompt.js +186 -94
  118. package/src/tui/runningLight.js +1 -1
  119. package/src/tui/runningLight.ts +1 -1
  120. package/src/tui/scrollInteraction.js +64 -36
  121. package/src/tui/scrollInteraction.ts +70 -37
  122. package/src/tui/selectList.js +60 -32
  123. package/src/tui/sessionLayout.js +11 -3
  124. package/src/tui/sessionLayout.ts +10 -3
  125. package/src/tui/sessionPicker.js +74 -46
  126. package/src/tui/sessionPicker.ts +73 -48
  127. package/src/tui/sessionPickerView.js +32 -19
  128. package/src/tui/sessionPickerView.ts +31 -18
  129. package/src/tui/sessionSidebar.js +87 -57
  130. package/src/tui/sessionSidebar.ts +90 -54
  131. package/src/tui/setup.js +28 -3
  132. package/src/tui/setup.ts +27 -3
  133. package/src/tui/skillAuthoring.js +11 -5
  134. package/src/tui/skillAuthoring.ts +11 -5
  135. package/src/tui/smartLinkClick.js +75 -23
  136. package/src/tui/smartLinkClick.ts +86 -26
  137. package/src/tui/stage.js +47 -16
  138. package/src/tui/stage.ts +53 -18
  139. package/src/tui/stageSurface.js +232 -51
  140. package/src/tui/statusLine.js +85 -53
  141. package/src/tui/statusLine.ts +82 -46
  142. package/src/tui/terminalInputFramer.js +5 -2
  143. package/src/tui/text.js +117 -46
  144. package/src/tui/text.ts +113 -43
  145. package/src/tui/textLayout.js +6 -4
  146. package/src/tui/textLayout.ts +11 -5
  147. package/src/tui/theme.js +17 -8
  148. package/src/tui/thinkingBox.js +95 -95
  149. package/src/tui/thinkingBox.ts +105 -80
  150. package/src/tui/toolActivityPolicy.js +8 -1
  151. package/src/tui/toolActivityPolicy.ts +7 -1
  152. package/src/tui/toolDisplay.js +15 -6
  153. package/src/tui/toolDisplay.ts +16 -6
  154. package/src/tui/toolOutputNormalizer.js +16 -3
  155. package/src/tui/toolOutputNormalizer.ts +13 -3
  156. package/src/tui/transcript.js +15 -9
  157. package/src/tui/turnRail.js +176 -80
  158. package/src/tui/turnRail.ts +173 -71
  159. package/src/tui/usageCard.js +136 -80
  160. package/src/tui/usageCard.ts +145 -103
  161. package/src/tui/viewport.js +48 -23
  162. package/src/tui/viewport.ts +48 -27
  163. package/src/tui/viewportAnchor.js +2 -2
  164. package/src/tui/viewportAnchor.ts +2 -2
  165. package/src/tui/workspaceFileIndex.js +8 -6
  166. package/src/tui/workspaceFileIndex.ts +8 -6
  167. package/src/tui/workspaceSwitch.js +13 -10
  168. package/src/tui/workspaceSwitch.ts +11 -7
  169. package/src/types/contracts.ts +3 -0
@@ -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.`
@@ -1,5 +1,5 @@
1
- // @ts-expect-error Legacy memory module has no TypeScript declarations yet.
2
1
  import { getMemory, saveMemory } from '../memory.js';
2
+ import { recordScopedFact } from '../memory/scopedFacts.js';
3
3
  import { cortexDb } from '../cortex/vectorDb.js';
4
4
  const MAX_FACTS = 100;
5
5
  export const memoryWrite = {
@@ -41,16 +41,14 @@ export const memoryWrite = {
41
41
  }
42
42
  try {
43
43
  const memory = getMemory();
44
- if (!Array.isArray(memory.facts))
45
- memory.facts = [];
46
44
  const fact = String(args.fact).trim();
47
- const alreadyKnown = memory.facts.includes(fact);
45
+ const workspace = dependencies?.parentLoop?.workspaceRoot || dependencies?.workspaceRoot;
46
+ const { memory: updated, alreadyKnown } = recordScopedFact(memory, fact, {
47
+ workspace,
48
+ maxFacts: MAX_FACTS
49
+ });
48
50
  if (!alreadyKnown) {
49
- memory.facts.push(fact);
50
- while (memory.facts.length > MAX_FACTS) {
51
- memory.facts.shift();
52
- }
53
- saveMemory(memory);
51
+ saveMemory(updated);
54
52
  }
55
53
  let creativeSaved = false;
56
54
  if (args.creativePattern && args.creativePattern.designApproach) {
@@ -76,7 +74,7 @@ export const memoryWrite = {
76
74
  }
77
75
  const notes = [
78
76
  alreadyKnown ? 'Fact already known, not duplicated.' : 'Fact saved.',
79
- `Total persistent facts: ${memory.facts.length}.`,
77
+ `Total persistent facts: ${updated.facts.length}.`,
80
78
  creativeSaved ? 'Creative pattern recorded in the V5 Cortex.' : ''
81
79
  ].filter(Boolean);
82
80
  return { success: true, output: notes.join(' ') };
@@ -1,5 +1,5 @@
1
- // @ts-expect-error Legacy memory module has no TypeScript declarations yet.
2
1
  import { getMemory, saveMemory } from '../memory.js';
2
+ import { recordScopedFact } from '../memory/scopedFacts.js';
3
3
  import { cortexDb } from '../cortex/vectorDb.js';
4
4
 
5
5
  const MAX_FACTS = 100;
@@ -17,6 +17,10 @@ export interface MemoryWriteArgs {
17
17
  }
18
18
 
19
19
  export interface MemoryWriteDependencies {
20
+ workspaceRoot?: string | undefined;
21
+ parentLoop?: {
22
+ workspaceRoot?: string | undefined;
23
+ } | undefined;
20
24
  broadcast?: (event: { type: string; content: string }) => void;
21
25
  }
22
26
 
@@ -65,18 +69,16 @@ export const memoryWrite = {
65
69
  }
66
70
 
67
71
  try {
68
- const memory = getMemory() as { facts?: string[] };
69
- if (!Array.isArray(memory.facts)) memory.facts = [];
70
-
72
+ const memory = getMemory();
71
73
  const fact = String(args.fact).trim();
72
- const alreadyKnown = memory.facts.includes(fact);
74
+ const workspace = dependencies?.parentLoop?.workspaceRoot || dependencies?.workspaceRoot;
75
+ const { memory: updated, alreadyKnown } = recordScopedFact(memory, fact, {
76
+ workspace,
77
+ maxFacts: MAX_FACTS
78
+ });
73
79
 
74
80
  if (!alreadyKnown) {
75
- memory.facts.push(fact);
76
- while (memory.facts.length > MAX_FACTS) {
77
- memory.facts.shift();
78
- }
79
- saveMemory(memory);
81
+ saveMemory(updated);
80
82
  }
81
83
 
82
84
  let creativeSaved = false;
@@ -104,7 +106,7 @@ export const memoryWrite = {
104
106
 
105
107
  const notes = [
106
108
  alreadyKnown ? 'Fact already known, not duplicated.' : 'Fact saved.',
107
- `Total persistent facts: ${memory.facts.length}.`,
109
+ `Total persistent facts: ${updated.facts.length}.`,
108
110
  creativeSaved ? 'Creative pattern recorded in the V5 Cortex.' : ''
109
111
  ].filter(Boolean);
110
112
 
@@ -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
  };
@@ -9,6 +9,7 @@
9
9
  * interval-based renderer.
10
10
  */
11
11
  import { stdout } from 'node:process';
12
+ import { safeDisplay } from './text.js';
12
13
  const BRAILLE_DOTS = [
13
14
  [0, 0, 0x01], [0, 1, 0x02], [0, 2, 0x04], [0, 3, 0x40],
14
15
  [1, 0, 0x08], [1, 1, 0x10], [1, 2, 0x20], [1, 3, 0x80],
@@ -53,8 +54,12 @@ function smoothstep(t) {
53
54
  const x = Math.max(0, Math.min(1, t));
54
55
  return x * x * (3 - 2 * x);
55
56
  }
57
+ function clampRotorRange(value, min, max, fallback) {
58
+ const numeric = Number(value ?? fallback);
59
+ return Number.isFinite(numeric) ? Math.max(min, Math.min(max, Math.floor(numeric))) : fallback;
60
+ }
56
61
  export function getAngle(elapsedMs, motion = 'heavy') {
57
- const t = Math.max(0, elapsedMs);
62
+ const t = Number.isFinite(elapsedMs) ? Math.max(0, elapsedMs) : 0;
58
63
  if (motion === 'smooth')
59
64
  return (t / 4200) * TAU;
60
65
  if (motion === 'pulse') {
@@ -94,8 +99,8 @@ function paint(text, kind, color) {
94
99
  * Intended for an existing TUI's render() method.
95
100
  */
96
101
  export function renderCausyneRotor(elapsedMs, options = {}) {
97
- const columns = Math.max(12, Math.min(56, Math.floor(options.columns ?? 24)));
98
- const rows = Math.max(6, Math.min(28, Math.floor(options.rows ?? 12)));
102
+ const columns = clampRotorRange(options.columns, 12, 56, 24);
103
+ const rows = clampRotorRange(options.rows, 6, 28, 12);
99
104
  const color = options.color ?? true;
100
105
  const angle = getAngle(elapsedMs, options.motion ?? 'heavy');
101
106
  const blades = Array.from({ length: 6 }, (_, i) => {
@@ -144,7 +149,10 @@ export function renderCausyneRotor(elapsedMs, options = {}) {
144
149
  lines.push(line);
145
150
  }
146
151
  if (options.label !== '') {
147
- const label = options.label ?? 'working';
152
+ const cleanLabel = options.label === undefined
153
+ ? 'working'
154
+ : safeDisplay(options.label).replace(/\s+/g, ' ').trim();
155
+ const label = cleanLabel || 'working';
148
156
  const status = color
149
157
  ? `${COLORS.lime}●${COLORS.reset} ${COLORS.text}${label}${COLORS.reset}`
150
158
  : `● ${label}`;
@@ -160,10 +168,13 @@ export function renderCausyneRotor(elapsedMs, options = {}) {
160
168
  export function startCausyneRotor(options = {}) {
161
169
  const color = options.color ?? (Boolean(stdout.isTTY) && !process.env.NO_COLOR && !process.env.CAUSYNE_NO_COLOR);
162
170
  if (!stdout.isTTY) {
163
- stdout.write((options.label ?? 'working') + '\n');
171
+ const label = options.label === undefined
172
+ ? 'working'
173
+ : safeDisplay(options.label).replace(/\s+/g, ' ').trim();
174
+ stdout.write(label + '\n');
164
175
  return { stop() { } };
165
176
  }
166
- const fps = Math.max(4, Math.min(30, options.fps ?? 16));
177
+ const fps = clampRotorRange(options.fps, 4, 30, 16);
167
178
  const started = Date.now();
168
179
  let stopped = false;
169
180
  let lastLines = 0;
@@ -217,18 +228,21 @@ export function getRotorSpinnerFrames(color = true, unicode = true) {
217
228
  }
218
229
  export function getRotorSpinnerFrame(tick, color = true, unicode = true) {
219
230
  const frames = getRotorSpinnerFrames(color, unicode);
220
- const index = Math.abs(Math.floor(tick)) % frames.length;
231
+ const safeTick = Number.isFinite(tick) ? Math.abs(Math.floor(tick)) : 0;
232
+ const index = safeTick % frames.length;
221
233
  return frames[index] ?? frames[0] ?? '⠇⠙';
222
234
  }
223
235
  const DOT_FRAMES = [' ', '. ', '.. ', '...'];
224
236
  export function getAnimatedDots(tick) {
225
- const stage = Math.floor(Math.abs(Math.floor(tick)) / 2) % DOT_FRAMES.length;
237
+ const safeTick = Number.isFinite(tick) ? Math.abs(Math.floor(tick)) : 0;
238
+ const stage = Math.floor(safeTick / 2) % DOT_FRAMES.length;
226
239
  return DOT_FRAMES[stage] ?? ' ';
227
240
  }
228
241
  export function formatAnimatedStatus(message, tick) {
229
- let base = (message || 'working').trimEnd();
242
+ let base = safeDisplay(message ?? '').replace(/\s+/g, ' ').trimEnd();
230
243
  while (base.endsWith('.') || base.endsWith('…')) {
231
244
  base = base.slice(0, -1).trimEnd();
232
245
  }
233
- return `${base}${getAnimatedDots(tick)}`;
246
+ const label = base.trim().length > 0 ? base : 'working';
247
+ return `${label}${getAnimatedDots(tick)}`;
234
248
  }