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
@@ -1,23 +1,31 @@
1
- // Clawbot-Calendar: the WeChat bot's bridge to the macOS Calendar (EventKit).
1
+ // Clawbot-Calendar: the WeChat bot's bridge to the macOS Calendar (EventKit)
2
+ // and to Reminders, for alarms (ReminderKit).
2
3
  //
3
4
  // The plugin builds this file into Clawbot-Calendar.app and launches it through
4
5
  // 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.
6
+ // so macOS treats the app as its own "responsible process": the calendar and
7
+ // reminders permission prompts name this app, and the grants do not depend on
8
+ // whatever started DSH (a menu-bar app, a terminal). Each launch handles one
9
+ // request and exits.
9
10
  //
10
11
  // Request (JSON file): { "cmd": "...", "timeZone": "America/New_York", "deadline": <epoch ms>, ... }
11
12
  // Response (JSON file): { "ok": true, ... } or { "ok": false, "error": "...", "code": "..." }
12
13
  //
13
14
  // Commands
14
- // status authorization state, no prompt
15
- // request ask for full access (shows the system prompt once)
15
+ // status both authorization states, whether alarms can work here, the protocol; no prompt
16
+ // request ask for full access to the calendar, then to reminders (each prompt once;
17
+ // `calendar` / `reminders`: false skips one)
16
18
  // calendars every event calendar with its account
17
19
  // events occurrences in [from, to), recurring ones expanded
18
20
  // ensureCalendar the dedicated calendar: a known id, an adopted one, or a new one
19
21
  // add add one event (and report what it overlaps)
20
22
  // update / delete change or remove one occurrence (or the series from it on)
23
+ // ensureAlarmList the reminders list alarms go into: a known id, one of that name, or a new one
24
+ // alarmAdd one alarm: an urgent reminder at a time of day
25
+ // alarms the reminders in the alarm list
26
+ // alarmDelete remove one alarm
27
+ // alarmComplete mark alarms done (ones that rang hours ago, so they do not pile up as overdue)
28
+ // rkcheck which ReminderKit pieces this macOS lacks (no permission needed)
21
29
  //
22
30
  // Times in: "2026-10-15T14:00" (local wall clock in timeZone), "2026-10-15"
23
31
  // (a date), or ISO 8601 with an offset. Times out: ISO 8601 with offset.
@@ -223,11 +231,18 @@ func describe(_ event: EKEvent) -> [String: Any] {
223
231
  out["organizerIsMe"] = event.organizer?.isCurrentUser ?? false
224
232
  }
225
233
  if let alarms = event.alarms, !alarms.isEmpty {
226
- out["alertMinutes"] = alarms.compactMap { $0.absoluteDate == nil ? Int(-$0.relativeOffset / 60) : nil }
234
+ out["alertMinutes"] = alarms.compactMap { $0.absoluteDate == nil ? alertMinutes($0) : nil }
227
235
  }
228
236
  return out
229
237
  }
230
238
 
239
+ /// An alert's minutes before the start; nil for one no calendar app would set
240
+ /// (Int() would trap on an absurd offset from some calendar server).
241
+ func alertMinutes(_ alarm: EKAlarm) -> Int? {
242
+ let minutes = -alarm.relativeOffset / 60
243
+ return minutes.isFinite && abs(minutes) < 1e9 ? Int(minutes) : nil
244
+ }
245
+
231
246
  /// One occurrence by its event id. Recurring occurrences share an id, so the
232
247
  /// caller also gives the occurrence's ORIGINAL date (it never changes, even when
233
248
  /// that occurrence was moved) and its current start; both are searched.
@@ -398,6 +413,422 @@ func target(_ request: [String: Any]) throws -> EKEvent {
398
413
  return event
399
414
  }
400
415
 
