bridge-agent 0.1.0-beta.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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Jerico
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,67 @@
1
+ # bridge-agent
2
+
3
+ Bridge local agent — connects your AI tools to Jerico
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install -g bridge-agent
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ### 1. Authenticate
14
+
15
+ Get a token from your Jerico server (Settings → Daemon Tokens), then:
16
+
17
+ ```bash
18
+ bridge-agent auth --server https://your-server.com --token YOUR_TOKEN
19
+ ```
20
+
21
+ Or with interactive browser flow:
22
+
23
+ ```bash
24
+ bridge-agent auth --server https://your-server.com
25
+ ```
26
+
27
+ ### 2. Start the Daemon
28
+
29
+ ```bash
30
+ bridge-agent start
31
+ ```
32
+
33
+ The daemon will:
34
+ - Connect to your Jerico server via WebSocket
35
+ - Detect installed AI agents (Claude, Qwen, Kimi, etc.)
36
+ - Allow spawning terminals from the web interface
37
+
38
+ ### 3. Check Status
39
+
40
+ ```bash
41
+ bridge-agent status
42
+ ```
43
+
44
+ ## Supported Agents
45
+
46
+ - **Claude Code** (`claude`) - Requires `claude` CLI
47
+ - **Qwen CLI** (`qwen`) - Requires `qwen` CLI
48
+ - **Kimi Code** (`kimi`) - Requires `kimi` CLI
49
+ - **Codex CLI** (`codex`) - Requires `codex` CLI
50
+ - **Gemini** (`gemini`) - Requires `gemini` CLI
51
+ - **Ollama** (`ollama`) - Requires `ollama`
52
+ - **Aider** (`aider`) - Requires `aider`
53
+ - **Shell** (`sh`) - System shell (always available)
54
+
55
+ ## Configuration
56
+
57
+ Config is stored in:
58
+ - macOS/Linux: `~/.bridge/config.json` or `~/.jerico/settings.json`
59
+
60
+ ## Requirements
61
+
62
+ - Node.js >= 20
63
+ - For each AI agent: the respective CLI tool installed and authenticated
64
+
65
+ ## License
66
+
67
+ MIT
@@ -0,0 +1 @@
1
+ export declare function runAuth(serverUrl: string, noBrowser?: boolean, providedToken?: string): Promise<void>;
@@ -0,0 +1,87 @@
1
+ import https from 'https';
2
+ import http from 'http';
3
+ import { saveConfig } from '../config.js';
4
+ function sanitizeToken(raw) {
5
+ return (raw ?? '').trim();
6
+ }
7
+ export async function runAuth(serverUrl, noBrowser = false, providedToken) {
8
+ console.log('[bridge] Starting auth flow...');
9
+ console.log(`[bridge] Server: ${serverUrl}`);
10
+ console.log('[bridge] Open this URL to generate a daemon token:');
11
+ console.log(` ${serverUrl}/connect`);
12
+ const inlineToken = sanitizeToken(providedToken);
13
+ if (inlineToken) {
14
+ console.log('[bridge] Using token from --token');
15
+ }
16
+ if (noBrowser) {
17
+ if (inlineToken) {
18
+ console.log('[bridge] --no-browser ignored because --token is provided.');
19
+ }
20
+ else {
21
+ console.log('[bridge] --no-browser: exiting after printing URL.');
22
+ process.exit(0);
23
+ }
24
+ }
25
+ let token = inlineToken;
26
+ if (!token) {
27
+ console.log();
28
+ console.log('[bridge] After authenticating, paste your token here:');
29
+ token = await promptToken();
30
+ }
31
+ if (!token) {
32
+ console.error('[bridge] No token provided. Exiting.');
33
+ process.exit(1);
34
+ }
35
+ // Validate token with server
36
+ const isValid = await validateToken(serverUrl, token);
37
+ if (!isValid) {
38
+ console.error('[bridge] Token validation failed. Please try again.');
39
+ process.exit(1);
40
+ }
41
+ const wsBase = serverUrl.replace(/^https?:\/\//, (match) => match.startsWith('https') ? 'wss://' : 'ws://');
42
+ const wsUrl = wsBase.replace(/\/?$/, '/ws/daemon');
43
+ saveConfig({
44
+ server: wsUrl,
45
+ token,
46
+ name: process.env['HOSTNAME'] ?? 'My Machine',
47
+ });
48
+ console.log('[bridge] Auth successful! Config saved to ~/.bridge/config.json');
49
+ console.log('[bridge] Run: bridge-agent start');
50
+ }
51
+ async function promptToken() {
52
+ return new Promise(resolve => {
53
+ process.stdout.write('Token: ');
54
+ let input = '';
55
+ process.stdin.setEncoding('utf-8');
56
+ process.stdin.on('data', (chunk) => {
57
+ input += chunk;
58
+ if (input.includes('\n')) {
59
+ process.stdin.pause();
60
+ resolve(input.trim());
61
+ }
62
+ });
63
+ process.stdin.resume();
64
+ });
65
+ }
66
+ async function validateToken(serverUrl, token) {
67
+ return new Promise(resolve => {
68
+ const url = new URL('/api/tokens/validate', serverUrl);
69
+ const isHttps = url.protocol === 'https:';
70
+ const lib = isHttps ? https : http;
71
+ const options = {
72
+ hostname: url.hostname,
73
+ port: url.port || (isHttps ? 443 : 80),
74
+ path: url.pathname,
75
+ method: 'POST',
76
+ headers: {
77
+ 'Content-Type': 'application/json',
78
+ 'Authorization': `Bearer ${token}`,
79
+ },
80
+ };
81
+ const req = lib.request(options, (res) => {
82
+ resolve(res.statusCode === 200);
83
+ });
84
+ req.on('error', () => resolve(false));
85
+ req.end();
86
+ });
87
+ }
@@ -0,0 +1 @@
1
+ export declare function runStart(): void;
@@ -0,0 +1,21 @@
1
+ import { createServer } from 'node:http';
2
+ import { PtyManager } from '../pty/manager.js';
3
+ import { startDaemonConnection, isDaemonWsConnected } from '../ws/client.js';
4
+ export function runStart() {
5
+ console.log('[bridge] Starting bridge-agent daemon...');
6
+ const manager = new PtyManager();
7
+ startDaemonConnection(manager);
8
+ const healthPort = parseInt(process.env['HEALTH_PORT'] ?? '3101', 10);
9
+ const health = createServer((_, res) => {
10
+ const connected = isDaemonWsConnected();
11
+ const body = JSON.stringify({ status: 'ok', connected, uptime: process.uptime() });
12
+ res.writeHead(connected ? 200 : 503, { 'Content-Type': 'application/json' });
13
+ res.end(body);
14
+ });
15
+ health.listen(healthPort, '127.0.0.1', () => {
16
+ console.log(`[bridge] health check listening on 127.0.0.1:${healthPort}`);
17
+ });
18
+ health.on('error', (err) => {
19
+ console.error('[bridge] health.server.error', { error: err.message });
20
+ });
21
+ }
@@ -0,0 +1,21 @@
1
+ export interface BridgeConfig {
2
+ server: string;
3
+ token: string;
4
+ name: string;
5
+ }
6
+ /** Project-level settings from .jerico/settings.json in cwd */
7
+ export interface ProjectSettings {
8
+ /** Override the agent binary to prefer in this project */
9
+ preferredAgent?: string;
10
+ /** Shell hooks — see lifecycle hooks (ISSUE 7) */
11
+ hooks?: Record<string, string>;
12
+ /** Additional env vars injected into spawned agents in this project */
13
+ env?: Record<string, string>;
14
+ }
15
+ export declare function loadConfig(): BridgeConfig;
16
+ export declare function saveConfig(config: BridgeConfig): void;
17
+ /**
18
+ * Load project-level settings from .jerico/settings.json in the given directory (or cwd).
19
+ * Returns empty object if the file does not exist or fails to parse.
20
+ */
21
+ export declare function loadProjectSettings(cwd?: string): ProjectSettings;
package/dist/config.js ADDED
@@ -0,0 +1,76 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import os from 'os';
4
+ /** New global path; legacy ~/.bridge/config.json is still supported as fallback */
5
+ const JERICO_CONFIG_PATH = path.join(os.homedir(), '.jerico', 'settings.json');
6
+ const CONFIG_PATH = path.join(os.homedir(), '.bridge', 'config.json');
7
+ export function loadConfig() {
8
+ // Prefer new ~/.jerico/settings.json; fall back to legacy ~/.bridge/config.json
9
+ const configPath = fs.existsSync(JERICO_CONFIG_PATH) ? JERICO_CONFIG_PATH : CONFIG_PATH;
10
+ if (!fs.existsSync(configPath)) {
11
+ console.error('[bridge] Config not found. Run: bridge-agent auth');
12
+ process.exit(1);
13
+ }
14
+ const raw = fs.readFileSync(configPath, 'utf-8');
15
+ let parsed;
16
+ try {
17
+ parsed = JSON.parse(raw);
18
+ }
19
+ catch {
20
+ console.error('[bridge] Invalid config file at', CONFIG_PATH);
21
+ process.exit(1);
22
+ }
23
+ if (!parsed || typeof parsed !== 'object') {
24
+ console.error('[bridge] Config must be a JSON object. Run: bridge-agent auth');
25
+ process.exit(1);
26
+ }
27
+ const obj = parsed;
28
+ const server = typeof obj['server'] === 'string' ? obj['server'] : '';
29
+ const token = typeof obj['token'] === 'string' ? obj['token'] : '';
30
+ const name = typeof obj['name'] === 'string' ? obj['name'] : 'bridge-agent';
31
+ if (!server || !token) {
32
+ console.error('[bridge] Config missing server or token. Run: bridge-agent auth');
33
+ process.exit(1);
34
+ }
35
+ return { server, token, name };
36
+ }
37
+ export function saveConfig(config) {
38
+ // Always write to new ~/.jerico path
39
+ const dir = path.dirname(JERICO_CONFIG_PATH);
40
+ if (!fs.existsSync(dir)) {
41
+ fs.mkdirSync(dir, { recursive: true });
42
+ }
43
+ fs.writeFileSync(JERICO_CONFIG_PATH, JSON.stringify(config, null, 2), { mode: 0o600 });
44
+ }
45
+ /**
46
+ * Load project-level settings from .jerico/settings.json in the given directory (or cwd).
47
+ * Returns empty object if the file does not exist or fails to parse.
48
+ */
49
+ export function loadProjectSettings(cwd) {
50
+ const settingsPath = path.join(cwd ?? process.cwd(), '.jerico', 'settings.json');
51
+ if (!fs.existsSync(settingsPath))
52
+ return {};
53
+ try {
54
+ const raw = fs.readFileSync(settingsPath, 'utf-8');
55
+ const parsed = JSON.parse(raw);
56
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
57
+ return {};
58
+ const obj = parsed;
59
+ const result = {};
60
+ if (typeof obj['preferredAgent'] === 'string')
61
+ result.preferredAgent = obj['preferredAgent'];
62
+ if (obj['hooks'] && typeof obj['hooks'] === 'object' && !Array.isArray(obj['hooks'])) {
63
+ result.hooks = Object.fromEntries(Object.entries(obj['hooks'])
64
+ .filter(([, v]) => typeof v === 'string'));
65
+ }
66
+ if (obj['env'] && typeof obj['env'] === 'object' && !Array.isArray(obj['env'])) {
67
+ result.env = Object.fromEntries(Object.entries(obj['env'])
68
+ .filter(([, v]) => typeof v === 'string'));
69
+ }
70
+ return result;
71
+ }
72
+ catch {
73
+ console.warn('[bridge] Failed to parse .jerico/settings.json, ignoring');
74
+ return {};
75
+ }
76
+ }
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};