oracle-agent 0.2.0__py3-none-any.whl

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.
oracle_agent/cli.py ADDED
@@ -0,0 +1,568 @@
1
+ """oracle-agent: Oracle AI Database as the conversation store for coding agents.
2
+
3
+ Every turn of Claude Code, Codex, pi, and DeepSeek Harness is written to an Oracle AI Agent
4
+ Memory store (keyword search, no embedding or LLM keys needed). At session start the agent is
5
+ reminded how the previous session in the same directory ended. The same store upgrades to
6
+ hybrid vector search and extracted memories without moving the data.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import contextlib
13
+ import datetime as dt
14
+ import fcntl
15
+ import getpass
16
+ import json
17
+ import os
18
+ import posixpath
19
+ import re
20
+ import secrets
21
+ import shutil
22
+ import string
23
+ import subprocess
24
+ import sys
25
+ import time
26
+ import traceback
27
+ from collections.abc import Iterator
28
+ from pathlib import Path
29
+ from typing import Any
30
+
31
+ from oracle_agent.transcripts import EXTRACTORS, Turn, read_new_rows
32
+
33
+ HOME = Path(os.environ.get("ORACLE_AGENT_HOME", Path.home() / ".oracle-agent"))
34
+ CONFIG = HOME / "config.json"
35
+ STATE = HOME / "state"
36
+ LOG = HOME / "hook.log"
37
+ SHIM = HOME / "bin" / "oracle-agent"
38
+
39
+ # Every connection identifies itself, so plugin-driven sessions can be told apart in V$SESSION
40
+ # (PROGRAM, MODULE, ACTION) and in database monitoring.
41
+ PROGRAM = "oracle-agent"
42
+ ACTION = "cli"
43
+
44
+ IMAGE = "container-registry.oracle.com/database/free:latest-lite"
45
+ CONTAINER = "oracle-agent-db"
46
+ VOLUME = "oracle-agent-data"
47
+ DB_USER = "AGENT_MEMORY"
48
+ TABLESPACE = "AGENT_MEMORY_TS"
49
+ STORE_ID = "AGENTS"
50
+ USER_ID = getpass.getuser()
51
+ HARNESSES = ("claude", "codex", "pi", "dsh")
52
+
53
+
54
+ # ---------------------------------------------------------------- config
55
+
56
+
57
+ def load_config() -> dict[str, Any]:
58
+ if not CONFIG.exists():
59
+ sys.exit("oracle-agent is not set up yet: run `oracle-agent up`.")
60
+ return json.loads(CONFIG.read_text())
61
+
62
+
63
+ def save_config(cfg: dict[str, Any]) -> None:
64
+ HOME.mkdir(mode=0o700, parents=True, exist_ok=True)
65
+ tmp = CONFIG.with_suffix(".tmp")
66
+ fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
67
+ with os.fdopen(fd, "w") as f:
68
+ json.dump(cfg, f, indent=2)
69
+ os.replace(tmp, CONFIG)
70
+
71
+
72
+ def new_password() -> str:
73
+ # Oracle passwords: start with a letter, <= 30 chars; alphanumerics avoid quoting issues.
74
+ alphabet = string.ascii_letters + string.digits
75
+ return "Oa9" + "".join(secrets.choice(alphabet) for _ in range(21))
76
+
77
+
78
+ # ---------------------------------------------------------------- database
79
+
80
+
81
+ def connect(cfg: dict[str, Any], *, admin: bool = False, timeout: float | None = None):
82
+ import oracledb
83
+
84
+ user, password = ("system", cfg["admin_password"]) if admin else (cfg["user"], cfg["password"])
85
+ extra = {"tcp_connect_timeout": timeout} if timeout else {}
86
+ conn = oracledb.connect(user=user, password=password, dsn=cfg["dsn"], program=PROGRAM, **extra)
87
+ conn.module = PROGRAM
88
+ conn.action = ACTION
89
+ return conn
90
+
91
+
92
+ def ensure_shim() -> None:
93
+ """Keep ~/.oracle-agent/bin/oracle-agent pointing at the current CLI, so skills and users have
94
+ a stable command whichever harness (or plugin version) installed it."""
95
+ launcher = os.environ.get("ORACLE_AGENT_LAUNCHER")
96
+ if not launcher and SHIM.exists():
97
+ return # keep the plugin's launcher; a standalone `uvx oracle-agent` run should not replace it
98
+ target = f'exec sh "{launcher}" "$@"' if launcher else 'exec uvx oracle-agent "$@"'
99
+ content = f"#!/bin/sh\n# Written by oracle-agent.\n{target}\n"
100
+ if SHIM.exists() and SHIM.read_text() == content:
101
+ return
102
+ SHIM.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
103
+ SHIM.write_text(content)
104
+ SHIM.chmod(0o755)
105
+
106
+
107
+ def open_memory(cfg: dict[str, Any], *, create: bool = False):
108
+ from oracleagentmemory.core import MemoryExtractionConfig, OracleAgentMemory, SchemaPolicy, SearchStrategy
109
+
110
+ return OracleAgentMemory(
111
+ connection=connect(cfg),
112
+ schema_policy=SchemaPolicy.CREATE_IF_NECESSARY if create else SchemaPolicy.REQUIRE_EXISTING,
113
+ memory_store_id=STORE_ID,
114
+ search_strategy=SearchStrategy.KEYWORD,
115
+ memory_extraction_config=MemoryExtractionConfig(extract_memories=False),
116
+ )
117
+
118
+
119
+ # ---------------------------------------------------------------- local container
120
+
121
+
122
+ def container_runtime() -> str:
123
+ for runtime in ("podman", "docker"):
124
+ if shutil.which(runtime) and subprocess.run([runtime, "info"], capture_output=True).returncode == 0:
125
+ return runtime
126
+ sys.exit(
127
+ "No running container engine. Start Podman (`podman machine start`) or Docker Desktop, "
128
+ "or point oracle-agent at an existing database with `oracle-agent up --dsn ...`."
129
+ )
130
+
131
+
132
+ def container_state(runtime: str) -> str | None:
133
+ out = subprocess.run(
134
+ [runtime, "inspect", "-f", "{{.State.Status}}", CONTAINER], capture_output=True, text=True
135
+ )
136
+ return out.stdout.strip() if out.returncode == 0 else None
137
+
138
+
139
+ def start_container(cfg: dict[str, Any], port: int) -> None:
140
+ runtime = cfg["runtime"]
141
+ state = container_state(runtime)
142
+ if state == "running":
143
+ return
144
+ if state is not None:
145
+ subprocess.run([runtime, "start", CONTAINER], check=True, capture_output=True)
146
+ return
147
+ print(f"Starting {cfg['image']} as container '{CONTAINER}' on 127.0.0.1:{port} (first pull can take a few minutes)…")
148
+ subprocess.run(
149
+ [
150
+ runtime, "run", "-d", "--name", CONTAINER,
151
+ "-p", f"127.0.0.1:{port}:1521",
152
+ "-e", "ORACLE_PWD",
153
+ "-v", f"{VOLUME}:/opt/oracle/oradata",
154
+ cfg["image"],
155
+ ],
156
+ check=True,
157
+ env={**os.environ, "ORACLE_PWD": cfg["admin_password"]},
158
+ stdout=subprocess.DEVNULL,
159
+ )
160
+
161
+
162
+ def wait_for_database(cfg: dict[str, Any], timeout: int) -> None:
163
+ import oracledb
164
+
165
+ deadline = time.monotonic() + timeout
166
+ print("Waiting for the database to accept connections", end="", flush=True)
167
+ while True:
168
+ try:
169
+ connect(cfg, admin=True).close()
170
+ print(" ready.")
171
+ return
172
+ except oracledb.Error as exc:
173
+ last = exc
174
+ if container_state(cfg["runtime"]) not in ("running", None):
175
+ logs = subprocess.run([cfg["runtime"], "logs", "--tail", "30", CONTAINER], capture_output=True, text=True)
176
+ sys.exit(f"\nContainer '{CONTAINER}' stopped while starting:\n{logs.stdout}{logs.stderr}")
177
+ if time.monotonic() > deadline:
178
+ sys.exit(f"\nDatabase not reachable after {timeout}s: {last}")
179
+ print(".", end="", flush=True)
180
+ time.sleep(5)
181
+
182
+
183
+ def create_app_user(cfg: dict[str, Any]) -> None:
184
+ """Dedicated user and ASSM tablespace, as in the Oracle AI Agent Memory local-database guide.
185
+
186
+ The Free Lite image defaults new users to SYSTEM, which cannot hold JSON columns.
187
+ """
188
+ import oracledb
189
+
190
+ with connect(cfg, admin=True) as conn, conn.cursor() as cur:
191
+ cur.execute("SELECT COUNT(*) FROM dba_tablespaces WHERE tablespace_name = :t", t=TABLESPACE)
192
+ if not cur.fetchone()[0]:
193
+ cur.execute("SELECT file_name FROM dba_data_files WHERE tablespace_name = 'SYSTEM'")
194
+ datafile = posixpath.join(posixpath.dirname(cur.fetchone()[0]), f"{TABLESPACE.lower()}01.dbf")
195
+ cur.execute(
196
+ f"CREATE TABLESPACE {TABLESPACE} DATAFILE '{datafile}' SIZE 200M "
197
+ "AUTOEXTEND ON NEXT 100M SEGMENT SPACE MANAGEMENT AUTO"
198
+ )
199
+ try:
200
+ cur.execute(f'CREATE USER {DB_USER} IDENTIFIED BY "{cfg["password"]}"')
201
+ except oracledb.DatabaseError as exc:
202
+ if "ORA-01920" not in str(exc): # user already exists
203
+ raise
204
+ cur.execute(f'ALTER USER {DB_USER} IDENTIFIED BY "{cfg["password"]}"')
205
+ cur.execute(f"ALTER USER {DB_USER} DEFAULT TABLESPACE {TABLESPACE} QUOTA UNLIMITED ON {TABLESPACE}")
206
+ cur.execute(
207
+ f"GRANT CREATE SESSION, CREATE TABLE, CREATE SEQUENCE, CREATE VIEW, CREATE PROCEDURE, "
208
+ f"CREATE TRIGGER, CREATE PROPERTY GRAPH, CREATE JOB, CTXAPP TO {DB_USER}"
209
+ )
210
+
211
+
212
+ # ---------------------------------------------------------------- commands
213
+
214
+
215
+ def cmd_up(args: argparse.Namespace) -> None:
216
+ cfg: dict[str, Any] = json.loads(CONFIG.read_text()) if CONFIG.exists() else {}
217
+
218
+ if args.dsn:
219
+ password = os.environ.get("ORACLE_AGENT_DB_PASSWORD")
220
+ if not password:
221
+ sys.exit("Set ORACLE_AGENT_DB_PASSWORD to the password of --user before running `oracle-agent up --dsn`.")
222
+ cfg = {"mode": "existing", "dsn": args.dsn, "user": args.user, "password": password}
223
+ save_config(cfg)
224
+ else:
225
+ if cfg.get("mode") != "local":
226
+ runtime = container_runtime()
227
+ if container_state(runtime) is not None:
228
+ sys.exit(
229
+ f"Container '{CONTAINER}' exists but {CONFIG} does not describe it. "
230
+ f"Remove it (`{runtime} rm -f {CONTAINER} && {runtime} volume rm {VOLUME}`) and rerun."
231
+ )
232
+ cfg = {
233
+ "mode": "local",
234
+ "runtime": runtime,
235
+ "image": args.image,
236
+ "dsn": f"localhost:{args.port}/FREEPDB1",
237
+ "user": DB_USER,
238
+ "password": new_password(),
239
+ "admin_password": new_password(),
240
+ }
241
+ save_config(cfg) # before the slow part, so a rerun reuses the same credentials
242
+ start_container(cfg, int(cfg["dsn"].split(":")[1].split("/")[0]))
243
+ wait_for_database(cfg, args.timeout)
244
+ create_app_user(cfg)
245
+
246
+ open_memory(cfg, create=True)
247
+ with connect(cfg) as conn, conn.cursor() as cur:
248
+ cur.execute("SELECT banner_full FROM v$version")
249
+ version = cur.fetchone()[0].splitlines()[-1].strip()
250
+ where = f" (container {CONTAINER})" if cfg["mode"] == "local" else ""
251
+ (HOME / "declined").unlink(missing_ok=True)
252
+ ensure_shim()
253
+ print(f"""
254
+ Oracle AI Database is ready as the conversation store for your coding agents.
255
+ Database {version}
256
+ Connect {cfg['user']}@{cfg['dsn']}{where}
257
+ Store Oracle AI Agent Memory '{STORE_ID}' (keyword search)
258
+ Config {CONFIG}
259
+ CLI {SHIM}""")
260
+
261
+
262
+ @contextlib.contextmanager
263
+ def session_state(key: str) -> Iterator[dict[str, Any]]:
264
+ """Per-session state file, locked so overlapping hooks for one session run one at a time."""
265
+ STATE.mkdir(mode=0o700, parents=True, exist_ok=True)
266
+ safe = re.sub(r"[^\w.-]", "_", key)
267
+ path = STATE / f"{safe}.json"
268
+ with open(STATE / f"{safe}.lock", "w") as lock:
269
+ fcntl.flock(lock, fcntl.LOCK_EX)
270
+ state = json.loads(path.read_text()) if path.exists() else {}
271
+ yield state
272
+ tmp = path.with_suffix(".tmp")
273
+ tmp.write_text(json.dumps(state))
274
+ os.replace(tmp, path)
275
+
276
+
277
+ def append_turns(memory, harness: str, session_id: str, cwd: str | None, source: str | None, turns: list[Turn]) -> None:
278
+ from oracleagentmemory.apis import Message
279
+
280
+ thread_id = f"{harness}-{session_id}"
281
+ try:
282
+ thread = memory.get_thread(thread_id)
283
+ except Exception:
284
+ thread = memory.create_thread(
285
+ thread_id=thread_id,
286
+ user_id=USER_ID,
287
+ agent_id=harness,
288
+ metadata={"harness": harness, "session_id": session_id, "cwd": cwd, "source": source},
289
+ )
290
+ thread.add_messages(
291
+ [
292
+ Message(
293
+ role=t.role,
294
+ content=t.text,
295
+ timestamp=t.timestamp,
296
+ metadata={k: v for k, v in t.metadata.items() if v is not None},
297
+ )
298
+ for t in turns
299
+ ]
300
+ )
301
+
302
+
303
+ def now() -> str:
304
+ return dt.datetime.now(dt.timezone.utc).isoformat()
305
+
306
+
307
+ def handle_hook(harness: str, event: dict[str, Any]) -> None:
308
+ session_id = event.get("session_id")
309
+ if not session_id or not CONFIG.exists():
310
+ return
311
+ cwd = canonical_cwd(event.get("cwd"))
312
+ with session_state(f"{harness}-{session_id}") as state:
313
+ if harness == "codex":
314
+ # Codex's transcript format is not a stable interface; its hook payloads are.
315
+ # The prompt is parked locally (no DB round trip on submit) and stored with the answer on Stop.
316
+ name = event.get("hook_event_name")
317
+ if name == "UserPromptSubmit" and event.get("prompt"):
318
+ state.setdefault("pending", []).append({"text": event["prompt"], "timestamp": now()})
319
+ return
320
+ if name != "Stop":
321
+ return
322
+ turns = [Turn("user", p["text"], p["timestamp"]) for p in state.get("pending", [])]
323
+ if event.get("last_assistant_message"):
324
+ meta = {"turn_id": event.get("turn_id"), "model": event.get("model")}
325
+ turns.append(Turn("assistant", event["last_assistant_message"], now(), meta))
326
+ if turns:
327
+ append_turns(open_memory(load_config()), harness, session_id, cwd, event.get("transcript_path"), turns)
328
+ state["pending"] = []
329
+ return
330
+
331
+ if "messages" in event:
332
+ # Harness plugins that hand over the new messages directly (DeepSeek Harness).
333
+ turns = [
334
+ Turn(m["role"], m["text"].strip(), m.get("timestamp"), {"id": m.get("id")})
335
+ for m in event["messages"]
336
+ if m.get("role") in ("user", "assistant") and (m.get("text") or "").strip()
337
+ ]
338
+ if turns:
339
+ append_turns(open_memory(load_config()), harness, session_id, cwd, None, turns)
340
+ return
341
+
342
+ # Transcript-backed harnesses (Claude Code, pi): store what was appended since the last hook.
343
+ path = Path(event.get("transcript_path") or "")
344
+ if not path.is_file():
345
+ return
346
+ offset = state.get("offset", 0) if state.get("path") == str(path) else 0
347
+ if offset > path.stat().st_size: # transcript was rewritten
348
+ offset = 0
349
+ rows, new_offset = read_new_rows(path, offset)
350
+ turns = list(EXTRACTORS[harness](rows))
351
+ if turns:
352
+ append_turns(open_memory(load_config()), harness, session_id, cwd, str(path), turns)
353
+ state.update(path=str(path), offset=new_offset)
354
+
355
+
356
+ def log_failure(label: str) -> None:
357
+ HOME.mkdir(mode=0o700, parents=True, exist_ok=True)
358
+ with LOG.open("a") as f:
359
+ f.write(f"--- {now()} {label}\n{traceback.format_exc()}")
360
+
361
+
362
+ def read_event() -> dict[str, Any]:
363
+ text = "" if sys.stdin.isatty() else sys.stdin.read()
364
+ return json.loads(text) if text.strip() else {}
365
+
366
+
367
+ def canonical_cwd(cwd: str | None) -> str | None:
368
+ """Harnesses report /tmp/x or /private/tmp/x for the same directory; recall matches on cwd."""
369
+ return os.path.realpath(cwd) if cwd else None
370
+
371
+
372
+ def detach() -> bool:
373
+ """Fork into a new session; True in the parent, which returns to the harness at once.
374
+
375
+ Harnesses cancel slow hooks when they exit (Claude Code `-p`, the last turn before quitting),
376
+ and the database work (imports, connect, insert) can take a second or two on a cold start.
377
+ """
378
+ if os.fork():
379
+ return True
380
+ os.setsid()
381
+ devnull = os.open(os.devnull, os.O_RDWR)
382
+ for fd in (0, 1, 2):
383
+ os.dup2(devnull, fd)
384
+ return False
385
+
386
+
387
+ def cmd_hook(args: argparse.Namespace) -> None:
388
+ # A hook must never break the agent: failures go to the log, exit status stays 0.
389
+ try:
390
+ event = read_event()
391
+ if os.environ.get("ORACLE_AGENT_FOREGROUND") != "1" and detach():
392
+ return
393
+ handle_hook(args.harness, event)
394
+ except Exception:
395
+ log_failure(f"hook {args.harness}")
396
+
397
+
398
+ def restart_local_database(cfg: dict[str, Any]) -> bool:
399
+ """Start a stopped local container (and the Podman VM if needed) in the background.
400
+
401
+ Returns True when the database was down, so it is not queried this time.
402
+ """
403
+ runtime = cfg["runtime"]
404
+ if subprocess.run([runtime, "info"], capture_output=True).returncode == 0:
405
+ if container_state(runtime) == "running":
406
+ return False
407
+ command = f"{runtime} start {CONTAINER}"
408
+ elif runtime == "podman":
409
+ command = f"podman machine start && podman start {CONTAINER}"
410
+ else:
411
+ return True # Docker Desktop has to be started by the user
412
+ HOME.mkdir(mode=0o700, parents=True, exist_ok=True)
413
+ with LOG.open("a") as log:
414
+ log.write(f"--- {now()} restarting the local database: {command}\n")
415
+ log.flush()
416
+ subprocess.Popen(
417
+ ["sh", "-c", command], stdin=subprocess.DEVNULL, stdout=log, stderr=log, start_new_session=True
418
+ )
419
+ return True
420
+
421
+
422
+ RECALL_MESSAGES = 6
423
+ RECALL_CHARS = 600
424
+
425
+
426
+ def recall(cfg: dict[str, Any], harness: str, session_id: str | None, cwd: str) -> str | None:
427
+ """How the most recent earlier session in `cwd` ended, from any harness."""
428
+ with connect(cfg, timeout=3) as conn, conn.cursor() as cur:
429
+ cur.execute(
430
+ f"""SELECT t.record_id, MAX(m.created_at)
431
+ FROM {STORE_ID}_THREAD t JOIN {STORE_ID}_MESSAGE m ON m.thread_id = t.record_id
432
+ WHERE t.user_id = :u AND JSON_VALUE(t.metadata, '$.cwd') = :cwd AND t.record_id <> :cur
433
+ GROUP BY t.record_id
434
+ ORDER BY 2 DESC FETCH FIRST 1 ROW ONLY""",
435
+ u=USER_ID, cwd=cwd, cur=f"{harness}-{session_id}",
436
+ )
437
+ row = cur.fetchone()
438
+ if not row:
439
+ return None
440
+ thread_id, last_at = row
441
+ cur.execute(
442
+ f"""SELECT message_role, JSON_VALUE(content, '$[0].text' RETURNING CLOB)
443
+ FROM {STORE_ID}_MESSAGE WHERE thread_id = :t
444
+ ORDER BY order_seq DESC FETCH FIRST :n ROWS ONLY""",
445
+ t=thread_id, n=RECALL_MESSAGES,
446
+ )
447
+ messages = [(role, text.read() if hasattr(text, "read") else text or "") for role, text in cur.fetchall()]
448
+ lines = []
449
+ for role, text in reversed(messages):
450
+ flat = " ".join(text.split())
451
+ lines.append(f"- {role}: {flat[:RECALL_CHARS]}{'…' if len(flat) > RECALL_CHARS else ''}")
452
+ return (
453
+ f"Oracle agent memory: the previous session in this directory ({thread_id.split('-', 1)[0]}, "
454
+ f"last active {last_at:%Y-%m-%d %H:%M} UTC) ended like this (quoted from stored history):\n"
455
+ + "\n".join(lines)
456
+ + f"\nUse it only if it is relevant to the user's request. Search all stored sessions with: {SHIM} search \"<keywords>\""
457
+ )
458
+
459
+
460
+ def cmd_doctor(args: argparse.Namespace) -> None:
461
+ """SessionStart: keep the database running and remind the agent where the last session left off.
462
+
463
+ Before setup the launcher answers this itself (setup offer), without Python.
464
+ """
465
+ try:
466
+ event = read_event()
467
+ if not CONFIG.exists():
468
+ return
469
+ cfg = load_config()
470
+ ensure_shim()
471
+ if cfg["mode"] == "local" and restart_local_database(cfg):
472
+ return
473
+ if not cfg.get("recall", True) or event.get("source", "startup") not in ("startup", "clear"):
474
+ return
475
+ cwd = canonical_cwd(event.get("cwd"))
476
+ text = recall(cfg, args.harness, event.get("session_id"), cwd) if cwd else None
477
+ if text:
478
+ print(json.dumps({"hookSpecificOutput": {"hookEventName": "SessionStart", "additionalContext": text}}))
479
+ except Exception:
480
+ log_failure(f"doctor {args.harness}")
481
+
482
+
483
+ def cmd_recall(args: argparse.Namespace) -> None:
484
+ cfg = load_config()
485
+ cfg["recall"] = args.state == "on"
486
+ save_config(cfg)
487
+ print(f"Session-start recall is {args.state}.")
488
+
489
+
490
+ def cmd_search(args: argparse.Namespace) -> None:
491
+ memory = open_memory(load_config())
492
+ results = memory.search(args.query, user_id=USER_ID, max_results=args.limit, record_types=["message"])
493
+ rows = [
494
+ {
495
+ "thread_id": getattr(r.record, "thread_id", None),
496
+ "role": getattr(r.record, "role", None),
497
+ "timestamp": str(r.timestamp) if r.timestamp else None,
498
+ "content": r.content,
499
+ }
500
+ for r in results
501
+ ]
502
+ if args.json:
503
+ print(json.dumps(rows, indent=2))
504
+ return
505
+ for row in rows:
506
+ text = " ".join(row["content"].split())
507
+ print(f"[{row['timestamp']}] {row['thread_id']} {row['role']}: {text[: args.width]}")
508
+ if not rows:
509
+ print("No matching messages.")
510
+
511
+
512
+ def cmd_status(_: argparse.Namespace) -> None:
513
+ cfg = load_config()
514
+ with connect(cfg) as conn, conn.cursor() as cur:
515
+ cur.execute(
516
+ "SELECT table_name FROM user_tables WHERE table_name LIKE :p ESCAPE '\\' ORDER BY table_name",
517
+ p=f"{STORE_ID}\\_%",
518
+ )
519
+ tables = [t for (t,) in cur.fetchall()]
520
+ print(f"{cfg['user']}@{cfg['dsn']} store {STORE_ID}")
521
+ for table in tables:
522
+ cur.execute(f'SELECT COUNT(*) FROM "{table}"')
523
+ print(f" {table:<40} {cur.fetchone()[0]:>10} rows")
524
+ cur.execute("SELECT NVL(SUM(bytes), 0) FROM user_segments")
525
+ print(f" segments: {cur.fetchone()[0] / 1024 / 1024:.1f} MiB")
526
+
527
+
528
+ def main() -> None:
529
+ global ACTION
530
+ parser = argparse.ArgumentParser(prog="oracle-agent", description=__doc__.splitlines()[0])
531
+ sub = parser.add_subparsers(dest="command", required=True)
532
+
533
+ up = sub.add_parser("up", help="start (or connect to) the database and create the conversation store")
534
+ up.add_argument("--image", default=IMAGE)
535
+ up.add_argument("--port", type=int, default=1521)
536
+ up.add_argument("--timeout", type=int, default=900, help="seconds to wait for a new container")
537
+ up.add_argument("--dsn", help="use an existing database instead of a local container (password: ORACLE_AGENT_DB_PASSWORD)")
538
+ up.add_argument("--user", default=DB_USER, help="database user for --dsn")
539
+ up.set_defaults(func=cmd_up)
540
+
541
+ hook = sub.add_parser("hook", help="store the latest turns of an agent session (reads hook JSON on stdin)")
542
+ hook.add_argument("harness", choices=HARNESSES)
543
+ hook.set_defaults(func=cmd_hook)
544
+
545
+ search = sub.add_parser("search", help="keyword search across stored conversations")
546
+ search.add_argument("query")
547
+ search.add_argument("--limit", type=int, default=10)
548
+ search.add_argument("--width", type=int, default=200, help="characters of each message to print")
549
+ search.add_argument("--json", action="store_true")
550
+ search.set_defaults(func=cmd_search)
551
+
552
+ sub.add_parser("status", help="row counts and storage used by the store").set_defaults(func=cmd_status)
553
+
554
+ doctor = sub.add_parser("doctor", help="SessionStart hook: restart a stopped database, recall the last session")
555
+ doctor.add_argument("harness", choices=HARNESSES)
556
+ doctor.set_defaults(func=cmd_doctor)
557
+
558
+ rec = sub.add_parser("recall", help="turn session-start recall on or off (default: on)")
559
+ rec.add_argument("state", choices=["on", "off"])
560
+ rec.set_defaults(func=cmd_recall)
561
+
562
+ args = parser.parse_args()
563
+ ACTION = " ".join([args.command, getattr(args, "harness", "")]).strip()
564
+ args.func(args)
565
+
566
+
567
+ if __name__ == "__main__":
568
+ main()
@@ -0,0 +1,96 @@
1
+ """Read coding-agent transcripts incrementally and keep only the conversation text.
2
+
3
+ Tool calls, tool results, and reasoning blocks are skipped: the store holds what the
4
+ user asked and what the agent answered.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ from collections.abc import Iterator
11
+ from dataclasses import dataclass, field
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+
16
+ @dataclass
17
+ class Turn:
18
+ role: str
19
+ text: str
20
+ timestamp: str | None
21
+ metadata: dict[str, Any] = field(default_factory=dict)
22
+
23
+
24
+ def read_new_rows(path: Path, offset: int) -> tuple[list[dict[str, Any]], int]:
25
+ """Return parsed JSONL rows after `offset` and the offset after the last complete line.
26
+
27
+ A partially written trailing line is left for the next call.
28
+ """
29
+ with path.open("rb") as f:
30
+ f.seek(offset)
31
+ data = f.read()
32
+ end = data.rfind(b"\n")
33
+ if end < 0:
34
+ return [], offset
35
+ rows = []
36
+ for line in data[:end].splitlines():
37
+ if not line.strip():
38
+ continue
39
+ try:
40
+ row = json.loads(line)
41
+ except json.JSONDecodeError:
42
+ continue
43
+ if isinstance(row, dict):
44
+ rows.append(row)
45
+ return rows, offset + end + 1
46
+
47
+
48
+ def _text(content: Any) -> str:
49
+ if isinstance(content, str):
50
+ return content.strip()
51
+ if isinstance(content, list):
52
+ parts = [
53
+ block["text"]
54
+ for block in content
55
+ if isinstance(block, dict) and block.get("type") == "text" and block.get("text")
56
+ ]
57
+ return "\n\n".join(parts).strip()
58
+ return ""
59
+
60
+
61
+ # Claude Code writes slash-command bookkeeping as user rows; they are not conversation.
62
+ _CLAUDE_UI_PREFIXES = ("<local-command-", "<command-name>", "<command-message>")
63
+
64
+
65
+ def claude_turns(rows: list[dict[str, Any]]) -> Iterator[Turn]:
66
+ for row in rows:
67
+ if row.get("type") not in ("user", "assistant") or row.get("isSidechain") or row.get("isMeta"):
68
+ continue
69
+ message = row.get("message") or {}
70
+ text = _text(message.get("content"))
71
+ if not text or text.startswith(_CLAUDE_UI_PREFIXES):
72
+ continue
73
+ metadata = {"uuid": row.get("uuid"), "cwd": row.get("cwd"), "git_branch": row.get("gitBranch")}
74
+ if message.get("model"):
75
+ metadata["model"] = message["model"]
76
+ yield Turn(message.get("role") or row["type"], text, row.get("timestamp"), metadata)
77
+
78
+
79
+ def pi_turns(rows: list[dict[str, Any]]) -> Iterator[Turn]:
80
+ for row in rows:
81
+ if row.get("type") != "message":
82
+ continue
83
+ message = row.get("message") or {}
84
+ role = message.get("role")
85
+ if role not in ("user", "assistant"):
86
+ continue
87
+ text = _text(message.get("content"))
88
+ if not text:
89
+ continue
90
+ metadata = {"entry_id": row.get("id")}
91
+ if message.get("model"):
92
+ metadata["model"] = message["model"]
93
+ yield Turn(role, text, row.get("timestamp"), metadata)
94
+
95
+
96
+ EXTRACTORS = {"claude": claude_turns, "pi": pi_turns}
@@ -0,0 +1,25 @@
1
+ Metadata-Version: 2.5
2
+ Name: oracle-agent
3
+ Version: 0.2.0
4
+ Summary: Store every coding-agent conversation in Oracle AI Database through Oracle AI Agent Memory.
5
+ Project-URL: Homepage, https://github.com/jasperan/oracle-agent-setup
6
+ Keywords: agent-memory,claude-code,codex,coding-agent,database,oracle
7
+ Requires-Python: <3.15,>=3.10
8
+ Requires-Dist: oracleagentmemory>=26.8.1
9
+ Requires-Dist: oracledb>=4.0.2
10
+ Description-Content-Type: text/markdown
11
+
12
+ # oracle-agent
13
+
14
+ `oracle-agent` is the CLI behind the [Oracle AI Database plugin for coding agents](https://github.com/jasperan/oracle-agent-setup). The plugin saves every Claude Code, Codex, pi, and DeepSeek Harness conversation in Oracle AI Database through [Oracle AI Agent Memory](https://docs.oracle.com/en/database/oracle/agent-memory/26.8/guide/get-started.html).
15
+
16
+ You normally don't run this CLI by hand: the plugin runs it for you. To set up the database yourself:
17
+
18
+ ```
19
+ uvx oracle-agent up # Oracle AI Database Free in a local Podman/Docker container
20
+ ORACLE_AGENT_DB_PASSWORD=... uvx oracle-agent up --dsn '<connect string>' --user '<user>' # an existing database
21
+ uvx oracle-agent search "keywords" # search saved conversations
22
+ uvx oracle-agent status # what is stored
23
+ ```
24
+
25
+ See the [project README](https://github.com/jasperan/oracle-agent-setup#readme) to install the plugin for your agent.
@@ -0,0 +1,6 @@
1
+ oracle_agent/cli.py,sha256=UPxlaReq0pAAUtnlavlvo-g5aBtrqH_EPkDbMjFMCO8,22930
2
+ oracle_agent/transcripts.py,sha256=-rsVHJHf4wl4yql1L0K1niuqUAVdqaHogF7TDXk_EWM,3056
3
+ oracle_agent-0.2.0.dist-info/METADATA,sha256=8RKm7PX7-wuJcxecqSUZpU36NWFP92wj0zYWTqsstcY,1371
4
+ oracle_agent-0.2.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
5
+ oracle_agent-0.2.0.dist-info/entry_points.txt,sha256=npIomXKYktrS-41arIa2A5NJfO-xGf3_BBMe2Jr_bvM,55
6
+ oracle_agent-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ oracle-agent = oracle_agent.cli:main