wechat-clawbot 1.1.0 → 1.2.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.
@@ -0,0 +1,543 @@
1
+ // Clawbot-Calendar: the WeChat bot's bridge to the macOS Calendar (EventKit).
2
+ //
3
+ // The plugin builds this file into Clawbot-Calendar.app and launches it through
4
+ // LaunchServices (`open -W -n -g -a … --args --request <file> --response <file>`),
5
+ // so macOS treats the app as its own "responsible process": the calendar
6
+ // permission prompt names this app, and the grant does not depend on whatever
7
+ // started DSH (a menu-bar app, a terminal). Each launch handles one request and
8
+ // exits.
9
+ //
10
+ // Request (JSON file): { "cmd": "...", "timeZone": "America/New_York", "deadline": <epoch ms>, ... }
11
+ // Response (JSON file): { "ok": true, ... } or { "ok": false, "error": "...", "code": "..." }
12
+ //
13
+ // Commands
14
+ // status authorization state, no prompt
15
+ // request ask for full access (shows the system prompt once)
16
+ // calendars every event calendar with its account
17
+ // events occurrences in [from, to), recurring ones expanded
18
+ // ensureCalendar the dedicated calendar: a known id, an adopted one, or a new one
19
+ // add add one event (and report what it overlaps)
20
+ // update / delete change or remove one occurrence (or the series from it on)
21
+ //
22
+ // Times in: "2026-10-15T14:00" (local wall clock in timeZone), "2026-10-15"
23
+ // (a date), or ISO 8601 with an offset. Times out: ISO 8601 with offset.
24
+ //
25
+ // All-day events follow EventKit's own rule: the end is the LAST day, inclusive
26
+ // (EventKit stores 23:59:59 of that day). Passing the next midnight, the usual
27
+ // exclusive convention, makes a one-day event two days long.
28
+
29
+ import EventKit
30
+ import Foundation
31
+
32
+ // MARK: - I/O
33
+
34
+ struct Failure: Error {
35
+ let code: String
36
+ let message: String
37
+ }
38
+
39
+ func argument(_ name: String) -> String? {
40
+ let args = CommandLine.arguments
41
+ guard let i = args.firstIndex(of: name), i + 1 < args.count else { return nil }
42
+ return args[i + 1]
43
+ }
44
+
45
+ let responseLock = NSLock()
46
+ var responded = false
47
+
48
+ /// Write the one response this launch gives, then never again (a watchdog may race the real answer).
49
+ func respond(_ object: [String: Any], to path: String) {
50
+ responseLock.lock()
51
+ defer { responseLock.unlock() }
52
+ guard !responded else { return }
53
+ responded = true
54
+ let data = (try? JSONSerialization.data(withJSONObject: object, options: [.sortedKeys]))
55
+ ?? Data("{\"ok\":false,\"code\":\"error\",\"error\":\"unencodable response\"}".utf8)
56
+ let url = URL(fileURLWithPath: path)
57
+ try? data.write(to: url, options: .atomic)
58
+ // Only the owner may read what the calendar said.
59
+ try? FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: path)
60
+ }
61
+
62
+ // MARK: - Time
63
+
64
+ var zone = TimeZone.current
65
+ var calendar: Calendar {
66
+ var c = Calendar(identifier: .gregorian)
67
+ c.timeZone = zone
68
+ return c
69
+ }
70
+
71
+ /// Past this instant nothing is written: the caller has given up and told the model so.
72
+ var deadline: Date? = nil
73
+
74
+ func beforeDeadline() throws {
75
+ if let d = deadline, Date() >= d {
76
+ throw Failure(code: "deadline", message: "took too long; nothing was changed")
77
+ }
78
+ }
79
+
80
+ func localFormatter(_ format: String) -> DateFormatter {
81
+ let f = DateFormatter()
82
+ f.locale = Locale(identifier: "en_US_POSIX")
83
+ f.calendar = calendar
84
+ f.timeZone = zone
85
+ f.dateFormat = format
86
+ f.isLenient = false
87
+ return f
88
+ }
89
+
90
+ /// Reject 2026-09-31, 2026-02-30, 25:00 instead of rolling them over to another day.
91
+ func checkFields(_ text: String, field: String) throws {
92
+ let pattern = #"^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2}))?)?"#
93
+ guard let re = try? NSRegularExpression(pattern: pattern),
94
+ let m = re.firstMatch(in: text, range: NSRange(text.startIndex..., in: text)) else { return }
95
+ func int(_ i: Int) -> Int? {
96
+ guard let r = Range(m.range(at: i), in: text) else { return nil }
97
+ return Int(text[r])
98
+ }
99
+ var parts = DateComponents()
100
+ parts.year = int(1)
101
+ parts.month = int(2)
102
+ parts.day = int(3)
103
+ let hour = int(4) ?? 0, minute = int(5) ?? 0, second = int(6) ?? 0
104
+ if !parts.isValidDate(in: Calendar(identifier: .gregorian)) || hour > 23 || minute > 59 || second > 59 {
105
+ throw Failure(code: "bad_request", message: "\(field) is not a real date or time: \(text)")
106
+ }
107
+ }
108
+
109
+ /// A parsed time, and whether it named only a date.
110
+ func parseTime(_ raw: Any?, field: String) throws -> (date: Date, dateOnly: Bool) {
111
+ guard let text = (raw as? String)?.trimmingCharacters(in: .whitespaces), !text.isEmpty else {
112
+ throw Failure(code: "bad_request", message: "\(field) is missing")
113
+ }
114
+ try checkFields(text, field: field)
115
+ let iso = ISO8601DateFormatter()
116
+ iso.formatOptions = [.withInternetDateTime]
117
+ if let d = iso.date(from: text) { return (d, false) }
118
+ iso.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
119
+ if let d = iso.date(from: text) { return (d, false) }
120
+ let normalized = text.replacingOccurrences(of: " ", with: "T")
121
+ for format in ["yyyy-MM-dd'T'HH:mm:ss", "yyyy-MM-dd'T'HH:mm"] {
122
+ if let d = localFormatter(format).date(from: normalized) { return (d, false) }
123
+ }
124
+ if let d = localFormatter("yyyy-MM-dd").date(from: text) { return (d, true) }
125
+ throw Failure(code: "bad_request", message: "\(field) is not a time: \(text)")
126
+ }
127
+
128
+ func isoString(_ date: Date) -> String {
129
+ let f = ISO8601DateFormatter()
130
+ f.formatOptions = [.withInternetDateTime]
131
+ f.timeZone = zone
132
+ return f.string(from: date)
133
+ }
134
+
135
+ /// `day` at the clock time of `clock` (both in the owner's zone).
136
+ func combine(day: Date, clock: Date) -> Date {
137
+ let t = calendar.dateComponents([.hour, .minute, .second], from: clock)
138
+ return calendar.date(bySettingHour: t.hour ?? 0, minute: t.minute ?? 0, second: t.second ?? 0, of: day) ?? day
139
+ }
140
+
141
+ // MARK: - EventKit helpers
142
+
143
+ let store = EKEventStore()
144
+
145
+ func authorization() -> String {
146
+ switch EKEventStore.authorizationStatus(for: .event) {
147
+ case .notDetermined: return "notDetermined"
148
+ case .restricted: return "restricted"
149
+ case .denied: return "denied"
150
+ case .fullAccess: return "fullAccess"
151
+ case .writeOnly: return "writeOnly"
152
+ @unknown default: return "unknown"
153
+ }
154
+ }
155
+
156
+ func requireFullAccess() throws {
157
+ let state = authorization()
158
+ guard state == "fullAccess" else {
159
+ throw Failure(code: "not_authorized", message: state)
160
+ }
161
+ }
162
+
163
+ /// Wait for an async EventKit callback without a UI run loop of our own.
164
+ func waitFor(seconds: TimeInterval, _ done: () -> Bool) -> Bool {
165
+ let until = Date().addingTimeInterval(seconds)
166
+ while !done() && Date() < until {
167
+ RunLoop.current.run(mode: .default, before: Date().addingTimeInterval(0.1))
168
+ }
169
+ return done()
170
+ }
171
+
172
+ func sourceType(_ type: EKSourceType) -> String {
173
+ switch type {
174
+ case .local: return "local"
175
+ case .exchange: return "exchange"
176
+ case .calDAV: return "caldav"
177
+ case .mobileMe: return "mobileme"
178
+ case .subscribed: return "subscribed"
179
+ case .birthdays: return "birthdays"
180
+ @unknown default: return "other"
181
+ }
182
+ }
183
+
184
+ func describe(_ calendar: EKCalendar) -> [String: Any] {
185
+ [
186
+ "id": calendar.calendarIdentifier,
187
+ "title": calendar.title,
188
+ "account": calendar.source?.title ?? "",
189
+ "accountType": calendar.source.map { sourceType($0.sourceType) } ?? "",
190
+ "writable": calendar.allowsContentModifications,
191
+ ]
192
+ }
193
+
194
+ func eventCalendars() -> [EKCalendar] {
195
+ store.calendars(for: .event)
196
+ }
197
+
198
+ func calendar(id: String) throws -> EKCalendar {
199
+ guard let cal = store.calendar(withIdentifier: id) else {
200
+ throw Failure(code: "no_calendar", message: "calendar \(id) not found")
201
+ }
202
+ return cal
203
+ }
204
+
205
+ func describe(_ event: EKEvent) -> [String: Any] {
206
+ var out: [String: Any] = [
207
+ "id": event.eventIdentifier ?? "",
208
+ "calendarId": event.calendar?.calendarIdentifier ?? "",
209
+ "calendar": event.calendar?.title ?? "",
210
+ "account": event.calendar?.source?.title ?? "",
211
+ "title": event.title ?? "",
212
+ "start": isoString(event.startDate),
213
+ "end": isoString(event.endDate),
214
+ "allDay": event.isAllDay,
215
+ "recurring": event.hasRecurrenceRules,
216
+ ]
217
+ if let location = event.location, !location.isEmpty { out["location"] = location }
218
+ if let notes = event.notes, !notes.isEmpty { out["notes"] = notes }
219
+ if let url = event.url { out["url"] = url.absoluteString }
220
+ if let occurrence = event.occurrenceDate { out["occurrence"] = isoString(occurrence) }
221
+ if let attendees = event.attendees, !attendees.isEmpty {
222
+ out["attendees"] = attendees.count
223
+ out["organizerIsMe"] = event.organizer?.isCurrentUser ?? false
224
+ }
225
+ if let alarms = event.alarms, !alarms.isEmpty {
226
+ out["alertMinutes"] = alarms.compactMap { $0.absoluteDate == nil ? Int(-$0.relativeOffset / 60) : nil }
227
+ }
228
+ return out
229
+ }
230
+
231
+ /// One occurrence by its event id. Recurring occurrences share an id, so the
232
+ /// caller also gives the occurrence's ORIGINAL date (it never changes, even when
233
+ /// that occurrence was moved) and its current start; both are searched.
234
+ func occurrence(id: String, original raw: Any?, current rawCurrent: Any?) throws -> EKEvent {
235
+ guard let master = store.event(withIdentifier: id) else {
236
+ throw Failure(code: "no_event", message: "event not found (it may have been deleted)")
237
+ }
238
+ guard master.hasRecurrenceRules, raw != nil else { return master }
239
+ let original = try parseTime(raw, field: "occurrence").date
240
+ let current = rawCurrent == nil ? original : try parseTime(rawCurrent, field: "start").date
241
+ let from = min(original, current).addingTimeInterval(-86_400)
242
+ let to = max(original, current).addingTimeInterval(86_400)
243
+ let predicate = store.predicateForEvents(withStart: from, end: to, calendars: [master.calendar])
244
+ let match = store.events(matching: predicate).first {
245
+ $0.eventIdentifier == id && abs(($0.occurrenceDate ?? $0.startDate).timeIntervalSince(original)) < 60
246
+ }
247
+ guard let found = match else {
248
+ throw Failure(code: "no_event", message: "that occurrence is not in the calendar any more")
249
+ }
250
+ return found
251
+ }
252
+
253
+ /// Events in a window that overlap [start, end), apart from `except`.
254
+ func overlaps(_ start: Date, _ end: Date, except: String?) -> [[String: Any]] {
255
+ let predicate = store.predicateForEvents(withStart: start, end: end, calendars: nil)
256
+ return store.events(matching: predicate)
257
+ .filter { !$0.isAllDay && $0.eventIdentifier != except && $0.startDate < end && $0.endDate > start }
258
+ .prefix(10)
259
+ .map { ["title": $0.title ?? "", "calendar": $0.calendar?.title ?? "", "start": isoString($0.startDate), "end": isoString($0.endDate)] }
260
+ }
261
+
262
+ /// Apply the requested fields. On update an event keeps being all-day or timed
263
+ /// unless `allDay` says otherwise, and a date-only start moves a timed event to
264
+ /// that day at its own time.
265
+ func applyFields(_ event: EKEvent, _ request: [String: Any], creating: Bool) throws {
266
+ if let title = request["title"] as? String { event.title = title }
267
+ if let location = request["location"] as? String { event.location = location.isEmpty ? nil : location }
268
+ if let notes = request["notes"] as? String { event.notes = notes.isEmpty ? nil : notes }
269
+ if let more = request["addNotes"] as? String, !more.isEmpty {
270
+ let existing = event.notes ?? ""
271
+ event.notes = existing.isEmpty ? more : "\(existing)\n\(more)"
272
+ }
273
+ if let url = request["url"] as? String { event.url = url.isEmpty ? nil : URL(string: url) }
274
+
275
+ let allDayAsked = request["allDay"] as? Bool
276
+ let hasStart = request["start"] != nil
277
+ let hasEnd = request["end"] != nil
278
+ if hasStart || hasEnd || allDayAsked != nil {
279
+ let parsedStart = hasStart ? try parseTime(request["start"], field: "start") : nil
280
+ let wholeDay: Bool = creating
281
+ ? (allDayAsked ?? parsedStart?.dateOnly ?? false)
282
+ : (allDayAsked ?? event.isAllDay)
283
+ let parsedEnd = hasEnd ? try parseTime(request["end"], field: "end") : nil
284
+
285
+ if wholeDay {
286
+ // Days, inclusive: EventKit's rule for all-day events.
287
+ let oldFirst = calendar.startOfDay(for: event.startDate ?? Date())
288
+ let oldLast = calendar.startOfDay(for: event.endDate ?? Date())
289
+ let first = parsedStart.map { calendar.startOfDay(for: $0.date) } ?? oldFirst
290
+ var last: Date
291
+ if let end = parsedEnd {
292
+ // A date is the last day; a time is an exclusive end (so 10-16 00:00 means through 10-15).
293
+ last = calendar.startOfDay(for: end.dateOnly ? end.date : end.date.addingTimeInterval(-1))
294
+ } else if creating || !event.isAllDay {
295
+ last = first
296
+ } else {
297
+ let days = calendar.dateComponents([.day], from: oldFirst, to: oldLast).day ?? 0
298
+ last = calendar.date(byAdding: .day, value: days, to: first) ?? first
299
+ }
300
+ if last < first { throw Failure(code: "bad_request", message: "the last day is before the first") }
301
+ event.isAllDay = true
302
+ event.startDate = first
303
+ event.endDate = last
304
+ } else {
305
+ var start: Date
306
+ if let s = parsedStart {
307
+ // A bare date on a timed event: that day, at the event's own time.
308
+ start = s.dateOnly && !creating && !event.isAllDay ? combine(day: s.date, clock: event.startDate) : s.date
309
+ } else {
310
+ start = event.startDate
311
+ }
312
+ var end: Date
313
+ if let e = parsedEnd {
314
+ end = e.dateOnly && !creating && !event.isAllDay ? combine(day: e.date, clock: event.endDate) : e.date
315
+ } else if creating || event.isAllDay {
316
+ end = start.addingTimeInterval(3_600)
317
+ } else if hasStart {
318
+ end = start.addingTimeInterval(event.endDate.timeIntervalSince(event.startDate))
319
+ } else {
320
+ end = event.endDate
321
+ }
322
+ if end <= start { throw Failure(code: "bad_request", message: "the end must be after the start") }
323
+ event.isAllDay = false
324
+ event.startDate = start
325
+ event.endDate = end
326
+ }
327
+ }
328
+ if let minutes = request["alertMinutes"] as? [Any] {
329
+ for alarm in event.alarms ?? [] { event.removeAlarm(alarm) }
330
+ for value in minutes {
331
+ if let m = (value as? NSNumber)?.doubleValue, m >= 0 { event.addAlarm(EKAlarm(relativeOffset: -m * 60)) }
332
+ }
333
+ }
334
+ }
335
+
336
+ func span(_ request: [String: Any]) -> EKSpan {
337
+ (request["span"] as? String) == "future" ? .futureEvents : .thisEvent
338
+ }
339
+
340
+ /// The dedicated calendar.
341
+ /// - `knownId`: the one this plugin created or the owner approved before.
342
+ /// - `adoptId`: an existing calendar with that title the owner just approved.
343
+ /// - Otherwise a writable calendar with the same title is NOT taken silently
344
+ /// (it may be shared, or the owner's real "Work"): it comes back as
345
+ /// `name_taken` so the owner can be asked. If none exists, a new one is made,
346
+ /// iCloud first so it reaches the phone (Google refuses new calendars over
347
+ /// CalDAV; a default in a work Exchange account is not where private planning
348
+ /// belongs).
349
+ func ensureCalendar(_ request: [String: Any]) throws -> [String: Any] {
350
+ guard let name = (request["name"] as? String)?.trimmingCharacters(in: .whitespaces), !name.isEmpty else {
351
+ throw Failure(code: "bad_request", message: "name is missing")
352
+ }
353
+ if let known = request["knownId"] as? String, let cal = store.calendar(withIdentifier: known), cal.allowsContentModifications {
354
+ return ["ok": true, "calendar": describe(cal), "created": false]
355
+ }
356
+ if let adopt = request["adoptId"] as? String {
357
+ guard let cal = store.calendar(withIdentifier: adopt), cal.allowsContentModifications, cal.title == name else {
358
+ throw Failure(code: "no_calendar", message: "that calendar is gone or read-only")
359
+ }
360
+ return ["ok": true, "calendar": describe(cal), "created": false]
361
+ }
362
+ let same = eventCalendars().filter { $0.title == name && $0.allowsContentModifications }
363
+ if !same.isEmpty {
364
+ return ["ok": false, "code": "name_taken", "error": "a writable calendar named \(name) already exists",
365
+ "calendars": same.map(describe)]
366
+ }
367
+ try beforeDeadline()
368
+ var sources: [EKSource] = []
369
+ sources += store.sources.filter { $0.sourceType == .calDAV && $0.title.lowercased().contains("icloud") }
370
+ if let preferred = store.defaultCalendarForNewEvents?.source { sources.append(preferred) }
371
+ sources += store.sources.filter { $0.sourceType == .calDAV || $0.sourceType == .exchange }
372
+ sources += store.sources.filter { $0.sourceType == .local }
373
+ var seen = Set<String>()
374
+ var lastError = "no account accepts new calendars"
375
+ for source in sources where seen.insert(source.sourceIdentifier).inserted {
376
+ let cal = EKCalendar(for: .event, eventStore: store)
377
+ cal.title = name
378
+ cal.source = source
379
+ do {
380
+ try store.saveCalendar(cal, commit: true)
381
+ return ["ok": true, "calendar": describe(cal), "created": true]
382
+ } catch {
383
+ lastError = "\(source.title): \(error.localizedDescription)"
384
+ }
385
+ }
386
+ throw Failure(code: "create_failed", message: lastError)
387
+ }
388
+
389
+ /// The occurrence an update or delete names, in the calendar the caller saw it in.
390
+ func target(_ request: [String: Any]) throws -> EKEvent {
391
+ let event = try occurrence(id: request["eventId"] as? String ?? "", original: request["occurrence"], current: request["currentStart"])
392
+ if let expected = request["expectCalendarId"] as? String, expected != event.calendar.calendarIdentifier {
393
+ throw Failure(code: "calendar_changed", message: event.calendar.title)
394
+ }
395
+ guard event.calendar.allowsContentModifications else {
396
+ throw Failure(code: "read_only", message: "calendar \(event.calendar.title) is read-only")
397
+ }
398
+ return event
399
+ }
400
+
401
+ // MARK: - Commands
402
+
403
+ func handle(_ request: [String: Any]) throws -> [String: Any] {
404
+ if let id = request["timeZone"] as? String, let tz = TimeZone(identifier: id) {
405
+ zone = tz
406
+ // EventKit floats all-day dates in the process's default zone: keep it the same.
407
+ NSTimeZone.default = tz
408
+ }
409
+ let cmd = request["cmd"] as? String ?? ""
410
+ switch cmd {
411
+ case "status":
412
+ return ["ok": true, "authorization": authorization()]
413
+
414
+ case "request":
415
+ if authorization() == "notDetermined" {
416
+ var finished = false
417
+ store.requestFullAccessToEvents { _, _ in finished = true }
418
+ let wait = (request["waitSeconds"] as? NSNumber)?.doubleValue ?? 120
419
+ _ = waitFor(seconds: wait) { finished }
420
+ }
421
+ return ["ok": true, "authorization": authorization()]
422
+
423
+ case "calendars":
424
+ try requireFullAccess()
425
+ return ["ok": true, "calendars": eventCalendars().map(describe)]
426
+
427
+ case "events":
428
+ try requireFullAccess()
429
+ let from = try parseTime(request["from"], field: "from").date
430
+ let to = try parseTime(request["to"], field: "to").date
431
+ guard to > from else { throw Failure(code: "bad_request", message: "to must be after from") }
432
+ // 92 calendar days, with room for a daylight-saving hour.
433
+ guard to.timeIntervalSince(from) <= 92 * 86_400 + 3_600 else {
434
+ throw Failure(code: "bad_request", message: "at most 92 days at a time")
435
+ }
436
+ let predicate = store.predicateForEvents(withStart: from, end: to, calendars: nil)
437
+ let events = store.events(matching: predicate).sorted { $0.startDate < $1.startDate }
438
+ return ["ok": true, "events": events.map(describe), "calendars": eventCalendars().map(describe)]
439
+
440
+ case "ensureCalendar":
441
+ try requireFullAccess()
442
+ return try ensureCalendar(request)
443
+
444
+ case "add":
445
+ try requireFullAccess()
446
+ let cal = try calendar(id: request["calendarId"] as? String ?? "")
447
+ guard cal.allowsContentModifications else {
448
+ throw Failure(code: "read_only", message: "calendar \(cal.title) is read-only")
449
+ }
450
+ guard let title = request["title"] as? String, !title.isEmpty else {
451
+ throw Failure(code: "bad_request", message: "title is missing")
452
+ }
453
+ let event = EKEvent(eventStore: store)
454
+ event.calendar = cal
455
+ try applyFields(event, request, creating: true)
456
+ try beforeDeadline()
457
+ try store.save(event, span: .thisEvent, commit: true)
458
+ return ["ok": true, "event": describe(event),
459
+ "overlaps": overlaps(event.startDate, event.endDate, except: event.eventIdentifier)]
460
+
461
+ case "update":
462
+ try requireFullAccess()
463
+ let event = try target(request)
464
+ if let moveTo = request["calendarId"] as? String, moveTo != event.calendar.calendarIdentifier {
465
+ let moved = try calendar(id: moveTo)
466
+ guard moved.allowsContentModifications else {
467
+ throw Failure(code: "read_only", message: "calendar \(moved.title) is read-only")
468
+ }
469
+ event.calendar = moved
470
+ }
471
+ try applyFields(event, request, creating: false)
472
+ try beforeDeadline()
473
+ try store.save(event, span: span(request), commit: true)
474
+ return ["ok": true, "event": describe(event),
475
+ "overlaps": overlaps(event.startDate, event.endDate, except: event.eventIdentifier)]
476
+
477
+ case "delete":
478
+ try requireFullAccess()
479
+ let event = try target(request)
480
+ let gone = describe(event)
481
+ try beforeDeadline()
482
+ try store.remove(event, span: span(request), commit: true)
483
+ return ["ok": true, "event": gone]
484
+
485
+ case "selftest":
486
+ // Runs applyFields on events that are never saved: needs no permission and
487
+ // touches no calendar. Lets the tests check EventKit's real date rules
488
+ // (all-day ends are inclusive) instead of a fake's.
489
+ var results: [[String: Any]] = []
490
+ for c in (request["cases"] as? [[String: Any]]) ?? [] {
491
+ let event = EKEvent(eventStore: store)
492
+ var row: [String: Any] = ["name": c["name"] as? String ?? ""]
493
+ do {
494
+ if let setup = c["setup"] as? [String: Any] { try applyFields(event, setup, creating: true) }
495
+ try applyFields(event, c["fields"] as? [String: Any] ?? [:], creating: c["setup"] == nil)
496
+ row["start"] = isoString(event.startDate)
497
+ row["end"] = isoString(event.endDate)
498
+ row["allDay"] = event.isAllDay
499
+ row["alerts"] = (event.alarms ?? []).map { Int(-$0.relativeOffset / 60) }
500
+ if let notes = event.notes { row["notes"] = notes }
501
+ } catch let f as Failure {
502
+ row["error"] = f.code
503
+ }
504
+ results.append(row)
505
+ }
506
+ return ["ok": true, "results": results]
507
+
508
+ default:
509
+ throw Failure(code: "bad_request", message: "unknown command \(cmd)")
510
+ }
511
+ }
512
+
513
+ // MARK: - Main
514
+
515
+ guard let requestPath = argument("--request"), let responsePath = argument("--response") else {
516
+ FileHandle.standardError.write(Data("usage: Clawbot-Calendar --request <file> --response <file>\n".utf8))
517
+ exit(2)
518
+ }
519
+ do {
520
+ let data = try Data(contentsOf: URL(fileURLWithPath: requestPath))
521
+ guard let request = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {
522
+ throw Failure(code: "bad_request", message: "request is not a JSON object")
523
+ }
524
+ if let ms = (request["deadline"] as? NSNumber)?.doubleValue {
525
+ let at = Date(timeIntervalSince1970: ms / 1000)
526
+ deadline = at
527
+ // Answer before the caller stops waiting, even if EventKit hangs: a write
528
+ // that lands after the caller gave up would be reported as a failure.
529
+ let wait = max(0.5, at.timeIntervalSinceNow)
530
+ DispatchQueue.global().asyncAfter(deadline: .now() + wait) {
531
+ // Unlike a refusal before committing ("deadline"), this one cannot know
532
+ // whether a save already in progress went through.
533
+ respond(["ok": false, "code": "timeout", "error": "took too long; a change may or may not have been saved"], to: responsePath)
534
+ exit(0)
535
+ }
536
+ }
537
+ respond(try handle(request), to: responsePath)
538
+ } catch let failure as Failure {
539
+ respond(["ok": false, "code": failure.code, "error": failure.message], to: responsePath)
540
+ } catch {
541
+ respond(["ok": false, "code": "error", "error": error.localizedDescription], to: responsePath)
542
+ }
543
+ exit(0)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "wechat-clawbot",
3
- "version": "1.1.0",
3
+ "version": "1.2.0",
4
4
  "description": "Connect DeepSeek Harness to WeChat via the official WeChat ClawBot (Tencent iLink) bridge — a DSH plugin bundle.",
