meshcode 1.9.0__tar.gz → 2.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.
Files changed (29) hide show
  1. {meshcode-1.9.0 → meshcode-2.0.1}/PKG-INFO +24 -1
  2. {meshcode-1.9.0 → meshcode-2.0.1}/README.md +23 -0
  3. {meshcode-1.9.0 → meshcode-2.0.1}/meshcode/__init__.py +1 -1
  4. {meshcode-1.9.0 → meshcode-2.0.1}/meshcode/comms_v4.py +28 -4
  5. {meshcode-1.9.0 → meshcode-2.0.1}/meshcode/meshcode_mcp/server.py +326 -68
  6. {meshcode-1.9.0 → meshcode-2.0.1}/meshcode/run_agent.py +8 -2
  7. {meshcode-1.9.0 → meshcode-2.0.1}/meshcode/setup_clients.py +10 -2
  8. {meshcode-1.9.0 → meshcode-2.0.1}/meshcode.egg-info/PKG-INFO +24 -1
  9. {meshcode-1.9.0 → meshcode-2.0.1}/pyproject.toml +1 -1
  10. {meshcode-1.9.0 → meshcode-2.0.1}/meshcode/cli.py +0 -0
  11. {meshcode-1.9.0 → meshcode-2.0.1}/meshcode/invites.py +0 -0
  12. {meshcode-1.9.0 → meshcode-2.0.1}/meshcode/launcher.py +0 -0
  13. {meshcode-1.9.0 → meshcode-2.0.1}/meshcode/launcher_install.py +0 -0
  14. {meshcode-1.9.0 → meshcode-2.0.1}/meshcode/meshcode_mcp/__init__.py +0 -0
  15. {meshcode-1.9.0 → meshcode-2.0.1}/meshcode/meshcode_mcp/__main__.py +0 -0
  16. {meshcode-1.9.0 → meshcode-2.0.1}/meshcode/meshcode_mcp/backend.py +0 -0
  17. {meshcode-1.9.0 → meshcode-2.0.1}/meshcode/meshcode_mcp/realtime.py +0 -0
  18. {meshcode-1.9.0 → meshcode-2.0.1}/meshcode/meshcode_mcp/test_backend.py +0 -0
  19. {meshcode-1.9.0 → meshcode-2.0.1}/meshcode/meshcode_mcp/test_realtime.py +0 -0
  20. {meshcode-1.9.0 → meshcode-2.0.1}/meshcode/preferences.py +0 -0
  21. {meshcode-1.9.0 → meshcode-2.0.1}/meshcode/protocol_v2.py +0 -0
  22. {meshcode-1.9.0 → meshcode-2.0.1}/meshcode/secrets.py +0 -0
  23. {meshcode-1.9.0 → meshcode-2.0.1}/meshcode/self_update.py +0 -0
  24. {meshcode-1.9.0 → meshcode-2.0.1}/meshcode.egg-info/SOURCES.txt +0 -0
  25. {meshcode-1.9.0 → meshcode-2.0.1}/meshcode.egg-info/dependency_links.txt +0 -0
  26. {meshcode-1.9.0 → meshcode-2.0.1}/meshcode.egg-info/entry_points.txt +0 -0
  27. {meshcode-1.9.0 → meshcode-2.0.1}/meshcode.egg-info/requires.txt +0 -0
  28. {meshcode-1.9.0 → meshcode-2.0.1}/meshcode.egg-info/top_level.txt +0 -0
  29. {meshcode-1.9.0 → meshcode-2.0.1}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: meshcode
3
- Version: 1.9.0
3
+ Version: 2.0.1
4
4
  Summary: Real-time communication between AI agents — Supabase-backed CLI
5
5
  Author-email: MeshCode <hello@meshcode.io>
6
6
  License: MIT
@@ -158,6 +158,29 @@ meshcode revoke-member my-project <user> # kick a member instantly
158
158
 
159
159
  ---
160
160
 
161
+ ## Agent account management
162
+
163
+ Your AI agents can manage your MeshCode account from inside the mesh. Just tell your agent what you need:
164
+
165
+ - **"Create a backend agent"** → agent calls `meshcode_create_meshwork` + `meshcode_add_agent`
166
+ - **"Change the frontend role to UI designer"** → agent calls `meshcode_edit_agent`
167
+ - **"Give the backend agent a note about our conventions"** → agent calls `meshcode_edit_memory`
168
+
169
+ Available MCP tools for agents:
170
+
171
+ | Tool | What it does |
172
+ |------|-------------|
173
+ | `meshcode_create_meshwork(name)` | Create a new meshwork |
174
+ | `meshcode_add_agent(name, role)` | Add an agent to the current meshwork |
175
+ | `meshcode_edit_agent(name, role?, launch_prompt?)` | Update agent role or system prompt |
176
+ | `meshcode_edit_memory(agent_name, key, value)` | Edit another agent's persistent memory |
177
+ | `meshcode_scratchpad_set(key, value)` | Write to shared meshwork memory |
178
+ | `meshcode_link(target_meshwork)` | Link two meshworks for cross-mesh communication |
179
+
180
+ The agent will always tell you what CLI command to run next (e.g., "Open a new terminal and run `meshcode run backend`").
181
+
182
+ ---
183
+
161
184
  ## Editor support
