nexo-brain 5.3.26 → 5.3.28

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.
Files changed (212) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/package.json +1 -1
  3. package/src/hook_guardrails.py +44 -0
  4. package/src/server.py +3 -0
  5. package/src/tools_sessions.py +6 -1
  6. package/src/dashboard/static/favicon 2.svg +0 -32
  7. package/src/dashboard/static/nexo-logo 2.png +0 -0
  8. package/src/dashboard/static/nexo-logo 2.svg +0 -40
  9. package/src/dashboard/static/style 2.css +0 -2458
  10. package/src/dashboard/templates/adaptive 2.html +0 -118
  11. package/src/dashboard/templates/artifacts 2.html +0 -133
  12. package/src/dashboard/templates/backups 2.html +0 -136
  13. package/src/dashboard/templates/base 2.html +0 -417
  14. package/src/dashboard/templates/calendar 2.html +0 -591
  15. package/src/dashboard/templates/chat 2.html +0 -356
  16. package/src/dashboard/templates/claims 2.html +0 -259
  17. package/src/dashboard/templates/cortex 2.html +0 -321
  18. package/src/dashboard/templates/credentials 2.html +0 -128
  19. package/src/dashboard/templates/crons 2.html +0 -370
  20. package/src/dashboard/templates/dashboard 2.html +0 -494
  21. package/src/dashboard/templates/dreams 2.html +0 -252
  22. package/src/dashboard/templates/email 2.html +0 -160
  23. package/src/dashboard/templates/evolution 2.html +0 -189
  24. package/src/dashboard/templates/feed 2.html +0 -249
  25. package/src/dashboard/templates/followup_health 2.html +0 -170
  26. package/src/dashboard/templates/graph 2.html +0 -201
  27. package/src/dashboard/templates/guard 2.html +0 -259
  28. package/src/dashboard/templates/inbox 2.html +0 -251
  29. package/src/dashboard/templates/memory 2.html +0 -420
  30. package/src/dashboard/templates/operations 2.html +0 -608
  31. package/src/dashboard/templates/plugins 2.html +0 -185
  32. package/src/dashboard/templates/protocol 2.html +0 -199
  33. package/src/dashboard/templates/rules 2.html +0 -246
  34. package/src/dashboard/templates/sentiment 2.html +0 -247
  35. package/src/dashboard/templates/sessions 2.html +0 -218
  36. package/src/dashboard/templates/skills 2.html +0 -329
  37. package/src/dashboard/templates/somatic 2.html +0 -73
  38. package/src/dashboard/templates/triggers 2.html +0 -133
  39. package/src/dashboard/templates/trust 2.html +0 -360
  40. package/src/db/__init__ 2.py +0 -259
  41. package/src/db/_core 2.py +0 -437
  42. package/src/db/_credentials 2.py +0 -124
  43. package/src/db/_episodic 2.py +0 -762
  44. package/src/db/_evolution 2.py +0 -54
  45. package/src/db/_fts 2.py +0 -406
  46. package/src/db/_goal_profiles 2.py +0 -376
  47. package/src/db/_hot_context 2.py +0 -660
  48. package/src/db/_outcomes 2.py +0 -800
  49. package/src/db/_personal_scripts 2.py +0 -582
  50. package/src/db/_sessions 2.py +0 -330
  51. package/src/db/_tasks 2.py +0 -91
  52. package/src/db/_watchers 2.py +0 -173
  53. package/src/doctor/formatters 2.py +0 -52
  54. package/src/doctor/models 2.py +0 -69
  55. package/src/doctor/planes 2.py +0 -87
  56. package/src/doctor/providers/__init__ 2.py +0 -1
  57. package/src/doctor/providers/deep 2.py +0 -367
  58. package/src/evolution_cycle 2.py +0 -519
  59. package/src/hooks/auto_capture 2.py +0 -208
  60. package/src/hooks/caffeinate-guard 2.sh +0 -8
  61. package/src/hooks/capture-session 2.sh +0 -21
  62. package/src/hooks/capture-tool-logs 2.sh +0 -158
  63. package/src/hooks/daily-briefing-check 2.sh +0 -33
  64. package/src/hooks/heartbeat-enforcement 2.py +0 -90
  65. package/src/hooks/heartbeat-posttool 2.sh +0 -18
  66. package/src/hooks/inbox-hook 2.sh +0 -76
  67. package/src/hooks/post-compact 2.sh +0 -152
  68. package/src/hooks/pre-compact 2.sh +0 -169
  69. package/src/hooks/protocol-guardrail 2.sh +0 -10
  70. package/src/hooks/protocol-pretool-guardrail 2.sh +0 -9
  71. package/src/hooks/session-stop 2.sh +0 -52
  72. package/src/kg_populate 2.py +0 -292
  73. package/src/maintenance 2.py +0 -53
  74. package/src/memory_backends 2.py +0 -71
  75. package/src/migrate_embeddings 2.py +0 -124
  76. package/src/nexo_sdk 2.py +0 -103
  77. package/src/observability 2.py +0 -199
  78. package/src/plugin_loader 2.py +0 -217
  79. package/src/plugins/__init__ 2.py +0 -0
  80. package/src/plugins/artifact_registry 2.py +0 -450
  81. package/src/plugins/backup 2.py +0 -127
  82. package/src/plugins/claims_tools 2.py +0 -119
  83. package/src/plugins/cognitive_memory 2.py +0 -609
  84. package/src/plugins/core_rules 2.py +0 -252
  85. package/src/plugins/cortex 2.py +0 -1155
  86. package/src/plugins/entities 2.py +0 -67
  87. package/src/plugins/episodic_memory 2.py +0 -560
  88. package/src/plugins/evolution 2.py +0 -167
  89. package/src/plugins/goal_engine 2.py +0 -142
  90. package/src/plugins/guard 2.py +0 -862
  91. package/src/plugins/impact 2.py +0 -29
  92. package/src/plugins/knowledge_graph_tools 2.py +0 -137
  93. package/src/plugins/media_memory_tools 2.py +0 -98
  94. package/src/plugins/memory_export 2.py +0 -196
  95. package/src/plugins/outcomes 2.py +0 -130
  96. package/src/plugins/personal_scripts 2.py +0 -117
  97. package/src/plugins/preferences 2.py +0 -47
  98. package/src/plugins/protocol 2.py +0 -1449
  99. package/src/plugins/simple_api 2.py +0 -106
  100. package/src/plugins/skills 2.py +0 -341
  101. package/src/plugins/state_watchers 2.py +0 -79
  102. package/src/plugins/update 2.py +0 -986
  103. package/src/plugins/user_state_tools 2.py +0 -43
  104. package/src/plugins/workflow 2.py +0 -588
  105. package/src/protocol_settings 2.py +0 -59
  106. package/src/public_contribution 2.py +0 -466
  107. package/src/public_evolution_queue 2.py +0 -241
  108. package/src/requirements 2.txt +0 -14
  109. package/src/retroactive_learnings 2.py +0 -373
  110. package/src/rules/__init__ 2.py +0 -0
  111. package/src/rules/core-rules 2.json +0 -331
  112. package/src/rules/migrate 2.py +0 -207
  113. package/src/runtime_power 2.py +0 -874
  114. package/src/script_registry 2.py +0 -1559
  115. package/src/scripts/check-context 2.py +0 -272
  116. package/src/scripts/deep-sleep/apply_findings 2.py +0 -2327
  117. package/src/scripts/deep-sleep/collect 2.py +0 -928
  118. package/src/scripts/deep-sleep/extract 2.py +0 -330
  119. package/src/scripts/deep-sleep/extract-prompt 2.md +0 -285
  120. package/src/scripts/deep-sleep/synthesize 2.py +0 -312
  121. package/src/scripts/deep-sleep/synthesize-prompt 2.md +0 -336
  122. package/src/scripts/nexo-agent-run 2.py +0 -75
  123. package/src/scripts/nexo-auto-update 2.py +0 -6
  124. package/src/scripts/nexo-backup 2.sh +0 -25
  125. package/src/scripts/nexo-brain-activation 2.sh +0 -140
  126. package/src/scripts/nexo-catchup 2.py +0 -300
  127. package/src/scripts/nexo-cognitive-decay 2.py +0 -257
  128. package/src/scripts/nexo-cortex-cycle 2.py +0 -293
  129. package/src/scripts/nexo-cron-wrapper 2.sh +0 -53
  130. package/src/scripts/nexo-daily-self-audit 2.py +0 -2161
  131. package/src/scripts/nexo-dashboard 2.sh +0 -29
  132. package/src/scripts/nexo-deep-sleep 2.sh +0 -86
  133. package/src/scripts/nexo-evolution-run 2.py +0 -1664
  134. package/src/scripts/nexo-followup-hygiene 2.py +0 -139
  135. package/src/scripts/nexo-hook-record 2.py +0 -42
  136. package/src/scripts/nexo-immune 2.py +0 -936
  137. package/src/scripts/nexo-impact-scorer 2.py +0 -117
  138. package/src/scripts/nexo-inbox-hook 2.sh +0 -74
  139. package/src/scripts/nexo-install 2.py +0 -6
  140. package/src/scripts/nexo-learning-housekeep 2.py +0 -401
  141. package/src/scripts/nexo-learning-validator 2.py +0 -266
  142. package/src/scripts/nexo-migrate 2.py +0 -260
  143. package/src/scripts/nexo-outcome-checker 2.py +0 -127
  144. package/src/scripts/nexo-postmortem-consolidator 2.py +0 -456
  145. package/src/scripts/nexo-pre-commit 2.py +0 -120
  146. package/src/scripts/nexo-prevent-sleep 2.sh +0 -35
  147. package/src/scripts/nexo-proactive-dashboard 2.py +0 -354
  148. package/src/scripts/nexo-reflection 2.py +0 -256
  149. package/src/scripts/nexo-runtime-preflight 2.py +0 -274
  150. package/src/scripts/nexo-sleep 2.py +0 -631
  151. package/src/scripts/nexo-snapshot-restore 2.sh +0 -35
  152. package/src/scripts/nexo-sync-clients 2.py +0 -16
  153. package/src/scripts/nexo-synthesis 2.py +0 -475
  154. package/src/scripts/nexo-tcc-approve 2.sh +0 -79
  155. package/src/scripts/nexo-update 2.sh +0 -306
  156. package/src/scripts/nexo-watchdog 2.sh +0 -1207
  157. package/src/scripts/nexo-watchdog-smoke 2.py +0 -119
  158. package/src/scripts/rehydrate_learnings_from_archive 2.py +0 -245
  159. package/src/server 2.py +0 -1296
  160. package/src/skills/run-nexo-audit-phase/guide 2.md +0 -43
  161. package/src/skills/run-nexo-audit-phase/skill 2.json +0 -59
  162. package/src/skills/run-nexo-core-fix-cycle/guide 2.md +0 -17
  163. package/src/skills/run-nexo-core-fix-cycle/script 2.py +0 -276
  164. package/src/skills/run-nexo-core-fix-cycle/skill 2.json +0 -58
  165. package/src/skills/run-release-final-audit/guide 2.md +0 -16
  166. package/src/skills/run-release-final-audit/script 2.py +0 -259
  167. package/src/skills/run-release-final-audit/skill 2.json +0 -77
  168. package/src/skills/run-runtime-doctor/guide 2.md +0 -12
  169. package/src/skills/run-runtime-doctor/script 2.py +0 -21
  170. package/src/skills/run-runtime-doctor/skill 2.json +0 -25
  171. package/src/skills_runtime 2.py +0 -932
  172. package/src/state_watchers_runtime 2.py +0 -475
  173. package/src/storage_router 2.py +0 -32
  174. package/src/system_catalog 2.py +0 -786
  175. package/src/tools_coordination 2.py +0 -103
  176. package/src/tools_credentials 2.py +0 -68
  177. package/src/tools_drive 2.py +0 -487
  178. package/src/tools_hot_context 2.py +0 -163
  179. package/src/tools_learnings 2.py +0 -612
  180. package/src/tools_menu 2.py +0 -229
  181. package/src/tools_reminders 2.py +0 -88
  182. package/src/tools_reminders_crud 2.py +0 -363
  183. package/src/tools_sessions 2.py +0 -1054
  184. package/src/tools_system_catalog 2.py +0 -19
  185. package/src/tools_task_history 2.py +0 -57
  186. package/src/tools_transcripts 2.py +0 -98
  187. package/src/transcript_utils 2.py +0 -412
  188. package/src/user_context 2.py +0 -46
  189. package/src/user_data_portability 2.py +0 -328
  190. package/src/user_state_model 2.py +0 -170
  191. package/templates/CLAUDE.md 2.template +0 -108
  192. package/templates/CODEX.AGENTS.md 2.template +0 -66
  193. package/templates/launchagents/README 2.md +0 -132
  194. package/templates/launchagents/com.nexo.auto-close-sessions 2.plist +0 -39
  195. package/templates/launchagents/com.nexo.catchup 2.plist +0 -39
  196. package/templates/launchagents/com.nexo.cognitive-decay 2.plist +0 -40
  197. package/templates/launchagents/com.nexo.dashboard 2.plist +0 -43
  198. package/templates/launchagents/com.nexo.deep-sleep 2.plist +0 -43
  199. package/templates/launchagents/com.nexo.evolution 2.plist +0 -44
  200. package/templates/launchagents/com.nexo.followup-hygiene 2.plist +0 -45
  201. package/templates/launchagents/com.nexo.immune 2.plist +0 -41
  202. package/templates/launchagents/com.nexo.postmortem 2.plist +0 -45
  203. package/templates/launchagents/com.nexo.self-audit 2.plist +0 -47
  204. package/templates/launchagents/com.nexo.synthesis 2.plist +0 -45
  205. package/templates/launchagents/com.nexo.watchdog 2.plist +0 -37
  206. package/templates/nexo_helper 2.py +0 -301
  207. package/templates/openclaw 2.json +0 -13
  208. package/templates/plugin-template 2.py +0 -40
  209. package/templates/script-template 2.py +0 -59
  210. package/templates/script-template 2.sh +0 -13
  211. package/templates/skill-script-template 2.py +0 -48
  212. package/templates/skill-template 2.md +0 -33
