codefission 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.
File without changes
@@ -0,0 +1,5 @@
1
+ """Allow running as `python -m codefission`."""
2
+
3
+ from codefission.cli import main
4
+
5
+ main()
codefission/cli.py ADDED
@@ -0,0 +1,20 @@
1
+ """CLI entry point for CodeFission."""
2
+
3
+ import sys
4
+
5
+ import uvicorn
6
+
7
+
8
+ def main():
9
+ port = int(sys.argv[1]) if len(sys.argv) > 1 else 8080
10
+ uvicorn.run(
11
+ "codefission.main:app",
12
+ host="0.0.0.0",
13
+ port=port,
14
+ ws_ping_interval=30,
15
+ ws_ping_timeout=10,
16
+ )
17
+
18
+
19
+ if __name__ == "__main__":
20
+ main()
codefission/config.py ADDED
@@ -0,0 +1,29 @@
1
+ import json
2
+ import os
3
+ from pathlib import Path
4
+
5
+ # Fixed location for the bootstrap config (read before DB exists)
6
+ CONFIG_FILE = Path.home() / ".codefission.json"
7
+
8
+ def _load_config() -> dict:
9
+ if CONFIG_FILE.exists():
10
+ try:
11
+ return json.loads(CONFIG_FILE.read_text())
12
+ except Exception:
13
+ pass
14
+ return {}
15
+
16
+ def save_config(updates: dict):
17
+ """Merge updates into the config file."""
18
+ cfg = _load_config()
19
+ cfg.update(updates)
20
+ CONFIG_FILE.write_text(json.dumps(cfg, indent=2) + "\n")
21
+
22
+ _cfg = _load_config()
23
+
24
+ # Data directory: config file > env var > default
25
+ DATA_DIR = Path(
26
+ _cfg.get("data_dir")
27
+ or os.environ.get("CODEFISSION_DATA_DIR")
28
+ or str(Path.home() / ".codefission")
29
+ )
codefission/db.py ADDED
@@ -0,0 +1,116 @@
1
+ import aiosqlite
2
+ from pathlib import Path
3
+ from contextlib import asynccontextmanager
4
+
5
+ from models import DEFAULT_PROVIDER, DEFAULT_MODEL
6
+ from config import DATA_DIR
7
+
8
+ DB_PATH = DATA_DIR / "codefission.db"
9
+
10
+ _conn: aiosqlite.Connection | None = None
11
+
12
+
13
+ async def _open_connection() -> aiosqlite.Connection:
14
+ DB_PATH.parent.mkdir(parents=True, exist_ok=True)
15
+ db = await aiosqlite.connect(str(DB_PATH))
16
+ db.row_factory = aiosqlite.Row
17
+ await db.execute("PRAGMA journal_mode=WAL")
18
+ await db.execute("PRAGMA foreign_keys=ON")
19
+ return db
20
+
21
+
22
+ @asynccontextmanager
23
+ async def get_db():
24
+ global _conn
25
+ if _conn is None:
26
+ _conn = await _open_connection()
27
+ yield _conn
28
+
29
+
30
+ async def close_db():
31
+ global _conn
32
+ if _conn is not None:
33
+ await _conn.close()
34
+ _conn = None
35
+
36
+
37
+ async def init_db():
38
+ global _conn
39
+ # Close existing connection (e.g. tests changing DB_PATH)
40
+ if _conn is not None:
41
+ await _conn.close()
42
+ _conn = None
43
+
44
+ async with get_db() as db:
45
+ await db.executescript("""
46
+ CREATE TABLE IF NOT EXISTS trees (
47
+ id TEXT PRIMARY KEY,
48
+ name TEXT NOT NULL,
49
+ created_at TEXT NOT NULL
50
+ );
51
+ CREATE TABLE IF NOT EXISTS nodes (
52
+ id TEXT PRIMARY KEY,
53
+ tree_id TEXT NOT NULL REFERENCES trees(id),
54
+ parent_id TEXT REFERENCES nodes(id),
55
+ user_message TEXT NOT NULL DEFAULT '',
56
+ assistant_response TEXT NOT NULL DEFAULT '',
57
+ label TEXT NOT NULL DEFAULT '',
58
+ status TEXT NOT NULL DEFAULT 'idle',
59
+ created_at TEXT NOT NULL
60
+ );
61
+ CREATE TABLE IF NOT EXISTS settings (
62
+ key TEXT PRIMARY KEY,
63
+ value TEXT
64
+ );
65
+ CREATE INDEX IF NOT EXISTS idx_nodes_tree ON nodes(tree_id);
66
+ CREATE INDEX IF NOT EXISTS idx_nodes_parent ON nodes(parent_id);
67
+ """)
68
+
69
+ # Migrate: add provider/model columns to trees if missing
70
+ cursor = await db.execute("PRAGMA table_info(trees)")
71
+ columns = {row[1] for row in await cursor.fetchall()}
72
+ if "provider" not in columns:
73
+ await db.execute(
74
+ f"ALTER TABLE trees ADD COLUMN provider TEXT NOT NULL DEFAULT '{DEFAULT_PROVIDER}'"
75
+ )
76
+ if "model" not in columns:
77
+ await db.execute(
78
+ f"ALTER TABLE trees ADD COLUMN model TEXT NOT NULL DEFAULT '{DEFAULT_MODEL}'"
79
+ )
80
+
81
+ # Migrate: add repo_mode, repo_source to trees
82
+ if "repo_mode" not in columns:
83
+ await db.execute("ALTER TABLE trees ADD COLUMN repo_mode TEXT NOT NULL DEFAULT 'none'")
84
+ if "repo_source" not in columns:
85
+ await db.execute("ALTER TABLE trees ADD COLUMN repo_source TEXT")
86
+
87
+ # Migrate: add max_turns to trees
88
+ if "max_turns" not in columns:
89
+ await db.execute("ALTER TABLE trees ADD COLUMN max_turns INTEGER")
90
+
91
+ # Migrate: add skill to trees
92
+ if "skill" not in columns:
93
+ await db.execute("ALTER TABLE trees ADD COLUMN skill TEXT NOT NULL DEFAULT ''")
94
+
95
+ # Migrate: add notes to trees
96
+ if "notes" not in columns:
97
+ await db.execute("ALTER TABLE trees ADD COLUMN notes TEXT NOT NULL DEFAULT '[]'")
98
+
99
+ # Migrate: rename provider "anthropic" → "claude-code"
100
+ await db.execute("UPDATE trees SET provider = 'claude-code' WHERE provider = 'anthropic'")
101
+
102
+ # Migrate: add git_branch, git_commit to nodes
103
+ cursor2 = await db.execute("PRAGMA table_info(nodes)")
104
+ node_columns = {row[1] for row in await cursor2.fetchall()}
105
+ if "git_branch" not in node_columns:
106
+ await db.execute("ALTER TABLE nodes ADD COLUMN git_branch TEXT")
107
+ if "git_commit" not in node_columns:
108
+ await db.execute("ALTER TABLE nodes ADD COLUMN git_commit TEXT")
109
+ if "session_id" not in node_columns:
110
+ await db.execute("ALTER TABLE nodes ADD COLUMN session_id TEXT")
111
+ if "created_by" not in node_columns:
112
+ await db.execute("ALTER TABLE nodes ADD COLUMN created_by TEXT NOT NULL DEFAULT 'human'")
113
+ if "quoted_node_ids" not in node_columns:
114
+ await db.execute("ALTER TABLE nodes ADD COLUMN quoted_node_ids TEXT NOT NULL DEFAULT '[]'")
115
+
116
+ await db.commit()
codefission/events.py ADDED
@@ -0,0 +1,103 @@
1
+ """Async event bus for decoupled communication between services and WebSocket layer.
2
+
3
+ Adapted from WhatTheBot's core/events.py — same pub/sub pattern, CodeFission-specific events.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import asyncio
9
+ from collections import defaultdict
10
+ from typing import Any, Callable, Coroutine
11
+
12
+ Callback = Callable[..., Coroutine[Any, Any, None]]
13
+
14
+
15
+ class EventBus:
16
+ def __init__(self) -> None:
17
+ self._listeners: dict[str, list[Callback]] = defaultdict(list)
18
+
19
+ def on(self, event: str, callback: Callback) -> None:
20
+ self._listeners[event].append(callback)
21
+
22
+ def off(self, event: str, callback: Callback) -> None:
23
+ self._listeners[event] = [
24
+ cb for cb in self._listeners[event] if cb is not callback
25
+ ]
26
+
27
+ async def emit(self, event: str, **kwargs: Any) -> None:
28
+ for cb in list(self._listeners.get(event, [])):
29
+ asyncio.create_task(cb(**kwargs))
30
+
31
+
32
+ # Singleton bus
33
+ bus = EventBus()
34
+
35
+
36
+ # ── Well-known event names (internal, backend-side) ─────────────────────
37
+
38
+ STREAM_START = "stream_start" # chat streaming begins for a node
39
+ STREAM_DELTA = "stream_delta" # new token(s) in a streaming response
40
+ STREAM_END = "stream_end" # chat streaming finished
41
+ STREAM_ERROR = "stream_error" # chat streaming hit an error
42
+ NODE_CREATED = "node_created" # a new node was created
43
+ NODE_UPDATED = "node_updated" # a node's data changed
44
+ TREE_CREATED = "tree_created" # a new tree was created
45
+ TREE_DELETED = "tree_deleted" # a tree was deleted
46
+
47
+
48
+ # ── WebSocket message types (wire protocol, client ↔ server) ───────────
49
+
50
+ class WS:
51
+ """Structured constants for WebSocket JSON message types.
52
+
53
+ Inbound = client → server requests
54
+ Outbound = server → client responses/pushes
55
+ """
56
+
57
+ # Inbound (client → server)
58
+ LIST_TREES = "list_trees"
59
+ CREATE_TREE = "create_tree"
60
+ LOAD_TREE = "load_tree"
61
+ DELETE_TREE = "delete_tree"
62
+ BRANCH = "branch"
63
+ CHAT = "chat"
64
+ CANCEL = "cancel"
65
+ DUPLICATE = "duplicate"
66
+ GET_NODE = "get_node"
67
+ SET_REPO = "set_repo"
68
+ GET_NODE_FILES = "get_node_files"
69
+ GET_NODE_DIFF = "get_node_diff"
70
+ GET_FILE_CONTENT = "get_file_content"
71
+ SELECT_TREE = "select_tree"
72
+ SET_EXPANDED = "set_expanded"
73
+ SET_SUBTREE_COLLAPSED = "set_subtree_collapsed"
74
+ GET_SETTINGS = "get_settings"
75
+ UPDATE_GLOBAL_SETTINGS = "update_global_settings"
76
+ UPDATE_TREE_SETTINGS = "update_tree_settings"
77
+ GET_NODE_PROCESSES = "get_node_processes"
78
+ KILL_PROCESS = "kill_process"
79
+ KILL_ALL_PROCESSES = "kill_all_processes"
80
+ DELETE_NODE = "delete_node"
81
+
82
+ # Outbound
83
+ SETTINGS = "settings"
84
+
85
+ # Outbound (server → client)
86
+ TREES = "trees"
87
+ TREE_CREATED = "tree_created"
88
+ TREE_LOADED = "tree_loaded"
89
+ TREE_DELETED = "tree_deleted"
90
+ TREE_UPDATED = "tree_updated"
91
+ NODE_CREATED = "node_created"
92
+ NODE_DATA = "node_data"
93
+ NODE_FILES = "node_files"
94
+ NODE_DIFF = "node_diff"
95
+ FILE_CONTENT = "file_content"
96
+ STATUS = "status"
97
+ CHUNK = "chunk"
98
+ TOOL_START = "tool_start"
99
+ TOOL_END = "tool_end"
100
+ DONE = "done"
101
+ ERROR = "error"
102
+ NODE_PROCESSES = "node_processes"
103
+ NODES_DELETED = "nodes_deleted"