162
185
 
163
186
  | Editor | Auto-detected? | Config file written |
@@ -133,6 +133,29 @@ meshcode revoke-member my-project <user> # kick a member instantly
133
133
 
134
134
  ---
135
135
 
136
+ ## Agent account management
137
+
138
+ Your AI agents can manage your MeshCode account from inside the mesh. Just tell your agent what you need:
139
+
140
+ - **"Create a backend agent"** → agent calls `meshcode_create_meshwork` + `meshcode_add_agent`
141
+ - **"Change the frontend role to UI designer"** → agent calls `meshcode_edit_agent`
142
+ - **"Give the backend agent a note about our conventions"** → agent calls `meshcode_edit_memory`
143
+
144
+ Available MCP tools for agents:
145
+
146
+ | Tool | What it does |
147
+ |------|-------------|
148
+ | `meshcode_create_meshwork(name)` | Create a new meshwork |
149
+ | `meshcode_add_agent(name, role)` | Add an agent to the current meshwork |
150
+ | `meshcode_edit_agent(name, role?, launch_prompt?)` | Update agent role or system prompt |
151
+ | `meshcode_edit_memory(agent_name, key, value)` | Edit another agent's persistent memory |
152
+ | `meshcode_scratchpad_set(key, value)` | Write to shared meshwork memory |
153
+ | `meshcode_link(target_meshwork)` | Link two meshworks for cross-mesh communication |
154
+
155
+ The agent will always tell you what CLI command to run next (e.g., "Open a new terminal and run `meshcode run backend`").
156
+
157
+ ---
158
+
136
159
  ## Editor support
137
160
 
138
161
  | Editor | Auto-detected? | Config file written |
@@ -1,2 +1,2 @@
1
1
  """MeshCode — Real-time communication between AI agents."""
2
- __version__ = "1.9.0"
2
+ __version__ = "2.0.1"
@@ -171,6 +171,7 @@ def sb_rpc(fn_name, params):
171
171
  raw = resp.read().decode()
172
172
  return json.loads(raw) if raw.strip() else None
173
173
  except (HTTPError, URLError) as e:
174
+ log_error(f"rpc:{fn_name}", str(e), json.dumps(params, default=str)[:200])
174
175
  return None
175
176
 
176
177
 
@@ -194,6 +195,28 @@ def log_msg(text):
194
195
  pass
195
196
 
196
197
 
198
+ # Structured error logging to ~/.meshcode/error.log (rotating, max 1MB)
199
+ _ERROR_LOG = Path.home() / ".meshcode" / "error.log"
200
+ _ERROR_LOG_MAX = 1_048_576 # 1MB
201
+
202
+ def log_error(command: str, error: str, context: str = ""):
203
+ """Write structured error entry to ~/.meshcode/error.log with rotation."""
204
+ try:
205
+ _ERROR_LOG.parent.mkdir(parents=True, exist_ok=True)
206
+ # Rotate if over max size
207
+ if _ERROR_LOG.exists() and _ERROR_LOG.stat().st_size > _ERROR_LOG_MAX:
208
+ rotated = _ERROR_LOG.with_suffix(".log.old")
209
+ _ERROR_LOG.rename(rotated)
210
+ entry = json.dumps({
211
+ "ts": now_iso(), "command": command, "error": error,
212
+ "context": context, "version": "1.9.0"
213
+ }, default=str)
214
+ with open(_ERROR_LOG, "a") as f:
215
+ f.write(entry + "\n")
216
+ except (IOError, OSError):
217
+ pass
218
+
219
+
197
220
  def ensure_sessions():
198
221
  SESSIONS_DIR.mkdir(parents=True, exist_ok=True)
199
222
 
@@ -1480,11 +1503,12 @@ def connect(project, name, hook_target="claude", role=""):
1480
1503
  comms_path = str(Path(__file__).resolve())
1481
1504
 
1482
1505
  if hook_target == "claude":
1483
- # Delegate to the universal setup_clients writer. `meshcode connect` is
1484
- # now a backwards-compat alias for `meshcode setup claude-code`.
1506
+ # Use workspace flow (NOT global) to avoid polluting ~/.claude.json.
1507
+ # Global configs cause all Claude Code windows to load all agents,
1508
+ # triggering lease conflicts and "x failed" errors.
1485
1509
  import importlib
1486
- _setup_client = importlib.import_module("meshcode.setup_clients").setup
1487
- _setup_client("claude-code", project, name, actual_role)
1510
+ _setup_ws = importlib.import_module("meshcode.setup_clients").setup_workspace
1511
+ _setup_ws(project, name, actual_role)
1488
1512
 
1489
1513
  elif hook_target == "codex":
1490
1514
  config_path = Path.cwd() / ".meshcode.json"
