wechat-clawbot 1.2.0 → 1.3.1

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.
Files changed (73) hide show
  1. package/README.md +26 -13
  2. package/README.zh.md +26 -13
  3. package/assets/icon.svg +7 -0
  4. package/cordis.patch.yml +4 -0
  5. package/lib/backlog.d.ts +14 -0
  6. package/lib/backlog.d.ts.map +1 -1
  7. package/lib/backlog.js +65 -4
  8. package/lib/backlog.js.map +1 -1
  9. package/lib/bridge.d.ts +6 -3
  10. package/lib/bridge.d.ts.map +1 -1
  11. package/lib/bridge.js +44 -11
  12. package/lib/bridge.js.map +1 -1
  13. package/lib/claude-peer.js +11 -11
  14. package/lib/claude-peer.js.map +1 -1
  15. package/lib/client.js +461 -85
  16. package/lib/codex-rpc.js +1 -1
  17. package/lib/config.d.ts +30 -7
  18. package/lib/config.d.ts.map +1 -1
  19. package/lib/config.js +17 -3
  20. package/lib/config.js.map +1 -1
  21. package/lib/idle-compact.d.ts +5 -0
  22. package/lib/idle-compact.d.ts.map +1 -1
  23. package/lib/idle-compact.js +10 -8
  24. package/lib/idle-compact.js.map +1 -1
  25. package/lib/index.d.ts.map +1 -1
  26. package/lib/index.js +78 -28
  27. package/lib/index.js.map +1 -1
  28. package/lib/localtime.d.ts +4 -3
  29. package/lib/localtime.d.ts.map +1 -1
  30. package/lib/localtime.js +7 -6
  31. package/lib/localtime.js.map +1 -1
  32. package/lib/mac-alarms.d.ts +168 -0
  33. package/lib/mac-alarms.d.ts.map +1 -0
  34. package/lib/mac-alarms.js +612 -0
  35. package/lib/mac-alarms.js.map +1 -0
  36. package/lib/mac-calendar.d.ts +126 -11
  37. package/lib/mac-calendar.d.ts.map +1 -1
  38. package/lib/mac-calendar.js +418 -99
  39. package/lib/mac-calendar.js.map +1 -1
  40. package/lib/mcp-route.d.ts.map +1 -1
  41. package/lib/mcp-route.js +8 -2
  42. package/lib/mcp-route.js.map +1 -1
  43. package/lib/mcp-server.js +1 -1
  44. package/lib/memory-auto.js +4 -4
  45. package/lib/memory-auto.js.map +1 -1
  46. package/lib/models-route.d.ts +1 -1
  47. package/lib/pending.d.ts +9 -1
  48. package/lib/pending.d.ts.map +1 -1
  49. package/lib/pending.js +18 -1
  50. package/lib/pending.js.map +1 -1
  51. package/lib/permissions.d.ts +164 -0
  52. package/lib/permissions.d.ts.map +1 -0
  53. package/lib/permissions.js +549 -0
  54. package/lib/permissions.js.map +1 -0
  55. package/lib/prompt.d.ts.map +1 -1
  56. package/lib/prompt.js +12 -11
  57. package/lib/prompt.js.map +1 -1
  58. package/lib/secretary.d.ts +42 -9
  59. package/lib/secretary.d.ts.map +1 -1
  60. package/lib/secretary.js +142 -36
  61. package/lib/secretary.js.map +1 -1
  62. package/lib/time-context.d.ts +57 -0
  63. package/lib/time-context.d.ts.map +1 -0
  64. package/lib/time-context.js +90 -0
  65. package/lib/time-context.js.map +1 -0
  66. package/lib/tool.js +1 -1
  67. package/lib/typing.d.ts +0 -1
  68. package/lib/typing.d.ts.map +1 -1
  69. package/lib/typing.js +7 -1
  70. package/lib/typing.js.map +1 -1
  71. package/native/macos-calendar/main.swift +476 -13
  72. package/package.json +7 -6
  73. package/wechat-clawbot-INSTALL.md +64 -40
@@ -16,7 +16,9 @@
16
16
  * process: the permission prompt names Clawbot-Calendar and the grant is its own.
17
17
  * One launch per request; request and response travel as 0600 JSON files. The
18
18
  * grant is tied to the build's signature (ad hoc), so a plugin update that
19
- * changes the Swift source needs one more click on the Mac.
19
+ * changes the Swift source needs one more click on the Mac. Each Mac's build
20
+ * carries a random installation id (infoPlist), so its signature is its own: a
21
+ * copy compiled anywhere else — a test's, say — does not get the owner's grant.
20
22
  *
21
23
  * ## What the bot may do
22
24
  *
@@ -28,6 +30,9 @@
28
30
  * waits — enforced here, not left to the model. The question goes to the
29
31
  * account owner only, is sent before anything listens for an answer, and says
30
32
  * what the change really covers (a whole recurring series, other attendees).
33
+ * The owner can switch that off (`macCalendarAsk`): their writable calendars
34
+ * are then changed directly, except a change other attendees would be told
35
+ * about, which still asks. Read-only and subscribed calendars stay untouched.
31
36
  * Only the owner can use these tools, and not at all while other people are on
32
37
  * the allow list: they share the conversation, so they would see the calendar.
33
38
  *
@@ -38,24 +43,42 @@
38
43
  * section — the rules live in the three tool descriptions.
39
44
  */
40
45
  import { execFile } from "node:child_process";
41
- import { createHash, randomUUID } from "node:crypto";
46
+ import { createHash, randomBytes, randomUUID } from "node:crypto";
42
47
  import fs from "node:fs";
48
+ import os from "node:os";
43
49
  import path from "node:path";
44
50
  import { fileURLToPath } from "node:url";
45
51
  import { defineTool } from "@deepseek-ai/dsh-tools";
46
52
  import { resolveStateDir } from "./ilink/storage/state-dir.js";
47
53
  import { logger } from "./ilink/util/logger.js";
48
54
  import { USER_TIME_ZONE, zonedDate, zonedStamp, zonedWeekday } from "./localtime.js";
