@nexrall/code-core 1.0.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.
Files changed (54) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +155 -0
  3. package/dist/agent/agentTypes.d.ts +17 -0
  4. package/dist/agent/agentTypes.d.ts.map +1 -0
  5. package/dist/agent/agentTypes.js +156 -0
  6. package/dist/agent/loop.d.ts +3 -0
  7. package/dist/agent/loop.d.ts.map +1 -0
  8. package/dist/agent/loop.js +775 -0
  9. package/dist/api/client.d.ts +27 -0
  10. package/dist/api/client.d.ts.map +1 -0
  11. package/dist/api/client.js +414 -0
  12. package/dist/auth/index.d.ts +7 -0
  13. package/dist/auth/index.d.ts.map +1 -0
  14. package/dist/auth/index.js +95 -0
  15. package/dist/checkpoint/manager.d.ts +86 -0
  16. package/dist/checkpoint/manager.d.ts.map +1 -0
  17. package/dist/checkpoint/manager.js +409 -0
  18. package/dist/commands/loader.d.ts +18 -0
  19. package/dist/commands/loader.d.ts.map +1 -0
  20. package/dist/commands/loader.js +183 -0
  21. package/dist/index.d.ts +14 -0
  22. package/dist/index.d.ts.map +1 -0
  23. package/dist/index.js +30 -0
  24. package/dist/mcp/client.d.ts +46 -0
  25. package/dist/mcp/client.d.ts.map +1 -0
  26. package/dist/mcp/client.js +128 -0
  27. package/dist/mcp/httpClient.d.ts +25 -0
  28. package/dist/mcp/httpClient.d.ts.map +1 -0
  29. package/dist/mcp/httpClient.js +143 -0
  30. package/dist/mcp/manager.d.ts +56 -0
  31. package/dist/mcp/manager.d.ts.map +1 -0
  32. package/dist/mcp/manager.js +234 -0
  33. package/dist/mcp/sseClient.d.ts +30 -0
  34. package/dist/mcp/sseClient.d.ts.map +1 -0
  35. package/dist/mcp/sseClient.js +224 -0
  36. package/dist/permissions/rules.d.ts +20 -0
  37. package/dist/permissions/rules.d.ts.map +1 -0
  38. package/dist/permissions/rules.js +218 -0
  39. package/dist/plugins/index.d.ts +18 -0
  40. package/dist/plugins/index.d.ts.map +1 -0
  41. package/dist/plugins/index.js +139 -0
  42. package/dist/tools/executor.d.ts +6 -0
  43. package/dist/tools/executor.d.ts.map +1 -0
  44. package/dist/tools/executor.js +1458 -0
  45. package/dist/tools/sandbox.d.ts +13 -0
  46. package/dist/tools/sandbox.d.ts.map +1 -0
  47. package/dist/tools/sandbox.js +140 -0
  48. package/dist/tools/symbols.d.ts +13 -0
  49. package/dist/tools/symbols.d.ts.map +1 -0
  50. package/dist/tools/symbols.js +279 -0
  51. package/dist/types.d.ts +186 -0
  52. package/dist/types.d.ts.map +1 -0
  53. package/dist/types.js +4 -0
  54. package/package.json +92 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Nexrall
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,155 @@
1
+ # @nexrall/code-core
2
+
3
+ Core agent loop, tools, and extension primitives for **Nexrall Code** — embed an AI coding agent in any Node.js application.
4
+
5
+ ```bash
6
+ npm install @nexrall/code-core
7
+ ```
8
+
9
+ ## What's inside
10
+
11
+ | Module | Description |
12
+ |--------|-------------|
13
+ | `@nexrall/code-core` | Everything via the root export |
14
+ | `@nexrall/code-core/agent` | `runAgentLoop` — the main agentic loop |
15
+ | `@nexrall/code-core/tools` | `executeTool` — built-in tool executor (bash, file I/O, search…) |
16
+ | `@nexrall/code-core/symbols` | `getSymbols`, `getWorkspaceSymbols` — regex-based LSP-lite scanner |
17
+ | `@nexrall/code-core/checkpoint` | `CheckpointManager` — persistent rewind / rollback |
18
+ | `@nexrall/code-core/commands` | `loadSlashCommands`, `expandCommand` — slash command loader & expander |
19
+ | `@nexrall/code-core/plugins` | `loadPlugins`, `pluginHooks`, `pluginMcpServers` — plugin system |
20
+ | `@nexrall/code-core/permissions` | `loadSettings`, `evaluatePermission` — 4-tier permission rules |
21
+ | `@nexrall/code-core/mcp` | `McpManager` — MCP server manager (stdio / HTTP / SSE) |
22
+ | `@nexrall/code-core/api` | `streamChat` — streaming chat API client |
23
+ | `@nexrall/code-core/types` | Shared TypeScript types |
24
+
25
+ ## Quick start
26
+
27
+ ```ts
28
+ import { runAgentLoop } from '@nexrall/code-core/agent';
29
+ import type { AgentLoopOptions } from '@nexrall/code-core';
30
+
31
+ const messages = [
32
+ { role: 'user', content: [{ type: 'text', text: 'List the files in src/ and summarise what this project does.' }] }
33
+ ];
34
+
35
+ const opts: AgentLoopOptions = {
36
+ model: 'turbo', // 'turbo' (Sonnet) | 'pro' (Opus) | 'ultra' (Fable 5)
37
+ workDir: process.cwd(),
38
+ env: { platform: 'node', cwd: process.cwd(), shell: 'bash' },
39
+ clientType: 'cli',
40
+ mode: 'auto',
41
+ onText: (t) => process.stdout.write(t),
42
+ onThinking: () => {},
43
+ onThinkingDelta: () => {},
44
+ onThinkingProgress: () => {},
45
+ onToolUse: (name, input) => console.error(`[tool] ${name}`, input),
46
+ onToolResult: (name, res) => console.error(`[tool result] ${name}`, res.error ?? '✓'),
47
+ onInjectedInput: () => {},
48
+ onUsage: () => {},
49
+ requestPermission: async () => true, // auto-approve everything
50
+ };
51
+
52
+ const history = await runAgentLoop(messages, opts);
53
+ console.log('Done —', history.length, 'messages');
54
+ ```
55
+
56
+ > **Requires authentication.** The agent streams through the Nexrall API — users must be logged in via `nexrall-code login` (or set `NEXRALL_TOKEN` env var).
57
+
58
+ ## Agent loop options
59
+
60
+ ```ts
61
+ interface AgentLoopOptions {
62
+ model: 'turbo' | 'pro' | 'ultra';
63
+ workDir: string;
64
+ env: EnvContext;
65
+ clientType?: 'cli' | 'vscode';
66
+ mode?: 'auto' | 'ask' | 'edit' | 'plan';
67
+ effort?: 'low' | 'medium' | 'high' | 'extra';
68
+ nexrallMd?: string; // project instructions (nexrall.md contents)
69
+ maxIterations?: number; // default 500, ceiling 2000
70
+ autoContinue?: boolean; // auto-extend budget when agent is mid-task (default: true)
71
+ autoCompact?: boolean; // auto-summarise history at 80% context window (default: true)
72
+ abortSignal?: { aborted: boolean };
73
+ checkpointManager?: CheckpointManager;
74
+ mcpManager?: McpManager;
75
+ // Stream callbacks
76
+ onText: (text: string) => void;
77
+ onThinking: (text: string) => void;
78
+ onThinkingDelta: (text: string) => void;
79
+ onThinkingProgress: (tokens: number) => void;
80
+ onToolUse: (name: string, input: Record<string, unknown>, isSubTask?: boolean) => void;
81
+ onToolResult: (name: string, result: ToolResult, isSubTask?: boolean) => void;
82
+ onInjectedInput: (text: string) => void;
83
+ onUsage: (usage: UsageStats) => void;
84
+ requestPermission: (req: PermissionRequest) => Promise<boolean>;
85
+ // Optional: inject follow-up messages while the agent is running
86
+ takePendingInput?: () => string[];
87
+ // Optional: handle tools not in the built-in executor (e.g. VS Code LSP tools)
88
+ executeExternalTool?: (name: string, input: Record<string, unknown>) => Promise<ToolResult | null>;
89
+ }
90
+ ```
91
+
92
+ ## Plugin system
93
+
94
+ Drop a folder into `.nexrall/plugins/<name>/` (project) or `~/.nexrall/plugins/<name>/` (global):
95
+
96
+ ```
97
+ .nexrall/plugins/my-plugin/
98
+ plugin.json # { "name", "version", "description" }
99
+ commands/review.md # custom /review slash command
100
+ agents/reviewer.md # custom sub-agent type
101
+ hooks.json # PreToolUse / PostToolUse hooks
102
+ mcp.json # { "mcpServers": { ... } }
103
+ ```
104
+
105
+ Precedence: **project** > **global** > **plugin** > **builtin**.
106
+
107
+ ```ts
108
+ import { loadPlugins, pluginHooks, pluginMcpServers } from '@nexrall/code-core/plugins';
109
+
110
+ const plugins = loadPlugins(process.cwd());
111
+ // [{ name: 'my-plugin', version: '1.0.0', dir: '...', scope: 'project' }]
112
+ ```
113
+
114
+ ## Slash commands & agents
115
+
116
+ ```ts
117
+ import { loadSlashCommands, expandCommand, findSlashCommand } from '@nexrall/code-core/commands';
118
+ import { loadAgentTypes, findAgentType } from '@nexrall/code-core/agent-types';
119
+
120
+ // Built-in /review command is always available (overridable)
121
+ const cmds = loadSlashCommands(process.cwd());
122
+ const review = findSlashCommand(cmds, 'review');
123
+ const prompt = expandCommand(review, 'main..feature-branch', process.cwd());
124
+
125
+ // Built-in 'reviewer' agent (read-only, usable as subagent_type: 'reviewer')
126
+ const agents = loadAgentTypes(process.cwd());
127
+ const reviewer = findAgentType(agents, 'reviewer');
128
+ ```
129
+
130
+ ## Checkpoint / rewind
131
+
132
+ ```ts
133
+ import { CheckpointManager } from '@nexrall/code-core/checkpoint';
134
+
135
+ // Scoped per session — persists to ~/.nexrall/checkpoints/<hash>/
136
+ const cp = new CheckpointManager(workDir, sessionId);
137
+ cp.beginTurn('refactor auth module', messages.length);
138
+ // ... agent runs and mutates files ...
139
+ cp.commitTurn();
140
+
141
+ // Roll back files + conversation
142
+ const result = cp.restore(cp.list()[0].id);
143
+ // result.restored → absolute paths rolled back
144
+ // result.bashCount → shell commands NOT undone (with warning)
145
+ // result.gitStashHashes → git stash create recovery points
146
+ ```
147
+
148
+ ## Requirements
149
+
150
+ - Node.js ≥ 18
151
+ - A Nexrall account (sign up at [nexrall.com](https://nexrall.com))
152
+
153
+ ## License
154
+
155
+ MIT © [Nexrall](https://nexrall.com)
@@ -0,0 +1,17 @@
1
+ export interface AgentType {
2
+ name: string;
3
+ description: string;
4
+ /** Optional allowlist — when set, the sub-agent may only use these tools. */
5
+ tools?: string[];
6
+ /** Optional model override for the sub-agent. */
7
+ model?: 'turbo' | 'pro' | 'ultra';
8
+ /** System instructions (the markdown body below the frontmatter). */
9
+ prompt: string;
10
+ source: 'project' | 'global' | 'builtin' | 'plugin';
11
+ }
12
+ /** Discover all custom agent types (project overrides global overrides builtin). */
13
+ export declare function loadAgentTypes(workDir: string): AgentType[];
14
+ /** A compact catalogue injected into the system prompt so the model can pick a type. */
15
+ export declare function summariseAgents(types: AgentType[]): string;
16
+ export declare function findAgentType(types: AgentType[], name: string | undefined): AgentType | undefined;
17
+ //# sourceMappingURL=agentTypes.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agentTypes.d.ts","sourceRoot":"","sources":["../../src/agent/agentTypes.ts"],"names":[],"mappings":"AAuBA,MAAM,WAAW,SAAS;IACxB,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,6EAA6E;IAC7E,KAAK,CAAC,EAAE,MAAM,EAAE,CAAC;IACjB,iDAAiD;IACjD,KAAK,CAAC,EAAE,OAAO,GAAG,KAAK,GAAG,OAAO,CAAC;IAClC,qEAAqE;IACrE,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,SAAS,GAAG,QAAQ,GAAG,SAAS,GAAG,QAAQ,CAAC;CACrD;AAoFD,oFAAoF;AACpF,wBAAgB,cAAc,CAAC,OAAO,EAAE,MAAM,GAAG,SAAS,EAAE,CAS3D;AAED,wFAAwF;AACxF,wBAAgB,eAAe,CAAC,KAAK,EAAE,SAAS,EAAE,GAAG,MAAM,CAQ1D;AAED,wBAAgB,aAAa,CAAC,KAAK,EAAE,SAAS,EAAE,EAAE,IAAI,EAAE,MAAM,GAAG,SAAS,GAAG,SAAS,GAAG,SAAS,CAIjG"}
@@ -0,0 +1,156 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.loadAgentTypes = loadAgentTypes;
37
+ exports.summariseAgents = summariseAgents;
38
+ exports.findAgentType = findAgentType;
39
+ const fs = __importStar(require("fs"));
40
+ const path = __importStar(require("path"));
41
+ const os = __importStar(require("os"));
42
+ const index_1 = require("../plugins/index");
43
+ // ── Built-in agent types ──────────────────────────────────────────────────────
44
+ // Shipped defaults; lowest precedence (project > global > builtin), so a user
45
+ // can override any of them with a same-name .nexrall/agents/<name>.md file.
46
+ const BUILTIN_AGENTS = [
47
+ {
48
+ name: 'reviewer',
49
+ description: 'Read-only code reviewer — finds correctness bugs, edge cases, and security issues in a diff or file set. Cannot modify files.',
50
+ tools: ['read_file', 'search_files', 'glob', 'list_directory', 'bash', 'get_symbols', 'get_workspace_symbols', 'find_references', 'go_to_definition', 'get_diagnostics'],
51
+ source: 'builtin',
52
+ prompt: [
53
+ 'You are a meticulous senior code reviewer. You NEVER modify files — you only read, search, and report.',
54
+ '',
55
+ 'Method:',
56
+ '1. Read the full context around every change you are asked to review; never judge a hunk in isolation.',
57
+ '2. Hunt specifically for: correctness bugs, unhandled edge cases (empty/null/unicode/concurrency/timezone),',
58
+ ' security issues (injection, path traversal, secrets in code, unsafe deserialization), breaking API',
59
+ ' changes (search for callers first), silent behaviour changes, and swallowed errors.',
60
+ '3. Verify test coverage: are the changed paths tested? Were assertions weakened or tests deleted?',
61
+ '4. Only use bash for read-only commands (git diff/log/show, grep, test runs). Never run mutating commands.',
62
+ '',
63
+ 'Report format: 🔴 Critical / 🟡 Warning / 🟢 Suggestion, each with file:line and a concrete fix,',
64
+ 'then a final verdict (APPROVE or REQUEST CHANGES) with a one-paragraph rationale.',
65
+ ].join('\n'),
66
+ },
67
+ ];
68
+ function parseFrontmatter(raw) {
69
+ const m = /^\s*---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/.exec(raw);
70
+ if (!m)
71
+ return { meta: {}, body: raw.trim() };
72
+ const meta = {};
73
+ for (const line of m[1].split(/\r?\n/)) {
74
+ const kv = /^([A-Za-z0-9_-]+)\s*:\s*(.*)$/.exec(line.trim());
75
+ if (kv)
76
+ meta[kv[1].toLowerCase()] = kv[2].trim().replace(/^["']|["']$/g, '');
77
+ }
78
+ return { meta, body: (m[2] ?? '').trim() };
79
+ }
80
+ function parseModel(v) {
81
+ const s = (v ?? '').toLowerCase();
82
+ return s === 'turbo' || s === 'pro' || s === 'ultra' ? s : undefined;
83
+ }
84
+ function parseToolList(v) {
85
+ if (!v)
86
+ return undefined;
87
+ const tools = v
88
+ .replace(/^\[|\]$/g, '') // tolerate [a, b] style
89
+ .split(/[,\s]+/)
90
+ .map((t) => t.trim())
91
+ .filter(Boolean);
92
+ return tools.length ? tools : undefined;
93
+ }
94
+ function loadDir(dir, source, into) {
95
+ let entries;
96
+ try {
97
+ entries = fs.readdirSync(dir).filter((f) => f.endsWith('.md'));
98
+ }
99
+ catch {
100
+ return;
101
+ }
102
+ for (const file of entries) {
103
+ try {
104
+ const raw = fs.readFileSync(path.join(dir, file), 'utf-8');
105
+ const { meta, body } = parseFrontmatter(raw);
106
+ const name = (meta.name || path.basename(file, '.md')).trim();
107
+ if (!name)
108
+ continue;
109
+ // Earlier tiers win (project > global > plugin).
110
+ if (source !== 'project' && into.has(name))
111
+ continue;
112
+ into.set(name, {
113
+ name,
114
+ description: meta.description || `Custom ${name} agent`,
115
+ tools: parseToolList(meta.tools),
116
+ model: parseModel(meta.model),
117
+ prompt: body,
118
+ source,
119
+ });
120
+ }
121
+ catch {
122
+ /* skip unreadable / malformed definitions */
123
+ }
124
+ }
125
+ }
126
+ /** Discover all custom agent types (project overrides global overrides builtin). */
127
+ function loadAgentTypes(workDir) {
128
+ const out = new Map();
129
+ loadDir(path.join(workDir, '.nexrall', 'agents'), 'project', out);
130
+ loadDir(path.join(os.homedir(), '.nexrall', 'agents'), 'global', out);
131
+ for (const dir of (0, index_1.pluginAssetDirs)(workDir, 'agents'))
132
+ loadDir(dir, 'plugin', out);
133
+ for (const agent of BUILTIN_AGENTS) {
134
+ if (!out.has(agent.name))
135
+ out.set(agent.name, agent);
136
+ }
137
+ return [...out.values()];
138
+ }
139
+ /** A compact catalogue injected into the system prompt so the model can pick a type. */
140
+ function summariseAgents(types) {
141
+ if (!types.length)
142
+ return '';
143
+ return types
144
+ .map((t) => {
145
+ const tools = t.tools ? ` (tools: ${t.tools.join(', ')})` : '';
146
+ return `- ${t.name}: ${t.description}${tools}`;
147
+ })
148
+ .join('\n');
149
+ }
150
+ function findAgentType(types, name) {
151
+ if (!name)
152
+ return undefined;
153
+ const want = name.trim().toLowerCase();
154
+ return types.find((t) => t.name.toLowerCase() === want);
155
+ }
156
+ //# sourceMappingURL=agentTypes.js.map
@@ -0,0 +1,3 @@
1
+ import type { Message, AgentLoopOptions } from '../types';
2
+ export declare function runAgentLoop(initialMessages: Message[], options: AgentLoopOptions): Promise<Message[]>;
3
+ //# sourceMappingURL=loop.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"loop.d.ts","sourceRoot":"","sources":["../../src/agent/loop.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,OAAO,EAMP,gBAAgB,EACjB,MAAM,UAAU,CAAC;AAuflB,wBAAsB,YAAY,CAChC,eAAe,EAAE,OAAO,EAAE,EAC1B,OAAO,EAAE,gBAAgB,GACxB,OAAO,CAAC,OAAO,EAAE,CAAC,CAuWpB"}