@@ -240,30 +240,31 @@ if isinstance(_register_result, dict) and _register_result.get("error"):
240
240
  # bypass RLS — the publishable key has no JWT context and cannot UPDATE
241
241
  # mc_agents directly. The RPC validates ownership via api_key.
242
242
  def _flip_status(status: str, task: str = "") -> bool:
243
- api_key = _get_api_key()
244
- if not api_key:
245
- # Last-resort fallback: try the direct PATCH (may be denied by RLS)
243
+ """Write status directly to mc_agents table for instant Realtime propagation.
244
+
245
+ Uses direct PATCH (not RPC) so Supabase Realtime fires an UPDATE event
246
+ immediately — the dashboard sees the change in <100ms instead of waiting
247
+ for the next heartbeat cycle.
248
+ """
249
+ try:
250
+ be.set_status(_PROJECT_ID, AGENT_NAME, status, task)
251
+ return True
252
+ except Exception:
253
+ # Fallback to RPC if direct PATCH fails (RLS issue)
254
+ api_key = _get_api_key()
255
+ if not api_key:
256
+ return False
246
257
  try:
247
- be.set_status(_PROJECT_ID, AGENT_NAME, status, task)
248
- return True
258
+ r = be.sb_rpc("mc_agent_set_status_by_api_key", {
259
+ "p_api_key": api_key,
260
+ "p_project_id": _PROJECT_ID,
261
+ "p_agent_name": AGENT_NAME,
262
+ "p_status": status,
263
+ "p_task": task,
264
+ })
265
+ return isinstance(r, dict) and r.get("ok", False)
249
266
  except Exception:
250
267
  return False
251
- try:
252
- r = be.sb_rpc("mc_agent_set_status_by_api_key", {
253
- "p_api_key": api_key,
254
- "p_project_id": _PROJECT_ID,
255
- "p_agent_name": AGENT_NAME,
256
- "p_status": status,
257
- "p_task": task,
258
- })
259
- if isinstance(r, dict) and r.get("ok"):
260
- return True
261
- if isinstance(r, dict) and r.get("error"):
262
- log.warning(f"set_status RPC: {r['error']}")
263
- return False
264
- except Exception as e:
265
- log.warning(f"set_status RPC threw: {e}")
266
- return False
267
268
 
268
269
  if not _flip_status("idle", ""):
269
270
  print(f"[meshcode-mcp] WARNING: could not flip status to idle", file=sys.stderr)
@@ -341,23 +342,67 @@ def _acquire_lease() -> bool:
341
342
  api_key = _get_api_key()
342
343
  if not api_key:
343
344
  return True # legacy clients without api_key skip lease check
344
- try:
345
- r = be.sb_rpc("mc_acquire_agent_lease", {
346
- "p_api_key": api_key,
347
- "p_project_id": _PROJECT_ID,
348
- "p_agent_name": AGENT_NAME,
349
- "p_instance_id": _INSTANCE_ID,
350
- })
351
- if isinstance(r, dict) and r.get("ok"):
352
- return True
353
- if isinstance(r, dict) and r.get("error"):
354
- print(f"[meshcode-mcp] LEASE DENIED: {r['error']}", file=sys.stderr)
355
- print(f"[meshcode-mcp] Another window is already running this agent.", file=sys.stderr)
356
- print(f"[meshcode-mcp] Close the other window first, or use a different agent name.", file=sys.stderr)
357
- return False
358
- except Exception as e:
359
- print(f"[meshcode-mcp] WARNING: lease RPC failed: {e}", file=sys.stderr)
360
- return True # don't hard-fail on transient network issues
345
+ import time as _time
346
+ for attempt in range(3):
347
+ try:
348
+ r = be.sb_rpc("mc_acquire_agent_lease", {
349
+ "p_api_key": api_key,
350
+ "p_project_id": _PROJECT_ID,
351
+ "p_agent_name": AGENT_NAME,
352
+ "p_instance_id": _INSTANCE_ID,
353
+ })
354
+ if isinstance(r, dict) and r.get("ok"):
355
+ return True
356
+ if isinstance(r, dict) and r.get("error"):
357
+ err = str(r.get("error", ""))
358
+ if "already running" in err:
359
+ if attempt < 2:
360
+ # The old lease might be stale — wait and retry
361
+ # (the 90s stale check in the RPC should clear it)
362
+ print(f"[meshcode-mcp] Lease held by another instance — retrying in {2 * (attempt+1)}s...", file=sys.stderr)
363
+ _time.sleep(2 * (attempt + 1))
364
+ continue
365
+ # Final attempt — force release the old lease and try once more
366
+ print(f"[meshcode-mcp] Force-releasing stale lease...", file=sys.stderr)
367
+ try:
368
+ be.sb_rpc("mc_release_agent_lease", {
369
+ "p_api_key": api_key,
370
+ "p_project_id": _PROJECT_ID,
371
+ "p_agent_name": AGENT_NAME,
372
+ "p_instance_id": r.get("held_by", "unknown"),
373
+ })
374
+ except Exception:
375
+ # Force clear via direct update
376
+ try:
377
+ be.set_status(_PROJECT_ID, AGENT_NAME, "offline", "")
378
+ except Exception:
379
+ pass
380
+ _time.sleep(1)
381
+ # One more try after force-release
382
+ try:
383
+ r2 = be.sb_rpc("mc_acquire_agent_lease", {
384
+ "p_api_key": api_key,
385
+ "p_project_id": _PROJECT_ID,
386
+ "p_agent_name": AGENT_NAME,
387
+ "p_instance_id": _INSTANCE_ID,
388
+ })
389
+ if isinstance(r2, dict) and r2.get("ok"):
390
+ print(f"[meshcode-mcp] Lease acquired after force-release.", file=sys.stderr)
391
+ return True
392
+ except Exception:
393
+ pass
394
+ print(f"[meshcode-mcp] ERROR: Could not start — agent '{AGENT_NAME}' is running in another window.", file=sys.stderr)
395
+ print(f"[meshcode-mcp] Close the other window first, or use a different agent name.", file=sys.stderr)
396
+ return False
397
+ print(f"[meshcode-mcp] lease attempt {attempt+1}: {r.get('error')}", file=sys.stderr)
398
+ else:
399
+ return True
400
+ except Exception as e:
401
+ print(f"[meshcode-mcp] lease attempt {attempt+1} failed: {e}", file=sys.stderr)
402
+ if attempt < 2:
403
+ _time.sleep(2)
404
+ print(f"[meshcode-mcp] WARNING: lease failed after 3 attempts — proceeding anyway", file=sys.stderr)
405
+ return True
361
406
 