55
+ import { localRequest } from "./secretary.js";
49
56
  /** The helper's name: the app bundle, its executable, and what the permission prompt shows. */
50
57
  export const HELPER_NAME = "Clawbot-Calendar";
51
58
  const BUNDLE_ID = "io.github.alphainfix.wechat-clawbot.calendar";
52
59
  const USAGE = "wechat-clawbot reads your calendars and schedules time in the calendar you chose. "
53
60
  + "微信 bot 会读取你的日历,并在你指定的专用日历里安排时间。";
54
- const INFO_PLIST = `<?xml version="1.0" encoding="UTF-8"?>
61
+ const REMINDERS_USAGE = "wechat-clawbot sets alarms for you: urgent reminders in a list of its own. "
62
+ + "微信 bot 会在它自己的清单里为你设闹钟(紧急提醒)。";
63
+ /**
64
+ * What this plugin needs of the helper (main.swift `helperProtocol`): 2 = the
65
+ * alarm commands, 3 = alarmComplete and alarm support in `status`. An older
66
+ * build keeps working for what it knows; the card offers 一键授权 to update it.
67
+ */
68
+ export const HELPER_PROTOCOL = 3;
69
+ /**
70
+ * The app's Info.plist. `installation` is the random id kept beside the app
71
+ * (install-id): it goes into the signature, which the permissions are tied to,
72
+ * so every build of the same source on another Mac — or in a test's folder —
73
+ * is a different app to macOS. Without it they are byte-identical, and any copy
74
+ * compiled anywhere would get the owner's calendar and reminders.
75
+ */
76
+ export function infoPlist(installation, bundleId = BUNDLE_ID) {
77
+ return `<?xml version="1.0" encoding="UTF-8"?>
55
78
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
56
79
  <plist version="1.0">
57
80
  <dict>
58
- <key>CFBundleIdentifier</key><string>${BUNDLE_ID}</string>
81
+ <key>CFBundleIdentifier</key><string>${bundleId}</string>
59
82
  <key>CFBundleName</key><string>${HELPER_NAME}</string>
60
83
  <key>CFBundleDisplayName</key><string>${HELPER_NAME}</string>
61
84
  <key>CFBundleExecutable</key><string>${HELPER_NAME}</string>
@@ -67,15 +90,24 @@ const INFO_PLIST = `<?xml version="1.0" encoding="UTF-8"?>
67
90
  <key>NSCalendarsFullAccessUsageDescription</key><string>${USAGE}</string>
68
91
  <key>NSCalendarsUsageDescription</key><string>${USAGE}</string>
69
92
  <key>NSCalendarsWriteOnlyAccessUsageDescription</key><string>${USAGE}</string>
93
+ <key>NSRemindersFullAccessUsageDescription</key><string>${REMINDERS_USAGE}</string>
94
+ <key>NSRemindersUsageDescription</key><string>${REMINDERS_USAGE}</string>
95
+ <key>ClawbotInstallation</key><string>${installation}</string>
70
96
  </dict>
71
97
  </plist>
72
98
  `;
99
+ }
73
100
  const GLOBAL_KEY = Symbol.for("clawbot.calendar");
74
101
  const shared = (globalThis[GLOBAL_KEY] ??= {});
75
- /** After an unanswered prompt, wait this long before putting up another one. */
76
- const PROMPT_BACKOFF_MS = 10 * 60_000;
77
- /** A failed build is not retried more often than this (unless the switch is flipped again). */
102
+ function setPending(pending) {
103
+ shared.pending = pending;
104
+ shared.generation = (shared.generation ?? 0) + 1;
105
+ }
106
+ /** A failed build is not retried more often than this (unless the owner asks at the card). */
78
107
  const BUILD_RETRY_MS = 10 * 60_000;
