@causyne/agent 1.20.39 → 1.20.41

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -9,7 +9,7 @@ Parameters
9
9
 
10
10
  Licensor: Ikbal Fadilah
11
11
 
12
- Licensed Work: Causyne Agent 1.20.39
12
+ Licensed Work: Causyne Agent 1.20.40
13
13
  The Licensed Work is (c) 2026 Ikbal Fadilah.
14
14
 
15
15
  Additional Use Grant: You may make use of the Licensed Work, provided that
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@causyne/agent",
3
- "version": "1.20.39",
3
+ "version": "1.20.41",
4
4
  "description": "Agentic AI for software, tools, and computer workflows",
5
5
  "main": "bin/causyne.js",
6
6
  "type": "module",
package/src/commands.js CHANGED
@@ -961,6 +961,47 @@ export const COMMANDS = [
961
961
  }
962
962
  },
963
963
 
964
+ {
965
+ name: 'thinking',
966
+ aliases: ['thought', 'thoughts'],
967
+ scope: 'local',
968
+ usage: '/thinking [toggle|expand|collapse]',
969
+ description: 'Toggle or fold thinking process chunks in the conversation transcript',
970
+ run: (argv, ctx) => {
971
+ const surface = ctx?.prompt?.surface;
972
+ const transcript = surface?.transcript;
973
+ if (!transcript || !Array.isArray(transcript.frames)) {
974
+ return ok('No active interactive transcript available.');
975
+ }
976
+ const reasoningFrames = transcript.frames.filter((f) => f.kind === 'reasoning');
977
+ if (reasoningFrames.length === 0) {
978
+ return ok('No thinking process frames found in the current conversation.');
979
+ }
980
+ const sub = (argv[0] || 'toggle').toLowerCase();
981
+ let newCollapsed;
982
+ if (sub === 'expand') {
983
+ newCollapsed = false;
984
+ } else if (sub === 'collapse') {
985
+ newCollapsed = true;
986
+ } else {
987
+ const last = reasoningFrames[reasoningFrames.length - 1];
988
+ newCollapsed = !Boolean(last?.meta?.collapsed);
989
+ }
990
+ for (const frame of reasoningFrames) {
991
+ if (frame.meta) {
992
+ frame.meta.collapsed = newCollapsed;
993
+ frame.rows = null;
994
+ frame.renderedWidth = -1;
995
+ }
996
+ }
997
+ transcript.cache = null;
998
+ transcript.revision++;
999
+ transcript.changed?.();
1000
+ if (ctx.prompt?.scheduleDraw) ctx.prompt.scheduleDraw();
1001
+ return ok(`${newCollapsed ? 'Collapsed' : 'Expanded'} ${reasoningFrames.length} thinking frame${reasoningFrames.length === 1 ? '' : 's'}.`);
1002
+ }
1003
+ },
1004
+
964
1005
  {
965
1006
  name: 'clear',
966
1007
  aliases: ['reset'],
@@ -173,7 +173,8 @@ export class PluginsFactory {
173
173
  `Security Status: DISABLED (Review source files before enabling)`,
174
174
  '',
175
175
  `To activate after review:`,
176
- ` causyne plugins enable ${normalizedName}`
176
+ ` causyne plugins enable ${normalizedName}`,
177
+ ` (or in chat: /plugins enable ${normalizedName})`
177
178
  ].join('\n');
178
179
  }
179
180
  else {
@@ -184,7 +185,8 @@ export class PluginsFactory {
184
185
  '',
185
186
  `To register and grant:`,
186
187
  ` causyne mcp add ${normalizedName} node ${path.join(targetDir, 'server.js')}`,
187
- ` causyne mcp grant ${normalizedName}`
188
+ ` causyne mcp grant ${normalizedName}`,
189
+ ` (or in chat: /mcp grant ${normalizedName})`
188
190
  ].join('\n');
189
191
  }
