@causyne/agent 1.20.60 → 1.20.62

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 (41) hide show
  1. package/package.json +1 -1
  2. package/src/acp/agentCatalog.js +1 -1
  3. package/src/acp/agentCatalog.ts +1 -1
  4. package/src/acp/peerProfiles.js +3 -3
  5. package/src/acp/peerProfiles.ts +3 -3
  6. package/src/agentLoop.js +58 -22
  7. package/src/agentLoop.ts +64 -25
  8. package/src/checkpoints.js +23 -5
  9. package/src/cliMode.js +4 -2
  10. package/src/commands.js +503 -78
  11. package/src/contextManager.d.ts +3 -0
  12. package/src/contextManager.js +78 -5
  13. package/src/cortex/autoCondenser.js +105 -145
  14. package/src/cortex/autoCondenser.ts +185 -0
  15. package/src/cortex/cortexEngine.js +179 -0
  16. package/src/cortex/cortexEngine.ts +209 -0
  17. package/src/cortex/provisioner.js +12 -14
  18. package/src/cortex/provisioner.ts +29 -0
  19. package/src/cortex/vectorDb.js +307 -386
  20. package/src/cortex/vectorDb.ts +473 -0
  21. package/src/reporting.js +30 -7
  22. package/src/sessionJournal.js +13 -0
  23. package/src/sessionJournal.ts +13 -0
  24. package/src/tokenTracker.js +22 -0
  25. package/src/tokenTracker.ts +28 -0
  26. package/src/tui/chatRenderer.js +6 -2
  27. package/src/tui/completion.js +34 -15
  28. package/src/tui/composerControls.js +5 -0
  29. package/src/tui/composerControls.ts +5 -0
  30. package/src/tui/layout.js +1 -1
  31. package/src/tui/layout.ts +1 -1
  32. package/src/tui/observerPicker.js +323 -0
  33. package/src/tui/observerPicker.ts +386 -0
  34. package/src/tui/prompt.js +184 -22
  35. package/src/tui/stageSurface.js +18 -8
  36. package/src/tui/usageCard.js +178 -0
  37. package/src/tui/usageCard.ts +240 -0
  38. package/src/utils/paths.js +30 -1
  39. package/src/utils/paths.ts +32 -1
  40. package/src/cortex/autoCondenser.d.ts +0 -2
  41. package/src/cortex/vectorDb.d.ts +0 -1