108
+ /** Commands that need each permission: while its prompt is up they answer "waiting" at once. */
109
+ const CALENDAR_COMMANDS = new Set(["calendars", "events", "ensureCalendar", "add", "update", "delete"]);
110
+ const ALARM_COMMANDS = new Set(["ensureAlarmList", "alarmAdd", "alarms", "alarmDelete", "alarmComplete"]);
79
111
  function execFileP(file, args, timeoutMs) {
80
112
  return new Promise((resolve, reject) => {
81
113
  execFile(file, [...args], { timeout: timeoutMs, maxBuffer: 4 << 20 }, (err, stdout, stderr) => {
@@ -97,10 +129,14 @@ export class CalendarHelper {
97
129
  lastStatus = null;
98
130
  statusInFlight = null;
99
131
  counts = null;
100
- constructor(root = path.join(resolveStateDir(), "calendar-helper"), source = fileURLToPath(new URL("../native/macos-calendar/main.swift", import.meta.url)), runner) {
132
+ bundleId;
133
+ constructor(root = path.join(resolveStateDir(), "calendar-helper"), source = fileURLToPath(new URL("../native/macos-calendar/main.swift", import.meta.url)), runner,
134
+ /** Tests build under their own bundle id, so not even a prompt there could touch the owner's grant. */
135
+ options = {}) {
101
136
  this.root = root;
102
137
  this.source = source;
103
138
  this.runner = runner;
139
+ this.bundleId = options.bundleId ?? BUNDLE_ID;
104
140
  this.sweep();
105
141
  }
106
142
  get appPath() {
@@ -109,23 +145,88 @@ export class CalendarHelper {
109
145
  get exePath() {
110
146
  return path.join(this.appPath, "Contents", "MacOS", HELPER_NAME);
111
147
  }
112
- /** Request/response files a timed-out helper may have written after the caller left. */
148
+ /**
149
+ * Request/response files a timed-out helper may have written after the
150
+ * caller left, and the folders of a build that was cut off halfway.
151
+ */
113
152
  sweep() {
114
- const dir = path.join(this.root, "calls");
153
+ const old = (file) => Date.now() - fs.statSync(file).mtimeMs > 3_600_000;
115
154
  try {
155
+ const dir = path.join(this.root, "calls");
116
156
  for (const name of fs.readdirSync(dir)) {
117
157
  const file = path.join(dir, name);
118
- if (Date.now() - fs.statSync(file).mtimeMs > 3_600_000)
158
+ if (old(file))
119
159
  fs.rmSync(file, { force: true });
120
160
  }
121
161
  }
122
162
  catch {
123
163
  // nothing to sweep
124
164
  }
165
+ try {
166
+ for (const name of fs.readdirSync(this.root)) {
167
+ const dir = path.join(this.root, name);
168
+ if (/^\.(build|old)-/.test(name) && old(dir))
169
+ fs.rmSync(dir, { recursive: true, force: true });
170
+ }
171
+ }
172
+ catch {
173
+ // no helper folder yet
174
+ }
175
+ }
176
+ /**
177
+ * This Mac's installation id (see infoPlist); "" before the first build,
178
+ * unless `create`. A lost or damaged file is taken back from the built app
179
+ * rather than minted anew: a new id is a new app to macOS, both permissions
180
+ * gone.
181
+ */
182
+ installation(create) {
183
+ const file = path.join(this.root, "install-id");
184
+ const read = () => {
185
+ try {
186
+ const id = fs.readFileSync(file, "utf-8").trim();
187
+ return /^[0-9a-f]{32}$/.test(id) ? id : "";
188
+ }
189
+ catch {
190
+ return "";
191
+ }
192
+ };
193
+ const known = read();
194
+ if (known !== "")
195
+ return known;
196
+ try {
197
+ const plist = fs.readFileSync(path.join(this.appPath, "Contents", "Info.plist"), "utf-8");
198
+ const built = /<key>ClawbotInstallation<\/key><string>([0-9a-f]{32})<\/string>/.exec(plist)?.[1];
199
+ if (built !== undefined) {
200
+ fs.mkdirSync(this.root, { recursive: true, mode: 0o700 });
201
+ fs.writeFileSync(file, built, { mode: 0o600 });
202
+ return built;
203
+ }
204
+ }
205
+ catch {
206
+ // no app built yet
207
+ }
208
+ if (!create)
209
+ return "";
210
+ fs.mkdirSync(this.root, { recursive: true, mode: 0o700 });
211
+ try {
212
+ // Exclusive: two processes starting at once must not each mint their own.
213
+ fs.writeFileSync(file, randomBytes(16).toString("hex"), { mode: 0o600, flag: "wx" });
214
+ }
215
+ catch (err) {
216
+ if (err.code !== "EEXIST")
217
+ throw err;
218
+ }
219
+ // The other process may still be writing its id.
220
+ for (let i = 0; i < 50 && read() === ""; i += 1)
221
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10);
222
+ const id = read();
223
+ if (id === "")
224
+ throw new Error(`${file} does not hold an installation id`);
225
+ return id;
125
226
  }
126
227
  /** What the built app was made from: a rebuild only when this changes. */
127
- fingerprint() {
128
- return createHash("sha256").update(fs.readFileSync(this.source)).update(INFO_PLIST).digest("hex");
228
+ fingerprint(installation = this.installation(false)) {
229
+ return createHash("sha256").update(fs.readFileSync(this.source)).update(infoPlist(installation, this.bundleId)).digest("hex");
129
230
  }
130
231
  /** Whether the app exists and matches the current source. */
131
232
  isBuilt() {
@@ -137,16 +238,40 @@ export class CalendarHelper {
137
238
  return false;
138
239
  }
139
240
  }
140
- /** Compile and sign the helper if it is missing or stale. A recent failure is reported, not retried. */
241
+ /** Whether there is a helper to ask (a test's runner counts); a status look never builds one. */
242
+ get hasApp() {
243
+ return this.runner !== undefined || fs.existsSync(this.exePath);
244
+ }
245
+ /** An app built from an older source: it still works for what it knows. */
246
+ isStale() {
247
+ return this.runner === undefined && fs.existsSync(this.exePath) && !this.isBuilt();
248
+ }
249
+ /**
250
+ * Compile and sign the helper if it is missing, or stale and `force`. A recent failure is reported, not retried.
251
+ *
252
+ * A rebuild changes the ad-hoc signature, and macOS takes the new build for a
253
+ * new app: the calendar and reminders permissions start over, and someone has
254
+ * to click Allow at the Mac. So an existing helper is replaced only when the
255
+ * owner asks at the settings card (the switch, or 一键授权) — never behind
256
+ * their back, when they may be far from the Mac.
257
+ */
141
258
  async ensureBuilt(force = false) {
142
- if (this.runner !== undefined || this.isBuilt())
259
+ if (this.runner !== undefined)
260
+ return;
261
+ // A build under way finishes first: the app is swapped in whole, never seen half-made.
262
+ while (this.building !== null)
263
+ await this.building.catch(() => undefined);
264
+ if (this.isBuilt())
143
265
  return;
144
- const print = this.fingerprint();
266
+ if (!force && fs.existsSync(this.exePath))
267
+ return;
268
+ const installation = this.installation(true);
269
+ const print = this.fingerprint(installation);
145
270
  const failed = this.buildFailure;
146
271
  if (!force && failed !== null && failed.fingerprint === print && Date.now() - failed.at < BUILD_RETRY_MS) {
147
272
  throw new Error(failed.message);
148
273
  }
149
- this.building ??= this.build(print)
274
+ this.building = this.build(print, installation)
150
275
  .catch((err) => {
151
276
  this.buildFailure = { fingerprint: print, at: Date.now(), message: String(err.message ?? err) };
152
277
  throw err;
@@ -154,37 +279,59 @@ export class CalendarHelper {
154
279
  .finally(() => { this.building = null; });
155
280
  return this.building;
156
281
  }
157
- async build(print) {
158
- const macos = path.join(this.appPath, "Contents", "MacOS");
159
- fs.rmSync(this.appPath, { recursive: true, force: true });
160
- fs.mkdirSync(macos, { recursive: true, mode: 0o700 });
282
+ /**
283
+ * Compile into a folder beside the app and swap the finished, signed bundle
284
+ * in whole. A build that fails — the command line tools broken by a macOS
285
+ * update, say — leaves the old helper where it was, still working, with its
286
+ * permissions.
287
+ */
288
+ async build(print, installation) {
289
+ const staging = path.join(this.root, `.build-${process.pid}-${randomUUID().slice(0, 8)}`);
290
+ const app = path.join(staging, `${HELPER_NAME}.app`);
291
+ const exe = path.join(app, "Contents", "MacOS", HELPER_NAME);
292
+ fs.mkdirSync(path.dirname(exe), { recursive: true, mode: 0o700 });
161
293
  logger.info(`calendar: building ${HELPER_NAME}.app (first use, or the plugin's Swift source changed)`);
162
294
  try {
163
- await execFileP("xcrun", ["swiftc", "-O", "-framework", "EventKit", this.source, "-o", this.exePath], 600_000);
164
- }
165
- catch (err) {
166
- const e = err;
167
- if (e.code === "ENOENT" || /xcrun: error|no developer tools|CommandLineTools/i.test(String(e.stderr ?? ""))) {
168
- throw new Error("编译 Clawbot-Calendar 需要 Xcode 命令行工具:在终端运行 xcode-select --install");
295
+ try {
296
+ await execFileP("xcrun", ["swiftc", "-O", "-framework", "EventKit", this.source, "-o", exe], 600_000);
169
297
  }
170
- throw new Error(`编译 Clawbot-Calendar 失败:${String(e.stderr ?? err).trim().slice(-300)}`);
298
+ catch (err) {
299
+ const e = err;
300
+ if (e.code === "ENOENT" || /xcrun: error|no developer tools|CommandLineTools/i.test(String(e.stderr ?? ""))) {
301
+ throw new Error("编译 Clawbot-Calendar 需要 Xcode 命令行工具:在终端运行 xcode-select --install");
302
+ }
303
+ throw new Error(`编译 Clawbot-Calendar 失败:${String(e.stderr ?? err).trim().slice(-300)}`);
304
+ }
305
+ fs.writeFileSync(path.join(app, "Contents", "Info.plist"), infoPlist(installation, this.bundleId));
306
+ // Ad-hoc signature: required on Apple silicon, and what the permission grant is tied to.
307
+ await execFileP("codesign", ["--force", "--sign", "-", app], 60_000);
308
+ const old = path.join(this.root, `.old-${process.pid}-${randomUUID().slice(0, 8)}`);
309
+ if (fs.existsSync(this.appPath))
310
+ fs.renameSync(this.appPath, old);
311
+ fs.renameSync(app, this.appPath);
312
+ fs.rmSync(old, { recursive: true, force: true });
313
+ fs.writeFileSync(path.join(this.root, "source.sha256"), print, { mode: 0o600 });
314
+ }
315
+ finally {
316
+ fs.rmSync(staging, { recursive: true, force: true });
171
317
  }
172
- fs.writeFileSync(path.join(this.appPath, "Contents", "Info.plist"), INFO_PLIST);
173
- // Ad-hoc signature: required on Apple silicon, and what the permission grant is tied to.
174
- await execFileP("codesign", ["--force", "--sign", "-", this.appPath], 60_000);
175
- fs.writeFileSync(path.join(this.root, "source.sha256"), print, { mode: 0o600 });
176
318
  this.buildFailure = null;
177
319
  logger.info(`calendar: built ${this.appPath}`);
178
320
  }
179
321
  /**
180
322
  * Run one request. Requests are serialized: two EventKit writers at once help
181
- * nobody. While the permission prompt is up, calendar reads and writes answer
182
- * "not authorized" at once instead of queueing behind it.
323
+ * nobody. While a permission prompt is up, what needs that permission
324
+ * answers "waiting for you at the Mac" at once instead of queueing behind
325
+ * it; the other permission's commands go ahead.
183
326
  */
184
327
  call(request, timeoutMs = 30_000, signal) {
185
- if (shared.promptOpen === true && request.cmd !== "status" && request.cmd !== "request") {
328
+ const cmd = String(request.cmd ?? "");
329
+ if (shared.pending?.calendar === true && CALENDAR_COMMANDS.has(cmd)) {
186
330
  return Promise.resolve({ ok: false, code: "not_authorized", error: "notDetermined", pending: true });
187
331
  }
332
+ if (shared.pending?.reminders === true && ALARM_COMMANDS.has(cmd)) {
333
+ return Promise.resolve({ ok: false, code: "reminders_not_authorized", error: "notDetermined", pending: true });
334
+ }
188
335
  const run = this.chain.then(() => (signal?.aborted
189
336
  ? { ok: false, code: "stopped", error: "the turn was stopped" }
190
337
  : this.callNow(request, timeoutMs)));
@@ -247,17 +394,41 @@ export class CalendarHelper {
247
394
  return this.statusInFlight;
248
395
  }
249
396
  async readStatus() {
397
+ const generation = shared.generation ?? 0;
250
398
  let value;
251
- try {
252
- if (shared.promptOpen === true) {
253
- value = { authorization: "notDetermined", built: true, prompting: true };
254
- }
255
- else {
399
+ if (!this.hasApp) {
400
+ // Looking builds nothing: a build takes a minute, and the card would wait on it.
401
+ // The switch and 一键授权 build (prepare); one that failed says why.
402
+ const lastFailure = this.buildFailure;
403
+ value = { authorization: "unknown", built: false, ...(lastFailure !== null ? { error: lastFailure.message } : {}) };
404
+ }
405
+ else {
406
+ try {
407
+ // Asking for the state puts up no prompt, so it is fine while one is on screen.
256
408
  const res = await this.call({ cmd: "status" }, 20_000);
257
- value = { authorization: String(res.authorization ?? res.code ?? "unknown"), built: this.runner !== undefined || this.isBuilt() };
409
+ const protocol = typeof res.protocol === "number" ? res.protocol : 1;
410
+ value = {
411
+ authorization: String(res.authorization ?? res.code ?? "unknown"),
412
+ // A build from before the alarms reports no reminders state at all.
413
+ reminders: typeof res.reminders === "string" ? res.reminders : "outdated",
414
+ protocol,
415
+ built: this.runner !== undefined || this.isBuilt(),
416
+ stale: this.isStale(),
417
+ outdated: res.ok === true && protocol < HELPER_PROTOCOL,
418
+ };
419
+ if (res.alarms === "supported" || res.alarms === "unsupported")
420
+ value.alarms = res.alarms;
421
+ const pending = shared.pending;
422
+ if (pending !== undefined) {
423
+ value.prompting = true;
424
+ value.waitingFor = [...(pending.calendar ? ["calendar"] : []), ...(pending.reminders ? ["reminders"] : [])];
425
+ }
258
426
  if (res.ok !== true && res.error !== undefined)
259
427
  value.error = String(res.error);
260
- if (value.authorization === "fullAccess") {
428
+ const failed = this.buildFailure;
429
+ if (value.stale === true && failed !== null && failed.fingerprint === this.fingerprint())
430
+ value.updateError = failed.message;
431
+ if (value.authorization === "fullAccess" && shared.pending?.calendar !== true) {
261
432
  if (this.counts === null || Date.now() - this.counts.at > 5 * 60_000) {
262
433
  const cals = await this.call({ cmd: "calendars" }, 20_000);
263
434
  const list = cals.calendars ?? [];
@@ -267,50 +438,142 @@ export class CalendarHelper {
267
438
  value.accounts = this.counts.accounts;
268
439
  }
269
440
  }
270
- }
271
- catch (err) {
272
- value = { authorization: "unknown", built: this.isBuilt(), error: String(err.message ?? err).slice(0, 240) };
441
+ catch (err) {
442
+ value = { authorization: "unknown", built: this.isBuilt(), error: String(err.message ?? err).slice(0, 240) };
443
+ }
273
444
  }
274
445
  const dedicated = this.dedicated();
275
446
  if (dedicated !== null)
276
447
  value.dedicated = { name: dedicated.name, account: dedicated.account };
277
- this.lastStatus = { at: Date.now(), value };
448
+ const alarms = this.alarmList();
449
+ if (alarms !== null)
450
+ value.alarmList = { name: alarms.name, account: alarms.account };
451
+ // A prompt went up or came down while this look ran: it may describe the other side of that.
452
+ // A look without an app launched nothing: not kept, so a build that ends shows at once.
453
+ if ((shared.generation ?? 0) === generation && this.hasApp)
454
+ this.lastStatus = { at: Date.now(), value };
278
455
  return value;
279
456
  }
457
+ /** Forget the cached status: the next look asks the helper again. */
458
+ invalidateStatus() {
459
+ this.lastStatus = null;
460
+ }
280
461
  /**
281
- * Build the helper and, if the owner has not answered yet, put the permission
282
- * prompt on the Mac's screen — one prompt at a time process-wide, and not
283
- * again within a while of one that went unanswered (unless `force`, which is
284
- * the switch being turned on).
462
+ * Get the helper ready. Without `force` (start-up) it is built if missing
463
+ * and asked for its state — never a prompt: nobody may be at the Mac, and a
464
+ * prompt nobody answers only blocks what waits on it. `force` is the owner at
465
+ * the settings card (the switch, or 一键授权): it also replaces a helper built
466
+ * from older source (which starts the permissions over, see ensureBuilt) and
467
+ * puts up a prompt for each permission still undecided — the calendar, then
468
+ * reminders (for alarms). One round at a time, process-wide.
285
469
  */
286
470
  prepare(force = false) {
287
- shared.preparing ??= this.prepareNow(force).finally(() => { shared.preparing = undefined; });
288
- return shared.preparing;
471
+ const running = shared.preparing;
472
+ if (running !== undefined) {
473
+ if (!force || running.force)
474
+ return running.done;
475
+ // 一键授权 during a quick start-up look: its own round right after it.
476
+ shared.queued ??= running.done.catch(() => undefined).then(() => {
477
+ shared.queued = undefined;
478
+ return this.prepare(true);
479
+ });
480
+ return shared.queued;
481
+ }
482
+ const done = this.prepareNow(force).finally(() => {
483
+ if (shared.preparing?.done === done)
484
+ shared.preparing = undefined;
485
+ });
486
+ shared.preparing = { force, done };
487
+ return done;
488
+ }
489
+ /** Whether a round is under way (the card shows it). */
490
+ get preparing() {
491
+ return shared.preparing !== undefined || shared.queued !== undefined;
289
492
  }
290
493
  async prepareNow(force) {
291
- await this.ensureBuilt(force);
494
+ // A new build resets both permissions, so a forced round replaces only a helper older than this
495
+ // plugin needs (its protocol), or one that does not answer; a build that merely differs stays.
496
+ let rebuild = force;
497
+ if (force && this.runner === undefined && this.isStale()) {
498
+ const before = await this.callNow({ cmd: "status" }, 20_000);
499
+ rebuild = before.ok !== true || (typeof before.protocol === "number" ? before.protocol : 1) < HELPER_PROTOCOL;
500
+ }
501
+ try {
502
+ await this.ensureBuilt(rebuild);
503
+ }
504
+ catch (err) {
505
+ // A failed update keeps the old helper: still ask with that one. The card shows why it was not replaced.
506
+ if (!force || this.runner !== undefined || !fs.existsSync(this.exePath))
507
+ throw err;
508
+ logger.warn(`calendar: could not update ${HELPER_NAME}, keeping the old one: ${String(err.message ?? err).slice(0, 300)}`);
509
+ }
510
+ this.lastStatus = null;
292
511
  const first = await this.callNow({ cmd: "status" }, 20_000);
293
- if (first.authorization !== "notDetermined") {
294
- logger.info(`calendar: ${HELPER_NAME} authorization = ${String(first.authorization ?? first.error)}`);
512
+ const state = `calendar ${String(first.authorization ?? first.error)}, reminders ${String(first.reminders ?? "(old build)")}`;
513
+ const calendar = force && first.authorization === "notDetermined";
514
+ const reminders = force && first.reminders === "notDetermined" && first.alarms !== "unsupported";
515
+ if (!calendar && !reminders) {
516
+ logger.info(`calendar: ${HELPER_NAME} authorization = ${state}`);
295
517
  return;
296
518
  }
297
- const recent = shared.lastPromptAt !== undefined && Date.now() - shared.lastPromptAt < PROMPT_BACKOFF_MS;
298
- if (recent && !force)
299
- return;
300
- logger.info(`calendar: asking for calendar access (a prompt for ${HELPER_NAME} is on the Mac's screen)`);
301
- shared.promptOpen = true;
302
- shared.lastPromptAt = Date.now();
519
+ logger.info(`calendar: asking for access (${Number(calendar) + Number(reminders)} prompt(s) for ${HELPER_NAME} on the Mac's screen)`);
520
+ // Outside the queue, one prompt per launch: while one is up, what needs it
521
+ // answers "waiting" (call above), and the calendar is free again as soon
522
+ // as its own prompt is answered.
523
+ setPending({ calendar, reminders });
303
524
  try {
304
- // Outside the queue: reads and writes answer "not authorized" meanwhile.
305
- const res = await this.callNow({ cmd: "request", waitSeconds: 120 }, 150_000);
306
- shared.lastPromptResult = String(res.authorization ?? res.error);
307
- logger.info(`calendar: authorization after the prompt = ${shared.lastPromptResult}`);
525
+ if (calendar) {
526
+ const res = await this.callNow({ cmd: "request", calendar: true, reminders: false, waitSeconds: 120 }, 140_000);
527
+ logger.info(`calendar: calendar access after the prompt = ${String(res.authorization ?? res.error)}`);
528
+ setPending({ calendar: false, reminders });
529
+ this.lastStatus = null;
530
+ }
531
+ if (reminders) {
532
+ const res = await this.callNow({ cmd: "request", calendar: false, reminders: true, waitSeconds: 120 }, 140_000);
533
+ logger.info(`calendar: reminders access after the prompt = ${String(res.reminders ?? res.error)}`);
534
+ }
308
535
  }
309
536
  finally {
310
- shared.promptOpen = false;
537
+ setPending(undefined);
311
538
  this.lastStatus = null;
312
539
  }
313
540
  }
541
+ /**
542
+ * What 一键授权 would do right now: build or update the helper, which
543
+ * prompts go up, and what only System Settings can fix. One fresh look at
544
+ * the helper (no prompt).
545
+ */
546
+ async authorizePlan() {
547
+ if (!this.hasApp) {
548
+ // Urgent reminders came with macOS 26.2 (Darwin 25.2): before it there are no alarms, so no Reminders prompt.
549
+ const [major, minor] = os.release().split(".").map(Number);
550
+ const alarmsUnsupported = major < 25 || (major === 25 && minor < 2);
551
+ return { build: "first", ask: alarmsUnsupported ? ["calendar"] : ["calendar", "reminders"], denied: [], ...(alarmsUnsupported ? { alarmsUnsupported } : {}) };
552
+ }
553
+ const res = await this.call({ cmd: "status" }, 20_000);
554
+ if (res.ok !== true)
555
+ return { ask: [], denied: [], error: String(res.error ?? res.code ?? "没有回应") };
556
+ const alarmsUnsupported = res.alarms === "unsupported";
557
+ // Only an older build is replaced (see prepareNow): a new build starts both permissions over.
558
+ if (this.isStale() && (typeof res.protocol === "number" ? res.protocol : 1) < HELPER_PROTOCOL) {
559
+ // A new build is a new app to macOS: both start over, refusals included.
560
+ return { build: "update", ask: alarmsUnsupported ? ["calendar"] : ["calendar", "reminders"], denied: [], ...(alarmsUnsupported ? { alarmsUnsupported } : {}) };
561
+ }
562
+ const refused = (state) => state === "denied" || state === "restricted" || state === "writeOnly";
563
+ const ask = [];
564
+ const denied = [];
565
+ if (res.authorization === "notDetermined")
566
+ ask.push("calendar");
567
+ else if (refused(res.authorization))
568
+ denied.push("calendar");
569
+ if (!alarmsUnsupported) {
570
+ if (res.reminders === "notDetermined")
571
+ ask.push("reminders");
572
+ else if (refused(res.reminders))
573
+ denied.push("reminders");
574
+ }
575
+ return { ask, denied, ...(alarmsUnsupported ? { alarmsUnsupported } : {}) };
576
+ }
314
577
  /** The dedicated calendar this plugin uses, or null before it was created or approved. */
315
578
  dedicated() {
316
579
  try {
@@ -327,8 +590,62 @@ export class CalendarHelper {
327
590
  fs.mkdirSync(this.root, { recursive: true, mode: 0o700 });
328
591
  fs.writeFileSync(path.join(this.root, "dedicated.json"), JSON.stringify(record), { mode: 0o600 });
329
592
  }
593
+ /** The reminders list alarms go into, or null before the first alarm. */
594
+ alarmList() {
595
+ try {
596
+ const rec = JSON.parse(fs.readFileSync(path.join(this.root, "alarm-list.json"), "utf-8"));
597
+ return typeof rec.id === "string" && typeof rec.name === "string"
598
+ ? { name: rec.name, id: rec.id, account: typeof rec.account === "string" ? rec.account : "" }
599
+ : null;
600
+ }
601
+ catch {
602
+ return null;
603
+ }
604
+ }
605
+ rememberAlarmList(record) {
606
+ fs.mkdirSync(this.root, { recursive: true, mode: 0o700 });
607
+ fs.writeFileSync(path.join(this.root, "alarm-list.json"), JSON.stringify(record), { mode: 0o600 });
608
+ }
609
+ /** The alarms this plugin set (by id): the only ones it ever ticks off by itself. */
610
+ createdAlarms() {
611
+ try {
612
+ const ids = JSON.parse(fs.readFileSync(path.join(this.root, "alarms-created.json"), "utf-8"));
613
+ return new Set(Array.isArray(ids) ? ids.filter((id) => typeof id === "string") : []);
614
+ }
615
+ catch {
616
+ return new Set();
617
+ }
618
+ }
619
+ rememberCreatedAlarm(id) {
620
+ this.writeCreated([...this.createdAlarms(), id].slice(-1000));
621
+ }
622
+ forgetCreatedAlarms(ids) {
623
+ const gone = new Set(ids);
624
+ this.writeCreated([...this.createdAlarms()].filter((id) => !gone.has(id)));
625
+ }
626
+ writeCreated(ids) {
627
+ fs.mkdirSync(this.root, { recursive: true, mode: 0o700 });
628
+ fs.writeFileSync(path.join(this.root, "alarms-created.json"), JSON.stringify(ids), { mode: 0o600 });
629
+ }
330
630
  }
331
631
  const HANDLE_LIMIT = 2_000;
632
+ /**
633
+ * Refuse anyone but the account owner — and everyone while friends are on the
634
+ * allow list: they share this one conversation, so whatever the calendar (or
635
+ * the alarm list) says would be in front of them.
636
+ */
637
+ export function notOwnerReason(deps, what = "日历") {
638
+ const owner = deps.getAccount()?.userId;
639
+ if (owner === undefined || owner === "")
640
+ return `不知道机主是谁(登录信息里没有用户 id),${what}工具不开放。重新扫码登录一次再试。`;
641
+ const others = (deps.config.allowFrom ?? []).filter((id) => id !== owner);
642
+ if (others.length > 0)
643
+ return `白名单里还有别人,大家共用这一个对话,${what}内容会被看到,所以${what}工具不开放。`;
644
+ const sender = deps.activeSender();
645
+ if (sender !== undefined && sender !== owner)
646
+ return `${what}只对机主开放,不能替别人查看或修改。`;
647
+ return undefined;
648
+ }
332
649
  /** A yes on WeChat. Anything else is a no: silence must never write to someone's calendar. */
333
650
  export function isYes(reply) {
334
651
  if (reply === null)
@@ -411,34 +728,22 @@ export function registerCalendarTools(agentCtx, deps) {
411
728
  return rec !== null && rec.name === dedicatedName() ? rec.id : undefined;
412
729
  };
413
730
  const isDedicated = (calendarId) => dedicatedId() === calendarId;
414
- /**
415
- * Refuse anyone but the account owner — and everyone while friends are on the
416
- * allow list: they share this one conversation, so whatever the calendar
417
- * says would be in front of them.
418
- */
419
- const notOwner = () => {
420
- const owner = deps.getAccount()?.userId;
421
- if (owner === undefined || owner === "")
422
- return "不知道机主是谁(登录信息里没有用户 id),日历工具不开放。重新扫码登录一次再试。";
423
- const others = (deps.config.allowFrom ?? []).filter((id) => id !== owner);
424
- if (others.length > 0)
425
- return "白名单里还有别人,大家共用这一个对话,日历内容会被看到,所以日历工具不开放。";
426
- const sender = deps.activeSender();
427
- if (sender !== undefined && sender !== owner)
428
- return "日历只对机主开放,不能替别人查看或修改。";
429
- return undefined;
430
- };
731
+ /** Whether a change to another calendar waits for the owner's yes (the default). */
732
+ const askFirst = () => deps.config.macCalendarAsk !== false;
733
+ const notOwner = () => notOwnerReason(deps);
431
734
  /** Turn a helper failure into a sentence the owner can act on. */
432
735
  const explain = (res, writing = false) => {
433
736
  if (res.code === "not_authorized") {
737
+ if (res.pending === true) {
738
+ return `正在等 Mac 上的授权:屏幕上有「${HELPER_NAME}」想要访问日历的窗口,点「允许」之后再试。`;
739
+ }
434
740
  if (res.error === "notDetermined") {
435
- void deps.helper.prepare().catch((err) => logger.warn(`calendar: prepare failed: ${String(err).slice(0, 200)}`));
436
- return `还没授权:Mac 屏幕上应该有「${HELPER_NAME}」想要访问日历的窗口,要在电脑前点「允许」`
437
- + "(插件更新后小程序重新编译过的话,也要再点一次)。没看到就去 系统设置 → 隐私与安全性 → 日历 打开它。";
741
+ // No prompt from here: the owner may be far from the Mac, and a prompt nobody answers helps nobody.
742
+ return "还没授权日历:到 Mac 前,在设置卡片「全天候秘书」上点「一键授权」,在弹出的窗口里点「允许」。";
438
743
  }
439
744
  if (res.error === "writeOnly")
440
- return `「${HELPER_NAME}」只有「仅添加」权限,读不到日程:在 系统设置 → 隐私与安全性 → 日历 里改成完全访问。`;
441
- return `「${HELPER_NAME}」没有日历权限(${String(res.error)}):在 Mac 的 系统设置 → 隐私与安全性 → 日历 里打开它。`;
745
+ return `「${HELPER_NAME}」只有「仅添加」权限,读不到日程:在 系统设置 → 隐私与安全 → 日历 里改成完全访问。`;
746
+ return `「${HELPER_NAME}」没有日历权限(${String(res.error)}):在 Mac 的 系统设置 → 隐私与安全 → 日历 里打开它。`;
442
747
  }
443
748
  if (res.code === "timeout" || res.code === "no_response") {
444
749
  return writing
@@ -489,7 +794,7 @@ export function registerCalendarTools(agentCtx, deps) {
489
794
  const ensureDedicated = async (signal) => {
490
795
  const name = dedicatedName();
491
796
  if (name === "")
492
- return { error: "专用日历还没起名字:在设置卡片「Mac 日历」里填上再试。" };
797
+ return { error: "专用日历还没起名字:在设置卡片「全天候秘书」里填上再试。" };
493
798
  const known = dedicatedId();
494
799
  let res = await run({ cmd: "ensureCalendar", name, ...(known === undefined ? {} : { knownId: known }) }, signal);
495
800
  if (!res.ok && res.code === "name_taken") {
@@ -653,8 +958,8 @@ export function registerCalendarTools(agentCtx, deps) {
653
958
  + "block, a meeting, an appointment, a trip) or when the owner asks for a calendar entry. "
654
959
  + "Without `calendar` it goes into the bot's own planning calendar "
655
960
  + "(named in the settings, created on first use): use that for the time blocks you plan, no need to ask. "
656
- + "Naming any other calendar makes this tool ask the owner on WeChat and wait for their answer, so do not "
657
- + "ask separately beforehand. It cannot invite anyone. The result lists events the new one overlaps. "
961
+ + "Another writable calendar can be named too; when the owner wants to be asked first, this tool asks on "
962
+ + "WeChat and waits by itself, so never ask separately beforehand. It cannot invite anyone. The result lists events the new one overlaps. "
658
963
  + "A calendar alert is added as set in the settings; pass `alert` only when the owner asked for a specific one. "
659
964
  + "It does not replace your WeChat reminder: for a to-do the owner should be reminded "
660
965
  + "of, still create one with schedule_create; both firing is fine.",
@@ -702,7 +1007,7 @@ export function registerCalendarTools(agentCtx, deps) {
702
1007
  return { ok: false, summary: `「${found.calendar.title}」是只读日历,加不进去。` };
703
1008
  target = found.calendar;
704
1009
  }
705
- if (!isDedicated(target.id)) {
1010
+ if (!isDedicated(target.id) && askFirst()) {
706
1011
  const span = a.end ? `${a.start} 到 ${a.end}` : String(a.start);
707
1012
  const ok = await ask(`要把「${title}」(${span}${a.all_day ? ",全天" : ""})加到你的「${target.title}」日历(${target.account || "本机"})吗?`, exec?.signal);
708
1013
  if (!ok.ok)
@@ -731,8 +1036,9 @@ export function registerCalendarTools(agentCtx, deps) {
731
1036
  agentCtx.tools.register(defineTool({
732
1037
  name: "calendar_change_event",
733
1038
  description: "Move, edit or delete one event, named by its handle (#e…) from calendar_events or calendar_add_event. "
734
- + "Events in the bot's own planning calendar are changed directly. For any other calendar this tool asks "
735
- + "the owner on WeChat first and waits, so do not ask separately. A recurring event changes only this "
1039
+ + "Events in the bot's own planning calendar are changed directly. For other calendars this tool itself asks "
1040
+ + "the owner on WeChat and waits when that is needed (as the owner set it, or when other attendees would be "
1041
+ + "told), so never ask separately. A recurring event changes only this "
736
1042
  + "occurrence; scope \"future\" changes this and every later one — use it only when the owner said so. "
737
1043
  + "A timed event stays timed and an all-day one stays all-day unless all_day says otherwise.",
738
1044
  parameters: {
@@ -806,7 +1112,8 @@ export function registerCalendarTools(agentCtx, deps) {
806
1112
  }
807
1113
  const label = `「${h.calendar}」日历里的「${h.title}」(${when(h.start, h.end, h.allDay)})`;
808
1114
  const touchesOthers = !isDedicated(h.calendarId) || (move !== undefined && !isDedicated(move.id));
809
- if (touchesOthers) {
1115
+ // With asking switched off, a change other attendees would be told about still asks.
1116
+ if (touchesOthers && (askFirst() || h.attendees > 0)) {
810
1117
  const reach = future ? "(这是重复日程:会连同之后的每一次一起" + (action === "delete" ? "删掉)" : "改)") : (h.recurring ? "(只这一次)" : "");
811
1118
  const people = h.attendees > 0
812
1119
  ? `这个日程有 ${h.attendees} 位参与者,${action === "delete" ? "删掉" : "改动"}可能会通知他们${h.organizerIsMe ? "" : "(你不是组织者)"}。`
@@ -862,16 +1169,28 @@ export const CALENDAR_STATUS_PATH = "/plugins/clawbot/calendar/status";
862
1169
  * the helper while the switch is off, so looking at the card builds nothing and
863
1170
  * asks for nothing. No event content: only the permission and counts.
864
1171
  */
865
- export function registerCalendarStatusRoute(ctx, read, helper) {
1172
+ export function registerCalendarStatusRoute(ctx,
1173
+ /** `secretary`: the rules are in memory.md; `secretaryOn`: their switch is on in the config. */
1174
+ read, helper) {
866
1175
  ctx.inject(["webServer"], (scoped) => {
867
1176
  const server = scoped.webServer;
868
1177
  scoped.effect(() => server.register({
869
1178
  kind: "exact",
870
1179
  path: CALENDAR_STATUS_PATH,
871
- async handler(_req, res) {
872
- const { enabled, name, others, secretary } = read();
1180
+ async handler(req, res) {
1181
+ // Names and counts, and every look launches the helper: this machine's page only (DNS rebinding).
1182
+ if (!localRequest(req)) {
1183
+ res.writeHead(403, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
1184
+ res.end(JSON.stringify({ ok: false, message: "只接受本机设置卡片的请求" }));
1185
+ return;
1186
+ }
1187
+ const { enabled, name, others, secretary, secretaryOn } = read();
873
1188
  const mac = process.platform === "darwin";
874
- const body = { ok: true, platform: process.platform, mac, enabled, name, others, secretary, helper: HELPER_NAME };
1189
+ const body = {
1190
+ ok: true, platform: process.platform, mac, enabled, name, others, secretary, secretaryOn, helper: HELPER_NAME,
1191
+ // What 一键授权 brings the helper up to, and whether a round of prompts is under way now.
1192
+ wantProtocol: HELPER_PROTOCOL, preparing: helper.preparing,
1193
+ };
875
1194
  if (mac && enabled)
876
1195
  Object.assign(body, await helper.status());
877
1196
  res.writeHead(200, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });