@causyne/agent 1.20.31 → 1.20.33

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@causyne/agent",
3
- "version": "1.20.31",
3
+ "version": "1.20.33",
4
4
  "description": "Agentic AI for software, tools, and computer workflows",
5
5
  "main": "bin/causyne.js",
6
6
  "type": "module",
package/src/agentLoop.js CHANGED
@@ -1735,6 +1735,14 @@ export class AgentLoop {
1735
1735
  }
1736
1736
  this.userPrompt = null; // Clear so we don't push it again
1737
1737
  this.attachments = null; // Clear attachments
1738
+ if (this.memoryManager && typeof this.memoryManager.saveHistory === 'function') {
1739
+ try {
1740
+ this.memoryManager.saveHistory(this.messages);
1741
+ }
1742
+ catch {
1743
+ // Best-effort early persistence so active turns are immediately forkable/revertable.
1744
+ }
1745
+ }
1738
1746
  }
1739
1747
  this.stepsCompleted = 0;
1740
1748
  // Fresh per task. A digest from a previous task would point at a step
package/src/agentLoop.ts CHANGED
@@ -1831,6 +1831,13 @@ export class AgentLoop {
1831
1831
 
1832
1832
  this.userPrompt = null; // Clear so we don't push it again
1833
1833
  this.attachments = null; // Clear attachments
1834
+ if (this.memoryManager && typeof (this.memoryManager as any).saveHistory === 'function') {
1835
+ try {
1836
+ (this.memoryManager as any).saveHistory(this.messages);
1837
+ } catch {
1838
+ // Best-effort early persistence so active turns are immediately forkable/revertable.
1839
+ }
1840
+ }
1834
1841
  }
1835
1842
 
1836
1843
  this.stepsCompleted = 0;
@@ -119,7 +119,7 @@ export function normalizePeerPlanEntries(value) {
119
119
  }
120
120
  return { explanation, plan: steps };
121
121
  }
122
- export function extractToolCallJsonObjects(text) {
122
+ export function extractToolCallJsonObjects(text, allowUnclosedHealing = true) {
123
123
  const results = [];
124
124
  if (!text || typeof text !== 'string')
125
125
  return results;
@@ -180,6 +180,8 @@ export function extractToolCallJsonObjects(text) {
180
180
  // Fall through to suffix healing below
181
181
  }
182
182
  }
183
+ if (!allowUnclosedHealing)
184
+ continue;
183
185
  // Unclosed or truncated JSON after <tool_call>: strip trailing XML/DSML closing tags and heal
184
186
  const nextTagIndex = text.indexOf('<tool_call>', braceStart + 1);
185
187
  const sliceEnd = nextTagIndex === -1 ? text.length : nextTagIndex;
@@ -243,6 +245,8 @@ export function extractToolCallJsonObjects(text) {
243
245
  }
244
246
  return results;
245
247
  }
