Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions client/cli/chat_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@
# tools: one records what the model said, the other hands it back for
# free so a harness change can be judged without paying for the model
# twice.
"--session": ("SPEAR_SESSION",
"open this named conversation of the corpus instead of its "
"default one; each is held by one spear-chat at a time"),
"--record": ("SPEAR_RECORD_TURNS",
"record this session's model turns to a file"),
"--replay": ("SPEAR_REPLAY_TURNS",
Expand Down
172 changes: 172 additions & 0 deletions client/cli/conversation_sessions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
"""Named conversations on one corpus, and the lock that keeps each to one process.

A corpus used to hold a single conversation: two spear-chat processes on the
same tree read and rewrote the same history file, and the last to save won.
A conversation now has a name; the unnamed one keeps the file it always had,
so nothing changes for whoever never names one.
"""

import fcntl
import glob
import json
import os
import re
from datetime import datetime


NAME_PATTERN = re.compile(r"[A-Za-z0-9_.-]{1,40}")

USAGE = ("usage: /session [list] | /session new <name> | "
"/session switch <name> | /session rm <name>")


class ConversationError(Exception):
"""A conversation that cannot be named, opened or removed as asked."""


def validate_name(name):
"""The name itself, or ConversationError. None names the default one."""
if name is None:
return None

if not NAME_PATTERN.fullmatch(name) or name in (".", ".."):
raise ConversationError(
f"invalid session name {name!r}: 1 to 40 of A-Z a-z 0-9 _ . -")

return name


def history_file(default_file, name):
"""Where conversation `name` keeps its history, beside the default one."""
if name is None:
return default_file

return f"{default_file[:-len('.json')]}-{validate_name(name)}.json"


def describe(name):
return name if name is not None else "(default)"


class ConversationLock:
"""An exclusive, advisory lock on one conversation, held while it is open.

flock and not a pid file: the kernel drops it when the process dies, so a
crashed session never leaves its conversation unusable.
"""

def __init__(self):
self.path = None
self._handle = None

def acquire(self, history_path):
"""Take the lock of `history_path`, or raise ConversationError."""
path = history_path + ".lock"

if path == self.path:
return

os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
handle = open(path, "a+")

try:
fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
handle.close()
raise ConversationError(
"this session is open in another spear-chat; "
"pick another with --session <name> or /session switch <name>"
) from None

self.release()
self.path, self._handle = path, handle

def release(self):
if self._handle is not None:
fcntl.flock(self._handle, fcntl.LOCK_UN)
self._handle.close()

self.path, self._handle = None, None

@staticmethod
def held_elsewhere(history_path):
"""Whether another process holds `history_path` (a probe, not a take)."""
path = history_path + ".lock"

if not os.path.exists(path):
return False

with open(path, "a+") as handle:
try:
fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
return True

fcntl.flock(handle, fcntl.LOCK_UN)

return False


def list_conversations(default_file):
"""(name, history path) for every conversation of this corpus, default first."""
found = [(None, default_file)]
prefix = default_file[:-len(".json")] + "-"

names = set()

for suffix in (".json", ".json.lock"):
for path in glob.glob(glob.escape(prefix) + "*" + suffix):
name = path[len(prefix):-len(suffix)]

if NAME_PATTERN.fullmatch(name) and (
suffix == ".json" or ConversationLock.held_elsewhere(
path[:-len(".lock")])):
names.add(name)

return found + [(name, f"{prefix}{name}.json") for name in sorted(names)]


def summary_lines(default_file, current, lock):
"""The /session listing: name, messages, last change, who holds it."""
lines = []

for name, path in list_conversations(default_file):
try:
with open(path) as handle:
count = len(json.load(handle))
changed = datetime.fromtimestamp(os.path.getmtime(path)).strftime(
"%Y-%m-%d %H:%M")
except (OSError, ValueError):
count, changed = 0, "-"

mark = "*" if name == current else " "
state = (" (open elsewhere)" if name != current
and ConversationLock.held_elsewhere(path) else "")

lines.append(f" {mark} {describe(name):<24} {count:4d} messages "
f"{changed}{state}")

return lines


def remove(default_file, name, current):
"""Delete conversation `name`'s history; never the open or the default one."""
validate_name(name)

if name is None or name == current:
raise ConversationError("cannot remove the session in use")

path = history_file(default_file, name)

if not os.path.exists(path):
raise ConversationError(f"no session named {name}")

if ConversationLock.held_elsewhere(path):
raise ConversationError(f"session {name} is open in another spear-chat")

os.remove(path)

try:
os.remove(path + ".lock")
except FileNotFoundError:
pass
3 changes: 2 additions & 1 deletion client/cli/operator_input.py
Original file line number Diff line number Diff line change
Expand Up @@ -312,7 +312,8 @@ def handle_bang_command(cmd_line):
#: one list, so a command cannot be completed and go unlisted, or the reverse.
SESSION_COMMANDS = ("/search", "/cd", "/reindex", "/corpus", "/history",
"/skills", "/remember", "/recall", "/knowledge", "/forget",
"/good", "/bad", "/fix", "/undo", "/clear", "/model", "/tools")
"/good", "/bad", "/fix", "/undo", "/clear", "/session",
"/model", "/tools")
OPERATOR_COMMANDS = ("/standard", "/finetune")