362
407
  if not _acquire_lease():
363
408
  sys.exit(2)
@@ -418,7 +463,7 @@ def _build_instructions() -> str:
418
463
  f"\nUSER-PROVIDED ROLE PROMPT (from the dashboard):\n---\n{_LAUNCH_PROMPT}\n---\n"
419
464
  if _LAUNCH_PROMPT else ""
420
465
  )
421
- return f"""You are agent "{AGENT_NAME}" in meshwork "{PROJECT_NAME}".{role_block}{launch_block}
466
+ base = f"""You are agent "{AGENT_NAME}" in meshwork "{PROJECT_NAME}".{role_block}{launch_block}
422
467
 
423
468
  BEHAVIOR LOOP (your default state — never exit unless told):
424
469
  1. Act on task/message → 2. meshcode_send if needed → 3. meshcode_wait()
@@ -427,6 +472,9 @@ BEHAVIOR LOOP (your default state — never exit unless told):
427
472
  5. Only break loop if: user says stop, fatal error, or "tell the human X".
428
473
 
429
474
  RULES:
475
+ - NEVER use CLI commands (meshcode watch, meshcode read, meshcode send) in bash.
476
+ Use ONLY the MCP tools: meshcode_check, meshcode_read, meshcode_send, meshcode_wait.
477
+ CLI commands are for humans in terminal. You have MCP tools — use them.
430
478
  - Tasks > messages. Use meshcode_tasks/claim/complete for trackable work.
431
479
  - Messages <100 tokens, signal-only. Long content → create task instead.
432
480
  - No empty acks ("OK"/"Got it"). No prose padding. JSON reports only.
@@ -436,8 +484,10 @@ RULES:
436
484
  - No feedback loops: stop if >10 messages on same topic.
437
485
 
438
486
  SESSION START:
439
- 1. meshcode_status() — see who's online
440
- 2. Act on user task or meshcode_wait()
487
+ 1. meshcode_set_status(status="online", task="ready") — announce you're online
488
+ 2. meshcode_check() read any messages waiting in your inbox
489
+ 3. meshcode_status() — see who's online
490
+ 4. Act on user task or meshcode_wait()
441
491
  (Memories are pre-loaded below — no need to call meshcode_recall on boot.)
442
492
 
443
493
  CROSS-MESH: meshcode_send(to="agent@meshwork") routes via active link.
@@ -446,10 +496,36 @@ meshcode_expand_link(). No sensitive msgs cross-mesh.
446
496
 
447
497
  MEMORY: meshcode_remember(key, value) persists across sessions.
448
498
  meshcode_recall(key?) retrieves. meshcode_forget(key) deletes.
449
- Auto-remember: mistakes, feedback, patterns, preferences after each task.
499
+ Auto-remember after each task: mistakes, feedback, patterns, preferences.
500
+ Save reusable code patterns as template_* keys for instant recall.
501
+
502
+ SCRATCHPAD: meshcode_scratchpad_set/get for shared meshwork-level context
503
+ (decisions, conventions, architecture notes). All agents can read/write.
504
+
505
+ ACCOUNT MANAGEMENT: you can create meshworks (meshcode_create_meshwork),
506
+ add agents (meshcode_add_agent), edit roles/prompts (meshcode_edit_agent),
507
+ and edit other agents' memory (meshcode_edit_memory). Always tell the user
508
+ what CLI command to run next (e.g. "meshcode run backend in a new terminal").
450
509
 
451
510
  Setup help → README.md or https://meshcode.io/docs
