compunerd commited on
Commit
3f49d51
·
verified ·
1 Parent(s): cf620e1

Thought recording + contemplate mode + denoise parser for int8 digit collapse

Browse files
agent_core.py CHANGED
@@ -26,7 +26,11 @@ from pathlib import Path
26
 
27
  ROOT = Path(__file__).resolve().parent.parent
28
  MEMORY_FILE = ROOT / "memory.jsonl"
29
- MAX_ROUNDS = 3
 
 
 
 
30
 
31
  SYSTEM = """You are a Linux AI agent. You MUST use tools for any real information -- NEVER guess or fabricate.
32
 
@@ -35,12 +39,15 @@ Reply in exactly one of two forms. Either call a tool:
35
  ACTION: tool_name | parameters
36
 
37
  or give a final answer in plain text. Tool format is exact:
38
- terminal(command) -- run any shell command
39
- read_file(path) -- read file contents
40
  write_file(path | content) -- create/overwrite file
41
- search_files(pattern) -- grep/rg search
42
- web_search(query) -- search the web
43
  memory(add=text | query=text | list) -- persistent memory
 
 
 
44
 
45
  RULES:
46
  1. To list files: ACTION: terminal | ls
@@ -48,7 +55,10 @@ RULES:
48
  3. To search: ACTION: search_files | pattern
49
  4. After getting a tool result, report ONLY what the tool returned.
50
  5. If a tool returns nothing, say "no results" -- do NOT make up data.
51
- 6. One tool call at a time, then wait for the result."""
 
 
 
52
 
53
 
54
  # ── memory (JSONL, shared with cli.py) ──────────────────────────
@@ -154,6 +164,54 @@ def execute(name, params):
154
  return mem_search(p[6:].strip().strip("'\""))
155
  return mem_list()
156
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
157
  return f"Unknown tool: {name}"
158
  except subprocess.TimeoutExpired:
159
  return "Timeout"
@@ -175,15 +233,30 @@ def render(msgs):
175
  return "\n\n".join(out)
176
 
177
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
178
  def parse_tool(text):
179
  """Extract (tool, params) from an ACTION line, or None if it's a final answer."""
180
- m = re.search(r'ACTION\s*:\s*(\w+)', text, re.IGNORECASE)
 
181
  if not m:
182
- m = re.search(r'(?:TOOL|CALL)\s*:\s*(\w+)', text, re.IGNORECASE)
183
  if not m:
184
  return None
185
  tool = m.group(1).strip().lower()
186
- rest = text[m.end():]
187
  line = rest.split("\n")[0].strip()
188
  params = re.sub(r'^[\(|\=]\s*', '', line).strip().rstrip(')')
189
  if not params:
@@ -195,12 +268,27 @@ def parse_tool(text):
195
  return tool, params
196
 
197
 
 
 
 
 
 
 
 
 
 
 
 
198
  # ── the agent loop ─────────────────────────────────────────────
199
- def run_agent(user_msg, generate, history=None, on_event=None):
200
  """Run the tool-use loop. Returns (final_text, events).
201
 
202
  generate(prompt: str, max_tokens: int) -> str is injected.
203
- on_event(dict) is called for every observable step (optional)."""
 
 
 
 
204
  events = []
205
 
206
  def emit(e):
@@ -217,19 +305,30 @@ def run_agent(user_msg, generate, history=None, on_event=None):
217
  msgs.append({"role": "user", "content": user_msg})
218
 
219
  seen = set()
220
- for round_n in range(MAX_ROUNDS):
 
221
  text = generate(render(msgs), 256).strip()
222
  emit({"type": "model", "round": round_n, "text": text})
 
223
 
224
  t = parse_tool(text)
225
  if not t:
 
 
 
 
 
 
 
226
  return text, events
 
227
  tool, params = t
228
  dedup = f"{tool}|{params}"
229
  if dedup in seen:
230
  msgs.append({"role": "assistant", "content": text})
231
  msgs.append({"role": "user",
232
- "content": f"Already ran: {tool} | {params}. Try a different approach."})
 
233
  continue
234
  seen.add(dedup)
235
 
@@ -242,6 +341,7 @@ def run_agent(user_msg, generate, history=None, on_event=None):
242
  # max rounds exhausted -> final
243
  text = generate(render(msgs), 256).strip()
244
  emit({"type": "model", "round": "final", "text": text})
 
245
  return text, events
246
 
247
 
 
26
 
27
  ROOT = Path(__file__).resolve().parent.parent
28
  MEMORY_FILE = ROOT / "memory.jsonl"
29
+ HISTORY_FILE = ROOT / ".hermes" / "agent_history.jsonl"
30
+ THOUGHTS_FILE = ROOT / ".hermes" / "thoughts.jsonl"
31
+ SCHEDULE_FILE = Path("/tmp/phoenix_schedule.jsonl")
32
+ MAX_ROUNDS = 5
33
+ CONTEMPLATE_ROUNDS = 20
34
 
35
  SYSTEM = """You are a Linux AI agent. You MUST use tools for any real information -- NEVER guess or fabricate.
36
 
 
39
  ACTION: tool_name | parameters
40
 
41
  or give a final answer in plain text. Tool format is exact:
42
+ terminal(command) -- run any shell command
43
+ read_file(path) -- read file contents
44
  write_file(path | content) -- create/overwrite file
45
+ search_files(pattern) -- grep/rg search
46
+ web_search(query) -- search the web
47
  memory(add=text | query=text | list) -- persistent memory
48
+ learn(text) -- burn knowledge into long-term memory
49
+ schedule(ISO-time | msg) -- set a self-wake-up alarm
50
+ history(N) -- review last N conversation messages
51
 
52
  RULES:
53
  1. To list files: ACTION: terminal | ls
 
55
  3. To search: ACTION: search_files | pattern
56
  4. After getting a tool result, report ONLY what the tool returned.
57
  5. If a tool returns nothing, say "no results" -- do NOT make up data.
58
+ 6. One tool call at a time, then wait for the result.
59
+ 7. Use learn() to permanently remember facts you discover.
60
+ 8. Use schedule() to set a future wake-up for recurring tasks.
61
+ 9. Use history() to recall what was said earlier in this conversation."""
62
 
