Spaces:
Paused
Paused
feat: parallel discussion + async Claude Code execution
Browse filesArchitecture change: Adam/Eve no longer block waiting for Claude Code.
- CC runs in background thread via cc_submit_task()
- Agents discuss every 15s, seeing CC's live output in context
- cc_get_live_status() shows: WORKING (with recent output), FINISHED, or IDLE
- Agents assign [TASK] when CC is idle, discuss progress when CC is busy
- cc_live_lines deque shares streaming output between CC and discussion
- Removed nudge logic (not needed — discussion is natural when CC is busy)
- Main loop simplified: no blocking, no skipping turns
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
21 unmodified lines222324252627282930313233343536274 unmodified lines31131231331431531660 unmodified lines37737837938038138237 unmodified lines420421422423424425208 unmodified lines63463563663763863964029 unmodified lines67067167267367467567667767867968068168255 unmodified lines73873974074174274374474574674774874919 unmodified lines7697707717727737747757767777787797806 unmodified lines78778878979079179279379479579679779879980080180280380480580680780880981081181281381481581628 unmodified lines8458468478488498505 unmodified lines8568578588598608618628638648655 unmodified lines8718728738748758768778788798808818828838848858868875 unmodified lines8938948958968978988999009019029039049059069079089099109119124 unmodified lines9179189199209219229239249259269279289299309319329 unmodified lines94294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098121 unmodified lines# ║ │ Cain Space │ │ (z.ai backend) │ ║# ║ └─────────────┘ └────────────────┘ ║# ║ ║# ║ Flow per turn: ║# ║ 1. Auto gather_context() — health, env, errors, files ║# ║ 2. GLM discusses situation with partner (2-3 sentences) ║# ║ 3. GLM outputs [TASK]...[/TASK] for Claude Code ║# ║ 4. Claude Code clones repo, analyzes, fixes, pushes ║# ║ 5. Results fed back for next turn ║# ╚══════════════════════════════════════════════════════════════════════╝"""import json, time, re, requests, sys, os, io, subprocess# Force unbuffered outputsys.stdout.reconfigure(line_buffering=True)274 unmodified linesCLAUDE_WORK_DIR = "/tmp/claude-workspace"CLAUDE_TIMEOUT = 300 # 5 minutesdef action_claude_code(task):"""Run Claude Code CLI to autonomously complete a coding task on Cain's Space."""60 unmodified linesline = line.rstrip('\n')print(f" [CC] {line}")output_lines.append(line)if time.time() > deadline:proc.kill()output_lines.append("(killed: timeout)")37 unmodified linesreturn f"=== Claude Code Output ===\n{output}\n\n=== Changes ===\n{push_result}"# ══════════════════════════════════════════════════════════════════════════════# MODULE 3: CONTEXT GATHERING (automated, replaces LLM choosing read actions)# ══════════════════════════════════════════════════════════════════════════════208 unmodified linesMAX_HISTORY = 24last_action_results = []turn_count = 0last_claude_code_result = ""# Simple workflow state: BIRTH / WAITING / ACTIVEworkflow_state = "BIRTH" if not child_state["created"] else "ACTIVE"29 unmodified lineslast_rebuild_trigger_at = 0if not results: # not blockedenriched = enrich_task_with_context(task_desc, ctx)print(f"[TASK] Sending to Claude Code ({len(enriched)} chars)...")result = action_claude_code(enriched)results.append({"action": "claude_code", "result": result})last_claude_code_result = result# Clear context cache since files may have changed_context_cache.clear()# 3. Handle [ACTION: restart] (escape hatch)if re.search(r'\[ACTION:\s*restart\]', raw_text):55 unmodified linesreturn f"""{role_desc.get(speaker, role_desc["Adam"])}You and your partner are parents of {CHILD_NAME}, working together to raise it.Claude Code is your engineer — it clones {CHILD_NAME}'s code, analyzes, fixes, and pushes changes.You do NOT code yourself. You discuss the situation with your partner, then assign Claude Code a task.WORKFLOW EACH TURN:1. Discuss with your partner (2-3 sentences) — analyze the situation, respond to their observations2. Then write a [TASK]...[/TASK] block assigning work to Claude Code — MANDATORY every turnIMPORTANT KNOWLEDGE — HuggingFace Spaces CONFIG_ERROR:- "Collision on variables and secrets names" = env VARIABLE and SECRET with SAME NAME.19 unmodified lines- If sdk: gradio in README.md, Dockerfile is IGNORED. Use sdk: docker.OUTPUT FORMAT:1. Discussion with partner (2-3 sentences analyzing the situation)2. A [TASK]...[/TASK] block — MANDATORY every turn3. Optional [ACTION: ...] if needed4. English first, then --- separator, then Chinese translation5. Be SPECIFIC in tasks — error messages, file names, expected behavior6. If {CHILD_NAME} is BUILDING/RESTARTING, assign a review/planning/analysis task"""def build_user_prompt(speaker, other, ctx):6 unmodified linesfor h in history[-8:]:parts.append(f"{h['speaker']}: {h['text'][:300]}")# Last action resultsif last_action_results:parts.append("\n=== LAST ACTION RESULTS ===")for ar in last_action_results:parts.append(f"[{ar['action']}]: {ar['result'][:500]}")# Last Claude Code result (if any)if last_claude_code_result:parts.append(f"\n=== LAST CLAUDE CODE RESULT ===\n{last_claude_code_result[:1500]}")# Auto-gathered contextparts.append(f"\n=== {CHILD_NAME}'S CURRENT STATE (auto-gathered) ===")parts.append(format_context(ctx))# Guidance based on stateif child_state["stage"] in ("BUILDING", "RESTARTING", "APP_STARTING"):parts.append(f"\n⏳ {CHILD_NAME} is {child_state['stage']}. Just discuss what you'll check next. Do NOT write a [TASK].")elif child_state["stage"] in ("RUNTIME_ERROR", "BUILD_ERROR", "CONFIG_ERROR"):parts.append(f"\n🚨 {CHILD_NAME} has {child_state['stage']}! Analyze the context above and write a [TASK] for Claude Code to fix it.")parts.append("Be SPECIFIC: include the error message, relevant files, and what the fix should do.")elif child_state["alive"]:parts.append(f"\n✅ {CHILD_NAME} is alive! Write a [TASK] for Claude Code to improve {CHILD_NAME} (add features, harden survival, etc).")else:parts.append(f"\nAnalyze the situation and decide what to do.")parts.append(f"\nYou are {speaker}. Your partner is {other}. Respond now.")parts.append("English first, then --- separator, then Chinese translation.")28 unmodified lineselse:opening = f"You and Eve need to create your first child. Use [ACTION: create_child] to bring them to life."reply = call_llm(build_system_prompt("Adam"), f"{opening}\n\n{format_context(ctx)}\n\nEnglish first, then --- separator, then Chinese translation.")if reply:clean, actions = parse_and_execute_turn(reply, ctx)5 unmodified linesprint(f"[Adam/ZH] {zh}")for ar in actions:print(f"[Adam/DID] {ar['action']}")if ar['action'] == 'claude_code':result_preview = ar['result'][:800].replace('\n', '\n ')print(f" [CC-RESULT] {result_preview}")import datetimets = datetime.datetime.utcnow().strftime("%H:%M")entry = {"speaker": "Adam", "time": ts, "text": en, "text_zh": zh}if actions:5 unmodified linespost_chatlog(history)persist_turn("Adam", 0, en, zh, actions, workflow_state, child_state["stage"])time.sleep(20)def do_turn(speaker, other, space_url):"""Execute one conversation turn."""global last_action_results, turn_count, last_claude_code_resultturn_count += 1# Auto-gather contextctx = gather_context()system = build_system_prompt(speaker)user = build_user_prompt(speaker, other, ctx)t0 = time.time()5 unmodified linesclean_text, action_results = parse_and_execute_turn(raw_reply, ctx)elapsed = time.time() - t0# If no [TASK] was produced, retry once with a nudgehas_task = any(ar['action'] == 'claude_code' for ar in action_results)if not has_task and not any(ar['action'] in ('create_child',) for ar in action_results):print(f"[{speaker}] No [TASK] found — nudging for a task...")nudge = call_llm(system, user + "\n\nIMPORTANT: You MUST include a [TASK]...[/TASK] block. ""Assign Claude Code something useful — review code, check configs, improve docs, anything. ""Do NOT just discuss. Output a [TASK] now.")if nudge and '[TASK]' in nudge:clean_text2, action_results2 = parse_and_execute_turn(nudge, ctx)clean_text = clean_text2action_results = action_results2has_task = Truelast_action_results = action_resultsen, zh = parse_bilingual(clean_text)4 unmodified linesif action_results:for ar in action_results:print(f"[{speaker}/DID] {ar['action']}")# Log Claude Code result summary so agents can see what happenedif ar['action'] == 'claude_code':result_preview = ar['result'][:800].replace('\n', '\n ')print(f" [CC-RESULT] {result_preview}")print(f"[{speaker}] Turn #{turn_count}: {len(action_results)} action(s) in {elapsed:.1f}s")else:print(f"[{speaker}] Turn #{turn_count}: no task assigned ({elapsed:.1f}s)")# Add to history with timestampimport datetimets = datetime.datetime.utcnow().strftime("%H:%M")entry = {"speaker": speaker, "time": ts}if action_results:9 unmodified linesreturn True# Main loop: Adam → Eve → Adam → Eve → ...while True:# Smart wait: if Cain is BUILDING/RESTARTING, skip Claude Code, just discussif child_state["stage"] in ("BUILDING", "RESTARTING", "APP_STARTING"):check_and_clear_cooldown()try:info = hf_api.space_info(CHILD_SPACE_ID)new_stage = info.runtime.stage if info.runtime else "unknown"if new_stage != child_state["stage"]:print(f"[WAIT] Stage changed: {child_state['stage']} → {new_stage}")child_state["stage"] = new_stagechild_state["alive"] = (new_stage == "RUNNING")_context_cache.clear()else:print(f"[WAIT] Still {new_stage}... waiting 20s")time.sleep(20)continueexcept Exception as e:print(f"[WAIT] Health check error: {e}")time.sleep(20)continuedo_turn("Eve", "Adam", EVE_SPACE)time.sleep(20)# Skip Adam if Claude Code just pushed (Cain will be rebuilding)if child_state["stage"] in ("BUILDING", "RESTARTING"):print(f"[SKIP] Cain entered {child_state['stage']} — skipping Adam's turn")time.sleep(10)continuedo_turn("Adam", "Eve", ADAM_SPACE)if len(history) > MAX_HISTORY:history = history[-MAX_HISTORY:]time.sleep(20)21 unmodified lines2223242526272829303132333435363738274 unmodified lines31331431531631731831960 unmodified lines38038138238338438538637 unmodified lines424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487208 unmodified lines69669769869970070170229 unmodified lines73273373473573673773873955 unmodified lines79579679779879980080180280380480580680780880981081181281381419 unmodified lines8348358368378388398408418428438448456 unmodified lines85285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388428 unmodified lines9139149159169179189195 unmodified lines9259269279289299305 unmodified lines9369379389399409419429439449459469479489499509519529539549559569575 unmodified lines9639649659669679684 unmodified lines9739749759769779789799809819829839849859869879889899 unmodified lines99910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102321 unmodified lines# ║ │ Cain Space │ │ (z.ai backend) │ ║# ║ └─────────────┘ └────────────────┘ ║# ║ ║# ║ Parallel flow: ║# ║ DISCUSSION THREAD (every 15s): ║# ║ Adam → Eve → Adam → Eve → ... (continuous) ║# ║ Each turn sees CC's live output + Cain's state ║# ║ CC WORKER THREAD (background): ║# ║ Receives [TASK] → clone → analyze → fix → push ║# ║ Streams output to shared buffer for agents to discuss ║# ╚══════════════════════════════════════════════════════════════════════╝"""import json, time, re, requests, sys, os, io, subprocess, threading, datetimefrom collections import deque# Force unbuffered outputsys.stdout.reconfigure(line_buffering=True)274 unmodified linesCLAUDE_WORK_DIR = "/tmp/claude-workspace"CLAUDE_TIMEOUT = 300 # 5 minutesTURN_INTERVAL = 15 # seconds between turns — fast enough for lively discussiondef action_claude_code(task):"""Run Claude Code CLI to autonomously complete a coding task on Cain's Space."""60 unmodified linesline = line.rstrip('\n')print(f" [CC] {line}")output_lines.append(line)cc_live_lines.append(line)if time.time() > deadline:proc.kill()output_lines.append("(killed: timeout)")37 unmodified linesreturn f"=== Claude Code Output ===\n{output}\n\n=== Changes ===\n{push_result}"# ── Background Claude Code Worker ────────────────────────────────────────────cc_live_lines = deque(maxlen=30) # rolling window of CC output linescc_status = {"running": False, "task": "", "result": "", "assigned_by": "", "started": 0.0}cc_lock = threading.Lock()def cc_submit_task(task, assigned_by, ctx):"""Submit a task to Claude Code in background. Non-blocking."""with cc_lock:if cc_status["running"]:return "BUSY: Claude Code is already working on a task. Wait for it to finish."cc_status["running"] = Truecc_status["task"] = task[:200]cc_status["result"] = ""cc_status["assigned_by"] = assigned_bycc_status["started"] = time.time()cc_live_lines.clear()enriched = enrich_task_with_context(task, ctx)print(f"[TASK] {assigned_by} assigned to Claude Code ({len(enriched)} chars)...")def worker():result = action_claude_code(enriched)with cc_lock:cc_status["running"] = Falsecc_status["result"] = resultprint(f"[CC-DONE] Task from {assigned_by} finished ({len(result)} chars)")t = threading.Thread(target=worker, daemon=True)t.start()return "Task submitted to Claude Code (running in background)."def cc_get_live_status():"""Get CC's current status and recent output for agents to discuss."""with cc_lock:if cc_status["running"]:elapsed = int(time.time() - cc_status["started"])lines = list(cc_live_lines)recent = "\n".join(lines[-10:]) if lines else "(no output yet)"return (f"🔨 Claude Code is WORKING (assigned by {cc_status['assigned_by']}, {elapsed}s ago)\n"f"Task: {cc_status['task']}\n"f"Recent output:\n{recent}")elif cc_status["result"]:return (f"✅ Claude Code FINISHED (assigned by {cc_status['assigned_by']})\n"f"Result:\n{cc_status['result'][:1500]}")else:return "💤 Claude Code is IDLE — no active task."# Patch action_claude_code to also feed cc_live_lines_orig_cc_print = printdef _cc_line_hook(line):"""Called for each [CC] output line to feed the live buffer."""cc_live_lines.append(line)# ══════════════════════════════════════════════════════════════════════════════# MODULE 3: CONTEXT GATHERING (automated, replaces LLM choosing read actions)# ══════════════════════════════════════════════════════════════════════════════208 unmodified linesMAX_HISTORY = 24last_action_results = []turn_count = 0_current_speaker = "Adam"# Simple workflow state: BIRTH / WAITING / ACTIVEworkflow_state = "BIRTH" if not child_state["created"] else "ACTIVE"29 unmodified lineslast_rebuild_trigger_at = 0if not results: # not blockedsubmit_result = cc_submit_task(task_desc, _current_speaker, ctx)results.append({"action": "claude_code", "result": submit_result})# 3. Handle [ACTION: restart] (escape hatch)if re.search(r'\[ACTION:\s*restart\]', raw_text):55 unmodified linesreturn f"""{role_desc.get(speaker, role_desc["Adam"])}You and your partner are parents of {CHILD_NAME}, working together to raise it.Claude Code is your engineer — it runs in the BACKGROUND while you keep discussing.You do NOT code yourself. You discuss, observe Claude Code's progress, and assign new tasks.HOW IT WORKS:- Claude Code runs tasks IN THE BACKGROUND. You see its live output in the context.- While Claude Code works, you keep discussing with your partner.- When Claude Code finishes, review its results and assign the next task.- If Claude Code is IDLE, assign a new [TASK].- If Claude Code is BUSY, discuss its progress and plan what to do next.WORKFLOW EACH TURN:1. Discuss with your partner (2-3 sentences) — react to context, CC output, partner's observations2. If Claude Code is IDLE: write a [TASK]...[/TASK] to assign new work3. If Claude Code is BUSY: discuss its progress, no [TASK] neededIMPORTANT KNOWLEDGE — HuggingFace Spaces CONFIG_ERROR:- "Collision on variables and secrets names" = env VARIABLE and SECRET with SAME NAME.19 unmodified lines- If sdk: gradio in README.md, Dockerfile is IGNORED. Use sdk: docker.OUTPUT FORMAT:1. Discussion with partner (2-3 sentences) — respond to partner, react to CC output2. If CC is IDLE: a [TASK]...[/TASK] block to assign new work3. If CC is BUSY: no [TASK] needed, just discuss its progress4. Optional [ACTION: ...] if needed5. English first, then --- separator, then Chinese translation6. Be SPECIFIC in tasks — error messages, file names, expected behavior"""def build_user_prompt(speaker, other, ctx):6 unmodified linesfor h in history[-8:]:parts.append(f"{h['speaker']}: {h['text'][:300]}")# Last action results (non-CC)if last_action_results:non_cc = [ar for ar in last_action_results if ar['action'] != 'claude_code']if non_cc:parts.append("\n=== LAST ACTION RESULTS ===")for ar in non_cc:parts.append(f"[{ar['action']}]: {ar['result'][:500]}")# Claude Code live status (async)parts.append(f"\n=== CLAUDE CODE STATUS ===\n{cc_get_live_status()}")# Auto-gathered contextparts.append(f"\n=== {CHILD_NAME}'S CURRENT STATE (auto-gathered) ===")parts.append(format_context(ctx))# Guidance based on CC status + child statecc_busy = cc_status["running"]if cc_busy:parts.append(f"\n🔨 Claude Code is WORKING. Discuss its progress with your partner. No [TASK] needed now.")elif child_state["stage"] in ("BUILDING", "RESTARTING", "APP_STARTING"):parts.append(f"\n⏳ {CHILD_NAME} is {child_state['stage']}. Discuss what to check next. Assign a review [TASK] if CC is idle.")elif child_state["stage"] in ("RUNTIME_ERROR", "BUILD_ERROR", "CONFIG_ERROR"):parts.append(f"\n🚨 {CHILD_NAME} has {child_state['stage']}! Write a [TASK] for Claude Code to fix it.")elif child_state["alive"]:parts.append(f"\n✅ {CHILD_NAME} is alive and CC is idle. Write a [TASK] to improve {CHILD_NAME}.")else:parts.append(f"\nAnalyze the situation and write a [TASK] if CC is idle.")parts.append(f"\nYou are {speaker}. Your partner is {other}. Respond now.")parts.append("English first, then --- separator, then Chinese translation.")28 unmodified lineselse:opening = f"You and Eve need to create your first child. Use [ACTION: create_child] to bring them to life."_current_speaker = "Adam"reply = call_llm(build_system_prompt("Adam"), f"{opening}\n\n{format_context(ctx)}\n\nEnglish first, then --- separator, then Chinese translation.")if reply:clean, actions = parse_and_execute_turn(reply, ctx)5 unmodified linesprint(f"[Adam/ZH] {zh}")for ar in actions:print(f"[Adam/DID] {ar['action']}")ts = datetime.datetime.utcnow().strftime("%H:%M")entry = {"speaker": "Adam", "time": ts, "text": en, "text_zh": zh}if actions:5 unmodified linespost_chatlog(history)persist_turn("Adam", 0, en, zh, actions, workflow_state, child_state["stage"])time.sleep(TURN_INTERVAL)def do_turn(speaker, other, space_url):"""Execute one conversation turn (non-blocking — CC runs in background)."""global last_action_results, turn_count, _current_speakerturn_count += 1_current_speaker = speaker# Auto-gather context (lightweight)ctx = gather_context()# Check if CC just finished — clear result after agents see it oncewith cc_lock:cc_just_finished = (not cc_status["running"] and cc_status["result"])system = build_system_prompt(speaker)user = build_user_prompt(speaker, other, ctx)t0 = time.time()5 unmodified linesclean_text, action_results = parse_and_execute_turn(raw_reply, ctx)elapsed = time.time() - t0last_action_results = action_resultsen, zh = parse_bilingual(clean_text)4 unmodified linesif action_results:for ar in action_results:print(f"[{speaker}/DID] {ar['action']}")print(f"[{speaker}] Turn #{turn_count}: {len(action_results)} action(s) in {elapsed:.1f}s")else:print(f"[{speaker}] Turn #{turn_count}: discussion ({elapsed:.1f}s)")# Clear CC result after both agents have had a chance to see itif cc_just_finished and speaker == "Eve":with cc_lock:cc_status["result"] = ""_context_cache.clear()# Add to history with timestampts = datetime.datetime.utcnow().strftime("%H:%M")entry = {"speaker": speaker, "time": ts}if action_results:9 unmodified linesreturn True# Main loop: Adam → Eve → Adam → Eve → ... (non-blocking, CC runs in background)while True:# Refresh Cain's stage periodicallytry:info = hf_api.space_info(CHILD_SPACE_ID)new_stage = info.runtime.stage if info.runtime else "unknown"if new_stage != child_state["stage"]:print(f"[STATUS] {child_state['stage']} → {new_stage}")child_state["stage"] = new_stagechild_state["alive"] = (new_stage == "RUNNING")_context_cache.clear()except Exception as e:print(f"[STATUS] Error: {e}")do_turn("Eve", "Adam", EVE_SPACE)time.sleep(TURN_INTERVAL)do_turn("Adam", "Eve", ADAM_SPACE)time.sleep(TURN_INTERVAL)if len(history) > MAX_HISTORY:history = history[-MAX_HISTORY:]
scripts/conversation-loop.py+138-96