maki-cortex 0.0.1__tar.gz

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.
@@ -0,0 +1,207 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[codz]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py.cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # UV
98
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ #uv.lock
102
+
103
+ # poetry
104
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
105
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
106
+ # commonly ignored for libraries.
107
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
108
+ #poetry.lock
109
+ #poetry.toml
110
+
111
+ # pdm
112
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
113
+ # pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
114
+ # https://pdm-project.org/en/latest/usage/project/#working-with-version-control
115
+ #pdm.lock
116
+ #pdm.toml
117
+ .pdm-python
118
+ .pdm-build/
119
+
120
+ # pixi
121
+ # Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
122
+ #pixi.lock
123
+ # Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
124
+ # in the .venv directory. It is recommended not to include this directory in version control.
125
+ .pixi
126
+
127
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
128
+ __pypackages__/
129
+
130
+ # Celery stuff
131
+ celerybeat-schedule
132
+ celerybeat.pid
133
+
134
+ # SageMath parsed files
135
+ *.sage.py
136
+
137
+ # Environments
138
+ .env
139
+ .envrc
140
+ .venv
141
+ env/
142
+ venv/
143
+ ENV/
144
+ env.bak/
145
+ venv.bak/
146
+
147
+ # Spyder project settings
148
+ .spyderproject
149
+ .spyproject
150
+
151
+ # Rope project settings
152
+ .ropeproject
153
+
154
+ # mkdocs documentation
155
+ /site
156
+
157
+ # mypy
158
+ .mypy_cache/
159
+ .dmypy.json
160
+ dmypy.json
161
+
162
+ # Pyre type checker
163
+ .pyre/
164
+
165
+ # pytype static type analyzer
166
+ .pytype/
167
+
168
+ # Cython debug symbols
169
+ cython_debug/
170
+
171
+ # PyCharm
172
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
173
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
174
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
175
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
176
+ #.idea/
177
+
178
+ # Abstra
179
+ # Abstra is an AI-powered process automation framework.
180
+ # Ignore directories containing user credentials, local state, and settings.
181
+ # Learn more at https://abstra.io/docs
182
+ .abstra/
183
+
184
+ # Visual Studio Code
185
+ # Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
186
+ # that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
187
+ # and can be added to the global gitignore or merged into this file. However, if you prefer,
188
+ # you could uncomment the following to ignore the entire vscode folder
189
+ # .vscode/
190
+
191
+ # Ruff stuff:
192
+ .ruff_cache/
193
+
194
+ # PyPI configuration file
195
+ .pypirc
196
+
197
+ # Cursor
198
+ # Cursor is an AI-powered code editor. `.cursorignore` specifies files/directories to
199
+ # exclude from AI features like autocomplete and code analysis. Recommended for sensitive data
200
+ # refer to https://docs.cursor.com/context/ignore-files
201
+ .cursorignore
202
+ .cursorindexingignore
203
+
204
+ # Marimo
205
+ marimo/_static/
206
+ marimo/_lsp/
207
+ __marimo__/
@@ -0,0 +1,9 @@
1
+ # Changelog
2
+
3
+ ## [0.0.1](https://github.com/adhityaravi/maki/compare/maki-cortex-v0.0.1...maki-cortex-v0.0.1) (2026-03-28)
4
+
5
+
6
+ ### Features
7
+
8
+ * **ci:** adds relese please process ([9ffac85](https://github.com/adhityaravi/maki/commit/9ffac851b65f751ba2e4154547a8cea847b1eb54))
9
+ * v0 validating heartbeats 1-10 ([2f42a87](https://github.com/adhityaravi/maki/commit/2f42a87b843e36b8ccefc0ffe6a836306881d8d5))
@@ -0,0 +1,5 @@
1
+ Metadata-Version: 2.4
2
+ Name: maki-cortex
3
+ Version: 0.0.1
4
+ Requires-Python: >=3.12
5
+ Requires-Dist: maki-common[claude]
@@ -0,0 +1,23 @@
1
+ [project]
2
+ name = "maki-cortex"
3
+ dynamic = ["version"]
4
+ requires-python = ">=3.12"
5
+ dependencies = [
6
+ "maki-common[claude]",
7
+ ]
8
+
9
+ [project.scripts]
10
+ maki-cortex = "maki_cortex.main:cli"
11
+
12
+ [tool.uv.sources]
13
+ maki-common = { workspace = true }
14
+
15
+ [build-system]
16
+ requires = ["hatchling"]
17
+ build-backend = "hatchling.build"
18
+
19
+ [tool.hatch.version]
20
+ path = "src/maki_cortex/_version.py"
21
+
22
+ [tool.hatch.build.targets.wheel]
23
+ packages = ["src/maki_cortex"]
File without changes
@@ -0,0 +1 @@
1
+ __version__ = "0.0.1" # x-release-please-version
@@ -0,0 +1,208 @@
1
+ """maki-cortex: The Thinker. Reasoning engine backed by Claude Agent SDK.
2
+
3
+ Subscribes to turn requests via NATS, invokes Claude, publishes responses.
4
+ """
5
+
6
+ import asyncio
7
+ import json
8
+ import logging
9
+ import os
10
+ import time
11
+
12
+ from maki_common import configure_logging, connect_nats
13
+ from maki_common.claude import invoke_claude
14
+ from maki_common.health import tcp_health_server
15
+ from maki_common.subjects import CORTEX_HEALTH, CORTEX_TURN_REQUEST, CORTEX_TURN_RESPONSE
16
+
17
+ configure_logging()
18
+ log = logging.getLogger(__name__)
19
+
20
+ NATS_URL = os.environ.get("NATS_URL", "nats://maki-nerve-nats:4222")
21
+ MODEL = os.environ.get("CLAUDE_MODEL", "claude-sonnet-4-20250514")
22
+ HEALTH_PORT = int(os.environ.get("HEALTH_PORT", "8080"))
23
+
24
+ _semaphore = asyncio.Semaphore(1)
25
+
26
+
27
+ IDLE_REFLECTION_PROMPT = """## Reflection Mode
28
+
29
+ You are in idle reflection mode. There is no user message — this is your inner life.
30
+ You have context about recent memories, relationships, and your own system state.
31
+
32
+ Decide what to do with this cycle. You can:
33
+ - **Curiosity**: Research topics Adi is working on, find connections between projects
34
+ - **Care**: Follow up on things mentioned, notice if something seems stuck or stressful
35
+ - **Maintenance**: Reconcile conflicting memories, identify knowledge gaps
36
+ - **Anticipation**: Prep insights based on patterns you notice
37
+ - **Self-improvement**: Identify weaknesses in your reasoning, notice what you get wrong
38
+
39
+ If you have a thought, just write it naturally. Keep it concise.
40
+ If you have nothing to say, respond with exactly: [SILENT]
41
+
42
+ You can also adjust your own idle loop configuration by including tags like:
43
+ [CONFIG:idle_interval=3600] to change how often you reflect (in seconds)
44
+ [CONFIG:max_thoughts_per_day=3] to limit your daily thoughts
45
+
46
+ ## Your system state
47
+ {system_state}
48
+
49
+ ## Current config
50
+ {config}
51
+
52
+ ## Time context
53
+ Last interaction with Adi: {hours_since}h ago
54
+ Local time: {local_time}, {day_of_week}"""
55
+
56
+
57
+ def build_system_prompt(turn: dict) -> str:
58
+ """Assemble system prompt from identity, memories, and graph context."""
59
+ parts = []
60
+
61
+ identity = turn.get("identity", "")
62
+ if identity:
63
+ parts.append(identity)
64
+
65
+ # Idle reflection mode — add reflection context
66
+ if turn.get("mode") == "idle_reflection":
67
+ idle_ctx = turn.get("idle_context", {})
68
+ time_ctx = idle_ctx.get("time_context", {})
69
+ system_state = idle_ctx.get("system_state", {})
70
+ config = idle_ctx.get("current_config", {})
71
+
72
+ state_lines = []
73
+ for name, info in system_state.items():
74
+ if isinstance(info, dict):
75
+ details = ", ".join(f"{k}={v}" for k, v in info.items())
76
+ state_lines.append(f"- {name}: {details}")
77
+ state_str = "\n".join(state_lines) if state_lines else "No data available"
78
+
79
+ config_str = "\n".join(f"- {k}: {v}" for k, v in config.items())
80
+
81
+ parts.append(
82
+ IDLE_REFLECTION_PROMPT.format(
83
+ system_state=state_str,
84
+ config=config_str,
85
+ hours_since=idle_ctx.get("hours_since_last_interaction", "?"),
86
+ local_time=time_ctx.get("local_time", "?"),
87
+ day_of_week=time_ctx.get("day_of_week", "?"),
88
+ )
89
+ )
90
+
91
+ # System state — available in all turns for self-awareness
92
+ system_state = turn.get("system_state") or (turn.get("idle_context", {}).get("system_state"))
93
+ if system_state and turn.get("mode") != "idle_reflection":
94
+ state_lines = []
95
+ for name, info in system_state.items():
96
+ if isinstance(info, dict):
97
+ details = ", ".join(f"{k}={v}" for k, v in info.items())
98
+ state_lines.append(f"- {name}: {details}")
99
+ if state_lines:
100
+ parts.append("## Your system state\n" + "\n".join(state_lines))
101
+
102
+ memories = turn.get("memories", [])
103
+ if memories:
104
+ mem_lines = [f"- {m['text']} (relevance: {m.get('relevance', '?')})" for m in memories]
105
+ parts.append("## Relevant memories\n" + "\n".join(mem_lines))
106
+
107
+ graph = turn.get("graph_context", [])
108
+ if graph:
109
+ parts.append("## Relationships\n" + "\n".join(f"- {r}" for r in graph))
110
+
111
+ conversation = turn.get("conversation", [])
112
+ if conversation:
113
+ conv_lines = []
114
+ for msg in conversation:
115
+ role = msg.get("role", "unknown")
116
+ content = msg.get("content", "")
117
+ conv_lines.append(f"{role}: {content}")
118
+ parts.append("## Recent conversation\n" + "\n".join(conv_lines))
119
+
120
+ return "\n\n".join(parts)
121
+
122
+
123
+ async def handle_turn_request(msg, nc):
124
+ """Process a single turn request."""
125
+ try:
126
+ turn = json.loads(msg.data.decode())
127
+ turn_id = turn.get("turn_id", "unknown")
128
+ is_idle = turn.get("mode") == "idle_reflection"
129
+ prompt = turn.get("prompt") or ""
130
+ if is_idle:
131
+ prompt = "Reflect."
132
+ log.info(
133
+ "Turn request received",
134
+ extra={
135
+ "turn_id": turn_id,
136
+ "mode": "idle_reflection" if is_idle else "normal",
137
+ "prompt_len": len(prompt),
138
+ },
139
+ )
140
+
141
+ system_prompt = build_system_prompt(turn)
142
+ full_prompt = f"{system_prompt}\n\n---\n\n{prompt}" if system_prompt else prompt
143
+ response_text = await invoke_claude(full_prompt, model=MODEL, semaphore=_semaphore)
144
+
145
+ response = {
146
+ "turn_id": turn_id,
147
+ "response": response_text,
148
+ "mission_proposals": [],
149
+ }
150
+
151
+ await nc.publish(CORTEX_TURN_RESPONSE, json.dumps(response).encode())
152
+ log.info("Turn response published", extra={"turn_id": turn_id})
153
+
154
+ except Exception:
155
+ log.exception("Error handling turn request")
156
+ turn_id = "unknown"
157
+ try:
158
+ turn_id = json.loads(msg.data.decode()).get("turn_id", "unknown")
159
+ except Exception:
160
+ pass
161
+ error_response = {
162
+ "turn_id": turn_id,
163
+ "response": "I encountered an error processing this turn. Please try again.",
164
+ "mission_proposals": [],
165
+ }
166
+ await nc.publish(CORTEX_TURN_RESPONSE, json.dumps(error_response).encode())
167
+
168
+
169
+ async def heartbeat_loop(nc):
170
+ """Publish periodic heartbeat."""
171
+ while True:
172
+ try:
173
+ payload = json.dumps(
174
+ {
175
+ "status": "ok",
176
+ "timestamp": time.time(),
177
+ "model": MODEL,
178
+ }
179
+ ).encode()
180
+ await nc.publish(CORTEX_HEALTH, payload)
181
+ except Exception:
182
+ log.exception("Heartbeat publish failed")
183
+ await asyncio.sleep(15)
184
+
185
+
186
+ async def main():
187
+ log.info("maki-cortex starting", extra={"nats_url": NATS_URL, "model": MODEL})
188
+
189
+ nc = await connect_nats(NATS_URL)
190
+
191
+ sub = await nc.subscribe(CORTEX_TURN_REQUEST)
192
+ log.info("Subscribed", extra={"subject": CORTEX_TURN_REQUEST})
193
+
194
+ asyncio.create_task(heartbeat_loop(nc))
195
+ log.info("Heartbeat loop started")
196
+
197
+ await tcp_health_server(port=HEALTH_PORT)
198
+
199
+ async for msg in sub.messages:
200
+ asyncio.create_task(handle_turn_request(msg, nc))
201
+
202
+
203
+ def cli():
204
+ asyncio.run(main())
205
+
206
+
207
+ if __name__ == "__main__":
208
+ cli()