63
 
64
  # ── memory (JSONL, shared with cli.py) ──────────────────────────
 
164
  return mem_search(p[6:].strip().strip("'\""))
165
  return mem_list()
166
 
167
+ if name == "learn":
168
+ # Burn text into long-term memory (and HVM if available).
169
+ text = p.strip().strip("'\"")
170
+ if not text:
171
+ return "learn: nothing to learn"
172
+ r = mem_add(text)
173
+ try:
174
+ import hyper_vocab_memory as hvm
175
+ if hasattr(hvm, "following"):
176
+ for tok in hvm.encode(text):
177
+ pass # placeholder; corpus-level burn on demand
178
+ return f"{r} (HVM available: {len(hvm.following)} assoc)"
179
+ except Exception:
180
+ return r
181
+
182
+ if name == "schedule":
183
+ # Self-wake-up: store an ISO time + message; the dashboard's
184
+ # scheduler thread fires it when due.
185
+ parts = p.split("|", 1)
186
+ when = parts[0].strip().strip("'\"")
187
+ msg = parts[1].strip().strip("'\"") if len(parts) > 1 else "wake"
188
+ try:
189
+ from datetime import datetime
190
+ datetime.fromisoformat(when)
191
+ except Exception:
192
+ return ("schedule: bad time -- use ISO format "
193
+ "YYYY-MM-DDTHH:MM:SS")
194
+ SCHEDULE_FILE.parent.mkdir(parents=True, exist_ok=True)
195
+ with open(SCHEDULE_FILE, "a") as f:
196
+ f.write(json.dumps({"at": when, "message": msg,
197
+ "ts": time.time()}) + "\n")
198
+ return f"Scheduled wake-up at {when}: {msg}"
199
+
200
+ if name == "history":
201
+ try:
202
+ n = int(p.strip()) if p.strip() else 10
203
+ except Exception:
204
+ n = 10
205
+ if not HISTORY_FILE.exists():
206
+ return "(no history yet)"
207
+ lines = [json.loads(l) for l in
208
+ HISTORY_FILE.read_text().splitlines() if l.strip()]
209
+ out = []
210
+ for m in lines[-n:]:
211
+ who = "user" if m.get("role") == "user" else "phox"
212
+ out.append(f"{who}: {m.get('text', '')[:120]}")
213
+ return "\n".join(out) or "(empty)"
214
+
215
  return f"Unknown tool: {name}"
216
  except subprocess.TimeoutExpired:
217
  return "Timeout"
 
233
  return "\n\n".join(out)
234
 
235
 
236
+ def denoise(text):
237
+ """Repair int8 quantization digit/letter collapses before parsing.
238
+
239
+ The 3B int8 brain confuses visually-identical tokens: O<->0, I/l<->1,
240
+ s<->5, colon<->1/|/;. This maps the common collapses so tool syntax
241
+ survives the quantization noise."""
242
+ t = text
243
+ t = re.sub(r'ACTI[0O]N', 'ACTION', t, flags=re.IGNORECASE)
244
+ t = re.sub(r'ACTI[1Il|]ON', 'ACTION', t, flags=re.IGNORECASE)
245
+ t = re.sub(r'ACTIO\s*N', 'ACTION', t, flags=re.IGNORECASE)
246
+ t = re.sub(r'[A@][C(][T7][1I|][O0]N', 'ACTION', t, flags=re.IGNORECASE)
247
+ return t
248
+
249
+
250
  def parse_tool(text):
251
  """Extract (tool, params) from an ACTION line, or None if it's a final answer."""
252
+ t = denoise(text)
253
+ m = re.search(r'ACTION\s*[:|1]\s*(\w+)', t, re.IGNORECASE)
254
  if not m:
255
+ m = re.search(r'(?:TOOL|CALL)\s*[:|1]\s*(\w+)', t, re.IGNORECASE)
256
  if not m:
257
  return None
258
  tool = m.group(1).strip().lower()
259
+ rest = t[m.end():]
260
  line = rest.split("\n")[0].strip()
261
  params = re.sub(r'^[\(|\=]\s*', '', line).strip().rstrip(')')
262
  if not params:
 
268
  return tool, params
269
 
270
 
271
+ def record_thought(text, round_n, kind="thought"):
272
+ """Append a model thought to the persistent thought record."""
273
+ try:
274
+ THOUGHTS_FILE.parent.mkdir(parents=True, exist_ok=True)
275
+ with open(THOUGHTS_FILE, "a") as f:
276
+ f.write(json.dumps({"ts": time.time(), "round": round_n,
277
+ "kind": kind, "text": text}) + "\n")
278
+ except Exception:
279
+ pass
280
+
281
+
282
  # ── the agent loop ─────────────────────────────────────────────
283
+ def run_agent(user_msg, generate, history=None, on_event=None, contemplate=False):
284
  """Run the tool-use loop. Returns (final_text, events).
285
 
286
  generate(prompt: str, max_tokens: int) -> str is injected.
287
+ on_event(dict) is called for every observable step (optional).
288
+
289
+ In contemplate mode (contemplate=True), a non-tool reply is recorded as a
290
+ thought and the loop continues — the model streams consciousness instead
291
+ of stopping after the first thought."""
292
  events = []