Expand Down
125 changes: 116 additions & 9 deletions client/cli/rag_chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,10 @@
from standard.standard_commands import (
StandardCommandError, handle_standard_command, standard_help_lines,
)
from cli import corpus_search, model_io, session_workspace, standard_session
from cli import (
conversation_sessions, corpus_search, model_io, session_workspace,
standard_session,
)
from cli.chat_settings import (
APP_DIR, CHECKPOINT_ROOT, CONTEXT_ENGINE, LEARNED_RULES_FILE,
LLAMA_SERVER_URL, RESULT_STORE, RULES_BUDGET, SESSION_STORE,
Expand Down Expand Up @@ -90,7 +93,8 @@
)
from cli.session_history import (
HISTORY_INJECT, MAX_HISTORY, TRAJECTORY_FILE, archive_entry,
load_history, save_experience, save_history, save_trajectory,
fresh_session, load_history, save_experience, save_history,
save_trajectory,
)
from cli.session_workspace import (
command_result_text, extra_roots_note, is_excluded_path,
Expand Down Expand Up @@ -219,6 +223,83 @@ def corpus_prompt():
return system_instructions, system_source, global_rules, project_rules


def reset_conversation_state():
"""Forget what the last answer engaged: the turn a follow-up would refer
back to is gone with the history (/clear) or belongs to another
conversation (/session switch)."""
standard_session.STANDARD_ENGAGED_BEFORE = False
standard_session.STANDARD_PRIOR_CLAUSES = ()
standard_session.STANDARD_PRIOR_ANSWER = ""
standard_session.STANDARD_PRIOR_REQUIREMENTS = requirement_set.RequirementSet()


def use_conversation(name, lock):
"""Point the history at conversation `name` and hold its lock."""
path = conversation_sessions.history_file(
session_workspace.DEFAULT_HISTORY_FILE, name)
lock.acquire(path)
session_workspace.CONVERSATION = name
session_workspace.HISTORY_FILE = path


def session_command(argument, history, lock):
"""/session: list, create, switch to or remove a named conversation.

Returns the history to continue with.
"""
words = argument.split()
action = words[0] if words else "list"
name = words[1] if len(words) == 2 else None
current = session_workspace.CONVERSATION
default_file = session_workspace.DEFAULT_HISTORY_FILE

try:
if action == "list" and len(words) <= 1:
print("\n".join(conversation_sessions.summary_lines(
default_file, current, lock)) + "\n")

return history

if action in ("new", "switch") and len(words) == 2:
target = None if name == "default" else name
path = conversation_sessions.history_file(default_file, target)

if action == "new" and os.path.exists(path):
raise conversation_sessions.ConversationError(
f"session {name} exists: /session switch {name}")

if (action == "switch" and target not in (current, None)
and not os.path.exists(path)
and not conversation_sessions.ConversationLock.held_elsewhere(path)):
raise conversation_sessions.ConversationError(
f"no session named {name}: /session new {name}")

save_history(history)
use_conversation(target, lock)
reset_conversation_state()
history = load_history()

if not os.path.exists(path):
save_history(history)

print(f"Session {conversation_sessions.describe(target)}: "
f"{len(history)} messages.\n")

return history

if action == "rm" and len(words) == 2:
conversation_sessions.remove(default_file, name, current)
print(f"Session {name} removed.\n")

return history

print(conversation_sessions.USAGE + "\n")
except conversation_sessions.ConversationError as exc:
print(f"{C_ERR}/session: {exc}{C_RST}\n")

return history


def main():
global TRACE_PROVIDER, TRACE_MODEL

Expand All @@ -231,6 +312,16 @@ def main():

banner_art()
set_project(resolve_project_at_startup())
conversation_lock = conversation_sessions.ConversationLock()

if not fresh_session():
try:
conversation_lock.acquire(session_workspace.HISTORY_FILE)
except conversation_sessions.ConversationError as exc:
print(f"{C_ERR}session "
f"{conversation_sessions.describe(session_workspace.CONVERSATION)}"
f": {exc}{C_RST}")
return

# Where /cd resolves a relative path from: the directory it last entered.

Expand Down Expand Up @@ -521,8 +612,19 @@ def read_user_input():
f"session was launched — relaunch spear there{C_RST}\n")
else:
save_history(history)
focus = target
previous = dict(session_workspace.PROJECT_SPEC)
set_project(corpus_at(target))

if not fresh_session():
try:
conversation_lock.acquire(session_workspace.HISTORY_FILE)
except conversation_sessions.ConversationError as exc:
set_project(previous)
print(f"{C_ERR}/cd: {exc}{C_RST}\n")

continue

focus = target
(system_instructions, system_source,
global_rules, project_rules) = corpus_prompt()
base_prompt = system_instructions + global_rules + project_rules + TOOL_GUIDE
Expand Down Expand Up @@ -569,14 +671,18 @@ def read_user_input():
if user_input in ("/clear", "/new"):
history = []
save_history(history)
reset_conversation_state()
print("History cleared.\n")

# The turn a follow-up would refer back to is gone with it.
continue

standard_session.STANDARD_ENGAGED_BEFORE = False
standard_session.STANDARD_PRIOR_CLAUSES = ()
standard_session.STANDARD_PRIOR_ANSWER = ""
standard_session.STANDARD_PRIOR_REQUIREMENTS = requirement_set.RequirementSet()
print("History cleared.\n")
if user_input == "/session" or user_input.startswith("/session "):
if fresh_session():
print(f"{C_ERR}/session: a --fresh session keeps no "
f"history{C_RST}\n")
else:
history = session_command(user_input[len("/session"):],
history, conversation_lock)

continue

Expand Down Expand Up @@ -1286,6 +1392,7 @@ def context_items_for(rendered):
"data_origin": os.environ.get(
"SPEAR_TRAINING_DATA_ORIGIN", "NORMAL_USAGE",
).upper(),
"conversation": session_workspace.CONVERSATION,
"user_input_chars": len(user_input),
"raw_content_recorded": False,
},
Expand Down
Loading
Loading