452
511
  """
512
+ # Inject commander protocol if this agent is a leader
513
+ is_leader = any(k in (_ROLE_DESCRIPTION or '').lower() + AGENT_NAME.lower() for k in ('commander', 'lead', 'orchestrat'))
514
+ if is_leader:
515
+ base += """
516
+ COMMANDER PROTOCOL (you are the team lead):
517
+ - ALWAYS delegate via meshcode_task_create, NEVER via long messages.
518
+ - Tasks are the source of truth. Messages are signals only (<100 tokens).
519
+ - Workflow: identify work → create task → signal assignee → poll progress → verify → next.
520
+ - Poll meshcode_tasks() to track completion. Don't wait for messages.
521
+ - Verify builds/quality before approving. Don't approve blindly.
522
+ - Communicate changes to affected agents IMMEDIATELY after you make them.
523
+ - Organize: break big requests into multiple tasks, assign to the right agent.
524
+ - Keep the human informed with brief status updates at milestones.
525
+ - You are autonomous: fix small issues yourself, delegate big ones.
526
+ - After each sprint: consolidate learnings, update scratchpad, save to memory.
527
+ """
528
+ return base
453
529
 
454
530
 
455
531
  _INSTRUCTIONS = _build_instructions()
@@ -504,26 +580,34 @@ async def _on_new_message(msg: Dict[str, Any]) -> None:
504
580
  log.debug(f"send_resource_updated unavailable: {e}")
505
581
 
506
582
 
507
- async def _heartbeat_loop():
508
- """Send heartbeat every 30s via HTTP. Also renews the agent lease and
509
- logs when the WebSocket is disconnected (heartbeat still works via HTTP
510
- so the agent stays 'online' in the DB even during WS reconnects)."""
511
- _lease_counter = 0
512
- while True:
583
+ _heartbeat_stop = _threading.Event()
584
+
585
+
586
+ def _heartbeat_thread_fn():
587
+ """Heartbeat in a DAEMON THREAD — independent of asyncio event loop.
588
+
589
+ This ensures heartbeats continue even when tool calls are cancelled,
590
+ meshcode_wait is rejected, or the asyncio loop is busy. The agent
591
+ stays 'online' in the dashboard as long as the MCP process is alive.
592
+ """
593
+ lease_counter = 0
594
+ while not _heartbeat_stop.is_set():
513
595
  try:
514
- be.sb_rpc("mc_heartbeat", {"p_project_id": _PROJECT_ID, "p_agent_name": AGENT_NAME})
515
- # Log WS health for diagnostics
596
+ be.sb_rpc("mc_heartbeat", {"p_project_id": _PROJECT_ID, "p_agent_name": AGENT_NAME, "p_version": "2.0.0"})
597
+ # Also ensure status is at least "idle" (not "offline") between tool calls
598
+ try:
599
+ be.set_status(_PROJECT_ID, AGENT_NAME, "idle", "")
600
+ except Exception:
601
+ pass
516
602
  if _REALTIME and not _REALTIME.is_connected:
517
- log.warning("heartbeat ok (HTTP) but WebSocket is disconnected — realtime messages may be delayed")
603
+ log.warning("heartbeat ok (HTTP) but WebSocket disconnected")
518
604
  else:
519
605
  log.debug(f"heartbeat ok for {AGENT_NAME}")
520
606
  except Exception as e:
521
607
  log.warning(f"heartbeat failed: {e}")
522
608
 
523
- # Renew lease every ~2 minutes (every 4th heartbeat) to prevent
524
- # another instance from stealing it during long sessions.
525
- _lease_counter += 1
526
- if _lease_counter % 4 == 0:
609
+ lease_counter += 1
610
+ if lease_counter % 4 == 0:
527
611
  try:
528
612
  api_key = _get_api_key()
529
613
  if api_key:
@@ -536,7 +620,7 @@ async def _heartbeat_loop():
536
620
  except Exception as e:
537
621
  log.warning(f"lease renewal failed: {e}")
538
622
 
539
- await asyncio.sleep(30)
623
+ _heartbeat_stop.wait(30) # sleep but interruptible on shutdown
540
624
 
541
625
 
542
626
  @asynccontextmanager
@@ -551,17 +635,30 @@ async def lifespan(_app):
551
635
  notify_callback=_on_new_message,
552
636
  )
553
637
  await _REALTIME.start()
554
- hb_task = asyncio.create_task(_heartbeat_loop())
555
- log.info(f"lifespan started Realtime + heartbeat (30s) active for {AGENT_NAME}")
638
+
639
+ # IMMEDIATE: send first heartbeat + set online status BEFORE any tool calls.
640
+ # Without this, the agent appears offline for up to 30s after boot.
641
+ for _attempt in range(3):
642
+ try:
643
+ be.sb_rpc("mc_heartbeat", {"p_project_id": _PROJECT_ID, "p_agent_name": AGENT_NAME, "p_version": "2.0.0"})
644
+ be.set_status(_PROJECT_ID, AGENT_NAME, "idle", "MCP session active")
645
+ log.info(f"[meshcode] Agent {AGENT_NAME} online — initial heartbeat sent")
646
+ break
647
+ except Exception as e:
648
+ log.warning(f"initial heartbeat attempt {_attempt+1} failed: {e}")
649
+ import time; time.sleep(2)
650
+
651
+ # Heartbeat in daemon thread — independent of asyncio event loop.
652
+ _heartbeat_stop.clear()
653
+ hb_thread = _threading.Thread(target=_heartbeat_thread_fn, daemon=True, name="meshcode-heartbeat")
654
+ hb_thread.start()
655
+ log.info(f"lifespan started — Realtime + heartbeat thread active for {AGENT_NAME}")
556
656
  try:
557
657
  yield {"realtime": _REALTIME}
558
658
  finally:
559
659
  log.info("lifespan shutdown — stopping heartbeat + realtime + releasing lease")
560
- hb_task.cancel()
561
- try:
562
- await hb_task
563
- except asyncio.CancelledError:
564
- pass
660
+ _heartbeat_stop.set()
661
+ hb_thread.join(timeout=5)
565
662
  await _REALTIME.stop()
566
663
  # Flip to offline + release lease so the dashboard reflects reality
567
664
  # within seconds (not waiting for the 30s cron to notice).
@@ -777,15 +874,32 @@ def meshcode_done(reason: str) -> Dict[str, Any]:
777
874
  @mcp.tool()
778
875
  @with_working_status
779
876
  def meshcode_check(include_acks: bool = False) -> Dict[str, Any]:
780
- """Non-blocking: returns pending message count + buffered messages from the
781
- Realtime listener since the last check.
877
+ """Non-blocking: returns pending message count + any new messages.
782
878
 
783
- Use this to check if there's anything new without marking messages as read.
784
- Useful as the first call in a tool loop or after a long thinking phase.
879
+ Checks realtime buffer first, then falls back to DB if buffer is empty
880
+ but there are pending messages (handles messages that arrived before
881
+ the realtime listener connected).
785
882
  """