190
192
  const result = {
@@ -204,6 +206,9 @@ export class PluginsFactory {
204
206
  */
205
207
  recordPluginState(pluginName, digest) {
206
208
  try {
209
+ if (!fs.existsSync(this.pluginsRoot)) {
210
+ fs.mkdirSync(this.pluginsRoot, { recursive: true, mode: 0o700 });
211
+ }
207
212
  const stateFile = path.join(this.pluginsRoot, 'state.json');
208
213
  let state = {
209
214
  version: 1,
@@ -215,7 +215,8 @@ export class PluginsFactory {
215
215
  `Security Status: DISABLED (Review source files before enabling)`,
216
216
  '',
217
217
  `To activate after review:`,
218
- ` causyne plugins enable ${normalizedName}`
218
+ ` causyne plugins enable ${normalizedName}`,
219
+ ` (or in chat: /plugins enable ${normalizedName})`
219
220
  ].join('\n');
220
221
  } else {
221
222
  instructions = [
@@ -225,7 +226,8 @@ export class PluginsFactory {
225
226
  '',
226
227
  `To register and grant:`,
227
228
  ` causyne mcp add ${normalizedName} node ${path.join(targetDir, 'server.js')}`,
228
- ` causyne mcp grant ${normalizedName}`
229
+ ` causyne mcp grant ${normalizedName}`,
230
+ ` (or in chat: /mcp grant ${normalizedName})`
229
231
  ].join('\n');
230
232
  }
231
233
 
@@ -247,6 +249,9 @@ export class PluginsFactory {
247
249
  */
248
250
  private recordPluginState(pluginName: string, digest: string): void {
249
251
  try {
252
+ if (!fs.existsSync(this.pluginsRoot)) {
253
+ fs.mkdirSync(this.pluginsRoot, { recursive: true, mode: 0o700 });
254
+ }
250
255
  const stateFile = path.join(this.pluginsRoot, 'state.json');
251
256
  let state: { version: number; plugins: Record<string, { enabled: boolean; digest?: string }> } = {
252
257
  version: 1,
@@ -2,13 +2,28 @@
2
2
  * Code and Manifest Templates for PluginsFactory.
3
3
  *
4
4
  * Scaffolds production-grade, secure implementations for:
5
- * 1. Native HTTP Plugin (Leanest, zero daemon overhead)
6
- * 2. Native CLI Plugin (Subprocess wrapper)
5
+ * 1. Native HTTP Plugin (Leanest, zero daemon overhead, full query param support)
6
+ * 2. Native CLI Plugin (Subprocess wrapper with robust stderr reporting)
7
7
  * 3. Python Bridge Plugin (Lightweight JSON stdio bridge for Python libraries)
8
- * 4. Stdio MCP Server (Zero-dependency JSON-RPC 2.0 stdio daemon)
8
+ * 4. Stdio MCP Server (Zero-dependency JSON-RPC 2.0 stdio daemon compliant with MCP spec)
9
9
  */
10
- function sanitizeIdentifier(name) {
11
- return name.replace(/[^a-zA-Z0-9_]/g, '_');
10
+ /**
11
+ * Sanitizes an arbitrary tool or parameter name into a valid JavaScript identifier.
12
+ * Prevents syntax errors when tools contain hyphens (e.g. "get-weather" -> "get_weather").
13
+ */
14
+ export function sanitizeIdentifier(name) {
15
+ const cleaned = name.replace(/[^a-zA-Z0-9_]/g, '_');
16
+ return /^[0-9]/.test(cleaned) ? `_${cleaned}` : (cleaned || 'fn');
17
+ }
18
+ /**
19
+ * Computes the canonical export name for a tool within an index.js ES module.
20
+ * The primary tool is always exported as "execute" (the default runner contract).
21
+ * Additional tools are exported with their sanitized identifier.
22
+ */
23
+ function getExportName(tool, index) {
24
+ if (index === 0)
25
+ return 'execute';
26
+ return sanitizeIdentifier(tool.name);
12
27
  }
13
28
  /**
14
29
  * Generates scaffold files for a Native HTTP Plugin.
@@ -26,17 +41,17 @@ export function generateHttpPluginScaffold(service) {
26
41
  version: '1.0.0',
27
42
  description: service.description || `Native HTTP plugin for ${service.name}`,
28
43
  capabilities,
29
- tools: service.tools.map(tool => ({
44
+ tools: service.tools.map((tool, idx) => ({
30
45
  name: tool.name,
31
46
  description: tool.description,
32
47
  parameters: tool.parameters,
33
48
  entry: 'index.js',
34
- export: tool.name === primaryTool.name ? 'execute' : tool.name,
49
+ export: getExportName(tool, idx),
35
50
  timeoutMs: 30000
36
51
  }))
37
52
  };
38
- const toolExecutors = service.tools.map(tool => {
39
- const fnName = tool.name === primaryTool.name ? 'execute' : tool.name;
53
+ const toolExecutors = service.tools.map((tool, idx) => {
54
+ const fnName = getExportName(tool, idx);
40
55
  const httpMethod = tool.httpMethod || 'POST';
41
56
  const httpPath = tool.httpPath || '/';
42
57
  return `
@@ -45,7 +60,16 @@ export function generateHttpPluginScaffold(service) {
45
60
  */
46
61
  export async function ${fnName}(args = {}, context = {}) {
47
62
  const endpoint = ${JSON.stringify(service.endpoint || 'https://api.example.com')};
48
- const url = new URL(${JSON.stringify(httpPath)}, endpoint).toString();
63
+ const base = endpoint.endsWith('/') ? endpoint : endpoint + '/';
64
+ const rel = ${JSON.stringify(httpPath)}.startsWith('/') ? ${JSON.stringify(httpPath)}.slice(1) : ${JSON.stringify(httpPath)};
65
+ const url = new URL(rel, base);
66
+
67
+ if (${JSON.stringify(httpMethod)} === 'GET' && args && typeof args === 'object') {
68
+ for (const [k, v] of Object.entries(args)) {
69
+ if (v !== undefined && v !== null) url.searchParams.append(k, String(v));
70
+ }
71
+ }
72
+
49
73
  const authHeader = ${service.authEnvVar
50
74
  ? `process.env[${JSON.stringify(service.authEnvVar)}] ? \`Bearer \${process.env[${JSON.stringify(service.authEnvVar)}]}\` : undefined`
51
75
  : 'undefined'};
@@ -57,7 +81,7 @@ export async function ${fnName}(args = {}, context = {}) {
57
81
  if (authHeader) headers['Authorization'] = authHeader;
58
82
 
59
83
  try {
60
- const response = await fetch(url, {
84
+ const response = await fetch(url.toString(), {
61
85
  method: ${JSON.stringify(httpMethod)},
62
86
  headers,
63
87
  body: ${httpMethod !== 'GET' ? 'JSON.stringify(args)' : 'undefined'}
@@ -132,19 +156,18 @@ export function generateCliPluginScaffold(service) {
132
156
  version: '1.0.0',
133
157
  description: service.description || `Native CLI plugin for ${service.name}`,
134
158
  capabilities,
135
- tools: service.tools.map(tool => ({
159
+ tools: service.tools.map((tool, idx) => ({
136
160
  name: tool.name,
137
161
  description: tool.description,
138
162
  parameters: tool.parameters,
139
163
  entry: 'index.js',
140
- export: tool.name === primaryTool.name ? 'execute' : tool.name,
164
+ export: getExportName(tool, idx),
141
165
  timeoutMs: 45000
142
166
  }))
143
167
  };
144
- const toolExecutors = service.tools.map(tool => {
145
- const fnName = tool.name === primaryTool.name ? 'execute' : tool.name;
168
+ const toolExecutors = service.tools.map((tool, idx) => {
169
+ const fnName = getExportName(tool, idx);
146
170
  const binary = service.cliBinary || service.name;
147
- const subcommand = tool.cliSubcommand ? ` ${tool.cliSubcommand}` : '';
148
171
  return `
149
172
  /**
150
173
  * ${tool.description}
@@ -158,7 +181,7 @@ export async function ${fnName}(args = {}, context = {}) {
158
181
  const cliArgs = [];
159
182
  ${tool.cliSubcommand ? `cliArgs.push(${JSON.stringify(tool.cliSubcommand)});` : ''}
160
183
 
161
- for (const [key, val] of Object.entries(args)) {
184
+ for (const [key, val] of Object.entries(args || {})) {
162
185
  if (val === true) cliArgs.push(\`--\${key}\`);
163
186
  else if (val !== false && val !== null && val !== undefined) {
164
187
  cliArgs.push(\`--\${key}\`, String(val));
@@ -178,9 +201,12 @@ export async function ${fnName}(args = {}, context = {}) {
178
201
  stderr: stderr.trim()
179
202
  };
180
203
  } catch (err) {
204
+ const errObj = err && typeof err === 'object' ? err : {};
205
+ const stderrMsg = typeof errObj.stderr === 'string' ? errObj.stderr.trim() : '';
206
+ const mainMsg = err instanceof Error ? err.message : String(err);
181
207
  return {
182
208
  success: false,
183
- error: err instanceof Error ? err.message : String(err)
209
+ error: [mainMsg, stderrMsg].filter(Boolean).join(': ')
184
210
  };
185
211
  }
186
212
  }
@@ -232,17 +258,17 @@ export function generatePythonBridgeScaffold(service) {
232
258
  version: '1.0.0',
233
259
  description: service.description || `Python bridge plugin for ${service.name}`,
234
260
  capabilities,
235
- tools: service.tools.map(tool => ({
261
+ tools: service.tools.map((tool, idx) => ({
236
262
  name: tool.name,
237
263
  description: tool.description,
238
264
  parameters: tool.parameters,
239
265
  entry: 'index.js',
240
- export: tool.name === primaryTool.name ? 'execute' : tool.name,
266
+ export: getExportName(tool, idx),
241
267
  timeoutMs: 60000
242
268
  }))
243
269
  };
244
- const toolExecutors = service.tools.map(tool => {
245
- const fnName = tool.name === primaryTool.name ? 'execute' : tool.name;
270
+ const toolExecutors = service.tools.map((tool, idx) => {
271
+ const fnName = getExportName(tool, idx);
246
272
  const pythonMethod = tool.pythonMethod || tool.name;
247
273
  return `
248
274
  /**
@@ -354,16 +380,15 @@ def handle_request(payload):
354
380
  args = payload.get("args", {})
355
381
  context = payload.get("context", {})
356
382
 
357
- # Dispatched action handler
358
383
  try:
359
- # Example: Import target python library safely
384
+ # Dynamically reference target python module
360
385
  # import ${pythonModule}
361
386
 
362
387
  result = {
363
388
  "action": action,
364
389
  "processed": True,
365
390
  "args_echo": args,
366
- "message": f"Successfully executed {action} via Python bridge."
391
+ "message": f"Successfully executed action '{action}' via Python bridge."
367
392
  }
368
393
  return {"success": True, "result": result}
369
394
  except Exception as exc:
@@ -486,6 +511,7 @@ function handleRequest(request) {
486
511
  };
487
512
 
488
513
  case 'notifications/initialized':
514
+ case 'initialized':
489
515
  return null;
490
516
 
491
517
  case 'ping':
@@ -498,6 +524,12 @@ function handleRequest(request) {
498
524
  result: { tools: TOOLS }
499
525
  };
500
526
 
527
+ case 'resources/list':
528
+ return { id, jsonrpc: '2.0', result: { resources: [] } };
529
+
530
+ case 'prompts/list':
531
+ return { id, jsonrpc: '2.0', result: { prompts: [] } };
532
+
501
533
  case 'tools/call': {
502
534
  const toolName = params?.name;
503
535
  const toolArgs = params?.arguments || {};
@@ -2,10 +2,10 @@
2
2
  * Code and Manifest Templates for PluginsFactory.
3
3
  *
4
4
  * Scaffolds production-grade, secure implementations for:
5
- * 1. Native HTTP Plugin (Leanest, zero daemon overhead)
6
- * 2. Native CLI Plugin (Subprocess wrapper)
5
+ * 1. Native HTTP Plugin (Leanest, zero daemon overhead, full query param support)
6
+ * 2. Native CLI Plugin (Subprocess wrapper with robust stderr reporting)
7
7
  * 3. Python Bridge Plugin (Lightweight JSON stdio bridge for Python libraries)
8
- * 4. Stdio MCP Server (Zero-dependency JSON-RPC 2.0 stdio daemon)
8
+ * 4. Stdio MCP Server (Zero-dependency JSON-RPC 2.0 stdio daemon compliant with MCP spec)
9
9
  */
10
10
 
11
11
  import type { ServiceDescriptor, ServiceToolDescriptor } from './types.js';
@@ -15,8 +15,23 @@ export interface ScaffoldingPayload {
15
15
  entryPoint: string;
16
16
  }
17
17
 
18
- function sanitizeIdentifier(name: string): string {
19
- return name.replace(/[^a-zA-Z0-9_]/g, '_');
18
+ /**
19
+ * Sanitizes an arbitrary tool or parameter name into a valid JavaScript identifier.
20
+ * Prevents syntax errors when tools contain hyphens (e.g. "get-weather" -> "get_weather").
21
+ */
22
+ export function sanitizeIdentifier(name: string): string {
23
+ const cleaned = name.replace(/[^a-zA-Z0-9_]/g, '_');
24
+ return /^[0-9]/.test(cleaned) ? `_${cleaned}` : (cleaned || 'fn');
25
+ }
26
+
27
+ /**
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.
31
+ */
32
+ function getExportName(tool: ServiceToolDescriptor, index: number): string {
33
+ if (index === 0) return 'execute';
34
+ return sanitizeIdentifier(tool.name);
20
35
  }
21
36
 
22
37
  /**
@@ -36,18 +51,18 @@ export function generateHttpPluginScaffold(service: ServiceDescriptor): Scaffold
36
51
  version: '1.0.0',
37
52
  description: service.description || `Native HTTP plugin for ${service.name}`,
38
53
  capabilities,
39
- tools: service.tools.map(tool => ({
54
+ tools: service.tools.map((tool, idx) => ({
40
55
  name: tool.name,
41
56
  description: tool.description,
42
57
  parameters: tool.parameters,
43
58
  entry: 'index.js',
44
- export: tool.name === primaryTool.name ? 'execute' : tool.name,
59
+ export: getExportName(tool, idx),
45
60
  timeoutMs: 30000
46
61
  }))
47
62
  };
48
63
 
49
- const toolExecutors = service.tools.map(tool => {
50
- const fnName = tool.name === primaryTool.name ? 'execute' : tool.name;
64
+ const toolExecutors = service.tools.map((tool, idx) => {
65
+ const fnName = getExportName(tool, idx);
51
66
  const httpMethod = tool.httpMethod || 'POST';
52
67
  const httpPath = tool.httpPath || '/';
53
68
  return `
@@ -56,7 +71,16 @@ export function generateHttpPluginScaffold(service: ServiceDescriptor): Scaffold
56
71
  */
57
72
  export async function ${fnName}(args = {}, context = {}) {
58
73
  const endpoint = ${JSON.stringify(service.endpoint || 'https://api.example.com')};
59
- const url = new URL(${JSON.stringify(httpPath)}, endpoint).toString();
74
+ 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);
77
+
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
+ }
82
+ }
83
+
60
84
  const authHeader = ${
61
85
  service.authEnvVar
62
86
  ? `process.env[${JSON.stringify(service.authEnvVar)}] ? \`Bearer \${process.env[${JSON.stringify(service.authEnvVar)}]}\` : undefined`
@@ -70,7 +94,7 @@ export async function ${fnName}(args = {}, context = {}) {
70
94
  if (authHeader) headers['Authorization'] = authHeader;
71
95
 
72
96
  try {
73
- const response = await fetch(url, {
97
+ const response = await fetch(url.toString(), {
74
98
  method: ${JSON.stringify(httpMethod)},
75
99
  headers,
76
100
  body: ${httpMethod !== 'GET' ? 'JSON.stringify(args)' : 'undefined'}
@@ -150,20 +174,19 @@ export function generateCliPluginScaffold(service: ServiceDescriptor): Scaffoldi
150
174
  version: '1.0.0',
151
175
  description: service.description || `Native CLI plugin for ${service.name}`,
152
176
  capabilities,
153
- tools: service.tools.map(tool => ({
177
+ tools: service.tools.map((tool, idx) => ({
154
178
  name: tool.name,
155
179
  description: tool.description,
156
180
  parameters: tool.parameters,
157
181
  entry: 'index.js',
158
- export: tool.name === primaryTool.name ? 'execute' : tool.name,
182
+ export: getExportName(tool, idx),
159
183
  timeoutMs: 45000
160
184
  }))
161
185
  };
162
186
 
163
- const toolExecutors = service.tools.map(tool => {
164
- const fnName = tool.name === primaryTool.name ? 'execute' : tool.name;
187
+ const toolExecutors = service.tools.map((tool, idx) => {
188
+ const fnName = getExportName(tool, idx);
165
189
  const binary = service.cliBinary || service.name;
166
- const subcommand = tool.cliSubcommand ? ` ${tool.cliSubcommand}` : '';
167
190
  return `
168
191
  /**
169
192
  * ${tool.description}
@@ -177,7 +200,7 @@ export async function ${fnName}(args = {}, context = {}) {
177
200
  const cliArgs = [];
178
201
  ${tool.cliSubcommand ? `cliArgs.push(${JSON.stringify(tool.cliSubcommand)});` : ''}
179
202
 
180
- for (const [key, val] of Object.entries(args)) {
203
+ for (const [key, val] of Object.entries(args || {})) {
181
204
  if (val === true) cliArgs.push(\`--\${key}\`);
182
205
  else if (val !== false && val !== null && val !== undefined) {
183
206
  cliArgs.push(\`--\${key}\`, String(val));
@@ -197,9 +220,12 @@ export async function ${fnName}(args = {}, context = {}) {
197
220
  stderr: stderr.trim()
198
221
  };
199
222
  } catch (err) {
223
+ const errObj = err && typeof err === 'object' ? err : {};
224
+ const stderrMsg = typeof errObj.stderr === 'string' ? errObj.stderr.trim() : '';
225
+ const mainMsg = err instanceof Error ? err.message : String(err);
200
226
  return {
201
227
  success: false,
202
- error: err instanceof Error ? err.message : String(err)
228
+ error: [mainMsg, stderrMsg].filter(Boolean).join(': ')
203
229
  };
204
230
  }
205
231
  }
@@ -256,18 +282,18 @@ export function generatePythonBridgeScaffold(service: ServiceDescriptor): Scaffo
256
282
  version: '1.0.0',
257
283
  description: service.description || `Python bridge plugin for ${service.name}`,
258
284
  capabilities,
259
- tools: service.tools.map(tool => ({
285
+ tools: service.tools.map((tool, idx) => ({
260
286
  name: tool.name,
261
287
  description: tool.description,
262
288
  parameters: tool.parameters,
263
289
  entry: 'index.js',
264
- export: tool.name === primaryTool.name ? 'execute' : tool.name,
290
+ export: getExportName(tool, idx),
265
291
  timeoutMs: 60000
266
292
  }))
267
293
  };
268
294
 
269
- const toolExecutors = service.tools.map(tool => {
270
- const fnName = tool.name === primaryTool.name ? 'execute' : tool.name;
295
+ const toolExecutors = service.tools.map((tool, idx) => {
296
+ const fnName = getExportName(tool, idx);
271
297
  const pythonMethod = tool.pythonMethod || tool.name;
272
298
  return `
273
299
  /**
@@ -381,16 +407,15 @@ def handle_request(payload):
381
407
  args = payload.get("args", {})
382
408
  context = payload.get("context", {})
383
409
 
384
- # Dispatched action handler
385
410
  try:
386
- # Example: Import target python library safely
411
+ # Dynamically reference target python module
387
412
  # import ${pythonModule}
388
413
 
389
414
  result = {
390
415
  "action": action,
391
416
  "processed": True,
392
417
  "args_echo": args,
393
- "message": f"Successfully executed {action} via Python bridge."
418
+ "message": f"Successfully executed action '{action}' via Python bridge."
394
419
  }
395
420
  return {"success": True, "result": result}
396
421
  except Exception as exc:
@@ -522,6 +547,7 @@ function handleRequest(request) {
522
547
  };
523
548
 
524
549
  case 'notifications/initialized':
550
+ case 'initialized':
525
551
  return null;
526
552
 
527
553
  case 'ping':
@@ -534,6 +560,12 @@ function handleRequest(request) {
534
560
  result: { tools: TOOLS }
535
561
  };
536
562
 
563
+ case 'resources/list':
564
+ return { id, jsonrpc: '2.0', result: { resources: [] } };
565
+
566
+ case 'prompts/list':
567
+ return { id, jsonrpc: '2.0', result: { prompts: [] } };
568
+
537
569
  case 'tools/call': {
538
570
  const toolName = params?.name;
539
571
  const toolArgs = params?.arguments || {};
@@ -628,4 +660,3 @@ causyne mcp grant ${service.name}
628
660
  ]
629
661
  };
630
662
  }
631
-
package/src/toolPacks.js CHANGED
@@ -334,7 +334,7 @@ const GAME_INTENT = /\b(game|games|gamedev|godot|unity|unreal|ue5|rpg|platformer
334
334
  const WEB_INTENT = /\b(web|webpage|website|frontend|front-end|landing page|homepage|dashboard|portfolio|html|css|scss|tailwind|bootstrap|react|vue|svelte|angular|next\.?js|nuxt|astro|ui|ux|user interface|web app|webapp|spa|dom|responsive|ui forge|component forge|component generation|ui component|three?\.?js|three?js|webgl|canvas|babylon)\b/i;
335
335
  const MEDIA_INTENT = /\b(image|images|picture|photo|photoshop|premiere|after\s*effects|illustrator|indesign|media\s*encoder|uxp|render|3d model|blender|animation|animate|video|movie|film|audio|sound|sfx|music|song|voice|tts|text.to.speech|narration|podcast|thumbnail|poster|illustration|logo)\b|\.(psd|prproj|aep|ai|indd|ccx)\b/i;
336
336
  const SYSTEM_INTENT = /\b(process|processes|pid|kill|port|zip|unzip|tar|archive|compress|extract|clipboard|copy to clipboard|print|printer|open in browser|launch app|computer use|vision grounding|desktop vision|gui agent|coordinate click|desktop control)\b/i;
337
- const ADVANCED_INTENT = /\b(pdf|document|proposal|screenplay|shotlist|shot list|voiceover|dubbing|forge a tool|custom tool|new tool|plugin|plugins|custom plugin|subagent|sub-agent|parallel agent|swarm|ast|symbols|refactor across)\b/i;
337
+ const ADVANCED_INTENT = /\b(pdf|document|proposal|screenplay|shotlist|shot list|voiceover|dubbing|forge a tool|custom tool|new tool|plugin|plugins|custom plugin|plugins? factory|python bridge|mcp|mcp server|subagent|sub-agent|parallel agent|swarm|ast|symbols|refactor across)\b/i;
338
338
  const REVERSE_ENGINEERING_INTENT = /\b(rea|rea-agents|decompile|decompiling|decompilation|disassemble|disassembly|disassembling|binary|binaries|apk|aab|dex|elf|mach-o|pe|coff|reverse[\s_-]?engineer(ing)?|sourcemap|deobfuscate|asar|symbols|ghidra|rizin|radare|hopper|frida|hook script|mitigations|pie|canary|clean[- ]?room)\b|\.(apk|aab|dex|dylib|so|dll|exe|asar)\b/i;
339
339
  const INTENT_MATCHERS = {
340
340
  game: GAME_INTENT,
package/src/toolPacks.ts CHANGED
@@ -378,7 +378,7 @@ const MEDIA_INTENT = /\b(image|images|picture|photo|photoshop|premiere|after\s*e
378
378
 
379
379
  const SYSTEM_INTENT = /\b(process|processes|pid|kill|port|zip|unzip|tar|archive|compress|extract|clipboard|copy to clipboard|print|printer|open in browser|launch app|computer use|vision grounding|desktop vision|gui agent|coordinate click|desktop control)\b/i;
380
380
 
381
- const ADVANCED_INTENT = /\b(pdf|document|proposal|screenplay|shotlist|shot list|voiceover|dubbing|forge a tool|custom tool|new tool|plugin|plugins|custom plugin|subagent|sub-agent|parallel agent|swarm|ast|symbols|refactor across)\b/i;
381
+ const ADVANCED_INTENT = /\b(pdf|document|proposal|screenplay|shotlist|shot list|voiceover|dubbing|forge a tool|custom tool|new tool|plugin|plugins|custom plugin|plugins? factory|python bridge|mcp|mcp server|subagent|sub-agent|parallel agent|swarm|ast|symbols|refactor across)\b/i;
382
382
 
383
383
  const REVERSE_ENGINEERING_INTENT = /\b(rea|rea-agents|decompile|decompiling|decompilation|disassemble|disassembly|disassembling|binary|binaries|apk|aab|dex|elf|mach-o|pe|coff|reverse[\s_-]?engineer(ing)?|sourcemap|deobfuscate|asar|symbols|ghidra|rizin|radare|hopper|frida|hook script|mitigations|pie|canary|clean[- ]?room)\b|\.(apk|aab|dex|dylib|so|dll|exe|asar)\b/i;
384
384
 
@@ -8,12 +8,19 @@
8
8
  import { PluginsFactory } from '../pluginsFactory/index.js';
9
9
  function normalizeServiceDescriptor(args) {
10
10
  const tools = (args.tools || []).map((t, idx) => {
11
+ const rawParams = (t.parameters && typeof t.parameters === 'object') ? t.parameters : {};
12
+ const { type: _discardType, ...restParams } = rawParams;
13
+ const parameters = {
14
+ ...restParams,
15
+ type: 'object',
16
+ properties: (rawParams['properties'] && typeof rawParams['properties'] === 'object')
17
+ ? rawParams['properties']
18
+ : {}
19
+ };
11
20
  const tool = {
12
21
  name: t.name || `tool_${idx + 1}`,
13
22
  description: t.description || `Tool ${t.name || idx + 1}`,
14
- parameters: (t.parameters && typeof t.parameters === 'object' && t.parameters.type === 'object')
15
- ? t.parameters
16
- : { type: 'object', properties: {} }
23
+ parameters
17
24
  };
18
25
  if (t.httpMethod !== undefined)
19
26
  tool.httpMethod = t.httpMethod;
@@ -14,7 +14,8 @@ import {
14
14
  type ScaffoldResult,
15
15
  type ServiceDescriptor,
16
16
  type ServiceKind,
17
- type ServiceToolDescriptor
17
+ type ServiceToolDescriptor,
18
+ type ToolParameterSchema
18
19
  } from '../pluginsFactory/index.js';
19
20
 
20
21
  export interface PluginsFactoryArgs {
@@ -53,12 +54,19 @@ export interface PluginsFactoryToolResult {
53
54
 
54
55
  function normalizeServiceDescriptor(args: PluginsFactoryArgs): ServiceDescriptor {
55
56
  const tools: ServiceToolDescriptor[] = (args.tools || []).map((t, idx) => {
57
+ const rawParams = (t.parameters && typeof t.parameters === 'object') ? (t.parameters as Record<string, unknown>) : {};
58
+ const { type: _discardType, ...restParams } = rawParams;
59
+ const parameters: ToolParameterSchema = {
60
+ ...restParams,
61
+ type: 'object',
62
+ properties: (rawParams['properties'] && typeof rawParams['properties'] === 'object')
63
+ ? (rawParams['properties'] as ToolParameterSchema['properties'])
64
+ : {}
65
+ };
56
66
  const tool: ServiceToolDescriptor = {
57
67
  name: t.name || `tool_${idx + 1}`,
58
68
  description: t.description || `Tool ${t.name || idx + 1}`,
59
- parameters: (t.parameters && typeof t.parameters === 'object' && t.parameters.type === 'object')
60
- ? (t.parameters as ServiceToolDescriptor['parameters'])
61
- : { type: 'object', properties: {} }
69
+ parameters
62
70
  };
63
71
  if (t.httpMethod !== undefined) tool.httpMethod = t.httpMethod;
64
72
  if (t.httpPath !== undefined) tool.httpPath = t.httpPath;
@@ -15,6 +15,7 @@ export class ChatRenderer {
15
15
  handle(message: { type: string; [key: string]: unknown }): boolean;
16
16
  resetTurn(): void;
17
17
  onAgentReasoning(message: { content?: string; streaming?: boolean; elapsedMs?: number }): void;
18
+ renderReasoning(content: string, options?: { streaming?: boolean; durationText?: string; collapsed?: boolean }): void;
18
19
  stopSpinner(): void;
19
20
  frame(kind: string, produce: () => void, meta?: Record<string, unknown> | null): void;
20
21
  updateTailFrame(kind: string, produce: () => void, meta?: Record<string, unknown> | null): void;
@@ -27,6 +27,7 @@ import { chatProseWidth, wrappedChatRows } from './textLayout.js';
27
27
  import { activityRows } from './activityLayout.js';
28
28
  import { cleanToolOutputPreview, normalizeHistoricalToolResult } from './toolOutputNormalizer.js';
29
29
  import { formatMarkdownMath } from './markdownMath.js';
30
+ import { renderThinkingFrame } from './thinkingBox.js';
30
31
 
31
32
  // Bound the preview AFTER wrapping, not by source newlines: one 400 KB line of
32
33
  // minified output would otherwise become thousands of rows and lock the
@@ -737,8 +738,9 @@ export class ChatRenderer {
737
738
  const elapsedMs = Number(msg.elapsedMs) || 0;
738
739
  const durationText = elapsedMs > 0 ? formatDuration(elapsedMs) : '';
739
740
 
741
+ const tailFrame = this.transcript?.frames?.at(-1);
740
742
  const tailIsReasoning = !this.transcript
741
- || this.transcript.frames?.at(-1)?.meta?.reasoning === true;
743
+ || tailFrame?.meta?.reasoning === true;
742
744
  if (this._activeReasoning && !tailIsReasoning) {
743
745
  this._activeReasoning = false;
744
746
  }
@@ -746,56 +748,77 @@ export class ChatRenderer {
746
748
  if (isStreaming) {
747
749
  if (!this._activeReasoning) {
748
750
  this._activeReasoning = true;
749
- this.frame('reasoning', () => this.renderReasoning(content, { streaming: true, durationText }), { reasoning: true });
751
+ const meta = {
752
+ reasoning: true,
753
+ collapsed: false,
754
+ streaming: true,
755
+ durationText,
756
+ content
757
+ };
758
+ this.frame('reasoning', () => this.renderReasoning(meta.content, {
759
+ streaming: true,
760
+ durationText: meta.durationText,
761
+ collapsed: Boolean(meta.collapsed)
762
+ }), meta);
750
763
  } else {
751
- this.updateTailFrame('reasoning', () => this.renderReasoning(content, { streaming: true, durationText }), { reasoning: true });
764
+ const meta = tailFrame?.meta || { reasoning: true };
765
+ meta.streaming = true;
766
+ meta.durationText = durationText;
767
+ meta.content = content;
768
+ if (meta.collapsed === undefined) meta.collapsed = false;
769
+ this.updateTailFrame('reasoning', () => this.renderReasoning(meta.content, {
770
+ streaming: true,
771
+ durationText: meta.durationText,
772
+ collapsed: Boolean(meta.collapsed)
773
+ }), meta);
752
774
  }
753
775
  return;
754
776
  }
755
777
 
756
778
  if (this._activeReasoning) {
757
779
  this._activeReasoning = false;
758
- this.updateTailFrame('reasoning', () => this.renderReasoning(content, { streaming: false, durationText }), { reasoning: true, done: true });
780
+ const meta = tailFrame?.meta || { reasoning: true };
781
+ meta.streaming = false;
782
+ meta.done = true;
783
+ meta.durationText = durationText;
784
+ meta.content = content;
785
+ if (meta.collapsed === undefined) meta.collapsed = false;
786
+ this.updateTailFrame('reasoning', () => this.renderReasoning(meta.content, {
787
+ streaming: false,
788
+ durationText: meta.durationText,
789
+ collapsed: Boolean(meta.collapsed)
790
+ }), meta);
759
791
  } else if (content.trim()) {
760
- this.frame('reasoning', () => this.renderReasoning(content, { streaming: false, durationText }), { reasoning: true, done: true });
792
+ const meta = {
793
+ reasoning: true,
794
+ done: true,
795
+ streaming: false,
796
+ durationText,
797
+ content,
798
+ collapsed: false
799
+ };
800
+ this.frame('reasoning', () => this.renderReasoning(meta.content, {
801
+ streaming: false,
802
+ durationText: meta.durationText,
803
+ collapsed: Boolean(meta.collapsed)
804
+ }), meta);
761
805
  }
762
806
  }
763
807
 
764
- renderReasoning(content, { streaming = false, durationText = '' } = {}) {
808
+ renderReasoning(content, { streaming = false, durationText = '', collapsed = false } = {}) {
765
809
  const width = this.measure();
766
- const rows = content.trim()
767
- ? wrapBlock(content, Math.max(20, width - 4))
768
- : ['Contemplating task and formulating approach…'];
769
-
770
- this.write();
771
- if (streaming) {
772
- this.write(`${paint('warn', GLYPHS.vLine || '│')} ${bold(paint('warn', 'thinking…'))}`);
773
- } else {
774
- const timePart = durationText ? ` · ${durationText}` : '';
775
- this.write(`${paint('muted', GLYPHS.vLine || '│')} ${dim(`thinking${timePart}`)}`);
776
- }
777
-
778
- if (streaming && rows.length > REASONING_LINES) {
779
- const hidden = rows.length - REASONING_LINES;
780
- this.write(`${paint('rule', GLYPHS.vLine || '│')} ${dim(`${GLYPHS.ellipsis} ${hidden} earlier thinking line${hidden === 1 ? '' : 's'}`)}`);
781
- }
782
-
783
- const displayRows = streaming && rows.length > REASONING_LINES
784
- ? rows.slice(rows.length - REASONING_LINES)
785
- : rows.slice(0, REASONING_LINES);
810
+ const rows = renderThinkingFrame(content, {
811
+ width,
812
+ streaming,
813
+ durationText,
814
+ collapsed
815
+ });
786
816
 
787
- for (const row of displayRows) {
788
- this.write(`${paint('rule', GLYPHS.vLine || '│')} ${dim(row)}`);
789
- }
817
+ if (rows.length === 0) return;
790
818
 
791
- if (!streaming && rows.length > REASONING_LINES) {
792
- const hidden = rows.length - REASONING_LINES;
793
- this.write(`${paint('rule', GLYPHS.corner || '└')} ${dim(`${GLYPHS.ellipsis} ${hidden} more line${hidden === 1 ? '' : 's'} of reasoning`)}`);
794
- } else if (streaming) {
795
- const timePart = durationText ? ` · ${durationText}` : '';
796
- this.write(`${paint('rule', GLYPHS.corner || '└')} ${bold(paint('warn', 'thinking…'))} ${dim(timePart || 'streaming thoughts')}`);
797
- } else {
798
- this.write(`${paint('rule', GLYPHS.corner || '└')}`);
819
+ this.write();
820
+ for (const row of rows) {
821
+ this.write(row);
799
822
  }
800
823
  this.write();
801
824
  }
@@ -108,6 +108,24 @@ export function handleMessageMouse(host, loop, event) {
108
108
  if (isMouseMotion(event.sequence))
109
109
  return true;
110
110
  if (mouse.button === 0 && mouse.pressed) {
111
+ const rawMarker = markerAt(surface, mouse);
112
+ if (rawMarker && rawMarker.kind === 'reasoning') {
113
+ const transcript = surface.transcript;
114
+ const frames = transcript?.frames;
115
+ const frame = Array.isArray(frames) ? frames.find(f => f.id === rawMarker.id) : null;
116
+ if (frame && frame.meta && frame.meta.reasoning) {
117
+ frame.meta.collapsed = !frame.meta.collapsed;
118
+ frame.rows = null;
119
+ frame.renderedWidth = -1;
120
+ if (transcript) {
121
+ transcript.cache = null;
122
+ transcript.revision = (transcript.revision || 0) + 1;
123
+ transcript.changed?.();
124
+ }
125
+ host.scheduleDraw();
126
+ return true;
127
+ }
128
+ }
111
129
  // Smart link detection: if the user clicked (or Cmd/Ctrl+Clicked) on a URL or OSC 8 hyperlink,
112
130
  // open the link directly in the system browser instead of popping up the Message Actions modal.
113
131
  const hitLink = detectLinkAtPoint(surface, mouse, marker);
@@ -130,8 +148,8 @@ export function handleMessageMouse(host, loop, event) {
130
148
  }
131
149
  const isMessage = (marker) => (marker.kind === 'user' || marker.kind === 'assistant')
132
150
  && typeof marker.meta?.messageText === 'string';
133
- /** Resolve screen coordinates against the painted viewport, including top padding. */
134
- export function messageAt(surface, point) {
151
+ /** Resolve screen coordinates against the painted viewport to find any frame marker. */
152
+ export function markerAt(surface, point) {
135
153
  if (!surface?.stage.reserved || !Number.isFinite(point.x) || !Number.isFinite(point.y))
136
154
  return null;
137
155
  const mainWidth = sidebarVisible(surface.width) ? sessionMainWidth(surface.width) : surface.width;
@@ -153,12 +171,17 @@ export function messageAt(surface, point) {
153
171
  if (!marker || marker.row > row)
154
172
  continue;
155
173
  const next = flat.markers[i + 1];
156
- if (isMessage(marker) && row < (next?.row ?? flat.rows.length))
174
+ if (row < (next?.row ?? flat.rows.length))
157
175
  return marker;
158
176
  return null;
159
177
  }
160
178
  return null;
161
179
  }
180
+ /** Resolve screen coordinates against the painted viewport, including top padding. */
181
+ export function messageAt(surface, point) {
182
+ const marker = markerAt(surface, point);
183
+ return marker && isMessage(marker) ? marker : null;
184
+ }
162
185
  /** Highlight only the visible non-empty rows of the hovered message, without altering transcript data. */
163
186
  export function markHoveredMessage(rows, surface, contentWidth) {
164
187
  registerStageConsoleGuard(surface);
@@ -22,7 +22,7 @@ export interface MessageMarker {
22
22
  id: number;
23
23
  kind: string;
24
24
  row: number;
25
- meta?: { messageText?: string } | null;
25
+ meta?: { messageText?: string; reasoning?: boolean; collapsed?: boolean } | null;
26
26
  }
27
27
 
28
28
  interface MousePoint { x: number; y: number }
@@ -183,6 +183,35 @@ export function handleMessageMouse(
183
183
  if (isMouseMotion(event.sequence)) return true;
184
184
 
185
185
  if (mouse.button === 0 && mouse.pressed) {
186
+ const rawMarker = markerAt(surface, mouse);
187
+ if (rawMarker && rawMarker.kind === 'reasoning') {
188
+ const transcript = surface.transcript as unknown as {
189
+ frames?: Array<{
190
+ id: number;
191
+ meta?: { reasoning?: boolean; collapsed?: boolean } | null;
192
+ rows?: unknown;
193
+ renderedWidth?: number;
194
+ }>;
195
+ cache?: unknown;
196
+ revision?: number;
197
+ changed?: () => void;
198
+ };
199
+ const frames = transcript?.frames;
200
+ const frame = Array.isArray(frames) ? frames.find(f => f.id === rawMarker.id) : null;
201
+ if (frame && frame.meta && frame.meta.reasoning) {
202
+ frame.meta.collapsed = !frame.meta.collapsed;
203
+ frame.rows = null;
204
+ frame.renderedWidth = -1;
205
+ if (transcript) {
206
+ transcript.cache = null;
207
+ transcript.revision = (transcript.revision || 0) + 1;
208
+ transcript.changed?.();
209
+ }
210
+ host.scheduleDraw();
211
+ return true;
212
+ }
213
+ }
214
+
186
215
  // Smart link detection: if the user clicked (or Cmd/Ctrl+Clicked) on a URL or OSC 8 hyperlink,
187
216
  // open the link directly in the system browser instead of popping up the Message Actions modal.
188
217
  const hitLink = detectLinkAtPoint(surface, mouse, marker);
@@ -208,8 +237,8 @@ const isMessage = (marker: MessageMarker): boolean =>
208
237
  (marker.kind === 'user' || marker.kind === 'assistant')
209
238
  && typeof marker.meta?.messageText === 'string';
210
239
 
211
- /** Resolve screen coordinates against the painted viewport, including top padding. */
212
- export function messageAt(surface: MessageSurface | null, point: MousePoint): MessageMarker | null {
240
+ /** Resolve screen coordinates against the painted viewport to find any frame marker. */
241
+ export function markerAt(surface: MessageSurface | null, point: MousePoint): MessageMarker | null {
213
242
  if (!surface?.stage.reserved || !Number.isFinite(point.x) || !Number.isFinite(point.y)) return null;
214
243
  const mainWidth = sidebarVisible(surface.width) ? sessionMainWidth(surface.width) : surface.width;
215
244
  const leftGutter = (surface.turnRailLayout?.turns?.length ?? 0) > 0 ? 3 : 0;
@@ -226,12 +255,18 @@ export function messageAt(surface: MessageSurface | null, point: MousePoint): Me
226
255
  const marker = flat.markers[i];
227
256
  if (!marker || marker.row > row) continue;
228
257
  const next = flat.markers[i + 1];
229
- if (isMessage(marker) && row < (next?.row ?? flat.rows.length)) return marker;
258
+ if (row < (next?.row ?? flat.rows.length)) return marker;
230
259
  return null;
231
260
  }
232
261
  return null;
233
262
  }
234
263
 
264
+ /** Resolve screen coordinates against the painted viewport, including top padding. */
265
+ export function messageAt(surface: MessageSurface | null, point: MousePoint): MessageMarker | null {
266
+ const marker = markerAt(surface, point);
267
+ return marker && isMessage(marker) ? marker : null;
268
+ }
269
+
235
270
  /** Highlight only the visible non-empty rows of the hovered message, without altering transcript data. */
236
271
  export function markHoveredMessage(
237
272
  rows: string[], surface: MessageSurface, contentWidth: number
@@ -0,0 +1,141 @@
1
+ // Collapsible & auto-scrolling thinking box container for Causyne Agent TUI.
2
+ //
3
+ // Encapsulates streaming reasoning into a bounded, scrolling card container
4
+ // with rounded border framing, auto-scrolling tail pinning, and interactive
5
+ // collapse/expand folding.
6
+ //
7
+ // Pure TypeScript under strict mode.
8
+ // @ts-expect-error theme.js has no TypeScript declaration yet.
9
+ import { paint, bold, dim, GLYPHS, HAS_UNICODE } from './theme.js';
10
+ import { padEnd, truncate, visibleWidth, wrapBlock } from './text.js';
11
+ export const DEFAULT_MAX_STREAMING_LINES = 8;
12
+ export const DEFAULT_MAX_EXPANDED_LINES = 12;
13
+ /**
14
+ * Single-line compact badge for collapsed reasoning frames.
15
+ */
16
+ export function renderCollapsedThinkingBadge(options, totalLines) {
17
+ const isStreaming = Boolean(options.streaming);
18
+ const durationText = options.durationText ? String(options.durationText).trim() : '';
19
+ const arrow = HAS_UNICODE ? '▸' : '>';
20
+ if (isStreaming) {
21
+ const timePart = durationText ? ` · ${durationText}` : '';
22
+ return ` ${paint('warn', arrow)} ${bold(paint('warn', 'thinking…'))}${dim(timePart)} ${dim('· click to expand')}`;
23
+ }
24
+ const timePart = durationText ? ` for ${durationText}` : '';
25
+ const lineWord = totalLines === 1 ? 'line' : 'lines';
26
+ return ` ${paint('muted', arrow)} ${dim(`Thought${timePart}`)} ${dim(`(${totalLines} ${lineWord})`)} ${dim('· click to expand')}`;
27
+ }
28
+ /**
29
+ * Builds the top, bottom, and side frame borders for the thinking box.
30
+ */
31
+ export function buildThinkingBoxBorders(title, footer, width, role = 'rule') {
32
+ const w = Math.max(20, Math.floor(width));
33
+ const inner = w - 2; // total space between left and right outer border corners
34
+ const h = GLYPHS.hLine || '─';
35
+ const v = GLYPHS.vLine || '│';
36
+ const tl = GLYPHS.topLeft || '╭';
37
+ const tr = GLYPHS.topRight || '╮';
38
+ const bl = GLYPHS.bottomLeft || '╰';
39
+ const br = GLYPHS.bottomRight || '╯';
40
+ // --- Top Border ---
41
+ const rawTitle = title ? ` ${title} ` : '';
42
+ const titleVis = visibleWidth(rawTitle);
43
+ const maxTitleVis = Math.max(0, inner - 4); // reserve at least 1 leading hLine and 2 trailing hLines
44
+ const safeTitle = titleVis > maxTitleVis ? (rawTitle ? ` ${truncate(title, Math.max(4, maxTitleVis - 2), GLYPHS.ellipsis || '…')} ` : '') : rawTitle;
45
+ const safeTitleVis = visibleWidth(safeTitle);
46
+ const topLead = h;
47
+ const topTrailCount = Math.max(0, inner - 1 - safeTitleVis);
48
+ const topTrail = h.repeat(topTrailCount);
49
+ const top = paint(role, tl + topLead) + safeTitle + paint(role, topTrail + tr);
50
+ // --- Bottom Border ---
51
+ const rawFooter = footer ? ` ${footer} ` : '';
52
+ const footerVis = visibleWidth(rawFooter);
53
+ const maxFooterVis = Math.max(0, inner - 4);
54
+ const safeFooter = footerVis > maxFooterVis ? (rawFooter ? ` ${truncate(footer, Math.max(4, maxFooterVis - 2), GLYPHS.ellipsis || '…')} ` : '') : rawFooter;
55
+ const safeFooterVis = visibleWidth(safeFooter);
56
+ const bottomLead = h;
57
+ const bottomTrailCount = Math.max(0, inner - 1 - safeFooterVis);
58
+ const bottomTrail = h.repeat(bottomTrailCount);
59
+ const bottom = paint(role, bl + bottomLead) + safeFooter + paint(role, bottomTrail + br);
60
+ // --- Middle Row Wrapper ---
61
+ // Format: "│ " + content + " │"
62
+ // content column width = inner - 2 = w - 4
63
+ const contentWidth = Math.max(2, inner - 2);
64
+ const side = paint(role, v);
65
+ const wrapRow = (line) => {
66
+ const truncated = truncate(line, contentWidth, GLYPHS.ellipsis || '…');
67
+ const padded = padEnd(truncated, contentWidth);
68
+ return `${side} ${padded} ${side}`;
69
+ };
70
+ return { top, bottom, wrapRow };
71
+ }
72
+ /**
73
+ * Render a complete thinking frame (either compact collapsed badge or expanded box).
74
+ */
75
+ export function renderThinkingFrame(content, options = {}) {
76
+ const text = String(content ?? '').trim();
77
+ if (!text)
78
+ return [];
79
+ const width = Math.max(20, Math.floor(options.width ?? 80));
80
+ const isStreaming = Boolean(options.streaming);
81
+ const isCollapsed = Boolean(options.collapsed);
82
+ const durationText = options.durationText ? String(options.durationText).trim() : '';
83
+ // Wrap lines for inner box width (w - 4)
84
+ const contentBudget = Math.max(10, width - 4);
85
+ const allRows = wrapBlock(text, contentBudget);
86
+ const totalLines = allRows.length;
87
+ if (isCollapsed) {
88
+ return [renderCollapsedThinkingBadge(options, totalLines)];
89
+ }
90
+ // Expanded Box Mode
91
+ const role = isStreaming ? 'warn' : (options.role ?? 'rule');
92
+ const collapseIndicator = HAS_UNICODE ? '▾' : 'v';
93
+ const collapseHint = dim(`${collapseIndicator} click to collapse`);
94
+ if (isStreaming) {
95
+ const maxLines = options.maxVisibleLines ?? DEFAULT_MAX_STREAMING_LINES;
96
+ const timePart = durationText ? ` · ${durationText}` : '';
97
+ const title = `${bold(paint('warn', 'thinking…'))}${dim(timePart)}`;
98
+ const footer = collapseHint;
99
+ const { top, bottom, wrapRow } = buildThinkingBoxBorders(title, footer, width, role);
100
+ const rows = [top];
101
+ if (totalLines > maxLines) {
102
+ const hiddenCount = totalLines - (maxLines - 1);
103
+ const scrollIndicator = HAS_UNICODE ? '↑' : '^';
104
+ const hiddenNotice = `${paint('rule', scrollIndicator)} ${dim(`${hiddenCount} earlier thinking line${hiddenCount === 1 ? '' : 's'} scrolled`)}`;
105
+ rows.push(wrapRow(hiddenNotice));
106
+ const tailRows = allRows.slice(totalLines - (maxLines - 1));
107
+ for (const row of tailRows) {
108
+ rows.push(wrapRow(dim(row)));
109
+ }
110
+ }
111
+ else {
112
+ for (const row of allRows) {
113
+ rows.push(wrapRow(dim(row)));
114
+ }
115
+ }
116
+ rows.push(bottom);
117
+ return rows;
118
+ }
119
+ // Completed Expanded Mode
120
+ const maxLines = options.maxVisibleLines ?? DEFAULT_MAX_EXPANDED_LINES;
121
+ const timePart = durationText ? ` · ${durationText}` : '';
122
+ const title = `${paint('muted', 'thinking')}${dim(timePart)} ${dim(`(${totalLines} line${totalLines === 1 ? '' : 's'})`)}`;
123
+ const { top, bottom, wrapRow } = buildThinkingBoxBorders(title, collapseHint, width, 'rule');
124
+ const rows = [top];
125
+ if (totalLines > maxLines) {
126
+ const hiddenCount = totalLines - maxLines;
127
+ const displayRows = allRows.slice(0, maxLines);
128
+ for (const row of displayRows) {
129
+ rows.push(wrapRow(dim(row)));
130
+ }
131
+ const moreNotice = `${GLYPHS.ellipsis || '…'} ${hiddenCount} more line${hiddenCount === 1 ? '' : 's'} of reasoning`;
132
+ rows.push(wrapRow(dim(moreNotice)));
133
+ }
134
+ else {
135
+ for (const row of allRows) {
136
+ rows.push(wrapRow(dim(row)));
137
+ }
138
+ }
139
+ rows.push(bottom);
140
+ return rows;
141
+ }
@@ -0,0 +1,190 @@
1
+ // Collapsible & auto-scrolling thinking box container for Causyne Agent TUI.
2
+ //
3
+ // Encapsulates streaming reasoning into a bounded, scrolling card container
4
+ // with rounded border framing, auto-scrolling tail pinning, and interactive
5
+ // collapse/expand folding.
6
+ //
7
+ // Pure TypeScript under strict mode.
8
+
9
+ // @ts-expect-error theme.js has no TypeScript declaration yet.
10
+ import { paint, bold, dim, GLYPHS, HAS_UNICODE } from './theme.js';
11
+ import { padEnd, truncate, visibleWidth, wrapBlock } from './text.js';
12
+
13
+ export interface ThinkingFrameOptions {
14
+ width?: number;
15
+ streaming?: boolean;
16
+ durationText?: string;
17
+ collapsed?: boolean;
18
+ maxVisibleLines?: number;
19
+ role?: string;
20
+ }
21
+
22
+ export const DEFAULT_MAX_STREAMING_LINES = 8;
23
+ export const DEFAULT_MAX_EXPANDED_LINES = 12;
24
+
25
+ /**
26
+ * Single-line compact badge for collapsed reasoning frames.
27
+ */
28
+ export function renderCollapsedThinkingBadge(
29
+ options: ThinkingFrameOptions,
30
+ totalLines: number
31
+ ): string {
32
+ const isStreaming = Boolean(options.streaming);
33
+ const durationText = options.durationText ? String(options.durationText).trim() : '';
34
+ const arrow = HAS_UNICODE ? '▸' : '>';
35
+
36
+ if (isStreaming) {
37
+ const timePart = durationText ? ` · ${durationText}` : '';
38
+ return ` ${paint('warn', arrow)} ${bold(paint('warn', 'thinking…'))}${dim(timePart)} ${dim('· click to expand')}`;
39
+ }
40
+
41
+ const timePart = durationText ? ` for ${durationText}` : '';
42
+ const lineWord = totalLines === 1 ? 'line' : 'lines';
43
+ return ` ${paint('muted', arrow)} ${dim(`Thought${timePart}`)} ${dim(`(${totalLines} ${lineWord})`)} ${dim('· click to expand')}`;
44
+ }
45
+
46
+ /**
47
+ * Builds the top, bottom, and side frame borders for the thinking box.
48
+ */
49
+ export function buildThinkingBoxBorders(
50
+ title: string,
51
+ footer: string,
52
+ width: number,
53
+ role: string = 'rule'
54
+ ): {
55
+ top: string;
56
+ bottom: string;
57
+ wrapRow: (line: string) => string;
58
+ } {
59
+ const w = Math.max(20, Math.floor(width));
60
+ const inner = w - 2; // total space between left and right outer border corners
61
+
62
+ const h = GLYPHS.hLine || '─';
63
+ const v = GLYPHS.vLine || '│';
64
+ const tl = GLYPHS.topLeft || '╭';
65
+ const tr = GLYPHS.topRight || '╮';
66
+ const bl = GLYPHS.bottomLeft || '╰';
67
+ const br = GLYPHS.bottomRight || '╯';
68
+
69
+ // --- Top Border ---
70
+ const rawTitle = title ? ` ${title} ` : '';
71
+ const titleVis = visibleWidth(rawTitle);
72
+ const maxTitleVis = Math.max(0, inner - 4); // reserve at least 1 leading hLine and 2 trailing hLines
73
+ const safeTitle = titleVis > maxTitleVis ? (rawTitle ? ` ${truncate(title, Math.max(4, maxTitleVis - 2), GLYPHS.ellipsis || '…')} ` : '') : rawTitle;
74
+ const safeTitleVis = visibleWidth(safeTitle);
75
+
76
+ const topLead = h;
77
+ const topTrailCount = Math.max(0, inner - 1 - safeTitleVis);
78
+ const topTrail = h.repeat(topTrailCount);
79
+ const top = paint(role, tl + topLead) + safeTitle + paint(role, topTrail + tr);
80
+
81
+ // --- Bottom Border ---
82
+ const rawFooter = footer ? ` ${footer} ` : '';
83
+ const footerVis = visibleWidth(rawFooter);
84
+ const maxFooterVis = Math.max(0, inner - 4);
85
+ const safeFooter = footerVis > maxFooterVis ? (rawFooter ? ` ${truncate(footer, Math.max(4, maxFooterVis - 2), GLYPHS.ellipsis || '…')} ` : '') : rawFooter;
86
+ const safeFooterVis = visibleWidth(safeFooter);
87
+
88
+ const bottomLead = h;
89
+ const bottomTrailCount = Math.max(0, inner - 1 - safeFooterVis);
90
+ const bottomTrail = h.repeat(bottomTrailCount);
91
+ const bottom = paint(role, bl + bottomLead) + safeFooter + paint(role, bottomTrail + br);
92
+
93
+ // --- Middle Row Wrapper ---
94
+ // Format: "│ " + content + " │"
95
+ // content column width = inner - 2 = w - 4
96
+ const contentWidth = Math.max(2, inner - 2);
97
+ const side = paint(role, v);
98
+
99
+ const wrapRow = (line: string): string => {
100
+ const truncated = truncate(line, contentWidth, GLYPHS.ellipsis || '…');
101
+ const padded = padEnd(truncated, contentWidth);
102
+ return `${side} ${padded} ${side}`;
103
+ };
104
+
105
+ return { top, bottom, wrapRow };
106
+ }
107
+
108
+ /**
109
+ * Render a complete thinking frame (either compact collapsed badge or expanded box).
110
+ */
111
+ export function renderThinkingFrame(
112
+ content: string,
113
+ options: ThinkingFrameOptions = {}
114
+ ): string[] {
115
+ const text = String(content ?? '').trim();
116
+ if (!text) return [];
117
+
118
+ const width = Math.max(20, Math.floor(options.width ?? 80));
119
+ const isStreaming = Boolean(options.streaming);
120
+ const isCollapsed = Boolean(options.collapsed);
121
+ const durationText = options.durationText ? String(options.durationText).trim() : '';
122
+
123
+ // Wrap lines for inner box width (w - 4)
124
+ const contentBudget = Math.max(10, width - 4);
125
+ const allRows = wrapBlock(text, contentBudget);
126
+ const totalLines = allRows.length;
127
+
128
+ if (isCollapsed) {
129
+ return [renderCollapsedThinkingBadge(options, totalLines)];
130
+ }
131
+
132
+ // Expanded Box Mode
133
+ const role = isStreaming ? 'warn' : (options.role ?? 'rule');
134
+ const collapseIndicator = HAS_UNICODE ? '▾' : 'v';
135
+ const collapseHint = dim(`${collapseIndicator} click to collapse`);
136
+
137
+ if (isStreaming) {
138
+ const maxLines = options.maxVisibleLines ?? DEFAULT_MAX_STREAMING_LINES;
139
+ const timePart = durationText ? ` · ${durationText}` : '';
140
+ const title = `${bold(paint('warn', 'thinking…'))}${dim(timePart)}`;
141
+ const footer = collapseHint;
142
+
143
+ const { top, bottom, wrapRow } = buildThinkingBoxBorders(title, footer, width, role);
144
+ const rows: string[] = [top];
145
+
146
+ if (totalLines > maxLines) {
147
+ const hiddenCount = totalLines - (maxLines - 1);
148
+ const scrollIndicator = HAS_UNICODE ? '↑' : '^';
149
+ const hiddenNotice = `${paint('rule', scrollIndicator)} ${dim(`${hiddenCount} earlier thinking line${hiddenCount === 1 ? '' : 's'} scrolled`)}`;
150
+ rows.push(wrapRow(hiddenNotice));
151
+
152
+ const tailRows = allRows.slice(totalLines - (maxLines - 1));
153
+ for (const row of tailRows) {
154
+ rows.push(wrapRow(dim(row)));
155
+ }
156
+ } else {
157
+ for (const row of allRows) {
158
+ rows.push(wrapRow(dim(row)));
159
+ }
160
+ }
161
+
162
+ rows.push(bottom);
163
+ return rows;
164
+ }
165
+
166
+ // Completed Expanded Mode
167
+ const maxLines = options.maxVisibleLines ?? DEFAULT_MAX_EXPANDED_LINES;
168
+ const timePart = durationText ? ` · ${durationText}` : '';
169
+ const title = `${paint('muted', 'thinking')}${dim(timePart)} ${dim(`(${totalLines} line${totalLines === 1 ? '' : 's'})`)}`;
170
+
171
+ const { top, bottom, wrapRow } = buildThinkingBoxBorders(title, collapseHint, width, 'rule');
172
+ const rows: string[] = [top];
173
+
174
+ if (totalLines > maxLines) {
175
+ const hiddenCount = totalLines - maxLines;
176
+ const displayRows = allRows.slice(0, maxLines);
177
+ for (const row of displayRows) {
178
+ rows.push(wrapRow(dim(row)));
179
+ }
180
+ const moreNotice = `${GLYPHS.ellipsis || '…'} ${hiddenCount} more line${hiddenCount === 1 ? '' : 's'} of reasoning`;
181
+ rows.push(wrapRow(dim(moreNotice)));
182
+ } else {
183
+ for (const row of allRows) {
184
+ rows.push(wrapRow(dim(row)));
185
+ }
186
+ }
187
+
188
+ rows.push(bottom);
189
+ return rows;
190
+ }