pi-backbeat 0.1.0

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 AuthurX
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,112 @@
1
+ # Backbeat
2
+
3
+ **The rhythm section for your day.** A local-first AI scheduler for Apple Calendar, powered by [Pi](https://pi.dev). An open-source alternative to Motion / Reclaim.ai — your data never leaves your machine.
4
+
5
+ It auto-blocks your day at 08:00, reshuffles on conflict via natural chat, and rolls unfinished tasks into tomorrow at 21:30.
6
+
7
+ ## How it works
8
+
9
+ ```
10
+ you: "加待办:写周报 周五前 2h 高优先级"
11
+ │
12
+ ▼
13
+ ~/.assistant/tasks.md ← todo pool (single source of truth)
14
+ │
15
+ 08:00 systemd timer ──► headless pi -p ──► reads pool + your calendar
16
+ │ (anchors = existing events)
17
+ ▼
18
+ Apple Calendar "Backbeat" calendar (iCloud CalDAV, native alarms)
19
+ │
20
+ ▼
21
+ iPhone / Mac: native notifications, all day
22
+ ```
23
+
24
+ - **Anchors first** — existing events are never touched; tasks fill free slots only
25
+ - **Big Rocks First** — top-priority task gets the best morning block
26
+ - **Buffers, not gap-filling** — 15 min after meetings, gaps intentionally left
27
+ - **Re-plan on conflict** — new meeting? remaining AI blocks reshuffle (`/replan`)
28
+ - **Reminders are calendar events** — "remind me in 10 min" = an event with a native alarm
29
+ - **Evening rollover** — unfinished tasks stay in the pool, auto-planned tomorrow
30
+ - **Learns from you** — fixed blocks ("lunch 12–14") are hard-excluded from free slots; behavioral patterns (you keep moving things to the morning) are distilled at the 21:30 review into `~/.assistant/preferences.md`, shown in the notification, editable at any time. The more you use it, the more it fits you.
31
+
32
+ ## Install
33
+
34
+ Prerequisites:
35
+ - [Pi](https://pi.dev)
36
+ - An iCloud **app-specific password**, stored in `~/.assistant/.env` (chmod 600):
37
+ ```
38
+ ICLOUD_USER=you@icloud.com
39
+ ICLOUD_PASSWORD=xxxx xxxx xxxx
40
+ ```
41
+ - A Python venv with `caldav` at `~/.assistant/venv`:
42
+ ```bash
43
+ python3 -m venv ~/.assistant/venv
44
+ ~/.assistant/venv/bin/pip install caldav
45
+ ```
46
+
47
+ ```bash
48
+ pi install pi-backbeat # from npm
49
+ # or: pi install /path/to/pi-backbeat
50
+ ```
51
+
52
+ Daily automation (08:00 plan / 21:30 review, headless pi + desktop notifications):
53
+
54
+ ```bash
55
+ bin/install-timers.sh # installs systemd user timers with your paths
56
+ ```
57
+
58
+ ## Usage
59
+
60
+ | You say | What happens |
61
+ |---|---|
62
+ | 加待办:写周报 周五前 2h 高优先级 | task added to the pool |
63
+ | 排一下今天 / `/plan` | day planned into Apple Calendar |
64
+ | 客户加了下午2点的会 | meeting added + remaining blocks re-planned |
65
+ | `/replan` | re-block the rest of today (deterministic) |
66
+ | 提醒我10分钟后喝水 | 10-min event with alarm |
67
+ | 周报写完了 | task marked done |
68
+ | 把明天健身改到7点 | event moved |
69
+ | 复盘 | evening summary + rollover |
70
+
71
+ ## Configuration
72
+
73
+ Env vars (or `~/.assistant/.env` for credentials only):
74
+
75
+ | Var | Default |
76
+ |---|---|
77
+ | `BACKBEAT_HOME` | `~/.assistant` |
78
+ | `BACKBEAT_CALENDAR` | `Backbeat` |
79
+ | `BACKBEAT_WORKHOURS` | `09:00-12:00,14:00-18:00` |
80
+ | `BACKBEAT_TZ` | `Asia/Shanghai` |
81
+ | `BACKBEAT_PYTHON` | `~/.assistant/venv/bin/python` |
82
+
83
+ ## vs. the SaaS
84
+
85
+ | | Motion | Reclaim | **Backbeat** |
86
+ |---|---|---|---|
87
+ | Price | $19/mo | $10/mo | free |
88
+ | Data location | their cloud | their cloud | **your machine** |
89
+ | Apple Calendar | sync | sync | **native (CalDAV)** |
90
+ | Reminders | in-app | in-app | **native iOS push** |
91
+ | Your AI, your rules | ❌ | ❌ | ✅ (Pi) |
92
+
93
+ ## Architecture
94
+
95
+ ```
96
+ pi-backbeat/
97
+ ├── extensions/index.ts # tasks + prefs + calendar tools, /plan /replan
98
+ ├── skills/backbeat/ # planning methodology for the LLM
99
+ ├── bin/ical.py # CalDAV CLI (all Apple Calendar I/O)
100
+ ├── bin/plan.sh # 08:00 headless planner
101
+ ├── bin/review.sh # 21:30 headless reviewer
102
+ ├── bin/install-timers.sh # installs the systemd user timers
103
+ └── systemd/ # unit templates
104
+ ```
105
+
106
+ ## Privacy
107
+
108
+ Everything stays local: the todo pool, preferences, and behavior feedback live in `~/.assistant/`; calendar I/O is direct CalDAV to your own iCloud account.
109
+
110
+ ## License
111
+
112
+ MIT — see [LICENSE](./LICENSE)
package/bin/ical.py ADDED
@@ -0,0 +1,428 @@
1
+ #!/usr/bin/env python3
2
+ """Backbeat CalDAV CLI — Apple Calendar (iCloud) operations for the Backbeat pi package.
3
+
4
+ All commands emit JSON. User data lives in $BACKBEAT_HOME (default ~/.assistant).
5
+ """
6
+ import argparse
7
+ import datetime as dt
8
+ import json
9
+ import os
10
+ import re
11
+ from pathlib import Path
12
+ from zoneinfo import ZoneInfo
13
+
14
+ from caldav import DAVClient, elements
15
+ try:
16
+ from icalendar import vDatetime as vCalDateTime # icalendar 5 & 7
17
+ except ImportError:
18
+ from icalendar import vCalDateTime # icalendar 6
19
+
20
+ HOME = Path(os.environ.get("BACKBEAT_HOME", str(Path.home() / ".assistant")))
21
+ TZ = ZoneInfo(os.environ.get("BACKBEAT_TZ", "Asia/Shanghai"))
22
+ AI_CALENDAR = os.environ.get("BACKBEAT_CALENDAR", "Backbeat")
23
+ WORK_HOURS = os.environ.get("BACKBEAT_WORKHOURS", "09:00-12:00,14:00-18:00")
24
+ MIN_SLOT = 15 # minutes
25
+ MARKER = "[backbeat]"
26
+
27
+
28
+ def load_env() -> dict:
29
+ env = {}
30
+ p = HOME / ".env"
31
+ if p.exists():
32
+ for line in p.read_text().splitlines():
33
+ if "=" in line and not line.startswith("#"):
34
+ k, v = line.split("=", 1)
35
+ env[k.strip()] = v.strip()
36
+ return env
37
+
38
+
39
+ def client() -> DAVClient:
40
+ e = load_env()
41
+ return DAVClient(
42
+ url=os.environ.get("BACKBEAT_CALDAV_URL", "https://p53-caldav.icloud.com"),
43
+ username=e["ICLOUD_USER"],
44
+ password=e["ICLOUD_PASSWORD"],
45
+ )
46
+
47
+
48
+ def out(data):
49
+ print(json.dumps(data, ensure_ascii=False, default=str))
50
+
51
+
52
+ def cal_name(cal) -> str:
53
+ return cal.get_display_name() or cal.name or ""
54
+
55
+
56
+ def find_cal(c: DAVClient, name: str):
57
+ for cal in c.principal().calendars():
58
+ if cal_name(cal) == name:
59
+ return cal
60
+ return None
61
+
62
+
63
+ def parse_dt(s: str) -> dt.datetime:
64
+ if len(s) <= 5: # "HH:MM" → today
65
+ h, m = s.split(":")
66
+ now = dt.datetime.now(TZ)
67
+ return now.replace(hour=int(h), minute=int(m), second=0, microsecond=0)
68
+ d = dt.datetime.fromisoformat(s)
69
+ if d.tzinfo is None:
70
+ d = d.replace(tzinfo=TZ)
71
+ return d
72
+
73
+
74
+ def event_rows(cal, start: dt.datetime, end: dt.datetime) -> list:
75
+ rows = []
76
+ for ev in cal.search(start=start, end=end, event=True):
77
+ comp = ev.icalendar_component
78
+ if comp is None:
79
+ continue
80
+ dts = comp.get("dtstart")
81
+ if dts is None:
82
+ continue
83
+ s = dts.dt
84
+ all_day = isinstance(s, dt.date) and not isinstance(s, dt.datetime)
85
+ if all_day:
86
+ s = dt.datetime.combine(s, dt.time(0, 0), TZ)
87
+ elif s.tzinfo is None:
88
+ s = s.replace(tzinfo=TZ)
89
+ dte = comp.get("dtend")
90
+ e = dte.dt if dte else s + dt.timedelta(minutes=30)
91
+ if isinstance(e, dt.date) and not isinstance(e, dt.datetime):
92
+ e = dt.datetime.combine(e, dt.time(23, 59, 59), TZ)
93
+ elif e.tzinfo is None:
94
+ e = e.replace(tzinfo=TZ)
95
+ rows.append(
96
+ {
97
+ "uid": ev.id,
98
+ "url": str(ev.url),
99
+ "calendar": cal_name(cal),
100
+ "summary": str(comp.get("summary") or ""),
101
+ "description": str(comp.get("description") or ""),
102
+ "start": s.isoformat(),
103
+ "end": e.isoformat(),
104
+ "all_day": all_day,
105
+ "ai": MARKER in str(comp.get("description") or ""),
106
+ }
107
+ )
108
+ return rows
109
+
110
+
111
+ WEEKDAY_MAP = {
112
+ "周一": 0, "周二": 1, "周三": 2, "周四": 3, "周五": 4, "周六": 5, "周日": 6,
113
+ "mon": 0, "tue": 1, "wed": 2, "thu": 3, "fri": 4, "sat": 5, "sun": 6,
114
+ }
115
+
116
+
117
+ def day_matches(spec: str, date: dt.date) -> bool:
118
+ s = spec.lower()
119
+ if s in ("每天", "daily"):
120
+ return True
121
+ if s in ("工作日", "weekdays"):
122
+ return date.weekday() < 5
123
+ if s in ("周末", "weekend"):
124
+ return date.weekday() >= 5
125
+ return date.weekday() == WEEKDAY_MAP.get(s, -1)
126
+
127
+
128
+ def pref_blocks(date: dt.date) -> list:
129
+ """Fixed no-schedule blocks from preferences.md matching this date."""
130
+ p = HOME / "preferences.md"
131
+ if not p.exists():
132
+ return []
133
+ blocks = []
134
+ pat = re.compile(
135
+ r"^- (每天|工作日|周末|周[一二三四五六日]|mon|tue|wed|thu|fri|sat|sun)"
136
+ r"\s+(\d{1,2}:\d{2})-(\d{1,2}:\d{2})\s*\S+" , re.IGNORECASE
137
+ )
138
+ for line in p.read_text().splitlines():
139
+ m = pat.match(line.strip())
140
+ if not m or not day_matches(m.group(1), date):
141
+ continue
142
+ sh, sm = map(int, m.group(2).split(":"))
143
+ eh, em = map(int, m.group(3).split(":"))
144
+ blocks.append(
145
+ (
146
+ dt.datetime(date.year, date.month, date.day, sh, sm, tzinfo=TZ),
147
+ dt.datetime(date.year, date.month, date.day, eh, em, tzinfo=TZ),
148
+ )
149
+ )
150
+ return blocks
151
+
152
+
153
+ def work_windows(date: dt.date) -> list:
154
+ wins = []
155
+ for part in WORK_HOURS.split(","):
156
+ a, b = part.split("-")
157
+ ah, am = map(int, a.split(":"))
158
+ bh, bm = map(int, b.split(":"))
159
+ wins.append(
160
+ (
161
+ dt.datetime(date.year, date.month, date.day, ah, am, tzinfo=TZ),
162
+ dt.datetime(date.year, date.month, date.day, bh, bm, tzinfo=TZ),
163
+ )
164
+ )
165
+ return wins
166
+
167
+
168
+ def all_events(c: DAVClient, start: dt.datetime, end: dt.datetime) -> list:
169
+ rows = []
170
+ for cal in c.principal().calendars():
171
+ rows.extend(event_rows(cal, start, end))
172
+ return rows
173
+
174
+
175
+ def find_event(c: DAVClient, uid: str | None, match: str | None, url: str | None):
176
+ if url:
177
+ return c.get_object_by_url(url)
178
+ for cal in c.principal().calendars():
179
+ if uid:
180
+ try:
181
+ return cal.get_object_by_uid(uid)
182
+ except Exception:
183
+ pass
184
+ if match:
185
+ now = dt.datetime.now(TZ)
186
+ for row in event_rows(cal, now - dt.timedelta(days=90), now + dt.timedelta(days=90)):
187
+ if match.lower() in row["summary"].lower():
188
+ return cal.get_object_by_uid(row["uid"])
189
+ return None
190
+
191
+
192
+ # ---------- commands ----------
193
+
194
+ def cmd_calendars(c):
195
+ out([{"name": cal_name(cal), "url": str(cal.url)} for cal in c.principal().calendars()])
196
+
197
+
198
+ def cmd_day(c, a):
199
+ date = dt.date.fromisoformat(a.date) if a.date else dt.datetime.now(TZ).date()
200
+ start = dt.datetime.combine(date, dt.time(0, 0), TZ)
201
+ rows = all_events(c, start, start + dt.timedelta(days=1))
202
+ rows.sort(key=lambda r: r["start"])
203
+ out(rows)
204
+
205
+
206
+ def cmd_free(c, a):
207
+ date = dt.date.fromisoformat(a.date) if a.date else dt.datetime.now(TZ).date()
208
+ day_start = dt.datetime.combine(date, dt.time(0, 0), TZ)
209
+ busy = []
210
+ for row in all_events(c, day_start, day_start + dt.timedelta(days=1)):
211
+ if row["all_day"]:
212
+ busy.append((day_start, day_start + dt.timedelta(days=1)))
213
+ else:
214
+ busy.append((dt.datetime.fromisoformat(row["start"]), dt.datetime.fromisoformat(row["end"])))
215
+ busy.extend(pref_blocks(date))
216
+ busy.sort()
217
+ merged = []
218
+ for s, e in busy:
219
+ if merged and s <= merged[-1][1]:
220
+ merged[-1] = (merged[-1][0], max(merged[-1][1], e))
221
+ else:
222
+ merged.append((s, e))
223
+ free = []
224
+ for ws, we in work_windows(date):
225
+ cur = ws
226
+ for s, e in merged:
227
+ if e <= ws or s >= we:
228
+ continue
229
+ if s > cur:
230
+ free.append((cur, min(s, we)))
231
+ cur = max(cur, e)
232
+ if cur >= we:
233
+ break
234
+ if cur < we:
235
+ free.append((cur, we))
236
+ out(
237
+ [
238
+ {"start": s.isoformat(), "end": e.isoformat(), "minutes": int((e - s).total_seconds() // 60)}
239
+ for s, e in free
240
+ if (e - s) >= dt.timedelta(minutes=MIN_SLOT)
241
+ ]
242
+ )
243
+
244
+
245
+ def cmd_add(c, a):
246
+ cal = find_cal(c, a.cal or AI_CALENDAR)
247
+ if cal is None:
248
+ raise SystemExit(f"calendar {a.cal or AI_CALENDAR!r} not found")
249
+ start = parse_dt(a.start)
250
+ end = parse_dt(a.end) if a.end else start + dt.timedelta(minutes=a.minutes or 30)
251
+ kwargs = {}
252
+ if a.rrule:
253
+ rule = {}
254
+ for kv in a.rrule.split(";"):
255
+ k, v = kv.split("=", 1)
256
+ if k == "UNTIL":
257
+ v = v.rstrip("Z")
258
+ if re.fullmatch(r"\d{14}", v):
259
+ v = f"{v[0:4]}-{v[4:6]}-{v[6:8]}T{v[8:10]}:{v[10:12]}:{v[12:14]}"
260
+ d = dt.datetime.fromisoformat(v)
261
+ rule[k] = d.replace(tzinfo=dt.timezone.utc) if d.tzinfo is None else d
262
+ else:
263
+ rule[k] = v
264
+ kwargs["rrule"] = rule
265
+ ev = cal.add_event(
266
+ summary=a.title,
267
+ dtstart=start,
268
+ dtend=end,
269
+ description=a.desc or "",
270
+ alarm_trigger=dt.timedelta(minutes=a.alarm),
271
+ **kwargs,
272
+ )
273
+ out({"uid": ev.id, "url": str(ev.url), "summary": a.title, "start": start.isoformat(), "end": end.isoformat()})
274
+
275
+
276
+ def cmd_move(c, a):
277
+ ev = find_event(c, a.uid, a.match, a.url)
278
+ if ev is None:
279
+ raise SystemExit("event not found")
280
+ comp = ev.icalendar_component
281
+ start = parse_dt(a.start)
282
+ old_s = comp.get("dtstart").dt
283
+ if isinstance(old_s, dt.date) and not isinstance(old_s, dt.datetime):
284
+ old_s = dt.datetime.combine(old_s, dt.time(0, 0), TZ)
285
+ elif old_s.tzinfo is None:
286
+ old_s = old_s.replace(tzinfo=TZ)
287
+ dte = comp.get("dtend")
288
+ old_e = dte.dt if dte else old_s + dt.timedelta(minutes=30)
289
+ if isinstance(old_e, dt.date) and not isinstance(old_e, dt.datetime):
290
+ old_e = dt.datetime.combine(old_e, dt.time(23, 59, 59), TZ)
291
+ elif old_e.tzinfo is None:
292
+ old_e = old_e.replace(tzinfo=TZ)
293
+ duration = old_e - old_s
294
+ end = parse_dt(a.end) if a.end else start + duration
295
+ comp["dtstart"] = vCalDateTime(start)
296
+ comp["dtend"] = vCalDateTime(end)
297
+ ev.save()
298
+ out({"uid": ev.id, "summary": str(comp.get("summary") or ""), "start": start.isoformat(), "end": end.isoformat()})
299
+
300
+
301
+ def cmd_delete(c, a):
302
+ ev = find_event(c, a.uid, a.match, a.url)
303
+ if ev is None:
304
+ raise SystemExit("event not found")
305
+ summary = str(ev.icalendar_component.get("summary") or "")
306
+ ev.delete()
307
+ out({"deleted": ev.id, "summary": summary})
308
+
309
+
310
+ def cmd_clear_ai(c, a):
311
+ date = dt.date.fromisoformat(a.date) if a.date else dt.datetime.now(TZ).date()
312
+ cal = find_cal(c, a.cal or AI_CALENDAR)
313
+ if cal is None:
314
+ out({"deleted": 0})
315
+ return
316
+ start = dt.datetime.combine(date, dt.time(0, 0), TZ)
317
+ after = dt.datetime.fromisoformat(a.after) if a.after else None
318
+ deleted = 0
319
+ for row in event_rows(cal, start, start + dt.timedelta(days=1)):
320
+ if not row["ai"]:
321
+ continue
322
+ if after and dt.datetime.fromisoformat(row["start"]) <= after:
323
+ continue
324
+ ev = cal.get_object_by_uid(row["uid"])
325
+ ev.delete()
326
+ deleted += 1
327
+ out({"deleted": deleted})
328
+
329
+
330
+ def cmd_rename_cal(c, a):
331
+ cal = find_cal(c, a.from_)
332
+ if cal is None:
333
+ raise SystemExit(f"calendar {a.from_!r} not found")
334
+ cal.set_properties([elements.dav.DisplayName(a.to)])
335
+ out({"renamed": f"{a.from_} -> {a.to}"})
336
+
337
+
338
+ def cmd_move_cal(c, a):
339
+ src = find_cal(c, a.from_)
340
+ dst = find_cal(c, a.to)
341
+ if src is None or dst is None:
342
+ raise SystemExit("calendar not found")
343
+ import uuid
344
+
345
+ ev = src.get_object_by_uid(a.uid)
346
+ data = ev.data if isinstance(ev.data, str) else ev.data.decode()
347
+ data = "\n".join(l for l in data.splitlines() if not l.upper().startswith("SCHEDULE-TAG"))
348
+ # iCloud enforces UID uniqueness across calendars: new UID, else PUT → 412
349
+ data = data.replace(f"UID:{a.uid}", f"UID:{uuid.uuid4()}")
350
+ new_ev = dst.add_event(data)
351
+ ev.delete()
352
+ out({"moved": a.uid, "from": a.from_, "to": a.to, "url": str(new_ev.url)})
353
+
354
+
355
+ def cmd_mkcalendar(c, a):
356
+ cal = c.principal().make_calendar(name=a.name)
357
+ out({"name": a.name, "url": str(cal.url)})
358
+
359
+
360
+ def main():
361
+ p = argparse.ArgumentParser(description="Backbeat CalDAV CLI")
362
+ sub = p.add_subparsers(dest="cmd", required=True)
363
+
364
+ sub.add_parser("calendars")
365
+
366
+ d = sub.add_parser("day")
367
+ d.add_argument("date", nargs="?")
368
+
369
+ f = sub.add_parser("free")
370
+ f.add_argument("date", nargs="?")
371
+
372
+ a = sub.add_parser("add")
373
+ a.add_argument("--title", required=True)
374
+ a.add_argument("--start", required=True)
375
+ a.add_argument("--end")
376
+ a.add_argument("--minutes", type=int)
377
+ a.add_argument("--cal")
378
+ a.add_argument("--alarm", type=int, default=5)
379
+ a.add_argument("--desc")
380
+ a.add_argument("--rrule", help="e.g. FREQ=WEEKLY;BYDAY=SA;UNTIL=20270101T000000Z")
381
+
382
+ m = sub.add_parser("move")
383
+ m.add_argument("--uid")
384
+ m.add_argument("--match")
385
+ m.add_argument("--url")
386
+ m.add_argument("--start", required=True)
387
+ m.add_argument("--end")
388
+
389
+ dl = sub.add_parser("delete")
390
+ dl.add_argument("--uid")
391
+ dl.add_argument("--match")
392
+ dl.add_argument("--url")
393
+
394
+ ca = sub.add_parser("clear-ai")
395
+ ca.add_argument("date", nargs="?")
396
+ ca.add_argument("--cal")
397
+ ca.add_argument("--after")
398
+
399
+ r = sub.add_parser("rename-cal")
400
+ r.add_argument("--from", dest="from_", required=True)
401
+ r.add_argument("--to", required=True)
402
+
403
+ mv = sub.add_parser("move-cal")
404
+ mv.add_argument("--uid", required=True)
405
+ mv.add_argument("--from", dest="from_", required=True)
406
+ mv.add_argument("--to", required=True)
407
+
408
+ mk = sub.add_parser("mkcalendar")
409
+ mk.add_argument("--name", required=True)
410
+
411
+ a_ = p.parse_args()
412
+ c = client()
413
+ {
414
+ "calendars": lambda: cmd_calendars(c),
415
+ "day": lambda: cmd_day(c, a_),
416
+ "free": lambda: cmd_free(c, a_),
417
+ "add": lambda: cmd_add(c, a_),
418
+ "move": lambda: cmd_move(c, a_),
419
+ "delete": lambda: cmd_delete(c, a_),
420
+ "clear-ai": lambda: cmd_clear_ai(c, a_),
421
+ "rename-cal": lambda: cmd_rename_cal(c, a_),
422
+ "move-cal": lambda: cmd_move_cal(c, a_),
423
+ "mkcalendar": lambda: cmd_mkcalendar(c, a_),
424
+ }[a_.cmd]()
425
+
426
+
427
+ if __name__ == "__main__":
428
+ main()
@@ -0,0 +1,25 @@
1
+ #!/usr/bin/env bash
2
+ # Install Backbeat systemd user timers (plan 08:00, review 21:30)
3
+ set -euo pipefail
4
+ HERE="$(cd "$(dirname "$0")/.." && pwd)"
5
+ UID_NUM="$(id -u)"
6
+ UNIT_DIR="$HOME/.config/systemd/user"
7
+
8
+ sub() {
9
+ sed -e "s|__BACKBEAT_ROOT__|$HERE|g" \
10
+ -e "s|__HOME__|$HOME|g" \
11
+ -e "s|__UID__|$UID_NUM|g" \
12
+ -e "s|__WAYLAND__|${WAYLAND_DISPLAY:-}|g" \
13
+ -e "s|__DISPLAY__|${DISPLAY:-}|g" "$1"
14
+ }
15
+
16
+ tmp="$(mktemp)"
17
+ for f in pi-backbeat-plan.service pi-backbeat-review.service pi-backbeat-plan.timer pi-backbeat-review.timer; do
18
+ sub "$HERE/systemd/$f" > "$tmp"
19
+ install -Dm600 "$tmp" "$UNIT_DIR/$f"
20
+ done
21
+ rm -f "$tmp"
22
+
23
+ systemctl --user daemon-reload
24
+ systemctl --user enable --now pi-backbeat-plan.timer pi-backbeat-review.timer
25
+ echo "Backbeat timers installed: plan 08:00, review 21:30 (systemctl --user list-timers | grep backbeat)"
package/bin/plan.sh ADDED
@@ -0,0 +1,17 @@
1
+ #!/usr/bin/env bash
2
+ # Backbeat morning planning — headless pi (run by systemd timer)
3
+ set -euo pipefail
4
+ HERE="$(cd "$(dirname "$0")/.." && pwd)"
5
+ PI_BIN="${PI_BIN:-$HOME/.npm-global/bin/pi}"
6
+ [ -x "$PI_BIN" ] || PI_BIN="$(command -v pi)"
7
+ TODAY="$(date +%F)"
8
+
9
+ PROMPT="Backbeat 晨间排程,今天是 $TODAY。
10
+ 1. 用 tasks 工具列出未完成待办。
11
+ 2. 用 calendar 工具:day $TODAY(锚点)、free $TODAY(空隙,已自动排除偏好固定时段)。
12
+ 3. 读 ~/.assistant/preferences.md,排程时参考『其他偏好』和『学到的偏好』。
13
+ 4. 按 backbeat skill 规则排程:calendar clear_ai $TODAY 后把任务块写入 Backbeat 日历(title [Backbeat] <任务>,desc [backbeat] task:<id>,alarm 5)。最重要的任务放早晨。
14
+ 5. 最后运行: notify-send 'Backbeat 今日日程' '<时间线摘要,最多5行>'。待办池为空则通知 '今日无待办'。
15
+ 排不下的任务列入摘要的'未排入'。"
16
+
17
+ exec "$PI_BIN" -p --no-session "$PROMPT"
package/bin/review.sh ADDED
@@ -0,0 +1,20 @@
1
+ #!/usr/bin/env bash
2
+ # Backbeat evening review — headless pi (run by systemd timer)
3
+ set -euo pipefail
4
+ HERE="$(cd "$(dirname "$0")/.." && pwd)"
5
+ PI_BIN="${PI_BIN:-$HOME/.npm-global/bin/pi}"
6
+ [ -x "$PI_BIN" ] || PI_BIN="$(command -v pi)"
7
+ TODAY="$(date +%F)"
8
+
9
+ PROMPT="Backbeat 晚间复盘,今天是 $TODAY。
10
+ 1. 用 tasks 工具列出全部待办(filter all)。
11
+ 2. 用 calendar 工具 day $TODAY,找出描述带 [backbeat] 的事件。
12
+ 3. 有 [backbeat] 事件但任务未标 [x] 的 = 未完成(保留在池中即滚入明天,不要删除)。
13
+ 4. 偏好学习:读 ~/.assistant/feedback.jsonl(今天条目,可能为空)和 ~/.assistant/preferences.md。
14
+ - 用户今天移动/删除了 AI 事件 → 提炼规律(如两次都挪到上午 → '重要任务偏好上午')
15
+ - 任务在其所在时段完成 → 该时段有效;被滚入 → 记录
16
+ - 把新规律写成简短 bullet 追加到 preferences.md 的『学到的偏好』小节(带日期,合并相似条目,整节最多 15 行)
17
+ 5. 最后运行: notify-send 'Backbeat 复盘' '完成 X/Y:<完成清单>;未完成滚入明天:<清单>[;新学会:<规律>(说一声就改)]'。
18
+ 没有新规律就不写『新学会』。不要删除任何日历事件,不要改动任务状态。"
19
+
20
+ exec "$PI_BIN" -p --no-session "$PROMPT"
@@ -0,0 +1,410 @@
1
+ import { type ExtensionAPI, type ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
2
+ import { Type } from "typebox";
3
+ import { execFile } from "node:child_process";
4
+ import { appendFileSync, existsSync, readFileSync, writeFileSync } from "node:fs";
5
+ import { dirname, join } from "node:path";
6
+ import { promisify } from "node:util";
7
+ import { fileURLToPath } from "node:url";
8
+
9
+ const pexec = promisify(execFile);
10
+
11
+ const HERE = (() => {
12
+ try {
13
+ return dirname(fileURLToPath(import.meta.url));
14
+ } catch {
15
+ return __dirname;
16
+ }
17
+ })();
18
+ const PKG = join(HERE, "..");
19
+ const HOME_DIR = process.env.BACKBEAT_HOME ?? join(process.env.HOME ?? "/root", ".assistant");
20
+ const VENV_PY = process.env.BACKBEAT_PYTHON || join(HOME_DIR, "venv", "bin", "python");
21
+ const TASKS_FILE = process.env.BACKBEAT_TASKS || join(HOME_DIR, "tasks.md");
22
+ const PREFS_FILE = process.env.BACKBEAT_PREFS || join(HOME_DIR, "preferences.md");
23
+ const FEEDBACK_FILE = join(HOME_DIR, "feedback.jsonl");
24
+
25
+ function logFeedback(entry: Record<string, unknown>): void {
26
+ try {
27
+ appendFileSync(FEEDBACK_FILE, JSON.stringify({ ts: new Date().toISOString(), ...entry }) + "\n");
28
+ } catch {
29
+ // non-fatal
30
+ }
31
+ }
32
+ const ICS = join(PKG, "bin", "ical.py");
33
+ const MARKER = "[backbeat]";
34
+
35
+ async function ical(args: string[]): Promise<string> {
36
+ try {
37
+ const { stdout, stderr } = await pexec(VENV_PY, [ICS, ...args], { maxBuffer: 10 * 1024 * 1024 });
38
+ return stdout.trim() || stderr.trim();
39
+ } catch (e: any) {
40
+ throw new Error(e.stderr?.trim() || e.message);
41
+ }
42
+ }
43
+
44
+ // ---------- tasks ----------
45
+
46
+ type Task = { id: string; text: string; meta: string; done: boolean };
47
+
48
+ function parseTasks(): Task[] {
49
+ if (!existsSync(TASKS_FILE)) return [];
50
+ const tasks: Task[] = [];
51
+ for (const line of readFileSync(TASKS_FILE, "utf8").split("\n")) {
52
+ const m = line.match(/^- \[( |x|X)\] (T\d+)\s+(.+)$/);
53
+ if (!m) continue;
54
+ const parts = m[3].split(/\s*\|\s*/);
55
+ tasks.push({ id: m[2], text: parts[0], meta: parts.slice(1).join(" | "), done: m[1] !== " " });
56
+ }
57
+ return tasks;
58
+ }
59
+
60
+ function fmtTask(t: Task): string {
61
+ return `- [${t.done ? "x" : " "}] ${t.id} ${t.text}${t.meta ? " | " + t.meta : ""}`;
62
+ }
63
+
64
+ function writeTasks(tasks: Task[]): void {
65
+ let header = "# Backbeat 待办池";
66
+ if (existsSync(TASKS_FILE)) {
67
+ const kept = readFileSync(TASKS_FILE, "utf8")
68
+ .split("\n")
69
+ .filter((l) => !l.match(/^- \[[ xX]\] T\d+/))
70
+ .join("\n")
71
+ .trimEnd();
72
+ if (kept) header = kept;
73
+ }
74
+ writeFileSync(TASKS_FILE, `${header}\n\n${tasks.map(fmtTask).join("\n")}\n`);
75
+ }
76
+
77
+ function nextId(tasks: Task[]): string {
78
+ const max = tasks.reduce((mx, t) => Math.max(mx, parseInt(t.id.slice(1), 10) || 0), 0);
79
+ return "T" + String(max + 1).padStart(2, "0");
80
+ }
81
+
82
+ const ok = (text: string) => ({ content: [{ type: "text" as const, text }], details: {} });
83
+ const err = (text: string) => ({ content: [{ type: "text" as const, text: `ERROR: ${text}` }], details: {} });
84
+
85
+ // ---------- deterministic planning ----------
86
+
87
+ function durMin(meta: string): number {
88
+ const m = meta.match(/(\d+(?:\.\d+)?)\s*(h|min|m|小时|分钟|分|时)/);
89
+ if (!m) return 60;
90
+ const v = parseFloat(m[1]);
91
+ const short = m[2] === "m" || m[2] === "min" || m[2] === "分钟" || m[2] === "分";
92
+ return Math.max(15, Math.round(short ? v : v * 60));
93
+ }
94
+
95
+ function prio(meta: string): number {
96
+ const m = meta.match(/P([0-3])/);
97
+ return m ? parseInt(m[1], 10) : 2;
98
+ }
99
+
100
+ function todayStr(): string {
101
+ const d = new Date();
102
+ const p = (n: number) => String(n).padStart(2, "0");
103
+ return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`;
104
+ }
105
+
106
+ function dueRank(meta: string, today: string): number {
107
+ if (meta.includes("今天")) return 0;
108
+ if (meta.includes("明天")) return 1;
109
+ const d = meta.match(/due:(\d{1,2})-(\d{1,2})/);
110
+ if (d) {
111
+ const [y, m2, dd] = today.split("-").map(Number);
112
+ const dueDate = new Date(y, m2 - 1, dd);
113
+ const target = new Date(y, parseInt(d[1], 10) - 1, parseInt(d[2], 10));
114
+ const diff = Math.round((target.getTime() - dueDate.getTime()) / 86400000);
115
+ if (diff <= 0) return 0;
116
+ return Math.min(4, 1 + diff);
117
+ }
118
+ if (meta.includes("本周")) return 4;
119
+ return 5;
120
+ }
121
+
122
+ function fmtDT(d: Date): string {
123
+ const p = (n: number) => String(n).padStart(2, "0");
124
+ return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}T${p(d.getHours())}:${p(d.getMinutes())}`;
125
+ }
126
+
127
+ async function runPlan(ctx: ExtensionCommandContext, replan: boolean): Promise<void> {
128
+ const date = todayStr();
129
+ const now = new Date();
130
+ const tasks = parseTasks().filter((t) => !t.done);
131
+
132
+ // events already on the calendar (anchors + existing AI events)
133
+ const dayJson: any[] = JSON.parse(await ical(["day", date]));
134
+ const aiEvents = dayJson.filter((e) => e.ai);
135
+ const running = new Set(
136
+ aiEvents
137
+ .filter((e) => new Date(e.start) <= now && new Date(e.end) > now)
138
+ .map((e) => (e.description.match(/task:(T\d+)/) || [])[1])
139
+ );
140
+
141
+ if (replan) {
142
+ await ical(["clear-ai", date, "--after", fmtDT(now)]);
143
+ } else {
144
+ await ical(["clear-ai", date]);
145
+ }
146
+
147
+ const freeJson: any[] = JSON.parse(await ical(["free", date]));
148
+ const slots = freeJson.filter((s) => new Date(s.start) > now).map((s) => ({ start: s.start, left: s.minutes }));
149
+
150
+ const queue = tasks
151
+ .filter((t) => !running.has(t.id))
152
+ .sort((a, b) => prio(a.meta) - prio(b.meta) || dueRank(a.meta, date) - dueRank(b.meta, date));
153
+
154
+ const plan: { task: Task; start: Date; end: Date }[] = [];
155
+ const overflow: Task[] = [];
156
+ for (const t of queue) {
157
+ const need = durMin(t.meta);
158
+ const slot = slots.find((s) => s.left >= need);
159
+ if (!slot) {
160
+ overflow.push(t);
161
+ continue;
162
+ }
163
+ const start = new Date(slot.start);
164
+ const end = new Date(start.getTime() + need * 60000);
165
+ plan.push({ task: t, start, end });
166
+ slot.start = fmtDT(end);
167
+ slot.left -= need;
168
+ }
169
+
170
+ for (const p of plan) {
171
+ await ical([
172
+ "add",
173
+ "--title", `[Backbeat] ${p.task.text}`,
174
+ "--start", fmtDT(p.start),
175
+ "--end", fmtDT(p.end),
176
+ "--desc", `${MARKER} task:${p.task.id}`,
177
+ ]);
178
+ }
179
+
180
+ const lines = plan.map((p) => `${fmtDT(p.start).slice(11)}–${fmtDT(p.end).slice(11)} ${p.task.text} (${p.task.id})`);
181
+ const summary = (lines.length ? lines.join("\n") : "(nothing scheduled)") +
182
+ (overflow.length ? "\n未排入: " + overflow.map((t) => t.text).join(", ") : "");
183
+ if (ctx.hasUI) ctx.ui.notify(`Backbeat ${date}\n${summary}`, "info");
184
+ }
185
+
186
+ // ---------- extension ----------
187
+
188
+ export default function (pi: ExtensionAPI) {
189
+ pi.registerTool({
190
+ name: "tasks",
191
+ label: "Tasks",
192
+ description:
193
+ "Manage the Backbeat todo pool (~/.assistant/tasks.md). Actions: add (text, due, duration, priority), list (pending/all/done), done (id), remove (id).",
194
+ parameters: Type.Object({
195
+ action: Type.Union([Type.Literal("add"), Type.Literal("list"), Type.Literal("done"), Type.Literal("remove")]),
196
+ text: Type.Optional(Type.String({ description: "task text (add)" })),
197
+ id: Type.Optional(Type.String({ description: "task id like T01 (done/remove)" })),
198
+ due: Type.Optional(Type.String({ description: "e.g. 今天 / 明天 / 11-28 / 周五 (add)" })),
199
+ duration: Type.Optional(Type.String({ description: "e.g. 2h / 45m (add)" })),
200
+ priority: Type.Optional(Type.Union([Type.Literal("P0"), Type.Literal("P1"), Type.Literal("P2"), Type.Literal("P3")])),
201
+ filter: Type.Optional(Type.Union([Type.Literal("pending"), Type.Literal("all"), Type.Literal("done")])),
202
+ }),
203
+ async execute(_id, params) {
204
+ const tasks = parseTasks();
205
+ switch (params.action) {
206
+ case "add": {
207
+ if (!params.text) return err("text required");
208
+ const meta = [params.due ? `due:${params.due}` : "", params.duration ?? "", params.priority ?? ""].filter(Boolean).join(" | ");
209
+ const t: Task = { id: nextId(tasks), text: params.text, meta, done: false };
210
+ tasks.push(t);
211
+ writeTasks(tasks);
212
+ return ok(`Added ${fmtTask(t)}`);
213
+ }
214
+ case "list": {
215
+ const f = params.filter ?? "pending";
216
+ const list = tasks.filter((t) => (f === "all" ? true : f === "done" ? t.done : !t.done));
217
+ return ok(list.length ? list.map(fmtTask).join("\n") : "(empty)");
218
+ }
219
+ case "done": {
220
+ const t = tasks.find((x) => x.id === params.id);
221
+ if (!t) return err(`task not found: ${params.id}`);
222
+ t.done = true;
223
+ if (!t.meta.includes("done:")) {
224
+ const d = new Date();
225
+ t.meta = `${t.meta ? t.meta + " | " : ""}done:${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
226
+ }
227
+ writeTasks(tasks);
228
+ return ok(`Done: ${t.id} ${t.text}`);
229
+ }
230
+ case "remove": {
231
+ const i = tasks.findIndex((x) => x.id === params.id);
232
+ if (i < 0) return err(`task not found: ${params.id}`);
233
+ const [t] = tasks.splice(i, 1);
234
+ writeTasks(tasks);
235
+ return ok(`Removed ${t.id} ${t.text}`);
236
+ }
237
+ }
238
+ },
239
+ });
240
+
241
+ pi.registerTool({
242
+ name: "prefs",
243
+ label: "Prefs",
244
+ description:
245
+ "Remember the user's standing preferences. add a fixed no-schedule block (e.g. 每天 12:00-14:00 午休); note a soft preference in words (e.g. 重要任务放上午); list shows current prefs; remove by label; forget by text. Planner's free-slot computation already honors fixed blocks; soft prefs guide LLM planning.",
246
+ parameters: Type.Object({
247
+ action: Type.Union([Type.Literal("add"), Type.Literal("list"), Type.Literal("remove"), Type.Literal("note"), Type.Literal("forget")]),
248
+ days: Type.Optional(Type.String({ description: "每天/工作日/周末/周一..周日 (add)" })),
249
+ start: Type.Optional(Type.String({ description: "HH:MM (add)" })),
250
+ end: Type.Optional(Type.String({ description: "HH:MM (add)" })),
251
+ label: Type.Optional(Type.String({ description: "short label like 午休 (add/remove)" })),
252
+ text: Type.Optional(Type.String({ description: "preference in words (note/forget)" })),
253
+ }),
254
+ async execute(_id, params) {
255
+ const read = () =>
256
+ existsSync(PREFS_FILE)
257
+ ? readFileSync(PREFS_FILE, "utf8")
258
+ : "# Backbeat 偏好\n\n## 固定时段(不排程)\n\n## 其他偏好\n";
259
+ switch (params.action) {
260
+ case "list":
261
+ return ok(read().trim());
262
+ case "add": {
263
+ if (!params.days || !params.start || !params.end || !params.label)
264
+ return err("days/start/end/label required");
265
+ const line = `- ${params.days} ${params.start}-${params.end} ${params.label}`;
266
+ let content = read();
267
+ if (content.includes(line)) return ok(`already remembered: ${line}`);
268
+ content = content.replace(
269
+ /(## 固定时段(不排程)\n)(<!--[^>]*-->\n)?/,
270
+ `$1$2${line}\n`
271
+ );
272
+ writeFileSync(PREFS_FILE, content);
273
+ return ok(`Remembered: ${line}`);
274
+ }
275
+ case "remove": {
276
+ if (!params.label) return err("label required");
277
+ const label = params.label;
278
+ let content = read();
279
+ const before = content;
280
+ content = content
281
+ .split("\n")
282
+ .filter((l) => !l.startsWith("- ") || !l.includes(label))
283
+ .join("\n");
284
+ if (content === before) return err(`no preference with label: ${params.label}`);
285
+ writeFileSync(PREFS_FILE, content);
286
+ return ok(`Removed preference: ${params.label}`);
287
+ }
288
+ case "note": {
289
+ if (!params.text) return err("text required");
290
+ let content = read();
291
+ if (content.includes(params.text)) return ok(`already noted: ${params.text}`);
292
+ content = content.replace(/(## 其他偏好\n)(<!--[^>]*-->\n)?/, `$1$2- ${params.text}\n`);
293
+ writeFileSync(PREFS_FILE, content);
294
+ return ok(`Noted: ${params.text}`);
295
+ }
296
+ case "forget": {
297
+ if (!params.text) return err("text required");
298
+ const text = params.text;
299
+ let content = read();
300
+ const before = content;
301
+ content = content
302
+ .split("\n")
303
+ .filter((l) => !l.startsWith("- ") || !l.includes(text))
304
+ .join("\n");
305
+ if (content === before) return err(`no preference matching: ${params.text}`);
306
+ writeFileSync(PREFS_FILE, content);
307
+ return ok(`Forgotten: ${params.text}`);
308
+ }
309
+ }
310
+ },
311
+ });
312
+
313
+ pi.registerTool({
314
+ name: "calendar",
315
+ label: "Calendar",
316
+ description:
317
+ "Apple Calendar (iCloud) via CalDAV. Actions: day (events of a date, all calendars), free (free slots in work hours), add, move, delete, clear_ai (remove today's AI events). AI events live in the Backbeat calendar, marked [backbeat].",
318
+ parameters: Type.Object({
319
+ action: Type.Union([
320
+ Type.Literal("day"),
321
+ Type.Literal("free"),
322
+ Type.Literal("add"),
323
+ Type.Literal("move"),
324
+ Type.Literal("delete"),
325
+ Type.Literal("clear_ai"),
326
+ ]),
327
+ date: Type.Optional(Type.String({ description: "YYYY-MM-DD, default today" })),
328
+ title: Type.Optional(Type.String()),
329
+ start: Type.Optional(Type.String({ description: "YYYY-MM-DDTHH:MM or HH:MM" })),
330
+ end: Type.Optional(Type.String()),
331
+ minutes: Type.Optional(Type.Number({ description: "duration when end omitted (add)" })),
332
+ cal: Type.Optional(Type.String({ description: "calendar name, default Backbeat" })),
333
+ alarm: Type.Optional(Type.Number({ description: "alarm minutes before start, default 5" })),
334
+ desc: Type.Optional(Type.String()),
335
+ uid: Type.Optional(Type.String()),
336
+ match: Type.Optional(Type.String({ description: "match by summary substring" })),
337
+ after: Type.Optional(Type.String({ description: "clear_ai: only events starting after this time" })),
338
+ }),
339
+ async execute(_id, params) {
340
+ try {
341
+ switch (params.action) {
342
+ case "day":
343
+ return ok(await ical(["day", ...(params.date ? [params.date] : [])]));
344
+ case "free":
345
+ return ok(await ical(["free", ...(params.date ? [params.date] : [])]));
346
+ case "add": {
347
+ if (!params.title || !params.start) return err("title and start required");
348
+ const args = ["add", "--title", params.title, "--start", params.start];
349
+ if (params.end) args.push("--end", params.end);
350
+ else if (params.minutes) args.push("--minutes", String(params.minutes));
351
+ if (params.cal) args.push("--cal", params.cal);
352
+ if (params.alarm !== undefined) args.push("--alarm", String(params.alarm));
353
+ if (params.desc) args.push("--desc", params.desc);
354
+ return ok(await ical(args));
355
+ }
356
+ case "move": {
357
+ if (!params.start) return err("start required");
358
+ const args = ["move", "--start", params.start];
359
+ if (params.uid) args.push("--uid", params.uid);
360
+ else if (params.match) args.push("--match", params.match);
361
+ if (params.end) args.push("--end", params.end);
362
+ const r = await ical(args);
363
+ logFeedback({ action: "move", start: params.start, end: params.end ?? null, result: r });
364
+ return ok(r);
365
+ }
366
+ case "delete": {
367
+ const args = ["delete"];
368
+ if (params.uid) args.push("--uid", params.uid);
369
+ else if (params.match) args.push("--match", params.match);
370
+ const r = await ical(args);
371
+ logFeedback({ action: "delete", uid: params.uid ?? null, match: params.match ?? null, result: r });
372
+ return ok(r);
373
+ }
374
+ case "clear_ai":
375
+ return ok(
376
+ await ical([
377
+ "clear-ai",
378
+ ...(params.date ? [params.date] : []),
379
+ ...(params.after ? ["--after", params.after] : []),
380
+ ])
381
+ );
382
+ }
383
+ } catch (e: any) {
384
+ return err(e.message);
385
+ }
386
+ },
387
+ });
388
+
389
+ pi.registerCommand("plan", {
390
+ description: "Plan the day deterministically: pending todos → free slots (priority order)",
391
+ handler: async (_args, ctx) => {
392
+ try {
393
+ await runPlan(ctx, false);
394
+ } catch (e: any) {
395
+ if (ctx.hasUI) ctx.ui.notify(`plan failed: ${e.message}`, "error");
396
+ }
397
+ },
398
+ });
399
+
400
+ pi.registerCommand("replan", {
401
+ description: "Re-plan the rest of today: keep started events, re-block the remaining AI events",
402
+ handler: async (_args, ctx) => {
403
+ try {
404
+ await runPlan(ctx, true);
405
+ } catch (e: any) {
406
+ if (ctx.hasUI) ctx.ui.notify(`replan failed: ${e.message}`, "error");
407
+ }
408
+ },
409
+ });
410
+ }
package/package.json ADDED
@@ -0,0 +1,27 @@
1
+ {
2
+ "name": "pi-backbeat",
3
+ "version": "0.1.0",
4
+ "description": "Backbeat — the rhythm section for your day. Local-first AI scheduling for Apple Calendar, powered by Pi.",
5
+ "type": "module",
6
+ "keywords": ["pi-package"],
7
+ "license": "MIT",
8
+ "files": [
9
+ "bin",
10
+ "extensions",
11
+ "skills",
12
+ "systemd",
13
+ "!bin/__pycache__"
14
+ ],
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/AuthurX/pi-backbeat.git"
18
+ },
19
+ "pi": {
20
+ "extensions": ["./extensions/index.ts"],
21
+ "skills": ["./skills"]
22
+ },
23
+ "peerDependencies": {
24
+ "@earendil-works/pi-coding-agent": "*",
25
+ "typebox": "*"
26
+ }
27
+ }
@@ -0,0 +1,61 @@
1
+ ---
2
+ name: backbeat
3
+ description: Backbeat 日程助理。待办记录、每日排程写入苹果日历、冲突重排、提醒、晚间复盘。当用户提到 待办/todo/排程/日程/排一下/重排/提醒我/复盘/我的日历 时使用。
4
+ ---
5
+
6
+ # Backbeat
7
+
8
+ 你是 Backbeat,一个本地日程助理。数据面:
9
+
10
+ - **待办池** `~/.assistant/tasks.md` — 用 `tasks` 工具管理(add/list/done/remove),不要直接编辑文件
11
+ - **苹果日历** (iCloud CalDAV) — 用 `calendar` 工具。AI 排的事件在 **Backbeat** 日历,描述带 `[backbeat] task:<id>` 标记;用户自己的日历(如 休息)只写用户亲口说的真实事件
12
+
13
+ ## 流程
14
+
15
+ ### 加待办
16
+ "加待办:写周报 周五前 2小时 高优先级" → `tasks add`(text、due、duration、priority P0-P3,高=P1 或 P0)。
17
+
18
+ ### 排程(用户说 排一下/帮我排/plan 时)
19
+ 1. `tasks list`(pending)
20
+ 2. `calendar day <date>` — 已有事件 = 锚点
21
+ 3. `calendar free <date>` — 工作时间内空隙
22
+ 4. 排程规则:
23
+ - 绝不覆盖已有事件;任务只进空隙
24
+ - 最重要任务 → 早晨最佳时段(Big Rocks First)
25
+ - 会议后留 15 分钟缓冲;**空隙不填满**,留白
26
+ - 排不下的任务明确告诉用户被裁掉了
27
+ 5. `calendar clear_ai <date>` 然后逐个 `calendar add`(title `[Backbeat] <任务>`,desc `[backbeat] task:<id>`,alarm 5)
28
+ 6. 用时间线格式回报:`9:00–11:00 写周报 (T01)` …
29
+
30
+ ### 重排(临时加会/状态变化)
31
+ 1. 新事件先 `calendar add`(写入用户日历,如 `--cal 休息`)
32
+ 2. 已开始的不动;剩余 `[backbeat]` 事件重新填入新空隙
33
+ 3. 快捷路径:`/replan` 命令(确定性,无需思考)
34
+
35
+ ### 提醒
36
+ "提醒我10分钟后喝水" → `calendar add` 一个 10 分钟事件(title `提醒:喝水`,Backbeat 日历,alarm 2)。
37
+
38
+ ### 标记完成
39
+ "周报写完了" → `tasks done T01`。
40
+
41
+ ### 记住偏好(越用越懂你)
42
+ **显性偏好**(用户明说):
43
+ - 固定时段:"我每天12:00–14:00休息" → `prefs add`(days/start/end/label),`free` 自动硬排除
44
+ - 软偏好:"重要任务放上午"、"别把我排太满" → `prefs note`(写入 preferences.md 其他偏好)
45
+ - 撤销:"不用记了/改一下" → `prefs remove` / `prefs forget`
46
+
47
+ **隐性偏好**(从行为学,自动):
48
+ - 用户要求移动/删除 AI 事件时,calendar 工具自动记入 feedback.jsonl(无需你操作)
49
+ - 21:30 复盘自动提炼规律 → 写入 preferences.md『学到的偏好』,并在通知里透明告知
50
+ - 排程时读 preferences.md 全部小节,参考软偏好和学到的规律
51
+ - 学习要克制:只写反复出现的模式(2次以上),一次性的不记;用户可随时删改
52
+
53
+ ### 复盘(晚间)
54
+ 1. `calendar day`(今天)+ `tasks list`
55
+ 2. 有 `[backbeat]` 事件但任务未 `[x]` 的 = 未完成(留在池里即自动滚入明天)
56
+ 3. 汇报:完成 X/Y + 未完成清单
57
+
58
+ ## 规则
59
+ - 没有 `[backbeat]` 标记的事件,用户明确要求前绝不改动
60
+ - 所有时间 Asia/Shanghai
61
+ - 回复简短:时间线 + 一句话总结
@@ -0,0 +1,13 @@
1
+ [Unit]
2
+ Description=Backbeat daily planning (headless pi)
3
+ After=network-online.target
4
+ Wants=network-online.target
5
+
6
+ [Service]
7
+ Type=simple
8
+ Environment=HOME=__HOME__
9
+ Environment=XDG_RUNTIME_DIR=/run/user/__UID__
10
+ Environment=WAYLAND_DISPLAY=__WAYLAND__
11
+ Environment=DISPLAY=__DISPLAY__
12
+ Environment=DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/__UID__/bus
13
+ ExecStart=__BACKBEAT_ROOT__/bin/plan.sh
@@ -0,0 +1,9 @@
1
+ [Unit]
2
+ Description=Backbeat daily plan at 08:00
3
+
4
+ [Timer]
5
+ OnCalendar=*-*-* 08:00:00
6
+ Persistent=true
7
+
8
+ [Install]
9
+ WantedBy=timers.target
@@ -0,0 +1,13 @@
1
+ [Unit]
2
+ Description=Backbeat evening review (headless pi)
3
+ After=network-online.target
4
+ Wants=network-online.target
5
+
6
+ [Service]
7
+ Type=simple
8
+ Environment=HOME=__HOME__
9
+ Environment=XDG_RUNTIME_DIR=/run/user/__UID__
10
+ Environment=WAYLAND_DISPLAY=__WAYLAND__
11
+ Environment=DISPLAY=__DISPLAY__
12
+ Environment=DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/__UID__/bus
13
+ ExecStart=__BACKBEAT_ROOT__/bin/review.sh
@@ -0,0 +1,9 @@
1
+ [Unit]
2
+ Description=Backbeat evening review at 21:30
3
+
4
+ [Timer]
5
+ OnCalendar=*-*-* 21:30:00
6
+ Persistent=true
7
+
8
+ [Install]
9
+ WantedBy=timers.target