@@ -85,6 +85,8 @@ export interface SettledUsage {
85
85
  dailyTokens: number;
86
86
  dailyCostUsd: number;
87
87
  dailyLimit: number;
88
+ sessionTokens?: number;
89
+ sessionCostUsd?: number;
88
90
  taskTokens: number;
89
91
  taskCostUsd: number;
90
92
  taskLimit: number;
@@ -102,6 +104,8 @@ export class TokenTracker {
102
104
  budget: TokenBudgetConfig;
103
105
  taskTokens: number;
104
106
  taskCostUsd: number;
107
+ sessionTokens: number;
108
+ sessionCostUsd: number;
105
109
  largestStepTokens: number;
106
110
 
107
111
  constructor() {
@@ -109,6 +113,8 @@ export class TokenTracker {
109
113
  this.budget = this.config.tokenBudget || { enabled: false };
110
114
  this.taskTokens = 0;
111
115
  this.taskCostUsd = 0;
116
+ this.sessionTokens = 0;
117
+ this.sessionCostUsd = 0;
112
118
  this.largestStepTokens = 0;
113
119
  this.ensureUsageDir();
114
120
  }
@@ -261,7 +267,9 @@ export class TokenTracker {
261
267
  const equivalentTokens = Math.round(cost / 0.000002);
262
268
 
263
269
  this.taskTokens += equivalentTokens;
270
+ this.sessionTokens = (this.sessionTokens || 0) + equivalentTokens;
264
271
  this.taskCostUsd += cost;
272
+ this.sessionCostUsd = (this.sessionCostUsd || 0) + cost;
265
273
 
266
274
  const cumulative = await this.getCumulativeUsage();
267
275
  const daily = await this.getDailyUsage();
@@ -408,9 +416,11 @@ export class TokenTracker {
408
416
  usedTokens: number;
409
417
  dailyTokens: number;
410
418
  taskTokens: number;
419
+ sessionTokens: number;
411
420
  lifetimeTokens: number;
412
421
  costUsd: number;
413
422
  taskCostUsd: number;
423
+ sessionCostUsd: number;
414
424
  lifetimeCostUsd: number;
415
425
  isDemo: boolean;
416
426
  }> {
@@ -420,9 +430,11 @@ export class TokenTracker {
420
430
  usedTokens: daily.totalTokens,
421
431
  dailyTokens: daily.totalTokens,
422
432
  taskTokens: this.taskTokens,
433
+ sessionTokens: this.sessionTokens || this.taskTokens || 0,
423
434
  lifetimeTokens: cumulative.totalTokens,
424
435
  costUsd: daily.totalCostUsd,
425
436
  taskCostUsd: this.taskCostUsd,
437
+ sessionCostUsd: this.sessionCostUsd || this.taskCostUsd || 0,
426
438
  lifetimeCostUsd: cumulative.totalCostUsd,
427
439
  isDemo: false
428
440
  };
@@ -462,12 +474,26 @@ export class TokenTracker {
462
474
  this.largestStepTokens = 0;
463
475
  }
464
476
 
477
+ resetSession(): void {
478
+ this.sessionTokens = 0;
479
+ this.sessionCostUsd = 0;
480
+ this.taskTokens = 0;
481
+ this.taskCostUsd = 0;
482
+ this.largestStepTokens = 0;
483
+ }
484
+
485
+ reset(): void {
486
+ this.resetSession();
487
+ }
488
+
465
489
  settle(extra: Record<string, unknown>, daily: DailyUsage, cumulative: CumulativeUsage): SettledUsage {
466
490
  return {
467
491
  usedTokens: daily.totalTokens,
468
492
  dailyTokens: daily.totalTokens,
469
493
  dailyCostUsd: daily.totalCostUsd || 0,
470
494
  dailyLimit: Number(this.budget && this.budget.maxTokensPerDay) || 0,
495
+ sessionTokens: this.sessionTokens || this.taskTokens || 0,
496
+ sessionCostUsd: this.sessionCostUsd || this.taskCostUsd || 0,
471
497
  taskTokens: this.taskTokens,
472
498
  taskCostUsd: this.taskCostUsd,
473
499
  taskLimit: Number(this.budget && this.budget.maxTokensPerTask) || 0,
@@ -511,10 +537,12 @@ export class TokenTracker {
511
537
  const freshStep = freshInput + cTokens;
512
538
 
513
539
  this.taskTokens += freshStep;
540
+ this.sessionTokens = (this.sessionTokens || 0) + freshStep;
514
541
  this.largestStepTokens = Math.max(this.largestStepTokens || 0, freshStep);
515
542
 
516
543
  const cost = this.calculateCost(promptTokens, completionTokens, usageDetail);
517
544
  this.taskCostUsd += cost;
545
+ this.sessionCostUsd = (this.sessionCostUsd || 0) + cost;
518
546
 
519
547
  const { daily, cumulative } = await withUsageLock(async () => {
520
548
  const cumulative = await this.getCumulativeUsage();
@@ -324,7 +324,11 @@ export class ChatRenderer {
324
324
  this.rowSink = previousSink;
325
325
  this.forcedWidth = previousWidth;
326
326
  }
327
- return sessionRows(sink, width).rows;
327
+ const maxAvailable = this.transcript?.surface?.composeAvailableWidth
328
+ ? this.transcript.surface.composeAvailableWidth()
329
+ : width;
330
+ const availableWidth = Math.min(width, maxAvailable);
331
+ return sessionRows(sink, availableWidth).rows;
328
332
  }
329
333
 
330
334
  /**
@@ -509,7 +513,7 @@ export class ChatRenderer {
509
513
  const blockWidth = Math.max(8, width);
510
514
  const innerWidth = Math.max(8, blockWidth - visibleWidth(GLYPHS.barHeavy || GLYPHS.bar) - 1);
511
515
  const rows = barBlock(
512
- wrapBlock(safeDisplay(text), innerWidth),
516
+ wrapBlock(safeDisplay(text), innerWidth, { hang: 0 }),
513
517
  { width: blockWidth, role: 'user', filled: true, surface: 'surfaceHi' }
514
518
  );
515
519
  this.write();
@@ -106,6 +106,9 @@ function rank(items, query, limit = 50, focusDir = null) {
106
106
  }
107
107
 
108
108
  if (value >= 0) {
109
+ if (item.isCommand) {
110
+ value += 2000;
111
+ }
109
112
  if (focusPrefix && val.toLowerCase().startsWith(focusPrefix)) {
110
113
  value += 3000;
111
114
  }
@@ -131,7 +134,7 @@ const ARGUMENT_LIMIT = 500;
131
134
  // `/` commands
132
135
  // ---------------------------------------------------------------------------
133
136
 
134
- function commandItems() {
137
+ function commandItems(query = '') {
135
138
  // Suggested/high-frequency commands prioritized at the top on a bare '/' (OpenCode architecture)
136
139
  const SUGGESTED_ORDER = ['model', 'sessions', 'new', 'clear', 'continuum', 'help', 'status', 'setup', 'mcp'];
137
140
  const allCommands = listCommands('terminal');
@@ -157,27 +160,43 @@ function commandItems() {
157
160
  match: command.name,
158
161
  aliases: Array.isArray(command.aliases) ? command.aliases.filter(isTerminalSafe) : [],
159
162
  label: primaryLabel,
160
- description: sanitize(command.description || '')
163
+ description: sanitize(command.description || ''),
164
+ isCommand: true
161
165
  });
162
166
  }
163
167
  }
164
168
 
165
- // Skills answer to the slash menu directly, the way claude-code surfaces a
166
- // skill as a command you simply type. `/docker` finds the Docker skill
167
- // without the user knowing it lives under `devops`, or that `/skills` exists
168
- // at all — which is the whole difficulty with a hundred-entry library.
169
- const skills = listSkillsForCompletion().map((skill) => ({
170
- value: `/skills ${skill.domain}/${skill.id}`,
171
- match: `${skill.id} ${skill.domain}`,
172
- label: `/${skill.id}`,
173
- description: sanitize(skill.description || '')
174
- }));
169
+ // On a bare '/' (no query entered), keep the menu purely focused on genuine slash commands.
170
+ // Skills belong in `/skills` and must never pollute the top-level palette.
171
+ if (!query) {
172
+ return commands;
173
+ }
174
+
175
+ // When a user explicitly searches for a skill keyword (e.g. `/docker`), offer matching skills,
176
+ // but commands always retain strict priority in ranking.
177
+ //
178
+ // Skills match only on a CONTIGUOUS piece of their own id, and only once the
179
+ // query is long enough to mean something. Loose subsequence matching over
180
+ // "id + domain" let `/p` and `/plu` pull 70+ unrelated skills into the
181
+ // command palette ("... 72 more"), burying the command being typed.
182
+ const needle = query.toLowerCase();
183
+ if (needle.length < SKILL_QUERY_MIN) return commands;
184
+ const skills = listSkillsForCompletion()
185
+ .filter((skill) => String(skill.id || '').toLowerCase().includes(needle))
186
+ .map((skill) => ({
187
+ value: `/skills ${skill.domain}/${skill.id}`,
188
+ match: skill.id,
189
+ label: `/${skill.id}`,
190
+ description: sanitize(skill.description || ''),
191
+ isCommand: false
192
+ }));
175
193
 
176
- // Commands first: on a bare `/` every entry scores 0, and a stable sort then
177
- // leaves the real commands above the library.
178
194
  return commands.concat(skills);
179
195
  }
180
196
 
197
+ // Below this many characters a query is still a command prefix, not a skill search.
198
+ const SKILL_QUERY_MIN = 3;
199
+
181
200
  /**
182
201
  * A command's own argument suggestions.
183
202
  *
@@ -401,7 +420,7 @@ export function suggest(text, cursor, options = {}) {
401
420
  if (!trigger) return null;
402
421
 
403
422
  if (trigger.kind === 'command') {
404
- const items = rank(commandItems(), trigger.query);
423
+ const items = rank(commandItems(trigger.query), trigger.query);
405
424
  if (items.length === 0) return null;
406
425
  return { ...trigger, items, total: items.total };
407
426
  }
@@ -130,6 +130,11 @@ export function handlePromptEscape(prompt, formatInterruptedRow) {
130
130
  prompt.scheduleDraw();
131
131
  return;
132
132
  }
133
+ if (prompt.usageCard) {
134
+ prompt.usageCard = null;
135
+ prompt.scheduleDraw();
136
+ return;
137
+ }
133
138
  if (prompt.completion) {
134
139
  prompt.completion = null;
135
140
  if (prompt.editor.getText().startsWith('/')) {
@@ -183,6 +183,11 @@ export function handlePromptEscape(
183
183
  prompt.scheduleDraw();
184
184
  return;
185
185
  }
186
+ if ((prompt as any).usageCard) {
187
+ (prompt as any).usageCard = null;
188
+ prompt.scheduleDraw();
189
+ return;
190
+ }
186
191
  if (prompt.completion) {
187
192
  prompt.completion = null;
188
193
  if (prompt.editor.getText().startsWith('/')) {
package/src/tui/layout.js CHANGED
@@ -15,7 +15,7 @@ export function centerRows(rows, columns) {
15
15
  /** Conversation content starts at the left margin while Home stays centered. */
16
16
  export function sessionRows(rows, columns) {
17
17
  const available = Number.isFinite(columns) ? Math.max(1, Math.floor(columns)) : 80;
18
- const inset = Math.min(2, Math.max(0, available - 2));
18
+ const inset = Math.min(3, Math.max(0, available - 3));
19
19
  const prefix = ' '.repeat(inset);
20
20
  return {
21
21
  rows: rows.map(row => row ? prefix + truncate(row, Math.max(1, available - inset - 1), '') : ''),
package/src/tui/layout.ts CHANGED
@@ -18,7 +18,7 @@ export function centerRows(rows: string[], columns: number): { rows: string[]; i
18
18
  /** Conversation content starts at the left margin while Home stays centered. */
19
19
  export function sessionRows(rows: string[], columns: number): { rows: string[]; inset: number } {
20
20
  const available = Number.isFinite(columns) ? Math.max(1, Math.floor(columns)) : 80;
21
- const inset = Math.min(2, Math.max(0, available - 2));
21
+ const inset = Math.min(3, Math.max(0, available - 3));
22
22
  const prefix = ' '.repeat(inset);
23
23
  return {
24
24
  rows: rows.map(row => row ? prefix + truncate(row, Math.max(1, available - inset - 1), '') : ''),
@@ -0,0 +1,323 @@
1
+ // Sovereign Interactive Cold Observer Setup & Picker — modal dialog for configuring Cold Observer.
2
+ // Authored in Strict TypeScript for Causyne Agent.
3
+ // Source-available under BUSL-1.1.
4
+ // @ts-expect-error untyped local TUI dialogs
5
+ import { SelectLayer, InputLayer, TextLayer } from './dialogs.js';
6
+ // @ts-expect-error untyped local TUI theme
7
+ import { paint, bold, dim, GLYPHS } from './theme.js';
8
+ import { coldObserver } from '../observer/coldObserver.js';
9
+ class DetailTextLayer extends TextLayer {
10
+ onDismiss;
11
+ dismissed = false;
12
+ constructor(options) {
13
+ super(options);
14
+ this.onDismiss = options.onDismiss;
15
+ }
16
+ answer() {
17
+ if (this.dismissed)
18
+ return;
19
+ this.dismissed = true;
20
+ if (this.onDismiss)
21
+ this.onDismiss();
22
+ }
23
+ }
24
+ /**
25
+ * Build interactive menu items reflecting live Cold Observer configuration and state.
26
+ */
27
+ export function buildObserverPickerItems(config, auditCount, vetoCount) {
28
+ const items = [];
29
+ // 1. Toggle Protection
30
+ const activeStatus = config.enabled ? '[Active ●]' : '[Disabled ○]';
31
+ const toggleAction = config.enabled ? 'Click to Turn OFF' : 'Click to Turn ON';
32
+ items.push({
33
+ id: 'toggle',
34
+ label: `${activeStatus} — ${toggleAction}`,
35
+ category: 'Protection Status',
36
+ description: config.enabled
37
+ ? 'Cold Observer is actively verifying tool mutations and completion claims'
38
+ : 'Cold Observer is DISABLED — safety invariants and claim checks are disabled',
39
+ searchText: 'toggle enable disable active status turn off turn on switch protection',
40
+ value: { action: 'toggle' }
41
+ });
42
+ // 2. Review Mode
43
+ const modeLabel = config.mode === 'advisory' ? 'ADVISORY (Neural loopback)' : 'DETERMINISTIC (Fast rules)';
44
+ items.push({
45
+ id: 'mode',
46
+ label: `Review Mode: ${modeLabel}`,
47
+ category: 'Configuration',
48
+ description: config.mode === 'advisory'
49
+ ? 'Uses local neural loopback endpoint to verify task claims'
50
+ : 'Uses fast, zero-latency deterministic command & outcome analysis',
51
+ searchText: 'mode deterministic advisory neural rules review verify',
52
+ value: { action: 'mode' }
53
+ });
54
+ // 3. Strictness
55
+ const strictnessLabel = config.strictness.toUpperCase();
56
+ items.push({
57
+ id: 'strictness',
58
+ label: `Strictness: ${strictnessLabel}`,
59
+ category: 'Configuration',
60
+ description: config.strictness === 'strict'
61
+ ? 'Strict: requires explicit test/build confirmation before declaring complete'
62
+ : config.strictness === 'relaxed'
63
+ ? 'Relaxed: minimal false vetoes; allows standard developer autonomy'
64
+ : 'Standard: balanced oversight without false vetoes (recommended)',
65
+ searchText: 'strictness standard strict relaxed level threshold safety',
66
+ value: { action: 'strictness' }
67
+ });
68
+ // 4. Advisory Loopback Endpoint
69
+ const endpointDisplay = config.endpoint || '(not configured)';
70
+ items.push({
71
+ id: 'endpoint',
72
+ label: `Advisory Endpoint: ${endpointDisplay}`,
73
+ category: 'Advisory Endpoint',
74
+ description: 'Local loopback HTTP endpoint for neural verification (e.g. http://localhost:11434/v1 or none)',
75
+ searchText: 'endpoint url loopback ollama localhost http address advisory',
76
+ value: { action: 'endpoint' }
77
+ });
78
+ // 5. Advisory Model Name
79
+ const modelDisplay = config.model || '(unset)';
80
+ items.push({
81
+ id: 'model',
82
+ label: `Advisory Model: ${modelDisplay}`,
83
+ category: 'Advisory Endpoint',
84
+ description: 'Name of the local neural model (e.g. tiny, qwen, llama3, or none)',
85
+ searchText: 'model name llama qwen tiny advisory neural',
86
+ value: { action: 'model' }
87
+ });
88
+ // 6. Test Advisory Endpoint
89
+ items.push({
90
+ id: 'test',
91
+ label: 'Test Advisory Endpoint (Health Probe)',
92
+ category: 'Diagnostics',
93
+ description: 'Probe loopback advisory endpoint and report latency and model readiness',
94
+ searchText: 'test health check ping probe latency verify endpoint',
95
+ value: { action: 'test' }
96
+ });
97
+ // 7. Audit History
98
+ items.push({
99
+ id: 'audit',
100
+ label: `Audit History (${auditCount} events recorded, ${vetoCount} vetoes)`,
101
+ category: 'Diagnostics',
102
+ description: 'Inspect recent mutation reviews and safety veto records',
103
+ searchText: 'audit history logs events vetoes inspect recent records',
104
+ value: { action: 'audit' }
105
+ });
106
+ // 8. Reset to Defaults
107
+ items.push({
108
+ id: 'reset',
109
+ label: 'Reset Configuration to Defaults',
110
+ category: 'Actions',
111
+ description: 'Restore enabled state, deterministic mode, standard strictness, and cleared endpoint',
112
+ searchText: 'reset default restore factory clear settings',
113
+ value: { action: 'reset' }
114
+ });
115
+ return items;
116
+ }
117
+ /**
118
+ * Launch the Interactive Cold Observer Setup Modal in the live prompt.
119
+ */
120
+ export function runInteractiveObserverPicker(prompt) {
121
+ return new Promise((resolve) => {
122
+ let settled = false;
123
+ const finish = (msg) => {
124
+ if (settled)
125
+ return;
126
+ settled = true;
127
+ resolve(msg);
128
+ };
129
+ function openMenu() {
130
+ const cfg = coldObserver.getConfig();
131
+ const audits = coldObserver.getAuditHistory();
132
+ const vetoes = audits.filter((a) => a.veto).length;
133
+ const items = buildObserverPickerItems(cfg, audits.length, vetoes);
134
+ const statusTag = cfg.enabled ? 'ACTIVE' : 'DISABLED';
135
+ const selectLayer = new SelectLayer({
136
+ title: `Cold Observer Setup (${statusTag} · ${cfg.mode.toUpperCase()})`,
137
+ placeholder: 'Search observer settings...',
138
+ emptyText: 'No matching observer settings found.',
139
+ items,
140
+ width: 76,
141
+ height: 20,
142
+ footer: `↑↓ choose ${GLYPHS.dot} enter toggle/edit ${GLYPHS.dot} esc finish`,
143
+ onPick: (picked) => {
144
+ if (!picked) {
145
+ prompt.closeLayer();
146
+ const currentCfg = coldObserver.getConfig();
147
+ finish(`Cold Observer is ${currentCfg.enabled ? 'ACTIVE' : 'DISABLED'} (${currentCfg.mode}, ${currentCfg.strictness}).`);
148
+ return;
149
+ }
150
+ const action = picked.value.action;
151
+ // 1. Toggle Protection (Synchronous in-place toggle with visual confirmation)
152
+ if (action === 'toggle') {
153
+ const current = coldObserver.getConfig();
154
+ const newEnabled = !current.enabled;
155
+ coldObserver.updateConfig({ enabled: newEnabled });
156
+ prompt.notice = `Cold Observer is now ${newEnabled ? 'ACTIVE (Enabled)' : 'DISABLED (Inactive)'}`;
157
+ refreshLayer();
158
+ return 'keep';
159
+ }
160
+ // 2. Mode Toggle
161
+ if (action === 'mode') {
162
+ const current = coldObserver.getConfig();
163
+ const nextMode = current.mode === 'deterministic' ? 'advisory' : 'deterministic';
164
+ coldObserver.updateConfig({ mode: nextMode });
165
+ prompt.notice = `Cold Observer mode set to "${nextMode.toUpperCase()}"`;
166
+ refreshLayer();
167
+ return 'keep';
168
+ }
169
+ // 3. Strictness Cycle
170
+ if (action === 'strictness') {
171
+ const current = coldObserver.getConfig();
172
+ let nextStrictness = 'standard';
173
+ if (current.strictness === 'standard')
174
+ nextStrictness = 'strict';
175
+ else if (current.strictness === 'strict')
176
+ nextStrictness = 'relaxed';
177
+ else
178
+ nextStrictness = 'standard';
179
+ coldObserver.updateConfig({ strictness: nextStrictness });
180
+ prompt.notice = `Cold Observer strictness set to "${nextStrictness}"`;
181
+ refreshLayer();
182
+ return 'keep';
183
+ }
184
+ // 4. Advisory Endpoint Input
185
+ if (action === 'endpoint') {
186
+ const current = coldObserver.getConfig();
187
+ prompt.closeLayer();
188
+ prompt.openLayer(new InputLayer({
189
+ title: 'Advisory Loopback Endpoint',
190
+ placeholder: 'http://localhost:11434/v1 (or "none" to clear)',
191
+ value: current.endpoint,
192
+ lines: [
193
+ 'Enter local loopback endpoint URL for advisory neural verification.',
194
+ 'Only loopback URLs (localhost, 127.0.0.1) are accepted for security.',
195
+ 'Type "none" to clear the endpoint.'
196
+ ],
197
+ onSubmit: (val) => {
198
+ const trimmed = val.trim();
199
+ try {
200
+ coldObserver.updateConfig({ endpoint: trimmed === 'none' ? '' : trimmed });
201
+ prompt.notice = coldObserver.getConfig().endpoint
202
+ ? `Advisory endpoint set to ${coldObserver.getConfig().endpoint}`
203
+ : 'Advisory endpoint cleared';
204
+ }
205
+ catch (err) {
206
+ prompt.notice = err instanceof Error ? err.message : 'Invalid loopback endpoint';
207
+ }
208
+ openMenu();
209
+ },
210
+ onCancel: () => {
211
+ openMenu();
212
+ }
213
+ }));
214
+ return;
215
+ }
216
+ // 5. Advisory Model Input
217
+ if (action === 'model') {
218
+ const current = coldObserver.getConfig();
219
+ prompt.closeLayer();
220
+ prompt.openLayer(new InputLayer({
221
+ title: 'Advisory Model Name',
222
+ placeholder: 'model name (e.g. tiny, qwen2.5-coder) or "none"',
223
+ value: current.model,
224
+ lines: [
225
+ 'Enter local advisory model name served at the loopback endpoint.',
226
+ 'Type "none" to clear the model name.'
227
+ ],
228
+ onSubmit: (val) => {
229
+ const trimmed = val.trim();
230
+ coldObserver.updateConfig({ model: trimmed === 'none' ? '' : trimmed });
231
+ prompt.notice = coldObserver.getConfig().model
232
+ ? `Advisory model set to ${coldObserver.getConfig().model}`
233
+ : 'Advisory model cleared';
234
+ openMenu();
235
+ },
236
+ onCancel: () => {
237
+ openMenu();
238
+ }
239
+ }));
240
+ return;
241
+ }
242
+ // 6. Test Advisory Endpoint
243
+ if (action === 'test') {
244
+ prompt.closeLayer();
245
+ void coldObserver.healthCheck().then((health) => {
246
+ const textLines = health.endpoint
247
+ ? [
248
+ `Endpoint: ${health.endpoint}`,
249
+ `Model: ${health.model || '(unset)'}`,
250
+ `Status: ${health.healthy ? 'HEALTHY' : 'UNREACHABLE'} (${health.latencyMs}ms latency)`,
251
+ `Detail: ${health.detail}`,
252
+ '',
253
+ 'Press Esc or Enter to return to Observer setup.'
254
+ ]
255
+ : [
256
+ 'No advisory endpoint configured.',
257
+ 'The deterministic observer requires no endpoint and remains fully active.',
258
+ '',
259
+ 'Press Esc or Enter to return to Observer setup.'
260
+ ];
261
+ prompt.openLayer(new DetailTextLayer({
262
+ title: 'Advisory Endpoint Health Check',
263
+ lines: textLines,
264
+ width: 70,
265
+ height: 12,
266
+ onDismiss: () => openMenu()
267
+ }));
268
+ });
269
+ return;
270
+ }
271
+ // 7. Audit History
272
+ if (action === 'audit') {
273
+ prompt.closeLayer();
274
+ const recentAudits = coldObserver.getAuditHistory();
275
+ const lines = recentAudits.length === 0
276
+ ? ['No Cold Observer audit records yet.', '', 'Press Esc or Enter to return to Observer setup.']
277
+ : recentAudits.slice(-12).map((a) => {
278
+ const time = new Date(a.timestamp).toLocaleTimeString();
279
+ const tag = a.type === 'mutation' ? `[mutation ${a.tool || ''}]` : '[verification]';
280
+ const score = typeof a.riskScore === 'number' ? `(${(a.riskScore * 100).toFixed(0)}% risk)` : '';
281
+ const veto = a.veto ? paint('danger', 'VETO') : paint('success', 'PASS');
282
+ return `${time} ${tag} ${veto} ${score} ${a.details}`;
283
+ });
284
+ prompt.openLayer(new DetailTextLayer({
285
+ title: `Cold Observer Audits (Last ${Math.min(12, recentAudits.length)})`,
286
+ lines,
287
+ width: 76,
288
+ height: 18,
289
+ onDismiss: () => openMenu()
290
+ }));
291
+ return;
292
+ }
293
+ // 8. Reset Defaults
294
+ if (action === 'reset') {
295
+ coldObserver.updateConfig({
296
+ enabled: true,
297
+ mode: 'deterministic',
298
+ endpoint: '',
299
+ model: '',
300
+ timeoutMs: 800,
301
+ strictness: 'standard'
302
+ });
303
+ prompt.notice = 'Cold Observer reset to default settings';
304
+ refreshLayer();
305
+ return 'keep';
306
+ }
307
+ return;
308
+ }
309
+ });
310
+ function refreshLayer() {
311
+ const updatedCfg = coldObserver.getConfig();
312
+ const updatedAudits = coldObserver.getAuditHistory();
313
+ const updatedVetoes = updatedAudits.filter((a) => a.veto).length;
314
+ const newItems = buildObserverPickerItems(updatedCfg, updatedAudits.length, updatedVetoes);
315
+ selectLayer.title = `Cold Observer Setup (${updatedCfg.enabled ? 'ACTIVE' : 'DISABLED'} · ${updatedCfg.mode.toUpperCase()})`;
316
+ selectLayer.list.setItems(newItems);
317
+ prompt.draw();
318
+ }
319
+ prompt.openLayer(selectLayer);
320
+ }
321
+ openMenu();
322
+ });
323
+ }