haillo 0.1.0__py3-none-any.whl

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.
haillo/__init__.py ADDED
@@ -0,0 +1,4 @@
1
+ import sys
2
+ from . import config
3
+
4
+ sys.path.insert(0, config.root)
haillo/__main__.py ADDED
@@ -0,0 +1,68 @@
1
+ from subprocess import call
2
+
3
+ import sys
4
+
5
+ from . import package
6
+ from . import config
7
+ from . import hutils
8
+
9
+
10
+ def main():
11
+ if len(sys.argv) == 2:
12
+
13
+ if sys.argv[1] == "--version":
14
+ show_dependencies()
15
+
16
+ elif sys.argv[1] == "help":
17
+ display_man_page(config.manpage_path)
18
+ sys.exit(0)
19
+
20
+ elif sys.argv[1] == "path":
21
+ print(config.root)
22
+ sys.exit(0)
23
+
24
+ elif sys.argv[1] == "run":
25
+ print('gunicorn --preload --workers=4 --threads=100 -b 127.0.0.1:8000 --chdir `haillo path` "haillo:webapp()"')
26
+ # print('waitress-serve --listen=127.0.0.1:8000 --threads=100 haillo:app')
27
+ # print('gunicorn --workers=1 --threads=100 --timeout=30 --keep-alive=5 --graceful-timeout=10 -b 127.0.0.1:8000 "haillo:webapp()"')
28
+ # print('waitress-serve --max-request-header-size=262144 --clear-untrusted-proxy-headers --listen=127.0.0.1:8000 --channel-timeout=30 --asyncore-use-poll --cleanup-interval=5 haillo:app')
29
+ sys.exit(0)
30
+
31
+ else:
32
+ help()
33
+
34
+ else:
35
+ help()
36
+
37
+ def show_dependencies():
38
+ def parse_dependency(dep_string):
39
+ # Common version specifiers
40
+ specifiers = ['==', '>=', '<=', '~=', '>', '<', '!=']
41
+
42
+ # Find the first matching specifier
43
+ for specifier in specifiers:
44
+ if specifier in dep_string:
45
+ name, version = dep_string.split(specifier, 1)
46
+ return name.strip(), specifier, version.strip()
47
+
48
+ # If no specifier found, return just the name
49
+ return dep_string.strip(), '', ''
50
+
51
+ dependencies = ""
52
+ for dep in package.dependencies:
53
+ name, specifier, version = parse_dependency(dep)
54
+ if version: # Only add separator if there's a version
55
+ dependencies += f" {name}/{version}"
56
+ else:
57
+ dependencies += f" {name}"
58
+
59
+ print(f"haillo/{package.__version__}{dependencies}")
60
+
61
+ def help():
62
+ hutils.eprint("for help, use:\n")
63
+ hutils.eprint(" haillo help")
64
+ sys.exit(2)
65
+
66
+ # displays a man page (file) located on a given path
67
+ def display_man_page(path):
68
+ call(["man", path])
haillo/config.py ADDED
@@ -0,0 +1,8 @@
1
+ import sys
2
+ import os
3
+ import importlib
4
+ import inspect
5
+
6
+ root = os.path.dirname(inspect.getfile(lambda: None))
7
+ manpage_path = root + "/data/haillo.1"
8
+ webapp_root = root + "/templates/"
haillo/data/haillo.1 ADDED
@@ -0,0 +1,33 @@
1
+ .TH HAILLO 1 "FEBRUARY 2025" Linux "User Manuals"
2
+ .SH NAME
3
+ Haillo \- a web frontend for hai (hcli_hai), the command line AI chat application.
4
+ .SH SYNOPSIS
5
+ .B haillo
6
+ [
7
+ .I option
8
+ |
9
+ .I <command>
10
+ ]
11
+ .SH DESCRIPTION
12
+ .B haillo
13
+ is a Web Service Gateway Interface (WSGI; PEP 3333) application and progressive web app (PWA) that provides a way to interact with the hai command line chat application.
14
+ .br
15
+ Note that huckle must be setup to interact with hcli_hai for haillo to be able to make use of it (e.g. huckle cli install localhost:10000 (where hcli_hai could be running))
16
+
17
+ .SH COMMANDS
18
+ .IP "path"
19
+ Provides the installation path of haillo, which can be used to help locate the path of the WSGI app to use in a WSGI server.
20
+ .IP help
21
+ This help file.
22
+ .SH OPTIONS
23
+ .IP --version
24
+ .B haillo
25
+ version and the version of it's dependencies.
26
+ .SH EXAMPLE
27
+ haillo path
28
+
29
+ haillo --version
30
+
31
+ haillo run | bash
32
+
33
+ gunicorn --preload --workers=4 --threads=100 -b 127.0.0.1:8000 --chdir `haillo path` "haillo:webapp()"
haillo/haillo.py ADDED
@@ -0,0 +1,231 @@
1
+ import flask
2
+ import config
3
+ import json
4
+ import logger
5
+ import sys
6
+ import io
7
+ import traceback
8
+ import contextlib
9
+ import urllib3
10
+ import time
11
+ from huckle import cli, stdin
12
+ from flask import Flask, render_template, send_file, jsonify, Response, redirect, url_for, request
13
+ import subprocess
14
+ import shlex
15
+ import ast
16
+
17
+ logging = logger.Logger()
18
+ logging.setLevel(logger.INFO)
19
+
20
+ app = None
21
+
22
+
23
+ def get_chat_list():
24
+ try:
25
+ chunks = cli("hai ls")
26
+ json_string = ""
27
+ for dest, chunk in chunks:
28
+ if dest == 'stdout':
29
+ json_string += chunk.decode()
30
+ chats = json.loads(json_string)
31
+ # Sort the list with most recent dates first
32
+ sorted_chats = sorted(chats, key=lambda x: x['update_time'], reverse=True)
33
+ return sorted_chats
34
+ except Exception as error:
35
+ logging.error(f"Error getting chat list: {error}")
36
+ return []
37
+
38
+ def parse_context(context_str):
39
+ try:
40
+ context_data = json.loads(context_str)
41
+ return {
42
+ 'messages': context_data.get('messages', []),
43
+ 'name': context_data.get('name', ''),
44
+ 'title': context_data.get('title', '')
45
+ }
46
+ except json.JSONDecodeError as e:
47
+ logging.error(f"Error parsing context JSON: {e}")
48
+ return {'messages': [], 'name': '', 'title': ''}
49
+
50
+ def webapp():
51
+ ################################################ CRITICAL ################################################
52
+ # This ensures a clean stdin state before workers fork.
53
+ # Without this, flask/gunicorn can hand off an inconsistent stdin state to huckle which causes
54
+ # Huckle to attempt to stream data when there is none to stream, leading to unexpected stream interruption
55
+ # socket closeout in urllib3's pool and bad file descriptor errors.
56
+ ##########################################################################################################
57
+ if not sys.stdin.isatty():
58
+ sys.stdin = io.BytesIO()
59
+
60
+ app = Flask(__name__)
61
+
62
+ @app.route('/')
63
+ def index():
64
+ try:
65
+ # Get the current context
66
+ chunks = cli("hai context")
67
+ context_str = ""
68
+ for dest, chunk in chunks:
69
+ if dest == 'stdout':
70
+ context_str += chunk.decode()
71
+
72
+ # Get chat list for sidebar
73
+ chats = get_chat_list()
74
+
75
+ # Get model in use
76
+ chunks = cli(f"hai model")
77
+ model = ""
78
+ for dest, chunk in chunks: # Now unpacking tuple of (dest, chunk)
79
+ if dest == 'stdout':
80
+ model += chunk.decode()
81
+
82
+ # Get model in use
83
+ chunks = cli(f"hai model ls")
84
+ models = ""
85
+ for dest, chunk in chunks: # Now unpacking tuple of (dest, chunk)
86
+ if dest == 'stdout':
87
+ models += chunk.decode()
88
+
89
+ # Convert to a python list
90
+ models = ast.literal_eval(models)
91
+
92
+ # Parse the context into structured data
93
+ context_data = parse_context(context_str)
94
+
95
+ return render_template('index.html',
96
+ messages=context_data['messages'],
97
+ name=context_data['name'],
98
+ title=context_data['title'],
99
+ chats=chats,
100
+ model=model,
101
+ models=models)
102
+ except Exception as error:
103
+ logging.error(traceback.format_exc())
104
+ return render_template('index.html',
105
+ messages=[],
106
+ name='',
107
+ title='',
108
+ chats=[],
109
+ model=None,
110
+ models=[])
111
+
112
+ @app.route('/chat_history')
113
+ def chat_history():
114
+ try:
115
+ # Get chat list for sidebar
116
+ chats = get_chat_list()
117
+
118
+ # Get model in use
119
+ chunks = cli(f"hai model")
120
+ model = ""
121
+ for dest, chunk in chunks: # Now unpacking tuple of (dest, chunk)
122
+ if dest == 'stdout':
123
+ model += chunk.decode()
124
+
125
+ # Get model in use
126
+ chunks = cli(f"hai model ls")
127
+ models = ""
128
+ for dest, chunk in chunks: # Now unpacking tuple of (dest, chunk)
129
+ if dest == 'stdout':
130
+ models += chunk.decode()
131
+
132
+ # Convert to a python list
133
+ models = ast.literal_eval(models)
134
+
135
+ return render_template('chat_history.html', chats=chats,
136
+ model=model,
137
+ models=models)
138
+ except Exception as error:
139
+ logging.error(traceback.format_exc())
140
+ return render_template('chat_history.html', chats=[],
141
+ model=None,
142
+ models=[])
143
+
144
+ # We select and set a chat context
145
+ @app.route('/context/<context_id>')
146
+ def navigate_context(context_id):
147
+ try:
148
+ # Execute hai set
149
+ cmd_start = time.time()
150
+ chunks = cli(f"hai set {context_id}")
151
+ chunk_count = 0
152
+ for dest, chunk in chunks:
153
+ chunk_count += 1
154
+
155
+
156
+ return redirect(url_for('index'))
157
+ except Exception as error:
158
+ logging.error(f"Context switch failed: {error}")
159
+ logging.error(traceback.format_exc())
160
+ return redirect(url_for('index'))
161
+
162
+ # We delete a chat context with hai rm
163
+ @app.route('/context/<context_id>', methods=['POST'])
164
+ def delete_context(context_id):
165
+ try:
166
+ chunks = cli(f"hai rm {context_id}")
167
+ chunk_count = 0
168
+ for dest, chunk in chunks:
169
+ chunk_count += 1
170
+ return redirect(url_for('index'))
171
+ except Exception as error:
172
+ logging.error(f"Context deletion failed: {error}")
173
+ logging.error(traceback.format_exc())
174
+ return redirect(url_for('index'))
175
+
176
+ # We stream chat data to hai
177
+ @app.route('/chat', methods=['POST'])
178
+ def chat():
179
+ try:
180
+ message = request.form.get('message')
181
+ stream = io.BytesIO(message.encode('utf-8'))
182
+ with stdin(stream):
183
+ chunks = cli(f"hai")
184
+ chunk_count = 0
185
+ for dest, chunk in chunks:
186
+ chunk_count += 1
187
+ return redirect(url_for('index'))
188
+ except Exception as error:
189
+ logging.error(f"Context switch failed: {error}")
190
+ logging.error(traceback.format_exc())
191
+ return redirect(url_for('index'))
192
+
193
+ # We set the model with hai model set
194
+ @app.route('/set_model', methods=['POST'])
195
+ def set_model():
196
+ try:
197
+ model = request.form.get('model')
198
+ chunks = cli(f"hai model set {model}")
199
+ for dest, chunk in chunks:
200
+ chunk_count += 1
201
+ return redirect(url_for('index'))
202
+ except Exception as error:
203
+ logging.error(f"Model switch failed: {error}")
204
+ logging.error(traceback.format_exc())
205
+ return redirect(url_for('index'))
206
+
207
+ # We create a new hai chat context with hai new
208
+ @app.route('/new_chat', methods=['POST'])
209
+ def new_chat():
210
+ try:
211
+ chunks = cli("hai new")
212
+ for dest, chunk in chunks:
213
+ pass
214
+
215
+ return redirect(url_for('index'))
216
+ except Exception as error:
217
+ logging.error(f"New chat creation failed: {error}")
218
+ logging.error(traceback.format_exc())
219
+ return redirect(url_for('index'))
220
+
221
+ @app.route('/manifest.json')
222
+ def serve_manifest():
223
+ return app.send_static_file('manifest.json')
224
+
225
+ @app.route('/sw.js')
226
+ def serve_sw():
227
+ return app.send_static_file('sw.js')
228
+
229
+ return app
230
+
231
+ app = webapp()
haillo/hutils.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ # helps with printing error messages to STDERR
4
+ def eprint(*args, **kwargs):
5
+ print(*args, file=sys.stderr, **kwargs)
haillo/logger.py ADDED
@@ -0,0 +1,96 @@
1
+ import logging
2
+ import traceback
3
+ import os
4
+ import io
5
+ import datetime
6
+ import threading
7
+ import collections
8
+
9
+ DEBUG = logging.DEBUG
10
+ INFO = logging.INFO
11
+ WARNING = logging.WARNING
12
+ ERROR = logging.ERROR
13
+ CRITICAL = logging.CRITICAL
14
+
15
+ # custom deque implementation to have log line limits as a sliding window that behaves like a stream being consumed when read.
16
+ class DequeHandler(logging.Handler):
17
+ def __init__(self, *args, **kwargs):
18
+ super().__init__(*args, **kwargs)
19
+ self.deque = collections.deque(maxlen=100)
20
+
21
+ def emit(self, record):
22
+ log_entry = self.format(record)
23
+ self.deque.append(log_entry)
24
+
25
+ def read_and_clear(self):
26
+ logs = list(self.deque)
27
+ self.deque.clear()
28
+ return logs
29
+
30
+ # custom logger implementation that allows for streaming to stdout and tailing of logs per a deque sliding window.
31
+ class Logger:
32
+ instance = None
33
+ streamHandler = None
34
+ clientHandler = None
35
+ initialized = False
36
+ lock = threading.Lock()
37
+
38
+ def __new__(self, *args, **kwargs):
39
+ with Logger.lock:
40
+ if Logger.instance is None:
41
+ Logger.instance = super().__new__(self, *args, **kwargs)
42
+ return Logger.instance
43
+
44
+ def __init__(self, *args, **kwargs):
45
+ with self.lock:
46
+ if not self.initialized:
47
+ self.instance = logging.getLogger("crumbs")
48
+
49
+ date_format = "%Y-%m-%d %H:%M:%S %z"
50
+ message_format = "[%(asctime)s] [%(levelname)-5s] [%(filename)13s:%(lineno)-3s] %(message)s"
51
+
52
+ formatter = logging.Formatter(fmt=message_format, datefmt=date_format)
53
+
54
+ # Check for existing StreamHandler to avoid duplicates
55
+ if not any(isinstance(h, logging.StreamHandler) for h in self.instance.handlers):
56
+ self.streamHandler = logging.StreamHandler()
57
+ self.streamHandler.setFormatter(formatter)
58
+ self.instance.addHandler(self.streamHandler)
59
+
60
+ # Check for existing DequeHandler to avoid duplicates
61
+ if not any(isinstance(h, DequeHandler) for h in self.instance.handlers):
62
+ self.clientHandler = DequeHandler()
63
+ self.clientHandler.setFormatter(formatter)
64
+ self.instance.addHandler(self.clientHandler)
65
+
66
+ self.instance.propagate = False
67
+
68
+ self.initialized = True
69
+
70
+ def setLevel(self, level):
71
+ logging.getLogger("crumbs").setLevel(level)
72
+ return
73
+
74
+ def info(self, msg, *args, **kwargs):
75
+ self.instance.info(msg, *args, stacklevel=2, **kwargs)
76
+
77
+ def debug(self, msg, *args, **kwargs):
78
+ self.instance.debug(msg, *args, stacklevel=2, **kwargs)
79
+
80
+ def warning(self, msg, *args, **kwargs):
81
+ self.instance.warning(msg, *args, stacklevel=2, **kwargs)
82
+
83
+ def error(self, msg, *args, **kwargs):
84
+ self.instance.error(msg, *args, stacklevel=2, **kwargs)
85
+
86
+ def critical(self, msg, *args, **kwargs):
87
+ self.instance.critical(msg, *args, stacklevel=2, **kwargs)
88
+
89
+ def tail(self):
90
+ log_entries = self.clientHandler.read_and_clear()
91
+ log_text = '\n'.join(log_entries)
92
+
93
+ if log_text:
94
+ log_text += '\n' # Adds newline character at the end if there is some log_text
95
+
96
+ return log_text.encode('utf-8')
haillo/package.py ADDED
@@ -0,0 +1,6 @@
1
+ from __future__ import absolute_import, division, print_function
2
+
3
+ __version__ = "0.1.0"
4
+ dependencies = ["flask==3.0.1",
5
+ "huckle>=5.5.4",
6
+ "hcli_hai>=2.1.3"]
@@ -0,0 +1,146 @@
1
+ * {
2
+ box-sizing: border-box;
3
+ margin: 0;
4
+ padding: 0;
5
+ }
6
+
7
+ body {
8
+ font-family: Arial, sans-serif;
9
+ line-height: 1.6;
10
+ }
11
+
12
+ .container {
13
+ display: flex;
14
+ min-height: 100vh;
15
+ }
16
+
17
+ /* Main content area */
18
+ .main-content {
19
+ flex: 1;
20
+ padding: 10px 100px 80px 200px;
21
+ margin-left: 0;
22
+ overflow-y: auto;
23
+ }
24
+
25
+ /* Message styles */
26
+ .message {
27
+ margin-bottom: 15px;
28
+ padding: 12px 15px;
29
+ border-radius: 8px;
30
+ max-width: 100%;
31
+ }
32
+
33
+ .user {
34
+ background-color: #e3f2fd;
35
+ color: #1a1a1a;
36
+ }
37
+
38
+ .assistant {
39
+ background-color: #f8f9fa;
40
+ color: #1a1a1a;
41
+ }
42
+
43
+ .system {
44
+ background-color: #fff3e0;
45
+ margin: 15px auto;
46
+ }
47
+
48
+ .message-role {
49
+ font-weight: bold;
50
+ margin-bottom: 5px;
51
+ color: #666;
52
+ font-size: 0.9em;
53
+ }
54
+
55
+ .message-content {
56
+ white-space: pre-wrap;
57
+ word-wrap: break-word;
58
+ }
59
+
60
+ /* Input area styles */
61
+ .input-container {
62
+ position: fixed;
63
+ bottom: 0;
64
+ left: 200px;
65
+ right: 100px;
66
+ background-color: #fff;
67
+ padding: 15px 0;
68
+ }
69
+
70
+ .input-wrapper {
71
+ display: flex;
72
+ gap: 10px;
73
+ margin-bottom: 5px;
74
+ }
75
+
76
+ .chat-input {
77
+ flex-grow: 1;
78
+ padding: 10px;
79
+ border: 1px solid #dee2e6;
80
+ border-radius: 4px;
81
+ font-family: inherit;
82
+ resize: none;
83
+ min-height: 44px;
84
+ max-height: 200px;
85
+ overflow-y: auto;
86
+ }
87
+
88
+ .send-button {
89
+ padding: 10px 20px;
90
+ background-color: #0066cc;
91
+ color: white;
92
+ border: none;
93
+ border-radius: 4px;
94
+ cursor: pointer;
95
+ font-size: 1em;
96
+ }
97
+
98
+ .send-button:hover {
99
+ background-color: #0052a3;
100
+ }
101
+
102
+ .model-display {
103
+ color: #666;
104
+ font-size: 0.85em;
105
+ text-align: right;
106
+ padding-top: 5px;
107
+ }
108
+
109
+ /* Code block styles */
110
+ .message-content pre {
111
+ background-color: #1a1a2e;
112
+ border-radius: 4px;
113
+ padding: 15px;
114
+ margin: 10px 0;
115
+ overflow-x: auto;
116
+ font-family: 'Consolas', 'Monaco', 'Andale Mono', monospace;
117
+ font-size: 0.9em;
118
+ line-height: 1.4;
119
+ box-shadow: 0 2px 4px rgba(0,0,0,0.1);
120
+ border: 1px solid #2a2a4e;
121
+ }
122
+
123
+ .message-content code {
124
+ background-color: #1a1a2e;
125
+ color: #e0e0e0;
126
+ padding: 0.2em 0.4em;
127
+ border-radius: 3px;
128
+ font-family: 'Consolas', 'Monaco', 'Andale Mono', monospace;
129
+ font-size: 0.9em;
130
+ }
131
+
132
+ .message-content pre code {
133
+ padding: 0;
134
+ background-color: transparent;
135
+ color: inherit;
136
+ }
137
+
138
+ /* Create a scrollable area for messages */
139
+ .messages-container {
140
+ flex-grow: 1;
141
+ overflow-y: auto;
142
+ padding: 20px;
143
+ padding-bottom: 20px;
144
+ /* Ensure content doesn't go behind input */
145
+ margin-bottom: 20px;
146
+ }
@@ -0,0 +1,59 @@
1
+ document.querySelector('.chat-input').addEventListener('input', function() {
2
+ this.style.height = 'auto';
3
+ this.style.height = (this.scrollHeight) + 'px';
4
+ });
5
+
6
+ function formatCodeBlocks() {
7
+ const messages = document.querySelectorAll('.message-content');
8
+ messages.forEach(message => {
9
+ if (!message.dataset.formatted) {
10
+ const content = message.innerHTML;
11
+ let result = '';
12
+ let codeBlock = '';
13
+ let language = '';
14
+ let isInCodeBlock = false;
15
+
16
+ const lines = content.split('\n');
17
+ for (let i = 0; i < lines.length; i++) {
18
+ const line = lines[i];
19
+ if (line.trim().startsWith('```')) {
20
+ if (!isInCodeBlock) {
21
+ isInCodeBlock = true;
22
+ language = line.trim().slice(3).trim();
23
+ codeBlock = '';
24
+ } else {
25
+ isInCodeBlock = false;
26
+ // Removed 'line-numbers' class
27
+ result += `<pre><code class="language-${language || 'plaintext'}">${codeBlock.trim()}</code></pre>\n`;
28
+ }
29
+ } else {
30
+ if (isInCodeBlock) {
31
+ codeBlock += line + '\n';
32
+ } else {
33
+ result += line + '\n';
34
+ }
35
+ }
36
+ }
37
+ message.innerHTML = result;
38
+ message.dataset.formatted = 'true';
39
+ Prism.highlightAllUnder(message);
40
+ }
41
+ });
42
+ }
43
+
44
+ document.addEventListener('DOMContentLoaded', formatCodeBlocks);
45
+
46
+ const observer = new MutationObserver((mutations) => {
47
+ mutations.forEach((mutation) => {
48
+ if (mutation.addedNodes.length) {
49
+ formatCodeBlocks();
50
+ }
51
+ });
52
+ });
53
+
54
+ document.addEventListener('DOMContentLoaded', () => {
55
+ observer.observe(document.querySelector('.main-content'), {
56
+ childList: true,
57
+ subtree: true
58
+ });
59
+ });
Binary file
@@ -0,0 +1,17 @@
1
+ {
2
+ "name": "Haillo",
3
+ "short_name": "Haillo",
4
+ "start_url": "/",
5
+ "scope": "/",
6
+ "display": "standalone",
7
+ "theme_color": "#317EFB",
8
+ "background_color": "#317EFB",
9
+ "icons": [
10
+ {
11
+ "src": "/static/icons/icon_144x144.png",
12
+ "sizes": "144x144",
13
+ "type": "image/png",
14
+ "purpose": "any maskable"
15
+ }
16
+ ]
17
+ }