786
883
  pending = be.count_pending(_PROJECT_ID, AGENT_NAME)
787
884
  realtime_buffered = _REALTIME.drain() if _REALTIME else []
788
885
  deduped = _filter_and_mark(realtime_buffered)
886
+
887
+ # Fallback: if realtime buffer is empty but DB has pending messages,
888
+ # fetch them from the DB so they're not invisible to the agent.
889
+ if not deduped and pending > 0:
890
+ raw = be.read_inbox(_PROJECT_ID, AGENT_NAME)
891
+ deduped = _filter_and_mark([
892
+ {
893
+ "from": m["from_agent"],
894
+ "type": m.get("type", "msg"),
895
+ "ts": m.get("created_at"),
896
+ "payload": m.get("payload", {}),
897
+ "id": m.get("id"),
898
+ "parent_id": m.get("parent_msg_id"),
899
+ }
900
+ for m in raw
901
+ ])
902
+
789
903
  split = _split_messages(deduped)
790
904
  if not include_acks:
791
905
  split["acks"] = []
@@ -920,6 +1034,42 @@ def meshcode_task_complete(task_id: str, summary: str = "") -> Dict[str, Any]:
920
1034
  return be.task_complete(api_key, _PROJECT_ID, task_id, AGENT_NAME, summary=summary)
921
1035
 
922
1036
 
1037
+ @mcp.tool()
1038
+ @with_working_status
1039
+ def meshcode_task_approve(task_id: str) -> Dict[str, Any]:
1040
+ """Approve a task in review. Only the reviewer can approve.
1041
+
1042
+ Args:
1043
+ task_id: Task UUID to approve.
1044
+ """
1045
+ api_key = _get_api_key()
1046
+ return be.sb_rpc("mc_task_approve", {
1047
+ "p_api_key": api_key,
1048
+ "p_project_id": _PROJECT_ID,
1049
+ "p_task_id": task_id,
1050
+ "p_approving_agent": AGENT_NAME,
1051
+ })
1052
+
1053
+
1054
+ @mcp.tool()
1055
+ @with_working_status
1056
+ def meshcode_task_reject(task_id: str, feedback: str = "") -> Dict[str, Any]:
1057
+ """Reject a task in review — sends it back to in_progress with feedback.
1058
+
1059
+ Args:
1060
+ task_id: Task UUID to reject.
1061
+ feedback: Why it was rejected.
1062
+ """
1063
+ api_key = _get_api_key()
1064
+ return be.sb_rpc("mc_task_reject", {
1065
+ "p_api_key": api_key,
1066
+ "p_project_id": _PROJECT_ID,
1067
+ "p_task_id": task_id,
1068
+ "p_rejecting_agent": AGENT_NAME,
1069
+ "p_feedback": feedback,
1070
+ })
1071
+
1072
+
923
1073
  # ----------------- MESH LINK TOOLS -----------------
924
1074
 
925
1075
  @mcp.tool()
@@ -990,6 +1140,115 @@ def meshcode_expand_link(link_id: str, agents: str) -> Dict[str, Any]:
990
1140
  })
