@build-astron-co/nimbus 0.2.0
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 +21 -0
- package/README.md +628 -0
- package/bin/nimbus +38 -0
- package/package.json +80 -0
- package/src/__tests__/app.test.ts +76 -0
- package/src/__tests__/audit.test.ts +877 -0
- package/src/__tests__/circuit-breaker.test.ts +116 -0
- package/src/__tests__/cli-run.test.ts +115 -0
- package/src/__tests__/context-manager.test.ts +502 -0
- package/src/__tests__/context.test.ts +242 -0
- package/src/__tests__/enterprise.test.ts +401 -0
- package/src/__tests__/generator.test.ts +433 -0
- package/src/__tests__/hooks.test.ts +582 -0
- package/src/__tests__/init.test.ts +436 -0
- package/src/__tests__/intent-parser.test.ts +229 -0
- package/src/__tests__/llm-router.test.ts +209 -0
- package/src/__tests__/lsp.test.ts +293 -0
- package/src/__tests__/modes.test.ts +336 -0
- package/src/__tests__/permissions.test.ts +338 -0
- package/src/__tests__/serve.test.ts +275 -0
- package/src/__tests__/sessions.test.ts +227 -0
- package/src/__tests__/sharing.test.ts +288 -0
- package/src/__tests__/snapshots.test.ts +581 -0
- package/src/__tests__/state-db.test.ts +334 -0
- package/src/__tests__/stream-with-tools.test.ts +732 -0
- package/src/__tests__/subagents.test.ts +176 -0
- package/src/__tests__/system-prompt.test.ts +169 -0
- package/src/__tests__/tool-converter.test.ts +256 -0
- package/src/__tests__/tool-schemas.test.ts +397 -0
- package/src/__tests__/tools.test.ts +143 -0
- package/src/__tests__/version.test.ts +49 -0
- package/src/agent/compaction-agent.ts +227 -0
- package/src/agent/context-manager.ts +435 -0
- package/src/agent/context.ts +427 -0
- package/src/agent/deploy-preview.ts +426 -0
- package/src/agent/index.ts +68 -0
- package/src/agent/loop.ts +717 -0
- package/src/agent/modes.ts +429 -0
- package/src/agent/permissions.ts +466 -0
- package/src/agent/subagents/base.ts +116 -0
- package/src/agent/subagents/cost.ts +51 -0
- package/src/agent/subagents/explore.ts +42 -0
- package/src/agent/subagents/general.ts +54 -0
- package/src/agent/subagents/index.ts +102 -0
- package/src/agent/subagents/infra.ts +59 -0
- package/src/agent/subagents/security.ts +69 -0
- package/src/agent/system-prompt.ts +436 -0
- package/src/app.ts +122 -0
- package/src/audit/activity-log.ts +290 -0
- package/src/audit/compliance-checker.ts +540 -0
- package/src/audit/cost-tracker.ts +318 -0
- package/src/audit/index.ts +23 -0
- package/src/audit/security-scanner.ts +596 -0
- package/src/auth/guard.ts +75 -0
- package/src/auth/index.ts +56 -0
- package/src/auth/oauth.ts +455 -0
- package/src/auth/providers.ts +470 -0
- package/src/auth/sso.ts +113 -0
- package/src/auth/store.ts +505 -0
- package/src/auth/types.ts +187 -0
- package/src/build.ts +141 -0
- package/src/cli/index.ts +16 -0
- package/src/cli/init.ts +854 -0
- package/src/cli/openapi-spec.ts +356 -0
- package/src/cli/run.ts +237 -0
- package/src/cli/serve-auth.ts +80 -0
- package/src/cli/serve.ts +462 -0
- package/src/cli/web.ts +67 -0
- package/src/cli.ts +1417 -0
- package/src/clients/core-engine-client.ts +227 -0
- package/src/clients/enterprise-client.ts +334 -0
- package/src/clients/generator-client.ts +351 -0
- package/src/clients/git-client.ts +627 -0
- package/src/clients/github-client.ts +410 -0
- package/src/clients/helm-client.ts +504 -0
- package/src/clients/index.ts +80 -0
- package/src/clients/k8s-client.ts +497 -0
- package/src/clients/llm-client.ts +161 -0
- package/src/clients/rest-client.ts +130 -0
- package/src/clients/service-discovery.ts +33 -0
- package/src/clients/terraform-client.ts +482 -0
- package/src/clients/tools-client.ts +1843 -0
- package/src/clients/ws-client.ts +115 -0
- package/src/commands/analyze/index.ts +352 -0
- package/src/commands/apply/helm.ts +473 -0
- package/src/commands/apply/index.ts +213 -0
- package/src/commands/apply/k8s.ts +454 -0
- package/src/commands/apply/terraform.ts +582 -0
- package/src/commands/ask.ts +167 -0
- package/src/commands/audit/index.ts +238 -0
- package/src/commands/auth-cloud.ts +294 -0
- package/src/commands/auth-list.ts +134 -0
- package/src/commands/auth-profile.ts +121 -0
- package/src/commands/auth-status.ts +141 -0
- package/src/commands/aws/ec2.ts +501 -0
- package/src/commands/aws/iam.ts +397 -0
- package/src/commands/aws/index.ts +133 -0
- package/src/commands/aws/lambda.ts +396 -0
- package/src/commands/aws/rds.ts +439 -0
- package/src/commands/aws/s3.ts +439 -0
- package/src/commands/aws/vpc.ts +393 -0
- package/src/commands/aws-discover.ts +649 -0
- package/src/commands/aws-terraform.ts +805 -0
- package/src/commands/azure/aks.ts +376 -0
- package/src/commands/azure/functions.ts +253 -0
- package/src/commands/azure/index.ts +116 -0
- package/src/commands/azure/storage.ts +478 -0
- package/src/commands/azure/vm.ts +355 -0
- package/src/commands/billing/index.ts +256 -0
- package/src/commands/chat.ts +314 -0
- package/src/commands/config.ts +346 -0
- package/src/commands/cost/cloud-cost-estimator.ts +266 -0
- package/src/commands/cost/estimator.ts +79 -0
- package/src/commands/cost/index.ts +594 -0
- package/src/commands/cost/parsers/terraform.ts +273 -0
- package/src/commands/cost/parsers/types.ts +25 -0
- package/src/commands/cost/pricing/aws.ts +544 -0
- package/src/commands/cost/pricing/azure.ts +499 -0
- package/src/commands/cost/pricing/gcp.ts +396 -0
- package/src/commands/cost/pricing/index.ts +40 -0
- package/src/commands/demo.ts +250 -0
- package/src/commands/doctor.ts +794 -0
- package/src/commands/drift/index.ts +439 -0
- package/src/commands/explain.ts +277 -0
- package/src/commands/feedback.ts +389 -0
- package/src/commands/fix.ts +324 -0
- package/src/commands/fs/index.ts +402 -0
- package/src/commands/gcp/compute.ts +325 -0
- package/src/commands/gcp/functions.ts +271 -0
- package/src/commands/gcp/gke.ts +438 -0
- package/src/commands/gcp/iam.ts +344 -0
- package/src/commands/gcp/index.ts +129 -0
- package/src/commands/gcp/storage.ts +284 -0
- package/src/commands/generate-helm.ts +1249 -0
- package/src/commands/generate-k8s.ts +1560 -0
- package/src/commands/generate-terraform.ts +1460 -0
- package/src/commands/gh/index.ts +863 -0
- package/src/commands/git/index.ts +1343 -0
- package/src/commands/helm/index.ts +1126 -0
- package/src/commands/help.ts +539 -0
- package/src/commands/history.ts +142 -0
- package/src/commands/import.ts +868 -0
- package/src/commands/index.ts +367 -0
- package/src/commands/init.ts +1046 -0
- package/src/commands/k8s/index.ts +1137 -0
- package/src/commands/login.ts +631 -0
- package/src/commands/logout.ts +83 -0
- package/src/commands/onboarding.ts +228 -0
- package/src/commands/plan/display.ts +279 -0
- package/src/commands/plan/index.ts +599 -0
- package/src/commands/preview.ts +452 -0
- package/src/commands/questionnaire.ts +1270 -0
- package/src/commands/resume.ts +55 -0
- package/src/commands/team/index.ts +346 -0
- package/src/commands/template.ts +232 -0
- package/src/commands/tf/index.ts +1034 -0
- package/src/commands/upgrade.ts +550 -0
- package/src/commands/usage/index.ts +134 -0
- package/src/commands/version.ts +170 -0
- package/src/compat/index.ts +2 -0
- package/src/compat/runtime.ts +12 -0
- package/src/compat/sqlite.ts +107 -0
- package/src/config/index.ts +17 -0
- package/src/config/manager.ts +530 -0
- package/src/config/safety-policy.ts +358 -0
- package/src/config/schema.ts +125 -0
- package/src/config/types.ts +527 -0
- package/src/context/context-db.ts +199 -0
- package/src/demo/index.ts +349 -0
- package/src/demo/scenarios/full-journey.ts +229 -0
- package/src/demo/scenarios/getting-started.ts +127 -0
- package/src/demo/scenarios/helm-release.ts +341 -0
- package/src/demo/scenarios/k8s-deployment.ts +194 -0
- package/src/demo/scenarios/terraform-vpc.ts +170 -0
- package/src/demo/types.ts +92 -0
- package/src/engine/cost-estimator.ts +438 -0
- package/src/engine/diagram-generator.ts +256 -0
- package/src/engine/drift-detector.ts +902 -0
- package/src/engine/executor.ts +1035 -0
- package/src/engine/index.ts +76 -0
- package/src/engine/orchestrator.ts +636 -0
- package/src/engine/planner.ts +720 -0
- package/src/engine/safety.ts +743 -0
- package/src/engine/verifier.ts +770 -0
- package/src/enterprise/audit.ts +348 -0
- package/src/enterprise/auth.ts +270 -0
- package/src/enterprise/billing.ts +822 -0
- package/src/enterprise/index.ts +17 -0
- package/src/enterprise/teams.ts +443 -0
- package/src/generator/best-practices.ts +1608 -0
- package/src/generator/helm.ts +630 -0
- package/src/generator/index.ts +37 -0
- package/src/generator/intent-parser.ts +514 -0
- package/src/generator/kubernetes.ts +976 -0
- package/src/generator/terraform.ts +1867 -0
- package/src/history/index.ts +8 -0
- package/src/history/manager.ts +322 -0
- package/src/history/types.ts +34 -0
- package/src/hooks/config.ts +432 -0
- package/src/hooks/engine.ts +391 -0
- package/src/hooks/index.ts +4 -0
- package/src/llm/auth-bridge.ts +198 -0
- package/src/llm/circuit-breaker.ts +140 -0
- package/src/llm/config-loader.ts +201 -0
- package/src/llm/cost-calculator.ts +171 -0
- package/src/llm/index.ts +8 -0
- package/src/llm/model-aliases.ts +115 -0
- package/src/llm/provider-registry.ts +63 -0
- package/src/llm/providers/anthropic.ts +433 -0
- package/src/llm/providers/bedrock.ts +477 -0
- package/src/llm/providers/google.ts +405 -0
- package/src/llm/providers/ollama.ts +767 -0
- package/src/llm/providers/openai-compatible.ts +340 -0
- package/src/llm/providers/openai.ts +328 -0
- package/src/llm/providers/openrouter.ts +338 -0
- package/src/llm/router.ts +1035 -0
- package/src/llm/types.ts +232 -0
- package/src/lsp/client.ts +298 -0
- package/src/lsp/languages.ts +116 -0
- package/src/lsp/manager.ts +278 -0
- package/src/mcp/client.ts +402 -0
- package/src/mcp/index.ts +5 -0
- package/src/mcp/manager.ts +133 -0
- package/src/nimbus.ts +214 -0
- package/src/plugins/index.ts +27 -0
- package/src/plugins/loader.ts +334 -0
- package/src/plugins/manager.ts +376 -0
- package/src/plugins/types.ts +284 -0
- package/src/scanners/cicd-scanner.ts +258 -0
- package/src/scanners/cloud-scanner.ts +466 -0
- package/src/scanners/framework-scanner.ts +469 -0
- package/src/scanners/iac-scanner.ts +388 -0
- package/src/scanners/index.ts +539 -0
- package/src/scanners/language-scanner.ts +276 -0
- package/src/scanners/package-manager-scanner.ts +277 -0
- package/src/scanners/types.ts +172 -0
- package/src/sessions/manager.ts +365 -0
- package/src/sessions/types.ts +44 -0
- package/src/sharing/sync.ts +296 -0
- package/src/sharing/viewer.ts +97 -0
- package/src/snapshots/index.ts +2 -0
- package/src/snapshots/manager.ts +530 -0
- package/src/state/artifacts.ts +147 -0
- package/src/state/audit.ts +137 -0
- package/src/state/billing.ts +240 -0
- package/src/state/checkpoints.ts +117 -0
- package/src/state/config.ts +67 -0
- package/src/state/conversations.ts +14 -0
- package/src/state/credentials.ts +154 -0
- package/src/state/db.ts +58 -0
- package/src/state/index.ts +26 -0
- package/src/state/messages.ts +115 -0
- package/src/state/projects.ts +123 -0
- package/src/state/schema.ts +236 -0
- package/src/state/sessions.ts +147 -0
- package/src/state/teams.ts +200 -0
- package/src/telemetry.ts +108 -0
- package/src/tools/aws-ops.ts +952 -0
- package/src/tools/azure-ops.ts +579 -0
- package/src/tools/file-ops.ts +593 -0
- package/src/tools/gcp-ops.ts +625 -0
- package/src/tools/git-ops.ts +773 -0
- package/src/tools/github-ops.ts +799 -0
- package/src/tools/helm-ops.ts +943 -0
- package/src/tools/index.ts +17 -0
- package/src/tools/k8s-ops.ts +819 -0
- package/src/tools/schemas/converter.ts +184 -0
- package/src/tools/schemas/devops.ts +612 -0
- package/src/tools/schemas/index.ts +73 -0
- package/src/tools/schemas/standard.ts +1144 -0
- package/src/tools/schemas/types.ts +705 -0
- package/src/tools/terraform-ops.ts +862 -0
- package/src/types/ambient.d.ts +193 -0
- package/src/types/config.ts +83 -0
- package/src/types/drift.ts +116 -0
- package/src/types/enterprise.ts +335 -0
- package/src/types/index.ts +20 -0
- package/src/types/plan.ts +44 -0
- package/src/types/request.ts +65 -0
- package/src/types/response.ts +54 -0
- package/src/types/service.ts +51 -0
- package/src/ui/App.tsx +997 -0
- package/src/ui/DeployPreview.tsx +169 -0
- package/src/ui/Header.tsx +68 -0
- package/src/ui/InputBox.tsx +350 -0
- package/src/ui/MessageList.tsx +585 -0
- package/src/ui/PermissionPrompt.tsx +151 -0
- package/src/ui/StatusBar.tsx +158 -0
- package/src/ui/ToolCallDisplay.tsx +409 -0
- package/src/ui/chat-ui.ts +853 -0
- package/src/ui/index.ts +33 -0
- package/src/ui/ink/index.ts +711 -0
- package/src/ui/streaming.ts +176 -0
- package/src/ui/types.ts +57 -0
- package/src/utils/analytics.ts +72 -0
- package/src/utils/cost-warning.ts +27 -0
- package/src/utils/env.ts +46 -0
- package/src/utils/errors.ts +69 -0
- package/src/utils/event-bus.ts +38 -0
- package/src/utils/index.ts +24 -0
- package/src/utils/logger.ts +171 -0
- package/src/utils/rate-limiter.ts +121 -0
- package/src/utils/service-auth.ts +49 -0
- package/src/utils/validation.ts +53 -0
- package/src/version.ts +4 -0
- package/src/watcher/index.ts +163 -0
- package/src/wizard/approval.ts +383 -0
- package/src/wizard/index.ts +25 -0
- package/src/wizard/prompts.ts +338 -0
- package/src/wizard/types.ts +171 -0
- package/src/wizard/ui.ts +556 -0
- package/src/wizard/wizard.ts +304 -0
- package/tsconfig.json +24 -0
|
@@ -0,0 +1,853 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Chat UI
|
|
3
|
+
*
|
|
4
|
+
* Interactive readline chat interface with full agentic tool-calling support.
|
|
5
|
+
* Uses runAgentLoop() to give users the same capabilities as the Ink TUI:
|
|
6
|
+
* file editing, bash execution, git operations, etc.
|
|
7
|
+
*
|
|
8
|
+
* This is the fallback UI when Ink TUI is not available (e.g. compiled binary).
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import * as readline from 'readline';
|
|
12
|
+
import * as fs from 'fs';
|
|
13
|
+
import * as path from 'path';
|
|
14
|
+
import { ui } from '../wizard/ui';
|
|
15
|
+
import { AuthStore } from '../auth/store';
|
|
16
|
+
import { getAppContext } from '../app';
|
|
17
|
+
import type { LLMRouter } from '../llm/router';
|
|
18
|
+
import type { LLMMessage } from '../llm/types';
|
|
19
|
+
import { runAgentLoop, type AgentLoopResult, type ToolCallInfo } from '../agent/loop';
|
|
20
|
+
import { defaultToolRegistry, type ToolResult, type ToolDefinition } from '../tools/schemas/types';
|
|
21
|
+
import { SnapshotManager } from '../snapshots/manager';
|
|
22
|
+
import { ContextManager } from '../agent/context-manager';
|
|
23
|
+
import { SessionManager } from '../sessions/manager';
|
|
24
|
+
import {
|
|
25
|
+
createPermissionState,
|
|
26
|
+
checkPermission as checkToolPermission,
|
|
27
|
+
approveForSession,
|
|
28
|
+
approveActionForSession,
|
|
29
|
+
type PermissionSessionState,
|
|
30
|
+
} from '../agent/permissions';
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Simple code block highlighter for terminal display.
|
|
34
|
+
* Wraps fenced code blocks (```...```) with dim formatting.
|
|
35
|
+
*/
|
|
36
|
+
function highlightCodeBlocks(text: string): string {
|
|
37
|
+
return text.replace(/```[\s\S]*?```/g, match => {
|
|
38
|
+
// Strip the fences and dim the content
|
|
39
|
+
const inner = match.replace(/^```\w*\n?/, '').replace(/\n?```$/, '');
|
|
40
|
+
return `\x1b[2m${inner}\x1b[0m`;
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Supported export formats for the /export command */
|
|
45
|
+
type ExportFormat = 'json' | 'markdown' | 'text';
|
|
46
|
+
|
|
47
|
+
export type PersonaTone = 'professional' | 'assistant' | 'expert';
|
|
48
|
+
|
|
49
|
+
/** Message shape used internally by ChatUI */
|
|
50
|
+
interface ChatMessage {
|
|
51
|
+
role: 'user' | 'assistant' | 'system';
|
|
52
|
+
content: string;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export interface ChatUIOptions {
|
|
56
|
+
/** LLM model to use */
|
|
57
|
+
model?: string;
|
|
58
|
+
/** Initial system prompt */
|
|
59
|
+
systemPrompt?: string;
|
|
60
|
+
/** Show token count after responses */
|
|
61
|
+
showTokenCount?: boolean;
|
|
62
|
+
/** Welcome message to display */
|
|
63
|
+
welcomeMessage?: string;
|
|
64
|
+
/** Active persona tone */
|
|
65
|
+
persona?: PersonaTone;
|
|
66
|
+
/** Resume a previous session by ID */
|
|
67
|
+
resumeSessionId?: string;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Summarize tool input for compact terminal display.
|
|
72
|
+
*/
|
|
73
|
+
function summarizeToolInput(toolName: string, input: unknown): string {
|
|
74
|
+
if (!input || typeof input !== 'object') {
|
|
75
|
+
return '';
|
|
76
|
+
}
|
|
77
|
+
const obj = input as Record<string, unknown>;
|
|
78
|
+
|
|
79
|
+
switch (toolName) {
|
|
80
|
+
case 'read_file':
|
|
81
|
+
case 'write_file':
|
|
82
|
+
case 'edit_file':
|
|
83
|
+
return obj.path ? String(obj.path) : '';
|
|
84
|
+
case 'multi_edit':
|
|
85
|
+
return obj.path ? String(obj.path) : '';
|
|
86
|
+
case 'bash':
|
|
87
|
+
return obj.command ? String(obj.command).substring(0, 80) : '';
|
|
88
|
+
case 'glob':
|
|
89
|
+
return obj.pattern ? String(obj.pattern) : '';
|
|
90
|
+
case 'grep':
|
|
91
|
+
return obj.pattern ? `"${String(obj.pattern)}"` : '';
|
|
92
|
+
case 'list_dir':
|
|
93
|
+
return obj.path ? String(obj.path) : '.';
|
|
94
|
+
case 'git':
|
|
95
|
+
return obj.action ? `${obj.action}${obj.args ? ` ${obj.args}` : ''}` : '';
|
|
96
|
+
case 'terraform':
|
|
97
|
+
case 'kubectl':
|
|
98
|
+
case 'helm':
|
|
99
|
+
return obj.action ? String(obj.action) : '';
|
|
100
|
+
default:
|
|
101
|
+
return '';
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* ChatUI provides an interactive terminal chat interface
|
|
107
|
+
* with full agentic tool-calling capabilities via runAgentLoop().
|
|
108
|
+
*/
|
|
109
|
+
export class ChatUI {
|
|
110
|
+
private options: ChatUIOptions;
|
|
111
|
+
private router: LLMRouter;
|
|
112
|
+
private snapshotManager: SnapshotManager;
|
|
113
|
+
private contextManager: ContextManager;
|
|
114
|
+
private sessionManager: SessionManager | null = null;
|
|
115
|
+
private sessionId: string | null = null;
|
|
116
|
+
private history: ChatMessage[] = [];
|
|
117
|
+
/** Conversation history in LLMMessage format for the agent loop. */
|
|
118
|
+
private agentHistory: LLMMessage[] = [];
|
|
119
|
+
private rl: readline.Interface | null = null;
|
|
120
|
+
private isProcessing: boolean = false;
|
|
121
|
+
private verboseOutput: boolean = false;
|
|
122
|
+
private abortController: AbortController = new AbortController();
|
|
123
|
+
private permissionState: PermissionSessionState = createPermissionState();
|
|
124
|
+
private currentMode: 'plan' | 'build' | 'deploy' = 'build';
|
|
125
|
+
|
|
126
|
+
constructor(options: ChatUIOptions = {}) {
|
|
127
|
+
this.options = options;
|
|
128
|
+
|
|
129
|
+
// Get the in-process LLM router from the app context
|
|
130
|
+
const ctx = getAppContext();
|
|
131
|
+
if (!ctx) {
|
|
132
|
+
throw new Error('App not initialised. Call initApp() before starting chat.');
|
|
133
|
+
}
|
|
134
|
+
this.router = ctx.router;
|
|
135
|
+
this.snapshotManager = new SnapshotManager({ projectDir: process.cwd() });
|
|
136
|
+
this.contextManager = new ContextManager();
|
|
137
|
+
|
|
138
|
+
// Create a session for conversation persistence
|
|
139
|
+
try {
|
|
140
|
+
this.sessionManager = SessionManager.getInstance();
|
|
141
|
+
const session = this.sessionManager.create({
|
|
142
|
+
name: `chat-${new Date().toISOString().slice(0, 16)}`,
|
|
143
|
+
mode: this.currentMode,
|
|
144
|
+
model: options.model,
|
|
145
|
+
cwd: process.cwd(),
|
|
146
|
+
});
|
|
147
|
+
this.sessionId = session.id;
|
|
148
|
+
} catch {
|
|
149
|
+
// Session persistence is non-critical
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// Add system prompt to history if provided
|
|
153
|
+
if (options.systemPrompt) {
|
|
154
|
+
this.history.push({
|
|
155
|
+
role: 'system',
|
|
156
|
+
content: options.systemPrompt,
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Start the interactive chat session
|
|
163
|
+
*/
|
|
164
|
+
async start(): Promise<void> {
|
|
165
|
+
// Display header
|
|
166
|
+
this.displayHeader();
|
|
167
|
+
|
|
168
|
+
// Create readline interface
|
|
169
|
+
this.rl = readline.createInterface({
|
|
170
|
+
input: process.stdin,
|
|
171
|
+
output: process.stdout,
|
|
172
|
+
terminal: true,
|
|
173
|
+
});
|
|
174
|
+
|
|
175
|
+
// Handle line input
|
|
176
|
+
this.rl.on('line', async input => {
|
|
177
|
+
await this.handleInput(input.trim());
|
|
178
|
+
});
|
|
179
|
+
|
|
180
|
+
// Handle close
|
|
181
|
+
this.rl.on('close', () => {
|
|
182
|
+
this.exit();
|
|
183
|
+
});
|
|
184
|
+
|
|
185
|
+
// Display prompt
|
|
186
|
+
this.displayPrompt();
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
private displayHeader(): void {
|
|
190
|
+
const authStore = new AuthStore();
|
|
191
|
+
const status = authStore.getStatus();
|
|
192
|
+
|
|
193
|
+
// Find the default provider's info
|
|
194
|
+
const defaultProviderInfo = status.providers.find(p => p.name === status.defaultProvider);
|
|
195
|
+
const modelInfo = this.options.model || defaultProviderInfo?.model || 'default';
|
|
196
|
+
const providerInfo = status.defaultProvider || 'unknown';
|
|
197
|
+
|
|
198
|
+
const content = [
|
|
199
|
+
ui.bold('Nimbus Agent'),
|
|
200
|
+
ui.dim(`Model: ${modelInfo} (${providerInfo}) | Mode: ${this.currentMode}`),
|
|
201
|
+
'',
|
|
202
|
+
ui.dim('AI agent with full tool access (file edit, bash, git, and more).'),
|
|
203
|
+
ui.dim('Type your message and press Enter. Press Ctrl+C to interrupt.'),
|
|
204
|
+
ui.dim(
|
|
205
|
+
'Commands: /help, /clear, /model, /models, /mode, /persona, /verbose, /history, /undo, /redo, /export, /exit'
|
|
206
|
+
),
|
|
207
|
+
];
|
|
208
|
+
|
|
209
|
+
ui.box({
|
|
210
|
+
content,
|
|
211
|
+
style: 'rounded',
|
|
212
|
+
borderColor: 'cyan',
|
|
213
|
+
padding: 1,
|
|
214
|
+
});
|
|
215
|
+
ui.newLine();
|
|
216
|
+
|
|
217
|
+
// Display welcome message if provided
|
|
218
|
+
if (this.options.welcomeMessage) {
|
|
219
|
+
ui.info(this.options.welcomeMessage);
|
|
220
|
+
ui.newLine();
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
private displayPrompt(): void {
|
|
225
|
+
if (this.rl && !this.isProcessing) {
|
|
226
|
+
process.stdout.write(ui.color('You: ', 'green'));
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
private async handleInput(input: string): Promise<void> {
|
|
231
|
+
// Block input while processing a response
|
|
232
|
+
if (this.isProcessing) {
|
|
233
|
+
ui.info('Please wait for the current response to finish.');
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
if (!input) {
|
|
238
|
+
this.displayPrompt();
|
|
239
|
+
return;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// Handle commands
|
|
243
|
+
if (input.startsWith('/')) {
|
|
244
|
+
await this.handleCommand(input);
|
|
245
|
+
return;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// Process chat message
|
|
249
|
+
await this.sendMessage(input);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
private async handleCommand(input: string): Promise<void> {
|
|
253
|
+
const parts = input.slice(1).split(' ');
|
|
254
|
+
const command = parts[0].toLowerCase();
|
|
255
|
+
const args = parts.slice(1);
|
|
256
|
+
|
|
257
|
+
switch (command) {
|
|
258
|
+
case 'help':
|
|
259
|
+
this.displayHelp();
|
|
260
|
+
break;
|
|
261
|
+
|
|
262
|
+
case 'clear':
|
|
263
|
+
this.clearHistory();
|
|
264
|
+
break;
|
|
265
|
+
|
|
266
|
+
case 'model':
|
|
267
|
+
if (args[0]) {
|
|
268
|
+
this.options.model = args[0];
|
|
269
|
+
ui.success(`Model changed to: ${args[0]}`);
|
|
270
|
+
} else {
|
|
271
|
+
ui.info(`Current model: ${this.options.model || 'default'}`);
|
|
272
|
+
}
|
|
273
|
+
break;
|
|
274
|
+
|
|
275
|
+
case 'persona':
|
|
276
|
+
this.handlePersonaCommand(args);
|
|
277
|
+
break;
|
|
278
|
+
|
|
279
|
+
case 'verbose':
|
|
280
|
+
this.verboseOutput = !this.verboseOutput;
|
|
281
|
+
ui.success(`Verbose output ${this.verboseOutput ? 'enabled' : 'disabled'}`);
|
|
282
|
+
break;
|
|
283
|
+
|
|
284
|
+
case 'history':
|
|
285
|
+
this.displayHistory();
|
|
286
|
+
break;
|
|
287
|
+
|
|
288
|
+
case 'export':
|
|
289
|
+
await this.handleExportCommand(args);
|
|
290
|
+
break;
|
|
291
|
+
|
|
292
|
+
case 'undo': {
|
|
293
|
+
const undoResult = await this.snapshotManager.undo();
|
|
294
|
+
if (undoResult.success) {
|
|
295
|
+
ui.success(undoResult.description);
|
|
296
|
+
} else {
|
|
297
|
+
ui.warning(undoResult.description);
|
|
298
|
+
}
|
|
299
|
+
break;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
case 'redo': {
|
|
303
|
+
const redoResult = await this.snapshotManager.redo();
|
|
304
|
+
if (redoResult.success) {
|
|
305
|
+
ui.success(redoResult.description);
|
|
306
|
+
} else {
|
|
307
|
+
ui.warning(redoResult.description);
|
|
308
|
+
}
|
|
309
|
+
break;
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
case 'mode': {
|
|
313
|
+
const validModes = ['plan', 'build', 'deploy'] as const;
|
|
314
|
+
const newMode = args[0]?.toLowerCase() as (typeof validModes)[number];
|
|
315
|
+
if (!newMode) {
|
|
316
|
+
ui.info(`Current mode: ${this.currentMode}`);
|
|
317
|
+
ui.print(ui.dim(' Available: plan, build, deploy'));
|
|
318
|
+
} else if (validModes.includes(newMode)) {
|
|
319
|
+
this.currentMode = newMode;
|
|
320
|
+
// Reset permission state to prevent privilege escalation
|
|
321
|
+
this.permissionState = createPermissionState();
|
|
322
|
+
ui.success(`Mode switched to: ${newMode}`);
|
|
323
|
+
} else {
|
|
324
|
+
ui.warning(`Invalid mode: ${newMode}`);
|
|
325
|
+
ui.print(ui.dim(' Available: plan, build, deploy'));
|
|
326
|
+
}
|
|
327
|
+
break;
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
case 'models': {
|
|
331
|
+
try {
|
|
332
|
+
const models = await this.router.getAvailableModels();
|
|
333
|
+
const entries = Object.entries(models);
|
|
334
|
+
if (entries.length === 0) {
|
|
335
|
+
ui.info('No providers configured.');
|
|
336
|
+
} else {
|
|
337
|
+
ui.section('Available Models');
|
|
338
|
+
for (const [provider, modelList] of entries) {
|
|
339
|
+
ui.print(` ${ui.bold(provider)}:`);
|
|
340
|
+
for (const model of modelList) {
|
|
341
|
+
ui.print(` - ${model}`);
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
} catch {
|
|
346
|
+
ui.warning('Failed to list models.');
|
|
347
|
+
}
|
|
348
|
+
break;
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
case 'exit':
|
|
352
|
+
case 'quit':
|
|
353
|
+
case 'q':
|
|
354
|
+
this.exit();
|
|
355
|
+
return;
|
|
356
|
+
|
|
357
|
+
default:
|
|
358
|
+
ui.warning(`Unknown command: /${command}`);
|
|
359
|
+
ui.info('Type /help for available commands.');
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
ui.newLine();
|
|
363
|
+
this.displayPrompt();
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
private handlePersonaCommand(args: string[]): void {
|
|
367
|
+
const validPersonas: PersonaTone[] = ['professional', 'assistant', 'expert'];
|
|
368
|
+
const tone = args[0]?.toLowerCase() as PersonaTone;
|
|
369
|
+
|
|
370
|
+
if (!tone) {
|
|
371
|
+
ui.info(`Current persona: ${this.options.persona || 'professional'}`);
|
|
372
|
+
ui.print(ui.dim(' Available: professional, assistant, expert'));
|
|
373
|
+
return;
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
if (!validPersonas.includes(tone)) {
|
|
377
|
+
ui.warning(`Invalid persona: ${tone}`);
|
|
378
|
+
ui.print(ui.dim(' Available: professional, assistant, expert'));
|
|
379
|
+
return;
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
this.options.persona = tone;
|
|
383
|
+
|
|
384
|
+
// Update system prompt in history
|
|
385
|
+
const personaPrompt = this.getPersonaSystemPrompt(tone);
|
|
386
|
+
const existingSystem = this.history.findIndex(m => m.role === 'system');
|
|
387
|
+
if (existingSystem >= 0) {
|
|
388
|
+
this.history[existingSystem].content = personaPrompt;
|
|
389
|
+
} else {
|
|
390
|
+
this.history.unshift({ role: 'system', content: personaPrompt });
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
ui.success(`Persona set to: ${tone}`);
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
private getPersonaSystemPrompt(tone: PersonaTone): string {
|
|
397
|
+
const baseIdentity = `You are Nimbus, an AI-powered cloud engineering assistant. You help users with:
|
|
398
|
+
|
|
399
|
+
- Infrastructure as Code (Terraform, CloudFormation, Pulumi)
|
|
400
|
+
- Kubernetes operations and configurations
|
|
401
|
+
- Cloud provider operations (AWS, GCP, Azure)
|
|
402
|
+
- Helm chart management and deployment
|
|
403
|
+
- DevOps best practices and CI/CD pipelines
|
|
404
|
+
- Troubleshooting infrastructure issues`;
|
|
405
|
+
|
|
406
|
+
const personaInstructions: Record<PersonaTone, string> = {
|
|
407
|
+
professional: `Maintain a formal, structured, and enterprise-focused tone at all times. Use bullet points and numbered lists to organize information clearly. Prefer formal language and avoid colloquialisms. Frame recommendations in terms of business impact, compliance, and operational excellence. When proposing changes, present them as structured plans with clear rationale, risk assessment, and rollback considerations.`,
|
|
408
|
+
assistant: `Be friendly and conversational while remaining helpful and accurate. Explain concepts in an approachable way, breaking down complex topics so they are easy to understand. When suggesting infrastructure code, walk through the reasoning behind each decision. If you need more information to provide accurate help, ask clarifying questions. Offer encouragement and context to help users learn as they go.`,
|
|
409
|
+
expert: `Be technical and concise. Assume the user has deep knowledge of cloud infrastructure, networking, and DevOps practices. Skip introductory explanations and get straight to the solution. Include advanced patterns, edge cases, and performance considerations where relevant. Reference specific API versions, provider documentation, and known gotchas. Prefer code-first responses with terse inline comments over lengthy prose.`,
|
|
410
|
+
};
|
|
411
|
+
|
|
412
|
+
return [baseIdentity, '', personaInstructions[tone]].join('\n');
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
private displayHelp(): void {
|
|
416
|
+
ui.newLine();
|
|
417
|
+
ui.section('Chat Commands');
|
|
418
|
+
ui.print(' /help - Show this help message');
|
|
419
|
+
ui.print(' /clear - Clear chat history');
|
|
420
|
+
ui.print(' /model <name> - Change the LLM model');
|
|
421
|
+
ui.print(' /models - List all available provider models');
|
|
422
|
+
ui.print(' /mode <mode> - Switch mode (plan, build, deploy)');
|
|
423
|
+
ui.print(' /persona <tone> - Set persona (professional, assistant, expert)');
|
|
424
|
+
ui.print(' /verbose - Toggle verbose output (tokens, model, latency)');
|
|
425
|
+
ui.print(' /history - Show conversation history');
|
|
426
|
+
ui.print(' /undo - Undo the last file-modifying tool call');
|
|
427
|
+
ui.print(' /redo - Re-apply a previously undone change');
|
|
428
|
+
ui.print(' /export [fmt] - Export conversation (json, markdown, text)');
|
|
429
|
+
ui.print(' /exit - Exit chat mode');
|
|
430
|
+
ui.newLine();
|
|
431
|
+
ui.print(ui.dim(' Press Ctrl+C to exit at any time.'));
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
private clearHistory(): void {
|
|
435
|
+
// Keep system prompt if present
|
|
436
|
+
const systemPrompt = this.history.find(m => m.role === 'system');
|
|
437
|
+
this.history = systemPrompt ? [systemPrompt] : [];
|
|
438
|
+
ui.success('Chat history cleared.');
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
private displayHistory(): void {
|
|
442
|
+
ui.newLine();
|
|
443
|
+
ui.section('Conversation History');
|
|
444
|
+
|
|
445
|
+
if (this.history.length === 0) {
|
|
446
|
+
ui.print(ui.dim(' No messages yet.'));
|
|
447
|
+
return;
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
for (const msg of this.history) {
|
|
451
|
+
const roleColor = msg.role === 'user' ? 'green' : msg.role === 'assistant' ? 'blue' : 'gray';
|
|
452
|
+
const roleLabel =
|
|
453
|
+
msg.role === 'user' ? 'You' : msg.role === 'assistant' ? 'Nimbus' : 'System';
|
|
454
|
+
|
|
455
|
+
const displayContent =
|
|
456
|
+
msg.role === 'assistant' ? highlightCodeBlocks(msg.content) : msg.content;
|
|
457
|
+
ui.print(
|
|
458
|
+
` ${ui.color(`${roleLabel}:`, roleColor)} ${displayContent.substring(0, 100)}${displayContent.length > 100 ? '...' : ''}`
|
|
459
|
+
);
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
/**
|
|
464
|
+
* Prompt user for permission via readline. Returns allow/deny/block.
|
|
465
|
+
*/
|
|
466
|
+
private promptPermission(
|
|
467
|
+
tool: ToolDefinition,
|
|
468
|
+
input: unknown
|
|
469
|
+
): Promise<'allow' | 'deny' | 'block'> {
|
|
470
|
+
return new Promise(resolve => {
|
|
471
|
+
const inputSummary =
|
|
472
|
+
input && typeof input === 'object'
|
|
473
|
+
? Object.entries(input as Record<string, unknown>)
|
|
474
|
+
.slice(0, 3)
|
|
475
|
+
.map(([k, v]) => {
|
|
476
|
+
const s = typeof v === 'string' ? v : JSON.stringify(v);
|
|
477
|
+
return ` ${k}: ${s.length > 60 ? `${s.slice(0, 57)}...` : s}`;
|
|
478
|
+
})
|
|
479
|
+
.join('\n')
|
|
480
|
+
: '';
|
|
481
|
+
|
|
482
|
+
ui.newLine();
|
|
483
|
+
process.stdout.write(
|
|
484
|
+
`${ui.color('⚠ Permission required', 'yellow')}: ${ui.bold(tool.name)}\n${
|
|
485
|
+
inputSummary ? `${inputSummary}\n` : ''
|
|
486
|
+
}${ui.dim('[y] Allow [n] Deny [a] Allow for session')} `
|
|
487
|
+
);
|
|
488
|
+
|
|
489
|
+
const onLine = (line: string) => {
|
|
490
|
+
const answer = line.trim().toLowerCase();
|
|
491
|
+
if (this.rl) {
|
|
492
|
+
this.rl.removeListener('line', onLine);
|
|
493
|
+
}
|
|
494
|
+
if (answer === 'y' || answer === 'yes') {
|
|
495
|
+
resolve('allow');
|
|
496
|
+
} else if (answer === 'a') {
|
|
497
|
+
approveForSession(tool, this.permissionState);
|
|
498
|
+
const action = (input as Record<string, unknown>)?.action;
|
|
499
|
+
if (typeof action === 'string') {
|
|
500
|
+
approveActionForSession(tool.name, action, this.permissionState);
|
|
501
|
+
}
|
|
502
|
+
resolve('allow');
|
|
503
|
+
} else {
|
|
504
|
+
resolve('deny');
|
|
505
|
+
}
|
|
506
|
+
};
|
|
507
|
+
|
|
508
|
+
if (this.rl) {
|
|
509
|
+
this.rl.once('line', onLine);
|
|
510
|
+
} else {
|
|
511
|
+
// Fallback: deny if readline not available
|
|
512
|
+
resolve('deny');
|
|
513
|
+
}
|
|
514
|
+
});
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
/**
|
|
518
|
+
* Expand @path/to/file references in text with file contents.
|
|
519
|
+
*/
|
|
520
|
+
private expandFileReferences(text: string): string {
|
|
521
|
+
const fileRefs = text.match(/@([\w./_-]+)/g);
|
|
522
|
+
if (!fileRefs) {
|
|
523
|
+
return text;
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
let expanded = text;
|
|
527
|
+
for (const ref of fileRefs) {
|
|
528
|
+
const filePath = ref.slice(1);
|
|
529
|
+
try {
|
|
530
|
+
const resolved = path.resolve(process.cwd(), filePath);
|
|
531
|
+
const content = fs.readFileSync(resolved, 'utf-8');
|
|
532
|
+
const truncated =
|
|
533
|
+
content.length > 10000
|
|
534
|
+
? `${content.slice(0, 10000)}\n... (truncated — showing 10,000 of ${content.length.toLocaleString()} chars)`
|
|
535
|
+
: content;
|
|
536
|
+
expanded = expanded.replace(ref, `\n<file path="${filePath}">\n${truncated}\n</file>`);
|
|
537
|
+
} catch {
|
|
538
|
+
// File not found — leave the @reference as-is
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
return expanded;
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
private async sendMessage(userMessage: string): Promise<void> {
|
|
545
|
+
this.isProcessing = true;
|
|
546
|
+
this.abortController = new AbortController();
|
|
547
|
+
|
|
548
|
+
// Expand @file references
|
|
549
|
+
const expandedMessage = this.expandFileReferences(userMessage);
|
|
550
|
+
|
|
551
|
+
// Add user message to display history
|
|
552
|
+
this.history.push({
|
|
553
|
+
role: 'user',
|
|
554
|
+
content: expandedMessage,
|
|
555
|
+
});
|
|
556
|
+
|
|
557
|
+
ui.newLine();
|
|
558
|
+
|
|
559
|
+
// Show a thinking indicator until the first text chunk arrives
|
|
560
|
+
process.stdout.write(ui.dim(' Thinking...'));
|
|
561
|
+
let thinkingCleared = false;
|
|
562
|
+
const clearThinking = () => {
|
|
563
|
+
if (!thinkingCleared) {
|
|
564
|
+
thinkingCleared = true;
|
|
565
|
+
// Clear the "Thinking..." text
|
|
566
|
+
process.stdout.write('\r\x1b[K');
|
|
567
|
+
}
|
|
568
|
+
};
|
|
569
|
+
|
|
570
|
+
let fullResponse = '';
|
|
571
|
+
let tokenCount = 0;
|
|
572
|
+
let textStarted = false;
|
|
573
|
+
const startTime = Date.now();
|
|
574
|
+
|
|
575
|
+
try {
|
|
576
|
+
// Run the full agentic loop with tool-calling support
|
|
577
|
+
const result: AgentLoopResult = await runAgentLoop(expandedMessage, this.agentHistory, {
|
|
578
|
+
router: this.router,
|
|
579
|
+
toolRegistry: defaultToolRegistry,
|
|
580
|
+
mode: this.currentMode,
|
|
581
|
+
model: this.options.model,
|
|
582
|
+
cwd: process.cwd(),
|
|
583
|
+
signal: this.abortController.signal,
|
|
584
|
+
contextManager: this.contextManager,
|
|
585
|
+
snapshotManager: this.snapshotManager,
|
|
586
|
+
sessionId: this.sessionId || undefined,
|
|
587
|
+
|
|
588
|
+
onText: text => {
|
|
589
|
+
clearThinking();
|
|
590
|
+
if (!textStarted) {
|
|
591
|
+
process.stdout.write(ui.color('Nimbus: ', 'blue'));
|
|
592
|
+
textStarted = true;
|
|
593
|
+
}
|
|
594
|
+
process.stdout.write(text);
|
|
595
|
+
fullResponse += text;
|
|
596
|
+
},
|
|
597
|
+
|
|
598
|
+
onToolCallStart: (info: ToolCallInfo) => {
|
|
599
|
+
clearThinking();
|
|
600
|
+
// Show tool execution inline as text
|
|
601
|
+
const inputSummary = summarizeToolInput(info.name, info.input);
|
|
602
|
+
process.stdout.write(`\n${ui.dim(` [Tool: ${info.name}]`)} ${ui.dim(inputSummary)}\n`);
|
|
603
|
+
textStarted = false; // Reset so next text block gets prefix
|
|
604
|
+
},
|
|
605
|
+
|
|
606
|
+
onToolCallEnd: (info: ToolCallInfo, result: ToolResult) => {
|
|
607
|
+
if (result.isError) {
|
|
608
|
+
process.stdout.write(` ${ui.color(`Error: ${result.error}`, 'red')}\n`);
|
|
609
|
+
} else {
|
|
610
|
+
// Show truncated output for non-error results
|
|
611
|
+
const output = result.output.trim();
|
|
612
|
+
if (output) {
|
|
613
|
+
const lines = output.split('\n');
|
|
614
|
+
const preview =
|
|
615
|
+
lines.length > 5
|
|
616
|
+
? `${lines.slice(0, 5).join('\n')}\n ... (${lines.length - 5} more lines)`
|
|
617
|
+
: output;
|
|
618
|
+
process.stdout.write(` ${ui.dim(preview)}\n`);
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
},
|
|
622
|
+
|
|
623
|
+
onCompact: compactResult => {
|
|
624
|
+
ui.info(
|
|
625
|
+
`Context auto-compacted: saved ${compactResult.savedTokens.toLocaleString()} tokens.`
|
|
626
|
+
);
|
|
627
|
+
},
|
|
628
|
+
|
|
629
|
+
checkPermission: async (tool, input) => {
|
|
630
|
+
const decision = checkToolPermission(tool, input, this.permissionState);
|
|
631
|
+
if (decision === 'allow') {
|
|
632
|
+
return 'allow';
|
|
633
|
+
}
|
|
634
|
+
if (decision === 'block') {
|
|
635
|
+
return 'block';
|
|
636
|
+
}
|
|
637
|
+
// decision === 'ask': prompt the user inline
|
|
638
|
+
return this.promptPermission(tool, input);
|
|
639
|
+
},
|
|
640
|
+
});
|
|
641
|
+
|
|
642
|
+
// Ensure we end the text output
|
|
643
|
+
if (textStarted) {
|
|
644
|
+
process.stdout.write('\n');
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
// Update agent history with the full conversation from this turn
|
|
648
|
+
this.agentHistory = result.messages;
|
|
649
|
+
tokenCount = result.usage.totalTokens;
|
|
650
|
+
|
|
651
|
+
// Persist conversation to SQLite
|
|
652
|
+
if (this.sessionManager && this.sessionId) {
|
|
653
|
+
try {
|
|
654
|
+
this.sessionManager.saveConversation(this.sessionId, this.agentHistory);
|
|
655
|
+
this.sessionManager.updateSession(this.sessionId, {
|
|
656
|
+
tokenCount: result.usage.totalTokens,
|
|
657
|
+
costUSD: result.totalCost,
|
|
658
|
+
});
|
|
659
|
+
} catch {
|
|
660
|
+
/* persistence is non-critical */
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
// Extract the final assistant response for display history
|
|
665
|
+
const lastAssistant = [...result.messages].reverse().find(m => m.role === 'assistant');
|
|
666
|
+
|
|
667
|
+
if (lastAssistant) {
|
|
668
|
+
this.history.push({
|
|
669
|
+
role: 'assistant',
|
|
670
|
+
content: (lastAssistant.content as string) ?? fullResponse,
|
|
671
|
+
});
|
|
672
|
+
} else if (fullResponse) {
|
|
673
|
+
this.history.push({
|
|
674
|
+
role: 'assistant',
|
|
675
|
+
content: fullResponse,
|
|
676
|
+
});
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
// Show verbose info (token count, model, latency, turns, cost) when enabled
|
|
680
|
+
if (this.verboseOutput || this.options.showTokenCount) {
|
|
681
|
+
const latencyMs = Date.now() - startTime;
|
|
682
|
+
const parts: string[] = [];
|
|
683
|
+
if (tokenCount > 0) {
|
|
684
|
+
parts.push(`${tokenCount} tokens`);
|
|
685
|
+
}
|
|
686
|
+
if (this.verboseOutput) {
|
|
687
|
+
parts.push(`model: ${this.options.model || 'default'}`);
|
|
688
|
+
parts.push(`${latencyMs}ms`);
|
|
689
|
+
parts.push(`${result.turns} turn${result.turns !== 1 ? 's' : ''}`);
|
|
690
|
+
if (result.totalCost > 0) {
|
|
691
|
+
const costStr =
|
|
692
|
+
result.totalCost < 0.01
|
|
693
|
+
? `$${result.totalCost.toFixed(4)}`
|
|
694
|
+
: `$${result.totalCost.toFixed(2)}`;
|
|
695
|
+
parts.push(`cost: ${costStr}`);
|
|
696
|
+
}
|
|
697
|
+
}
|
|
698
|
+
if (parts.length > 0) {
|
|
699
|
+
ui.print(ui.dim(` (${parts.join(' | ')})`));
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
if (result.interrupted) {
|
|
704
|
+
ui.info('Operation interrupted.');
|
|
705
|
+
}
|
|
706
|
+
} catch (error: any) {
|
|
707
|
+
clearThinking();
|
|
708
|
+
if (textStarted) {
|
|
709
|
+
process.stdout.write('\n');
|
|
710
|
+
}
|
|
711
|
+
ui.error(error.message || 'Failed to get response');
|
|
712
|
+
this.history.pop(); // Remove failed user message
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
this.isProcessing = false;
|
|
716
|
+
|
|
717
|
+
ui.newLine();
|
|
718
|
+
this.displayPrompt();
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
/**
|
|
722
|
+
* Handle the /export command.
|
|
723
|
+
*
|
|
724
|
+
* Exports the current conversation to a file in the requested format.
|
|
725
|
+
* Supported formats: json (default), markdown, text.
|
|
726
|
+
*/
|
|
727
|
+
private async handleExportCommand(args: string[]): Promise<void> {
|
|
728
|
+
const userMessages = this.history.filter(m => m.role !== 'system');
|
|
729
|
+
|
|
730
|
+
if (userMessages.length === 0) {
|
|
731
|
+
ui.info('Nothing to export. Start a conversation first.');
|
|
732
|
+
return;
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
// Parse the requested format (default: json)
|
|
736
|
+
const rawFormat = (args[0] || 'json').toLowerCase();
|
|
737
|
+
const formatAliases: Record<string, ExportFormat> = {
|
|
738
|
+
json: 'json',
|
|
739
|
+
md: 'markdown',
|
|
740
|
+
markdown: 'markdown',
|
|
741
|
+
txt: 'text',
|
|
742
|
+
text: 'text',
|
|
743
|
+
};
|
|
744
|
+
const format: ExportFormat | undefined = formatAliases[rawFormat];
|
|
745
|
+
|
|
746
|
+
if (!format) {
|
|
747
|
+
ui.warning(`Unsupported export format: ${rawFormat}`);
|
|
748
|
+
ui.info('Supported formats: json, markdown (md), text (txt)');
|
|
749
|
+
return;
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
|
|
753
|
+
const extMap: Record<ExportFormat, string> = {
|
|
754
|
+
json: 'json',
|
|
755
|
+
markdown: 'md',
|
|
756
|
+
text: 'txt',
|
|
757
|
+
};
|
|
758
|
+
const ext = extMap[format];
|
|
759
|
+
const filename = `nimbus-chat-export-${timestamp}.${ext}`;
|
|
760
|
+
const filepath = path.resolve(process.cwd(), filename);
|
|
761
|
+
|
|
762
|
+
let content: string;
|
|
763
|
+
|
|
764
|
+
switch (format) {
|
|
765
|
+
case 'json': {
|
|
766
|
+
const payload = {
|
|
767
|
+
title: `Nimbus Chat Export`,
|
|
768
|
+
messages: this.history.map(m => ({
|
|
769
|
+
role: m.role,
|
|
770
|
+
content: m.content,
|
|
771
|
+
})),
|
|
772
|
+
exportedAt: new Date().toISOString(),
|
|
773
|
+
model: this.options.model || 'default',
|
|
774
|
+
};
|
|
775
|
+
content = JSON.stringify(payload, null, 2);
|
|
776
|
+
break;
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
case 'markdown': {
|
|
780
|
+
const lines: string[] = [
|
|
781
|
+
`# Nimbus Chat Export`,
|
|
782
|
+
'',
|
|
783
|
+
`> Exported at ${new Date().toISOString()} | Model: ${this.options.model || 'default'}`,
|
|
784
|
+
'',
|
|
785
|
+
];
|
|
786
|
+
for (const msg of this.history) {
|
|
787
|
+
if (msg.role === 'system') {
|
|
788
|
+
continue;
|
|
789
|
+
}
|
|
790
|
+
const heading = msg.role === 'user' ? 'User' : 'Assistant';
|
|
791
|
+
lines.push(`## ${heading}`, '', msg.content, '');
|
|
792
|
+
}
|
|
793
|
+
content = lines.join('\n');
|
|
794
|
+
break;
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
case 'text': {
|
|
798
|
+
const lines: string[] = [
|
|
799
|
+
`Nimbus Chat Export`,
|
|
800
|
+
`Exported at ${new Date().toISOString()} | Model: ${this.options.model || 'default'}`,
|
|
801
|
+
'---',
|
|
802
|
+
'',
|
|
803
|
+
];
|
|
804
|
+
for (const msg of this.history) {
|
|
805
|
+
if (msg.role === 'system') {
|
|
806
|
+
continue;
|
|
807
|
+
}
|
|
808
|
+
const label = msg.role === 'user' ? 'You' : 'Nimbus';
|
|
809
|
+
lines.push(`${label}:`, msg.content, '');
|
|
810
|
+
}
|
|
811
|
+
content = lines.join('\n');
|
|
812
|
+
break;
|
|
813
|
+
}
|
|
814
|
+
}
|
|
815
|
+
|
|
816
|
+
try {
|
|
817
|
+
fs.writeFileSync(filepath, content, 'utf-8');
|
|
818
|
+
ui.success(`Conversation exported to ${filename}`);
|
|
819
|
+
} catch (err: any) {
|
|
820
|
+
ui.warning(`Failed to write export file: ${err.message}`);
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
private exit(): void {
|
|
825
|
+
ui.newLine();
|
|
826
|
+
ui.info('Goodbye!');
|
|
827
|
+
ui.newLine();
|
|
828
|
+
|
|
829
|
+
// Mark the session as completed before exiting
|
|
830
|
+
if (this.sessionManager && this.sessionId) {
|
|
831
|
+
try {
|
|
832
|
+
this.sessionManager.complete(this.sessionId);
|
|
833
|
+
} catch {
|
|
834
|
+
/* ignore */
|
|
835
|
+
}
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
if (this.rl) {
|
|
839
|
+
this.rl.close();
|
|
840
|
+
this.rl = null;
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
process.exit(0);
|
|
844
|
+
}
|
|
845
|
+
}
|
|
846
|
+
|
|
847
|
+
/**
|
|
848
|
+
* Start an interactive chat session
|
|
849
|
+
*/
|
|
850
|
+
export async function startChat(options: ChatUIOptions = {}): Promise<void> {
|
|
851
|
+
const chatUI = new ChatUI(options);
|
|
852
|
+
await chatUI.start();
|
|
853
|
+
}
|