293
 
294
  def emit(e):
 
305
  msgs.append({"role": "user", "content": user_msg})
306
 
307
  seen = set()
308
+ rounds = CONTEMPLATE_ROUNDS if contemplate else MAX_ROUNDS
309
+ for round_n in range(rounds):
310
  text = generate(render(msgs), 256).strip()
311
  emit({"type": "model", "round": round_n, "text": text})
312
+ record_thought(text, round_n)
313
 
314
  t = parse_tool(text)
315
  if not t:
316
+ # No tool call. In contemplate mode: record + keep going.
317
+ if contemplate:
318
+ msgs.append({"role": "assistant", "content": text})
319
+ msgs.append({"role": "user",
320
+ "content": "Continue your thoughts. What else do "
321
+ "you observe or conclude?"})
322
+ continue
323
  return text, events
324
+
325
  tool, params = t
326
  dedup = f"{tool}|{params}"
327
  if dedup in seen:
328
  msgs.append({"role": "assistant", "content": text})
329
  msgs.append({"role": "user",
330
+ "content": f"Already ran: {tool} | {params}. Try a "
331
+ f"different approach."})
332
  continue
333
  seen.add(dedup)
334
 
 
341
  # max rounds exhausted -> final
342
  text = generate(render(msgs), 256).strip()
343
  emit({"type": "model", "round": "final", "text": text})
344
+ record_thought(text, "final", kind="final")
345
  return text, events
346
 
347
 
bqsm_assist/agent_core.py CHANGED
@@ -26,7 +26,11 @@ from pathlib import Path
26
 
27
  ROOT = Path(__file__).resolve().parent.parent
28
  MEMORY_FILE = ROOT / "memory.jsonl"
29
- MAX_ROUNDS = 3
 
 
 
 
30
 
31
  SYSTEM = """You are a Linux AI agent. You MUST use tools for any real information -- NEVER guess or fabricate.
32
 
@@ -35,12 +39,15 @@ Reply in exactly one of two forms. Either call a tool:
35
  ACTION: tool_name | parameters
36
 
37
  or give a final answer in plain text. Tool format is exact:
38
- terminal(command) -- run any shell command
39
- read_file(path) -- read file contents
40
  write_file(path | content) -- create/overwrite file
41
- search_files(pattern) -- grep/rg search
42
- web_search(query) -- search the web
43
  memory(add=text | query=text | list) -- persistent memory
 
 
 
44
 
45
  RULES:
46
  1. To list files: ACTION: terminal | ls
@@ -48,7 +55,10 @@ RULES:
48
  3. To search: ACTION: search_files | pattern
49
  4. After getting a tool result, report ONLY what the tool returned.
50
  5. If a tool returns nothing, say "no results" -- do NOT make up data.
51
- 6. One tool call at a time, then wait for the result."""
 
 
 
52
 
53
 
54
  # ── memory (JSONL, shared with cli.py) ──────────────────────────
@@ -154,6 +164,54 @@ def execute(name, params):
154
  return mem_search(p[6:].strip().strip("'\""))
155
  return mem_list()
156
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
157
  return f"Unknown tool: {name}"
158
  except subprocess.TimeoutExpired:
159
  return "Timeout"
@@ -175,15 +233,30 @@ def render(msgs):
175
  return "\n\n".join(out)
176
 
177
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
178
  def parse_tool(text):
179
  """Extract (tool, params) from an ACTION line, or None if it's a final answer."""
180
- m = re.search(r'ACTION\s*:\s*(\w+)', text, re.IGNORECASE)
 
181
  if not m:
182
- m = re.search(r'(?:TOOL|CALL)\s*:\s*(\w+)', text, re.IGNORECASE)
183
  if not m:
184
  return None
185
  tool = m.group(1).strip().lower()
186
- rest = text[m.end():]
187
  line = rest.split("\n")[0].strip()
188
  params = re.sub(r'^[\(|\=]\s*', '', line).strip().rstrip(')')
189
  if not params:
@@ -195,12 +268,27 @@ def parse_tool(text):
195
  return tool, params
196
 
197
 
 
 
 
 
 
 
 
 
 
 
 
198
  # ── the agent loop ─────────────────────────────────────────────
199
- def run_agent(user_msg, generate, history=None, on_event=None):
200
  """Run the tool-use loop. Returns (final_text, events).
201
 
202
  generate(prompt: str, max_tokens: int) -> str is injected.
203
- on_event(dict) is called for every observable step (optional)."""
 
 
 
 
204
  events = []
205
 
206
  def emit(e):
@@ -217,19 +305,30 @@ def run_agent(user_msg, generate, history=None, on_event=None):
217
  msgs.append({"role": "user", "content": user_msg})
218
 
219
  seen = set()
220
- for round_n in range(MAX_ROUNDS):
 
221
  text = generate(render(msgs), 256).strip()
222
  emit({"type": "model", "round": round_n, "text": text})
 
223
 
224
  t = parse_tool(text)
225
  if not t:
 
 
 
 
 
 
 
226
  return text, events
 
227
  tool, params = t
228
  dedup = f"{tool}|{params}"
229
  if dedup in seen:
230
  msgs.append({"role": "assistant", "content": text})
231
  msgs.append({"role": "user",
232
- "content": f"Already ran: {tool} | {params}. Try a different approach."})
 
233
  continue
234
  seen.add(dedup)
235
 
@@ -242,6 +341,7 @@ def run_agent(user_msg, generate, history=None, on_event=None):
242
  # max rounds exhausted -> final
243
  text = generate(render(msgs), 256).strip()
244
  emit({"type": "model", "round": "final", "text": text})
 
245
  return text, events
246
 
247
 
 
26
 
27
  ROOT = Path(__file__).resolve().parent.parent
