@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
@@ -15,23 +15,106 @@ export interface ScaffoldingPayload {
15
15
  entryPoint: string;
16
16
  }
17
17
 
18
+ /**
19
+ * Words that cannot be used as a generated export binding. Modules are always
20
+ * strict, so `delete`, `default`, `eval`, `arguments`, and friends would make
21
+ * the generated module fail to parse.
22
+ */
23
+ const RESERVED_IDENTIFIERS = new Set([
24
+ 'arguments', 'await', 'break', 'case', 'catch', 'class', 'const', 'continue',
25
+ 'debugger', 'default', 'delete', 'do', 'else', 'enum', 'eval', 'export',
26
+ 'extends', 'false', 'finally', 'for', 'function', 'if', 'implements',
27
+ 'import', 'in', 'instanceof', 'interface', 'let', 'new', 'null', 'package',
28
+ 'private', 'protected', 'public', 'return', 'static', 'super', 'switch',
29
+ 'this', 'throw', 'true', 'try', 'typeof', 'var', 'void', 'while', 'with',
30
+ 'yield'
31
+ ]);
32
+
33
+ /**
34
+ * Quotes a value for safe display inside a POSIX shell command line.
35
+ */
36
+ export function shellQuote(value: string): string {
37
+ return `'${value.replace(/'/g, "'\\''")}'`;
38
+ }
39
+
18
40
  /**
19
41
  * Sanitizes an arbitrary tool or parameter name into a valid JavaScript identifier.
20
42
  * Prevents syntax errors when tools contain hyphens (e.g. "get-weather" -> "get_weather").
21
43
  */