416
+ // MARK: - Alarms: urgent reminders through ReminderKit
417
+ //
418
+ // An alarm is an urgent reminder: Reminders rings it like an alarm on the
419
+ // owner's devices (macOS and iOS 26 and later), and iCloud carries it to the
420
+ // phone, so it rings even when WeChat could not deliver a message. EventKit,
421
+ // the public API, has no "urgent", so alarms go through ReminderKit, the
422
+ // private framework Reminders.app itself uses: the same remindd, the same
423
+ // Reminders permission. Private means any macOS update may change it, so every
424
+ // call first checks that the method is still there and fails with
425
+ // "reminderkit_missing" instead of crashing; `rkcheck` lists what is missing.
426
+ //
427
+ // Where it rings: only on the device Find My uses as the owner's location
428
+ // (usually the iPhone); other devices show a plain notification. And the phone
429
+ // has its own say: Reminders there asks to allow urgent alarms only the first
430
+ // time someone marks a reminder urgent there by hand.
431
+ //
432
+ // Protocol 2 = this file has the alarm commands; 3 = also alarmComplete, and
433
+ // `status` says whether alarms can work on this macOS. The plugin reads it
434
+ // from `status` and tells an older build apart without asking it anything new.
435
+ // Every change to this file bumps it (a regression test holds the two together).
436
+ let helperProtocol = 3
437
+
438
+ func remindersAuthorization() -> String {
439
+ switch EKEventStore.authorizationStatus(for: .reminder) {
440
+ case .notDetermined: return "notDetermined"
441
+ case .restricted: return "restricted"
442
+ case .denied: return "denied"
443
+ case .fullAccess: return "fullAccess"
444
+ case .writeOnly: return "writeOnly"
445
+ @unknown default: return "unknown"
446
+ }
447
+ }
448
+
449
+ func requireRemindersAccess() throws {
450
+ let state = remindersAuthorization()
451
+ guard state == "fullAccess" else {
452
+ throw Failure(code: "reminders_not_authorized", message: state)
453
+ }
454
+ }
455
+
456
+ /// Typed calls into ReminderKit through the Objective-C runtime. Its objects keep
457
+ /// most fields in a storage object they forward to, so "does it answer" asks both.
458
+ enum RK {
459
+ static var loaded = false
460
+
461
+ static func load() throws {
462
+ if loaded { return }
463
+ guard let bundle = Bundle(path: "/System/Library/PrivateFrameworks/ReminderKit.framework"), bundle.load() else {
464
+ throw Failure(code: "reminderkit_missing", message: "ReminderKit could not be loaded")
465
+ }
466
+ loaded = true
467
+ }
468
+
469
+ static func missing(_ what: String) -> Failure {
470
+ Failure(code: "reminderkit_missing", message: "ReminderKit changed: \(what) is gone")
471
+ }
472
+
473
+ static func answers(_ target: NSObject, _ sel: Selector) -> Bool {
474
+ if target.responds(to: sel) { return true }
475
+ if let other = target.forwardingTarget(for: sel) as? NSObject { return other.responds(to: sel) }
476
+ return false
477
+ }
478
+
479
+ static func selector(_ target: NSObject, _ name: String) throws -> Selector {
480
+ let sel = NSSelectorFromString(name)
481
+ guard answers(target, sel) else { throw missing("\(type(of: target)).\(name)") }
482
+ return sel
483
+ }
484
+
485
+ /// An object-returning method with up to three object arguments. Not owned (+0).
486
+ static func object(_ target: NSObject, _ name: String, _ args: AnyObject?...) throws -> NSObject? {
487
+ let sel = try selector(target, name)
488
+ let imp = target.method(for: sel)
489
+ switch args.count {
490
+ case 0:
491
+ typealias F = @convention(c) (NSObject, Selector) -> Unmanaged<NSObject>?
492
+ return unsafeBitCast(imp, to: F.self)(target, sel)?.takeUnretainedValue()
493
+ case 1:
494
+ typealias F = @convention(c) (NSObject, Selector, AnyObject?) -> Unmanaged<NSObject>?
495
+ return unsafeBitCast(imp, to: F.self)(target, sel, args[0])?.takeUnretainedValue()
496
+ case 2:
497
+ typealias F = @convention(c) (NSObject, Selector, AnyObject?, AnyObject?) -> Unmanaged<NSObject>?
498
+ return unsafeBitCast(imp, to: F.self)(target, sel, args[0], args[1])?.takeUnretainedValue()
499
+ case 3:
500
+ typealias F = @convention(c) (NSObject, Selector, AnyObject?, AnyObject?, AnyObject?) -> Unmanaged<NSObject>?
501
+ return unsafeBitCast(imp, to: F.self)(target, sel, args[0], args[1], args[2])?.takeUnretainedValue()
502
+ default:
503
+ throw Failure(code: "error", message: "too many arguments for \(name)")
504
+ }
505
+ }
506
+
507
+ /// A fetch that reports failure through a trailing NSError**.
508
+ static func fetch(_ target: NSObject, _ name: String, _ args: AnyObject?...) throws -> NSObject? {
509
+ let sel = try selector(target, name)
510
+ let imp = target.method(for: sel)
511
+ var error: Unmanaged<NSError>? = nil
512
+ let result: NSObject?
513
+ switch args.count {
514
+ case 0:
515
+ typealias F = @convention(c) (NSObject, Selector, UnsafeMutablePointer<Unmanaged<NSError>?>) -> Unmanaged<NSObject>?
516
+ result = unsafeBitCast(imp, to: F.self)(target, sel, &error)?.takeUnretainedValue()
517
+ case 1:
518
+ typealias F = @convention(c) (NSObject, Selector, AnyObject?, UnsafeMutablePointer<Unmanaged<NSError>?>) -> Unmanaged<NSObject>?
519
+ result = unsafeBitCast(imp, to: F.self)(target, sel, args[0], &error)?.takeUnretainedValue()
520
+ default:
521
+ throw Failure(code: "error", message: "too many arguments for \(name)")
522
+ }
523
+ if result == nil, let e = error?.takeUnretainedValue() {
524
+ throw Failure(code: "reminders_error", message: e.localizedDescription)
525
+ }
526
+ return result
527
+ }
528
+
529
+ static func bool(_ target: NSObject, _ name: String) throws -> Bool {
530
+ let sel = try selector(target, name)
531
+ typealias F = @convention(c) (NSObject, Selector) -> Bool
532
+ return unsafeBitCast(target.method(for: sel), to: F.self)(target, sel)
533
+ }
534
+
535
+ /// A void method with no argument or one object argument.
536
+ static func perform(_ target: NSObject, _ name: String, _ arg: AnyObject? = nil, hasArgument: Bool = false) throws {
537
+ let sel = try selector(target, name)
538
+ let imp = target.method(for: sel)
539
+ if hasArgument {
540
+ typealias F = @convention(c) (NSObject, Selector, AnyObject?) -> Void
541
+ unsafeBitCast(imp, to: F.self)(target, sel, arg)
542
+ } else {
543
+ typealias F = @convention(c) (NSObject, Selector) -> Void
544
+ unsafeBitCast(imp, to: F.self)(target, sel)
545
+ }
546
+ }
547
+
548
+ static func setBool(_ target: NSObject, _ name: String, _ value: Bool) throws {
549
+ let sel = try selector(target, name)
550
+ typealias F = @convention(c) (NSObject, Selector, Bool) -> Void
551
+ unsafeBitCast(target.method(for: sel), to: F.self)(target, sel, value)
552
+ }
553
+
554
+ /// `[[ClassName alloc] initName:arg]`, owned by the caller. The init gets its
555
+ /// own reference to consume, so this stays balanced whether it returns the
556
+ /// allocated object or another one.
557
+ static func make(_ className: String, _ initName: String, object arg: AnyObject? = nil, bool flag: Bool? = nil) throws -> NSObject {
558
+ try load()
559
+ guard let cls: AnyClass = NSClassFromString(className), let meta = object_getClass(cls) else { throw missing(className) }
560
+ let allocSel = NSSelectorFromString("alloc")
561
+ typealias Alloc = @convention(c) (AnyClass, Selector) -> Unmanaged<NSObject>?
562
+ guard let allocIMP = class_getMethodImplementation(meta, allocSel),
563
+ let raw = unsafeBitCast(allocIMP, to: Alloc.self)(cls, allocSel)?.takeRetainedValue() else {
564
+ throw missing("\(className) alloc")
565
+ }
566
+ let sel = try selector(raw, initName)
567
+ let imp = raw.method(for: sel)
568
+ _ = Unmanaged.passUnretained(raw).retain()
569
+ let made: NSObject?
570
+ if let flag {
571
+ typealias F = @convention(c) (NSObject, Selector, Bool) -> Unmanaged<NSObject>?
572
+ made = unsafeBitCast(imp, to: F.self)(raw, sel, flag)?.takeRetainedValue()
573
+ } else {
574
+ typealias F = @convention(c) (NSObject, Selector, AnyObject?) -> Unmanaged<NSObject>?
575
+ made = unsafeBitCast(imp, to: F.self)(raw, sel, arg)?.takeRetainedValue()
576
+ }
577
+ guard let made else { throw Failure(code: "reminders_error", message: "\(className) \(initName) returned nil") }
578
+ return made
579
+ }
580
+
581
+ static func save(_ request: NSObject) throws {
582
+ let sel = try selector(request, "saveSynchronouslyWithError:")
583
+ typealias F = @convention(c) (NSObject, Selector, UnsafeMutablePointer<Unmanaged<NSError>?>) -> Bool
584
+ var error: Unmanaged<NSError>? = nil
585
+ guard unsafeBitCast(request.method(for: sel), to: F.self)(request, sel, &error) else {
586
+ throw Failure(code: "save_failed", message: error?.takeUnretainedValue().localizedDescription ?? "Reminders did not save")
587
+ }
588
+ }
589
+ }
590
+
591
+ var remindersStore: NSObject? = nil
592
+
593
+ func reminderStore() throws -> NSObject {
594
+ if let s = remindersStore { return s }
595
+ try requireRemindersAccess()
596
+ let s = try RK.make("REMStore", "initUserInteractive:", bool: true)
597
+ remindersStore = s
598
+ return s
599
+ }
600
+
601
+ func uuidOf(_ object: NSObject?) -> String? {
602
+ guard let object, let oid = try? RK.object(object, "objectID"), let uuid = try? RK.object(oid, "uuid") else { return nil }
603
+ return (uuid as? NSUUID)?.uuidString
604
+ }
605
+
606
+ func text(_ object: NSObject, _ name: String) -> String? {
607
+ ((try? RK.object(object, name)) ?? nil) as? String
608
+ }
609
+
610
+ /// Lists only (groups hold lists and take no reminders).
611
+ func reminderLists(_ rem: NSObject) throws -> [NSObject] {
612
+ let lists = (try RK.fetch(rem, "fetchEligibleDefaultListsWithError:") as? [NSObject]) ?? []
613
+ return lists.filter { !((try? RK.bool($0, "isGroup")) ?? false) }
614
+ }
615
+
616
+ func accountName(_ account: NSObject?) -> String {
617
+ guard let account else { return "" }
618
+ return text(account, "name") ?? ""
619
+ }
620
+
621
+ func describeList(_ list: NSObject) -> [String: Any] {
622
+ ["id": uuidOf(list) ?? "", "name": text(list, "name") ?? "", "account": accountName((try? RK.object(list, "account")) ?? nil)]
623
+ }
624
+
625
+ /// Where alarms live: the primary iCloud account, which must support urgent alarms.
626
+ func alarmAccount(_ rem: NSObject) throws -> NSObject {
627
+ guard let account = try RK.fetch(rem, "fetchPrimaryActiveCloudKitAccountWithError:") else {
628
+ throw Failure(code: "no_icloud", message: "Reminders has no active iCloud account")
629
+ }
630
+ if let capabilities = try RK.object(account, "capabilities"), try !RK.bool(capabilities, "supportsUrgentAlarm") {
631
+ throw Failure(code: "no_urgent", message: "the iCloud account \(accountName(account)) does not support urgent reminders")
632
+ }
633
+ return account
634
+ }
635
+
636
+ /// The alarm list:
637
+ /// - `knownId`: the one used before.
638
+ /// - Otherwise a list with exactly this name in the alarm account (the owner
639
+ /// made it, or it outlived the record of it): an alarm list is what it is for.
640
+ /// - Otherwise a new one in that account.
641
+ func ensureAlarmList(_ request: [String: Any]) throws -> [String: Any] {
642
+ guard let name = (request["name"] as? String)?.trimmingCharacters(in: .whitespaces), !name.isEmpty else {
643
+ throw Failure(code: "bad_request", message: "name is missing")
644
+ }
645
+ let rem = try reminderStore()
646
+ let lists = try reminderLists(rem)
647
+ if let known = (request["knownId"] as? String)?.uppercased(), let list = lists.first(where: { uuidOf($0) == known }) {
648
+ return ["ok": true, "list": describeList(list), "created": false]
649
+ }
650
+ let account = try alarmAccount(rem)
651
+ let accountID = uuidOf(account)
652
+ if let same = lists.first(where: { text($0, "name") == name && uuidOf((try? RK.object($0, "account")) ?? nil) == accountID }) {
653
+ return ["ok": true, "list": describeList(same), "created": false, "adopted": true]
654
+ }
655
+ try beforeDeadline()
656
+ let save = try RK.make("REMSaveRequest", "initWithStore:", object: rem)
657
+ guard let accountChange = try RK.object(save, "updateAccount:", account),
658
+ let listChange = try RK.object(save, "addListWithName:toAccountChangeItem:listObjectID:", name as NSString, accountChange, nil),
659
+ let id = uuidOf(listChange) else {
660
+ throw Failure(code: "create_failed", message: "Reminders did not make the list")
661
+ }
662
+ try RK.save(save)
663
+ // Made: a read that fails from here on is not a failure (the next call finds it by name).
664
+ let made = ((try? reminderLists(rem)) ?? []).first { uuidOf($0) == id }
665
+ return ["ok": true, "list": made.map(describeList) ?? ["id": id, "name": name, "account": accountName(account)], "created": true]
666
+ }
667
+
668
+ func alarmList(_ rem: NSObject, _ raw: Any?) throws -> NSObject {
669
+ let id = ((raw as? String) ?? "").uppercased()
670
+ guard let list = try reminderLists(rem).first(where: { uuidOf($0) == id }) else {
671
+ throw Failure(code: "no_list", message: "the alarm list is gone")
672
+ }
673
+ return list
674
+ }
675
+
676
+ func remindersIn(_ rem: NSObject, _ list: NSObject) throws -> [NSObject] {
677
+ guard let listID = try RK.object(list, "objectID") else { throw RK.missing("REMList.objectID") }
678
+ return (try RK.fetch(rem, "fetchRemindersForEventKitBridgingWithListIDs:error:", [listID] as NSArray) as? [NSObject]) ?? []
679
+ }
680
+
681
+ /// A due date as Reminders keeps it (wall clock, maybe with a zone) as an instant.
682
+ func instant(_ raw: NSObject?) -> Date? {
683
+ guard var parts = raw as? DateComponents ?? (raw as? NSDateComponents).map({ $0 as DateComponents }) else { return nil }
684
+ var cal = Calendar(identifier: .gregorian)
685
+ cal.timeZone = parts.timeZone ?? zone
686
+ parts.timeZone = nil
687
+ parts.calendar = nil
688
+ return cal.date(from: parts)
689
+ }
690
+
691
+ /// No fallback through urgentAlarmContext: that context only forwards to this
692
+ /// same getter, so where the getter is gone it would crash instead of saying no.
693
+ func isUrgent(_ reminder: NSObject) -> Bool {
694
+ (try? RK.bool(reminder, "isUrgentStateEnabledForCurrentUser")) ?? false
695
+ }
696
+
697
+ func describeAlarm(_ reminder: NSObject) -> [String: Any] {
698
+ var out: [String: Any] = [
699
+ "id": uuidOf(reminder) ?? "",
700
+ "title": text(reminder, "titleAsString") ?? "",
701
+ "completed": (try? RK.bool(reminder, "isCompleted")) ?? false,
702
+ "urgent": isUrgent(reminder),
703
+ ]
704
+ if let due = instant((try? RK.object(reminder, "dueDateComponents")) ?? nil) { out["due"] = isoString(due) }
705
+ if let notes = text(reminder, "notesAsString"), !notes.isEmpty { out["notes"] = notes }
706
+ return out
707
+ }
708
+
709
+ func addAlarm(_ request: [String: Any]) throws -> [String: Any] {
710
+ // The request is checked before Reminders is opened: that needs no permission.
711
+ guard let title = (request["title"] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines), !title.isEmpty else {
712
+ throw Failure(code: "bad_request", message: "title is missing")
713
+ }
714
+ let due = try parseTime(request["due"], field: "due")
715
+ if due.dateOnly { throw Failure(code: "bad_request", message: "an alarm needs a time of day") }
716
+ if due.date <= Date() { throw Failure(code: "past", message: "that time has already passed") }
717
+ var parts = calendar.dateComponents([.year, .month, .day, .hour, .minute], from: due.date)
718
+ parts.timeZone = zone
719
+ // Reminders keeps a wall clock and a zone. In the hour the clocks go back one
720
+ // wall time names two instants and reads back as the first: refuse the second
721
+ // rather than ring an hour early.
722
+ if let back = instant(parts as NSDateComponents), abs(back.timeIntervalSince(due.date)) > 1 {
723
+ throw Failure(code: "ambiguous", message: "that wall-clock time happens twice (clocks going back); only the first can be set")
724
+ }
725
+ let rem = try reminderStore()
726
+ let list = try alarmList(rem, request["listId"])
727
+ try beforeDeadline()
728
+ let save = try RK.make("REMSaveRequest", "initWithStore:", object: rem)
729
+ guard let listChange = try RK.object(save, "updateList:", list),
730
+ let change = try RK.object(save, "addReminderWithTitle:toListChangeItem:", title as NSString, listChange),
731
+ let id = uuidOf(change) else {
732
+ throw Failure(code: "create_failed", message: "Reminders did not make the alarm")
733
+ }
734
+ // A due time with its default alert, then the urgent state on top of it.
735
+ try RK.perform(change, "setDueDateComponentsWithAlarmsIfNeeded:", parts as NSDateComponents, hasArgument: true)
736
+ if let notes = request["notes"] as? String, !notes.isEmpty {
737
+ try RK.perform(change, "setNotesAsString:", notes as NSString, hasArgument: true)
738
+ }
739
+ guard let urgent = try RK.object(change, "urgentAlarmContext") else { throw RK.missing("urgentAlarmContext") }
740
+ try RK.setBool(urgent, "setIsUrgentStateEnabledForCurrentUser:", true)
741
+ try RK.save(save)
742
+ // What Reminders actually kept, urgent state included. The alarm exists from
743
+ // here on, so a read that fails now is not a failure: reporting one would
744
+ // have the caller set it again, and the owner would get two.
745
+ let saved = ((try? remindersIn(rem, list)) ?? []).first { uuidOf($0) == id }
746
+ return ["ok": true, "alarm": saved.map(describeAlarm) ?? ["id": id, "title": title, "due": isoString(due.date), "urgent": true, "completed": false]]
747
+ }
748
+
749
+ /// Alarms that rang a while ago stay open in Reminders (ringing does not
750
+ /// complete them) and would pile up as overdue items: mark them done.
751
+ func completeAlarms(_ request: [String: Any]) throws -> [String: Any] {
752
+ let rem = try reminderStore()
753
+ let list = try alarmList(rem, request["listId"])
754
+ let wanted = Set(((request["ids"] as? [Any]) ?? []).compactMap { ($0 as? String)?.uppercased() })
755
+ let open = try remindersIn(rem, list).filter {
756
+ guard let id = uuidOf($0), wanted.contains(id) else { return false }
757
+ return !((try? RK.bool($0, "isCompleted")) ?? false)
758
+ }
759
+ if open.isEmpty { return ["ok": true, "completed": 0] }
760
+ try beforeDeadline()
761
+ let save = try RK.make("REMSaveRequest", "initWithStore:", object: rem)
762
+ for reminder in open {
763
+ guard let change = try RK.object(save, "updateReminder:", reminder) else { throw RK.missing("updateReminder:") }
764
+ try RK.setBool(change, "setCompleted:", true)
765
+ }
766
+ try RK.save(save)
767
+ return ["ok": true, "completed": open.count]
768
+ }
769
+
770
+ func deleteAlarm(_ request: [String: Any]) throws -> [String: Any] {
771
+ let rem = try reminderStore()
772
+ let list = try alarmList(rem, request["listId"])
773
+ let id = ((request["id"] as? String) ?? "").uppercased()
774
+ guard let reminder = try remindersIn(rem, list).first(where: { uuidOf($0) == id }) else {
775
+ throw Failure(code: "no_alarm", message: "that alarm is not in the list any more")
776
+ }
777
+ let gone = describeAlarm(reminder)
778
+ try beforeDeadline()
779
+ let save = try RK.make("REMSaveRequest", "initWithStore:", object: rem)
780
+ guard let change = try RK.object(save, "updateReminder:", reminder) else { throw RK.missing("updateReminder:") }
781
+ try RK.perform(change, "removeFromList")
782
+ try RK.save(save)
783
+ return ["ok": true, "alarm": gone]
784
+ }
785
+
786
+ /// What the alarm commands rely on, checked on the classes alone: no rem, no permission.
787
+ func reminderKitCheck() -> [String] {
788
+ guard (try? RK.load()) != nil else { return ["ReminderKit.framework"] }
789
+ let needs: [(String, String)] = [
790
+ ("REMStore", "initUserInteractive:"),
791
+ ("REMStore", "fetchEligibleDefaultListsWithError:"),
792
+ ("REMStore", "fetchPrimaryActiveCloudKitAccountWithError:"),
793
+ ("REMStore", "fetchRemindersForEventKitBridgingWithListIDs:error:"),
794
+ ("REMSaveRequest", "initWithStore:"),
795
+ ("REMSaveRequest", "updateAccount:"),
796
+ ("REMSaveRequest", "updateList:"),
797
+ ("REMSaveRequest", "updateReminder:"),
798
+ ("REMSaveRequest", "addListWithName:toAccountChangeItem:listObjectID:"),
799
+ ("REMSaveRequest", "addReminderWithTitle:toListChangeItem:"),
800
+ ("REMSaveRequest", "saveSynchronouslyWithError:"),
801
+ ("REMAccount", "capabilities"),
802
+ ("REMAccountCapabilities", "supportsUrgentAlarm"),
803
+ ("REMAccountStorage", "name"),
804
+ ("REMListStorage", "name"),
805
+ ("REMListStorage", "objectID"),
806
+ ("REMListStorage", "isGroup"),
807
+ ("REMReminderStorage", "objectID"),
808
+ ("REMReminderStorage", "titleAsString"),
809
+ ("REMReminderStorage", "dueDateComponents"),
810
+ ("REMReminderStorage", "isCompleted"),
811
+ ("REMReminderStorage", "isUrgentStateEnabledForCurrentUser"),
812
+ ("REMReminderStorage", "setIsUrgentStateEnabledForCurrentUser:"),
813
+ ("REMReminderStorage", "notesAsString"),
814
+ ("REMReminderStorage", "setNotesAsString:"),
815
+ ("REMReminderStorage", "setCompleted:"),
816
+ ("REMAccountStorage", "objectID"),
817
+ ("REMReminderChangeItem", "setDueDateComponentsWithAlarmsIfNeeded:"),
818
+ ("REMReminderChangeItem", "setNotesAsString:"),
819
+ ("REMReminderChangeItem", "urgentAlarmContext"),
820
+ ("REMReminderChangeItem", "removeFromList"),
821
+ ("REMReminderChangeItem", "setCompleted:"),
822
+ ("REMList", "account"),
823
+ ("REMReminderUrgentAlarmContextChangeItem", "setIsUrgentStateEnabledForCurrentUser:"),
824
+ ("REMObjectID", "uuid"),
825
+ ]
826
+ return needs.compactMap { cls, sel in
827
+ guard let c: AnyClass = NSClassFromString(cls) else { return cls }
828
+ return class_getInstanceMethod(c, NSSelectorFromString(sel)) == nil ? "\(cls).\(sel)" : nil
829
+ }
830
+ }
831
+
401
832
  // MARK: - Commands
