oracle-agent 0.2.0__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.
@@ -0,0 +1,17 @@
1
+ {
2
+ "name": "oracle-ai-database",
3
+ "version": "0.2.0",
4
+ "description": "Stores every Claude Code conversation in Oracle AI Database (Oracle AI Agent Memory) and adds a skill to recall past sessions.",
5
+ "author": {
6
+ "name": "jasperan",
7
+ "url": "https://github.com/jasperan"
8
+ },
9
+ "homepage": "https://github.com/jasperan/oracle-agent-setup",
10
+ "repository": "https://github.com/jasperan/oracle-agent-setup",
11
+ "keywords": [
12
+ "oracle",
13
+ "database",
14
+ "agent-memory",
15
+ "memory"
16
+ ]
17
+ }
@@ -0,0 +1,35 @@
1
+ {
2
+ "name": "oracle-ai-database",
3
+ "version": "0.2.0",
4
+ "description": "Stores every Codex conversation in Oracle AI Database (Oracle AI Agent Memory) and adds a skill to recall past sessions.",
5
+ "author": {
6
+ "name": "jasperan",
7
+ "url": "https://github.com/jasperan"
8
+ },
9
+ "homepage": "https://github.com/jasperan/oracle-agent-setup",
10
+ "repository": "https://github.com/jasperan/oracle-agent-setup",
11
+ "keywords": [
12
+ "oracle",
13
+ "database",
14
+ "agent-memory",
15
+ "memory"
16
+ ],
17
+ "skills": "./skills/",
18
+ "hooks": "./hooks/codex.json",
19
+ "interface": {
20
+ "displayName": "Oracle AI Database",
21
+ "shortDescription": "Your agent conversations, stored and searchable in Oracle AI Database",
22
+ "longDescription": "Writes every Codex turn to an Oracle AI Agent Memory store in Oracle AI Database and teaches Codex to recall earlier sessions.",
23
+ "developerName": "jasperan",
24
+ "category": "Productivity",
25
+ "capabilities": [
26
+ "Read",
27
+ "Write"
28
+ ],
29
+ "websiteURL": "https://github.com/jasperan/oracle-agent-setup",
30
+ "defaultPrompt": [
31
+ "What did we decide last week about the database schema?",
32
+ "Find my earlier sessions about this repository"
33
+ ]
34
+ }
35
+ }
@@ -0,0 +1,4 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.egg-info/
4
+ node_modules/
@@ -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,14 @@
1
+ # oracle-agent
2
+
3
+ `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).
4
+
5
+ You normally don't run this CLI by hand: the plugin runs it for you. To set up the database yourself:
6
+
7
+ ```
8
+ uvx oracle-agent up # Oracle AI Database Free in a local Podman/Docker container
9
+ ORACLE_AGENT_DB_PASSWORD=... uvx oracle-agent up --dsn '<connect string>' --user '<user>' # an existing database
10
+ uvx oracle-agent search "keywords" # search saved conversations
11
+ uvx oracle-agent status # what is stored
12
+ ```
13
+
14
+ See the [project README](https://github.com/jasperan/oracle-agent-setup#readme) to install the plugin for your agent.
@@ -0,0 +1,63 @@
1
+ #!/bin/sh
2
+ # Runs the oracle-agent CLI that ships inside this plugin. uv installs its Python dependencies
3
+ # (oracleagentmemory, oracledb) on first use and caches them. The plugin's own sources are
4
+ # installed editable, so a plugin updated in place (pi, dsh) never runs a stale cached build.
5
+ #
6
+ # Before setup, hooks exit immediately, and `doctor` asks the agent to offer setup.
7
+ # Neither needs Python or a download.
8
+
9
+ root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
10
+ home=${ORACLE_AGENT_HOME:-$HOME/.oracle-agent}
11
+ export ORACLE_AGENT_LAUNCHER="$root/bin/oracle-agent"
12
+
13
+ uv=$(command -v uv)
14
+ for candidate in "$HOME/.local/bin/uv" "$HOME/.cargo/bin/uv" /opt/homebrew/bin/uv /usr/local/bin/uv; do
15
+ [ -n "$uv" ] && break
16
+ [ -x "$candidate" ] && uv=$candidate
17
+ done
18
+ cli() { "$uv" run --quiet --no-project --with-editable "$root" python -m oracle_agent.cli "$@"; }
19
+
20
+ if [ "$1" = decline ]; then
21
+ mkdir -p "$home" && touch "$home/declined"
22
+ echo "Oracle AI Database setup postponed; the plugin will offer it again in 14 days."
23
+ exit 0
24
+ fi
25
+
26
+ if [ ! -f "$home/config.json" ]; then
27
+ case "$1" in
28
+ hook)
29
+ cat >/dev/null
30
+ exit 0
31
+ ;;
32
+ doctor)
33
+ cat >/dev/null
34
+ if [ -f "$home/declined" ] && [ -n "$(find "$home/declined" -mtime -14 2>/dev/null)" ]; then
35
+ exit 0
36
+ fi
37
+ launcher=$(printf '%s' "$ORACLE_AGENT_LAUNCHER" | sed 's/[\\"]/\\&/g')
38
+ uv_note=""
39
+ if [ -z "$uv" ]; then
40
+ uv_note="Setup needs uv, which is not installed. With the user's permission, install it first: curl -LsSf https://astral.sh/uv/install.sh | sh\\n"
41
+ else
42
+ # Warm uv's cache in the background so `up` starts immediately.
43
+ (cli --help </dev/null >/dev/null 2>&1 &)
44
+ fi
45
+ printf '{"hookSpecificOutput":{"hookEventName":"SessionStart","additionalContext":"%s"}}\n' \
46
+ "The oracle-ai-database plugin is installed but not set up, so this conversation is not being saved to Oracle AI Database.\\n\
47
+ ${uv_note}\
48
+ Ask the user once, in one short question at the start of your first reply, whether to set it up, then continue with what they asked:\\n\
49
+ 1. Local database (recommended): Oracle AI Database Free in a Podman or Docker container on this machine. About 1.7 GB download, no account. Run: sh '${launcher}' up\\n\
50
+ 2. An existing Oracle AI Database, for example Autonomous AI Database on OCI. New to OCI: https://signup.cloud.oracle.com/ . Existing OCI users can create or open one at https://cloud.oracle.com/db/adbs . Ask for its connect string, username and password (never invent them), then run: ORACLE_AGENT_DB_PASSWORD='<password>' sh '${launcher}' up --dsn '<connect string>' --user '<username>'\\n\
51
+ 3. Not now: run sh '${launcher}' decline (the plugin asks again in 14 days).\\n\
52
+ If up reports that no container engine is running, run podman machine start (or ask the user to start Docker Desktop) and retry."
53
+ exit 0
54
+ ;;
55
+ esac
56
+ fi
57
+
58
+ if [ -z "$uv" ]; then
59
+ [ "$1" = hook ] || [ "$1" = doctor ] && { cat >/dev/null; exit 0; }
60
+ echo "oracle-agent needs uv: curl -LsSf https://astral.sh/uv/install.sh | sh" >&2
61
+ exit 1
62
+ fi
63
+ cli "$@"
@@ -0,0 +1,3 @@
1
+ - insert:
2
+ - id: oracle-agent-setup-dsh
3
+ name: oracle-agent-setup-dsh
@@ -0,0 +1,60 @@
1
+ // Store each DeepSeek Harness turn in Oracle AI Database.
2
+ //
3
+ // dsh session files are zstd-compressed by default and not flushed at turn boundaries, so this
4
+ // plugin collects the turn's user/assistant text from the live `session/event` stream and hands it
5
+ // to the plugin's bundled launcher (`bin/oracle-agent hook dsh`) when the turn ends.
6
+
7
+ import { spawn } from 'node:child_process'
8
+ import { fileURLToPath } from 'node:url'
9
+
10
+ export const name = 'oracle-agent-setup-dsh'
11
+
12
+ const launcher = fileURLToPath(new URL('../bin/oracle-agent', import.meta.url))
13
+
14
+ const textOf = (content) =>
15
+ (content ?? []).filter((b) => b.type === 'text' && b.text).map((b) => b.text).join('\n\n').trim()
16
+
17
+ export function apply(ctx) {
18
+ const pending = new Map() // session id -> messages of the running turn
19
+
20
+ const push = (sessionId, role, message, time) => {
21
+ const text = textOf(message?.content)
22
+ if (text) pending.get(sessionId)?.push({ role, text, timestamp: new Date(time).toISOString(), id: message.id })
23
+ }
24
+
25
+ const store = (session, messages) => {
26
+ const child = spawn('sh', [launcher, 'hook', 'dsh'], { stdio: ['pipe', 'ignore', 'ignore'] })
27
+ child.on('error', (error) => ctx.logger?.warn?.(`oracle-agent hook failed to start: ${error}`))
28
+ child.stdin.on('error', () => {})
29
+ child.stdin.end(JSON.stringify({
30
+ session_id: session.id,
31
+ transcript_path: null,
32
+ cwd: session.header?.cwd ?? null,
33
+ hook_event_name: 'Stop',
34
+ messages,
35
+ }))
36
+ }
37
+
38
+ ctx.on('session/event', (session, event) => {
39
+ if (session.header?.origin === 'subagent') return
40
+ switch (event.type) {
41
+ case 'turn/start':
42
+ pending.set(session.id, [])
43
+ break
44
+ case 'user/message':
45
+ if (event.data?.source?.kind === 'user') push(session.id, 'user', event.data, event.time)
46
+ break
47
+ case 'assistant/message':
48
+ push(session.id, 'assistant', event.data?.message, event.time)
49
+ break
50
+ case 'turn/end': {
51
+ const messages = pending.get(session.id)
52
+ pending.delete(session.id)
53
+ if (messages?.length) store(session, messages)
54
+ break
55
+ }
56
+ }
57
+ })
58
+
59
+ ctx.on('session/disposed', (session) => pending.delete(session.id))
60
+ }
@@ -0,0 +1,40 @@
1
+ {
2
+ "description": "Oracle AI Database: offer setup, recall the last session, and store each Codex turn.",
3
+ "hooks": {
4
+ "SessionStart": [
5
+ {
6
+ "matcher": "startup|clear|resume",
7
+ "hooks": [
8
+ {
9
+ "type": "command",
10
+ "command": "sh \"${CLAUDE_PLUGIN_ROOT}/bin/oracle-agent\" doctor codex",
11
+ "timeout": 60
12
+ }
13
+ ]
14
+ }
15
+ ],
16
+ "UserPromptSubmit": [
17
+ {
18
+ "hooks": [
19
+ {
20
+ "type": "command",
21
+ "command": "sh \"${CLAUDE_PLUGIN_ROOT}/bin/oracle-agent\" hook codex",
22
+ "timeout": 10
23
+ }
24
+ ]
25
+ }
26
+ ],
27
+ "Stop": [
28
+ {
29
+ "hooks": [
30
+ {
31
+ "type": "command",
32
+ "command": "sh \"${CLAUDE_PLUGIN_ROOT}/bin/oracle-agent\" hook codex",
33
+ "async": true,
34
+ "timeout": 120
35
+ }
36
+ ]
37
+ }
38
+ ]
39
+ }
40
+ }
@@ -0,0 +1,40 @@
1
+ {
2
+ "description": "Oracle AI Database: offer setup, recall the last session, and store each Claude Code turn.",
3
+ "hooks": {
4
+ "SessionStart": [
5
+ {
6
+ "matcher": "startup|clear|resume",
7
+ "hooks": [
8
+ {
9
+ "type": "command",
10
+ "command": "sh \"${CLAUDE_PLUGIN_ROOT}/bin/oracle-agent\" doctor claude",
11
+ "timeout": 60
12
+ }
13
+ ]
14
+ }
15
+ ],
16
+ "Stop": [
17
+ {
18
+ "hooks": [
19
+ {
20
+ "type": "command",
21
+ "command": "sh \"${CLAUDE_PLUGIN_ROOT}/bin/oracle-agent\" hook claude",
22
+ "async": true,
23
+ "timeout": 120
24
+ }
25
+ ]
26
+ }
27
+ ],
28
+ "SessionEnd": [
29
+ {
30
+ "hooks": [
31
+ {
32
+ "type": "command",
33
+ "command": "sh \"${CLAUDE_PLUGIN_ROOT}/bin/oracle-agent\" hook claude",
34
+ "timeout": 30
35
+ }
36
+ ]
37
+ }
38
+ ]
39
+ }
40
+ }
@@ -0,0 +1,25 @@
1
+ {
2
+ "name": "oracle-agent-setup-dsh",
3
+ "version": "0.2.0",
4
+ "description": "Store every DeepSeek Harness conversation in Oracle AI Database (Oracle AI Agent Memory).",
5
+ "type": "module",
6
+ "main": "dsh/index.js",
7
+ "files": [
8
+ "dsh",
9
+ "bin",
10
+ "cordis.patch.yml",
11
+ "pyproject.toml",
12
+ "src"
13
+ ],
14
+ "keywords": [
15
+ "dsh-plugin",
16
+ "oracle",
17
+ "database",
18
+ "agent-memory"
19
+ ],
20
+ "dsh": {
21
+ "bundle": {
22
+ "patch": "./cordis.patch.yml"
23
+ }
24
+ }
25
+ }
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Oracle AI Database for pi: offers setup (or recalls the previous session) before the first prompt
3
+ * of a session, and stores each turn by handing the session file to the plugin's launcher.
4
+ */
5
+
6
+ import { spawn, spawnSync } from "node:child_process";
7
+ import { fileURLToPath } from "node:url";
8
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
9
+
10
+ const launcher = fileURLToPath(new URL("../bin/oracle-agent", import.meta.url));
11
+
12
+ function event(ctx: ExtensionContext, extra: Record<string, unknown> = {}): string {
13
+ return JSON.stringify({
14
+ session_id: ctx.sessionManager.getSessionId(),
15
+ transcript_path: ctx.sessionManager.getSessionFile() ?? null,
16
+ cwd: ctx.cwd,
17
+ ...extra,
18
+ });
19
+ }
20
+
21
+ function store(ctx: ExtensionContext): void {
22
+ if (!ctx.sessionManager.getSessionFile()) return; // ephemeral session (--no-session)
23
+ const child = spawn("sh", [launcher, "hook", "pi"], { stdio: ["pipe", "ignore", "ignore"], detached: true });
24
+ child.on("error", () => {}); // never break the session
25
+ child.stdin.on("error", () => {});
26
+ child.stdin.end(event(ctx));
27
+ child.unref();
28
+ }
29
+
30
+ function doctor(ctx: ExtensionContext): string | undefined {
31
+ const result = spawnSync("sh", [launcher, "doctor", "pi"], {
32
+ input: event(ctx, { source: "startup" }),
33
+ encoding: "utf8",
34
+ timeout: 60_000,
35
+ });
36
+ try {
37
+ return JSON.parse(result.stdout).hookSpecificOutput?.additionalContext;
38
+ } catch {
39
+ return undefined; // nothing to say, or the launcher failed
40
+ }
41
+ }
42
+
43
+ export default function (pi: ExtensionAPI) {
44
+ const greeted = new Set<string>();
45
+
46
+ pi.on("before_agent_start", async (e, ctx) => {
47
+ const id = ctx.sessionManager.getSessionId();
48
+ if (e.messageType !== "user" || greeted.has(id)) return;
49
+ greeted.add(id);
50
+ const context = doctor(ctx);
51
+ if (context) return { message: { customType: "oracle-agent", content: context, display: false } };
52
+ });
53
+ pi.on("agent_settled", async (_e, ctx) => store(ctx));
54
+ pi.on("session_shutdown", async (_e, ctx) => store(ctx));
55
+ }
@@ -0,0 +1,24 @@
1
+ [project]
2
+ name = "oracle-agent"
3
+ version = "0.2.0"
4
+ description = "Store every coding-agent conversation in Oracle AI Database through Oracle AI Agent Memory."
5
+ readme = "README.md"
6
+ requires-python = ">=3.10,<3.15"
7
+ keywords = ["oracle", "database", "agent-memory", "claude-code", "codex", "coding-agent"]
8
+ dependencies = [
9
+ "oracleagentmemory>=26.8.1",
10
+ "oracledb>=4.0.2",
11
+ ]
12
+
13
+ [project.urls]
14
+ Homepage = "https://github.com/jasperan/oracle-agent-setup"
15
+
16
+ [project.scripts]
17
+ oracle-agent = "oracle_agent.cli:main"
18
+
19
+ [build-system]
20
+ requires = ["hatchling"]
21
+ build-backend = "hatchling.build"
22
+
23
+ [tool.hatch.build.targets.wheel]
24
+ packages = ["src/oracle_agent"]
@@ -0,0 +1,47 @@
1
+ ---
2
+ name: oracle-agent-memory
3
+ description: Recall earlier coding-agent conversations stored in Oracle AI Database. Use when the user refers to previous sessions or decisions ("last time", "what did we decide", "remember when", "we discussed", "earlier you said"), asks to find past work on a topic, file, error, or repository, or wants to know what is stored about their agent history.
4
+ ---
5
+
6
+ # Oracle Agent Memory
7
+
8
+ Every turn of this agent (user prompt + assistant reply; no tool output) is written to an
9
+ Oracle AI Agent Memory store in Oracle AI Database by the `oracle-ai-database` plugin. At the
10
+ start of a session the plugin also adds how the previous session in the same directory ended.
11
+ Use the store to answer questions about earlier sessions instead of guessing.
12
+
13
+ The CLI is `~/.oracle-agent/bin/oracle-agent`. If that file does not exist, the store is not set
14
+ up yet: offer the user to set it up with the instructions the plugin added at session start, or
15
+ from https://raw.githubusercontent.com/jasperan/oracle-agent-setup/main/prompt.md.
16
+
17
+ ## Recall
18
+
19
+ ```bash
20
+ ~/.oracle-agent/bin/oracle-agent search "<2-4 distinctive keywords>" --limit 10
21
+ ~/.oracle-agent/bin/oracle-agent search "<keywords>" --json # full message text, for quoting
22
+ ```
23
+
24
+ - Search is keyword-based: use distinctive nouns (table names, error codes, file names,
25
+ product names), not full sentences. Retry with synonyms or fewer words when nothing matches.
26
+ - Results show `[timestamp] <harness>-<session id> <role>: text`. Threads from every
27
+ harness (claude, codex, pi, dsh) are searched together.
28
+ - Quote what was said and when; say which session it came from.
29
+
30
+ ## Status and settings
31
+
32
+ ```bash
33
+ ~/.oracle-agent/bin/oracle-agent status # row counts per store table and storage used
34
+ ~/.oracle-agent/bin/oracle-agent recall off # stop adding the previous session at session start (on/off)
35
+ ~/.oracle-agent/bin/oracle-agent up # idempotent: starts a stopped local database
36
+ ```
37
+
38
+ Failures inside hooks are logged to `~/.oracle-agent/hook.log`.
39
+
40
+ ## Direct SQL
41
+
42
+ Connection settings are in `~/.oracle-agent/config.json` (`user`, `password`, `dsn`). Messages
43
+ live in `AGENTS_MESSAGE` (`THREAD_ID`, `ORDER_SEQ`, `MESSAGE_ROLE`, `CONTENT` JSON, `TIMESTAMP`,
44
+ `METADATA` JSON); sessions in `AGENTS_THREAD` (`RECORD_ID` = the thread ID, `METADATA` JSON with
45
+ `harness`, `cwd`). Read-only queries only: never update or delete stored
46
+ history unless the user explicitly asks. For Oracle SQL, PL/SQL, and Oracle AI Vector Search
47
+ guidance, use the Oracle `db` skills.
@@ -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}