wechat-clawbot 1.0.1 → 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.
- package/README.md +19 -0
- package/README.zh.md +19 -0
- package/lib/backlog.d.ts +7 -3
- package/lib/backlog.d.ts.map +1 -1
- package/lib/backlog.js +4 -2
- package/lib/backlog.js.map +1 -1
- package/lib/bridge.d.ts +23 -0
- package/lib/bridge.d.ts.map +1 -1
- package/lib/bridge.js +135 -2
- package/lib/bridge.js.map +1 -1
- package/lib/claude-peer.d.ts +30 -0
- package/lib/claude-peer.d.ts.map +1 -1
- package/lib/claude-peer.js +292 -28
- package/lib/claude-peer.js.map +1 -1
- package/lib/client.js +165 -1
- package/lib/codex-rpc.js +1 -1
- package/lib/config.d.ts +31 -0
- package/lib/config.d.ts.map +1 -1
- package/lib/config.js +41 -0
- package/lib/config.js.map +1 -1
- package/lib/dsh-sessions.d.ts +124 -0
- package/lib/dsh-sessions.d.ts.map +1 -0
- package/lib/dsh-sessions.js +344 -0
- package/lib/dsh-sessions.js.map +1 -0
- package/lib/index.d.ts.map +1 -1
- package/lib/index.js +78 -0
- package/lib/index.js.map +1 -1
- package/lib/instance-guard.d.ts.map +1 -1
- package/lib/instance-guard.js +32 -7
- package/lib/instance-guard.js.map +1 -1
- package/lib/mac-calendar.d.ts +124 -0
- package/lib/mac-calendar.d.ts.map +1 -0
- package/lib/mac-calendar.js +883 -0
- package/lib/mac-calendar.js.map +1 -0
- package/lib/mcp-route.d.ts +1 -1
- package/lib/mcp-route.d.ts.map +1 -1
- package/lib/mcp-route.js +48 -189
- package/lib/mcp-route.js.map +1 -1
- package/lib/mcp-server.js +1 -1
- package/lib/memory.d.ts.map +1 -1
- package/lib/memory.js +12 -1
- package/lib/memory.js.map +1 -1
- package/lib/owner-notify.d.ts +90 -0
- package/lib/owner-notify.d.ts.map +1 -0
- package/lib/owner-notify.js +200 -0
- package/lib/owner-notify.js.map +1 -0
- package/lib/secretary.d.ts +27 -0
- package/lib/secretary.d.ts.map +1 -0
- package/lib/secretary.js +175 -0
- package/lib/secretary.js.map +1 -0
- package/native/macos-calendar/main.swift +543 -0
- package/package.json +2 -1
- package/wechat-clawbot-INSTALL.md +83 -6
|
@@ -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.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",
|