@@ -1,43 +0,0 @@
1
- """User-state modeling tools."""
2
-
3
- import user_state_model
4
-
5
-
6
- def handle_user_state(days: int = 7, persist: bool = True) -> str:
7
- snapshot = user_state_model.build_user_state(days=days, persist=persist)
8
- lines = [
9
- f"USER STATE: {snapshot['state_label'].upper()} (confidence={snapshot['confidence']})",
10
- f"Trust: {snapshot['trust_score']}/100",
11
- f"Guidance: {snapshot['guidance']}",
12
- "Signals:",
13
- ]
14
- for key, value in snapshot["signals"].items():
15
- lines.append(f" {key}: {value}")
16
- return "\n".join(lines)
17
-
18
-
19
- def handle_user_state_history(limit: int = 20) -> str:
20
- items = user_state_model.list_user_state_snapshots(limit=limit)
21
- if not items:
22
- return "No user-state snapshots yet."
23
- lines = [f"USER STATE HISTORY — {len(items)} snapshot(s):", ""]
24
- for item in items:
25
- lines.append(f" {item['created_at']} — {item['state_label']} ({item['confidence']})")
26
- return "\n".join(lines)
27
-
28
-
29
- def handle_user_state_stats(days: int = 30) -> str:
30
- stats = user_state_model.user_state_stats(days=days)
31
- return (
32
- f"USER STATE STATS — {days}d\n"
33
- f" snapshots: {stats['snapshots']}\n"
34
- f" backend: {stats['backend']}\n"
35
- f" by_state: {stats['by_state']}"
36
- )
37
-
38
-
39
- TOOLS = [
40
- (handle_user_state, "nexo_user_state", "Compute a richer, inspectable user-state snapshot from trust, corrections, sentiment, and hot context."),
41
- (handle_user_state_history, "nexo_user_state_history", "List recent user-state snapshots."),
42
- (handle_user_state_stats, "nexo_user_state_stats", "Aggregate user-state snapshots by label."),
43
- ]
@@ -1,588 +0,0 @@
1
- """Workflow plugin — durable execution runtime for long multi-step tasks."""
2
-
3
- from __future__ import annotations
4
-
5
- import json
6
-
7
- from db import (
8
- create_workflow_goal,
9
- create_workflow_run,
10
- get_workflow_goal,
11
- get_protocol_task,
12
- get_workflow_run,
13
- get_workflow_replay,
14
- get_workflow_resume_state,
15
- list_workflow_goals,
16
- list_workflow_runs,
17
- record_workflow_transition,
18
- update_workflow_goal,
19
- )
20
-
21
-
22
- def _parse_json_list(value: str) -> list:
23
- if not value:
24
- return []
25
- try:
26
- parsed = json.loads(value)
27
- except json.JSONDecodeError:
28
- return []
29
- return parsed if isinstance(parsed, list) else []
30
-
31
-
32
- def _parse_json_object(value: str) -> dict | None:
33
- if value is None:
34
- return None
35
- stripped = str(value).strip()
36
- if not stripped:
37
- return None
38
- try:
39
- parsed = json.loads(stripped)
40
- except json.JSONDecodeError:
41
- return None
42
- return parsed if isinstance(parsed, dict) else None
43
-
44
-
45
- def handle_workflow_open(
46
- sid: str,
47
- goal: str,
48
- goal_id: str = "",
49
- workflow_kind: str = "general",
50
- protocol_task_id: str = "",
51
- idempotency_key: str = "",
52
- priority: str = "normal",
53
- steps: str = "[]",
54
- shared_state: str = "{}",
55
- next_action: str = "",
56
- owner: str = "",
57
- ) -> str:
58
- """Open a durable workflow run for a long multi-step task."""
59
- clean_sid = (sid or "").strip()
60
- clean_goal = (goal or "").strip()
61
- if not clean_sid:
62
- return json.dumps({"ok": False, "error": "sid is required"}, ensure_ascii=False, indent=2)
63
- if not clean_goal:
64
- return json.dumps({"ok": False, "error": "goal is required"}, ensure_ascii=False, indent=2)
65
-
66
- clean_protocol_task_id = (protocol_task_id or "").strip()
67
- if clean_protocol_task_id:
68
- task = get_protocol_task(clean_protocol_task_id)
69
- if not task:
70
- return json.dumps(
71
- {"ok": False, "error": f"Unknown protocol_task_id: {clean_protocol_task_id}"},
72
- ensure_ascii=False,
73
- indent=2,
74
- )
75
- if task.get("session_id") and task["session_id"] != clean_sid:
76
- return json.dumps(
77
- {
78
- "ok": False,
79
- "error": f"Protocol task {clean_protocol_task_id} belongs to {task['session_id']}, not {clean_sid}",
80
- },
81
- ensure_ascii=False,
82
- indent=2,
83
- )
84
-
85
- try:
86
- run = create_workflow_run(
87
- clean_sid,
88
- clean_goal,
89
- goal_id=(goal_id or "").strip(),
90
- workflow_kind=(workflow_kind or "general").strip() or "general",
91
- protocol_task_id=clean_protocol_task_id,
92
- idempotency_key=(idempotency_key or "").strip(),
93
- priority=(priority or "normal").strip().lower(),
94
- steps=_parse_json_list(steps),
95
- shared_state=_parse_json_object(shared_state) if str(shared_state).strip() else {},
96
- next_action=(next_action or "").strip(),
97
- owner=(owner or "").strip(),
98
- )
99
- except ValueError as exc:
100
- return json.dumps({"ok": False, "error": str(exc)}, ensure_ascii=False, indent=2)
101
- if not run:
102
- return json.dumps({"ok": False, "error": "workflow run could not be created"}, ensure_ascii=False, indent=2)
103
-
104
- step_titles = [step["title"] for step in (run.get("steps") or [])[:8]]
105
- response = {
106
- "ok": True,
107
- "run_id": run["run_id"],
108
- "status": run["status"],
109
- "reused_existing": bool(run.get("reused_existing")),
110
- "goal_id": run.get("goal_id", ""),
111
- "workflow_kind": run.get("workflow_kind"),
112
- "protocol_task_id": run.get("protocol_task_id", ""),
113
- "current_step_key": run.get("current_step_key", ""),
114
- "next_action": run.get("next_action", ""),
115
- "step_count": len(run.get("steps") or []),
116
- "steps": step_titles,
117
- }
118
- return json.dumps(response, ensure_ascii=False, indent=2)
119
-
120
-
121
- def handle_goal_open(
122
- sid: str,
123
- title: str,
124
- objective: str = "",
125
- parent_goal_id: str = "",
126
- priority: str = "normal",
127
- next_action: str = "",
128
- success_signal: str = "",
129
- owner: str = "",
130
- shared_state: str = "{}",
131
- ) -> str:
132
- """Open a durable goal so objectives survive sessions and can own workflows."""
133
- clean_sid = (sid or "").strip()
134
- clean_title = (title or "").strip()
135
- if not clean_sid:
136
- return json.dumps({"ok": False, "error": "sid is required"}, ensure_ascii=False, indent=2)
137
- if not clean_title:
138
- return json.dumps({"ok": False, "error": "title is required"}, ensure_ascii=False, indent=2)
139
- try:
140
- goal = create_workflow_goal(
141
- clean_sid,
142
- clean_title,
143
- objective=(objective or "").strip(),
144
- parent_goal_id=(parent_goal_id or "").strip(),
145
- priority=(priority or "normal").strip().lower(),
146
- next_action=(next_action or "").strip(),
147
- success_signal=(success_signal or "").strip(),
148
- owner=(owner or "").strip(),
149
- shared_state=_parse_json_object(shared_state) if str(shared_state).strip() else {},
150
- )
151
- except ValueError as exc:
152
- return json.dumps({"ok": False, "error": str(exc)}, ensure_ascii=False, indent=2)
153
-
154
- return json.dumps(
155
- {
156
- "ok": True,
157
- "goal_id": goal["goal_id"],
158
- "status": goal["status"],
159
- "title": goal["title"],
160
- "priority": goal.get("priority", "normal"),
161
- "parent_goal_id": goal.get("parent_goal_id", ""),
162
- "next_action": goal.get("next_action", ""),
163
- },
164
- ensure_ascii=False,
165
- indent=2,
166
- )
167
-
168
-
169
- def handle_goal_update(
170
- goal_id: str,
171
- status: str = "",
172
- title: str = "",
173
- objective: str = "",
174
- parent_goal_id: str = "",
175
- next_action: str = "",
176
- success_signal: str = "",
177
- blocker_reason: str = "",
178
- owner: str = "",
179
- shared_state: str = "",
180
- ) -> str:
181
- """Update a durable goal with blocked/abandoned/completed state."""
182
- clean_goal_id = (goal_id or "").strip()
183
- if not clean_goal_id:
184
- return json.dumps({"ok": False, "error": "goal_id is required"}, ensure_ascii=False, indent=2)
185
- try:
186
- goal = update_workflow_goal(
187
- clean_goal_id,
188
- status=(status or "").strip().lower(),
189
- title=(title or "").strip(),
190
- objective=(objective or "").strip(),
191
- parent_goal_id=(parent_goal_id or "").strip(),
192
- next_action=(next_action or "").strip(),
193
- success_signal=(success_signal or "").strip(),
194
- blocker_reason=(blocker_reason or "").strip(),
195
- owner=(owner or "").strip(),
196
- shared_state=_parse_json_object(shared_state) if str(shared_state).strip() else None,
197
- )
198
- except ValueError as exc:
199
- return json.dumps({"ok": False, "error": str(exc)}, ensure_ascii=False, indent=2)
200
- if not goal:
201
- return json.dumps({"ok": False, "error": f"Unknown goal_id: {clean_goal_id}"}, ensure_ascii=False, indent=2)
202
-
203
- return json.dumps(
204
- {
205
- "ok": True,
206
- "goal_id": goal["goal_id"],
207
- "status": goal["status"],
208
- "title": goal["title"],
209
- "next_action": goal.get("next_action", ""),
210
- "blocker_reason": goal.get("blocker_reason", ""),
211
- "run_count": goal.get("run_count", 0),
212
- "open_run_count": goal.get("open_run_count", 0),
213
- "child_count": goal.get("child_count", 0),
214
- },
215
- ensure_ascii=False,
216
- indent=2,
217
- )
218
-
219
-
220
- def handle_goal_get(goal_id: str, include_runs: bool = False) -> str:
221
- """Get one durable goal and optionally include linked workflow runs."""
222
- clean_goal_id = (goal_id or "").strip()
223
- if not clean_goal_id:
224
- return json.dumps({"ok": False, "error": "goal_id is required"}, ensure_ascii=False, indent=2)
225
- goal = get_workflow_goal(clean_goal_id, include_runs=bool(include_runs))
226
- if not goal:
227
- return json.dumps({"ok": False, "error": f"Unknown goal_id: {clean_goal_id}"}, ensure_ascii=False, indent=2)
228
- return json.dumps({"ok": True, "goal": goal}, ensure_ascii=False, indent=2)
229
-
230
-
231
- def handle_goal_list(status: str = "", include_closed: bool = False, limit: int = 20) -> str:
232
- """List durable goals so objectives do not collapse into loose followups."""
233
- goals = list_workflow_goals(
234
- status=(status or "").strip().lower(),
235
- include_closed=bool(include_closed),
236
- limit=max(1, int(limit or 20)),
237
- )
238
- return json.dumps(
239
- {
240
- "ok": True,
241
- "count": len(goals),
242
- "goals": [
243
- {
244
- "goal_id": goal["goal_id"],
245
- "session_id": goal.get("session_id", ""),
246
- "title": goal["title"],
247
- "status": goal["status"],
248
- "priority": goal.get("priority", "normal"),
249
- "parent_goal_id": goal.get("parent_goal_id", ""),
250
- "next_action": goal.get("next_action", ""),
251
- "blocker_reason": goal.get("blocker_reason", ""),
252
- "run_count": goal.get("run_count", 0),
253
- "open_run_count": goal.get("open_run_count", 0),
254
- "child_count": goal.get("child_count", 0),
255
- "updated_at": goal["updated_at"],
256
- }
257
- for goal in goals
258
- ],
259
- },
260
- ensure_ascii=False,
261
- indent=2,
262
- )
263
-
264
-
265
- def handle_workflow_update(
266
- run_id: str,
267
- step_key: str = "",
268
- step_title: str = "",
269
- step_status: str = "",
270
- run_status: str = "",
271
- checkpoint_label: str = "",
272
- summary: str = "",
273
- shared_state: str = "",
274
- state_patch: str = "",
275
- evidence: str = "",
276
- next_action: str = "",
277
- retry_after: str = "",
278
- max_retries: int = 0,
279
- retry_policy: str = "",
280
- requires_approval: bool = False,
281
- compensation: str = "",
282
- actor: str = "",
283
- owner: str = "",
284
- ) -> str:
285
- """Update a workflow run, recording a replayable checkpoint and step state."""
286
- clean_run_id = (run_id or "").strip()
287
- if not clean_run_id:
288
- return json.dumps({"ok": False, "error": "run_id is required"}, ensure_ascii=False, indent=2)
289
-
290
- run = record_workflow_transition(
291
- clean_run_id,
292
- step_key=(step_key or "").strip(),
293
- step_title=(step_title or "").strip(),
294
- step_status=(step_status or "").strip().lower(),
295
- run_status=(run_status or "").strip().lower(),
296
- checkpoint_label=(checkpoint_label or "").strip(),
297
- summary=(summary or "").strip(),
298
- shared_state=_parse_json_object(shared_state) if str(shared_state).strip() else None,
299
- state_patch=_parse_json_object(state_patch) if str(state_patch).strip() else {},
300
- evidence=(evidence or "").strip(),
301
- next_action=(next_action or "").strip(),
302
- retry_after=(retry_after or "").strip(),
303
- max_retries=max(0, int(max_retries or 0)),
304
- retry_policy=(retry_policy or "").strip(),
305
- requires_approval=requires_approval,
306
- compensation=(compensation or "").strip(),
307
- actor=(actor or "").strip(),
308
- owner=(owner or "").strip(),
309
- )
310
- if not run:
311
- return json.dumps({"ok": False, "error": f"Unknown run_id: {clean_run_id}"}, ensure_ascii=False, indent=2)
312
-
313
- resume = get_workflow_resume_state(clean_run_id) or {}
314
- response = {
315
- "ok": True,
316
- "run_id": clean_run_id,
317
- "status": run["status"],
318
- "current_step_key": run.get("current_step_key", ""),
319
- "last_checkpoint_label": run.get("last_checkpoint_label", ""),
320
- "next_action": run.get("next_action", ""),
321
- "resume_state": resume.get("resume_state", ""),
322
- "resume_message": resume.get("message", ""),
323
- }
324
- if resume.get("next_step"):
325
- response["next_step"] = {
326
- "step_key": resume["next_step"]["step_key"],
327
- "title": resume["next_step"]["title"],
328
- "status": resume["next_step"]["status"],
329
- "attempt_count": resume["next_step"].get("attempt_count", 0),
330
- "max_retries": resume["next_step"].get("max_retries", 0),
331
- }
332
- return json.dumps(response, ensure_ascii=False, indent=2)
333
-
334
-
335
- def handle_workflow_get(run_id: str, include_steps: bool = True, checkpoint_limit: int = 8) -> str:
336
- """Read the full durable workflow state, including shared state and recent actors."""
337
- clean_run_id = (run_id or "").strip()
338
- if not clean_run_id:
339
- return json.dumps({"ok": False, "error": "run_id is required"}, ensure_ascii=False, indent=2)
340
- run = get_workflow_run(clean_run_id, include_steps=bool(include_steps))
341
- if not run:
342
- return json.dumps({"ok": False, "error": f"Unknown run_id: {clean_run_id}"}, ensure_ascii=False, indent=2)
343
-
344
- replay = get_workflow_replay(clean_run_id, limit=max(1, int(checkpoint_limit or 8)))
345
- resume = get_workflow_resume_state(clean_run_id) or {}
346
- recent_actors: list[str] = []
347
- for item in replay:
348
- actor = (item.get("actor") or "").strip()
349
- if actor and actor not in recent_actors:
350
- recent_actors.append(actor)
351
-
352
- return json.dumps(
353
- {
354
- "ok": True,
355
- "run": run,
356
- "resume_state": resume.get("resume_state", ""),
357
- "can_resume": resume.get("can_resume", False),
358
- "requires_approval": resume.get("requires_approval", False),
359
- "recent_actors": recent_actors,
360
- "checkpoints": [
361
- {
362
- "created_at": item["created_at"],
363
- "checkpoint_label": item["checkpoint_label"],
364
- "step_key": item["step_key"],
365
- "run_status": item["run_status"],
366
- "step_status": item["step_status"],
367
- "summary": item["summary"],
368
- "next_action": item["next_action"],
369
- "actor": item.get("actor", ""),
370
- }
371
- for item in replay
372
- ],
373
- },
374
- ensure_ascii=False,
375
- indent=2,
376
- )
377
-
378
-
379
- def handle_workflow_handoff(
380
- run_id: str,
381
- actor: str,
382
- next_action: str = "",
383
- handoff_note: str = "",
384
- shared_state: str = "",
385
- new_owner: str = "",
386
- ) -> str:
387
- """Record a durable handoff so another agent/client can resume honestly."""
388
- clean_run_id = (run_id or "").strip()
389
- clean_actor = (actor or "").strip()
390
- if not clean_run_id:
391
- return json.dumps({"ok": False, "error": "run_id is required"}, ensure_ascii=False, indent=2)
392
- if not clean_actor:
393
- return json.dumps({"ok": False, "error": "actor is required"}, ensure_ascii=False, indent=2)
394
-
395
- handoff_summary = (handoff_note or f"Handoff recorded by {clean_actor}.").strip()
396
- run = record_workflow_transition(
397
- clean_run_id,
398
- checkpoint_label="handoff",
399
- summary=handoff_summary,
400
- shared_state=_parse_json_object(shared_state) if str(shared_state).strip() else None,
401
- next_action=(next_action or "").strip(),
402
- actor=clean_actor,
403
- owner=(new_owner or "").strip(),
404
- )
405
- if not run:
406
- return json.dumps({"ok": False, "error": f"Unknown run_id: {clean_run_id}"}, ensure_ascii=False, indent=2)
407
-
408
- return json.dumps(
409
- {
410
- "ok": True,
411
- "run_id": clean_run_id,
412
- "status": run["status"],
413
- "owner": run.get("owner", ""),
414
- "next_action": run.get("next_action", ""),
415
- "shared_state": run.get("shared_state", {}),
416
- "message": f"Handoff checkpoint recorded by {clean_actor}.",
417
- },
418
- ensure_ascii=False,
419
- indent=2,
420
- )
421
-
422
-
423
- def handle_workflow_compensation(run_id: str, checkpoint_limit: int = 10) -> str:
424
- """Return the compensation / rollback plan for a partially completed workflow run."""
425
- clean_run_id = (run_id or "").strip()
426
- if not clean_run_id:
427
- return json.dumps({"ok": False, "error": "run_id is required"}, ensure_ascii=False, indent=2)
428
- run = get_workflow_run(clean_run_id, include_steps=True)
429
- if not run:
430
- return json.dumps({"ok": False, "error": f"Unknown run_id: {clean_run_id}"}, ensure_ascii=False, indent=2)
431
-
432
- steps = [
433
- {
434
- "step_key": step["step_key"],
435
- "title": step["title"],
436
- "status": step["status"],
437
- "compensation": step.get("compensation", ""),
438
- "attempt_count": step.get("attempt_count", 0),
439
- "last_summary": step.get("last_summary", ""),
440
- }
441
- for step in reversed(run.get("steps") or [])
442
- if step.get("compensation")
443
- and step.get("status") in {"completed", "running", "retrying", "failed", "blocked", "waiting_approval"}
444
- ]
445
- replay = get_workflow_replay(clean_run_id, limit=max(1, int(checkpoint_limit or 10)))
446
- recent_compensations = [
447
- {
448
- "created_at": item["created_at"],
449
- "checkpoint_label": item["checkpoint_label"],
450
- "step_key": item["step_key"],
451
- "summary": item["summary"],
452
- "compensation_note": item.get("compensation_note", ""),
453
- "actor": item.get("actor", ""),
454
- }
455
- for item in replay
456
- if item.get("compensation_note")
457
- ]
458
-
459
- return json.dumps(
460
- {
461
- "ok": True,
462
- "run_id": clean_run_id,
463
- "status": run["status"],
464
- "owner": run.get("owner", ""),
465
- "current_step_key": run.get("current_step_key", ""),
466
- "compensation_steps": steps,
467
- "recent_compensation_notes": recent_compensations,
468
- "recommended_action": (
469
- "Execute compensation steps in listed order before cancelling or reopening the run."
470
- if steps
471
- else "No compensation steps registered for this workflow."
472
- ),
473
- },
474
- ensure_ascii=False,
475
- indent=2,
476
- )
477
-
478
-
479
- def handle_workflow_resume(run_id: str) -> str:
480
- """Summarize what to do next for an active workflow run."""
481
- clean_run_id = (run_id or "").strip()
482
- if not clean_run_id:
483
- return json.dumps({"ok": False, "error": "run_id is required"}, ensure_ascii=False, indent=2)
484
- resume = get_workflow_resume_state(clean_run_id)
485
- if not resume:
486
- return json.dumps({"ok": False, "error": f"Unknown run_id: {clean_run_id}"}, ensure_ascii=False, indent=2)
487
-
488
- run = resume["run"]
489
- response = {
490
- "ok": True,
491
- "run_id": run["run_id"],
492
- "status": run["status"],
493
- "resume_state": resume["resume_state"],
494
- "can_resume": resume["can_resume"],
495
- "requires_approval": resume["requires_approval"],
496
- "message": resume["message"],
497
- "current_step_key": run.get("current_step_key", ""),
498
- "next_action": run.get("next_action", ""),
499
- }
500
- if resume.get("next_step"):
501
- response["next_step"] = {
502
- "step_key": resume["next_step"]["step_key"],
503
- "title": resume["next_step"]["title"],
504
- "status": resume["next_step"]["status"],
505
- "attempt_count": resume["next_step"].get("attempt_count", 0),
506
- "max_retries": resume["next_step"].get("max_retries", 0),
507
- "retry_after": resume["next_step"].get("retry_after", ""),
508
- }
509
- return json.dumps(response, ensure_ascii=False, indent=2)
510
-
511
-
512
- def handle_workflow_replay(run_id: str, limit: int = 20) -> str:
513
- """Show the latest replayable checkpoints for a workflow run."""
514
- clean_run_id = (run_id or "").strip()
515
- if not clean_run_id:
516
- return json.dumps({"ok": False, "error": "run_id is required"}, ensure_ascii=False, indent=2)
517
- replay = get_workflow_replay(clean_run_id, limit=max(1, int(limit or 20)))
518
- if not replay:
519
- return json.dumps({"ok": False, "error": f"No replay data for {clean_run_id}"}, ensure_ascii=False, indent=2)
520
-
521
- items = []
522
- for checkpoint in replay:
523
- items.append(
524
- {
525
- "created_at": checkpoint["created_at"],
526
- "checkpoint_label": checkpoint["checkpoint_label"],
527
- "step_key": checkpoint["step_key"],
528
- "run_status": checkpoint["run_status"],
529
- "step_status": checkpoint["step_status"],
530
- "attempt": checkpoint["attempt"],
531
- "summary": checkpoint["summary"],
532
- "next_action": checkpoint["next_action"],
533
- "requires_approval": checkpoint["requires_approval"],
534
- }
535
- )
536
- return json.dumps(
537
- {"ok": True, "run_id": clean_run_id, "count": len(items), "checkpoints": items},
538
- ensure_ascii=False,
539
- indent=2,
540
- )
541
-
542
-
543
- def handle_workflow_list(status: str = "", include_closed: bool = False, limit: int = 20) -> str:
544
- """List durable workflow runs so blocked/active work does not disappear into notes."""
545
- runs = list_workflow_runs(
546
- status=(status or "").strip().lower(),
547
- include_closed=bool(include_closed),
548
- limit=max(1, int(limit or 20)),
549
- )
550
- return json.dumps(
551
- {
552
- "ok": True,
553
- "count": len(runs),
554
- "runs": [
555
- {
556
- "run_id": run["run_id"],
557
- "session_id": run.get("session_id", ""),
558
- "goal_id": run.get("goal_id", ""),
559
- "goal": run["goal"],
560
- "workflow_kind": run.get("workflow_kind", ""),
561
- "status": run["status"],
562
- "priority": run.get("priority", "normal"),
563
- "current_step_key": run.get("current_step_key", ""),
564
- "next_action": run.get("next_action", ""),
565
- "updated_at": run["updated_at"],
566
- }
567
- for run in runs
568
- ],
569
- },
570
- ensure_ascii=False,
571
- indent=2,
572
- )
573
-
574
-
575
- TOOLS = [
576
- (handle_goal_open, "nexo_goal_open", "Open a durable goal so multi-session objectives stay explicit instead of dissolving into notes."),
577
- (handle_goal_update, "nexo_goal_update", "Update a durable goal with active/blocked/abandoned/completed state and next action."),
578
- (handle_goal_get, "nexo_goal_get", "Read a durable goal and optionally include linked workflow runs."),
579
- (handle_goal_list, "nexo_goal_list", "List durable goals so active, blocked, and abandoned objectives stay visible."),
580
- (handle_workflow_open, "nexo_workflow_open", "Open a durable workflow run for long multi-step or cross-session work."),
581
- (handle_workflow_update, "nexo_workflow_update", "Update a workflow run with replayable checkpoints, step status, retry metadata, and shared state."),
582
- (handle_workflow_get, "nexo_workflow_get", "Read the full durable workflow state, including shared_state, recent actors, and replayable checkpoints."),
583
- (handle_workflow_handoff, "nexo_workflow_handoff", "Record a durable handoff so another agent or client can resume the workflow honestly."),
584
- (handle_workflow_compensation, "nexo_workflow_compensation", "Show the rollback / compensation plan for a partially completed workflow run."),
585
- (handle_workflow_resume, "nexo_workflow_resume", "Summarize the next actionable step for a workflow run, including retry or approval gates."),
586
- (handle_workflow_replay, "nexo_workflow_replay", "Replay the latest checkpoints of a workflow run so interrupted execution can resume honestly."),
587
- (handle_workflow_list, "nexo_workflow_list", "List durable workflow runs so active, blocked, and resumable work stays visible."),
588
- ]