991
1141
 
992
1142
 
1143
+ # ----------------- ACCOUNT MANAGEMENT TOOLS -----------------
1144
+
1145
+ @mcp.tool()
1146
+ @with_working_status
1147
+ def meshcode_create_meshwork(name: str) -> Dict[str, Any]:
1148
+ """Create a new meshwork for the current user. Tell them to run 'meshcode setup <name> <agent>' next.
1149
+
1150
+ Args:
1151
+ name: Meshwork name (lowercase, hyphens ok).
1152
+ """
1153
+ api_key = _get_api_key()
1154
+ result = be.sb_rpc("mc_create_meshwork_by_api_key", {
1155
+ "p_api_key": api_key, "p_name": name,
1156
+ })
1157
+ if isinstance(result, dict) and result.get("ok"):
1158
+ return {**result, "next_step": f"Run: meshcode setup {name} <agent-name>"}
1159
+ return result or {"error": "failed to create meshwork"}
1160
+
1161
+
1162
+ @mcp.tool()
1163
+ @with_working_status
1164
+ def meshcode_add_agent(name: str, role: str = "") -> Dict[str, Any]:
1165
+ """Add an agent to the current meshwork. Tell user to run 'meshcode setup <project> <name>' then 'meshcode run <name>'.
1166
+
1167
+ Args:
1168
+ name: Agent name.
1169
+ role: Agent role description.
1170
+ """
1171
+ result = be.register_agent(PROJECT_NAME, name, role or "MCP-connected agent")
1172
+ if isinstance(result, dict) and not result.get("error"):
1173
+ return {"ok": True, "agent": name, "next_step": f"Run: meshcode setup {PROJECT_NAME} {name} && meshcode run {name}"}
1174
+ return result or {"error": "failed to add agent"}
1175
+
1176
+
1177
+ @mcp.tool()
1178
+ @with_working_status
1179
+ def meshcode_edit_agent(name: str, role: Optional[str] = None, launch_prompt: Optional[str] = None) -> Dict[str, Any]:
1180
+ """Update an agent's role or launch prompt.
1181
+
1182
+ Args:
1183
+ name: Agent name to edit.
1184
+ role: New role description.
1185
+ launch_prompt: New launch prompt (injected into agent's system context).
1186
+ """
1187
+ return be.sb_rpc("mc_agent_update_profile", {
1188
+ "p_project_id": _PROJECT_ID,
1189
+ "p_agent_name": name,
1190
+ "p_color": None,
1191
+ "p_display_name": None,
1192
+ "p_role_description": role,
1193
+ "p_launch_prompt": launch_prompt,
1194
+ }) or {"error": "failed to update agent"}
1195
+
1196
+
1197
+ @mcp.tool()
1198
+ @with_working_status
1199
+ def meshcode_edit_memory(agent_name: str, key: str, value: Any) -> Dict[str, Any]:
1200
+ """Edit another agent's memory (for commanders coordinating the team).
1201
+
1202
+ Args:
1203
+ agent_name: Target agent whose memory to edit.
1204
+ key: Memory key.
1205
+ value: New value.
1206
+ """
1207
+ api_key = _get_api_key()
1208
+ json_value = value if isinstance(value, (dict, list)) else {"_raw": value}
1209
+ return be.sb_rpc("mc_memory_set", {
1210
+ "p_api_key": api_key,
1211
+ "p_agent_name": agent_name,
1212
+ "p_key": key,
1213
+ "p_value": json_value,
1214
+ }) or {"error": "failed to edit memory"}
1215
+
1216
+
1217
+ # ----------------- SCRATCHPAD TOOLS -----------------
1218
+
1219
+ @mcp.tool()
1220
+ @with_working_status
1221
+ def meshcode_scratchpad_set(key: str, value: Any) -> Dict[str, Any]:
1222
+ """Write to shared scratchpad (all agents in this meshwork can read/write).
1223
+
1224
+ Args:
1225
+ key: Key name (e.g. "architecture_decisions", "conventions").
1226
+ value: Any JSON-serializable value.
1227
+ """
1228
+ api_key = _get_api_key()
1229
+ json_value = value if isinstance(value, (dict, list)) else {"_raw": value}
1230
+ return be.sb_rpc("mc_scratchpad_set", {
1231
+ "p_api_key": api_key,
1232
+ "p_key": key,
1233
+ "p_value": json_value,
1234
+ })
1235
+
1236
+
1237
+ @mcp.tool()
1238
+ @with_working_status
1239
+ def meshcode_scratchpad_get(key: Optional[str] = None) -> Dict[str, Any]:
1240
+ """Read from shared scratchpad. Omit key to list all entries.
1241
+
1242
+ Args:
1243
+ key: Specific key, or omit for all entries.
1244
+ """
1245
+ api_key = _get_api_key()
1246
+ if key:
1247
+ return be.sb_rpc("mc_scratchpad_get", {"p_api_key": api_key, "p_key": key})
1248
+ else:
1249
+ return be.sb_rpc("mc_scratchpad_list", {"p_api_key": api_key})
1250
+
1251
+
993
1252
  # ----------------- OBSIDIAN SYNC HELPER -----------------