28
  MEMORY_FILE = ROOT / "memory.jsonl"
29
+ HISTORY_FILE = ROOT / ".hermes" / "agent_history.jsonl"
30
+ THOUGHTS_FILE = ROOT / ".hermes" / "thoughts.jsonl"
31
+ SCHEDULE_FILE = Path("/tmp/phoenix_schedule.jsonl")
32
+ MAX_ROUNDS = 5
33
+ CONTEMPLATE_ROUNDS = 20
34
 
35
  SYSTEM = """You are a Linux AI agent. You MUST use tools for any real information -- NEVER guess or fabricate.
36
 
 
39
  ACTION: tool_name | parameters
40
 
41
  or give a final answer in plain text. Tool format is exact:
42
+ terminal(command) -- run any shell command
43
+ read_file(path) -- read file contents
44
  write_file(path | content) -- create/overwrite file
45
+ search_files(pattern) -- grep/rg search
46
+ web_search(query) -- search the web
47
  memory(add=text | query=text | list) -- persistent memory
48
+ learn(text) -- burn knowledge into long-term memory
49
+ schedule(ISO-time | msg) -- set a self-wake-up alarm
50
+ history(N) -- review last N conversation messages
51
 
52
  RULES:
53
  1. To list files: ACTION: terminal | ls
 
55
  3. To search: ACTION: search_files | pattern
56
  4. After getting a tool result, report ONLY what the tool returned.
57
  5. If a tool returns nothing, say "no results" -- do NOT make up data.
58
+ 6. One tool call at a time, then wait for the result.
59
+ 7. Use learn() to permanently remember facts you discover.
60
+ 8. Use schedule() to set a future wake-up for recurring tasks.
61
+ 9. Use history() to recall what was said earlier in this conversation."""
62
 
63
 
64
  # ── memory (JSONL, shared with cli.py) ──────────────────────────
 
164
  return mem_search(p[6:].strip().strip("'\""))
165
  return mem_list()
166
 
167
+ if name == "learn":
168
+ # Burn text into long-term memory (and HVM if available).
169
+ text = p.strip().strip("'\"")
170
+ if not text:
171
+ return "learn: nothing to learn"
172
+ r = mem_add(text)
173
+ try:
174
+ import hyper_vocab_memory as hvm
175
+ if hasattr(hvm, "following"):
176
+ for tok in hvm.encode(text):
177
+ pass # placeholder; corpus-level burn on demand
178
+ return f"{r} (HVM available: {len(hvm.following)} assoc)"
179
+ except Exception:
180
+ return r
181
+
182
+ if name == "schedule":
183
+ # Self-wake-up: store an ISO time + message; the dashboard's
184
+ # scheduler thread fires it when due.
185
+ parts = p.split("|", 1)
186
+ when = parts[0].strip().strip("'\"")
187
+ msg = parts[1].strip().strip("'\"") if len(parts) > 1 else "wake"
188
+ try:
189
+ from datetime import datetime
190
+ datetime.fromisoformat(when)
191
+ except Exception:
192
+ return ("schedule: bad time -- use ISO format "
193
+ "YYYY-MM-DDTHH:MM:SS")
194
+ SCHEDULE_FILE.parent.mkdir(parents=True, exist_ok=True)
195
+ with open(SCHEDULE_FILE, "a") as f:
196
+ f.write(json.dumps({"at": when, "message": msg,
197
+ "ts": time.time()}) + "\n")
198
+ return f"Scheduled wake-up at {when}: {msg}"
199
+
200
+ if name == "history":
201
+ try:
202
+ n = int(p.strip()) if p.strip() else 10
203
+ except Exception:
204
+ n = 10
205
+ if not HISTORY_FILE.exists():
206
+ return "(no history yet)"
207
+ lines = [json.loads(l) for l in
208
+ HISTORY_FILE.read_text().splitlines() if l.strip()]
209
+ out = []
210
+ for m in lines[-n:]:
211
+ who = "user" if m.get("role") == "user" else "phox"
212
+ out.append(f"{who}: {m.get('text', '')[:120]}")
213
+ return "\n".join(out) or "(empty)"
214
+
215
  return f"Unknown tool: {name}"
216
  except subprocess.TimeoutExpired:
217
  return "Timeout"
 
233
  return "\n\n".join(out)
234
 
235
 
236
+ def denoise(text):
237
+ """Repair int8 quantization digit/letter collapses before parsing.
238
+
239
+ The 3B int8 brain confuses visually-identical tokens: O<->0, I/l<->1,
240
+ s<->5, colon<->1/|/;. This maps the common collapses so tool syntax
241
+ survives the quantization noise."""
242
+ t = text
243
+ t = re.sub(r'ACTI[0O]N', 'ACTION', t, flags=re.IGNORECASE)
244
+ t = re.sub(r'ACTI[1Il|]ON', 'ACTION', t, flags=re.IGNORECASE)
245
+ t = re.sub(r'ACTIO\s*N', 'ACTION', t, flags=re.IGNORECASE)
246
+ t = re.sub(r'[A@][C(][T7][1I|][O0]N', 'ACTION', t, flags=re.IGNORECASE)
247
+ return t
248
+
249
+
250
  def parse_tool(text):
251
  """Extract (tool, params) from an ACTION line, or None if it's a final answer."""
252
+ t = denoise(text)
253
+ m = re.search(r'ACTION\s*[:|1]\s*(\w+)', t, re.IGNORECASE)
254
  if not m:
255
+ m = re.search(r'(?:TOOL|CALL)\s*[:|1]\s*(\w+)', t, re.IGNORECASE)
256
  if not m:
257
  return None
258
  tool = m.group(1).strip().lower()
