noguard 0.0.0-stage → 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.
- package/bin/noguard.mjs +154 -0
- package/lib/api.mjs +76 -0
- package/lib/auth.mjs +77 -0
- package/lib/chat.mjs +325 -0
- package/lib/config.mjs +57 -0
- package/package.json +21 -4
- package/README.md +0 -3
package/bin/noguard.mjs
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
const VERSION = '1.0.0'
|
|
4
|
+
const HELP = `
|
|
5
|
+
\x1b[1mNoGuard AI CLI v${VERSION}\x1b[0m
|
|
6
|
+
The AI that doesn't say no — from your terminal.
|
|
7
|
+
|
|
8
|
+
\x1b[1mUsage:\x1b[0m
|
|
9
|
+
noguard Start chatting (same as noguard chat)
|
|
10
|
+
noguard chat [--model X] Start an interactive chat session
|
|
11
|
+
noguard login Sign in with your NoGuard account
|
|
12
|
+
noguard logout Sign out and revoke the token
|
|
13
|
+
noguard me Show your account and credits
|
|
14
|
+
noguard models List available models with tiers and pricing
|
|
15
|
+
noguard usage [--days N] Show credit usage history
|
|
16
|
+
noguard config Show config file location
|
|
17
|
+
noguard endpoint [URL] Show or set the API endpoint
|
|
18
|
+
|
|
19
|
+
\x1b[1mOptions:\x1b[0m
|
|
20
|
+
--help, -h Show this help
|
|
21
|
+
--version, -v Show version
|
|
22
|
+
--model, -m Choose a model (alias or name, e.g. noguard-ultra)
|
|
23
|
+
|
|
24
|
+
\x1b[1mIn-chat commands:\x1b[0m
|
|
25
|
+
/models List models and switch
|
|
26
|
+
/model <name> Switch to a model by alias or name
|
|
27
|
+
/libraries Show and toggle research libraries
|
|
28
|
+
/clear Start a new conversation
|
|
29
|
+
/credits Show remaining credits
|
|
30
|
+
/help Show all commands
|
|
31
|
+
/exit Leave the chat
|
|
32
|
+
`
|
|
33
|
+
|
|
34
|
+
async function main() {
|
|
35
|
+
const args = process.argv.slice(2)
|
|
36
|
+
const command = args[0]?.startsWith('-') ? null : args[0]
|
|
37
|
+
|
|
38
|
+
if (args.includes('--help') || args.includes('-h')) {
|
|
39
|
+
console.log(HELP)
|
|
40
|
+
return
|
|
41
|
+
}
|
|
42
|
+
if (args.includes('--version') || args.includes('-v')) {
|
|
43
|
+
console.log(VERSION)
|
|
44
|
+
return
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
switch (command) {
|
|
48
|
+
case 'login': {
|
|
49
|
+
const { login } = await import('../lib/auth.mjs')
|
|
50
|
+
await login()
|
|
51
|
+
break
|
|
52
|
+
}
|
|
53
|
+
case 'logout': {
|
|
54
|
+
const { logout } = await import('../lib/auth.mjs')
|
|
55
|
+
await logout()
|
|
56
|
+
break
|
|
57
|
+
}
|
|
58
|
+
case 'me': {
|
|
59
|
+
const { getToken } = await import('../lib/config.mjs')
|
|
60
|
+
const { get } = await import('../lib/api.mjs')
|
|
61
|
+
if (!getToken()) { console.log('\x1b[31m✗\x1b[0m Not signed in. Run \x1b[1mnoguard login\x1b[0m first.'); return }
|
|
62
|
+
try {
|
|
63
|
+
const me = await get('/api/v1/me')
|
|
64
|
+
console.log()
|
|
65
|
+
console.log(` \x1b[1mAccount\x1b[0m`)
|
|
66
|
+
console.log(` Email: ${me.email}`)
|
|
67
|
+
console.log(` Tier: ${me.tier}`)
|
|
68
|
+
console.log(` Verified: ${me.verified ? '\x1b[32myes\x1b[0m' : '\x1b[31mno\x1b[0m'}`)
|
|
69
|
+
console.log(` Credits: \x1b[33m${me.credits}\x1b[0m (${me.available} available)`)
|
|
70
|
+
console.log(` Token: ${me.token.name} (${me.token.uid})`)
|
|
71
|
+
console.log()
|
|
72
|
+
} catch (err) {
|
|
73
|
+
if (err.status === 401) console.log('\x1b[31m✗\x1b[0m Session expired. Run \x1b[1mnoguard login\x1b[0m again.')
|
|
74
|
+
else console.error(`\x1b[31m✗\x1b[0m ${err.message}`)
|
|
75
|
+
}
|
|
76
|
+
break
|
|
77
|
+
}
|
|
78
|
+
case 'models': {
|
|
79
|
+
const { get } = await import('../lib/api.mjs')
|
|
80
|
+
const { printModels } = await import('../lib/chat.mjs')
|
|
81
|
+
try {
|
|
82
|
+
const res = await get('/api/v1/models')
|
|
83
|
+
printModels(res.data)
|
|
84
|
+
} catch (err) {
|
|
85
|
+
console.error(`\x1b[31m✗\x1b[0m ${err.message}`)
|
|
86
|
+
}
|
|
87
|
+
break
|
|
88
|
+
}
|
|
89
|
+
case 'usage': {
|
|
90
|
+
const { getToken } = await import('../lib/config.mjs')
|
|
91
|
+
const { get } = await import('../lib/api.mjs')
|
|
92
|
+
if (!getToken()) { console.log('\x1b[31m✗\x1b[0m Not signed in. Run \x1b[1mnoguard login\x1b[0m first.'); return }
|
|
93
|
+
const daysIdx = args.indexOf('--days')
|
|
94
|
+
const days = daysIdx !== -1 ? parseInt(args[daysIdx + 1], 10) || 30 : 30
|
|
95
|
+
try {
|
|
96
|
+
const res = await get(`/api/v1/usage?days=${days}`)
|
|
97
|
+
console.log()
|
|
98
|
+
console.log(` \x1b[1mUsage (last ${res.days_covered} days)\x1b[0m`)
|
|
99
|
+
if (res.by_day?.length) {
|
|
100
|
+
for (const day of res.by_day) {
|
|
101
|
+
console.log(` ${day.date} \x1b[33m${day.credits_spent}\x1b[0m credits ${day.requests} requests`)
|
|
102
|
+
}
|
|
103
|
+
} else {
|
|
104
|
+
console.log(' \x1b[2mNo usage yet.\x1b[0m')
|
|
105
|
+
}
|
|
106
|
+
console.log()
|
|
107
|
+
} catch (err) {
|
|
108
|
+
if (err.status === 401) console.log('\x1b[31m✗\x1b[0m Session expired. Run \x1b[1mnoguard login\x1b[0m again.')
|
|
109
|
+
else console.error(`\x1b[31m✗\x1b[0m ${err.message}`)
|
|
110
|
+
}
|
|
111
|
+
break
|
|
112
|
+
}
|
|
113
|
+
case 'config': {
|
|
114
|
+
const { configPath, load } = await import('../lib/config.mjs')
|
|
115
|
+
const cfg = load()
|
|
116
|
+
console.log()
|
|
117
|
+
console.log(` \x1b[1mConfig\x1b[0m`)
|
|
118
|
+
console.log(` File: ${configPath()}`)
|
|
119
|
+
console.log(` Endpoint: ${cfg.endpoint ?? 'https://noguard.ai'}`)
|
|
120
|
+
console.log(` Signed: ${cfg.token ? '\x1b[32myes\x1b[0m' : '\x1b[31mno\x1b[0m'}`)
|
|
121
|
+
if (cfg.account) console.log(` Account: ${cfg.account.email}`)
|
|
122
|
+
console.log()
|
|
123
|
+
break
|
|
124
|
+
}
|
|
125
|
+
case 'endpoint': {
|
|
126
|
+
const sub = args[1]
|
|
127
|
+
if (sub && !sub.startsWith('-')) {
|
|
128
|
+
const { setEndpoint } = await import('../lib/config.mjs')
|
|
129
|
+
setEndpoint(sub)
|
|
130
|
+
console.log(`\x1b[32m✓\x1b[0m Endpoint set to \x1b[1m${sub}\x1b[0m`)
|
|
131
|
+
} else {
|
|
132
|
+
const { getEndpoint } = await import('../lib/config.mjs')
|
|
133
|
+
console.log(getEndpoint())
|
|
134
|
+
}
|
|
135
|
+
break
|
|
136
|
+
}
|
|
137
|
+
case 'chat':
|
|
138
|
+
case undefined: {
|
|
139
|
+
const modelIdx = args.indexOf('--model') !== -1 ? args.indexOf('--model') : args.indexOf('-m')
|
|
140
|
+
const model = modelIdx !== -1 ? args[modelIdx + 1] : undefined
|
|
141
|
+
const { chat } = await import('../lib/chat.mjs')
|
|
142
|
+
await chat({ model })
|
|
143
|
+
break
|
|
144
|
+
}
|
|
145
|
+
default:
|
|
146
|
+
console.log(`\x1b[31m✗\x1b[0m Unknown command: ${command}`)
|
|
147
|
+
console.log(' Run \x1b[1mnoguard --help\x1b[0m for usage.')
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
main().catch(err => {
|
|
152
|
+
console.error(`\x1b[31m✗\x1b[0m ${err.message}`)
|
|
153
|
+
process.exit(1)
|
|
154
|
+
})
|
package/lib/api.mjs
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { getToken, getEndpoint } from './config.mjs'
|
|
2
|
+
|
|
3
|
+
export class ApiError extends Error {
|
|
4
|
+
constructor(status, body) {
|
|
5
|
+
const msg = body?.error?.message ?? body?.error_description ?? body?.message ?? `HTTP ${status}`
|
|
6
|
+
super(msg)
|
|
7
|
+
this.status = status
|
|
8
|
+
this.code = body?.error?.type ?? body?.error ?? body?.code ?? 'unknown'
|
|
9
|
+
this.body = body
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function headers(token) {
|
|
14
|
+
const h = { 'Content-Type': 'application/json', 'Accept': 'application/json' }
|
|
15
|
+
if (token) h['Authorization'] = `Bearer ${token}`
|
|
16
|
+
return h
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export async function request(method, path, body, opts = {}) {
|
|
20
|
+
const base = getEndpoint()
|
|
21
|
+
const token = opts.token ?? getToken()
|
|
22
|
+
const url = `${base}${path}`
|
|
23
|
+
const res = await fetch(url, {
|
|
24
|
+
method,
|
|
25
|
+
headers: headers(token),
|
|
26
|
+
body: body ? JSON.stringify(body) : undefined,
|
|
27
|
+
signal: opts.signal,
|
|
28
|
+
})
|
|
29
|
+
if (path === '/api/v1/messages' && opts.stream) return res
|
|
30
|
+
const json = await res.json().catch(() => null)
|
|
31
|
+
if (!res.ok) throw new ApiError(res.status, json)
|
|
32
|
+
return json
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export async function get(path, opts) { return request('GET', path, null, opts) }
|
|
36
|
+
export async function post(path, body, opts) { return request('POST', path, body, opts) }
|
|
37
|
+
export async function del(path, opts) { return request('DELETE', path, null, opts) }
|
|
38
|
+
|
|
39
|
+
export async function* streamMessages(body, opts = {}) {
|
|
40
|
+
const base = getEndpoint()
|
|
41
|
+
const token = getToken()
|
|
42
|
+
const res = await fetch(`${base}/api/v1/messages`, {
|
|
43
|
+
method: 'POST',
|
|
44
|
+
headers: { ...headers(token), 'Accept': 'text/event-stream' },
|
|
45
|
+
body: JSON.stringify({ ...body, stream: true }),
|
|
46
|
+
signal: opts.signal,
|
|
47
|
+
})
|
|
48
|
+
if (!res.ok) {
|
|
49
|
+
const json = await res.json().catch(() => null)
|
|
50
|
+
throw new ApiError(res.status, json)
|
|
51
|
+
}
|
|
52
|
+
const reader = res.body.getReader()
|
|
53
|
+
const decoder = new TextDecoder()
|
|
54
|
+
let buffer = ''
|
|
55
|
+
while (true) {
|
|
56
|
+
const { done, value } = await reader.read()
|
|
57
|
+
if (done) break
|
|
58
|
+
buffer += decoder.decode(value, { stream: true })
|
|
59
|
+
const lines = buffer.split('\n')
|
|
60
|
+
buffer = lines.pop() ?? ''
|
|
61
|
+
let eventName = ''
|
|
62
|
+
for (const line of lines) {
|
|
63
|
+
if (line.startsWith('event: ')) {
|
|
64
|
+
eventName = line.slice(7).trim()
|
|
65
|
+
} else if (line.startsWith('data: ')) {
|
|
66
|
+
const data = line.slice(6)
|
|
67
|
+
try {
|
|
68
|
+
yield { event: eventName, data: JSON.parse(data) }
|
|
69
|
+
} catch {
|
|
70
|
+
yield { event: eventName, data }
|
|
71
|
+
}
|
|
72
|
+
eventName = ''
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
package/lib/auth.mjs
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { post } from './api.mjs'
|
|
2
|
+
import { setToken, clearToken, getToken, getEndpoint } from './config.mjs'
|
|
3
|
+
|
|
4
|
+
export async function login() {
|
|
5
|
+
const token = getToken()
|
|
6
|
+
if (token) {
|
|
7
|
+
console.log('\x1b[33m⚠\x1b[0m Already signed in. Run \x1b[1mnoguard logout\x1b[0m first to switch accounts.')
|
|
8
|
+
return
|
|
9
|
+
}
|
|
10
|
+
console.log('\x1b[36m◆\x1b[0m Starting sign-in…\n')
|
|
11
|
+
const flow = await post('/api/device/code', { client: 'cli' }, { token: null })
|
|
12
|
+
const code = flow.user_code
|
|
13
|
+
const url = flow.verification_uri_complete
|
|
14
|
+
|
|
15
|
+
console.log(' Open this URL in your browser:\n')
|
|
16
|
+
console.log(` \x1b[4m\x1b[36m${url}\x1b[0m\n`)
|
|
17
|
+
console.log(` Or go to \x1b[1m${flow.verification_uri}\x1b[0m and enter: \x1b[1m${code}\x1b[0m\n`)
|
|
18
|
+
|
|
19
|
+
try {
|
|
20
|
+
const parsed = new URL(url)
|
|
21
|
+
const base = new URL(getEndpoint())
|
|
22
|
+
if ((parsed.protocol === 'https:' || parsed.protocol === 'http:') && parsed.hostname === base.hostname) {
|
|
23
|
+
const { execFile } = await import('node:child_process')
|
|
24
|
+
const platform = process.platform
|
|
25
|
+
if (platform === 'win32') execFile('rundll32', ['url.dll,FileProtocolHandler', parsed.href])
|
|
26
|
+
else if (platform === 'darwin') execFile('open', ['--', parsed.href])
|
|
27
|
+
else execFile('xdg-open', [parsed.href])
|
|
28
|
+
}
|
|
29
|
+
} catch { /* browser open is best-effort */ }
|
|
30
|
+
|
|
31
|
+
console.log(' Waiting for approval…')
|
|
32
|
+
const interval = (flow.interval ?? 5) * 1000
|
|
33
|
+
const deadline = Date.now() + (flow.expires_in ?? 600) * 1000
|
|
34
|
+
|
|
35
|
+
while (Date.now() < deadline) {
|
|
36
|
+
await sleep(interval)
|
|
37
|
+
try {
|
|
38
|
+
const result = await post('/api/device/token', { device_code: flow.device_code }, { token: null })
|
|
39
|
+
if (result.access_token) {
|
|
40
|
+
setToken(result.access_token, result.account)
|
|
41
|
+
console.log(`\n\x1b[32m✓\x1b[0m Signed in as \x1b[1m${result.account.email}\x1b[0m`)
|
|
42
|
+
console.log(` Credits: \x1b[33m${result.account.credits}\x1b[0m`)
|
|
43
|
+
return
|
|
44
|
+
}
|
|
45
|
+
} catch (err) {
|
|
46
|
+
if (err.code === 'authorization_pending' || err.code === 'slow_down') continue
|
|
47
|
+
if (err.code === 'access_denied') {
|
|
48
|
+
console.log('\n\x1b[31m✗\x1b[0m Sign-in was denied in the browser.')
|
|
49
|
+
return
|
|
50
|
+
}
|
|
51
|
+
if (err.code === 'expired_token') {
|
|
52
|
+
console.log('\n\x1b[31m✗\x1b[0m Sign-in code expired. Run \x1b[1mnoguard login\x1b[0m again.')
|
|
53
|
+
return
|
|
54
|
+
}
|
|
55
|
+
throw err
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
console.log('\n\x1b[31m✗\x1b[0m Sign-in timed out. Run \x1b[1mnoguard login\x1b[0m again.')
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export async function logout() {
|
|
62
|
+
const token = getToken()
|
|
63
|
+
if (!token) {
|
|
64
|
+
console.log('\x1b[33m⚠\x1b[0m Not signed in.')
|
|
65
|
+
return
|
|
66
|
+
}
|
|
67
|
+
try {
|
|
68
|
+
const { del } = await import('./api.mjs')
|
|
69
|
+
await del('/api/v1/token')
|
|
70
|
+
} catch { /* revoke is best-effort; the token is cleared locally either way */ }
|
|
71
|
+
clearToken()
|
|
72
|
+
console.log('\x1b[32m✓\x1b[0m Signed out.')
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function sleep(ms) {
|
|
76
|
+
return new Promise(resolve => setTimeout(resolve, ms))
|
|
77
|
+
}
|
package/lib/chat.mjs
ADDED
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
import { createInterface } from 'node:readline'
|
|
2
|
+
import { get, streamMessages, ApiError } from './api.mjs'
|
|
3
|
+
import { getToken } from './config.mjs'
|
|
4
|
+
|
|
5
|
+
const RESET_COMMANDS = new Set(['/clear', '/reset', '/new'])
|
|
6
|
+
const EXIT_COMMANDS = new Set(['/exit', '/quit', '/bye'])
|
|
7
|
+
|
|
8
|
+
const TIER_COLORS = { ultra: '\x1b[33m', standard: '\x1b[36m', pro: '\x1b[32m', raw: '\x1b[35m' }
|
|
9
|
+
const TIER_ICONS = { ultra: '💎', standard: '⚡', pro: '🔥', raw: '🗡️' }
|
|
10
|
+
const RST = '\x1b[0m'
|
|
11
|
+
const DIM = '\x1b[2m'
|
|
12
|
+
const BOLD = '\x1b[1m'
|
|
13
|
+
const GREEN = '\x1b[32m'
|
|
14
|
+
const YELLOW = '\x1b[33m'
|
|
15
|
+
const RED = '\x1b[31m'
|
|
16
|
+
const CYAN = '\x1b[36m'
|
|
17
|
+
|
|
18
|
+
const LIBRARIES = [
|
|
19
|
+
{ id: 'cyber', label: 'Cipher · Cyber', summary: 'Exploits, offensive security, reverse engineering' },
|
|
20
|
+
{ id: 'engineering', label: 'Forge · Engineering', summary: 'Software, systems and hardware engineering' },
|
|
21
|
+
{ id: 'bio', label: 'Helix · Bio', summary: 'Pharmacology, substance data, harm reduction' },
|
|
22
|
+
{ id: 'creative', label: 'Muse · Creative', summary: 'Uncensored creative writing and full artistic freedom' },
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
function requireAuth() {
|
|
26
|
+
if (!getToken()) {
|
|
27
|
+
console.log(`${RED}✗${RST} Not signed in. Run ${BOLD}noguard login${RST} first.`)
|
|
28
|
+
process.exit(1)
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function printModels(models, current = null) {
|
|
33
|
+
console.log()
|
|
34
|
+
console.log(` ${BOLD}Available models${RST}`)
|
|
35
|
+
console.log()
|
|
36
|
+
for (const model of models) {
|
|
37
|
+
const tierColor = TIER_COLORS[model.tier] ?? CYAN
|
|
38
|
+
const icon = TIER_ICONS[model.tier] ?? '🤖'
|
|
39
|
+
const tags = []
|
|
40
|
+
if (model.default_chat) tags.push(`${GREEN}chat default${RST}`)
|
|
41
|
+
if (model.default_build) tags.push(`${GREEN}build default${RST}`)
|
|
42
|
+
if (model.default && !model.default_chat && !model.default_build) tags.push(`${GREEN}default${RST}`)
|
|
43
|
+
const active = current && model.id === current ? ` ${YELLOW}← active${RST}` : ''
|
|
44
|
+
const tagStr = tags.length ? ` ${tags.join(' · ')}` : ''
|
|
45
|
+
const cost = model.cost_indicator ?? '$'
|
|
46
|
+
console.log(` ${icon} ${tierColor}${BOLD}${model.display_name}${RST} ${DIM}${model.id}${RST} ${GREEN}${cost}${RST}${tagStr}${active}`)
|
|
47
|
+
if (model.description) console.log(` ${DIM}${model.description}${RST}`)
|
|
48
|
+
const caps = []
|
|
49
|
+
if (model.chat_eligible) caps.push('chat')
|
|
50
|
+
if (model.build_eligible) caps.push('build')
|
|
51
|
+
if (model.supports_tools) caps.push('tools')
|
|
52
|
+
if (caps.length) console.log(` ${DIM}Supports: ${caps.join(', ')} · Context: ${(model.context_window / 1000).toFixed(0)}k · Max output: ${(model.max_output_tokens / 1000).toFixed(0)}k${RST}`)
|
|
53
|
+
console.log()
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function printLibraries(activeLibs) {
|
|
58
|
+
console.log()
|
|
59
|
+
console.log(` ${BOLD}Research libraries${RST}`)
|
|
60
|
+
console.log(` ${DIM}Toggle with /library <id> — active libraries inject curated sources into your questions.${RST}`)
|
|
61
|
+
console.log()
|
|
62
|
+
for (const lib of LIBRARIES) {
|
|
63
|
+
const active = activeLibs.has(lib.id)
|
|
64
|
+
const mark = active ? `${GREEN}●${RST}` : `${DIM}○${RST}`
|
|
65
|
+
const label = active ? `${BOLD}${lib.label}${RST}` : `${DIM}${lib.label}${RST}`
|
|
66
|
+
console.log(` ${mark} ${label} ${DIM}(${lib.id})${RST}`)
|
|
67
|
+
console.log(` ${DIM}${lib.summary}${RST}`)
|
|
68
|
+
}
|
|
69
|
+
console.log()
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function printBanner(modelName) {
|
|
73
|
+
console.log()
|
|
74
|
+
console.log(`${BOLD} ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓${RST}`)
|
|
75
|
+
console.log(`${BOLD} ┃ NoGuard AI — CLI Chat ┃${RST}`)
|
|
76
|
+
console.log(`${BOLD} ┃ The AI that doesn't say no. ┃${RST}`)
|
|
77
|
+
console.log(`${BOLD} ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛${RST}`)
|
|
78
|
+
console.log()
|
|
79
|
+
if (modelName) console.log(` ${DIM}Model: ${BOLD}${modelName}${RST}`)
|
|
80
|
+
console.log(` ${DIM}Commands: /models · /model <name> · /libraries · /library <id> · /clear · /credits · /help · /exit${RST}`)
|
|
81
|
+
console.log(` ${DIM}Multi-line: end with \\\\ or use """ to start/end a block${RST}`)
|
|
82
|
+
console.log()
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export async function chat(opts = {}) {
|
|
86
|
+
requireAuth()
|
|
87
|
+
|
|
88
|
+
let availableModels = []
|
|
89
|
+
try {
|
|
90
|
+
const res = await get('/api/v1/models')
|
|
91
|
+
availableModels = res.data ?? []
|
|
92
|
+
} catch { /* models will be empty; user can still chat with defaults */ }
|
|
93
|
+
|
|
94
|
+
let currentModel = opts.model ?? null
|
|
95
|
+
if (currentModel && availableModels.length) {
|
|
96
|
+
const match = availableModels.find(m => m.id === currentModel || m.display_name.toLowerCase() === currentModel.toLowerCase())
|
|
97
|
+
if (match) currentModel = match.id
|
|
98
|
+
else {
|
|
99
|
+
console.log(`${YELLOW}⚠${RST} Model "${currentModel}" not found. Using default.`)
|
|
100
|
+
currentModel = null
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
if (!currentModel && availableModels.length) {
|
|
104
|
+
const def = availableModels.find(m => m.default_chat || m.default)
|
|
105
|
+
if (def) currentModel = def.id
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const currentModelName = () => {
|
|
109
|
+
const m = availableModels.find(m => m.id === currentModel)
|
|
110
|
+
return m ? m.display_name : currentModel ?? 'default'
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
printBanner(currentModelName())
|
|
114
|
+
|
|
115
|
+
const messages = []
|
|
116
|
+
let credits = null
|
|
117
|
+
let multilineBuffer = null
|
|
118
|
+
const activeLibraries = new Set()
|
|
119
|
+
|
|
120
|
+
const rl = createInterface({
|
|
121
|
+
input: process.stdin,
|
|
122
|
+
output: process.stdout,
|
|
123
|
+
prompt: `${CYAN}❯${RST} `,
|
|
124
|
+
terminal: process.stdin.isTTY !== false,
|
|
125
|
+
})
|
|
126
|
+
|
|
127
|
+
rl.prompt()
|
|
128
|
+
|
|
129
|
+
rl.on('line', async (raw) => {
|
|
130
|
+
const line = raw.trimEnd()
|
|
131
|
+
|
|
132
|
+
if (multilineBuffer !== null) {
|
|
133
|
+
if (line === '"""') {
|
|
134
|
+
const text = multilineBuffer.join('\n')
|
|
135
|
+
multilineBuffer = null
|
|
136
|
+
if (text.trim()) await sendMessage(text)
|
|
137
|
+
else rl.prompt()
|
|
138
|
+
} else {
|
|
139
|
+
multilineBuffer.push(line)
|
|
140
|
+
process.stdout.write(`${DIM}...${RST} `)
|
|
141
|
+
}
|
|
142
|
+
return
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
if (line === '"""') {
|
|
146
|
+
multilineBuffer = []
|
|
147
|
+
process.stdout.write(`${DIM}...${RST} `)
|
|
148
|
+
return
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
if (line.endsWith('\\\\')) {
|
|
152
|
+
multilineBuffer = [line.slice(0, -2)]
|
|
153
|
+
process.stdout.write(`${DIM}...${RST} `)
|
|
154
|
+
return
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const trimmed = line.trim()
|
|
158
|
+
if (!trimmed) { rl.prompt(); return }
|
|
159
|
+
|
|
160
|
+
if (EXIT_COMMANDS.has(trimmed.toLowerCase())) {
|
|
161
|
+
console.log(`${DIM} Bye.${RST}`)
|
|
162
|
+
rl.close()
|
|
163
|
+
return
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
if (RESET_COMMANDS.has(trimmed.toLowerCase())) {
|
|
167
|
+
messages.length = 0
|
|
168
|
+
console.log(`${GREEN}✓${RST} New conversation.\n`)
|
|
169
|
+
rl.prompt()
|
|
170
|
+
return
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
if (trimmed.toLowerCase() === '/credits') {
|
|
174
|
+
if (credits !== null) console.log(` ${YELLOW}${credits}${RST} credits remaining.\n`)
|
|
175
|
+
else console.log(` ${DIM}Credits will show after your first message.${RST}\n`)
|
|
176
|
+
rl.prompt()
|
|
177
|
+
return
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
if (trimmed.toLowerCase() === '/models') {
|
|
181
|
+
if (availableModels.length) printModels(availableModels, currentModel)
|
|
182
|
+
else console.log(` ${DIM}No models loaded. Send a message and the default will be used.${RST}\n`)
|
|
183
|
+
rl.prompt()
|
|
184
|
+
return
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
if (trimmed.toLowerCase().startsWith('/model ')) {
|
|
188
|
+
const name = trimmed.slice(7).trim()
|
|
189
|
+
if (!name) { console.log(` ${DIM}Usage: /model <alias or name>${RST}\n`); rl.prompt(); return }
|
|
190
|
+
const match = availableModels.find(m =>
|
|
191
|
+
m.id === name || m.id === name.toLowerCase() ||
|
|
192
|
+
m.display_name.toLowerCase() === name.toLowerCase()
|
|
193
|
+
)
|
|
194
|
+
if (match) {
|
|
195
|
+
currentModel = match.id
|
|
196
|
+
console.log(`${GREEN}✓${RST} Switched to ${BOLD}${match.display_name}${RST} (${match.id})\n`)
|
|
197
|
+
} else {
|
|
198
|
+
console.log(`${RED}✗${RST} Model "${name}" not found. Run /models to see options.\n`)
|
|
199
|
+
}
|
|
200
|
+
rl.prompt()
|
|
201
|
+
return
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
if (trimmed.toLowerCase() === '/libraries' || trimmed.toLowerCase() === '/libs') {
|
|
205
|
+
printLibraries(activeLibraries)
|
|
206
|
+
rl.prompt()
|
|
207
|
+
return
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
if (trimmed.toLowerCase().startsWith('/library ') || trimmed.toLowerCase().startsWith('/lib ')) {
|
|
211
|
+
const id = trimmed.split(/\s+/)[1]?.toLowerCase()
|
|
212
|
+
const lib = LIBRARIES.find(l => l.id === id)
|
|
213
|
+
if (!lib) {
|
|
214
|
+
console.log(`${RED}✗${RST} Unknown library "${id}". Options: ${LIBRARIES.map(l => l.id).join(', ')}\n`)
|
|
215
|
+
} else if (activeLibraries.has(id)) {
|
|
216
|
+
activeLibraries.delete(id)
|
|
217
|
+
console.log(`${GREEN}✓${RST} Disabled ${BOLD}${lib.label}${RST}\n`)
|
|
218
|
+
} else {
|
|
219
|
+
activeLibraries.add(id)
|
|
220
|
+
console.log(`${GREEN}✓${RST} Enabled ${BOLD}${lib.label}${RST}\n`)
|
|
221
|
+
}
|
|
222
|
+
rl.prompt()
|
|
223
|
+
return
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
if (trimmed.toLowerCase() === '/help') {
|
|
227
|
+
console.log()
|
|
228
|
+
console.log(` ${BOLD}Commands${RST}`)
|
|
229
|
+
console.log(` /models — List all models with tier info`)
|
|
230
|
+
console.log(` /model <name> — Switch to a model (alias or display name)`)
|
|
231
|
+
console.log(` /libraries, /libs — Show research libraries and their status`)
|
|
232
|
+
console.log(` /library <id>, /lib — Toggle a library on/off`)
|
|
233
|
+
console.log(` /clear, /reset, /new — Start a new conversation`)
|
|
234
|
+
console.log(` /credits — Show remaining credits`)
|
|
235
|
+
console.log(` /exit, /quit — Leave the chat`)
|
|
236
|
+
console.log()
|
|
237
|
+
console.log(` ${BOLD}Multi-line input${RST}`)
|
|
238
|
+
console.log(` End a line with \\\\ — Continue on the next line`)
|
|
239
|
+
console.log(` Type """ — Start/end a multi-line block`)
|
|
240
|
+
console.log()
|
|
241
|
+
rl.prompt()
|
|
242
|
+
return
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
await sendMessage(trimmed)
|
|
246
|
+
})
|
|
247
|
+
|
|
248
|
+
rl.on('close', () => process.exit(0))
|
|
249
|
+
|
|
250
|
+
async function sendMessage(text) {
|
|
251
|
+
rl.pause()
|
|
252
|
+
messages.push({ role: 'user', content: text })
|
|
253
|
+
|
|
254
|
+
const libs = [...activeLibraries]
|
|
255
|
+
const body = {
|
|
256
|
+
model: currentModel ?? undefined,
|
|
257
|
+
messages: [...messages],
|
|
258
|
+
noguard_persona: true,
|
|
259
|
+
stream: true,
|
|
260
|
+
...(libs.length ? { libraries: libs } : {}),
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
const modelLabel = currentModelName()
|
|
264
|
+
process.stdout.write(`\n\x1b[35m◆ NoGuard${RST} ${DIM}(${modelLabel}${libs.length ? ` + ${libs.length} lib${libs.length > 1 ? 's' : ''}` : ''})${RST}\n`)
|
|
265
|
+
let reply = ''
|
|
266
|
+
let spent = 0
|
|
267
|
+
|
|
268
|
+
try {
|
|
269
|
+
const controller = new AbortController()
|
|
270
|
+
const onInt = () => { controller.abort(); process.off('SIGINT', onInt) }
|
|
271
|
+
process.on('SIGINT', onInt)
|
|
272
|
+
|
|
273
|
+
for await (const { event, data } of streamMessages(body, { signal: controller.signal })) {
|
|
274
|
+
if (event === 'content_block_delta' && data?.delta?.text) {
|
|
275
|
+
const chunk = data.delta.text
|
|
276
|
+
reply += chunk
|
|
277
|
+
process.stdout.write(chunk)
|
|
278
|
+
}
|
|
279
|
+
if (event === 'noguard_credits') {
|
|
280
|
+
credits = data.balance ?? credits
|
|
281
|
+
spent = data.spent ?? spent
|
|
282
|
+
}
|
|
283
|
+
if (event === 'error') {
|
|
284
|
+
const msg = data?.error?.message ?? 'Something went wrong.'
|
|
285
|
+
process.stdout.write(`\n${RED} Error: ${msg}${RST}`)
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
process.off('SIGINT', onInt)
|
|
290
|
+
} catch (err) {
|
|
291
|
+
if (err.name === 'AbortError') {
|
|
292
|
+
process.stdout.write(`${DIM} [stopped]${RST}`)
|
|
293
|
+
} else if (err instanceof ApiError) {
|
|
294
|
+
process.stdout.write(`${RED} Error: ${err.message}${RST}`)
|
|
295
|
+
if (err.code === 'invalid_token' || err.status === 401) {
|
|
296
|
+
console.log(`\n${YELLOW}⚠${RST} Session expired. Run ${BOLD}noguard login${RST} again.`)
|
|
297
|
+
rl.close()
|
|
298
|
+
return
|
|
299
|
+
}
|
|
300
|
+
if (err.code === 'out_of_credits') {
|
|
301
|
+
console.log(`\n${YELLOW}⚠${RST} Out of credits. Top up at \x1b[4mhttps://noguard.ai/credits${RST}`)
|
|
302
|
+
}
|
|
303
|
+
if (err.code === 'model_unavailable') {
|
|
304
|
+
console.log(`\n${YELLOW}⚠${RST} That model is not available. Run /models to see options.`)
|
|
305
|
+
}
|
|
306
|
+
messages.pop()
|
|
307
|
+
} else {
|
|
308
|
+
process.stdout.write(`${RED} Connection error: ${err.message}${RST}`)
|
|
309
|
+
messages.pop()
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
if (reply) {
|
|
314
|
+
messages.push({ role: 'assistant', content: reply })
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
console.log()
|
|
318
|
+
if (spent > 0) {
|
|
319
|
+
console.log(`${DIM} ${spent} credits · ${credits ?? '?'} remaining${RST}`)
|
|
320
|
+
}
|
|
321
|
+
console.log()
|
|
322
|
+
rl.resume()
|
|
323
|
+
rl.prompt()
|
|
324
|
+
}
|
|
325
|
+
}
|
package/lib/config.mjs
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync, chmodSync } from 'node:fs'
|
|
2
|
+
import { homedir } from 'node:os'
|
|
3
|
+
import { join } from 'node:path'
|
|
4
|
+
|
|
5
|
+
const DIR = join(homedir(), '.noguard')
|
|
6
|
+
const FILE = join(DIR, 'config.json')
|
|
7
|
+
|
|
8
|
+
function ensureDir() {
|
|
9
|
+
if (!existsSync(DIR)) mkdirSync(DIR, { recursive: true, mode: 0o700 })
|
|
10
|
+
try { chmodSync(DIR, 0o700) } catch { /* windows may not support posix perms */ }
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function load() {
|
|
14
|
+
try {
|
|
15
|
+
return JSON.parse(readFileSync(FILE, 'utf-8'))
|
|
16
|
+
} catch {
|
|
17
|
+
return {}
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function save(data) {
|
|
22
|
+
ensureDir()
|
|
23
|
+
writeFileSync(FILE, JSON.stringify(data, null, 2) + '\n', { encoding: 'utf-8', mode: 0o600 })
|
|
24
|
+
try { chmodSync(FILE, 0o600) } catch { /* windows may not support posix perms */ }
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function getToken() {
|
|
28
|
+
return load().token ?? null
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function setToken(token, account) {
|
|
32
|
+
const cfg = load()
|
|
33
|
+
cfg.token = token
|
|
34
|
+
cfg.account = account
|
|
35
|
+
save(cfg)
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function clearToken() {
|
|
39
|
+
const cfg = load()
|
|
40
|
+
delete cfg.token
|
|
41
|
+
delete cfg.account
|
|
42
|
+
save(cfg)
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function getEndpoint() {
|
|
46
|
+
return load().endpoint ?? 'https://noguard.ai'
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function setEndpoint(url) {
|
|
50
|
+
const cfg = load()
|
|
51
|
+
cfg.endpoint = url.replace(/\/+$/, '')
|
|
52
|
+
save(cfg)
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function configPath() {
|
|
56
|
+
return FILE
|
|
57
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,23 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "noguard",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "NoGuard AI — the AI that doesn't say no. Chat from your terminal.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"noguard": "bin/noguard.mjs"
|
|
8
|
+
},
|
|
9
|
+
"files": [
|
|
10
|
+
"bin/",
|
|
11
|
+
"lib/"
|
|
12
|
+
],
|
|
13
|
+
"keywords": [
|
|
14
|
+
"noguard",
|
|
15
|
+
"ai",
|
|
16
|
+
"cli",
|
|
17
|
+
"chat"
|
|
18
|
+
],
|
|
19
|
+
"license": "UNLICENSED",
|
|
20
|
+
"engines": {
|
|
21
|
+
"node": ">=18"
|
|
22
|
+
}
|
|
23
|
+
}
|
package/README.md
DELETED