402
833
 
403
834
  func handle(_ request: [String: Any]) throws -> [String: Any] {
@@ -409,16 +840,48 @@ func handle(_ request: [String: Any]) throws -> [String: Any] {
409
840
  let cmd = request["cmd"] as? String ?? ""
410
841
  switch cmd {
411
842
  case "status":
412
- return ["ok": true, "authorization": authorization()]
843
+ let missing = reminderKitCheck()
844
+ var out: [String: Any] = ["ok": true, "authorization": authorization(), "reminders": remindersAuthorization(),
845
+ "protocol": helperProtocol, "alarms": missing.isEmpty ? "supported" : "unsupported"]
846
+ if !missing.isEmpty { out["missing"] = missing }
847
+ return out
413
848
 
414
849
  case "request":
415
- if authorization() == "notDetermined" {
850
+ // Both prompts in one go, while the owner is at the Mac: one for the
851
+ // calendar, then one for reminders (alarms). Each shows only once. No
852
+ // reminders prompt where urgent alarms cannot work: it would ask for nothing.
853
+ let wait = (request["waitSeconds"] as? NSNumber)?.doubleValue ?? 120
854
+ if (request["calendar"] as? Bool ?? true) && authorization() == "notDetermined" {
416
855
  var finished = false
417
856
  store.requestFullAccessToEvents { _, _ in finished = true }
418
- let wait = (request["waitSeconds"] as? NSNumber)?.doubleValue ?? 120
419
857
  _ = waitFor(seconds: wait) { finished }
420
858
  }
421
- return ["ok": true, "authorization": authorization()]
859
+ if (request["reminders"] as? Bool ?? true) && remindersAuthorization() == "notDetermined" && reminderKitCheck().isEmpty {
860
+ var finished = false
861
+ store.requestFullAccessToReminders { _, _ in finished = true }
862
+ _ = waitFor(seconds: wait) { finished }
863
+ }
864
+ return ["ok": true, "authorization": authorization(), "reminders": remindersAuthorization(), "protocol": helperProtocol]
865
+
866
+ case "ensureAlarmList":
867
+ return try ensureAlarmList(request)
868
+
869
+ case "alarmAdd":
870
+ return try addAlarm(request)
871
+
872
+ case "alarms":
873
+ let rem = try reminderStore()
874
+ let list = try alarmList(rem, request["listId"])
875
+ return ["ok": true, "alarms": try remindersIn(rem, list).map(describeAlarm), "list": describeList(list)]
876
+
877
+ case "alarmDelete":
878
+ return try deleteAlarm(request)
879
+
880
+ case "alarmComplete":
881
+ return try completeAlarms(request)
882
+
883
+ case "rkcheck":
884
+ return ["ok": true, "missing": reminderKitCheck(), "protocol": helperProtocol]
422
885
 
423
886
  case "calendars":
424
887
  try requireFullAccess()
@@ -496,7 +959,7 @@ func handle(_ request: [String: Any]) throws -> [String: Any] {
496
959
  row["start"] = isoString(event.startDate)
497
960
  row["end"] = isoString(event.endDate)
498
961
  row["allDay"] = event.isAllDay
499
- row["alerts"] = (event.alarms ?? []).map { Int(-$0.relativeOffset / 60) }
962
+ row["alerts"] = (event.alarms ?? []).compactMap(alertMinutes)
500
963
  if let notes = event.notes { row["notes"] = notes }
501
964
  } catch let f as Failure {
502
965
  row["error"] = f.code
package/package.json CHANGED
@@ -1,7 +1,8 @@
1
1
  {
2
2
  "name": "wechat-clawbot",
3
- "version": "1.2.0",
3
+ "version": "1.3.1",
4
4
  "description": "Connect DeepSeek Harness to WeChat via the official WeChat ClawBot (Tencent iLink) bridge — a DSH plugin bundle.",
5
+ "icon": "assets/icon.svg",
5
6
  "keywords": [
6
7
  "deepseek-harness",
7
8
  "dsh",
@@ -22,14 +23,14 @@
22
23
  },
23
24
  "type": "module",
24
25
  "main": "lib/index.js",
25
- "types": "lib/types/index.d.ts",
26
+ "types": "lib/index.d.ts",
26
27
  "exports": {
27
28
  ".": {
28
- "types": "./lib/types/index.d.ts",
29
+ "types": "./lib/index.d.ts",
29
30
  "default": "./lib/index.js"
30
31
  },
31
32
  "./cli": {
32
- "types": "./lib/types/cli.d.ts",
33
+ "types": "./lib/cli.d.ts",
33
34
  "default": "./lib/cli.js"
34
35
  },
35
36
  "./cordis.patch.yml": "./cordis.patch.yml",
@@ -41,6 +42,7 @@
41
42
  "clawbot-mcp": "lib/mcp-cli.js"
42
43
  },
43
44
  "files": [
45
+ "assets",
44
46
  "lib",
45
47
  "native",
46
48
  "cordis.patch.yml",
@@ -67,8 +69,7 @@
67
69
  "client": {
68
70
  "platform": "web",
69
71
  "inject": [
70
- "slots",
71
- "settingsScope"
72
+ "slots"
72
73
  ]
73
74
  }
74
75
  },