22
44
  export function sanitizeIdentifier(name: string): string {
23
45
  const cleaned = name.replace(/[^a-zA-Z0-9_]/g, '_');
24
- return /^[0-9]/.test(cleaned) ? `_${cleaned}` : (cleaned || 'fn');
46
+ const identifier = /^[0-9]/.test(cleaned) ? `_${cleaned}` : (cleaned || 'fn');
47
+ return RESERVED_IDENTIFIERS.has(identifier) ? `${identifier}_` : identifier;
48
+ }
49
+
50
+ /**
51
+ * Keeps user-supplied text inside a generated comment. A description that
52
+ * contains a comment terminator would otherwise escape the docblock and run
53
+ * as generated JavaScript.
54
+ */
55
+ export function sanitizeComment(text: string): string {
56
+ return String(text ?? '')
57
+ .replace(/\*\//g, '*\\/')
58
+ .replace(/[\u0000-\u001f\u007f]/g, ' ')
59
+ .trim();
25
60
  }
26
61
 
27
62
  /**
28
- * Computes the canonical export name for a tool within an index.js ES module.
29
- * The primary tool is always exported as "execute" (the default runner contract).
30
- * Additional tools are exported with their sanitized identifier.
63
+ * Keeps user-supplied text inert inside generated Python comments and
64
+ * docstrings. Newlines would start a new statement, a triple quote would end
65
+ * the docstring early, and a trailing backslash would escape its delimiter.
31
66
  */
32
- function getExportName(tool: ServiceToolDescriptor, index: number): string {
33
- if (index === 0) return 'execute';
34
- return sanitizeIdentifier(tool.name);
67
+ export function sanitizePythonText(text: string): string {
68
+ return String(text ?? '')
69
+ .replace(/\\/g, '\\\\')
70
+ .replace(/"""/g, "'''")
71
+ .replace(/[\u0000-\u001f\u007f]/g, ' ')
72
+ .trim();
73
+ }
74
+
75
+ /**
76
+ * Computes canonical export names for every tool in a module.
77
+ * The primary tool is always exported as "execute" (the default runner
78
+ * contract). Additional tools receive sanitized identifiers, disambiguated
79
+ * when two tool names collapse to the same binding (e.g. "get-user" and
80
+ * "get_user").
81
+ */
82
+ function buildExportNames(tools: ServiceToolDescriptor[]): string[] {
83
+ const used = new Set<string>(['execute']);
84
+ return tools.map((tool, index) => {
85
+ if (index === 0) return 'execute';
86
+ const base = sanitizeIdentifier(tool.name);
87
+ let name = base;
88
+ let suffix = 2;
89
+ while (used.has(name)) name = `${base}_${suffix++}`;
90
+ used.add(name);
91
+ return name;
92
+ });
93
+ }
94
+
95
+ /**
96
+ * Builds the generated auth setup. The env var keeps the secret out of the
97
+ * manifest while authType selects the header shape the API expects.
98
+ */
99
+ function buildAuthSetup(service: ServiceDescriptor): string {
100
+ if (!service.authEnvVar || service.authType === 'none') {
101
+ return 'const authHeader = undefined;';
102
+ }
103
+ const envAccess = `process.env[${JSON.stringify(service.authEnvVar)}]`;
104
+ const authType = service.authType || 'bearer';
105
+ let headerName = 'Authorization';
106
+ let valueExpression: string;
107
+ if (authType === 'basic') {
108
+ valueExpression = `\`Basic \${Buffer.from(${envAccess}).toString('base64')}\``;
109
+ } else if (authType === 'apiKey') {
110
+ headerName = 'X-API-Key';
111
+ valueExpression = envAccess;
112
+ } else if (authType === 'env') {
113
+ valueExpression = envAccess;
114
+ } else {
115
+ valueExpression = `\`Bearer \${${envAccess}}\``;
116
+ }
117
+ return `const authHeader = ${envAccess} ? { name: ${JSON.stringify(headerName)}, value: ${valueExpression} } : undefined;`;
35
118
  }
36
119
 
37
120
  /**
@@ -39,11 +122,12 @@ function getExportName(tool: ServiceToolDescriptor, index: number): string {
39
122
  */
40
123
  export function generateHttpPluginScaffold(service: ServiceDescriptor): ScaffoldingPayload {
41
124
  const capabilities = Array.from(new Set(['network', ...(service.capabilities || [])]));
42
- const primaryTool = service.tools[0] || {
125
+ const effectiveTools: ServiceToolDescriptor[] = service.tools.length > 0 ? service.tools : [{
43
126
  name: 'query',
44
127
  description: `Execute request against ${service.name}`,
45
128
  parameters: { type: 'object', properties: {} }
46
- };
129
+ }];
130
+ const exportNames = buildExportNames(effectiveTools);
47
131
 
48
132
  const manifest = {
49
133
  schemaVersion: 1,
@@ -51,53 +135,69 @@ export function generateHttpPluginScaffold(service: ServiceDescriptor): Scaffold
51
135
  version: '1.0.0',
52
136
  description: service.description || `Native HTTP plugin for ${service.name}`,
53
137
  capabilities,
54
- tools: service.tools.map((tool, idx) => ({
138
+ tools: effectiveTools.map((tool, idx) => ({
55
139
  name: tool.name,
56
140
  description: tool.description,
57
141
  parameters: tool.parameters,
58
142
  entry: 'index.js',
59
- export: getExportName(tool, idx),
143
+ export: exportNames[idx],
60
144
  timeoutMs: 30000
61
145
  }))
62
146
  };
63
147
 
64
- const toolExecutors = service.tools.map((tool, idx) => {
65
- const fnName = getExportName(tool, idx);
148
+ const toolExecutors = effectiveTools.map((tool, idx) => {
149
+ const fnName = exportNames[idx];
66
150
  const httpMethod = tool.httpMethod || 'POST';
67
151
  const httpPath = tool.httpPath || '/';
68
152
  return `
69
153
  /**
70
- * ${tool.description}
154
+ * ${sanitizeComment(tool.description)}
71
155
  */
72
156
  export async function ${fnName}(args = {}, context = {}) {
73
157
  const endpoint = ${JSON.stringify(service.endpoint || 'https://api.example.com')};
74
158
  const base = endpoint.endsWith('/') ? endpoint : endpoint + '/';
75
- const rel = ${JSON.stringify(httpPath)}.startsWith('/') ? ${JSON.stringify(httpPath)}.slice(1) : ${JSON.stringify(httpPath)};
76
- const url = new URL(rel, base);
159
+ const rawPath = ${JSON.stringify(httpPath)};
160
+ const pathParamNames = Array.from(rawPath.matchAll(/\\{([^}]+)\\}/g), match => match[1]);
161
+ const requestArgs = args && typeof args === 'object' ? { ...args } : {};
162
+ const missingPathParams = pathParamNames.filter(key => requestArgs[key] === undefined || requestArgs[key] === null);
163
+ if (missingPathParams.length > 0) {
164
+ return { success: false, error: \`Missing path parameter(s): \${missingPathParams.join(', ')}\` };
165
+ }
166
+ let url;
167
+ try {
168
+ const rel = rawPath.replace(/\\{([^}]+)\\}/g, (_match, key) => encodeURIComponent(String(requestArgs[key])));
169
+ for (const key of pathParamNames) delete requestArgs[key];
170
+ const targetPath = rel.startsWith('/') ? rel.slice(1) : rel;
171
+ url = new URL(targetPath, base);
172
+ } catch (err) {
173
+ return { success: false, error: \`Invalid request URL: \${err instanceof Error ? err.message : String(err)}\` };
174
+ }
77
175
 
78
- if (${JSON.stringify(httpMethod)} === 'GET' && args && typeof args === 'object') {
79
- for (const [k, v] of Object.entries(args)) {
80
- if (v !== undefined && v !== null) url.searchParams.append(k, String(v));
81
- }
176
+ if (${JSON.stringify(httpMethod)} === 'GET' && requestArgs && typeof requestArgs === 'object') {
177
+ const appendQuery = (key, value) => {
178
+ if (value === undefined || value === null) return;
179
+ if (Array.isArray(value)) {
180
+ for (const item of value) appendQuery(key, item);
181
+ return;
182
+ }
183
+ url.searchParams.append(key, typeof value === 'object' ? JSON.stringify(value) : String(value));
184
+ };
185
+ for (const [k, v] of Object.entries(requestArgs)) appendQuery(k, v);
82
186
  }
83
187
 
84
- const authHeader = ${
85
- service.authEnvVar
86
- ? `process.env[${JSON.stringify(service.authEnvVar)}] ? \`Bearer \${process.env[${JSON.stringify(service.authEnvVar)}]}\` : undefined`
87
- : 'undefined'
88
- };
188
+ ${buildAuthSetup(service)}
89
189
 
90
190
  const headers = {
91
191
  'Accept': 'application/json',
92
192
  'Content-Type': 'application/json'
93
193
  };
94
- if (authHeader) headers['Authorization'] = authHeader;
194
+ if (authHeader) headers[authHeader.name] = authHeader.value;
95
195
 
96
196
  try {
97
197
  const response = await fetch(url.toString(), {
98
198
  method: ${JSON.stringify(httpMethod)},
99
199
  headers,
100
- body: ${httpMethod !== 'GET' ? 'JSON.stringify(args)' : 'undefined'}
200
+ body: ${httpMethod !== 'GET' ? 'JSON.stringify(requestArgs)' : 'undefined'}
101
201
  });
102
202
 
103
203
  if (!response.ok) {
@@ -143,7 +243,7 @@ ${service.authEnvVar ? `- **Environment Variable**: Set \`${service.authEnvVar}\
143
243
  By default, this plugin is created in a **disabled** state to allow code review.
144
244
  To activate after reviewing the code:
145
245
  \`\`\`bash
146
- causyne plugins enable ${service.name}
246
+ /plugins enable ${service.name}
147
247
  \`\`\`
148
248
  `;
149
249
 
@@ -162,11 +262,12 @@ causyne plugins enable ${service.name}
162
262
  */
163
263
  export function generateCliPluginScaffold(service: ServiceDescriptor): ScaffoldingPayload {
164
264
  const capabilities = Array.from(new Set(['subprocess', ...(service.capabilities || [])]));
165
- const primaryTool = service.tools[0] || {
265
+ const effectiveTools: ServiceToolDescriptor[] = service.tools.length > 0 ? service.tools : [{
166
266
  name: 'run',
167
267
  description: `Execute command for ${service.name}`,
168
268
  parameters: { type: 'object', properties: {} }
169
- };
269
+ }];
270
+ const exportNames = buildExportNames(effectiveTools);
170
271
 
171
272
  const manifest = {
172
273
  schemaVersion: 1,
@@ -174,22 +275,22 @@ export function generateCliPluginScaffold(service: ServiceDescriptor): Scaffoldi
174
275
  version: '1.0.0',
175
276
  description: service.description || `Native CLI plugin for ${service.name}`,
176
277
  capabilities,
177
- tools: service.tools.map((tool, idx) => ({
278
+ tools: effectiveTools.map((tool, idx) => ({
178
279
  name: tool.name,
179
280
  description: tool.description,
180
281
  parameters: tool.parameters,
181
282
  entry: 'index.js',
182
- export: getExportName(tool, idx),
283
+ export: exportNames[idx],
183
284
  timeoutMs: 45000
184
285
  }))
185
286
  };
186
287
 
187
- const toolExecutors = service.tools.map((tool, idx) => {
188
- const fnName = getExportName(tool, idx);
288
+ const toolExecutors = effectiveTools.map((tool, idx) => {
289
+ const fnName = exportNames[idx];
189
290
  const binary = service.cliBinary || service.name;
190
291
  return `
191
292
  /**
192
- * ${tool.description}
293
+ * ${sanitizeComment(tool.description)}
193
294
  */
194
295
  export async function ${fnName}(args = {}, context = {}) {
195
296
  const { execFile } = await import('node:child_process');
@@ -198,7 +299,7 @@ export async function ${fnName}(args = {}, context = {}) {
198
299
 
199
300
  const bin = ${JSON.stringify(binary)};
200
301
  const cliArgs = [];
201
- ${tool.cliSubcommand ? `cliArgs.push(${JSON.stringify(tool.cliSubcommand)});` : ''}
302
+ ${tool.cliSubcommand ? `cliArgs.push(...${JSON.stringify(tool.cliSubcommand)}.split(/\\s+/).filter(Boolean));` : ''}
202
303
 
203
304
  for (const [key, val] of Object.entries(args || {})) {
204
305
  if (val === true) cliArgs.push(\`--\${key}\`);
@@ -250,7 +351,7 @@ ${service.description}
250
351
  ## Security & Activation
251
352
  This plugin is created disabled. After verifying the source code:
252
353
  \`\`\`bash
253
- causyne plugins enable ${service.name}
354
+ /plugins enable ${service.name}
254
355
  \`\`\`
255
356
  `;
256
357
 
@@ -270,11 +371,12 @@ causyne plugins enable ${service.name}
270
371
  */
271
372
  export function generatePythonBridgeScaffold(service: ServiceDescriptor): ScaffoldingPayload {
272
373
  const capabilities = Array.from(new Set(['subprocess', ...(service.capabilities || [])]));
273
- const primaryTool = service.tools[0] || {
374
+ const effectiveTools: ServiceToolDescriptor[] = service.tools.length > 0 ? service.tools : [{
274
375
  name: 'run_python',
275
376
  description: `Execute Python workflow for ${service.name}`,
276
377
  parameters: { type: 'object', properties: {} }
277
- };
378
+ }];
379
+ const exportNames = buildExportNames(effectiveTools);
278
380
 
279
381
  const manifest = {
280
382
  schemaVersion: 1,
@@ -282,22 +384,22 @@ export function generatePythonBridgeScaffold(service: ServiceDescriptor): Scaffo
282
384
  version: '1.0.0',
283
385
  description: service.description || `Python bridge plugin for ${service.name}`,
284
386
  capabilities,
285
- tools: service.tools.map((tool, idx) => ({
387
+ tools: effectiveTools.map((tool, idx) => ({
286
388
  name: tool.name,
287
389
  description: tool.description,
288
390
  parameters: tool.parameters,
289
391
  entry: 'index.js',
290
- export: getExportName(tool, idx),
392
+ export: exportNames[idx],
291
393
  timeoutMs: 60000
292
394
  }))
293
395
  };
294
396
 
295
- const toolExecutors = service.tools.map((tool, idx) => {
296
- const fnName = getExportName(tool, idx);
397
+ const toolExecutors = effectiveTools.map((tool, idx) => {
398
+ const fnName = exportNames[idx];
297
399
  const pythonMethod = tool.pythonMethod || tool.name;
298
400
  return `
299
401
  /**
300
- * ${tool.description}
402
+ * ${sanitizeComment(tool.description)}
301
403
  */
302
404
  export async function ${fnName}(args = {}, context = {}) {
303
405
  return invokePythonBridge(${JSON.stringify(pythonMethod)}, args, context);
@@ -314,6 +416,7 @@ import { fileURLToPath } from 'node:url';
314
416
 
315
417
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
316
418
  const BRIDGE_SCRIPT = path.join(__dirname, 'bridge.py');
419
+ const PYTHON_BIN = process.env.CAUSYNE_PYTHON || (process.platform === 'win32' ? 'python' : 'python3');
317
420
 
318
421
  async function invokePythonBridge(action, args, context) {
319
422
  const payload = JSON.stringify({
@@ -325,7 +428,7 @@ async function invokePythonBridge(action, args, context) {
325
428
  });
326
429
 
327
430
  return new Promise((resolve) => {
328
- const child = spawn('python3', [BRIDGE_SCRIPT], {
431
+ const child = spawn(PYTHON_BIN, [BRIDGE_SCRIPT], {
329
432
  stdio: ['pipe', 'pipe', 'pipe'],
330
433
  env: { ...process.env, PYTHONUNBUFFERED: '1' }
331
434
  });
@@ -352,16 +455,23 @@ async function invokePythonBridge(action, args, context) {
352
455
  child.on('error', (err) => {
353
456
  finish({
354
457
  success: false,
355
- error: \`Failed to spawn python3: \${err.message}. Ensure python3 is installed and in PATH.\`
458
+ error: \`Failed to spawn \${PYTHON_BIN}: \${err.message}. Ensure Python 3 is installed and in PATH.\`
459
+ });
460
+ });
461
+
462
+ child.stdin.on('error', (err) => {
463
+ finish({
464
+ success: false,
465
+ error: \`Python bridge stdin error: \${err.message}\`
356
466
  });
357
467
  });
358
468
 
359
469
  child.on('close', (code) => {
360
- if (code !== 0 && !stdout.trim()) {
470
+ if (!stdout.trim()) {
361
471
  finish({
362
472
  success: false,
363
473
  exitCode: code,
364
- error: stderr.trim() || \`Python bridge exited with code \${code}\`
474
+ error: stderr.trim() || \`Python bridge returned no output (exit code \${code})\`
365
475
  });
366
476
  return;
367
477
  }
@@ -388,14 +498,16 @@ ${toolExecutors}
388
498
  `;
389
499
 
390
500
  const pythonModule = service.pythonModule || service.name;
501
+ const safeServiceName = sanitizePythonText(service.name);
502
+ const safePythonModule = sanitizePythonText(pythonModule);
391
503
  const bridgePy = `#!/usr/bin/env python3
392
504
  # -*- coding: utf-8 -*-
393
505
  """
394
- Python Bridge for ${service.name}
506
+ Python Bridge for ${safeServiceName}
395
507
  Auto-generated by Causyne PluginsFactory
396
508
 
397
509
  Communicates with Causyne Agent via JSON on stdin/stdout.
398
- Provides on-demand buffer for ${pythonModule}.
510
+ Provides on-demand buffer for ${safePythonModule}.
399
511
  """
400
512
 
401
513
  import sys
@@ -409,7 +521,7 @@ def handle_request(payload):
409
521
 
410
522
  try:
411
523
  # Dynamically reference target python module
412
- # import ${pythonModule}
524
+ # import ${safePythonModule}
413
525
 
414
526
  result = {
415
527
  "action": action,
@@ -467,7 +579,7 @@ python3 --version
467
579
  ## Security & Activation
468
580
  This plugin is created disabled. Review the code in \`bridge.py\` and \`index.js\`, then enable:
469
581
  \`\`\`bash
470
- causyne plugins enable ${service.name}
582
+ /plugins enable ${service.name}
471
583
  \`\`\`
472
584
  `;
473
585
 
@@ -531,6 +643,10 @@ function send(message) {
531
643
  function handleRequest(request) {
532
644
  const { id, method, params } = request;
533
645
 
646
+ // JSON-RPC notifications carry no id and must never receive a response,
647
+ // even when they use a request-style method such as tools/list.
648
+ if (id === undefined) return null;
649
+
534
650
  switch (method) {
535
651
  case 'initialize':
536
652
  return {
@@ -575,7 +691,7 @@ function handleRequest(request) {
575
691
  return {
576
692
  id,
577
693
  jsonrpc: '2.0',
578
- error: { code: -32601, message: \`Tool '\${toolName}' not found\` }
694
+ error: { code: -32602, message: \`Unknown tool: '\${toolName}'\` }
579
695
  };
580
696
  }
581
697
 
@@ -618,6 +734,10 @@ rl.on('line', (line) => {
618
734
  if (!trimmed) return;
619
735
  try {
620
736
  const request = JSON.parse(trimmed);
737
+ if (!request || typeof request !== 'object' || Array.isArray(request)) {
738
+ send({ jsonrpc: '2.0', id: null, error: { code: -32600, message: 'Invalid Request' } });
739
+ return;
740
+ }
621
741
  const response = handleRequest(request);
622
742
  if (response) send(response);
623
743
  } catch (err) {
@@ -646,7 +766,7 @@ Where feasible, prefer native plugins or Python bridges for higher token efficie
646
766
  ## Registration & Grant
647
767
  In Causyne Agent, register and review this server:
648
768
  \`\`\`bash
649
- causyne mcp add ${service.name} node ~/.causyne/mcp-servers/${service.name}/server.js
769
+ causyne mcp add ${service.name} node "$HOME/.causyne/mcp-servers/${service.name}/server.js"
650
770
  causyne mcp grant ${service.name}
651
771
  \`\`\`
652
772
  `;
@@ -7,7 +7,7 @@
7
7
  *
8
8
  * Authorship: Strict TypeScript (Causyne Agent).
9
9
  */
10
- import { PACK_PLAYBOOKS, isWebIntent } from './toolPacks.js';
10
+ import { PACK_PLAYBOOKS, isReverseEngineeringIntent, isWebIntent } from './toolPacks.js';
11
11
  import { isMutatingToolCall, isPureSkillOrCapabilityLookup, redactSkillAndQueryLiterals } from './decisionPolicy.js';
12
12
  const INSPECTION_TOOLS = new Set([
13
13
  'fs_read', 'fs_list', 'fs_find', 'fs_search', 'grep_search', 'code_searcher',
@@ -134,10 +134,9 @@ const EXPLICIT_MEDIA_GENERATION_PATTERN = /\b(blender|3d model|render 3d|render
134
134
  const EXPLICIT_WEB_ENGINEERING_PATTERN = /\b(build|create|make|design|develop|implement|redesign|buat\w*)\b[\s\S]*(?:\b(web|website|webpage|webapp|landing page|dashboard|ui|frontend|webgl|canvas|cad view|cad viewer|cad style view|3d view|3d viewer|3d configurator|3d visualizer)\b|(?:threejs|three\.js|thre\.?js|3js|babylon\.?js|pixi\.js|d3\.js|p5\.js|chart\.js)\b)/i;
135
135
  // Explicit game development intent
136
136
  const EXPLICIT_GAME_DEV_PATTERN = /(?:\b(?:build|create|make|design|develop|scaffold|render|animate|code|program|buat\w*|bikin\w*)[\s\S]*(?:game|simulation|simulator|simulasi|interactive|3d|three\.?js|threejs|webgl|canvas3d|babylonjs|godot|unity|unreal|platformer|rpg|arcade)\b|\b(?:game|gamedev|godot|unity|unreal|platformer|rpg|arcade|simulator|simulation|simulasi|interactive)\b|\b3d\s*(?:game|app|simulator|simulation|scene|city|world|view|body|human|anatomy|model|mesh|character|rendering|visualization|experience|space|environment)\b|\bin 3d\b|[-_]3d\b|\b3d[-_]|\b(?:threejs|three\.js|webgl|canvas3d|babylonjs)\b)/i;
137
- // Explicit reverse engineering and binary analysis intent
138
- const EXPLICIT_REVERSE_ENGINEERING_PATTERN = /\b(reverse[-_ ]?engineering|decompile|disassemble|disasm|apk|aab|dex|radare|rizin|ghidra|jadx|apktool|mach-o|elf binary|portable executable|\.apk\b|\.aab\b|\.dex\b|\.so\b|\.dylib\b|\.wasm\b|\.asar\b)\b/i;
137
+ // Explicit reverse engineering and binary analysis intent is defined in toolPacks.ts (isReverseEngineeringIntent).
139
138
  // Explicit software and systems engineering intent (backend, APIs, refactoring, algorithms, testing, architecture, CLI tools, Android/mobile)
140
- const EXPLICIT_SOFTWARE_ENGINEERING_PATTERN = /(?:\b(?:build|create|code|program|develop|refactor|debug|fix|implement|test|optimize|write|add|modify|migrate|architect|architecture|engineer|benchmark|profile|audit|scaffold)\b[\s\S]*\b(?:api|backend|service|microservice|server|database|schema|endpoint|controller|auth|test|spec|algorithm|function|module|class|feature|script|pipeline|codebase|repo|repository|bug|issue|engine|tool|cli|library|sdk|migration|handler|worker|queue|stream|app|application|compose|jetpack|android|gradle|package)\b|\b(?:python|rust|golang|c\+\+|cpp|java|kotlin|swift|csharp|typescript|javascript|ruby|php|sql|bash|shell|docker|k8s|kubernetes|gradle|compose|android)\b)/i;
139
+ const EXPLICIT_SOFTWARE_ENGINEERING_PATTERN = /(?:\b(?:build|create|code|program|develop|refactor|debug|fix|implement|test|optimize|write|add|modify|migrate|architect|architecture|engineer|benchmark|profile|audit|scaffold|bump|export)\b[\s\S]*\b(?:api|backend|service|microservice|server|database|schema|endpoint|controller|auth|test|spec|algorithm|function|module|class|feature|script|pipeline|codebase|repo|repository|bug|issue|engine|tool|cli|library|sdk|migration|handler|worker|queue|stream|app|application|compose|jetpack|android|gradle|package|apk|aab|bundle|version)\b|\b(?:python|rust|golang|c\+\+|cpp|java|kotlin|swift|csharp|typescript|javascript|ruby|php|sql|bash|shell|docker|k8s|kubernetes|gradle|compose|android|apk|aab)\b)/i;
141
140
  /**
142
141
  * Select tools to preload based on prompt intent. This is never an allowlist:
143
142
  * tool_search can add capabilities as the task develops.
@@ -165,7 +164,7 @@ export function determineToolScope(prompt, _taskShape) {
165
164
  }
166
165
  const effectiveText = redactSkillAndQueryLiterals(text);
167
166
  // 1. Reverse engineering & binary analysis intent
168
- if (EXPLICIT_REVERSE_ENGINEERING_PATTERN.test(effectiveText)) {
167
+ if (isReverseEngineeringIntent(effectiveText)) {
169
168
  const tools = new Set([
170
169
  'reverse_engineering',
171
170
  'fs_read',
@@ -8,7 +8,7 @@
8
8
  * Authorship: Strict TypeScript (Causyne Agent).
9
9
  */
10
10
 
11
- import { PACK_PLAYBOOKS, isWebIntent } from './toolPacks.js';
11
+ import { PACK_PLAYBOOKS, isReverseEngineeringIntent, isWebIntent } from './toolPacks.js';
12
12
  import {
13
13
  isMutatingToolCall,
14
14
  isPureSkillOrCapabilityLookup,
@@ -185,13 +185,11 @@ const EXPLICIT_WEB_ENGINEERING_PATTERN =
185
185
  const EXPLICIT_GAME_DEV_PATTERN =
186
186
  /(?:\b(?:build|create|make|design|develop|scaffold|render|animate|code|program|buat\w*|bikin\w*)[\s\S]*(?:game|simulation|simulator|simulasi|interactive|3d|three\.?js|threejs|webgl|canvas3d|babylonjs|godot|unity|unreal|platformer|rpg|arcade)\b|\b(?:game|gamedev|godot|unity|unreal|platformer|rpg|arcade|simulator|simulation|simulasi|interactive)\b|\b3d\s*(?:game|app|simulator|simulation|scene|city|world|view|body|human|anatomy|model|mesh|character|rendering|visualization|experience|space|environment)\b|\bin 3d\b|[-_]3d\b|\b3d[-_]|\b(?:threejs|three\.js|webgl|canvas3d|babylonjs)\b)/i;
187
187
 
188
- // Explicit reverse engineering and binary analysis intent
189
- const EXPLICIT_REVERSE_ENGINEERING_PATTERN =
190
- /\b(reverse[-_ ]?engineering|decompile|disassemble|disasm|apk|aab|dex|radare|rizin|ghidra|jadx|apktool|mach-o|elf binary|portable executable|\.apk\b|\.aab\b|\.dex\b|\.so\b|\.dylib\b|\.wasm\b|\.asar\b)\b/i;
188
+ // Explicit reverse engineering and binary analysis intent is defined in toolPacks.ts (isReverseEngineeringIntent).
191
189
 
192
190
  // Explicit software and systems engineering intent (backend, APIs, refactoring, algorithms, testing, architecture, CLI tools, Android/mobile)
193
191
  const EXPLICIT_SOFTWARE_ENGINEERING_PATTERN =
194
- /(?:\b(?:build|create|code|program|develop|refactor|debug|fix|implement|test|optimize|write|add|modify|migrate|architect|architecture|engineer|benchmark|profile|audit|scaffold)\b[\s\S]*\b(?:api|backend|service|microservice|server|database|schema|endpoint|controller|auth|test|spec|algorithm|function|module|class|feature|script|pipeline|codebase|repo|repository|bug|issue|engine|tool|cli|library|sdk|migration|handler|worker|queue|stream|app|application|compose|jetpack|android|gradle|package)\b|\b(?:python|rust|golang|c\+\+|cpp|java|kotlin|swift|csharp|typescript|javascript|ruby|php|sql|bash|shell|docker|k8s|kubernetes|gradle|compose|android)\b)/i;
192
+ /(?:\b(?:build|create|code|program|develop|refactor|debug|fix|implement|test|optimize|write|add|modify|migrate|architect|architecture|engineer|benchmark|profile|audit|scaffold|bump|export)\b[\s\S]*\b(?:api|backend|service|microservice|server|database|schema|endpoint|controller|auth|test|spec|algorithm|function|module|class|feature|script|pipeline|codebase|repo|repository|bug|issue|engine|tool|cli|library|sdk|migration|handler|worker|queue|stream|app|application|compose|jetpack|android|gradle|package|apk|aab|bundle|version)\b|\b(?:python|rust|golang|c\+\+|cpp|java|kotlin|swift|csharp|typescript|javascript|ruby|php|sql|bash|shell|docker|k8s|kubernetes|gradle|compose|android|apk|aab)\b)/i;
195
193
 
196
194
  /**
197
195
  * Select tools to preload based on prompt intent. This is never an allowlist:
@@ -226,7 +224,7 @@ export function determineToolScope(
226
224
  const effectiveText = redactSkillAndQueryLiterals(text);
227
225
 
228
226
  // 1. Reverse engineering & binary analysis intent
229
- if (EXPLICIT_REVERSE_ENGINEERING_PATTERN.test(effectiveText)) {
227
+ if (isReverseEngineeringIntent(effectiveText)) {
230
228
  const tools = new Set([
231
229
  'reverse_engineering',
232
230
  'fs_read',
package/src/taskShape.js CHANGED
@@ -85,6 +85,19 @@ const ARCHETYPES = {
85
85
  { name: 'Report', tools: [], note: 'Answer concisely and cite exact file paths or URLs. Do not modify anything unless asked.' }
86
86
  ]
87
87
  },
88
+ modify_repo: {
89
+ label: 'Inspect and update an existing project or build release artifact',
90
+ match: {
91
+ strong: ['bump', 'version code', 'version name', 'aab', 'apk', 'release', 'export', 'synchronize', 'sync', 'upgrade', 'migrate', 'rebuild'],
92
+ weak: ['version', 'bundle', 'existing', 'repo', 'repository', 'docs']
93
+ },
94
+ phases: [
95
+ { name: 'Orient in docs and structure', tools: ['fs_read', 'fs_list'], note: 'Read the workspace README, docs/ guides (e.g. ANDROID_RELEASE.md, ENGINEERING.md), and build scripts/manifests FIRST to follow the repository conventions.' },
96
+ { name: 'Apply targeted updates', tools: ['fs_read', 'fs_edit', 'MultiEdit'], note: 'Modify only the exact configuration, version fields, or source files required by the user request.' },
97
+ { name: 'Run documented build', tools: ['sysRun'], note: 'Execute the project’s documented build/export command for the requested deliverable only. Do not build unrelated web or side targets.' },
98
+ { name: 'Verify artifact', tools: ['sysRun', 'fs_read'], note: 'Verify the exact produced output (version, signature, alignment, tests) before reporting.' }
99
+ ]
100
+ },
88
101
  maintain: {
89
102
  label: 'Operate on files, processes or the machine itself',
90
103
  match: {
@@ -123,6 +136,12 @@ function scoreSignals(text, signals) {
123
136
  }
124
137
  return { score, hits };
125
138
  }
139
+ function isPureGreeting(prompt) {
140
+ const cleaned = String(prompt || '').trim().toLowerCase().replace(/[!?.]+$/g, '');
141
+ if (!cleaned)
142
+ return false;
143
+ return /^(?:hi+|hello+|hey+|yo+|sup|greetings|good\s+(?:morning|afternoon|evening)|thanks|thank\s+you|ok(?:ay)?)$/.test(cleaned);
144
+ }
126
145
  /**
127
146
  * Analyse a request into the shape of the work it implies.
128
147
  *
@@ -130,10 +149,12 @@ function scoreSignals(text, signals) {
130
149
  export function analyzeTask(prompt, workspaceContext = null) {
131
150
  const rawPrompt = String(prompt || '');
132
151
  const pureSkillLookup = isPureSkillOrCapabilityLookup(rawPrompt);
152
+ const pureGreeting = !pureSkillLookup && isPureGreeting(rawPrompt);
153
+ const lightweightLookup = pureSkillLookup || pureGreeting;
133
154
  const text = (pureSkillLookup ? redactSkillAndQueryLiterals(rawPrompt) : rawPrompt).toLowerCase();
134
155
  // Which capability packs are worth their token cost for this request.
135
156
  const packScores = [];
136
- if (!pureSkillLookup) {
157
+ if (!lightweightLookup) {
137
158
  for (const packName of Object.keys(PACK_SIGNALS)) {
138
159
  const signals = PACK_SIGNALS[packName];
139
160
  if (!signals)
@@ -147,12 +168,14 @@ export function analyzeTask(prompt, workspaceContext = null) {
147
168
  // Workspace evidence outranks keywords: a Godot project on disk is far more
148
169
  // reliable than any phrasing in the prompt. Pure skill/capability lookups
149
170
  // stay lightweight and never preload workspace app packs.
150
- if (workspaceContext && !pureSkillLookup) {
171
+ if (workspaceContext && !lightweightLookup) {
151
172
  const signals = [
152
173
  workspaceContext.framework,
153
174
  workspaceContext.projectType,
154
175
  workspaceContext.designSystem,
155
- Array.isArray(workspaceContext.keyFiles) ? workspaceContext.keyFiles.join(' ') : ''
176
+ Array.isArray(workspaceContext.keyFiles) ? workspaceContext.keyFiles.join(' ') : '',
177
+ Array.isArray(workspaceContext.subprojectStacks) ? workspaceContext.subprojectStacks.join(' ') : '',
178
+ Array.isArray(workspaceContext.buildFiles) ? workspaceContext.buildFiles.join(' ') : ''
156
179
  ].filter(Boolean).join(' ').toLowerCase();
157
180
  const bump = (name, amount) => {
158
181
  const existing = packScores.find(p => p.name === name);
@@ -161,10 +184,15 @@ export function analyzeTask(prompt, workspaceContext = null) {
161
184
  else
162
185
  packScores.push({ name, score: amount });
163
186
  };
164
- if (/godot|project\.godot|unity|\.tscn/.test(signals))
187
+ const hasGameProject = /godot|project\.godot|unity|\.tscn/.test(signals);
188
+ const hasExplicitWebFramework = /\b(react|vue|svelte|next|nuxt|astro|angular|tailwind|vite)\b/.test(signals);
189
+ const explicitNonWebTarget = /\b(aab|apk|gradle|android|godot|export_presets|tscn|gdscript|xcode|ipa|ios|rust|cargo)\b/.test(text);
190
+ const hasPromptWebSignal = /\b(web|website|html|css|browser|frontend|page|ui|dom|react|vue|svelte|vite|next|playwright|lighthouse|localhost)\b/.test(text);
191
+ if (hasGameProject)
165
192
  bump('game', 5);
166
- if (/react|vue|svelte|next|nuxt|astro|angular|tailwind|vite|index\.html/.test(signals))
193
+ if (!explicitNonWebTarget && (hasExplicitWebFramework || (!hasGameProject && /index\.html/.test(signals)) || (hasGameProject && /index\.html/.test(signals) && hasPromptWebSignal))) {
167
194
  bump('web', 4);
195
+ }
168
196
  }
169
197
  packScores.sort((a, b) => b.score - a.score);
170
198
  // Which archetype the work follows.
@@ -191,11 +219,25 @@ export function analyzeTask(prompt, workspaceContext = null) {
191
219
  bestArchetype = 'integrate';
192
220
  bestScore = integrationScore;
193
221
  }
194
- if (pureSkillLookup) {
222
+ const hasExistingRepo = Boolean(workspaceContext && ((Array.isArray(workspaceContext.keyFiles) && workspaceContext.keyFiles.length > 0)
223
+ || (Array.isArray(workspaceContext.buildFiles) && workspaceContext.buildFiles.length > 0)
224
+ || (Array.isArray(workspaceContext.docFiles) && workspaceContext.docFiles.length > 0)
225
+ || (Array.isArray(workspaceContext.subprojectStacks) && workspaceContext.subprojectStacks.length > 0)
226
+ || (workspaceContext.framework && !/^(?:none|unknown)$/i.test(String(workspaceContext.framework)))
227
+ || (workspaceContext.projectType && !/^(?:none|unknown)$/i.test(String(workspaceContext.projectType)))));
228
+ const explicitGreenfield = /\b(?:from\s+scratch|new\s+app(?:lication)?|new\s+project|greenfield|scaffold)\b/.test(text);
229
+ const explicitRepoReleaseOrModify = /\b(?:aab|apk|gradle|android|release|bump|versioncode|version|export|rebuild|update|upgrade|modify|extend|add\s+feature|existing|script)\b/.test(text);
230
+ if (!lightweightLookup && hasExistingRepo && (bestArchetype === 'build_app' || !bestArchetype) && !explicitGreenfield) {
231
+ if (bestArchetype !== 'build_app' || explicitRepoReleaseOrModify) {
232
+ bestArchetype = 'modify_repo';
233
+ bestScore = Math.max(bestScore, STRONG_WEIGHT);
234
+ }
235
+ }
236
+ if (lightweightLookup) {
195
237
  bestArchetype = 'research';
196
238
  bestScore = Math.max(bestScore, STRONG_WEIGHT);
197
239
  }
198
- const archetype = bestArchetype || 'build_app';
240
+ const archetype = bestArchetype || (hasExistingRepo ? 'modify_repo' : 'build_app');
199
241
  const confidence = bestScore >= 6 ? 'high' : (bestScore >= 3 ? 'medium' : 'low');
200
242
  const definition = ARCHETYPES[archetype];
201
243
  if (!definition)