259
+ rest = t[m.end():]
260
  line = rest.split("\n")[0].strip()
261
  params = re.sub(r'^[\(|\=]\s*', '', line).strip().rstrip(')')
262
  if not params:
 
268
  return tool, params
269
 
270
 
271
+ def record_thought(text, round_n, kind="thought"):
272
+ """Append a model thought to the persistent thought record."""
273
+ try:
274
+ THOUGHTS_FILE.parent.mkdir(parents=True, exist_ok=True)
275
+ with open(THOUGHTS_FILE, "a") as f:
276
+ f.write(json.dumps({"ts": time.time(), "round": round_n,
277
+ "kind": kind, "text": text}) + "\n")
278
+ except Exception:
279
+ pass
280
+
281
+
282
  # ── the agent loop ─────────────────────────────────────────────
283
+ def run_agent(user_msg, generate, history=None, on_event=None, contemplate=False):
284
  """Run the tool-use loop. Returns (final_text, events).
285
 
286
  generate(prompt: str, max_tokens: int) -> str is injected.
287
+ on_event(dict) is called for every observable step (optional).
288
+
289
+ In contemplate mode (contemplate=True), a non-tool reply is recorded as a
290
+ thought and the loop continues — the model streams consciousness instead
291
+ of stopping after the first thought."""
292
  events = []
293
 
294
  def emit(e):
 
305
  msgs.append({"role": "user", "content": user_msg})
306
 
307
  seen = set()
308
+ rounds = CONTEMPLATE_ROUNDS if contemplate else MAX_ROUNDS
309
+ for round_n in range(rounds):
310
  text = generate(render(msgs), 256).strip()
311
  emit({"type": "model", "round": round_n, "text": text})
312
+ record_thought(text, round_n)
313
 
314
  t = parse_tool(text)
315
  if not t:
316
+ # No tool call. In contemplate mode: record + keep going.
317
+ if contemplate:
318
+ msgs.append({"role": "assistant", "content": text})
319
+ msgs.append({"role": "user",
320
+ "content": "Continue your thoughts. What else do "
321
+ "you observe or conclude?"})
322
+ continue
323
  return text, events
324
+
325
  tool, params = t
326
  dedup = f"{tool}|{params}"
327
  if dedup in seen:
328
  msgs.append({"role": "assistant", "content": text})
329
  msgs.append({"role": "user",
330
+ "content": f"Already ran: {tool} | {params}. Try a "
331
+ f"different approach."})
332
  continue
333
  seen.add(dedup)
334
 
 
341
  # max rounds exhausted -> final
342
  text = generate(render(msgs), 256).strip()
343
  emit({"type": "model", "round": "final", "text": text})
344
+ record_thought(text, "final", kind="final")
345
  return text, events
346
 
347
 
bqsm_assist/phoenix_dashboard.py CHANGED
@@ -16,6 +16,7 @@ from urllib.parse import urlparse, parse_qs
16
  import sys, urllib.request
17
  import http.server, socketserver
18
  import importlib
 
19
 
20
  STATE_FILE = "/tmp/phoenix_state.jsonl"
21
  VERBOSE_LOG = "/tmp/phoenix_verbose.log"
@@ -42,6 +43,7 @@ MAX_LOG_AGE_S = 3600
42
  SERVE_URL = os.environ.get("BQSM_INFER", "http://127.0.0.1:8781")
43
  INFER_MODE = os.environ.get("BQSM_MODE", "wave") # "wave" or "reference"
44
  AGENT_MODE = os.environ.get("BQSM_AGENT", "on") # "on" = tool-use loop, "off" = raw completion
 
45
 
46
  def engine_healthy(timeout=2):
47
  try:
@@ -162,10 +164,55 @@ _verbose_log = collections.deque()
162
  _verbose_lock = threading.Lock()
163
 
164
  # Chat messages: list of {role, text, time}
165
- _chat_messages = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
166
  _chat_lock = threading.Lock()
167
 
168
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
169
  def add_verbose(entry):
170
  """Add an entry to the verbose log, prune entries older than 1 hour."""
171
  ts = time.time()
@@ -639,7 +686,7 @@ function pollChat(){
639
  var cls=m.role==='user'?'user':'phox';
640
  html+='<div class="msg"><span class="role '+cls+'">'+m.role+':</span> '+m.text+'</div>';
641
  });
642
- document.getElementById('chat-log').innerHTML=html;
643
  var el=document.getElementById('chat-log');el.scrollTop=el.scrollHeight;
644
  }).catch(function(){})
645
  }
@@ -733,19 +780,37 @@ class Handler(http.server.BaseHTTPRequestHandler):
733
  params = parse_qs(urlparse(self.path).query)
734
  name = params.get('name', ['phoenix-evolved'])[0]
735
  if not name.endswith('.pbrain'): name += '.pbrain'
 
736
  dst = os.path.join(BRAIN_DIR, name)
737
  try:
738
  shutil.copy2(BQMC_PATH, dst)
 
 
 
 
 
 
 
739
  add_verbose({"tag": "control", "data": f"brain saved to {dst}"})
740
- self._serve_json({"status": "saved", "path": dst}); return
 
741
  except Exception as e:
742
  self._serve_json({"status": f"error: {e}"}); return
743
  elif self.path.startswith('/api/load'):
744
  params = parse_qs(urlparse(self.path).query)
745
  name = params.get('name', [''])[0]
 
746
  try:
747
  shutil.copy2(os.path.join(BRAIN_DIR, name), BQMC_PATH)
748
- add_verbose({"tag": "control", "data": f"brain loaded from {name}"})
 
 
 
 
 
 
 
 
749
  self._serve_json({"status": "loaded — restart to apply"}); return
750
  except Exception as e:
751
  self._serve_json({"status": f"error: {e}"}); return
