batonpass-cli 0.5.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.
batonpass/sync/pull.py ADDED
@@ -0,0 +1,186 @@
1
+ """Read other machines' streams into this library.
2
+
3
+ Everything here is a tail read of an append-only file, resumable by byte
4
+ offset. Re-reading is always safe: every insert is INSERT OR IGNORE and every
5
+ blob is addressed by its plaintext hash, so the same line imported twice
6
+ leaves exactly the rows the first import left.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import os
12
+
13
+ from ..store.content import Codec, get_dict, put_content
14
+ from ..store.write import message_key, part_key, put_message, put_part, upsert_session
15
+ from . import channel as ch
16
+ from . import wire
17
+
18
+
19
+ def _sync_get(conn, channel, key, default=None):
20
+ row = conn.execute(
21
+ "SELECT value FROM sync_state WHERE channel=? AND key=?", (channel, key)
22
+ ).fetchone()
23
+ return row[0] if row else default
24
+
25
+
26
+ def _sync_put(conn, channel, key, value):
27
+ conn.execute(
28
+ "INSERT INTO sync_state(channel,key,value) VALUES(?,?,?)"
29
+ " ON CONFLICT(channel,key) DO UPDATE SET value=excluded.value",
30
+ (channel, key, str(value)),
31
+ )
32
+
33
+
34
+ def _session_row(o) -> dict:
35
+ return {
36
+ "sid": o.get("sid"), "source": o.get("src"), "source_sid": o.get("csid"),
37
+ "device": o.get("dev"), "project_key": o.get("pk"),
38
+ "project_key_tier": o.get("pkt"), "cwd": o.get("cwd"),
39
+ "title": o.get("title"), "created_at": o.get("c0"),
40
+ "updated_at": o.get("u0"), "msg_count": o.get("n") or 0,
41
+ "first_msg_at": o.get("f0"), "last_msg_at": o.get("l0"),
42
+ "forked_from": o.get("parent"), "adapter_ver": o.get("av"),
43
+ "content_hash": o.get("ch"),
44
+ }
45
+
46
+
47
+ def _put_head(conn, o):
48
+ conn.execute(
49
+ "INSERT INTO session_head(sid,device,one_line,head_json,msg_total,updated_at)"
50
+ " VALUES(?,?,?,?,?,datetime('now'))"
51
+ " ON CONFLICT(sid) DO UPDATE SET one_line=excluded.one_line,"
52
+ " head_json=excluded.head_json, msg_total=excluded.msg_total,"
53
+ " updated_at=excluded.updated_at",
54
+ (o.get("sid"), o.get("dev"), o.get("one"), wire.pack({"head": o.get("head")}),
55
+ int(o.get("n") or 0)),
56
+ )
57
+ # A card is only as good as the files it can name, and those arrive with the
58
+ # summary rather than with the bodies — so a tier-1 pull still knows what you
59
+ # produced, even on a machine that has none of the messages yet.
60
+ refs = o.get("refs") or []
61
+ if refs:
62
+ from ..identity.artifacts import merge_refs
63
+
64
+ cur = conn.execute("SELECT artifact_refs FROM session WHERE sid=?",
65
+ (o.get("sid"),)).fetchone()
66
+ merged = merge_refs(cur[0] if cur else "", refs)
67
+ conn.execute("UPDATE session SET artifact_refs=? WHERE sid=?",
68
+ (merged, o.get("sid")))
69
+
70
+
71
+ def _import_blob(conn, channel, sha, codecs, source, stat):
72
+ """Turn a channel blob into a local content row, keeping the same sha."""
73
+ if not sha:
74
+ return True
75
+ if conn.execute("SELECT 1 FROM content WHERE sha256=?", (sha,)).fetchone():
76
+ return True
77
+ data = wire.get_blob(channel, sha)
78
+ if data is None:
79
+ stat["missing"].append(sha)
80
+ return False
81
+ got, _ = put_content(conn, data, codecs.get(source))
82
+ if got != sha:
83
+ stat["missing"].append("%s!=%s" % (sha[:8], got[:8]))
84
+ return False
85
+ stat["blobs_new"] += 1
86
+ return True
87
+
88
+
89
+ def _device_dirs(channel):
90
+ out = []
91
+ sdir = os.path.join(channel, "stream")
92
+ if not os.path.isdir(sdir):
93
+ return out
94
+ for name in sorted(os.listdir(sdir)):
95
+ if os.path.isdir(os.path.join(sdir, name)):
96
+ out.append(name)
97
+ return out
98
+
99
+
100
+ def pull(channel: str, tier: int = 0, device: str = None, conn=None,
101
+ sid_prefix: str = None) -> dict:
102
+ channel = os.path.abspath(os.path.expanduser(channel))
103
+ me = device or ch.device_name()
104
+ if not ch.is_channel(channel):
105
+ raise SystemExit("no batonpass channel at %s" % channel)
106
+ # Pull never writes into the channel: reading other machines' history
107
+ # should not be able to change it.
108
+ ckey = ch.identity(channel) or channel
109
+ codecs = _Codecs(conn)
110
+ stat = {"channel": channel, "channel_id": ckey, "device": me, "tier": tier, "devices": [],
111
+ "sessions_new": 0, "sessions_seen": 0, "heads": 0, "messages_new": 0,
112
+ "parts_new": 0, "blobs_new": 0, "bad_lines": 0, "missing": [],
113
+ "sources": {}}
114
+
115
+ # A filtered pull is a one-off deep read of a specific task: don't advance
116
+ # any offset, so unfiltered rows are never skipped by accident.
117
+ advance = not sid_prefix
118
+
119
+ for dev in _device_dirs(channel):
120
+ stat["devices"].append(dev)
121
+ for t in range(0, tier + 1):
122
+ tier_name = "t%d" % t
123
+ # The offset belongs to a *generation* of the file, not to the file.
124
+ # A compacted stream (gen+1) therefore looks brand new and is read
125
+ # from zero — which is safe, because every import is idempotent.
126
+ gen = int(ch.read_head(channel, dev, tier_name).get("gen") or 0)
127
+ key = "pull:%s:%s:g%d" % (dev, tier_name, gen)
128
+ offset = 0 if not advance else int(_sync_get(conn, ckey, key, 0) or 0)
129
+ rows, new_offset, bad = wire.read_since(channel, dev, tier_name, offset)
130
+ if advance and int(ch.read_head(channel, dev, tier_name).get("gen") or 0) != gen:
131
+ gen = int(ch.read_head(channel, dev, tier_name).get("gen") or 0)
132
+ key = "pull:%s:%s:g%d" % (dev, tier_name, gen)
133
+ rows, new_offset, bad = wire.read_since(channel, dev, tier_name, 0)
134
+ stat["gen_changed"] = stat.get("gen_changed", 0) + 1
135
+ stat["bad_lines"] += bad
136
+ for o in rows:
137
+ sid = o.get("sid")
138
+ if sid_prefix and not (sid or "").startswith(sid_prefix):
139
+ continue
140
+ if o.get("t") == 0:
141
+ stat["sessions_seen"] += 1
142
+ if upsert_session(conn, _session_row(o)):
143
+ stat["sessions_new"] += 1
144
+ elif o.get("t") == 1:
145
+ _put_head(conn, o)
146
+ stat["heads"] += 1
147
+ elif o.get("t") == 2:
148
+ _apply_t2(conn, channel, codecs, o, stat)
149
+ if advance and new_offset != offset:
150
+ _sync_put(conn, ckey, key, new_offset)
151
+ conn.commit()
152
+ return stat
153
+
154
+
155
+ class _Codecs:
156
+ def __init__(self, conn):
157
+ self.conn, self._cache = conn, {}
158
+
159
+ def get(self, source):
160
+ source = source or ""
161
+ if source not in self._cache:
162
+ self._cache[source] = Codec(get_dict(self.conn, source))
163
+ return self._cache[source]
164
+
165
+
166
+ def _apply_t2(conn, channel, codecs, o, stat):
167
+ source = _source_of(conn, o.get("sid"))
168
+ if o.get("k") == "m":
169
+ sid, seq = o.get("sid"), int(o.get("seq") or 0)
170
+ _import_blob(conn, channel, o.get("th"), codecs, source, stat)
171
+ if put_message(conn, message_key(sid, seq), sid, seq, o.get("r"),
172
+ o.get("th"), o.get("mo"), o.get("ts"), o.get("mj")):
173
+ stat["messages_new"] += 1
174
+ stat["sources"][source] = stat["sources"].get(source, 0) + 1
175
+ elif o.get("k") == "p":
176
+ mid, seq = o.get("mid"), int(o.get("seq") or 0)
177
+ _import_blob(conn, channel, o.get("ah"), codecs, source, stat)
178
+ _import_blob(conn, channel, o.get("rh"), codecs, source, stat)
179
+ if put_part(conn, part_key(mid, seq), mid, seq, o.get("pk"), o.get("nm"),
180
+ o.get("ah"), o.get("rh"), o.get("e"), o.get("ts")):
181
+ stat["parts_new"] += 1
182
+
183
+
184
+ def _source_of(conn, sid) -> str:
185
+ row = conn.execute("SELECT source FROM session WHERE sid=?", (sid,)).fetchone()
186
+ return row[0] if row else ""
batonpass/sync/push.py ADDED
@@ -0,0 +1,276 @@
1
+ """Write this machine's view of the world into a channel.
2
+
3
+ Tiers, because 2.2 GB of chat history is not what you need in order to
4
+ remember that you were in the middle of something:
5
+
6
+ t0 catalog ~140 KB one line per session: where, when, how big
7
+ t1 summary ~2 MB the first ask and the last few rounds, as prose
8
+ t2 messages ~27 MB every message and tool call, bodies as blobs
9
+
10
+ t0+t1 is what makes a brand-new machine useful in a second or two. t2 is only
11
+ pulled when you actually continue the work.
12
+
13
+ A session is re-sent when its message count changed, so a session that grew
14
+ after the last push is not silently frozen at its old size. A session that
15
+ raised is *not* marked as sent, so the next push retries it.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import json
21
+ import os
22
+
23
+ from .. import __version__
24
+ from ..store.content import Codec, get_content, get_dict
25
+ from ..store.text import clean
26
+ from ..store.write import message_key, part_key
27
+ from . import channel as ch
28
+ from . import wire
29
+
30
+ SUMMARY_VER = 3
31
+ MAX_T1_REFS = 12 # 24 is the cap the identity layer keeps; a card shows five
32
+ HEAD_PER_ROLE = 3
33
+ HEAD_CHARS = 600
34
+ ONE_LINE_CHARS = 160
35
+
36
+
37
+ def _sync_get(conn, channel, key, default=None):
38
+ row = conn.execute(
39
+ "SELECT value FROM sync_state WHERE channel=? AND key=?", (channel, key)
40
+ ).fetchone()
41
+ return row[0] if row else default
42
+
43
+
44
+ def _sync_put(conn, channel, key, value):
45
+ conn.execute(
46
+ "INSERT INTO sync_state(channel,key,value) VALUES(?,?,?)"
47
+ " ON CONFLICT(channel,key) DO UPDATE SET value=excluded.value",
48
+ (channel, key, str(value)),
49
+ )
50
+
51
+
52
+ def _counts(conn, sid) -> tuple:
53
+ row = conn.execute(
54
+ "SELECT COUNT(*), COALESCE(MAX(seq),0) FROM message WHERE sid=?", (sid,)
55
+ ).fetchone()
56
+ return int(row[0] or 0), int(row[1] or 0)
57
+
58
+
59
+ class _Codecs:
60
+ """One compressor per source, because each source has its own dictionary."""
61
+
62
+ def __init__(self, conn):
63
+ self.conn = conn
64
+ self._cache = {}
65
+
66
+ def get(self, source):
67
+ source = source or ""
68
+ if source not in self._cache:
69
+ self._cache[source] = Codec(get_dict(self.conn, source))
70
+ return self._cache[source]
71
+
72
+ def text(self, source, sha):
73
+ return get_content(self.conn, sha, self.get(source))
74
+
75
+
76
+ def _t0(row) -> dict:
77
+ return {
78
+ "v": wire.WIRE_VERSION, "t": 0,
79
+ "sid": row["sid"], "src": row["source"], "csid": row["source_sid"],
80
+ "dev": row["device"], "pk": row["project_key"], "pkt": row["project_key_tier"],
81
+ "cwd": row["cwd"], "title": row["title"],
82
+ "c0": row["created_at"], "u0": row["updated_at"],
83
+ "n": row["msg_count"], "f0": row["first_msg_at"], "l0": row["last_msg_at"],
84
+ "parent": row["forked_from"], "av": row["adapter_ver"],
85
+ "ch": row["content_hash"],
86
+ }
87
+
88
+
89
+ def _t1_refs(row) -> list:
90
+ """The files a session produced, small enough to ride along with its summary.
91
+
92
+ A handover card without its files is a card about a task rather than the task:
93
+ you arrive on the new machine, the card says what you were doing, and then it
94
+ cannot tell you which document you were writing. The refs live in the session
95
+ row, so they cost nothing extra to send — just bytes on the wire.
96
+ """
97
+ raw = row["artifact_refs"]
98
+ if not raw:
99
+ return []
100
+ try:
101
+ refs = json.loads(raw)
102
+ except (ValueError, TypeError):
103
+ return []
104
+ keep = ("name", "ts", "via") # rank() only needs the name; `via` says how we know
105
+ return [{k: r[k] for k in keep if k in r}
106
+ for r in refs[:MAX_T1_REFS] if isinstance(r, dict) and r.get("name")]
107
+
108
+
109
+ def _head_prose(conn, codecs, sid, source) -> tuple:
110
+ """First ask + last few rounds. Cheap, local, no model involved.
111
+
112
+ This is what turns "I think I was doing something like X" into "it was on
113
+ the mini, in this session, and the last thing you asked was Y".
114
+ """
115
+ rows = conn.execute(
116
+ "SELECT seq, role, text_sha FROM message WHERE sid=? ORDER BY seq", (sid,)
117
+ ).fetchall()
118
+ if not rows:
119
+ return "", []
120
+ first_user = next((r for r in rows if (r[1] or "") == "user"), None)
121
+ pick = [first_user] if first_user else []
122
+ for role in ("user", "assistant"):
123
+ for r in [x for x in rows if (x[1] or "") == role][-HEAD_PER_ROLE:]:
124
+ if r not in pick:
125
+ pick.append(r)
126
+ out = []
127
+ for r in pick:
128
+ shas = [r[2]] if r[2] else []
129
+ for a, b in conn.execute(
130
+ "SELECT args_sha, result_sha FROM part WHERE mid=? ORDER BY seq",
131
+ (message_key(sid, r[0]),),
132
+ ):
133
+ shas.extend([a, b])
134
+ text = "\n".join(t for t in (clean(codecs.text(source, s)) for s in shas if s) if t)
135
+ if text.strip():
136
+ out.append([r[0], r[1] or "", text[:HEAD_CHARS]])
137
+ one_line = out[0][2].splitlines()[0][:ONE_LINE_CHARS] if out else ""
138
+ return one_line, out
139
+
140
+
141
+ def push(channel: str, tier: int = 1, device: str = None, conn=None,
142
+ sid_prefix: str = None) -> dict:
143
+ channel = os.path.abspath(os.path.expanduser(channel))
144
+ device = device or ch.device_name()
145
+ ch.init_channel(channel, device)
146
+ ckey = ch.identity(channel) or channel # watermarks follow the channel, not its path
147
+ codecs = _Codecs(conn)
148
+ stat = {"channel": channel, "channel_id": ckey, "device": device, "tier": tier,
149
+ "sessions": 0, "sessions_sent": 0, "lines": {0: 0, 1: 0, 2: 0},
150
+ "blobs_new": 0, "blob_bytes": 0, "messages": 0, "parts": 0,
151
+ "skipped": 0, "errors": []}
152
+
153
+ q, args = "SELECT rowid,* FROM session", ()
154
+ if sid_prefix:
155
+ q += " WHERE sid LIKE ?"
156
+ args = (sid_prefix + "%",)
157
+ rows = conn.execute(q + " ORDER BY rowid", args).fetchall()
158
+ stat["sessions"] = len(rows)
159
+
160
+ t0_buf, t1_buf, t2_buf = [], [], []
161
+ sent = {}
162
+ for row in rows:
163
+ sid, source = row["sid"], row["source"]
164
+ n_msg, max_seq = _counts(conn, sid)
165
+ sig = "%d:%d:%d" % (n_msg, max_seq, SUMMARY_VER)
166
+ last_tier = int(_sync_get(conn, ckey, "sent_tier:" + sid, 0) or 0)
167
+ # Two separate questions. Metadata goes stale when the session grows or
168
+ # the summariser improves; bodies are missing until they have been sent
169
+ # at the tier you are asking for now. Asking for tier 2 after a tier-1
170
+ # push must still send the messages, and must not re-send 713 summaries.
171
+ need_meta = _sync_get(conn, ckey, "sent:" + sid) != sig
172
+ need_bodies = tier >= 2 and last_tier < tier
173
+ if not need_meta and not need_bodies:
174
+ stat["skipped"] += 1
175
+ continue
176
+ try:
177
+ stat["sessions_sent"] += 1
178
+ if need_meta:
179
+ t0_buf.append(wire.pack(_t0(row)))
180
+
181
+ if need_meta and tier >= 1:
182
+ # The summary carries its text inline. Sending it as blobs too
183
+ # would mean thousands of 700-byte files, and a filesystem
184
+ # charges a 4 KB block for each of them.
185
+ one_line, head = _head_prose(conn, codecs, sid, source)
186
+ line = {"v": wire.WIRE_VERSION, "t": 1, "sid": sid, "one": one_line,
187
+ "head": head, "n": n_msg}
188
+ refs = _t1_refs(row)
189
+ if refs:
190
+ line["refs"] = refs
191
+ t1_buf.append(wire.pack(line))
192
+
193
+ if need_bodies:
194
+ stat["messages"] += _push_messages(
195
+ conn, ckey, channel, codecs, sid, source, t2_buf, stat)
196
+ sent[sid] = [sig, tier, max_seq]
197
+ except Exception as exc: # one bad session must not sink the push
198
+ stat["errors"].append("%s: %s" % (sid, exc))
199
+
200
+ for t, buf in ((0, t0_buf), (1, t1_buf), (2, t2_buf)):
201
+ if not buf:
202
+ continue
203
+ name = "t%d" % t
204
+ wire.append_lines(channel, device, name, buf)
205
+ stat["lines"][t] = len(buf)
206
+ ch.write_head(channel, device, name, {"lines": len(buf)})
207
+ comp = ch.compact(channel, device, name)
208
+ if comp.get("compacted"):
209
+ stat.setdefault("compacted", {})[name] = comp
210
+
211
+ # Mark what we sent only after the bytes are on disk, and never a session
212
+ # that raised — otherwise it would never be retried.
213
+ for sid, (sig, sent_tier, max_seq) in sent.items():
214
+ if _sync_get(conn, ckey, "sent:" + sid) != sig:
215
+ _sync_put(conn, ckey, "sent:" + sid, sig)
216
+ if sent_tier > int(_sync_get(conn, ckey, "sent_tier:" + sid, 0) or 0):
217
+ _sync_put(conn, ckey, "sent_tier:" + sid, sent_tier)
218
+ if sent_tier >= 2:
219
+ _sync_put(conn, ckey, "sent2:" + sid, max_seq)
220
+ conn.commit()
221
+
222
+ ch.heartbeat(channel, device, {"version": __version__,
223
+ "counts": {"sessions": stat["sessions"]}})
224
+ return stat
225
+
226
+
227
+ def _push_messages(conn, ckey, channel, codecs, sid, source, buf, stat) -> int:
228
+ """Append messages and parts after the last seq this channel already has.
229
+
230
+ Per-session seq watermark, so a session that gained three messages costs
231
+ three messages, not the whole conversation again.
232
+ """
233
+ # -1, not 0: seq 0 is the first message of every session, and a zero
234
+ # watermark would silently drop it from every push forever.
235
+ seen = _sync_get(conn, ckey, "sent2:" + sid)
236
+ already = -1 if seen is None else int(seen)
237
+ n = 0
238
+ rows = conn.execute(
239
+ "SELECT seq,role,text_sha,model,ts,meta_json FROM message"
240
+ " WHERE sid=? AND seq>? ORDER BY seq", (sid, already)
241
+ ).fetchall()
242
+ for m in rows:
243
+ buf.append(wire.pack({
244
+ "v": wire.WIRE_VERSION, "t": 2, "k": "m", "sid": sid, "seq": m[0],
245
+ "r": m[1], "th": m[2], "mo": m[3], "ts": m[4], "mj": m[5],
246
+ }))
247
+ n += 1
248
+ _ship_blob(channel, codecs, source, m[2], stat)
249
+ mid = message_key(sid, m[0])
250
+ for p in conn.execute(
251
+ "SELECT seq,kind,name,args_sha,result_sha,is_error,ts FROM part"
252
+ " WHERE mid=? ORDER BY seq", (mid,)
253
+ ):
254
+ buf.append(wire.pack({
255
+ "v": wire.WIRE_VERSION, "t": 2, "k": "p", "mid": mid, "sid": sid,
256
+ "seq": p[0], "pk": p[1], "nm": p[2], "ah": p[3], "rh": p[4],
257
+ "e": p[5], "ts": p[6],
258
+ }))
259
+ stat["parts"] += 1
260
+ _ship_blob(channel, codecs, source, p[3], stat)
261
+ _ship_blob(channel, codecs, source, p[4], stat)
262
+ return n
263
+
264
+
265
+ def _ship_blob(channel, codecs, source, sha, stat):
266
+ if not sha or wire.has_blob(channel, sha):
267
+ return
268
+ try:
269
+ text = codecs.text(source, sha)
270
+ except Exception:
271
+ return
272
+ if not text:
273
+ return
274
+ _, wrote, is_new = wire.put_blob(channel, text)
275
+ stat["blob_bytes"] += wrote
276
+ stat["blobs_new"] += 1 if is_new else 0
@@ -0,0 +1,56 @@
1
+ """What is in the channel, and how much of it this machine has read.
2
+
3
+ Deliberately answers the human question first — "who else is in here, and when
4
+ did they last show up" — before any row counts.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import os
11
+
12
+ from . import channel as ch
13
+ from . import wire
14
+
15
+
16
+ def _offsets(conn, ckey):
17
+ out = {}
18
+ for name, value in conn.execute(
19
+ "SELECT key,value FROM sync_state WHERE channel=? AND key LIKE 'pull:%'", (ckey,)
20
+ ):
21
+ out[name] = int(value or 0)
22
+ return out
23
+
24
+
25
+ def status(channel: str, conn=None) -> dict:
26
+ channel = os.path.abspath(os.path.expanduser(channel))
27
+ devices = ch.devices(channel)
28
+ heads = ch.read_heads(channel)
29
+ ckey = ch.identity(channel) or channel
30
+ offsets = _offsets(conn, ckey) if conn is not None else {}
31
+ streams = []
32
+ sdir = os.path.join(channel, "stream")
33
+ if os.path.isdir(sdir):
34
+ for dev in sorted(os.listdir(sdir)):
35
+ d = os.path.join(sdir, dev)
36
+ if not os.path.isdir(d):
37
+ continue
38
+ for name in sorted(os.listdir(d)):
39
+ if not name.endswith(".jsonl"):
40
+ continue
41
+ path = os.path.join(d, name)
42
+ tier = name[:-6]
43
+ gen = int(ch.read_head(channel, dev, tier).get("gen") or 0)
44
+ # A compacted stream is a new generation: what we read before
45
+ # the rewrite says nothing about what is in the file now.
46
+ key = "pull:%s:%s:g%d" % (dev, tier, gen)
47
+ size = os.path.getsize(path)
48
+ done = offsets.get(key)
49
+ streams.append({
50
+ "device": dev, "tier": tier, "bytes": size, "gen": gen,
51
+ "read": done, "pending": (size - done) if done is not None else size,
52
+ })
53
+ return {"channel": channel, "channel_id": ckey if ch.is_channel(channel) else None,
54
+ "exists": ch.is_channel(channel),
55
+ "devices": devices, "heads": heads, "streams": streams,
56
+ "offsets": offsets}