5
5
  "keywords": [
6
6
  "deepseek-harness",
@@ -42,6 +42,7 @@
42
42
  },
43
43
  "files": [
44
44
  "lib",
45
+ "native",
45
46
  "cordis.patch.yml",
46
47
  "README.md",
47
48
  "README.zh.md",
@@ -112,7 +112,8 @@ grep -o 'http://127.0.0.1:3080/?token=[A-Za-z0-9_-]*' ~/.dsh/logs/dsh-web.out.lo
112
112
  |---|---|---|
113
113
  | 模型(provider、模型、思考等级)、允许发消息的人、图片相关四项、发文件预告阈值、emoji、审批等待超时、日志级别、拉活 Claude 会话的权限、开放 MCP 桥、空闲时整理对话、说明文件开关 | 网页「插件」→ wechat-clawbot → 微信 Bot | **立即生效**,微信连接不中断。日志:`设置已即时生效 […](没有重启,微信监听未中断)` |
114
114
  | `autoMemory`(自动记忆,默认开) | 只能手改配置文件 | 立即生效(下一条消息) |
115
- | `codexPeer`(Codex 会话联动,默认关) | 设置卡片或配置文件 | **会重启微信监听**(几秒) |
115
+ | `macCalendar`(Mac 日历)、`codexPeer`(Codex 会话联动),都默认关 | 设置卡片或配置文件 | **会重启微信监听**(几秒),因为 bot 的工具变了 |
116
+ | `macCalendarName`、`macCalendarAlert`、`macCalendarAlertMinutes`、`secretary`(日程秘书) | 设置卡片或配置文件 | 立即生效;日程秘书开关当场改写 `memory.md` |
116
117
  | `sessionId`、`cwd`、`autoStart`、`forwardQuestions`、`apiBaseUrl`、`botAgent`、`codexTransport`、`codexSocket`、`codexBinary` | 只能手改配置文件 | **会重启微信监听**(几秒) |
117
118
 
118
119
  改过的字段在卡片上会标「已覆盖」,旁边有「重置」。
@@ -183,6 +184,55 @@ DSH 的默认行为:bot 在哪个项目里干过活,那里的 AGENTS.md / CL
183
184
 
184
185
  具体配置见 README 的「和 Codex 联动」一节。
185
186
 
187
+ ### Mac 日历(`macCalendar`,默认关,仅 macOS)
188
+
189
+ 打开后,bot 能读到 Mac「日历」App 里所有账户的日程,范围包括 iCloud、Google、Exchange、CalDAV 和订阅日历;重复日程会展开,备注也会给 bot。它还能在一个**专用日历**里自主加、改、删日程,用来排时间块。
190
+
191
+ - **专用日历**:
192
+ - 名字由用户自己起,在设置卡片里填,没填名字开关打不开。
193
+ - 第一次添加时自动创建,优先建在 iCloud,手机上也看得到。插件按日历的编号认它,不按名字。
194
+ - 如果已经有同名的日历,bot 会先在微信里问一次要不要用它;不同意就换个名字。
195
+ - **别的日历**:动别的日历里的日程时,工具会先在微信里问用户,回「好」才执行。
196
+ - 问题只发给扫码登录的本人,并且确认发到了才开始等回答。
197
+ - 改重复日程的「以后每一次」、或者日程有其他参与者(改动可能会通知他们)时,问题里会写明。
198
+ - 用户回的不是「好」,原话会转给 bot 照着处理。
199
+ - **范围限制**:
200
+ - 只有扫码登录的本人能用这几个工具。白名单里还有其他人时,这几个工具**整体不开放**:大家共用同一个对话,日历内容会被别人看到。
201
+ - 加日程不会给任何人发邀请。
202
+ - **日历提醒**:bot 加日程时,默认带一个提前 10 分钟的日历提醒,手机上也会响。设置卡片「日历提醒」里可以关掉或改分钟数。全天日程不自动加。这个提醒不代替 bot 的微信提醒,两个都响没关系。
203
+
204
+ **怎么开**:网页「插件」→ wechat-clawbot → 微信 Bot →「Mac 日历」。先填专用日历的名字,再打开开关。改开关会重启微信监听。
205
+
206
+ **第一次打开会发生的事**:
207
+
208
+ 1. 插件用 Xcode 命令行工具在本机编译一个后台小程序 `Clawbot-Calendar.app`,放在 `~/.dsh/clawbot/calendar-helper/`。没有装工具的话,运行 `xcode-select --install`。
209
+ 2. Mac 屏幕上弹出「Clawbot-Calendar 想要访问你的日历」,要在电脑前点「允许」。没看到这个框,就去 系统设置 → 隐私与安全性 → 日历 打开它。
210
+ 3. 设置卡片里显示「已授权,能看到 N 个日历」就好了。
211
+
212
+ 关着时,这几个工具不会发给模型,不占 token。
213
+
214
+ **为什么单独做一个小程序**:macOS 把日历权限记在「负责的 App」名下。直接在 DSH 里读日历,权限会记到启动 DSH 的那个程序上(菜单栏 App 或终端),换个方式启动就没了。`Clawbot-Calendar` 通过 `open` 启动,权限归它自己。每次查询或修改大约 0.5–1 秒。
215
+
216
+ **要跟用户讲清的两点**:
217
+
218
+ - 插件更新时,如果这个小程序的源码改过,它会重新编译。重新编译后签名变了,系统会**再弹一次授权框**,要在电脑前再点一次「允许」。
219
+ - 权限是授给 `Clawbot-Calendar` 的。同一个 macOS 用户下的其他程序,理论上也能借它读写日历;bot 本身就有终端权限,所以这不算新的风险,但用户应该知道。
220
+
221
+ ### 日程秘书(`secretary`,默认关,要先开 Mac 日历)
222
+
223
+ 打开后,插件把一套排日程的规则写进长期记忆 `memory.md` 末尾的「## 日程秘书」一节。bot 每一轮都读记忆,所以下一条消息就按它来:
224
+
225
+ - 用户说待办、截止时间,或者问接下来做什么,bot 先查日历,直接排进专用日历再汇报,不反问。只说了哪天、没说几点的,找那天的空档。
226
+ - 先保住课程、会议、硬截止。一天一条主线、最多三个关键交付;深度工作 60–90 分钟一块,只排满 70–80%。
227
+ - 只说「提醒我…」的事只设微信提醒,不进日历。要占一段时间的事才排进日历,并且照样设微信提醒。
228
+ - 回复要短:几行编号说清几点做什么、挪走了什么、哪里有冲突。
229
+
230
+ **规则归用户自己**:可以直接在 `memory.md` 里改措辞、加减条目,下一条消息生效。关掉开关时,这一节移出记忆,存到 `~/.dsh/clawbot/secretary-rules.md`;再打开时放回的是用户改过的那一版,不是默认版。设置卡片「日程秘书」那一行有「打开 memory.md」按钮:在 Mac 上用 .md 文件的默认 App 打开它,没有默认 App 就用文本编辑。
231
+
232
+ **和 Mac 日历的关系**:Mac 日历没开时,秘书开关是灰的。秘书开着的时候关掉日历,规则也会移出记忆,秘书暂停;日历再打开就自动恢复。
233
+
234
+ 规则放在记忆里、不写进插件提示词,是因为它和人设一样属于用户:不开的人一个字都不占,开了的人想怎么改都行。开着时每轮多带约 400 字。
235
+
186
236
  ### DSH 会话联动(DSH 内部桥,1.1.0 起)
187
237
 
188
238
  bot 能看到同一个 DSH 里的其他会话,范围是所有工作目录,不只某一个文件夹:
@@ -319,6 +369,11 @@ legacy reminder schedule-7 carried over as schedule-3f2a9c1e-… (due 2026-10-01
319
369
  | 让 bot 给 Claude Code 会话捎话失败,报模型不受支持 | `claude` 命令行太旧,运行 `claude update` |
320
370
  | 桌面版打不开某个 Claude Code 会话,提示 Claude Code crashed | bot 刚把它拉到后台处理捎去的话,处理完会自动交还;急用就运行 `claude stop <会话 id 前 8 位>` |
321
371
  | 网页里的 DSH 会话说没有 `notify_wechat` 工具 | 插件早于 1.1.0,或者升级后还没重启 DSH |
372
+ | 「Mac 日历」开关打不开 | 先填专用日历的名字;不是 macOS 也打不开 |
373
+ | bot 说日历「还没授权」 | Mac 上有「Clawbot-Calendar」的授权窗口没点。在电脑前点「允许」,或者去 系统设置 → 隐私与安全性 → 日历 打开。插件更新后小程序重新编译过的话,也要再点一次 |
374
+ | bot 说「白名单里还有别人,日历工具不开放」 | 设计如此:白名单里的人和用户共用一个对话。要用日历,就把白名单清空 |
375
+ | 卡片显示「编译 Clawbot-Calendar 需要 Xcode 命令行工具」 | 运行 `xcode-select --install`,装完关掉再打开一次开关 |
376
+ | 开了日程秘书,bot 还是不主动排日程 | 看 `memory.md` 末尾有没有「## 日程秘书」一节,没有就把开关关掉再打开。Mac 日历也要开着 |
322
377
 
323
378
  ---
324
379