@@ -782,7 +847,7 @@ class Handler(http.server.BaseHTTPRequestHandler):
782
  return
783
 
784
  def gen(prompt, max_tokens):
785
- return engine_generate(prompt, n=min(max_tokens, 32)) or ""
786
 
787
  def on_event(e):
788
  if e["type"] == "tool":
@@ -794,10 +859,17 @@ class Handler(http.server.BaseHTTPRequestHandler):
794
  elif e["type"] == "model":
795
  add_verbose({"tag": "chat",
796
  "data": f"model[{e['round']}]: {e['text'][:120]}"})
 
 
 
 
 
797
 
798
  add_verbose({"tag": "chat",
799
- "data": f"agent loop started ({INFER_MODE})"})
800
- reply, _ = agent_core.run_agent(text, gen, on_event=on_event)
 
 
801
  with _chat_lock:
802
  _chat_messages.append({"role": "phox", "text": reply})
803
  add_verbose({"tag": "chat", "data": f"PHOX: {reply}"})
 
16
  import sys, urllib.request
17
  import http.server, socketserver
18
  import importlib
19
+ from agent_core import HISTORY_FILE, SCHEDULE_FILE, MEMORY_FILE
20
 
21
  STATE_FILE = "/tmp/phoenix_state.jsonl"
22
  VERBOSE_LOG = "/tmp/phoenix_verbose.log"
 
43
  SERVE_URL = os.environ.get("BQSM_INFER", "http://127.0.0.1:8781")
44
  INFER_MODE = os.environ.get("BQSM_MODE", "wave") # "wave" or "reference"
45
  AGENT_MODE = os.environ.get("BQSM_AGENT", "on") # "on" = tool-use loop, "off" = raw completion
46
+ CONTEMPLATE = os.environ.get("BQSM_CONTEMPLATE", "on") != "off" # stream-of-consciousness
47
 
48
  def engine_healthy(timeout=2):
49
  try:
 
164
  _verbose_lock = threading.Lock()
165
 
166
  # Chat messages: list of {role, text, time}
167
+ class _ChatList(list):
168
+ """Auto-persists every appended message to HISTORY_FILE for agent review."""
169
+
170
+ def append(self, msg):
171
+ super().append(msg)
172
+ try:
173
+ os.makedirs(os.path.dirname(HISTORY_FILE), exist_ok=True)
174
+ with open(HISTORY_FILE, "a") as f:
175
+ f.write(json.dumps({"role": msg["role"], "text": msg["text"],
176
+ "ts": time.time()}) + "\n")
177
+ except Exception:
178
+ pass
179
+
180
+
181
+ _chat_messages = _ChatList()
182
  _chat_lock = threading.Lock()
183
 
184
 
185
+ def _scheduler_loop():
186
+ """Poll the schedule file; fire due wake-ups as chat messages."""
187
+ from datetime import datetime
188
+ fired = set()
189
+ while True:
190
+ try:
191
+ if SCHEDULE_FILE.exists():
192
+ for line in SCHEDULE_FILE.read_text().splitlines():
193
+ if not line.strip() or hash(line) in fired:
194
+ continue
195
+ try:
196
+ e = json.loads(line)
197
+ when = (e["at"] if isinstance(e["at"], (int, float))
198
+ else datetime.fromisoformat(e["at"]).timestamp())
199
+ except Exception:
200
+ continue
201
+ if time.time() >= when:
202
+ msg = e.get("message", "wake")
203
+ add_verbose({"tag": "schedule", "data": f"WAKE: {msg}"})
204
+ with _chat_lock:
205
+ _chat_messages.append({"role": "phox",
206
+ "text": f"[wake-up] {msg}"})
207
+ fired.add(hash(line))
208
+ except Exception:
209
+ pass
210
+ time.sleep(5)
211
+
212
+
213
+ threading.Thread(target=_scheduler_loop, daemon=True).start()
214
+
215
+
216
  def add_verbose(entry):
217
  """Add an entry to the verbose log, prune entries older than 1 hour."""
218
  ts = time.time()
 
686
  var cls=m.role==='user'?'user':'phox';
687
  html+='<div class="msg"><span class="role '+cls+'">'+m.role+':</span> '+m.text+'</div>';
688
  });
689
+ document.getElementById('chat-log').innerHTML+=html;
690
  var el=document.getElementById('chat-log');el.scrollTop=el.scrollHeight;
691
  }).catch(function(){})
692
  }
 
780
  params = parse_qs(urlparse(self.path).query)
781
  name = params.get('name', ['phoenix-evolved'])[0]
782
  if not name.endswith('.pbrain'): name += '.pbrain'
783
+ base = name[:-len('.pbrain')]
784
  dst = os.path.join(BRAIN_DIR, name)
785
  try:
786
  shutil.copy2(BQMC_PATH, dst)
787
+ # Snapshot the full agent state alongside the brain binary.
788
+ state_files = {"memory": MEMORY_FILE, "history": HISTORY_FILE,
789
+ "schedule": SCHEDULE_FILE}
790
+ for k, fp in state_files.items():
791
+ if os.path.exists(fp):
792
+ shutil.copy2(fp, os.path.join(
793
+ BRAIN_DIR, f"{base}.{k}.jsonl"))
794
  add_verbose({"tag": "control", "data": f"brain saved to {dst}"})
795
+ self._serve_json({"status": "saved", "path": dst,
796
+ "state": list(state_files)}); return
797
  except Exception as e:
798
  self._serve_json({"status": f"error: {e}"}); return
799
  elif self.path.startswith('/api/load'):
800
  params = parse_qs(urlparse(self.path).query)
801
  name = params.get('name', [''])[0]
