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/__init__.py ADDED
@@ -0,0 +1,7 @@
1
+ """batonpass — never drop the baton.
2
+
3
+ A read-only archive of the AI history already on your machine, portable to the
4
+ one you will be on tomorrow.
5
+ """
6
+
7
+ __version__ = "0.5.0"
batonpass/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
@@ -0,0 +1,4 @@
1
+ from .runner import archive_one, run_archive
2
+ from .adapters import ADAPTERS, ArchiveResult, get
3
+
4
+ __all__ = ["archive_one", "run_archive", "ADAPTERS", "ArchiveResult", "get"]
@@ -0,0 +1,616 @@
1
+ """Source adapters.
2
+
3
+ Every adapter answers the same two questions and nothing else:
4
+
5
+ sessions(conn) -> what conversations exist?
6
+ messages(conn, sid) -> what was said in this one?
7
+
8
+ Storage, compression, idempotency and the raw layer all live in `_ingest`, so a
9
+ new source is 30 lines rather than 300.
10
+
11
+ Degradation is explicit, never silent. When a column is missing the adapter
12
+ falls back one level and records the fallback in `result.notes`:
13
+
14
+ lossless every field found, structure preserved
15
+ text-fallback text recovered, tool calls flattened into the text
16
+ skip-placeholder rows exist but carry no recoverable text; counted, not faked
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import json
22
+ import os
23
+ import sqlite3
24
+
25
+ from ..store.content import put_content, sha256_bytes, sha256_text, short, sniff_and_decode
26
+ from ..store.write import message_key, part_key, put_message, put_part, session_key, upsert_session
27
+
28
+ ADAPTER_VER = "0.2.0"
29
+
30
+
31
+ # ── small helpers ───────────────────────────────────────────────
32
+
33
+ def columns(conn, table) -> list:
34
+ try:
35
+ return [r[1] for r in conn.execute("PRAGMA table_info(%s)" % table)]
36
+ except sqlite3.Error:
37
+ return []
38
+
39
+
40
+ def tables(conn) -> set:
41
+ try:
42
+ return {r[0] for r in conn.execute("SELECT name FROM sqlite_master WHERE type='table'")}
43
+ except sqlite3.Error:
44
+ return set()
45
+
46
+
47
+ def pick(cols, *names):
48
+ for n in names:
49
+ if n in cols:
50
+ return n
51
+ return None
52
+
53
+
54
+ def rowdict(row):
55
+ return dict(row) if isinstance(row, sqlite3.Row) else dict(row or {})
56
+
57
+
58
+ def extract(obj, _depth=0):
59
+ """Pull (text, parts) out of whatever shape a message body happens to be."""
60
+ if obj is None or _depth > 6:
61
+ return "", []
62
+ if isinstance(obj, bytes):
63
+ obj, _ = sniff_and_decode(obj)
64
+ try:
65
+ obj = json.loads(obj.decode("utf-8", "replace"))
66
+ except Exception:
67
+ return obj.decode("utf-8", "replace"), []
68
+ if isinstance(obj, str):
69
+ s = obj.strip()
70
+ if s[:1] in "{[":
71
+ try:
72
+ return extract(json.loads(s), _depth + 1)
73
+ except Exception:
74
+ return obj, []
75
+ return obj, []
76
+ if isinstance(obj, list):
77
+ texts, parts = [], []
78
+ for item in obj:
79
+ t, ps = extract(item, _depth + 1)
80
+ if t:
81
+ texts.append(t)
82
+ parts.extend(ps)
83
+ return "\n".join(texts), parts
84
+ if isinstance(obj, dict):
85
+ kind = obj.get("type") or obj.get("kind") or ""
86
+ if kind in ("text", "input_text", "output_text") and isinstance(obj.get("text"), str):
87
+ return obj["text"], []
88
+ if kind in ("reasoning", "thinking"):
89
+ return "", [{"kind": "reasoning", "text": obj.get("text") or obj.get("thinking") or ""}]
90
+ if kind in ("tool", "tool_call", "tool_use", "tool-invocation"):
91
+ name = obj.get("name") or obj.get("toolName") or obj.get("tool")
92
+ args = obj.get("input") or obj.get("args") or obj.get("parameters") or {}
93
+ return "", [{"kind": "tool_call", "name": name,
94
+ "args": json.dumps(args, ensure_ascii=False, default=str)}]
95
+ if kind in ("tool_result", "tool-result", "tool_output"):
96
+ body = obj.get("output") or obj.get("result") or obj.get("content") or ""
97
+ t, ps = extract(body, _depth + 1) if not isinstance(body, str) else (body, [])
98
+ return "", ps + [{"kind": "tool_result", "text": t, "is_error": bool(obj.get("isError"))}]
99
+ texts, parts = [], []
100
+ for key in ("content", "parts", "text", "message", "body", "output", "result", "reasoning"):
101
+ if key in obj:
102
+ t, ps = extract(obj[key], _depth + 1)
103
+ if t:
104
+ texts.append(t)
105
+ parts.extend(ps)
106
+ return "\n".join(texts), parts
107
+ return str(obj), []
108
+
109
+
110
+ class ArchiveResult:
111
+ def __init__(self, adapter, path):
112
+ self.adapter = adapter
113
+ self.path = path
114
+ self.source_sha = ""
115
+ self.sessions = 0
116
+ self.messages = 0
117
+ self.parts = 0
118
+ self.raw_records = 0
119
+ self.new_rows = 0
120
+ self.bytes_in = 0
121
+ self.bytes_stored = 0
122
+ self.skipped = 0
123
+ self.bad_rows = 0
124
+ self.declared_drops = 0
125
+ self.empty_text = 0
126
+ self.errors = []
127
+ self.notes = []
128
+ self.readonly_mode = ""
129
+
130
+ def note(self, s):
131
+ if s not in self.notes:
132
+ self.notes.append(s)
133
+
134
+ def as_dict(self):
135
+ return {k: v for k, v in self.__dict__.items()}
136
+
137
+
138
+ # ── the one ingestion path ──────────────────────────────────────
139
+
140
+ def _ingest(conn_lib, result, codec, source, device, src_conn, sessions, messages,
141
+ limit=None, level=1, raw_ok=True):
142
+ seen = 0
143
+ for s in sessions:
144
+ if limit is not None and seen >= limit:
145
+ break
146
+ seen += 1
147
+ sid = session_key(source, s["source_sid"], device)
148
+ msgs = list(messages(src_conn, s["source_sid"]))
149
+ s = dict(s)
150
+ s.update(sid=sid, source=source, device=device, adapter_ver=ADAPTER_VER,
151
+ msg_count=len(msgs))
152
+ if msgs:
153
+ stamps = [m.get("ts") for m in msgs if m.get("ts")]
154
+ if stamps:
155
+ s["first_msg_at"] = min(stamps)
156
+ s["last_msg_at"] = max(stamps)
157
+ if upsert_session(conn_lib, s):
158
+ result.new_rows += 1
159
+ result.sessions += 1
160
+ if raw_ok and level >= 2:
161
+ row = json.dumps({k: v for k, v in s.items() if k != "sid"},
162
+ ensure_ascii=False, default=str).encode()
163
+ if _raw(conn_lib, result, kind="session", key=s["source_sid"],
164
+ payload=row, codec=codec):
165
+ result.new_rows += 1
166
+
167
+ for i, m in enumerate(msgs):
168
+ seq = m.get("seq")
169
+ try:
170
+ seq = int(seq)
171
+ except (TypeError, ValueError):
172
+ seq = i
173
+ mid = message_key(sid, seq)
174
+ text = m.get("text") or ""
175
+ try:
176
+ tsha = ""
177
+ if text:
178
+ tsha, was_new = put_content(conn_lib, text, codec)
179
+ if was_new:
180
+ result.bytes_stored += len(text.encode())
181
+ if put_message(conn_lib, mid, sid, seq, m.get("role") or "unknown",
182
+ tsha, _as_str(m.get("model")), _as_str(m.get("ts")),
183
+ json.dumps(m["meta"], ensure_ascii=False, default=str)
184
+ if m.get("meta") else None):
185
+ result.new_rows += 1
186
+ result.messages += 1
187
+ result.declared_drops += m.get("dropped") or 0
188
+ if not text.strip():
189
+ result.empty_text += 1
190
+ if not m.get("parts"):
191
+ result.skipped += 1
192
+ for j, p in enumerate(m.get("parts") or []):
193
+ args, res = p.get("args"), p.get("text")
194
+ asha = rsha = None
195
+ if args:
196
+ asha, _ = put_content(conn_lib, str(args), codec)
197
+ if res:
198
+ rsha, _ = put_content(conn_lib, str(res), codec)
199
+ if put_part(conn_lib, part_key(mid, j), mid, j, p.get("kind") or "text",
200
+ _as_str(p.get("name")), asha, rsha, p.get("is_error"),
201
+ _as_str(m.get("ts"))):
202
+ result.new_rows += 1
203
+ result.parts += 1
204
+ except sqlite3.Error as exc:
205
+ # One malformed row must never cost you the other 47,987.
206
+ if len(result.errors) < 8:
207
+ result.errors.append("message seq=%s: %s" % (seq, exc))
208
+ result.bad_rows += 1
209
+
210
+
211
+ def _raw(conn_lib, result, kind, key, payload: bytes, codec=None) -> bool:
212
+ from ..store.write import put_raw_record
213
+ seq = result.raw_records + 1
214
+ result.raw_records += 1
215
+ if codec is not None:
216
+ sha, was_new = put_content(conn_lib, payload, codec)
217
+ if was_new:
218
+ result.bytes_stored += len(payload)
219
+ return put_raw_record(conn_lib, result.source_sha, seq, kind, sha, codec.name)
220
+ return put_raw_record(conn_lib, result.source_sha, seq, kind, sha256_bytes(payload))
221
+
222
+
223
+ # ── zcode ───────────────────────────────────────────────────────
224
+
225
+ ZCODE_ROLE = {"user": "user", "assistant": "assistant", "system": "system", "tool": "tool"}
226
+
227
+
228
+ class ZCode:
229
+ name = "zcode"
230
+
231
+ @staticmethod
232
+ def detect(conn):
233
+ t = tables(conn)
234
+ score, why = 0.0, []
235
+ if {"session", "message"} <= t:
236
+ score += 0.4
237
+ cols = columns(conn, "message")
238
+ if {"session_id", "data", "sequence"} <= set(cols):
239
+ score += 0.45
240
+ why.append("message(session_id,data,sequence)")
241
+ if "session_entry" in t:
242
+ score += 0.1
243
+ return min(score, 0.99), why
244
+
245
+ @staticmethod
246
+ def sessions(conn):
247
+ cols = columns(conn, "session")
248
+ out = []
249
+ for r in conn.execute("SELECT * FROM session ORDER BY time_created"):
250
+ d = rowdict(r)
251
+ out.append(dict(
252
+ source_sid=str(d.get("id")),
253
+ title=d.get("title"),
254
+ cwd=d.get("directory") or d.get("path"),
255
+ created_at=_ts(d.get("time_created")),
256
+ updated_at=_ts(d.get("time_updated")),
257
+ project_key=d.get("project_id") or d.get("workspace_id"),
258
+ project_key_tier=2,
259
+ forked_from=d.get("parent_id"),
260
+ artifact_refs=None,
261
+ ))
262
+ return out
263
+
264
+ @staticmethod
265
+ def messages(conn, sid):
266
+ """zcode keeps the words in `part`, not in `message.data`.
267
+
268
+ message.data carries only routing metadata (role, model, semantics,
269
+ tool list); every character the user or model actually wrote lives in a
270
+ part row. Reading `message.data` alone yields 48k empty messages, which
271
+ is exactly the kind of silent loss this project exists to avoid.
272
+ """
273
+ by_msg, dropped = {}, {}
274
+ for p in conn.execute("SELECT * FROM part WHERE session_id=?", (sid,)):
275
+ d = rowdict(p)
276
+ try:
277
+ obj = json.loads(d["data"])
278
+ except Exception:
279
+ continue
280
+ mid_key = d["message_id"]
281
+ part = _zcode_part(obj)
282
+ if part is None:
283
+ dropped[mid_key] = dropped.get(mid_key, 0) + 1
284
+ continue
285
+ by_msg.setdefault(mid_key, []).append((int(d["sequence"] or 0), part))
286
+
287
+ sql = ("SELECT * FROM message WHERE session_id=? "
288
+ "ORDER BY CAST(sequence AS INTEGER)")
289
+ for r in conn.execute(sql, (sid,)):
290
+ d = rowdict(r)
291
+ try:
292
+ obj = json.loads(d["data"])
293
+ except Exception:
294
+ obj = {}
295
+ sem = (obj.get("semantics") or {})
296
+ kind = sem.get("kind") or ""
297
+ role = {"user_prompt": "user",
298
+ "assistant_response": "assistant",
299
+ "system_reminder": "system",
300
+ "todo_reminder": "system",
301
+ "background_notification": "system",
302
+ "timeline_event": "system",
303
+ "compact_summary": "system"}.get(kind)
304
+ if role is None:
305
+ role = ZCODE_ROLE.get(str(obj.get("role", "")).lower()) or "unknown"
306
+
307
+ parts = []
308
+ for _seq, part in sorted(by_msg.get(d["id"], []), key=lambda x: x[0]):
309
+ if part:
310
+ parts.append(part)
311
+ body = "\n".join(p["text"] for p in parts
312
+ if p.get("kind") == "text" and p.get("text"))
313
+ if not body:
314
+ summary = obj.get("summary") or {}
315
+ body = summary.get("body") or ""
316
+ yield dict(
317
+ seq=d.get("sequence") or 0, role=role, text=body,
318
+ parts=parts, dropped=dropped.get(d["id"], 0),
319
+ ts=_ts(d.get("time_created")),
320
+ model=_as_str((obj.get("modelSelection") or {}).get("model")
321
+ if isinstance(obj.get("modelSelection"), dict)
322
+ else obj.get("model")),
323
+ meta={"id": d["id"], "semantics": kind,
324
+ "hidden": sem.get("transcriptVisibility") == "hidden"},)
325
+
326
+
327
+ def _tool_of(body):
328
+ """Pull (name, args) out of a tool-call payload, keeping the raw text if
329
+ the shape is unfamiliar — an unparsed call is still worth keeping."""
330
+ try:
331
+ obj = json.loads(body)
332
+ except Exception:
333
+ return None, body
334
+ if isinstance(obj, dict):
335
+ name = obj.get("name") or obj.get("tool") or obj.get("toolName")
336
+ args = obj.get("args") or obj.get("input") or obj.get("arguments") or obj
337
+ if not isinstance(args, str):
338
+ args = json.dumps(args, ensure_ascii=False, default=str)
339
+ return name, args
340
+ return None, body
341
+
342
+
343
+ def _as_str(v):
344
+ """Sources store model/title as nested JSON often enough to matter."""
345
+ if v is None or isinstance(v, str):
346
+ return v
347
+ if isinstance(v, (int, float, bool)):
348
+ return str(v)
349
+ try:
350
+ return json.dumps(v, ensure_ascii=False, default=str)[:200]
351
+ except Exception:
352
+ return str(v)[:200]
353
+
354
+
355
+ SKIP_PART_TYPES = {"step-start", "step-finish", "snapshot", "patch"}
356
+
357
+
358
+ def _zcode_part(obj):
359
+ """Normalise one zcode part into the canonical part shape, or None."""
360
+ if not isinstance(obj, dict):
361
+ return None
362
+ t = obj.get("type") or ""
363
+ if t in SKIP_PART_TYPES:
364
+ return None
365
+ if t == "text":
366
+ return {"kind": "text", "text": obj.get("text") or ""}
367
+ if t == "reasoning":
368
+ return {"kind": "reasoning", "text": obj.get("text") or ""}
369
+ if t == "tool":
370
+ name = obj.get("toolName") or obj.get("name") or obj.get("tool")
371
+ args = obj.get("args") or obj.get("input") or obj.get("parameters")
372
+ state = obj.get("state") or {}
373
+ if isinstance(state, dict) and state.get("input") and not args:
374
+ args = state["input"]
375
+ result = obj.get("result") or obj.get("output")
376
+ if result is None and isinstance(state, dict):
377
+ result = state.get("output") or state.get("error")
378
+ if args is not None and not isinstance(args, str):
379
+ args = json.dumps(args, ensure_ascii=False, default=str)
380
+ if result is not None and not isinstance(result, str):
381
+ result = json.dumps(result, ensure_ascii=False, default=str)
382
+ is_error = bool(obj.get("isError")) or str(
383
+ (state.get("status") if isinstance(state, dict) else "") or "").lower() == "error"
384
+ return {"kind": "tool_call" if result is None else "tool_result",
385
+ "name": name, "args": args, "text": result, "is_error": is_error}
386
+ if t in ("file", "timeline", "compaction"):
387
+ label = obj.get("path") or obj.get("filename") or obj.get("title") or t
388
+ return {"kind": t, "name": label,
389
+ "text": obj.get("text") or obj.get("content") or None}
390
+ return {"kind": t or "unknown",
391
+ "text": obj.get("text") or json.dumps(obj, ensure_ascii=False)[:2000]}
392
+
393
+
394
+ def _role(blob):
395
+ try:
396
+ obj = blob if isinstance(blob, dict) else json.loads(
397
+ blob.decode() if isinstance(blob, bytes) else blob)
398
+ return ZCODE_ROLE.get(str(obj.get("role", "")).lower(), obj.get("role") or "unknown")
399
+ except Exception:
400
+ return "unknown"
401
+
402
+
403
+ def _ts(v):
404
+ if v in (None, "", 0):
405
+ return None
406
+ if isinstance(v, (int, float)):
407
+ secs = v / 1000.0 if v > 1e11 else v
408
+ try:
409
+ from datetime import datetime, timezone
410
+ return datetime.fromtimestamp(secs, timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
411
+ except Exception:
412
+ return str(v)
413
+ return str(v)
414
+
415
+
416
+ # ── billion ─────────────────────────────────────────────────────
417
+
418
+ class Billion:
419
+ name = "billion"
420
+
421
+ @staticmethod
422
+ def detect(conn):
423
+ t, score, why = tables(conn), 0.0, []
424
+ if {"sessions", "messages", "content"} <= t:
425
+ score += 0.5
426
+ why.append("sessions+messages+content")
427
+ if "content_hash" in columns(conn, "messages"):
428
+ score += 0.45
429
+ why.append("messages.content_hash")
430
+ return min(score, 0.99), why
431
+
432
+ @staticmethod
433
+ def sessions(conn):
434
+ for r in conn.execute("SELECT * FROM sessions ORDER BY created_at"):
435
+ d = rowdict(r)
436
+ yield dict(
437
+ source_sid=str(d.get("session_id")),
438
+ title=d.get("title") or d.get("label") or d.get("host_title"),
439
+ cwd=None,
440
+ created_at=_ts(d.get("created_at")),
441
+ updated_at=_ts(d.get("updated_at")),
442
+ project_key=d.get("namespace") or d.get("origin"),
443
+ project_key_tier=3,
444
+ forked_from=d.get("parent_session_id"),
445
+ artifact_refs=None,
446
+ )
447
+
448
+ @staticmethod
449
+ def messages(conn, sid):
450
+ """billion splits a turn into one row per *kind*: text, reasoning,
451
+ tool-call, tool-result. Only `text` rows are prose; routing the rest
452
+ through a text extractor silently throws away every tool argument,
453
+ which is most of what makes a transcript replayable.
454
+ """
455
+ sql = ("SELECT m.seq,m.role,m.kind,m.ts,m.content_hash,m.identity,"
456
+ " c.bytes,c.byte_len FROM messages m "
457
+ "JOIN content c ON c.hash=m.content_hash "
458
+ "WHERE m.session_id=? ORDER BY m.seq")
459
+ for r in conn.execute(sql, (sid,)):
460
+ d = rowdict(r)
461
+ kind = (d.get("kind") or "text").lower()
462
+ body = ""
463
+ if d.get("bytes"):
464
+ decoded, _how = sniff_and_decode(d["bytes"])
465
+ body = decoded.decode("utf-8", "replace") if isinstance(decoded, bytes) else str(decoded)
466
+
467
+ text, parts = body, []
468
+ if kind == "reasoning":
469
+ text, parts = "", [{"kind": "reasoning", "text": body}]
470
+ elif kind in ("tool-call", "tool_call"):
471
+ name, args = _tool_of(body)
472
+ text, parts = "", [{"kind": "tool_call", "name": name, "args": args}]
473
+ elif kind in ("tool-result", "tool_result"):
474
+ text, parts = "", [{"kind": "tool_result", "text": body,
475
+ "is_error": body.lstrip()[:1] == "{" and
476
+ '"error"' in body[:400]}]
477
+ yield dict(seq=d.get("seq") or 0, role=d.get("role") or "unknown",
478
+ text=text, parts=parts, ts=_ts(d.get("ts")),
479
+ model=None,
480
+ meta={"kind": d.get("kind"), "identity": d.get("identity")})
481
+
482
+
483
+ # ── dsh ─────────────────────────────────────────────────────────
484
+
485
+ class Dsh:
486
+ name = "dsh-chat"
487
+
488
+ @staticmethod
489
+ def detect(conn):
490
+ cols = columns(conn, "messages")
491
+ if {"text", "who", "session"} <= set(cols):
492
+ return 0.95, ["messages(text,who,session)"]
493
+ return 0.0, []
494
+
495
+ @staticmethod
496
+ def sessions(conn):
497
+ t = tables(conn)
498
+ if "sessions" in t:
499
+ cols = columns(conn, "sessions")
500
+ idc = pick(cols, "id", "session", "session_id")
501
+ if idc:
502
+ for r in conn.execute("SELECT * FROM sessions"):
503
+ d = rowdict(r)
504
+ yield dict(source_sid=str(d.get(idc)),
505
+ title=d.get(pick(cols, "title", "name") or "title"),
506
+ cwd=None, created_at=_ts(d.get(pick(cols, "started_at", "created_at", "time"))),
507
+ updated_at=None, project_key=None, project_key_tier=3,
508
+ forked_from=None, artifact_refs=None)
509
+ return
510
+ for r in conn.execute("SELECT session, min(time), max(time), count(*) FROM messages "
511
+ "GROUP BY session ORDER BY min(time)"):
512
+ yield dict(source_sid=str(r[0]), title=None, cwd=None,
513
+ created_at=_ts(r[1]), updated_at=_ts(r[2]),
514
+ project_key=None, project_key_tier=3,
515
+ forked_from=None, artifact_refs=None)
516
+
517
+ @staticmethod
518
+ def messages(conn, sid):
519
+ for r in conn.execute("SELECT * FROM messages WHERE session=? ORDER BY seq", (sid,)):
520
+ d = rowdict(r)
521
+ yield dict(seq=d.get("seq") or d.get("id") or 0,
522
+ role=_role_from_who(d.get("who")), text=d.get("text") or "",
523
+ parts=[], ts=_ts(d.get("time")), model=None,
524
+ meta={"who": d.get("who")})
525
+
526
+
527
+ def _role_from_who(who):
528
+ w = str(who or "").lower()
529
+ if w in ("user", "human"): return "user"
530
+ if w in ("assistant", "bot", "ai", "agent"): return "assistant"
531
+ if w in ("tool", "system"): return w
532
+ return "unknown"
533
+
534
+
535
+ # ── alma ────────────────────────────────────────────────────────
536
+
537
+ class Alma:
538
+ name = "alma"
539
+
540
+ @staticmethod
541
+ def detect(conn):
542
+ t = tables(conn)
543
+ if "chat_threads" in t and "chat_messages" in t:
544
+ return 0.97, ["chat_threads+chat_messages"]
545
+ return 0.0, []
546
+
547
+ @staticmethod
548
+ def sessions(conn):
549
+ for r in conn.execute("SELECT * FROM chat_threads ORDER BY created_at"):
550
+ d = rowdict(r)
551
+ yield dict(source_sid=str(d.get("id")), title=d.get("title"), cwd=None,
552
+ created_at=_ts(d.get("created_at")), updated_at=_ts(d.get("updated_at")),
553
+ project_key=d.get("workspace_id"), project_key_tier=2,
554
+ forked_from=d.get("parent_thread_id"), artifact_refs=None)
555
+
556
+ @staticmethod
557
+ def messages(conn, sid):
558
+ for r in conn.execute("SELECT * FROM chat_messages WHERE thread_id=? "
559
+ "ORDER BY created_at, id", (sid,)):
560
+ d = rowdict(r)
561
+ text, parts = extract(d.get("message"))
562
+ yield dict(seq=d.get("id") or 0, role=_role(d.get("message")), text=text,
563
+ parts=parts, ts=_ts(d.get("created_at") or d.get("timestamp")),
564
+ model=None, meta={"depth": d.get("depth")})
565
+
566
+
567
+ # ── pinky ───────────────────────────────────────────────────────
568
+
569
+ class Pinky:
570
+ name = "pinky"
571
+
572
+ @staticmethod
573
+ def detect(conn):
574
+ t = tables(conn)
575
+ if {"tasks", "steps"} <= t:
576
+ return 0.9, ["tasks+steps"]
577
+ return 0.0, []
578
+
579
+ @staticmethod
580
+ def sessions(conn):
581
+ cols = columns(conn, "sessions")
582
+ title = pick(cols, "agent", "id")
583
+ for r in conn.execute("SELECT * FROM sessions ORDER BY started_at"):
584
+ d = rowdict(r)
585
+ yield dict(source_sid=str(d.get("id")), title=d.get(title) or "pinky session",
586
+ cwd=None, created_at=_ts(d.get("started_at")),
587
+ updated_at=_ts(d.get("ended_at")),
588
+ project_key=d.get("agent"), project_key_tier=3,
589
+ forked_from=None, artifact_refs=None)
590
+
591
+ @staticmethod
592
+ def messages(conn, sid):
593
+ for r in conn.execute("SELECT * FROM tasks WHERE session_id=? ORDER BY started_at", (sid,)):
594
+ d = rowdict(r)
595
+ text = "\n".join(x for x in (d.get("title"), d.get("summary"), d.get("outcome")) if x)
596
+ parts = []
597
+ for s in conn.execute("SELECT * FROM steps WHERE task_id=? ORDER BY idx", (d.get("id"),)):
598
+ sd = rowdict(s)
599
+ parts.append({"kind": "step", "name": sd.get("tool"),
600
+ "args": sd.get("args"),
601
+ "text": sd.get("intent") or sd.get("text"),
602
+ "is_error": (sd.get("status") or "") not in ("ok", "done", "success", "")})
603
+ yield dict(seq=d.get("id") or 0, role="assistant", text=text, parts=parts,
604
+ ts=_ts(d.get("started_at")), model=d.get("agent"),
605
+ meta={"state": d.get("state"), "device": d.get("device_name")})
606
+
607
+
608
+ ADAPTERS = {a.name: a for a in (ZCode, Billion, Dsh, Alma, Pinky)}
609
+ # the scanner's names are the ones that matter; these are the obvious aliases
610
+ ADAPTERS["dsh"] = Dsh
611
+
612
+
613
+ def get(name):
614
+ if name not in ADAPTERS:
615
+ raise KeyError("unknown adapter %r; have %s" % (name, ", ".join(sorted(ADAPTERS))))
616
+ return ADAPTERS[name]