248
+ const TRAILING_PARTIAL_TOOL_TAG = /<\/?(?:t(?:o(?:o(?:l(?:_(?:c(?:a(?:l(?:l)?)?)?)?)?)?)?)?|f(?:u(?:n(?:c(?:t(?:i(?:o(?:n(?:_(?:c(?:a(?:l(?:l(?:s)?)?)?)?)?)?)?)?)?)?)?)?)?|i(?:n(?:v(?:o(?:k(?:e)?)?)?)?)?|[||][^\n>]*)$/i;
249
+ const TRAILING_PARTIAL_THINK_TAG = /<\/?(?:t(?:h(?:i(?:n(?:k(?:i(?:n(?:g)?)?)?)?|o(?:u(?:g(?:h(?:t)?)?)?)?)?)?)?|r(?:e(?:a(?:s(?:o(?:n(?:i(?:n(?:g(?:_(?:s(?:c(?:r(?:a(?:t(?:c(?:h(?:p(?:a(?:d)?)?)?)?)?)?)?)?)?)?)?)?)?)?)?)?)?)?)?)$/i;
246
250
  export function stripToolCallMarkup(text) {
247
251
  if (!text || typeof text !== 'string')
248
252
  return '';
@@ -250,6 +254,7 @@ export function stripToolCallMarkup(text) {
250
254
  .replace(/<tool_call>[\s\S]*?(?:<\/tool_call>|(?:\s*<\/?[||]DSML[||][^>]*>)+|$)/gi, '')
251
255
  .replace(/<[||]DSML[||][\s\S]*?(?:<\/[||]DSML[||]\s*calls>|$)/gi, '')
252
256
  .replace(/(?:\s*<\/?[||]DSML[||][^>]*>)+/gi, '')
257
+ .replace(TRAILING_PARTIAL_TOOL_TAG, '')
253
258
  .trim();
254
259
  }
255
260
  export function stripThinkBlocks(text) {
@@ -257,6 +262,7 @@ export function stripThinkBlocks(text) {
257
262
  return '';
258
263
  return text
259
264
  .replace(/<(?:think|thought|reasoning|thinking|REASONING_SCRATCHPAD)>[\s\S]*?(?:<\/(?:think|thought|reasoning|thinking|REASONING_SCRATCHPAD)>|$)/gi, '')
265
+ .replace(TRAILING_PARTIAL_THINK_TAG, '')
260
266
  .trim();
261
267
  }
262
268
  export function extractLivePlanFromText(text, allowTrailing = false) {
@@ -265,7 +271,7 @@ export function extractLivePlanFromText(text, allowTrailing = false) {
265
271
  const cleanText = text.replace(/\r\n/g, '\n');
266
272
  // 1. Check for inline <tool_call>{"name": "update_plan" | "todowrite", ...}</tool_call> (including DSML-closed blocks)
267
273
  let latestToolPlan = null;
268
- for (const parsed of extractToolCallJsonObjects(cleanText)) {
274
+ for (const parsed of extractToolCallJsonObjects(cleanText, allowTrailing)) {
269
275
  try {
270
276
  const toolName = String(parsed?.name || parsed?.tool || '').toLowerCase().trim();
271
277
  if (toolName === 'update_plan' || toolName === 'todowrite' || toolName === 'todo_write') {
@@ -127,7 +127,7 @@ export function normalizePeerPlanEntries(value: unknown): PlanUpdate | null {
127
127
  return { explanation, plan: steps };
128
128
  }
129
129
 
130
- export function extractToolCallJsonObjects(text: string): Array<Record<string, unknown>> {
130
+ export function extractToolCallJsonObjects(text: string, allowUnclosedHealing = true): Array<Record<string, unknown>> {
131
131
  const results: Array<Record<string, unknown>> = [];
132
132
  if (!text || typeof text !== 'string') return results;
133
133
 
@@ -183,6 +183,8 @@ export function extractToolCallJsonObjects(text: string): Array<Record<string, u
183
183
  }
184
184
  }
185
185
 
186
+ if (!allowUnclosedHealing) continue;
187
+
186
188
  // Unclosed or truncated JSON after <tool_call>: strip trailing XML/DSML closing tags and heal
187
189
  const nextTagIndex = text.indexOf('<tool_call>', braceStart + 1);
188
190
  const sliceEnd = nextTagIndex === -1 ? text.length : nextTagIndex;
@@ -245,12 +247,16 @@ export function extractToolCallJsonObjects(text: string): Array<Record<string, u
245
247
  return results;
246
248
  }
247
249
 
250
+ const TRAILING_PARTIAL_TOOL_TAG = /<\/?(?:t(?:o(?:o(?:l(?:_(?:c(?:a(?:l(?:l)?)?)?)?)?)?)?)?|f(?:u(?:n(?:c(?:t(?:i(?:o(?:n(?:_(?:c(?:a(?:l(?:l(?:s)?)?)?)?)?)?)?)?)?)?)?)?)?|i(?:n(?:v(?:o(?:k(?:e)?)?)?)?)?|[||][^\n>]*)$/i;
251
+ const TRAILING_PARTIAL_THINK_TAG = /<\/?(?:t(?:h(?:i(?:n(?:k(?:i(?:n(?:g)?)?)?)?|o(?:u(?:g(?:h(?:t)?)?)?)?)?)?)?|r(?:e(?:a(?:s(?:o(?:n(?:i(?:n(?:g(?:_(?:s(?:c(?:r(?:a(?:t(?:c(?:h(?:p(?:a(?:d)?)?)?)?)?)?)?)?)?)?)?)?)?)?)?)?)?)?)?)$/i;
252
+
248
253
  export function stripToolCallMarkup(text: string): string {
249
254
  if (!text || typeof text !== 'string') return '';
250
255
  return text
251
256
  .replace(/<tool_call>[\s\S]*?(?:<\/tool_call>|(?:\s*<\/?[||]DSML[||][^>]*>)+|$)/gi, '')
252
257
  .replace(/<[||]DSML[||][\s\S]*?(?:<\/[||]DSML[||]\s*calls>|$)/gi, '')
253
258
  .replace(/(?:\s*<\/?[||]DSML[||][^>]*>)+/gi, '')
259
+ .replace(TRAILING_PARTIAL_TOOL_TAG, '')
254
260
  .trim();
255
261
  }
256
262
 
@@ -258,6 +264,7 @@ export function stripThinkBlocks(text: string): string {
258
264
  if (!text || typeof text !== 'string') return '';
259
265
  return text
260
266
  .replace(/<(?:think|thought|reasoning|thinking|REASONING_SCRATCHPAD)>[\s\S]*?(?:<\/(?:think|thought|reasoning|thinking|REASONING_SCRATCHPAD)>|$)/gi, '')
267
+ .replace(TRAILING_PARTIAL_THINK_TAG, '')
261
268
  .trim();
262
269
  }
263
270
 
@@ -267,7 +274,7 @@ export function extractLivePlanFromText(text: string, allowTrailing = false): Pl
267
274
 
268
275
  // 1. Check for inline <tool_call>{"name": "update_plan" | "todowrite", ...}</tool_call> (including DSML-closed blocks)
269
276
  let latestToolPlan: PlanUpdate | null = null;
270
- for (const parsed of extractToolCallJsonObjects(cleanText)) {
277
+ for (const parsed of extractToolCallJsonObjects(cleanText, allowTrailing)) {
271
278
  try {
272
279
  const toolName = String(parsed?.name || parsed?.tool || '').toLowerCase().trim();
273
280
  if (toolName === 'update_plan' || toolName === 'todowrite' || toolName === 'todo_write') {
@@ -11,7 +11,9 @@ const MUTATION_TOOLS = new Set([
11
11
  'create_skill', 'manage_local_dependencies'
12
12
  ]);
13
13
  export function isLaunchOnlyPrompt(prompt) {
14
- if (/\brun\s+(?:the\s+)?(?:tests?|checks?|lint|benchmarks?|scripts?|commands?)\b/i.test(prompt))
14
+ if (/\b(?:run|execute)\s+(?:the\s+)?(?:tests?|checks?|lint|benchmarks?|scripts?|commands?|tools?|creative_apps|resolve_act|memory_recall|native_engine|browser_act|fs_read|sysRun)\b/i.test(prompt))
15
+ return false;
16
+ if (/\b(?:verify|verification|verify_bridge|inspectActive|simulate|probe|audit|analyze|diagnose)\b/i.test(prompt))
15
17
  return false;
16
18
  return LAUNCH_VERBS.test(prompt) && !CHANGE_VERBS.test(prompt);
17
19
  }
@@ -13,7 +13,8 @@ const MUTATION_TOOLS = new Set([
13
13
  ]);
14
14
 
15
15
  export function isLaunchOnlyPrompt(prompt: string): boolean {
16
- if (/\brun\s+(?:the\s+)?(?:tests?|checks?|lint|benchmarks?|scripts?|commands?)\b/i.test(prompt)) return false;
16
+ if (/\b(?:run|execute)\s+(?:the\s+)?(?:tests?|checks?|lint|benchmarks?|scripts?|commands?|tools?|creative_apps|resolve_act|memory_recall|native_engine|browser_act|fs_read|sysRun)\b/i.test(prompt)) return false;
17
+ if (/\b(?:verify|verification|verify_bridge|inspectActive|simulate|probe|audit|analyze|diagnose)\b/i.test(prompt)) return false;
17
18
  return LAUNCH_VERBS.test(prompt) && !CHANGE_VERBS.test(prompt);
18
19
  }
19
20
 
@@ -331,7 +331,9 @@ export async function discoverTools() {
331
331
  }
332
332
  catch (error) {
333
333
  const message = error instanceof Error ? error.message : String(error);
334
- console.warn(`[MCP] ${server.name} unavailable: ${message}`);
334
+ if (process.env.CAUSYNE_DEBUG === '1') {
335
+ console.warn(`[MCP] ${server.name} unavailable: ${message}`);
336
+ }
335
337
  return [];
336
338
  }
337
339
  }));
@@ -355,7 +355,9 @@ export async function discoverTools(): Promise<DynamicToolDefinition[]> {
355
355
  .concat(utilityDefinitions(server, client));
356
356
  } catch (error) {
357
357
  const message = error instanceof Error ? error.message : String(error);
358
- console.warn(`[MCP] ${server.name} unavailable: ${message}`);
358
+ if (process.env.CAUSYNE_DEBUG === '1') {
359
+ console.warn(`[MCP] ${server.name} unavailable: ${message}`);
360
+ }
359
361
  return [];
360
362
  }
361
363
  }));
@@ -397,7 +397,7 @@ export function scanMutation(toolName, args, context) {
397
397
  }
398
398
  export function boundedArgs(args) {
399
399
  const result = {};
400
- for (const key of ['command', 'cmd', 'path', 'file_path', 'source', 'destination', 'action', 'url', 'query', 'pattern']) {
400
+ for (const key of ['command', 'cmd', 'path', 'file_path', 'source', 'destination', 'action', 'operation', 'engine', 'host', 'mode', 'url', 'query', 'pattern']) {
401
401
  const value = args[key];
402
402
  if (typeof value === 'string')
403
403
  result[key] = value.slice(0, 400);
@@ -406,6 +406,12 @@ export function boundedArgs(args) {
406
406
  result.recursive = args.recursive;
407
407
  if (typeof args.overwrite === 'boolean')
408
408
  result.overwrite = args.overwrite;
409
+ if (typeof args.simulate === 'boolean')
410
+ result.simulate = args.simulate;
411
+ if (typeof args.dryRun === 'boolean')
412
+ result.dryRun = args.dryRun;
413
+ if (typeof args.extractTextOnly === 'boolean')
414
+ result.extractTextOnly = args.extractTextOnly;
409
415
  if (typeof args.content === 'string')
410
416
  result.contentBytes = Buffer.byteLength(args.content, 'utf8');
411
417
  if (Array.isArray(args.edits))
@@ -423,7 +429,8 @@ export function outcomeFromResult(tool, args, result, at) {
423
429
  ? args.command
424
430
  : typeof args.cmd === 'string' ? args.cmd : '';
425
431
  const browserData = Array.isArray(record.data) ? record.data : [];
426
- const observedImage = success && record._is_image_marker === true && record.visionDelivered !== false;
432
+ const imageCaptured = success && record._is_image_marker === true;
433
+ const observedImage = imageCaptured && record.visionDelivered !== false;
427
434
  const rendered = success && (observedImage || (tool === 'browser_act' && browserData.some((item) => {
428
435
  if (!item || typeof item !== 'object')
429
436
  return false;
@@ -442,6 +449,7 @@ export function outcomeFromResult(tool, args, result, at) {
442
449
  path: pathArgument(args).slice(0, 400),
443
450
  at,
444
451
  ...(rendered ? { rendered: true } : {}),
445
- ...(observedImage ? { observedImage: true } : {})
452
+ ...(observedImage ? { observedImage: true } : {}),
453
+ ...(imageCaptured ? { imageCaptured: true } : {})
446
454
  };
447
455
  }
@@ -40,6 +40,7 @@ export interface ToolOutcome {
40
40
  at: number;
41
41
  rendered?: boolean;
42
42
  observedImage?: boolean;
43
+ imageCaptured?: boolean;
43
44
  }
44
45
 
45
46
  const SEVERITY_WEIGHT: Record<RiskSeverity, number> = {
@@ -467,12 +468,15 @@ export function scanMutation(toolName: string, args: Record<string, unknown>, co
467
468
 
468
469
  export function boundedArgs(args: Record<string, unknown>): Record<string, unknown> {
469
470
  const result: Record<string, unknown> = {};
470
- for (const key of ['command', 'cmd', 'path', 'file_path', 'source', 'destination', 'action', 'url', 'query', 'pattern']) {
471
+ for (const key of ['command', 'cmd', 'path', 'file_path', 'source', 'destination', 'action', 'operation', 'engine', 'host', 'mode', 'url', 'query', 'pattern']) {
471
472
  const value = args[key];
472
473
  if (typeof value === 'string') result[key] = value.slice(0, 400);
473
474
  }
474
475
  if (typeof args.recursive === 'boolean') result.recursive = args.recursive;
475
476
  if (typeof args.overwrite === 'boolean') result.overwrite = args.overwrite;
477
+ if (typeof args.simulate === 'boolean') result.simulate = args.simulate;
478
+ if (typeof args.dryRun === 'boolean') result.dryRun = args.dryRun;
479
+ if (typeof args.extractTextOnly === 'boolean') result.extractTextOnly = args.extractTextOnly;
476
480
  if (typeof args.content === 'string') result.contentBytes = Buffer.byteLength(args.content, 'utf8');
477
481
  if (Array.isArray(args.edits)) result.editCount = args.edits.length;
478
482
  return result;
@@ -489,7 +493,8 @@ export function outcomeFromResult(tool: string, args: Record<string, unknown>, r
489
493
  ? args.command
490
494
  : typeof args.cmd === 'string' ? args.cmd : '';
491
495
  const browserData = Array.isArray(record.data) ? record.data : [];
492
- const observedImage = success && record._is_image_marker === true && record.visionDelivered !== false;
496
+ const imageCaptured = success && record._is_image_marker === true;
497
+ const observedImage = imageCaptured && record.visionDelivered !== false;
493
498
  const rendered = success && (observedImage || (tool === 'browser_act' && browserData.some((item: unknown) => {
494
499
  if (!item || typeof item !== 'object') return false;
495
500
  const action = item as { action?: string; success?: boolean; error?: unknown; data?: { runtimeErrors?: unknown[] } };
@@ -508,6 +513,7 @@ export function outcomeFromResult(tool: string, args: Record<string, unknown>, r
508
513
  path: pathArgument(args).slice(0, 400),
509
514
  at,
510
515
  ...(rendered ? { rendered: true } : {}),
511
- ...(observedImage ? { observedImage: true } : {})
516
+ ...(observedImage ? { observedImage: true } : {}),
517
+ ...(imageCaptured ? { imageCaptured: true } : {})
512
518
  };
513
519
  }
@@ -1,99 +1,81 @@
1
+ // @ts-expect-error Legacy memory module has no TypeScript declarations yet.
1
2
  import { getMemory, saveMemory } from '../memory.js';
2
3
  import { cortexDb } from '../cortex/vectorDb.js';
3
-
4
- // Persistent memory write.
5
- //
6
- // This tool used to append facts to `{cwd}/.causyne_memory_store.json` — a file
7
- // that nothing in the codebase ever reads. The facts the agent is actually shown
8
- // come from `getMemoryContextString()`, which reads `~/.causyne/memory.json`, and
9
-
10
- // never connected, so every fact the agent chose to remember was written into a
11
- // per-project dead end and silently lost. It now writes where the agent reads.
12
-
13
4
  const MAX_FACTS = 100;
14
-
15
5
  export const memoryWrite = {
16
- schema: {
17
- name: 'memory_write',
18
- description: "Save a durable fact about the user, their machine, or their project into persistent memory. Facts saved here are injected into your system context on every future task, so record only things worth remembering across sessions (preferences, conventions, paths, stack choices). After completing a web or UI design, also pass creativePattern so you do not repeat the same aesthetic next time.",
19
- parameters: {
20
- type: 'object',
21
- properties: {
22
- fact: {
23
- type: 'string',
24
- description: 'The concise, durable fact to remember. One fact per call.'
25
- },
26
- creativePattern: {
27
- type: 'object',
28
- description: 'Optional. Record a completed design so future projects deliberately differ from it.',
29
- properties: {
30
- project: { type: 'string', description: 'What was built, e.g. "coffee roaster landing page".' },
31
- designApproach: { type: 'string', description: 'The design movement committed to, e.g. "Swiss International", "Brutalism".' },
32
- colorPalette: { type: 'string', description: 'The palette used, e.g. "warm neutrals + oxblood accent".' },
33
- fonts: { type: 'string', description: 'Typefaces used, e.g. "Space Grotesk / Inter".' }
34
- }
6
+ schema: {
7
+ name: 'memory_write',
8
+ description: 'Save a durable fact about the user, their machine, or their project into persistent memory. Facts saved here are injected into your system context on every future task, so record only things worth remembering across sessions (preferences, conventions, paths, stack choices). After completing a web or UI design, also pass creativePattern so you do not repeat the same aesthetic next time.',
9
+ parameters: {
10
+ type: 'object',
11
+ properties: {
12
+ fact: {
13
+ type: 'string',
14
+ description: 'The concise, durable fact to remember. One fact per call.'
15
+ },
16
+ creativePattern: {
17
+ type: 'object',
18
+ description: 'Optional. Record a completed design so future projects deliberately differ from it.',
19
+ properties: {
20
+ project: { type: 'string', description: 'What was built, e.g. "coffee roaster landing page".' },
21
+ designApproach: { type: 'string', description: 'The design movement committed to, e.g. "Swiss International", "Brutalism".' },
22
+ colorPalette: { type: 'string', description: 'The palette used, e.g. "warm neutrals + oxblood accent".' },
23
+ fonts: { type: 'string', description: 'Typefaces used, e.g. "Space Grotesk / Inter".' }
24
+ }
25
+ }
26
+ },
27
+ required: ['fact']
35
28
  }
36
- },
37
- required: ['fact']
38
- }
39
- },
40
-
41
- execute: async (args, dependencies) => {
42
- if (!args || !args.fact) {
43
- return { success: false, error: "Missing 'fact' parameter." };
44
- }
45
-
46
- try {
47
- const memory = getMemory();
48
- if (!Array.isArray(memory.facts)) memory.facts = [];
49
-
50
- const fact = String(args.fact).trim();
51
- const alreadyKnown = memory.facts.includes(fact);
52
-
53
- if (!alreadyKnown) {
54
- memory.facts.push(fact);
55
- // Self-culling: keep the store bounded so it cannot grow into the
56
- // system prompt without limit.
57
- while (memory.facts.length > MAX_FACTS) {
58
- memory.facts.shift();
29
+ },
30
+ execute: async (args, dependencies) => {
31
+ if (!args || !args.fact) {
32
+ return { success: false, error: "Missing 'fact' parameter." };
59
33
  }
60
- saveMemory(memory);
61
- }
62
-
63
- // Anti-slop creative memory. saveCreativePattern() existed but had no
64
- // caller anywhere, so getRecentCreativePatterns() always returned empty
65
- // and the "DO NOT REPEAT RECENT PATTERNS" directive never once fired.
66
- let creativeSaved = false;
67
- if (args.creativePattern && args.creativePattern.designApproach) {
68
34
  try {
69
- await cortexDb.saveCreativePattern({
70
- project: args.creativePattern.project || 'untitled project',
71
- designApproach: args.creativePattern.designApproach,
72
- colorPalette: args.creativePattern.colorPalette || 'unspecified',
73
- fonts: args.creativePattern.fonts || 'unspecified'
74
- });
75
- creativeSaved = true;
76
- } catch (e) {
77
- console.error('[CORTEX] Creative pattern save failed:', e.message);
35
+ const memory = getMemory();
36
+ if (!Array.isArray(memory.facts))
37
+ memory.facts = [];
38
+ const fact = String(args.fact).trim();
39
+ const alreadyKnown = memory.facts.includes(fact);
40
+ if (!alreadyKnown) {
41
+ memory.facts.push(fact);
42
+ while (memory.facts.length > MAX_FACTS) {
43
+ memory.facts.shift();
44
+ }
45
+ saveMemory(memory);
46
+ }
47
+ let creativeSaved = false;
48
+ if (args.creativePattern && args.creativePattern.designApproach) {
49
+ try {
50
+ await cortexDb.saveCreativePattern({
51
+ project: args.creativePattern.project || 'untitled project',
52
+ designApproach: args.creativePattern.designApproach,
53
+ colorPalette: args.creativePattern.colorPalette || 'unspecified',
54
+ fonts: args.creativePattern.fonts || 'unspecified'
55
+ });
56
+ creativeSaved = true;
57
+ }
58
+ catch {
59
+ // Optional Cortex dependencies may not be installed; standard local session memory remains active.
60
+ // Never write raw errors to console.error during a TUI session as that corrupts the composer viewport.
61
+ }
62
+ }
63
+ if (dependencies && typeof dependencies.broadcast === 'function') {
64
+ dependencies.broadcast({
65
+ type: 'agent_message',
66
+ content: `🧠 Persistent memory updated: "${fact}"`
67
+ });
68
+ }
69
+ const notes = [
70
+ alreadyKnown ? 'Fact already known, not duplicated.' : 'Fact saved.',
71
+ `Total persistent facts: ${memory.facts.length}.`,
72
+ creativeSaved ? 'Creative pattern recorded in the V5 Cortex.' : ''
73
+ ].filter(Boolean);
74
+ return { success: true, output: notes.join(' ') };
75
+ }
76
+ catch (e) {
77
+ const msg = e instanceof Error ? e.message : String(e);
78
+ return { success: false, error: `Failed to save memory: ${msg}` };
78
79
  }
79
- }
80
-
81
- if (dependencies && dependencies.broadcast) {
82
- dependencies.broadcast({
83
- type: 'agent_message',
84
- content: `🧠 Persistent memory updated: "${fact}"`
85
- });
86
- }
87
-
88
- const notes = [
89
- alreadyKnown ? 'Fact already known, not duplicated.' : 'Fact saved.',
90
- `Total persistent facts: ${memory.facts.length}.`,
91
- creativeSaved ? 'Creative pattern recorded in the V5 Cortex.' : ''
92
- ].filter(Boolean);
93
-
94
- return { success: true, output: notes.join(' ') };
95
- } catch (e) {
96
- return { success: false, error: `Failed to save memory: ${e.message}` };
97
80
  }
98
- }
99
81
  };
@@ -0,0 +1,108 @@
1
+ // @ts-expect-error Legacy memory module has no TypeScript declarations yet.
2
+ import { getMemory, saveMemory } from '../memory.js';
3
+ import { cortexDb } from '../cortex/vectorDb.js';
4
+
5
+ const MAX_FACTS = 100;
6
+
7
+ export interface CreativePatternInput {
8
+ project?: string;
9
+ designApproach?: string;
10
+ colorPalette?: string;
11
+ fonts?: string;
12
+ }
13
+
14
+ export interface MemoryWriteArgs {
15
+ fact?: string;
16
+ creativePattern?: CreativePatternInput;
17
+ }
18
+
19
+ export interface MemoryWriteDependencies {
20
+ broadcast?: (event: { type: string; content: string }) => void;
21
+ }
22
+
23
+ export const memoryWrite = {
24
+ schema: {
25
+ name: 'memory_write',
26
+ description:
27
+ 'Save a durable fact about the user, their machine, or their project into persistent memory. Facts saved here are injected into your system context on every future task, so record only things worth remembering across sessions (preferences, conventions, paths, stack choices). After completing a web or UI design, also pass creativePattern so you do not repeat the same aesthetic next time.',
28
+ parameters: {
29
+ type: 'object',
30
+ properties: {
31
+ fact: {
32
+ type: 'string',
33
+ description: 'The concise, durable fact to remember. One fact per call.'
34
+ },
35
+ creativePattern: {
36
+ type: 'object',
37
+ description: 'Optional. Record a completed design so future projects deliberately differ from it.',
38
+ properties: {
39
+ project: { type: 'string', description: 'What was built, e.g. "coffee roaster landing page".' },
40
+ designApproach: { type: 'string', description: 'The design movement committed to, e.g. "Swiss International", "Brutalism".' },
41
+ colorPalette: { type: 'string', description: 'The palette used, e.g. "warm neutrals + oxblood accent".' },
42
+ fonts: { type: 'string', description: 'Typefaces used, e.g. "Space Grotesk / Inter".' }
43
+ }
44
+ }
45
+ },
46
+ required: ['fact']
47
+ }
48
+ },
49
+
50
+ execute: async (
51
+ args: MemoryWriteArgs | null | undefined,
52
+ dependencies?: MemoryWriteDependencies
53
+ ): Promise<{ success: boolean; output?: string; error?: string }> => {
54
+ if (!args || !args.fact) {
55
+ return { success: false, error: "Missing 'fact' parameter." };
56
+ }
57
+
58
+ try {
59
+ const memory = getMemory() as { facts?: string[] };
60
+ if (!Array.isArray(memory.facts)) memory.facts = [];
61
+
62
+ const fact = String(args.fact).trim();
63
+ const alreadyKnown = memory.facts.includes(fact);
64
+
65
+ if (!alreadyKnown) {
66
+ memory.facts.push(fact);
67
+ while (memory.facts.length > MAX_FACTS) {
68
+ memory.facts.shift();
69
+ }
70
+ saveMemory(memory);
71
+ }
72
+
73
+ let creativeSaved = false;
74
+ if (args.creativePattern && args.creativePattern.designApproach) {
75
+ try {
76
+ await cortexDb.saveCreativePattern({
77
+ project: args.creativePattern.project || 'untitled project',
78
+ designApproach: args.creativePattern.designApproach,
79
+ colorPalette: args.creativePattern.colorPalette || 'unspecified',
80
+ fonts: args.creativePattern.fonts || 'unspecified'
81
+ });
82
+ creativeSaved = true;
83
+ } catch {
84
+ // Optional Cortex dependencies may not be installed; standard local session memory remains active.
85
+ // Never write raw errors to console.error during a TUI session as that corrupts the composer viewport.
86
+ }
87
+ }
88
+
89
+ if (dependencies && typeof dependencies.broadcast === 'function') {
90
+ dependencies.broadcast({
91
+ type: 'agent_message',
92
+ content: `🧠 Persistent memory updated: "${fact}"`
93
+ });
94
+ }
95
+
96
+ const notes = [
97
+ alreadyKnown ? 'Fact already known, not duplicated.' : 'Fact saved.',
98
+ `Total persistent facts: ${memory.facts.length}.`,
99
+ creativeSaved ? 'Creative pattern recorded in the V5 Cortex.' : ''
100
+ ].filter(Boolean);
101
+
102
+ return { success: true, output: notes.join(' ') };
103
+ } catch (e) {
104
+ const msg = e instanceof Error ? e.message : String(e);
105
+ return { success: false, error: `Failed to save memory: ${msg}` };
106
+ }
107
+ }
108
+ };
@@ -0,0 +1,85 @@
1
+ const activeStageHosts = new Set();
2
+ let stageMouseSessionDepth = 0;
3
+ let guardInstalled = false;
4
+ const originalConsole = {
5
+ log: console.log.bind(console),
6
+ info: console.info.bind(console),
7
+ warn: console.warn.bind(console),
8
+ error: console.error.bind(console)
9
+ };
10
+ export function isAnyStageReservedOnStdout() {
11
+ if (stageMouseSessionDepth > 0 && process.stdout?.isTTY) {
12
+ return true;
13
+ }
14
+ for (const host of activeStageHosts) {
15
+ if (host.stage?.reserved && (!host.out || host.out === process.stdout)) {
16
+ return true;
17
+ }
18
+ }
19
+ return false;
20
+ }
21
+ function ensureConsoleGuardInstalled() {
22
+ if (guardInstalled)
23
+ return;
24
+ guardInstalled = true;
25
+ const wrap = (fn) => (...args) => {
26
+ if (isAnyStageReservedOnStdout()) {
27
+ // Never write raw console output while the full-screen TUI Stage owns stdout,
28
+ // because the terminal cursor rests inside the composer input box and raw
29
+ // writes corrupt the composer rows and shift the physical cursor.
30
+ return;
31
+ }
32
+ fn(...args);
33
+ };
34
+ console.log = wrap(originalConsole.log);
35
+ console.info = wrap(originalConsole.info);
36
+ console.warn = wrap(originalConsole.warn);
37
+ console.error = wrap(originalConsole.error);
38
+ }
39
+ /**
40
+ * Track TUI Stage open/close lifecycle so raw console writes cannot corrupt the composer box.
41
+ */
42
+ export function setStageConsoleGuardActive(active) {
43
+ ensureConsoleGuardInstalled();
44
+ if (active) {
45
+ stageMouseSessionDepth = Math.max(1, stageMouseSessionDepth + 1);
46
+ }
47
+ else {
48
+ stageMouseSessionDepth = Math.max(0, stageMouseSessionDepth - 1);
49
+ }
50
+ }
51
+ /**
52
+ * Register a StageSurface host so raw console writes are suppressed while its Stage is reserved.
53
+ */
54
+ export function registerStageConsoleGuard(host) {
55
+ ensureConsoleGuardInstalled();
56
+ activeStageHosts.add(host);
57
+ return () => {
58
+ activeStageHosts.delete(host);
59
+ };
60
+ }
61
+ const noticeTimers = new WeakMap();
62
+ /**
63
+ * Set a transient status notice on the prompt/composer host and auto-clear it after `ttlMs`
64
+ * if nothing else has overwritten `host.notice` in the meantime.
65
+ */
66
+ export function setTransientNotice(host, message, ttlMs = 4000) {
67
+ const existing = noticeTimers.get(host);
68
+ if (existing) {
69
+ clearTimeout(existing);
70
+ noticeTimers.delete(host);
71
+ }
72
+ host.notice = message;
73
+ host.scheduleDraw();
74
+ if (!message || ttlMs <= 0)
75
+ return;
76
+ const timer = setTimeout(() => {
77
+ noticeTimers.delete(host);
78
+ if (host.notice === message) {
79
+ host.notice = '';
80
+ host.scheduleDraw();
81
+ }
82
+ }, ttlMs);
83
+ timer.unref?.();
84
+ noticeTimers.set(host, timer);
85
+ }