802
+ base = name[:-len('.pbrain')] if name.endswith('.pbrain') else name
803
  try:
804
  shutil.copy2(os.path.join(BRAIN_DIR, name), BQMC_PATH)
805
+ # Restore the agent state (memory, history, schedule).
806
+ state_files = {"memory": MEMORY_FILE, "history": HISTORY_FILE,
807
+ "schedule": SCHEDULE_FILE}
808
+ for k, fp in state_files.items():
809
+ src = os.path.join(BRAIN_DIR, f"{base}.{k}.jsonl")
810
+ if os.path.exists(src):
811
+ shutil.copy2(src, fp)
812
+ add_verbose({"tag": "control",
813
+ "data": f"brain loaded from {name} (+state)"})
814
  self._serve_json({"status": "loaded — restart to apply"}); return
815
  except Exception as e:
816
  self._serve_json({"status": f"error: {e}"}); return
 
847
  return
848
 
849
  def gen(prompt, max_tokens):
850
+ return engine_generate(prompt, n=min(max_tokens, 256)) or ""
851
 
852
  def on_event(e):
853
  if e["type"] == "tool":
 
859
  elif e["type"] == "model":
860
  add_verbose({"tag": "chat",
861
  "data": f"model[{e['round']}]: {e['text'][:120]}"})
862
+ # In contemplate mode, surface each thought in chat
863
+ if CONTEMPLATE and e.get("round", 0) >= 0:
864
+ with _chat_lock:
865
+ _chat_messages.append({"role": "phox",
866
+ "text": f"[thought #{e['round']}] {e['text'][:200]}"})
867
 
868
  add_verbose({"tag": "chat",
869
+ "data": f"agent loop started ({INFER_MODE})"
870
+ f"{' contemplate' if CONTEMPLATE else ''}"})
871
+ reply, _ = agent_core.run_agent(text, gen, on_event=on_event,
872
+ contemplate=CONTEMPLATE)
873
  with _chat_lock:
874
  _chat_messages.append({"role": "phox", "text": reply})
875
  add_verbose({"tag": "chat", "data": f"PHOX: {reply}"})
phoenix_dashboard.py CHANGED
@@ -16,6 +16,7 @@ from urllib.parse import urlparse, parse_qs
16
  import sys, urllib.request
17
  import http.server, socketserver
18
  import importlib
 
19
 
20
  STATE_FILE = "/tmp/phoenix_state.jsonl"
21
  VERBOSE_LOG = "/tmp/phoenix_verbose.log"
@@ -42,6 +43,7 @@ MAX_LOG_AGE_S = 3600
42
  SERVE_URL = os.environ.get("BQSM_INFER", "http://127.0.0.1:8781")
43
  INFER_MODE = os.environ.get("BQSM_MODE", "wave") # "wave" or "reference"
44
  AGENT_MODE = os.environ.get("BQSM_AGENT", "on") # "on" = tool-use loop, "off" = raw completion
 
45
 
46
  def engine_healthy(timeout=2):
47
  try:
@@ -162,10 +164,55 @@ _verbose_log = collections.deque()
162
  _verbose_lock = threading.Lock()
163
 
164
  # Chat messages: list of {role, text, time}
165
- _chat_messages = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
166
  _chat_lock = threading.Lock()
167
 
168
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
169
  def add_verbose(entry):
170
  """Add an entry to the verbose log, prune entries older than 1 hour."""
171
  ts = time.time()
@@ -733,19 +780,37 @@ class Handler(http.server.BaseHTTPRequestHandler):
733
  params = parse_qs(urlparse(self.path).query)
734
  name = params.get('name', ['phoenix-evolved'])[0]
735
  if not name.endswith('.pbrain'): name += '.pbrain'
 
736
  dst = os.path.join(BRAIN_DIR, name)
737
  try:
738
  shutil.copy2(BQMC_PATH, dst)
 
 
 
 
 
 
 
739
  add_verbose({"tag": "control", "data": f"brain saved to {dst}"})
740
- self._serve_json({"status": "saved", "path": dst}); return
 
741
  except Exception as e:
742
  self._serve_json({"status": f"error: {e}"}); return
743
  elif self.path.startswith('/api/load'):
744
  params = parse_qs(urlparse(self.path).query)
745
  name = params.get('name', [''])[0]
 
746
  try:
747
  shutil.copy2(os.path.join(BRAIN_DIR, name), BQMC_PATH)
748
- add_verbose({"tag": "control", "data": f"brain loaded from {name}"})
 
 
 
 
 
 
 
 
749
  self._serve_json({"status": "loaded — restart to apply"}); return
750
  except Exception as e:
751
  self._serve_json({"status": f"error: {e}"}); return
@@ -794,10 +859,17 @@ class Handler(http.server.BaseHTTPRequestHandler):
794
  elif e["type"] == "model":
795
  add_verbose({"tag": "chat",
796
  "data": f"model[{e['round']}]: {e['text'][:120]}"})
 
 
 
 
 
797
 
798
  add_verbose({"tag": "chat",
799
- "data": f"agent loop started ({INFER_MODE})"})
800
- reply, _ = agent_core.run_agent(text, gen, on_event=on_event)
 
 
801
  with _chat_lock:
802
  _chat_messages.append({"role": "phox", "text": reply})
803
  add_verbose({"tag": "chat", "data": f"PHOX: {reply}"})
 
16
  import sys, urllib.request
17
  import http.server, socketserver
18
  import importlib
19
+ from agent_core import HISTORY_FILE, SCHEDULE_FILE, MEMORY_FILE
20
 
21
  STATE_FILE = "/tmp/phoenix_state.jsonl"
22
  VERBOSE_LOG = "/tmp/phoenix_verbose.log"
 
