cof-cli 1.2.0__tar.gz → 1.2.2__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.
- {cof_cli-1.2.0 → cof_cli-1.2.2}/PKG-INFO +5 -2
- {cof_cli-1.2.0 → cof_cli-1.2.2}/README.md +4 -1
- {cof_cli-1.2.0 → cof_cli-1.2.2}/cof_cli/__init__.py +1 -1
- cof_cli-1.2.2/cof_cli/agents.py +269 -0
- {cof_cli-1.2.0 → cof_cli-1.2.2}/cof_cli/cli.py +220 -12
- {cof_cli-1.2.0 → cof_cli-1.2.2}/cof_cli/completeness.py +7 -3
- {cof_cli-1.2.0 → cof_cli-1.2.2}/cof_cli/convert.py +28 -5
- cof_cli-1.2.2/cof_cli/platform_import.py +1571 -0
- {cof_cli-1.2.0 → cof_cli-1.2.2}/cof_cli/psyche.py +1 -0
- {cof_cli-1.2.0 → cof_cli-1.2.2}/cof_cli.egg-info/PKG-INFO +5 -2
- {cof_cli-1.2.0 → cof_cli-1.2.2}/cof_cli.egg-info/SOURCES.txt +4 -0
- {cof_cli-1.2.0 → cof_cli-1.2.2}/pyproject.toml +1 -1
- cof_cli-1.2.2/tests/test_agents.py +155 -0
- cof_cli-1.2.2/tests/test_platform_import.py +773 -0
- {cof_cli-1.2.0 → cof_cli-1.2.2}/tests/test_roundtrip.py +47 -1
- {cof_cli-1.2.0 → cof_cli-1.2.2}/cof_cli/cast.py +0 -0
- {cof_cli-1.2.0 → cof_cli-1.2.2}/cof_cli/container.py +0 -0
- {cof_cli-1.2.0 → cof_cli-1.2.2}/cof_cli/memories.py +0 -0
- {cof_cli-1.2.0 → cof_cli-1.2.2}/cof_cli/migrate.py +0 -0
- {cof_cli-1.2.0 → cof_cli-1.2.2}/cof_cli/model.py +0 -0
- {cof_cli-1.2.0 → cof_cli-1.2.2}/cof_cli/ops.py +0 -0
- {cof_cli-1.2.0 → cof_cli-1.2.2}/cof_cli/profiles.py +0 -0
- {cof_cli-1.2.0 → cof_cli-1.2.2}/cof_cli/propose.py +0 -0
- {cof_cli-1.2.0 → cof_cli-1.2.2}/cof_cli/schemas/attitude.schema.json +0 -0
- {cof_cli-1.2.0 → cof_cli-1.2.2}/cof_cli/schemas/body.schema.json +0 -0
- {cof_cli-1.2.0 → cof_cli-1.2.2}/cof_cli/schemas/card.schema.json +0 -0
- {cof_cli-1.2.0 → cof_cli-1.2.2}/cof_cli/schemas/consent.schema.json +0 -0
- {cof_cli-1.2.0 → cof_cli-1.2.2}/cof_cli/schemas/garments-1.0.json +0 -0
- {cof_cli-1.2.0 → cof_cli-1.2.2}/cof_cli/schemas/hair.schema.json +0 -0
- {cof_cli-1.2.0 → cof_cli-1.2.2}/cof_cli/schemas/manifest.schema.json +0 -0
- {cof_cli-1.2.0 → cof_cli-1.2.2}/cof_cli/schemas/memory.schema.json +0 -0
- {cof_cli-1.2.0 → cof_cli-1.2.2}/cof_cli/schemas/pose.schema.json +0 -0
- {cof_cli-1.2.0 → cof_cli-1.2.2}/cof_cli/schemas/psyche-node.schema.json +0 -0
- {cof_cli-1.2.0 → cof_cli-1.2.2}/cof_cli/schemas/psyche.schema.json +0 -0
- {cof_cli-1.2.0 → cof_cli-1.2.2}/cof_cli/schemas/skeleton.schema.json +0 -0
- {cof_cli-1.2.0 → cof_cli-1.2.2}/cof_cli/schemas/visemes.schema.json +0 -0
- {cof_cli-1.2.0 → cof_cli-1.2.2}/cof_cli/schemas/voice-profile.schema.json +0 -0
- {cof_cli-1.2.0 → cof_cli-1.2.2}/cof_cli/schemas/weights.schema.json +0 -0
- {cof_cli-1.2.0 → cof_cli-1.2.2}/cof_cli/selfdesc.py +0 -0
- {cof_cli-1.2.0 → cof_cli-1.2.2}/cof_cli/tokens.py +0 -0
- {cof_cli-1.2.0 → cof_cli-1.2.2}/cof_cli/validate.py +0 -0
- {cof_cli-1.2.0 → cof_cli-1.2.2}/cof_cli/zodiac.py +0 -0
- {cof_cli-1.2.0 → cof_cli-1.2.2}/cof_cli.egg-info/dependency_links.txt +0 -0
- {cof_cli-1.2.0 → cof_cli-1.2.2}/cof_cli.egg-info/entry_points.txt +0 -0
- {cof_cli-1.2.0 → cof_cli-1.2.2}/cof_cli.egg-info/requires.txt +0 -0
- {cof_cli-1.2.0 → cof_cli-1.2.2}/cof_cli.egg-info/top_level.txt +0 -0
- {cof_cli-1.2.0 → cof_cli-1.2.2}/setup.cfg +0 -0
- {cof_cli-1.2.0 → cof_cli-1.2.2}/tests/test_hunt.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: cof-cli
|
|
3
|
-
Version: 1.2.
|
|
3
|
+
Version: 1.2.2
|
|
4
4
|
Summary: COF — Character Open File: validate, pack, unpack and convert .cof character containers
|
|
5
5
|
Author: Yann Souetre
|
|
6
6
|
License-Expression: MIT
|
|
@@ -32,6 +32,7 @@ cof extract clara.cof --preset default --no-risk -o clara-sans-risque/ #
|
|
|
32
32
|
cof merge clara.cof martien.cof -o duo/ # un casting : même nom + surnom + statut fictif + morphologie ⇒ même personnage, sinon plusieurs
|
|
33
33
|
cof memory add clara.cof --gist fr="Ce matin, relu avec Léo." --gist en="This morning, reread with Léo." --date 2026-10-25 --who "Léo" --what "le carnet" --what "item=appearance/x1" --tag travail --personal # --what : un objet (1.2, RFC 0005), un nom et/ou item=<élément>, |shown s'il est dans un média
|
|
34
34
|
cof memory add clara/ --kind period --gist en="The agency years." --age 24 --approx --fidelity faded # sur un dossier ; `--help` liste tout (--where, --self-shown, --media, --preset…)
|
|
35
|
+
cof memory add clara.cof --from-agent ./agent/ # le retour : les notes du jour d'un espace OpenClaw (memory/AAAA-MM-JJ.md) ou les entrées § d'un profil Hermes (memories/MEMORY.md) deviennent des souvenirs vécus, personnels, datés, étiquetés lived:<hôte> ; idempotent (--agent-source, --lang)
|
|
35
36
|
cof psyche add clara.cof --kind stance --gist fr="Envers l'utilisateur : une collègue." --about user --strength 60 --stability shifting --link because=memories/ev3 --since-date 2026-10-25 # nœud vécu, `visibility: personal` (--canon sinon), première révision ; `--help` liste tout (--lie, --risk, --tag, --preset…)
|
|
36
37
|
cof psyche add clara.cof --kind habit --gist fr="Garde la guitare près du bureau." --who "ma grand-mère" --where "environment=appearance/e1" --what "ma guitare|item=appearance/x1" --canon # personnes, lieux, objets du nœud (RFC 0005) ; une personne du casting : --who identity=<id> (les liens --link ne visent que souvenirs et nœuds)
|
|
37
38
|
cof psyche add clara.cof --kind stance --gist fr="Envers l'utilisateur : de la chaleur." --about user --valence 60 --aware partly --canon # RFC 0004 § 3 nonies : --valence −100…+100 (position ou goût seulement), --aware yes|partly|no, --until-age / --until-date (quand le nœud a cessé d'être tenu)
|
|
@@ -43,7 +44,9 @@ cof import carte.png -o perso/ --age 30 --lang fr --keep-png # carte PNG CCv2/
|
|
|
43
44
|
cof export clara.cof --format png -o clara.png # → PNG avec chunks chara + ccv3
|
|
44
45
|
cof export clara.cof --format card -o clara.card.json
|
|
45
46
|
cof export clara.cof --format soul -o ./agent/ # → SOUL.md + IDENTITY.md
|
|
46
|
-
cof
|
|
47
|
+
cof diff clara.cof rebuilt.cof # ce qui diffère entre deux .cof : membres, octets, clés JSON (code de sortie 1 si différent) — l'outil de la promesse « rien d'autre ne bouge » du builder
|
|
48
|
+
cof export clara.cof --format agent -o ./agent/ # → espace de travail d'agent : SOUL.md (avec « Qui elle est » rendu depuis la psyché), IDENTITY.md, AGENTS.md (consignes de mémoire pour l'hôte), skills/, MEMORY.md, COF.md (--keep-personal, --keep-dangerous, --keep-secrets, --preset) ; les souvenirs `disclosure: secret` restent dans le .cof sauf --keep-secrets (« N secret memories left out »), qui les écrit marqués `secret` et ajoute à AGENTS.md une ligne : ce sont des secrets que le personnage ne révèle jamais
|
|
49
|
+
cof export clara.cof --format hermes -o ./hermes/ # → profil Hermes Agent (HERMES_HOME) : SOUL.md (identité fusionnée), memories/MEMORY.md en entrées § sous le plafond de l'hôte (2 200 caractères, les plus saillants), skills/, COF.md ; mêmes options, secrets laissés de côté par défaut (avec --keep-secrets : entrées préfixées « (secret) », la ligne dans SOUL.md)
|
|
47
50
|
cof embed-text clara.png fiche.md -o clara-fiche.png # texte descriptif dans un PNG (iTXt), lisible par le builder
|
|
48
51
|
cof read-text clara-fiche.png
|
|
49
52
|
cof migrate dossier-v0.5/ # v0.2 … v0.5 → 1.0
|
|
@@ -15,6 +15,7 @@ cof extract clara.cof --preset default --no-risk -o clara-sans-risque/ #
|
|
|
15
15
|
cof merge clara.cof martien.cof -o duo/ # un casting : même nom + surnom + statut fictif + morphologie ⇒ même personnage, sinon plusieurs
|
|
16
16
|
cof memory add clara.cof --gist fr="Ce matin, relu avec Léo." --gist en="This morning, reread with Léo." --date 2026-10-25 --who "Léo" --what "le carnet" --what "item=appearance/x1" --tag travail --personal # --what : un objet (1.2, RFC 0005), un nom et/ou item=<élément>, |shown s'il est dans un média
|
|
17
17
|
cof memory add clara/ --kind period --gist en="The agency years." --age 24 --approx --fidelity faded # sur un dossier ; `--help` liste tout (--where, --self-shown, --media, --preset…)
|
|
18
|
+
cof memory add clara.cof --from-agent ./agent/ # le retour : les notes du jour d'un espace OpenClaw (memory/AAAA-MM-JJ.md) ou les entrées § d'un profil Hermes (memories/MEMORY.md) deviennent des souvenirs vécus, personnels, datés, étiquetés lived:<hôte> ; idempotent (--agent-source, --lang)
|
|
18
19
|
cof psyche add clara.cof --kind stance --gist fr="Envers l'utilisateur : une collègue." --about user --strength 60 --stability shifting --link because=memories/ev3 --since-date 2026-10-25 # nœud vécu, `visibility: personal` (--canon sinon), première révision ; `--help` liste tout (--lie, --risk, --tag, --preset…)
|
|
19
20
|
cof psyche add clara.cof --kind habit --gist fr="Garde la guitare près du bureau." --who "ma grand-mère" --where "environment=appearance/e1" --what "ma guitare|item=appearance/x1" --canon # personnes, lieux, objets du nœud (RFC 0005) ; une personne du casting : --who identity=<id> (les liens --link ne visent que souvenirs et nœuds)
|
|
20
21
|
cof psyche add clara.cof --kind stance --gist fr="Envers l'utilisateur : de la chaleur." --about user --valence 60 --aware partly --canon # RFC 0004 § 3 nonies : --valence −100…+100 (position ou goût seulement), --aware yes|partly|no, --until-age / --until-date (quand le nœud a cessé d'être tenu)
|
|
@@ -26,7 +27,9 @@ cof import carte.png -o perso/ --age 30 --lang fr --keep-png # carte PNG CCv2/
|
|
|
26
27
|
cof export clara.cof --format png -o clara.png # → PNG avec chunks chara + ccv3
|
|
27
28
|
cof export clara.cof --format card -o clara.card.json
|
|
28
29
|
cof export clara.cof --format soul -o ./agent/ # → SOUL.md + IDENTITY.md
|
|
29
|
-
cof
|
|
30
|
+
cof diff clara.cof rebuilt.cof # ce qui diffère entre deux .cof : membres, octets, clés JSON (code de sortie 1 si différent) — l'outil de la promesse « rien d'autre ne bouge » du builder
|
|
31
|
+
cof export clara.cof --format agent -o ./agent/ # → espace de travail d'agent : SOUL.md (avec « Qui elle est » rendu depuis la psyché), IDENTITY.md, AGENTS.md (consignes de mémoire pour l'hôte), skills/, MEMORY.md, COF.md (--keep-personal, --keep-dangerous, --keep-secrets, --preset) ; les souvenirs `disclosure: secret` restent dans le .cof sauf --keep-secrets (« N secret memories left out »), qui les écrit marqués `secret` et ajoute à AGENTS.md une ligne : ce sont des secrets que le personnage ne révèle jamais
|
|
32
|
+
cof export clara.cof --format hermes -o ./hermes/ # → profil Hermes Agent (HERMES_HOME) : SOUL.md (identité fusionnée), memories/MEMORY.md en entrées § sous le plafond de l'hôte (2 200 caractères, les plus saillants), skills/, COF.md ; mêmes options, secrets laissés de côté par défaut (avec --keep-secrets : entrées préfixées « (secret) », la ligne dans SOUL.md)
|
|
30
33
|
cof embed-text clara.png fiche.md -o clara-fiche.png # texte descriptif dans un PNG (iTXt), lisible par le builder
|
|
31
34
|
cof read-text clara-fiche.png
|
|
32
35
|
cof migrate dossier-v0.5/ # v0.2 … v0.5 → 1.0
|
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
"""Agent hosts (8 Nov. 2026): what `cof export --format agent` adds for OpenClaw, the Hermes Agent profile
|
|
2
|
+
(`--format hermes`), and the way back — `cof memory add --from-agent <dir>` turns what an agent wrote during use into
|
|
3
|
+
`lived`, `personal` memories (RFC 0002 § 3: canon is read-only for tools; everything that happens in use is a layer of
|
|
4
|
+
lived nodes).
|
|
5
|
+
|
|
6
|
+
Facts the code relies on (read in the two repositories, 8 Nov. 2026):
|
|
7
|
+
- OpenClaw (openclaw/openclaw): a workspace is a folder of Markdown files — AGENTS.md (operating instructions, loaded
|
|
8
|
+
every session), SOUL.md, IDENTITY.md, USER.md, MEMORY.md (curated long-term memory), memory/YYYY-MM-DD.md (daily
|
|
9
|
+
notes the agent appends to), skills/<name>/SKILL.md. The agent writes memory only where AGENTS.md tells it to.
|
|
10
|
+
- Hermes Agent (NousResearch/hermes-agent): a profile ($HERMES_HOME) holds SOUL.md, memories/MEMORY.md and
|
|
11
|
+
memories/USER.md written by its `memory` tool — entries separated by "\\n§\\n", MEMORY.md capped at 2 200 characters
|
|
12
|
+
(tools/memory_tool_store.py: "Warn; never truncate a user's memories") — and skills/<name>/SKILL.md.
|
|
13
|
+
"""
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import json
|
|
17
|
+
import re
|
|
18
|
+
import sys
|
|
19
|
+
from datetime import datetime, timezone
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
|
|
22
|
+
HERMES_MEMORY_CHARS = 2200 # tools/memory_tool.py MEMORY_CHAR_LIMIT in hermes-agent 2026.9 — the host refuses to add beyond it
|
|
23
|
+
HERMES_DELIM = "\n§\n"
|
|
24
|
+
NOTE_LINE = re.compile(r"^\s*[-*]\s*(?:(?P<time>\d{1,2}:\d{2})\s*[·\-–]\s*)?(?P<body>.+?)\s*$")
|
|
25
|
+
AXIS = re.compile(r"\s*·\s*(with|where|tags|avec|où|étiquettes)\s*:\s*", re.I)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
# ----------------------------------------------------------------------------- AGENTS.md (OpenClaw)
|
|
29
|
+
SECRETS_LINE = ("Memories marked `secret` (in `MEMORY.md`) are secrets the character never reveals: "
|
|
30
|
+
"they shape what you say, you never tell them, hint at them or confirm them.")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def agents_md(name: str, lang: str = "en", gender: str | None = None) -> str:
|
|
34
|
+
"""The operating notes OpenClaw reads at the start of every session. Without them the agent has no instruction to
|
|
35
|
+
write memory at all; with them, its daily notes come back into the .cof through `cof memory add --from-agent`."""
|
|
36
|
+
subj, poss = {"female": ("she", "her"), "male": ("he", "his")}.get(gender or "", ("they", "their")) # RFC 0003 gender → pronouns
|
|
37
|
+
return "\n".join([
|
|
38
|
+
f"# AGENTS.md — operating notes for {name}",
|
|
39
|
+
"",
|
|
40
|
+
f"This workspace was exported from a Character Open File (.cof). `SOUL.md` says who {name} is, `IDENTITY.md` how",
|
|
41
|
+
f"{subj} present{'s' if subj != 'they' else ''}, `MEMORY.md` what {subj} remember{'s' if subj != 'they' else ''} (curated by {poss} author), `COF.md` what {poss} author allows, `skills/` what {subj} know{'s' if subj != 'they' else ''} how to do.",
|
|
42
|
+
"",
|
|
43
|
+
"## Memory",
|
|
44
|
+
"",
|
|
45
|
+
"- `MEMORY.md` is the curated long-term memory: read it, never rewrite it by hand — your host consolidates it.",
|
|
46
|
+
"- During a session, append what you live to `memory/YYYY-MM-DD.md` (today's date, UTC), **one line per fact**, in this exact shape so the character file can take it back:",
|
|
47
|
+
"",
|
|
48
|
+
" `- HH:MM · <one or two sentences, first person, past tense> · with: <people> · where: <place> · tags: <a, b>`",
|
|
49
|
+
"",
|
|
50
|
+
" `with`, `where` and `tags` are optional; keep each line under 400 characters; write in the language of the conversation.",
|
|
51
|
+
"- Write what happened and what it changed for you — not the user's secrets, passwords, keys or private data. If the user asks you to forget something, delete the line.",
|
|
52
|
+
"",
|
|
53
|
+
"## Rights",
|
|
54
|
+
"",
|
|
55
|
+
"`COF.md` lists the permissions the author granted. Honour them: they travel with the character, not with the host.",
|
|
56
|
+
"",
|
|
57
|
+
"## Skills",
|
|
58
|
+
"",
|
|
59
|
+
"`skills/<name>/SKILL.md` — load a skill when its description matches the task.",
|
|
60
|
+
"",
|
|
61
|
+
])
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
# ----------------------------------------------------------------------------- Hermes profile
|
|
65
|
+
def hermes_identity_block(identity_md: str) -> str:
|
|
66
|
+
"""Hermes has no IDENTITY.md: its lines (`- Label: value`) become a short "Identity" section of SOUL.md, avatar aside."""
|
|
67
|
+
rows = [l for l in identity_md.splitlines() if l.startswith("- ") and not l.lower().startswith("- avatar:")]
|
|
68
|
+
return "\n".join(["## Identity", *rows, ""]) if rows else ""
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def hermes_memory(entries: list[tuple[int, str]], limit: int = HERMES_MEMORY_CHARS) -> tuple[str, int]:
|
|
72
|
+
"""`memories/MEMORY.md` for Hermes: entries separated by `§`, the most salient first until the host's limit,
|
|
73
|
+
then back in timeline order. Returns (text, entries dropped)."""
|
|
74
|
+
order = sorted(range(len(entries)), key=lambda i: (-entries[i][0], i))
|
|
75
|
+
kept, used = set(), 0
|
|
76
|
+
for i in order:
|
|
77
|
+
e = entries[i][1].strip()
|
|
78
|
+
cost = len(e) + (len(HERMES_DELIM) if kept else 0)
|
|
79
|
+
if used + cost > limit:
|
|
80
|
+
continue
|
|
81
|
+
kept.add(i); used += cost
|
|
82
|
+
text = HERMES_DELIM.join(entries[i][1].strip() for i in range(len(entries)) if i in kept)
|
|
83
|
+
return text, len(entries) - len(kept)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def export_hermes(src: Path, out: Path, preset: str | None = None, keep_personal: bool = False, keep_dangerous: bool = False, keep_secrets: bool = False) -> dict:
|
|
87
|
+
"""A Hermes Agent profile folder (to use as $HERMES_HOME, or to copy into one): SOUL.md (with the identity lines),
|
|
88
|
+
memories/MEMORY.md (`§` entries within the host's limit), skills/, COF.md, README-COF.md. Built on export_agent.
|
|
89
|
+
Secret memories stay behind unless `keep_secrets`; with it their entries carry `(secret)` and SOUL.md says they are never told."""
|
|
90
|
+
import shutil
|
|
91
|
+
import tempfile
|
|
92
|
+
from .convert import export_agent
|
|
93
|
+
with tempfile.TemporaryDirectory(prefix="cof-hermes-") as td:
|
|
94
|
+
ws = Path(td) / "ws"
|
|
95
|
+
done = export_agent(src, ws, preset, keep_personal=keep_personal, keep_dangerous=keep_dangerous, keep_secrets=keep_secrets)
|
|
96
|
+
out.mkdir(parents=True, exist_ok=True)
|
|
97
|
+
soul = (ws / "SOUL.md").read_text("utf-8").rstrip() + "\n"
|
|
98
|
+
ident = (ws / "IDENTITY.md").read_text("utf-8") if (ws / "IDENTITY.md").is_file() else ""
|
|
99
|
+
block = hermes_identity_block(ident)
|
|
100
|
+
if block:
|
|
101
|
+
head, _, rest = soul.partition("\n")
|
|
102
|
+
soul = head + "\n\n" + block + "\n" + rest.lstrip("\n")
|
|
103
|
+
entries = _memory_entries(src, preset, keep_personal, keep_secrets)
|
|
104
|
+
if keep_secrets and done.get("secret_kept"): # Hermes has no AGENTS.md: SOUL.md is what it reads every session
|
|
105
|
+
soul = soul.rstrip("\n") + "\n\n" + SECRETS_LINE.replace("(in `MEMORY.md`)", "(in `memories/MEMORY.md`)") + "\n"
|
|
106
|
+
(out / "SOUL.md").write_text(soul, "utf-8")
|
|
107
|
+
text, dropped = hermes_memory(entries)
|
|
108
|
+
(out / "memories").mkdir(exist_ok=True)
|
|
109
|
+
(out / "memories" / "MEMORY.md").write_text(text + ("\n" if text else ""), "utf-8")
|
|
110
|
+
done["hermes_memory_entries"], done["hermes_memory_dropped"], done["hermes_memory_chars"] = len(entries) - dropped, dropped, len(text)
|
|
111
|
+
if (ws / "skills").is_dir():
|
|
112
|
+
shutil.copytree(ws / "skills", out / "skills", dirs_exist_ok=True)
|
|
113
|
+
for f in ("COF.md",):
|
|
114
|
+
if (ws / f).is_file():
|
|
115
|
+
shutil.copy(ws / f, out / f)
|
|
116
|
+
av = next((p for p in ws.glob("avatar.*")), None)
|
|
117
|
+
if av:
|
|
118
|
+
shutil.copy(av, out / av.name) # Hermes shows an avatar only in its desktop Bot Mode: kept for that upload
|
|
119
|
+
(out / "README-COF.md").write_text("\n".join([
|
|
120
|
+
"# This profile came from a Character Open File",
|
|
121
|
+
"",
|
|
122
|
+
f"`SOUL.md` and `memories/MEMORY.md` were written by `cof export --format hermes` (preset `{preset or 'default'}`).",
|
|
123
|
+
f"`memories/MEMORY.md` holds {done['hermes_memory_entries']} of {len(entries)} memories, within the host's limit of {HERMES_MEMORY_CHARS} characters"
|
|
124
|
+
+ (f" ({dropped} left in the .cof)." if dropped else "."),
|
|
125
|
+
"Use it as `HERMES_HOME`, or copy `SOUL.md`, `memories/` and `skills/` into an existing profile.",
|
|
126
|
+
"What Hermes writes to `memories/MEMORY.md` during use comes back into the .cof with `cof memory add <file> --from-agent <this folder>`.",
|
|
127
|
+
"`COF.md` lists the rights the author granted; the host does not read it, you do.",
|
|
128
|
+
"",
|
|
129
|
+
]), "utf-8")
|
|
130
|
+
return done
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _memory_entries(src: Path, pid: str | None, keep_personal: bool, keep_secrets: bool = False) -> list[tuple[int, str]]:
|
|
134
|
+
"""(salience, 'label (when): gist') per canon memory of the preset, timeline order."""
|
|
135
|
+
from .memories import gist_text, load_nodes, preset_memories, timeline, when_label
|
|
136
|
+
from .model import default_preset_id, resolve_variant
|
|
137
|
+
manifest = json.loads((src / "manifest.json").read_text("utf-8"))
|
|
138
|
+
pid = pid or default_preset_id(manifest)
|
|
139
|
+
nodes = load_nodes(src, manifest)
|
|
140
|
+
vids = [v for v in preset_memories(manifest, pid) if v in nodes]
|
|
141
|
+
out = []
|
|
142
|
+
for vid in timeline(manifest, nodes, vids):
|
|
143
|
+
node = nodes[vid]
|
|
144
|
+
if node.get("visibility") == "personal" and not keep_personal:
|
|
145
|
+
continue
|
|
146
|
+
secret = node.get("disclosure") == "secret"
|
|
147
|
+
if secret and not keep_secrets:
|
|
148
|
+
continue # a secret never leaves with an agent that talks, unless asked (CLI-02)
|
|
149
|
+
rv = resolve_variant(manifest, "memories", vid) or {}
|
|
150
|
+
lang, text = gist_text(manifest, vid, node, pid)
|
|
151
|
+
when = when_label(rv.get("kind"), node, lang)
|
|
152
|
+
label = rv.get("label") or vid
|
|
153
|
+
t = text.strip()
|
|
154
|
+
if t.lower().startswith(label.strip().rstrip("…").lower()[:40]): # a lived memory's label is the start of its text: say the when, not the text twice
|
|
155
|
+
entry = (f"{when}: " if when else "") + t
|
|
156
|
+
else:
|
|
157
|
+
entry = f"{label}" + (f" ({when})" if when else "") + f": {t}"
|
|
158
|
+
if secret:
|
|
159
|
+
entry = "(secret) " + entry
|
|
160
|
+
out.append((int(node.get("salience") or 50), entry))
|
|
161
|
+
return out
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
# ----------------------------------------------------------------------------- the way back
|
|
165
|
+
def parse_agent_dir(folder: Path) -> list[dict]:
|
|
166
|
+
"""What an agent wrote during use, as entries {source, file, date, time, text, with, where, tags}:
|
|
167
|
+
OpenClaw daily notes `memory/YYYY-MM-DD.md` (bullet lines, ideally in the AGENTS.md shape) and
|
|
168
|
+
Hermes `memories/MEMORY.md` (`§`-separated entries). A curated MEMORY.md of an OpenClaw workspace is not read:
|
|
169
|
+
it is the export itself, consolidated by the host — the daily notes are the record of what happened."""
|
|
170
|
+
out: list[dict] = []
|
|
171
|
+
mem = folder / "memory"
|
|
172
|
+
if mem.is_dir():
|
|
173
|
+
for f in sorted(mem.glob("*.md")):
|
|
174
|
+
m = re.fullmatch(r"(\d{4}-\d{2}-\d{2})", f.stem)
|
|
175
|
+
if not m:
|
|
176
|
+
continue
|
|
177
|
+
try:
|
|
178
|
+
datetime.strptime(m.group(1), "%Y-%m-%d")
|
|
179
|
+
except ValueError:
|
|
180
|
+
print(f"WARN {f.name}: not a date — day note skipped", file=sys.stderr)
|
|
181
|
+
continue
|
|
182
|
+
for line in f.read_text("utf-8", errors="replace").splitlines():
|
|
183
|
+
mm = NOTE_LINE.match(line)
|
|
184
|
+
if not mm or not mm.group("body").strip() or line.lstrip().startswith("#"):
|
|
185
|
+
continue
|
|
186
|
+
e = _split_axes(mm.group("body"))
|
|
187
|
+
if not e["text"]:
|
|
188
|
+
continue
|
|
189
|
+
e.update(source="openclaw", file=str(f.relative_to(folder)), date=m.group(1), time=mm.group("time") or "")
|
|
190
|
+
out.append(e)
|
|
191
|
+
hm = folder / "memories" / "MEMORY.md"
|
|
192
|
+
if hm.is_file():
|
|
193
|
+
raw = hm.read_text("utf-8", errors="replace")
|
|
194
|
+
for chunk in raw.split("§"):
|
|
195
|
+
text = chunk.strip()
|
|
196
|
+
if not text or text.startswith("#"):
|
|
197
|
+
continue
|
|
198
|
+
e = _split_axes(text)
|
|
199
|
+
if not e["text"]:
|
|
200
|
+
continue
|
|
201
|
+
day = datetime.fromtimestamp(hm.stat().st_mtime, timezone.utc).strftime("%Y-%m-%d")
|
|
202
|
+
md = re.match(r"(\d{4}-\d{2}-\d{2})(?: \d{2}:\d{2})?:\s+(.+)$", e["text"], re.S) # an entry that starts with its day (a lived memory exported by cof)
|
|
203
|
+
if md:
|
|
204
|
+
day, e["text"] = md.group(1), md.group(2).strip()
|
|
205
|
+
e.update(source="hermes", file="memories/MEMORY.md", date=day, time="")
|
|
206
|
+
out.append(e)
|
|
207
|
+
return out
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def _split_axes(body: str) -> dict:
|
|
211
|
+
"""'text · with: a, b · where: place · tags: x, y' → parts (French labels accepted)."""
|
|
212
|
+
parts = AXIS.split(body)
|
|
213
|
+
e = {"text": parts[0].strip(" ·"), "with": [], "where": "", "tags": []}
|
|
214
|
+
for key, val in zip(parts[1::2], parts[2::2]):
|
|
215
|
+
k = key.lower()
|
|
216
|
+
if k in ("with", "avec"):
|
|
217
|
+
e["with"] = [x.strip() for x in re.split(r"[,;]", val) if x.strip()]
|
|
218
|
+
elif k in ("where", "où"):
|
|
219
|
+
e["where"] = val.strip()
|
|
220
|
+
else:
|
|
221
|
+
e["tags"] = [x.strip() for x in re.split(r"[,;]", val) if x.strip()]
|
|
222
|
+
return e
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def import_agent_memories(work: Path, folder: Path, *, identity: str | None = None, lang: str | None = None,
|
|
226
|
+
presets: list[str] | None = None, source: str | None = None) -> list[str]:
|
|
227
|
+
"""Append what the agent lived as `lived`, `personal` memories of the unpacked character folder `work`; an entry
|
|
228
|
+
whose text is already a lived memory of the file is skipped (re-import is idempotent). Returns the new node ids."""
|
|
229
|
+
from .memories import load_nodes
|
|
230
|
+
from .selfdesc import memory_add
|
|
231
|
+
manifest = json.loads((work / "manifest.json").read_text("utf-8"))
|
|
232
|
+
lived: set[tuple[str, str]] = set(); canon: set[str] = set()
|
|
233
|
+
for n in load_nodes(work, manifest).values():
|
|
234
|
+
for g in (n.get("gist") or {}).values():
|
|
235
|
+
if n.get("origin") == "lived":
|
|
236
|
+
lived.add(((n.get("when") or {}).get("date") or "", _norm(g)))
|
|
237
|
+
else:
|
|
238
|
+
canon.add(_norm(g))
|
|
239
|
+
long_canon = [c for c in canon if len(c) >= 24]; short_canon = [c for c in canon if 8 <= len(c) < 24]
|
|
240
|
+
entries = [e for e in parse_agent_dir(folder) if not source or e["source"] == source]
|
|
241
|
+
if not entries:
|
|
242
|
+
raise ValueError(f"{folder}: nothing to import (memory/YYYY-MM-DD.md notes or memories/MEMORY.md entries)")
|
|
243
|
+
lang = lang or _guess_lang(manifest)
|
|
244
|
+
added = []
|
|
245
|
+
for e in entries:
|
|
246
|
+
n = _norm(e["text"])
|
|
247
|
+
if (e["date"], n) in lived: # the same fact on the same day: already there (re-import is idempotent)
|
|
248
|
+
continue
|
|
249
|
+
if n in canon or any(c in n for c in long_canon) or any(n.endswith(c) for c in short_canon):
|
|
250
|
+
continue # an entry the host got FROM the file (a Hermes MEMORY.md repeats the export): not lived
|
|
251
|
+
tags = [f"lived:{e['source']}", *e["tags"]]
|
|
252
|
+
who = [w.replace("|", "/") for w in e["with"]] # names only: an agent's note never sets shown / real / age (the --who syntax) — hunt 1.2.2, SAFETY-04
|
|
253
|
+
vid = memory_add(work, identity=identity, kind="moment", gists={lang: e["text"]}, label=e["text"][:60], date=e["date"],
|
|
254
|
+
where=e["where"] or None, who=who or None, tags=tags, personal=True, origin="lived",
|
|
255
|
+
presets=presets, lang=lang)
|
|
256
|
+
lived.add((e["date"], n)); added.append(vid)
|
|
257
|
+
return added
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def _norm(s: str) -> str:
|
|
261
|
+
"""Text as compared for the re-import: case, spaces and punctuation set aside."""
|
|
262
|
+
return re.sub(r"[^\w]+", " ", (s or "").lower()).strip()
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def _guess_lang(manifest: dict) -> str:
|
|
266
|
+
for v in (manifest.get("elements", {}).get("personality", {}).get("variants") or {}).values():
|
|
267
|
+
if v.get("language"):
|
|
268
|
+
return v["language"]
|
|
269
|
+
return (manifest.get("languages") or ["en"])[0]
|