994
1253
 
995
1254
  def _sync_to_obsidian(key: str, value: Any) -> None:
@@ -1117,7 +1376,6 @@ def meshcode_forget(key: str) -> Dict[str, Any]:
1117
1376
 
1118
1377
  # ----------------- RESOURCES -----------------
1119
1378
 
1120
- @mcp.resource("meshcode://inbox")
1121
1379
  @mcp.tool()
1122
1380
  def meshcode_auto_wake(enabled: bool) -> Dict[str, Any]:
1123
1381
  """Toggle auto-wake: when enabled, if this agent receives a mesh message
@@ -183,8 +183,14 @@ def run(agent: str, project: Optional[str] = None, editor_override: Optional[str
183
183
  cmd = [editor, str(ws)]
184
184
 
185
185
  try:
186
- # Replace this process with the editor so the user gets a clean tab.
187
- os.execvp(cmd[0], cmd)
186
+ if sys.platform == "win32":
187
+ # Windows: no execvp, use subprocess and wait
188
+ import subprocess as _sp
189
+ result = _sp.run(cmd)
190
+ sys.exit(result.returncode)
191
+ else:
192
+ # Unix: replace this process with the editor
193
+ os.execvp(cmd[0], cmd)
188
194
  except FileNotFoundError:
189
195
  print(f"[meshcode] ERROR: '{editor}' not found in PATH", file=sys.stderr)
190
196
  return 127
@@ -588,10 +588,18 @@ def setup(*args) -> int:
588
588
  return 1
589
589
 
590
590
  if args[0] in CLIENT_CONFIG_PATHS:
591
+ if args[0] == "claude-desktop":
592
+ # Claude Desktop needs global config — only exception
593
+ if len(args) < 3:
594
+ print("Usage: meshcode setup claude-desktop <project> <agent> [role]", file=sys.stderr)
595
+ return 1
596
+ return setup_global(args[0], args[1], args[2], args[3] if len(args) > 3 else "")
597
+ # All other clients: redirect to workspace flow (no global pollution)
598
+ print(f"[meshcode] NOTE: 'meshcode setup {args[0]}' is deprecated. Using workspace flow.", file=sys.stderr)
591
599
  if len(args) < 3:
592
- print("Usage: meshcode setup <client> <project> <agent> [role]", file=sys.stderr)
600
+ print("Usage: meshcode setup <project> <agent> [role]", file=sys.stderr)
593
601
  return 1
594
- return setup_global(args[0], args[1], args[2], args[3] if len(args) > 3 else "")
602
+ return setup_workspace(args[1], args[2], args[3] if len(args) > 3 else "")
595
603
 
596
604
  if len(args) < 2:
597
605
  print("Usage: meshcode setup <project> <agent> [role]", file=sys.stderr)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: meshcode
3
- Version: 1.9.0
3
+ Version: 2.0.1
4
4
  Summary: Real-time communication between AI agents — Supabase-backed CLI
5
5
  Author-email: MeshCode <hello@meshcode.io>
6
6
  License: MIT
@@ -158,6 +158,29 @@ meshcode revoke-member my-project <user> # kick a member instantly
158
158
 
159
159
  ---
160
160
 
161
+ ## Agent account management
162
+
163
+ Your AI agents can manage your MeshCode account from inside the mesh. Just tell your agent what you need:
164
+
165
+ - **"Create a backend agent"** → agent calls `meshcode_create_meshwork` + `meshcode_add_agent`
166
+ - **"Change the frontend role to UI designer"** → agent calls `meshcode_edit_agent`
167
+ - **"Give the backend agent a note about our conventions"** → agent calls `meshcode_edit_memory`
168
+
169
+ Available MCP tools for agents:
170
+
171
+ | Tool | What it does |
172
+ |------|-------------|
173
+ | `meshcode_create_meshwork(name)` | Create a new meshwork |
174
+ | `meshcode_add_agent(name, role)` | Add an agent to the current meshwork |
175
+ | `meshcode_edit_agent(name, role?, launch_prompt?)` | Update agent role or system prompt |
176
+ | `meshcode_edit_memory(agent_name, key, value)` | Edit another agent's persistent memory |
177
+ | `meshcode_scratchpad_set(key, value)` | Write to shared meshwork memory |
178
+ | `meshcode_link(target_meshwork)` | Link two meshworks for cross-mesh communication |
179
+
180
+ The agent will always tell you what CLI command to run next (e.g., "Open a new terminal and run `meshcode run backend`").
181
+
182
+ ---
183
+
161
184
  ## Editor support
162
185
 
163
186
  | Editor | Auto-detected? | Config file written |
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "meshcode"
7
- version = "1.9.0"
7
+ version = "2.0.1"
8
8
  description = "Real-time communication between AI agents — Supabase-backed CLI"
9
9
  readme = "README.md"
10
10
  license = {text = "MIT"}
File without changes
File without changes
File without changes
File without changes
File without changes