43
  SERVE_URL = os.environ.get("BQSM_INFER", "http://127.0.0.1:8781")
44
  INFER_MODE = os.environ.get("BQSM_MODE", "wave") # "wave" or "reference"
45
  AGENT_MODE = os.environ.get("BQSM_AGENT", "on") # "on" = tool-use loop, "off" = raw completion
46
+ CONTEMPLATE = os.environ.get("BQSM_CONTEMPLATE", "on") != "off" # stream-of-consciousness
47
 
48
  def engine_healthy(timeout=2):
49
  try:
 
164
  _verbose_lock = threading.Lock()
165
 
166
  # Chat messages: list of {role, text, time}
167
+ class _ChatList(list):
168
+ """Auto-persists every appended message to HISTORY_FILE for agent review."""
169
+
170
+ def append(self, msg):
171
+ super().append(msg)
172
+ try:
173
+ os.makedirs(os.path.dirname(HISTORY_FILE), exist_ok=True)
174
+ with open(HISTORY_FILE, "a") as f:
175
+ f.write(json.dumps({"role": msg["role"], "text": msg["text"],
176
+ "ts": time.time()}) + "\n")
177
+ except Exception:
178
+ pass
179
+
180
+
181
+ _chat_messages = _ChatList()
182
  _chat_lock = threading.Lock()
183
 
184
 
185
+ def _scheduler_loop():
186
+ """Poll the schedule file; fire due wake-ups as chat messages."""
187
+ from datetime import datetime
188
+ fired = set()
189
+ while True:
190
+ try:
191
+ if SCHEDULE_FILE.exists():
192
+ for line in SCHEDULE_FILE.read_text().splitlines():
193
+ if not line.strip() or hash(line) in fired:
194
+ continue
195
+ try:
196
+ e = json.loads(line)
197
+ when = (e["at"] if isinstance(e["at"], (int, float))
198
+ else datetime.fromisoformat(e["at"]).timestamp())
199
+ except Exception:
200
+ continue
201
+ if time.time() >= when:
202
+ msg = e.get("message", "wake")
203
+ add_verbose({"tag": "schedule", "data": f"WAKE: {msg}"})
204
+ with _chat_lock:
205
+ _chat_messages.append({"role": "phox",
206
+ "text": f"[wake-up] {msg}"})
207
+ fired.add(hash(line))
208
+ except Exception:
209
+ pass
210
+ time.sleep(5)
211
+
212
+
213
+ threading.Thread(target=_scheduler_loop, daemon=True).start()
214
+
215
+
216
  def add_verbose(entry):
217
  """Add an entry to the verbose log, prune entries older than 1 hour."""
218
  ts = time.time()
 
780
  params = parse_qs(urlparse(self.path).query)
781
  name = params.get('name', ['phoenix-evolved'])[0]
782
  if not name.endswith('.pbrain'): name += '.pbrain'
783
+ base = name[:-len('.pbrain')]
784
  dst = os.path.join(BRAIN_DIR, name)
785
  try:
786
  shutil.copy2(BQMC_PATH, dst)
787
+ # Snapshot the full agent state alongside the brain binary.
788
+ state_files = {"memory": MEMORY_FILE, "history": HISTORY_FILE,
789
+ "schedule": SCHEDULE_FILE}
790
+ for k, fp in state_files.items():
791
+ if os.path.exists(fp):
792
+ shutil.copy2(fp, os.path.join(
793
+ BRAIN_DIR, f"{base}.{k}.jsonl"))
794
  add_verbose({"tag": "control", "data": f"brain saved to {dst}"})
795
+ self._serve_json({"status": "saved", "path": dst,
796
+ "state": list(state_files)}); return
797
  except Exception as e:
798
  self._serve_json({"status": f"error: {e}"}); return
799
  elif self.path.startswith('/api/load'):
800
  params = parse_qs(urlparse(self.path).query)
801
  name = params.get('name', [''])[0]
802
+ base = name[:-len('.pbrain')] if name.endswith('.pbrain') else name
803
  try:
804
  shutil.copy2(os.path.join(BRAIN_DIR, name), BQMC_PATH)
805
+ # Restore the agent state (memory, history, schedule).
806
+ state_files = {"memory": MEMORY_FILE, "history": HISTORY_FILE,
807
+ "schedule": SCHEDULE_FILE}
808
+ for k, fp in state_files.items():
809
+ src = os.path.join(BRAIN_DIR, f"{base}.{k}.jsonl")
810
+ if os.path.exists(src):
811
+ shutil.copy2(src, fp)
812
+ add_verbose({"tag": "control",
813
+ "data": f"brain loaded from {name} (+state)"})
814
  self._serve_json({"status": "loaded — restart to apply"}); return
815
  except Exception as e:
816
  self._serve_json({"status": f"error: {e}"}); return
 
859
  elif e["type"] == "model":
860
  add_verbose({"tag": "chat",
861
  "data": f"model[{e['round']}]: {e['text'][:120]}"})
862
+ # In contemplate mode, surface each thought in chat
863
+ if CONTEMPLATE and e.get("round", 0) >= 0:
864
+ with _chat_lock:
865
+ _chat_messages.append({"role": "phox",
866
+ "text": f"[thought #{e['round']}] {e['text'][:200]}"})
867
 
868
  add_verbose({"tag": "chat",
869
+ "data": f"agent loop started ({INFER_MODE})"
870
+ f"{' contemplate' if CONTEMPLATE else ''}"})
871
+ reply, _ = agent_core.run_agent(text, gen, on_event=on_event,
872
+ contemplate=CONTEMPLATE)
873
  with _chat_lock:
874
  _chat_messages.append({"role": "phox", "text": reply})
875
  add_verbose({"tag": "chat", "data": f"PHOX: {reply}"})