wechat-clawbot 1.1.0 → 1.3.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/README.md +19 -0
- package/README.zh.md +19 -0
- package/assets/icon.svg +7 -0
- package/cordis.patch.yml +4 -0
- package/lib/backlog.d.ts +14 -0
- package/lib/backlog.d.ts.map +1 -1
- package/lib/backlog.js +65 -4
- package/lib/backlog.js.map +1 -1
- package/lib/bridge.d.ts +29 -3
- package/lib/bridge.d.ts.map +1 -1
- package/lib/bridge.js +172 -13
- package/lib/bridge.js.map +1 -1
- package/lib/claude-peer.js +11 -11
- package/lib/claude-peer.js.map +1 -1
- package/lib/client.js +288 -2
- package/lib/config.d.ts +56 -2
- package/lib/config.d.ts.map +1 -1
- package/lib/config.js +55 -0
- package/lib/config.js.map +1 -1
- package/lib/dsh-sessions.d.ts.map +1 -1
- package/lib/dsh-sessions.js +2 -1
- package/lib/dsh-sessions.js.map +1 -1
- package/lib/idle-compact.d.ts +5 -0
- package/lib/idle-compact.d.ts.map +1 -1
- package/lib/idle-compact.js +10 -8
- package/lib/idle-compact.js.map +1 -1
- package/lib/index.d.ts.map +1 -1
- package/lib/index.js +132 -18
- package/lib/index.js.map +1 -1
- package/lib/instance-guard.d.ts.map +1 -1
- package/lib/instance-guard.js +32 -7
- package/lib/instance-guard.js.map +1 -1
- package/lib/localtime.d.ts +4 -3
- package/lib/localtime.d.ts.map +1 -1
- package/lib/localtime.js +7 -6
- package/lib/localtime.js.map +1 -1
- package/lib/mac-alarms.d.ts +168 -0
- package/lib/mac-alarms.d.ts.map +1 -0
- package/lib/mac-alarms.js +610 -0
- package/lib/mac-alarms.js.map +1 -0
- package/lib/mac-calendar.d.ts +239 -0
- package/lib/mac-calendar.d.ts.map +1 -0
- package/lib/mac-calendar.js +1201 -0
- package/lib/mac-calendar.js.map +1 -0
- package/lib/mcp-route.d.ts.map +1 -1
- package/lib/mcp-route.js +8 -2
- package/lib/mcp-route.js.map +1 -1
- package/lib/memory-auto.js +4 -4
- package/lib/memory-auto.js.map +1 -1
- package/lib/memory.d.ts.map +1 -1
- package/lib/memory.js +12 -1
- package/lib/memory.js.map +1 -1
- package/lib/models-route.d.ts +1 -1
- package/lib/pending.d.ts +9 -1
- package/lib/pending.d.ts.map +1 -1
- package/lib/pending.js +18 -1
- package/lib/pending.js.map +1 -1
- package/lib/prompt.d.ts.map +1 -1
- package/lib/prompt.js +12 -11
- package/lib/prompt.js.map +1 -1
- package/lib/secretary.d.ts +60 -0
- package/lib/secretary.d.ts.map +1 -0
- package/lib/secretary.js +281 -0
- package/lib/secretary.js.map +1 -0
- package/lib/time-context.d.ts +57 -0
- package/lib/time-context.d.ts.map +1 -0
- package/lib/time-context.js +90 -0
- package/lib/time-context.js.map +1 -0
- package/lib/tool.js +1 -1
- package/lib/typing.d.ts +0 -1
- package/lib/typing.d.ts.map +1 -1
- package/lib/typing.js +7 -1
- package/lib/typing.js.map +1 -1
- package/native/macos-calendar/main.swift +1006 -0
- package/package.json +4 -1
- package/wechat-clawbot-INSTALL.md +77 -2
|
@@ -0,0 +1,610 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Alarms for the WeChat bot, part of 全天候秘书: urgent reminders in a Reminders
|
|
3
|
+
* list of the bot's own ("规划 闹钟" for a calendar named 规划). Reminders rings
|
|
4
|
+
* an urgent reminder like an alarm on the device Find My uses as the owner's
|
|
5
|
+
* location — usually the iPhone; other devices only show a notification — and
|
|
6
|
+
* iCloud carries it there, so it rings even when WeChat would not let the bot
|
|
7
|
+
* write first (the ~24 h window after the owner's last message).
|
|
8
|
+
*
|
|
9
|
+
* The helper app does the work (native/macos-calendar/main.swift, the alarm
|
|
10
|
+
* commands, through the private ReminderKit). This file is the plugin side:
|
|
11
|
+
* the list, the three tools, and the two buttons on the settings card
|
|
12
|
+
* (一键授权, 测试闹钟).
|
|
13
|
+
*
|
|
14
|
+
* What the Mac cannot do for the owner, which the card says:
|
|
15
|
+
* - The phone has its own permission: Reminders on the iPhone asks to allow
|
|
16
|
+
* urgent alarms only the first time someone marks a reminder urgent there by
|
|
17
|
+
* hand. Until then an alarm is saved and synced but does not ring.
|
|
18
|
+
* - Both Mac permissions (calendar, reminders) are asked for when the switch
|
|
19
|
+
* goes on or 一键授权 is pressed, never later behind the owner's back: a
|
|
20
|
+
* prompt nobody is at the Mac to answer is a feature that silently stops.
|
|
21
|
+
*
|
|
22
|
+
* Planning alarms day by day is not in here on purpose: the owner sets that up
|
|
23
|
+
* with the bot in chat, as a daily 「任务」 reminder with their own rules
|
|
24
|
+
* (prompt.ts, G5).
|
|
25
|
+
*/
|
|
26
|
+
import { createHash } from "node:crypto";
|
|
27
|
+
import { defineTool } from "@deepseek-ai/dsh-tools";
|
|
28
|
+
import { logger } from "./ilink/util/logger.js";
|
|
29
|
+
import { USER_TIME_ZONE, zonedDate, zonedStamp, zonedWeekday } from "./localtime.js";
|
|
30
|
+
import { HELPER_NAME, notOwnerReason, } from "./mac-calendar.js";
|
|
31
|
+
import { cardRequestAllowed } from "./secretary.js";
|
|
32
|
+
const wallFormat = new Intl.DateTimeFormat("en-US", {
|
|
33
|
+
timeZone: USER_TIME_ZONE,
|
|
34
|
+
hourCycle: "h23",
|
|
35
|
+
year: "numeric",
|
|
36
|
+
month: "2-digit",
|
|
37
|
+
day: "2-digit",
|
|
38
|
+
hour: "2-digit",
|
|
39
|
+
minute: "2-digit",
|
|
40
|
+
});
|
|
41
|
+
function wallOf(at) {
|
|
42
|
+
const parts = Object.fromEntries(wallFormat.formatToParts(at).map((p) => [p.type, p.value]));
|
|
43
|
+
return { y: Number(parts.year), m: Number(parts.month), d: Number(parts.day), h: Number(parts.hour) % 24, mi: Number(parts.minute) };
|
|
44
|
+
}
|
|
45
|
+
/** The owner's UTC offset at `at`, in minutes. */
|
|
46
|
+
function offsetAt(at) {
|
|
47
|
+
const minute = Math.floor(at.getTime() / 60_000) * 60_000;
|
|
48
|
+
const w = wallOf(new Date(minute));
|
|
49
|
+
return Math.round((Date.UTC(w.y, w.m - 1, w.d, w.h, w.mi) - minute) / 60_000);
|
|
50
|
+
}
|
|
51
|
+
/** "2026-10-23T07:00" back into its parts. */
|
|
52
|
+
function parseWall(text) {
|
|
53
|
+
const [date, time] = text.split("T");
|
|
54
|
+
const [y, m, d] = date.split("-").map(Number);
|
|
55
|
+
const [h, mi] = time.split(":").map(Number);
|
|
56
|
+
return { y, m, d, h, mi };
|
|
57
|
+
}
|
|
58
|
+
const sameWall = (a, b) => a.y === b.y && a.m === b.m && a.d === b.d && a.h === b.h && a.mi === b.mi;
|
|
59
|
+
/**
|
|
60
|
+
* Every instant a wall-clock time in the owner's zone names, earliest first:
|
|
61
|
+
* none for a time that does not exist there (2026-02-30, or the hour skipped
|
|
62
|
+
* when the clocks go forward), two in the hour repeated when they go back.
|
|
63
|
+
*/
|
|
64
|
+
export function zonedInstants(w) {
|
|
65
|
+
const local = Date.UTC(w.y, w.m - 1, w.d, w.h, w.mi);
|
|
66
|
+
const found = new Set();
|
|
67
|
+
// The offsets in force within a day either side cover both sides of any change.
|
|
68
|
+
for (const probe of [-86_400_000, -43_200_000, 0, 43_200_000, 86_400_000]) {
|
|
69
|
+
const at = local - offsetAt(new Date(local + probe)) * 60_000;
|
|
70
|
+
if (sameWall(wallOf(new Date(at)), w))
|
|
71
|
+
found.add(at);
|
|
72
|
+
}
|
|
73
|
+
return [...found].sort((a, b) => a - b).map((ms) => new Date(ms));
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* The instant a wall-clock time in the owner's zone names, or undefined for a
|
|
77
|
+
* time that does not exist there. In the hour the clocks go back it is the
|
|
78
|
+
* first of the two: Reminders keeps a wall clock and reads it back that way.
|
|
79
|
+
*/
|
|
80
|
+
export function zonedInstant(w) {
|
|
81
|
+
return zonedInstants(w)[0];
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* "2026-10-23 07:00" / "2026-10-23T07:00" (seconds ignored); a date alone is
|
|
85
|
+
* not an alarm time. `repeated` is the second instant of a wall time that
|
|
86
|
+
* happens twice (the hour the clocks go back).
|
|
87
|
+
*/
|
|
88
|
+
export function parseAlarmTime(text) {
|
|
89
|
+
const m = /^\s*(\d{4})-(\d{1,2})-(\d{1,2})[T\s]+(\d{1,2}):(\d{2})(?::\d{2})?\s*$/.exec(text);
|
|
90
|
+
if (m === null)
|
|
91
|
+
return { error: "format" };
|
|
92
|
+
const w = { y: Number(m[1]), m: Number(m[2]), d: Number(m[3]), h: Number(m[4]), mi: Number(m[5]) };
|
|
93
|
+
if (w.m < 1 || w.m > 12 || w.d < 1 || w.d > 31 || w.h > 23 || w.mi > 59)
|
|
94
|
+
return { error: "invalid" };
|
|
95
|
+
const all = zonedInstants(w);
|
|
96
|
+
if (all.length === 0)
|
|
97
|
+
return { error: "invalid" };
|
|
98
|
+
const pad = (n) => String(n).padStart(2, "0");
|
|
99
|
+
return { wall: `${w.y}-${pad(w.m)}-${pad(w.d)}T${pad(w.h)}:${pad(w.mi)}`, at: all[0], ...(all.length > 1 ? { repeated: all[1] } : {}) };
|
|
100
|
+
}
|
|
101
|
+
/** "2026-10-23T07:00": a wall-clock time in the owner's zone, as the helper takes it. */
|
|
102
|
+
export function wallText(at) {
|
|
103
|
+
const w = wallOf(at);
|
|
104
|
+
const pad = (n) => String(n).padStart(2, "0");
|
|
105
|
+
return `${w.y}-${pad(w.m)}-${pad(w.d)}T${pad(w.h)}:${pad(w.mi)}`;
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* When a due time the helper reported happens, as the owner reads it: its own
|
|
109
|
+
* wall clock ("10-23 周五 07:00"), not one worked out again here. macOS and Node
|
|
110
|
+
* ship time-zone rules of their own, and Reminders rings by macOS's.
|
|
111
|
+
*/
|
|
112
|
+
export function dueWhen(due, now = new Date()) {
|
|
113
|
+
const m = /^(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2})(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:\d{2})$/.exec(due);
|
|
114
|
+
if (m === null || m[0].endsWith("Z")) {
|
|
115
|
+
const at = new Date(due);
|
|
116
|
+
return Number.isNaN(at.getTime()) ? "(没有时间)" : alarmWhen(at, now);
|
|
117
|
+
}
|
|
118
|
+
return `${m[1].slice(0, 4) === zonedDate(now).slice(0, 4) ? m[1].slice(5) : m[1]} ${zonedWeekday(m[1])} ${m[2]}`;
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* An instant as the helper takes it: ISO 8601 with the owner's offset
|
|
122
|
+
* ("2026-10-25T01:30:00+01:00"). Unlike a bare wall clock it cannot be read
|
|
123
|
+
* as the other one of two: sent only for a time in the hour the clocks go
|
|
124
|
+
* back. Everything else goes as a wall clock (wallText), so the instant is
|
|
125
|
+
* worked out with macOS's own time-zone rules, the ones Reminders rings by.
|
|
126
|
+
*/
|
|
127
|
+
export function isoAt(at) {
|
|
128
|
+
const w = wallOf(at);
|
|
129
|
+
const off = offsetAt(at);
|
|
130
|
+
const pad = (n) => String(n).padStart(2, "0");
|
|
131
|
+
const abs = Math.abs(off);
|
|
132
|
+
return `${w.y}-${pad(w.m)}-${pad(w.d)}T${pad(w.h)}:${pad(w.mi)}:00${off < 0 ? "-" : "+"}${pad(Math.trunc(abs / 60))}:${pad(abs % 60)}`;
|
|
133
|
+
}
|
|
134
|
+
/** "10-23 周五 07:00"; with the year when it is not this year ("2027-10-24 周日 06:30"), so a year slip shows. */
|
|
135
|
+
export function alarmWhen(at, now = new Date()) {
|
|
136
|
+
const stamp = zonedStamp(at);
|
|
137
|
+
const day = zonedDate(at);
|
|
138
|
+
return `${day.slice(0, 4) === zonedDate(now).slice(0, 4) ? stamp.slice(0, 5) : day} ${zonedWeekday(day)} ${stamp.slice(6)}`;
|
|
139
|
+
}
|
|
140
|
+
/** An empty value means "not given" (some models fill every optional field with ""). */
|
|
141
|
+
function given(value) {
|
|
142
|
+
return typeof value === "string" && value.trim() !== "" ? value.trim() : undefined;
|
|
143
|
+
}
|
|
144
|
+
function isAlarm(value) {
|
|
145
|
+
return typeof value === "object" && value !== null && typeof value.id === "string" && value.id !== "";
|
|
146
|
+
}
|
|
147
|
+
/** The alarms in a helper answer, whatever shape it came in. */
|
|
148
|
+
function alarmsOf(res) {
|
|
149
|
+
return (Array.isArray(res.alarms) ? res.alarms : []).filter(isAlarm).map((a) => ({
|
|
150
|
+
...a, title: typeof a.title === "string" ? a.title : "", urgent: a.urgent === true, completed: a.completed === true,
|
|
151
|
+
...(typeof a.due === "string" ? { due: a.due } : { due: undefined }),
|
|
152
|
+
}));
|
|
153
|
+
}
|
|
154
|
+
const timeOf = (a) => (a.due === undefined ? Number.NaN : new Date(a.due).getTime());
|
|
155
|
+
/** Alarms whose time passed this long ago are marked done (see tidy). */
|
|
156
|
+
const TIDY_AFTER_MS = 2 * 3_600_000;
|
|
157
|
+
/** The alarm list and what goes in it, for the tools and the card alike. */
|
|
158
|
+
export class AlarmService {
|
|
159
|
+
helper;
|
|
160
|
+
baseName;
|
|
161
|
+
/** Adds run one at a time: the look for the same alarm and the add must not interleave. */
|
|
162
|
+
adding = Promise.resolve();
|
|
163
|
+
constructor(helper,
|
|
164
|
+
/** The dedicated calendar's name, read live (hot field). */
|
|
165
|
+
baseName) {
|
|
166
|
+
this.helper = helper;
|
|
167
|
+
this.baseName = baseName;
|
|
168
|
+
}
|
|
169
|
+
/** "规划 闹钟": the name a new list gets, after the bot's own calendar. Empty before that has a name. */
|
|
170
|
+
listName() {
|
|
171
|
+
const base = this.baseName().trim();
|
|
172
|
+
return base === "" ? "" : `${base} 闹钟`;
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* The list's name as Reminders has it. Once made, the list is the one
|
|
176
|
+
* remembered by id, even after the calendar is renamed on the card: a new
|
|
177
|
+
* list would strand the alarms already set in the old one.
|
|
178
|
+
*/
|
|
179
|
+
shownName() {
|
|
180
|
+
return this.helper.alarmList()?.name || this.listName();
|
|
181
|
+
}
|
|
182
|
+
/** A helper failure as a sentence the owner (or the model) can act on; `op` is what was being done. */
|
|
183
|
+
explain(res, op = "list") {
|
|
184
|
+
const code = String(res.code ?? "");
|
|
185
|
+
const error = String(res.error ?? "");
|
|
186
|
+
if (res.pending === true) {
|
|
187
|
+
return `正在等 Mac 上的授权:屏幕上有「${HELPER_NAME}」的授权窗口,点「允许」之后再试。`;
|
|
188
|
+
}
|
|
189
|
+
if (code === "reminders_not_authorized") {
|
|
190
|
+
if (error === "notDetermined") {
|
|
191
|
+
return "还没授权「提醒事项」,闹钟设不了:到 Mac 前,在设置卡片「全天候秘书」上点「一键授权」,在弹出的窗口里点「允许」。";
|
|
192
|
+
}
|
|
193
|
+
if (error === "denied")
|
|
194
|
+
return `「提醒事项」的授权被拒绝了:在 Mac 的 系统设置 → 隐私与安全性 → 提醒事项 里打开「${HELPER_NAME}」。`;
|
|
195
|
+
return `「${HELPER_NAME}」没有「提醒事项」的完全访问权限(${error}):在 Mac 的 系统设置 → 隐私与安全性 → 提醒事项 里打开它。`;
|
|
196
|
+
}
|
|
197
|
+
if (code === "bad_request" && /unknown command/.test(error)) {
|
|
198
|
+
return `Mac 上的「${HELPER_NAME}」还是旧版,没有闹钟功能:到 Mac 前在设置卡片「全天候秘书」上点「一键授权」更新它(会再弹出两次授权,都点「允许」)。`;
|
|
199
|
+
}
|
|
200
|
+
if (code === "reminderkit_missing") {
|
|
201
|
+
return `这台 Mac 的「提醒事项」没有紧急提醒(要 macOS 26 或更新;系统更新后也可能变了),闹钟用不了;日历不受影响。${error ? `(${error})` : ""}`;
|
|
202
|
+
}
|
|
203
|
+
if (code === "no_icloud")
|
|
204
|
+
return "「提醒事项」里没有登录 iCloud:闹钟要靠 iCloud 才能到 iPhone 上响。";
|
|
205
|
+
if (code === "no_urgent")
|
|
206
|
+
return "这个 iCloud 账户不支持紧急提醒,闹钟设不了。";
|
|
207
|
+
if (code === "past")
|
|
208
|
+
return "这个时间已经过了。";
|
|
209
|
+
if (code === "ambiguous")
|
|
210
|
+
return "这个钟点正赶上夏令时结束、时钟往回拨的那一小时(一天里有两次),闹钟只能定在第一次:换一个这一小时以外的时间。";
|
|
211
|
+
if (code === "no_alarm")
|
|
212
|
+
return "这个闹钟已经不在清单里了(可能在 iPhone 上删掉或完成了):先用 alarm_list 再看一下。";
|
|
213
|
+
if (code === "timeout" || code === "no_response") {
|
|
214
|
+
if (op === "set")
|
|
215
|
+
return `${error}。闹钟可能已经设上了:先用 alarm_list 看一下;再设一次也没关系,同一时间、同一标题的不会设两个。`;
|
|
216
|
+
if (op === "cancel")
|
|
217
|
+
return `${error}。闹钟可能已经取消了:先用 alarm_list 看一下,再决定要不要重试。`;
|
|
218
|
+
return `${error},稍后再试。`;
|
|
219
|
+
}
|
|
220
|
+
if (code === "deadline")
|
|
221
|
+
return "这次太慢,到时限前停下了,什么都没改,可以再试一次。";
|
|
222
|
+
if (code === "stopped")
|
|
223
|
+
return "这一轮被停了,闹钟没有动。";
|
|
224
|
+
return `闹钟操作失败:${error || code || "未知原因"}`;
|
|
225
|
+
}
|
|
226
|
+
async run(request, signal) {
|
|
227
|
+
let res;
|
|
228
|
+
try {
|
|
229
|
+
res = await this.helper.call(request, 30_000, signal);
|
|
230
|
+
}
|
|
231
|
+
catch (err) {
|
|
232
|
+
return { ok: false, code: "error", error: (err instanceof Error ? err.message : String(err)).slice(0, 300) };
|
|
233
|
+
}
|
|
234
|
+
// The helper checks the permission before ReminderKit. On a macOS without urgent
|
|
235
|
+
// reminders nothing ever asks for Reminders access (一键授权 skips it), so "not
|
|
236
|
+
// authorized" there is not something 一键授权 or System Settings could fix.
|
|
237
|
+
if (res.code === "reminders_not_authorized" && res.pending !== true) {
|
|
238
|
+
const status = await this.helper.status().catch(() => undefined);
|
|
239
|
+
if (status?.alarms === "unsupported")
|
|
240
|
+
return { ok: false, code: "reminderkit_missing", error: "" };
|
|
241
|
+
}
|
|
242
|
+
return res;
|
|
243
|
+
}
|
|
244
|
+
/** The list, made on first use and then kept by id. */
|
|
245
|
+
async ensureList(signal) {
|
|
246
|
+
const name = this.listName();
|
|
247
|
+
if (name === "")
|
|
248
|
+
return { ok: false, message: "专用日历还没起名字:在设置卡片「全天候秘书」里填上再试。" };
|
|
249
|
+
const known = this.helper.alarmList();
|
|
250
|
+
// By id, whatever the card's name is now (see shownName). The helper falls
|
|
251
|
+
// back to the name, then to a new list, when that one was deleted.
|
|
252
|
+
const res = await this.run({ cmd: "ensureAlarmList", name, ...(known !== null ? { knownId: known.id } : {}) }, signal);
|
|
253
|
+
if (!res.ok)
|
|
254
|
+
return { ok: false, message: this.explain(res) };
|
|
255
|
+
const list = res.list;
|
|
256
|
+
if (list === undefined || typeof list.id !== "string" || list.id === "") {
|
|
257
|
+
return { ok: false, message: "闹钟操作失败:小程序的回答不完整(没有清单),可能要在设置卡片上点「一键授权」更新它。" };
|
|
258
|
+
}
|
|
259
|
+
const record = {
|
|
260
|
+
name: typeof list.name === "string" && list.name !== "" ? list.name : name,
|
|
261
|
+
id: list.id,
|
|
262
|
+
account: typeof list.account === "string" ? list.account : "",
|
|
263
|
+
};
|
|
264
|
+
this.helper.rememberAlarmList(record);
|
|
265
|
+
if (res.created === true)
|
|
266
|
+
logger.info(`alarms: created the reminders list 「${record.name}」 in ${record.account || "iCloud"}`);
|
|
267
|
+
if (res.adopted === true)
|
|
268
|
+
logger.info(`alarms: using the existing reminders list 「${record.name}」`);
|
|
269
|
+
return { ok: true, value: { ...record, created: res.created === true, adopted: res.adopted === true } };
|
|
270
|
+
}
|
|
271
|
+
/**
|
|
272
|
+
* Run commands on the list; a list that has disappeared is made again, once.
|
|
273
|
+
* `step` gets the list's id and answers with the helper's response.
|
|
274
|
+
*/
|
|
275
|
+
async onList(step, signal) {
|
|
276
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
277
|
+
const list = await this.ensureList(signal);
|
|
278
|
+
if (!list.ok)
|
|
279
|
+
return list;
|
|
280
|
+
const { res, op, value } = await step(list.value.id);
|
|
281
|
+
if (res.ok)
|
|
282
|
+
return { ok: true, value: { res, ...(value === undefined ? {} : { value }), listId: list.value.id } };
|
|
283
|
+
if (res.code !== "no_list" || attempt > 0)
|
|
284
|
+
return { ok: false, message: this.explain(res, op) };
|
|
285
|
+
}
|
|
286
|
+
return { ok: false, message: "闹钟清单找不到了" };
|
|
287
|
+
}
|
|
288
|
+
/**
|
|
289
|
+
* Alarms that rang a couple of hours ago stay open in Reminders (ringing
|
|
290
|
+
* does not complete them) and would pile up there as overdue: mark them
|
|
291
|
+
* done, in the background. Only the alarms this plugin set itself: a list
|
|
292
|
+
* adopted by its name may also hold the owner's own to-dos, all-day ones, or
|
|
293
|
+
* one the owner made repeat — none of them the bot's to tick off. An older
|
|
294
|
+
* helper without the command just skips it.
|
|
295
|
+
*/
|
|
296
|
+
tidy(alarms, listId) {
|
|
297
|
+
const cutoff = Date.now() - TIDY_AFTER_MS;
|
|
298
|
+
const ours = this.helper.createdAlarms();
|
|
299
|
+
const ids = alarms.filter((a) => !a.completed && a.urgent && ours.has(a.id) && timeOf(a) < cutoff).map((a) => a.id);
|
|
300
|
+
if (ids.length === 0)
|
|
301
|
+
return;
|
|
302
|
+
void this.run({ cmd: "alarmComplete", listId, ids }).then((res) => {
|
|
303
|
+
if (!res.ok)
|
|
304
|
+
return;
|
|
305
|
+
this.helper.forgetCreatedAlarms(ids);
|
|
306
|
+
logger.info(`alarms: marked ${String(res.completed ?? ids.length)} alarm(s) that rang hours ago as done`);
|
|
307
|
+
});
|
|
308
|
+
}
|
|
309
|
+
/**
|
|
310
|
+
* Set one alarm, unless the same one (same minute, same title) is already
|
|
311
|
+
* set: a retry after a timeout, or a routine that runs twice, then finds it
|
|
312
|
+
* instead of ringing the owner twice.
|
|
313
|
+
*/
|
|
314
|
+
add(input, signal) {
|
|
315
|
+
const run = this.adding.then(() => this.addNow(input, signal));
|
|
316
|
+
this.adding = run.catch(() => undefined);
|
|
317
|
+
return run;
|
|
318
|
+
}
|
|
319
|
+
async addNow(input, signal) {
|
|
320
|
+
let seen = [];
|
|
321
|
+
let existing = false;
|
|
322
|
+
const done = await this.onList(async (listId) => {
|
|
323
|
+
const listed = await this.run({ cmd: "alarms", listId }, signal);
|
|
324
|
+
if (!listed.ok)
|
|
325
|
+
return { res: listed, op: "list" };
|
|
326
|
+
seen = alarmsOf(listed);
|
|
327
|
+
// Compared by the wall clock the helper reports: an instant worked out here may differ from macOS's.
|
|
328
|
+
const same = seen.find((a) => !a.completed && a.due?.slice(0, 16) === input.wall && a.title === input.title);
|
|
329
|
+
if (same !== undefined) {
|
|
330
|
+
existing = true;
|
|
331
|
+
return { res: listed, op: "list", value: same };
|
|
332
|
+
}
|
|
333
|
+
const res = await this.run({
|
|
334
|
+
cmd: "alarmAdd", listId, due: input.repeated === true ? isoAt(input.at) : input.wall, title: input.title,
|
|
335
|
+
...(input.notes ? { notes: input.notes } : {}),
|
|
336
|
+
}, signal);
|
|
337
|
+
return { res, op: "set", ...(isAlarm(res.alarm) ? { value: res.alarm } : {}) };
|
|
338
|
+
}, signal);
|
|
339
|
+
if (!done.ok)
|
|
340
|
+
return done;
|
|
341
|
+
this.tidy(seen, done.value.listId);
|
|
342
|
+
const alarm = done.value.value;
|
|
343
|
+
if (alarm === undefined)
|
|
344
|
+
return { ok: false, message: "闹钟可能设上了,但小程序的回答不完整:先用 alarm_list 看一下。" };
|
|
345
|
+
const value = {
|
|
346
|
+
...alarm, title: typeof alarm.title === "string" ? alarm.title : input.title,
|
|
347
|
+
urgent: alarm.urgent === true, completed: alarm.completed === true,
|
|
348
|
+
};
|
|
349
|
+
if (existing)
|
|
350
|
+
return { ok: true, value: { ...value, existing: true } };
|
|
351
|
+
this.helper.rememberCreatedAlarm(value.id);
|
|
352
|
+
logger.info("alarm_set: one alarm added");
|
|
353
|
+
return { ok: true, value };
|
|
354
|
+
}
|
|
355
|
+
async list(signal) {
|
|
356
|
+
const done = await this.onList(async (listId) => ({ res: await this.run({ cmd: "alarms", listId }, signal), op: "list" }), signal);
|
|
357
|
+
if (!done.ok)
|
|
358
|
+
return done;
|
|
359
|
+
const alarms = alarmsOf(done.value.res);
|
|
360
|
+
this.tidy(alarms, done.value.listId);
|
|
361
|
+
return { ok: true, value: alarms };
|
|
362
|
+
}
|
|
363
|
+
async remove(id, signal) {
|
|
364
|
+
const done = await this.onList(async (listId) => ({ res: await this.run({ cmd: "alarmDelete", listId, id }, signal), op: "cancel" }), signal);
|
|
365
|
+
if (!done.ok)
|
|
366
|
+
return done;
|
|
367
|
+
logger.info("alarm_cancel: one alarm removed");
|
|
368
|
+
const gone = done.value.res.alarm;
|
|
369
|
+
return { ok: true, value: isAlarm(gone) ? gone : { id, title: "", urgent: false, completed: false } };
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
const SUMMARY_SCHEMA = {
|
|
373
|
+
type: "object",
|
|
374
|
+
additionalProperties: false,
|
|
375
|
+
properties: { ok: { type: "boolean", required: true }, summary: { type: "string", required: true } },
|
|
376
|
+
};
|
|
377
|
+
const HANDLE_LIMIT = 500;
|
|
378
|
+
export function registerAlarmTools(agentCtx, deps) {
|
|
379
|
+
const alarms = deps.alarms;
|
|
380
|
+
/** Alarms shown this process lifetime, by the short handle the model uses. */
|
|
381
|
+
const handles = new Map();
|
|
382
|
+
const remember = (a) => {
|
|
383
|
+
const digest = createHash("sha1").update(a.id).digest("hex");
|
|
384
|
+
let len = 8;
|
|
385
|
+
let tag = `a${digest.slice(0, len)}`;
|
|
386
|
+
while (handles.has(tag) && handles.get(tag).id !== a.id && len < digest.length)
|
|
387
|
+
tag = `a${digest.slice(0, ++len)}`;
|
|
388
|
+
handles.delete(tag);
|
|
389
|
+
handles.set(tag, { id: a.id, title: a.title, ...(a.due === undefined ? {} : { due: a.due }) });
|
|
390
|
+
while (handles.size > HANDLE_LIMIT)
|
|
391
|
+
handles.delete(handles.keys().next().value);
|
|
392
|
+
return tag;
|
|
393
|
+
};
|
|
394
|
+
const line = (a) => {
|
|
395
|
+
const when = a.due === undefined ? "(没有时间)" : dueWhen(a.due);
|
|
396
|
+
return `${when}「${a.title || "(无标题)"}」${a.urgent ? "" : "(不是紧急提醒,只会通知、不会像闹钟一样响)"} #${remember(a)}`;
|
|
397
|
+
};
|
|
398
|
+
agentCtx.tools.register(defineTool({
|
|
399
|
+
name: "alarm_set",
|
|
400
|
+
description: "Set an alarm for the owner: an urgent reminder in the bot's own alarm list in the Reminders app. At that time it "
|
|
401
|
+
+ "rings like an alarm on the device Find My uses as the owner's location (usually their iPhone), and it does not "
|
|
402
|
+
+ "go through WeChat, so it rings even when a WeChat message could not reach them. Use it when the owner asks for "
|
|
403
|
+
+ "an alarm or a wake-up call (闹钟, 叫醒, 定个闹钟), or wants something at an exact time to ring rather than just a "
|
|
404
|
+
+ "message (a flight, an exam). A plain \"remind me to…\" stays a WeChat reminder (schedule_create); a block of "
|
|
405
|
+
+ "time goes in the calendar. The same time with the same title is never set twice (it answers that it is already "
|
|
406
|
+
+ "set), so retrying, or a routine that plans alarms, can simply set what it wants. To move an alarm, set the new "
|
|
407
|
+
+ "time first, then cancel the old one. Say back the time it will ring, as the result gives it. If the owner says "
|
|
408
|
+
+ "one did not ring: Reminders on that iPhone must be allowed to ring urgent reminders (it asks the first time a "
|
|
409
|
+
+ "reminder is marked urgent there by hand), and Find My's My Location must be that iPhone.",
|
|
410
|
+
parameters: {
|
|
411
|
+
time: { type: "string", required: true, description: "When it rings: a date and a time of day in the owner's time zone, e.g. 2026-10-23 07:00." },
|
|
412
|
+
title: { type: "string", description: "What it is for, shown when it rings, e.g. 起床. Default 闹钟." },
|
|
413
|
+
note: { type: "string", description: "Details shown with it, if any." },
|
|
414
|
+
},
|
|
415
|
+
output: { schema: SUMMARY_SCHEMA, render: (_args, value) => [{ type: "text", text: value.summary }] },
|
|
416
|
+
async execute(args, exec) {
|
|
417
|
+
const refused = notOwnerReason(deps, "闹钟");
|
|
418
|
+
if (refused !== undefined)
|
|
419
|
+
return { ok: false, summary: refused };
|
|
420
|
+
const raw = args;
|
|
421
|
+
const time = given(raw.time);
|
|
422
|
+
if (time === undefined)
|
|
423
|
+
return { ok: false, summary: "要给出响的时间:日期加几点几分,例如 2026-10-23 07:00。" };
|
|
424
|
+
const parsed = parseAlarmTime(time);
|
|
425
|
+
if ("error" in parsed) {
|
|
426
|
+
return {
|
|
427
|
+
ok: false,
|
|
428
|
+
summary: parsed.error === "format"
|
|
429
|
+
? `看不懂「${time}」:要写成 2026-10-23 07:00 这样,日期加几点几分(闹钟一定要有钟点)。`
|
|
430
|
+
: `「${time}」不是一个真实存在的时间(日期不存在,或正赶上夏令时跳过的那一小时)。`,
|
|
431
|
+
};
|
|
432
|
+
}
|
|
433
|
+
const soon = Date.now() + 30_000;
|
|
434
|
+
if (parsed.repeated !== undefined && parsed.at.getTime() <= soon && parsed.repeated.getTime() > soon) {
|
|
435
|
+
// Reminders keeps a wall clock, and reads a repeated one as the first: the second cannot be set.
|
|
436
|
+
return { ok: false, summary: `${parsed.wall.slice(11)} 正赶上夏令时结束、时钟往回拨的那一小时,今天有两次,第一次已经过了;闹钟只能定在第一次,换一个这一小时以外的时间。` };
|
|
437
|
+
}
|
|
438
|
+
if (parsed.at.getTime() <= soon) {
|
|
439
|
+
return { ok: false, summary: `${alarmWhen(parsed.at)} 已经过了(或离现在不到半分钟):给一个以后的时间。` };
|
|
440
|
+
}
|
|
441
|
+
if (parsed.at.getTime() > Date.now() + 400 * 86_400_000) {
|
|
442
|
+
return { ok: false, summary: "闹钟最多设到一年多以后;更远的事先记进日历。" };
|
|
443
|
+
}
|
|
444
|
+
const title = given(raw.title) ?? "闹钟";
|
|
445
|
+
const note = given(raw.note);
|
|
446
|
+
const res = await alarms.add({
|
|
447
|
+
at: parsed.at, wall: parsed.wall, repeated: parsed.repeated !== undefined, title, ...(note === undefined ? {} : { notes: note }),
|
|
448
|
+
}, exec?.signal);
|
|
449
|
+
if (!res.ok)
|
|
450
|
+
return { ok: false, summary: res.message };
|
|
451
|
+
const a = res.value;
|
|
452
|
+
if (a.existing === true)
|
|
453
|
+
return { ok: true, summary: `这个闹钟已经设过了:${line(a)},没有再设一个。` };
|
|
454
|
+
return {
|
|
455
|
+
ok: true,
|
|
456
|
+
summary: `已设闹钟:${line(a)},在「${alarms.shownName()}」清单里。`
|
|
457
|
+
+ (a.urgent ? "" : "\n注意:没能设成紧急提醒,到点只会弹通知;把这个告诉机主。"),
|
|
458
|
+
};
|
|
459
|
+
},
|
|
460
|
+
}));
|
|
461
|
+
agentCtx.tools.register(defineTool({
|
|
462
|
+
name: "alarm_list",
|
|
463
|
+
description: "The alarms in the bot's alarm list that have not rung yet, soonest first, each with a handle like #a3f9a2b1 for "
|
|
464
|
+
+ "alarm_cancel (also any without a time, and any whose time passed but that are still open). Check it before "
|
|
465
|
+
+ "changing alarms and to answer which alarms are set — never from memory.",
|
|
466
|
+
parameters: {},
|
|
467
|
+
output: { schema: SUMMARY_SCHEMA, render: (_args, value) => [{ type: "text", text: value.summary }] },
|
|
468
|
+
async execute(_args, exec) {
|
|
469
|
+
const refused = notOwnerReason(deps, "闹钟");
|
|
470
|
+
if (refused !== undefined)
|
|
471
|
+
return { ok: false, summary: refused };
|
|
472
|
+
const res = await alarms.list(exec?.signal);
|
|
473
|
+
if (!res.ok)
|
|
474
|
+
return { ok: false, summary: res.message };
|
|
475
|
+
const now = Date.now();
|
|
476
|
+
const open = res.value.filter((a) => !a.completed);
|
|
477
|
+
const upcoming = open.filter((a) => timeOf(a) > now).sort((x, y) => timeOf(x) - timeOf(y));
|
|
478
|
+
const timeless = open.filter((a) => Number.isNaN(timeOf(a)));
|
|
479
|
+
const passed = open.filter((a) => timeOf(a) <= now).sort((x, y) => timeOf(y) - timeOf(x));
|
|
480
|
+
const shown = upcoming.slice(0, 30);
|
|
481
|
+
const lines = [
|
|
482
|
+
upcoming.length === 0
|
|
483
|
+
? `「${alarms.shownName()}」里没有还没响的闹钟。`
|
|
484
|
+
: `还没响的闹钟(${upcoming.length} 个):`,
|
|
485
|
+
...shown.map((a) => `• ${line(a)}`),
|
|
486
|
+
];
|
|
487
|
+
if (upcoming.length > shown.length)
|
|
488
|
+
lines.push(`(还有 ${upcoming.length - shown.length} 个更晚的没列出)`);
|
|
489
|
+
if (timeless.length > 0) {
|
|
490
|
+
lines.push(`没有时间、不会响的(${timeless.length} 个):`, ...timeless.slice(0, 10).map((a) => `• ${line(a)}`));
|
|
491
|
+
}
|
|
492
|
+
if (passed.length > 0) {
|
|
493
|
+
lines.push(`时间已经过了、还没勾掉的(${passed.length} 个):`, ...passed.slice(0, 10).map((a) => `• ${line(a)}`));
|
|
494
|
+
}
|
|
495
|
+
return { ok: true, summary: lines.join("\n") };
|
|
496
|
+
},
|
|
497
|
+
}));
|
|
498
|
+
agentCtx.tools.register(defineTool({
|
|
499
|
+
name: "alarm_cancel",
|
|
500
|
+
description: "Cancel one alarm, named by its handle (#a…) from alarm_list or alarm_set. To move an alarm, set the new one "
|
|
501
|
+
+ "first, then cancel the old one.",
|
|
502
|
+
parameters: {
|
|
503
|
+
alarm: { type: "string", required: true, description: "The handle, e.g. #a3f9a2b1." },
|
|
504
|
+
},
|
|
505
|
+
output: { schema: SUMMARY_SCHEMA, render: (_args, value) => [{ type: "text", text: value.summary }] },
|
|
506
|
+
async execute(args, exec) {
|
|
507
|
+
const refused = notOwnerReason(deps, "闹钟");
|
|
508
|
+
if (refused !== undefined)
|
|
509
|
+
return { ok: false, summary: refused };
|
|
510
|
+
const tag = (given(args.alarm) ?? "").replace(/^[##]/, "").toLowerCase();
|
|
511
|
+
const known = handles.get(tag);
|
|
512
|
+
if (known === undefined)
|
|
513
|
+
return { ok: false, summary: `不认识 #${tag}:先用 alarm_list 看一下,用那里给的编号。` };
|
|
514
|
+
const res = await alarms.remove(known.id, exec?.signal);
|
|
515
|
+
if (!res.ok)
|
|
516
|
+
return { ok: false, summary: res.message };
|
|
517
|
+
handles.delete(tag);
|
|
518
|
+
return { ok: true, summary: `已取消闹钟:${known.due === undefined ? "" : dueWhen(known.due)}「${known.title}」。` };
|
|
519
|
+
},
|
|
520
|
+
}));
|
|
521
|
+
}
|
|
522
|
+
export const AUTHORIZE_PATH = "/plugins/clawbot/secretary/authorize";
|
|
523
|
+
export const TEST_ALARM_PATH = "/plugins/clawbot/secretary/test-alarm";
|
|
524
|
+
/** Two minutes from now at least, on a whole minute. */
|
|
525
|
+
export function testAlarmTime(now = new Date()) {
|
|
526
|
+
return new Date(Math.ceil((now.getTime() + 120_000) / 60_000) * 60_000);
|
|
527
|
+
}
|
|
528
|
+
/** What the test alarm says when it rings: what to check on the phone if it did not. */
|
|
529
|
+
export const TEST_ALARM_NOTE = "像闹钟一样响了,就说明一切就绪,这条可以删掉。没响的话看 iPhone:①「设置 → 你的名字 → 查找 → 我的位置」"
|
|
530
|
+
+ "要是这台 iPhone(紧急提醒只在这台设备上像闹钟一样响);②在「提醒事项」里手动把一条提醒设成紧急一次,允许弹出的授权。";
|
|
531
|
+
/** A test alarm at most this often: each one rings the owner's phone. */
|
|
532
|
+
const TEST_ALARM_EVERY_MS = 60_000;
|
|
533
|
+
let lastTestAlarmAt = 0;
|
|
534
|
+
/**
|
|
535
|
+
* POST /plugins/clawbot/secretary/authorize — 一键授权: replace an outdated
|
|
536
|
+
* helper and put up every permission prompt still open (calendar, reminders),
|
|
537
|
+
* while the owner is at the Mac. Answers at once with what it is doing (the
|
|
538
|
+
* plan); the card follows the status.
|
|
539
|
+
*
|
|
540
|
+
* POST /plugins/clawbot/secretary/test-alarm — 测试闹钟: an urgent reminder two
|
|
541
|
+
* minutes out, so the owner hears the phone ring before walking away.
|
|
542
|
+
*
|
|
543
|
+
* Plugin routes are not behind DSH's login cookie, so both take only what the
|
|
544
|
+
* card itself sends (see cardRequestAllowed).
|
|
545
|
+
*/
|
|
546
|
+
export async function handleCardRoute(kind, req, res, deps) {
|
|
547
|
+
const reply = (status, body) => {
|
|
548
|
+
res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
|
|
549
|
+
res.end(JSON.stringify(body));
|
|
550
|
+
};
|
|
551
|
+
if ((req.method ?? "GET") !== "POST")
|
|
552
|
+
return reply(405, { ok: false, message: "use POST" });
|
|
553
|
+
if (!cardRequestAllowed(req))
|
|
554
|
+
return reply(403, { ok: false, message: "只接受设置卡片发来的请求" });
|
|
555
|
+
if (process.platform !== "darwin")
|
|
556
|
+
return reply(400, { ok: false, message: "只支持 macOS" });
|
|
557
|
+
if (!deps.enabled())
|
|
558
|
+
return reply(409, { ok: false, message: "先打开「全天候秘书」" });
|
|
559
|
+
if (kind === "authorize") {
|
|
560
|
+
let plan;
|
|
561
|
+
try {
|
|
562
|
+
plan = await deps.helper.authorizePlan();
|
|
563
|
+
}
|
|
564
|
+
catch (err) {
|
|
565
|
+
plan = { ask: [], denied: [], error: (err instanceof Error ? err.message : String(err)).slice(0, 240) };
|
|
566
|
+
}
|
|
567
|
+
// A helper that does not answer may just need its update: let the forced round try.
|
|
568
|
+
const started = plan.build !== undefined || plan.ask.length > 0 || plan.error !== undefined;
|
|
569
|
+
if (started) {
|
|
570
|
+
void deps.helper.prepare(true).catch((err) => logger.warn(`calendar: 一键授权 failed: ${(err instanceof Error ? err.message : String(err)).slice(0, 300)}`));
|
|
571
|
+
}
|
|
572
|
+
deps.helper.invalidateStatus();
|
|
573
|
+
logger.info(`calendar: 一键授权 pressed on the settings card (${started ? [plan.build, ...plan.ask].filter(Boolean).join(", ") || "retrying" : "nothing to ask"})`);
|
|
574
|
+
return reply(200, { ok: true, started, plan });
|
|
575
|
+
}
|
|
576
|
+
const wait = lastTestAlarmAt + TEST_ALARM_EVERY_MS - Date.now();
|
|
577
|
+
if (wait > 0)
|
|
578
|
+
return reply(429, { ok: false, message: `刚设过一个测试闹钟,${Math.ceil(wait / 1000)} 秒后再试` });
|
|
579
|
+
// Claimed before waiting on the helper: two presses at once must not both ring.
|
|
580
|
+
const claimed = Date.now();
|
|
581
|
+
lastTestAlarmAt = claimed;
|
|
582
|
+
const at = testAlarmTime();
|
|
583
|
+
const wall = wallText(at);
|
|
584
|
+
if (zonedInstants(parseWall(wall)).length > 1) {
|
|
585
|
+
// Two minutes from now falls in the hour the clocks go back: a wall time there names two instants.
|
|
586
|
+
lastTestAlarmAt = 0;
|
|
587
|
+
return reply(200, { ok: false, message: "时钟正在往回拨(夏令时结束):过了这一小时再点「测试闹钟」" });
|
|
588
|
+
}
|
|
589
|
+
const made = await deps.alarms.add({ at, wall, title: "全天候秘书测试闹钟", notes: TEST_ALARM_NOTE });
|
|
590
|
+
if (!made.ok) {
|
|
591
|
+
if (lastTestAlarmAt === claimed)
|
|
592
|
+
lastTestAlarmAt = 0;
|
|
593
|
+
return reply(200, { ok: false, message: made.message });
|
|
594
|
+
}
|
|
595
|
+
const due = made.value.due === undefined ? at : new Date(made.value.due);
|
|
596
|
+
return reply(200, {
|
|
597
|
+
ok: true,
|
|
598
|
+
at: zonedStamp(Number.isNaN(due.getTime()) ? at : due).slice(6),
|
|
599
|
+
list: deps.alarms.shownName(),
|
|
600
|
+
urgent: made.value.urgent,
|
|
601
|
+
});
|
|
602
|
+
}
|
|
603
|
+
export function registerCardRoutes(ctx, deps) {
|
|
604
|
+
ctx.inject(["webServer"], (scoped) => {
|
|
605
|
+
const server = scoped.webServer;
|
|
606
|
+
scoped.effect(() => server.register({ kind: "exact", path: AUTHORIZE_PATH, handler: (req, res) => handleCardRoute("authorize", req, res, deps) }), "clawbot: secretary authorize route");
|
|
607
|
+
scoped.effect(() => server.register({ kind: "exact", path: TEST_ALARM_PATH, handler: (req, res) => handleCardRoute("test", req, res, deps) }), "clawbot: secretary test-alarm route");
|
|
608
|
+
});
|
|
609
|
+
}
|
|
610
|
+
//# sourceMappingURL=mac-alarms.js.map
|