@narumitw/pi-notify 0.4.0 → 0.4.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.
package/dist/index.ts ADDED
@@ -0,0 +1,1096 @@
1
+ // @generated by scripts/build-runtime.mjs; do not edit.
2
+ // @ts-nocheck -- generated JavaScript uses a .ts extension for Pi's Jiti loader.
3
+ import {
4
+ SettingsStore,
5
+ clipText,
6
+ defaults,
7
+ deliver,
8
+ displayPath,
9
+ isObject,
10
+ notificationMetadata
11
+ } from "./chunks/chunk-YXQ43SWY.ts";
12
+
13
+ // src/notify.ts
14
+ import { join } from "node:path";
15
+ import {
16
+ CONFIG_DIR_NAME,
17
+ getAgentDir
18
+ } from "@earendil-works/pi-coding-agent";
19
+
20
+ // src/coordinator.ts
21
+ import { randomUUID } from "node:crypto";
22
+
23
+ // src/activity.ts
24
+ import { isKeyRelease, parseKey } from "@earendil-works/pi-tui";
25
+ function isUserActivity(data) {
26
+ if (!data || isKeyRelease(data)) return false;
27
+ if (data.startsWith("\x1B[200~") && data.endsWith("\x1B[201~")) return true;
28
+ if (data === "\x1B[I") return true;
29
+ if (data === "\x1B[O") return false;
30
+ const sgr = /^\x1b\[<(\d+);\d+;\d+([Mm])$/.exec(data);
31
+ if (sgr) return sgr[2] === "M" && (Number(sgr[1]) & 32) === 0;
32
+ if (data.length === 6 && data.startsWith("\x1B[M")) {
33
+ const button = data.charCodeAt(3) - 32;
34
+ return (button & 32) === 0 && (button & 3) !== 3;
35
+ }
36
+ if (parseKey(data) !== void 0) return true;
37
+ return !/[\x00-\x1f\x7f-\x9f]/.test(data);
38
+ }
39
+
40
+ // src/coordinator.ts
41
+ var Coordinator = class {
42
+ constructor(settings, providers2, tui, metadata = notificationMetadata, onFailure = () => {
43
+ }) {
44
+ this.settings = settings;
45
+ this.providers = providers2;
46
+ this.tui = tui;
47
+ this.metadata = metadata;
48
+ this.onFailure = onFailure;
49
+ }
50
+ settings;
51
+ providers;
52
+ tui;
53
+ metadata;
54
+ onFailure;
55
+ alive = true;
56
+ revision = 0;
57
+ sequence = 0;
58
+ work;
59
+ pending;
60
+ lastActivity = Date.now();
61
+ tasks = /* @__PURE__ */ new Map();
62
+ statuses = /* @__PURE__ */ new Map();
63
+ get pendingAt() {
64
+ return this.pending?.dueAt;
65
+ }
66
+ observeActivity() {
67
+ this.lastActivity = Date.now();
68
+ }
69
+ begin(replace = false) {
70
+ if (!this.alive) return;
71
+ this.cancelPending();
72
+ if (!this.work || replace)
73
+ this.work = { id: randomUUID(), startedAt: Date.now(), error: false, revision: this.revision };
74
+ }
75
+ assistant(error) {
76
+ if (this.work) this.work.error = error;
77
+ }
78
+ input(data) {
79
+ if (this.tui && this.alive && isUserActivity(data)) {
80
+ this.lastActivity = Date.now();
81
+ this.cancelPending();
82
+ }
83
+ }
84
+ apply(settings) {
85
+ this.cancelPending();
86
+ this.revision++;
87
+ this.settings = settings;
88
+ for (const id of this.statuses.keys()) if (!Object.hasOwn(settings.destinations, id)) this.statuses.delete(id);
89
+ }
90
+ cancelPending() {
91
+ const pending = this.pending;
92
+ this.pending = void 0;
93
+ if (pending) {
94
+ clearTimeout(pending.timer);
95
+ pending.controller.abort();
96
+ }
97
+ }
98
+ settle(aborted, data) {
99
+ const work = this.work;
100
+ this.work = void 0;
101
+ if (!this.alive || !work || work.revision !== this.revision || aborted || !this.settings.enabled || !this.settings.targetIds.length)
102
+ return;
103
+ this.cancelPending();
104
+ const now = Date.now();
105
+ const dueAt = this.tui && this.settings.mode === "after-inactivity" ? Math.max(now, this.lastActivity + this.settings.inactivitySeconds * 1e3) : now;
106
+ const pending = { work, dueAt, controller: new AbortController() };
107
+ this.pending = pending;
108
+ if (dueAt > now) pending.timer = setTimeout(() => this.trySend(pending), dueAt - now);
109
+ const task = this.metadata({ ...data, ...work, settledAt: now }, pending.controller.signal).then((notification) => {
110
+ if (this.pending !== pending || !this.alive || pending.controller.signal.aborted) return;
111
+ pending.notification = notification;
112
+ this.trySend(pending);
113
+ }).catch(() => {
114
+ if (this.pending === pending) this.cancelPending();
115
+ });
116
+ this.track(task, pending.controller);
117
+ }
118
+ trySend(pending) {
119
+ if (!this.alive || this.pending !== pending || pending.controller.signal.aborted || this.work || Date.now() < pending.dueAt || !pending.notification || !this.settings.enabled)
120
+ return;
121
+ this.pending = void 0;
122
+ clearTimeout(pending.timer);
123
+ const notification = pending.notification;
124
+ for (const id of this.settings.targetIds) {
125
+ const destination = this.settings.destinations[id];
126
+ if (destination) void this.send(id, destination, notification);
127
+ }
128
+ }
129
+ track(promise, controller) {
130
+ this.tasks.set(promise, controller);
131
+ void promise.finally(() => this.tasks.delete(promise)).catch(() => {
132
+ });
133
+ return promise;
134
+ }
135
+ send(id, destination, notification, signal) {
136
+ const controller = new AbortController();
137
+ const combined = signal ? AbortSignal.any([signal, controller.signal]) : controller.signal;
138
+ if (!this.alive) controller.abort();
139
+ const sequence = ++this.sequence;
140
+ this.statuses.set(id, { sequence, result: { state: "sending" } });
141
+ const task = deliver(this.providers, destination, notification, combined).then((result) => {
142
+ if (this.alive && this.statuses.get(id)?.sequence === sequence) {
143
+ this.statuses.set(id, { sequence, result });
144
+ if (result.state === "failed") this.onFailure();
145
+ }
146
+ return result;
147
+ });
148
+ return this.track(task, controller);
149
+ }
150
+ async close() {
151
+ this.alive = false;
152
+ this.work = void 0;
153
+ this.cancelPending();
154
+ for (const controller of this.tasks.values()) controller.abort();
155
+ await Promise.allSettled(this.tasks.keys());
156
+ this.statuses.clear();
157
+ }
158
+ };
159
+
160
+ // src/providers/http.ts
161
+ var TIMEOUT_MS = 1e4;
162
+ var MAX_RESPONSE_BYTES = 65536;
163
+ function normalizeHttpUrl(value) {
164
+ if (typeof value !== "string" || value.length > 2048 || /[\s\\?#\p{Cc}]/u.test(value)) return void 0;
165
+ if (!/^https?:\/\/[^/@]+(?:\/|$)/i.test(value)) return void 0;
166
+ try {
167
+ if (/[\\\p{Cc}]/u.test(decodeURIComponent(value))) return void 0;
168
+ const raw = /^https?:\/\/([^/]+)(\/.*)?$/i.exec(value);
169
+ if (!raw || decodeURIComponent(raw[2] ?? "").split("/").some((part) => part === "." || part === ".."))
170
+ return void 0;
171
+ const url = new URL(value);
172
+ if (url.username || url.password || !url.hostname) return void 0;
173
+ const rawHost = raw[1]?.split(":")[0];
174
+ if (/^(?:\d{1,3}\.){3}\d{1,3}$/.test(url.hostname) && rawHost !== url.hostname) return void 0;
175
+ const normalized = url.href.replace(/\/+$/, "");
176
+ return normalized.length <= 2048 ? normalized : void 0;
177
+ } catch {
178
+ return void 0;
179
+ }
180
+ }
181
+ function truncateUtf8(value, maxBytes) {
182
+ let bytes = 0;
183
+ let result = "";
184
+ for (const point of value) {
185
+ bytes += Buffer.byteLength(point, "utf8");
186
+ if (bytes > maxBytes) break;
187
+ result += point;
188
+ }
189
+ return result;
190
+ }
191
+ async function postJson(url, payload, signal, fetcher = fetch, headers = {}) {
192
+ if (signal.aborted) return { state: "cancelled", code: "cancelled" };
193
+ const timeout = new AbortController();
194
+ const timer = setTimeout(() => timeout.abort(), TIMEOUT_MS);
195
+ const combined = AbortSignal.any([signal, timeout.signal]);
196
+ let rejectAbort;
197
+ const aborted = new Promise((_resolve, reject) => {
198
+ rejectAbort = reject;
199
+ });
200
+ const onAbort = () => rejectAbort(combined.reason);
201
+ combined.addEventListener("abort", onAbort, { once: true });
202
+ let reader;
203
+ try {
204
+ const fetching = fetcher(url, {
205
+ method: "POST",
206
+ redirect: "error",
207
+ signal: combined,
208
+ headers: { "content-type": "application/json", ...headers },
209
+ body: JSON.stringify(payload)
210
+ }).then((response2) => {
211
+ if (combined.aborted) void response2.body?.cancel().catch(() => {
212
+ });
213
+ return response2;
214
+ });
215
+ const response = await Promise.race([fetching, aborted]);
216
+ combined.throwIfAborted();
217
+ if (!response.ok) {
218
+ void response.body?.cancel().catch(() => {
219
+ });
220
+ const retry = response.headers.get("retry-after");
221
+ return {
222
+ state: "failed",
223
+ code: response.status === 429 ? "rate-limit" : "http",
224
+ ...response.status === 429 && retry && /^\d+$/.test(retry) && Number.isSafeInteger(Number(retry)) && Number(retry) > 0 ? { retryAfterSeconds: Number(retry) } : {}
225
+ };
226
+ }
227
+ reader = response.body?.getReader();
228
+ const chunks = [];
229
+ let length = 0;
230
+ while (reader) {
231
+ const part = await Promise.race([reader.read(), aborted]);
232
+ combined.throwIfAborted();
233
+ if (part.done) break;
234
+ length += part.value.byteLength;
235
+ if (length > MAX_RESPONSE_BYTES) return { state: "failed", code: "response" };
236
+ if (part.value.byteLength) chunks.push(part.value);
237
+ }
238
+ let body;
239
+ try {
240
+ body = JSON.parse(Buffer.concat(chunks, length).toString("utf8"));
241
+ } catch {
242
+ body = void 0;
243
+ }
244
+ return { state: "response", body, status: response.status };
245
+ } catch {
246
+ if (signal.aborted) return { state: "cancelled", code: "cancelled" };
247
+ return { state: "failed", code: timeout.signal.aborted ? "timeout" : "network" };
248
+ } finally {
249
+ if (reader) {
250
+ void reader.cancel().catch(() => {
251
+ });
252
+ reader.releaseLock();
253
+ }
254
+ combined.removeEventListener("abort", onAbort);
255
+ clearTimeout(timer);
256
+ }
257
+ }
258
+
259
+ // src/providers/bark.ts
260
+ function createBarkProvider(fetcher = fetch) {
261
+ return {
262
+ id: "bark",
263
+ label: "Bark",
264
+ validate(value) {
265
+ if (!isObject(value) || value.provider !== "bark") return void 0;
266
+ if (typeof value.label !== "string" || !value.label.trim() || value.label.length > 128) return void 0;
267
+ const serverUrl = normalizeHttpUrl(value.serverUrl);
268
+ if (!serverUrl || typeof value.deviceKey !== "string" || !/^[\x21-\x7e]{1,512}$/.test(value.deviceKey))
269
+ return void 0;
270
+ return { provider: "bark", label: value.label, serverUrl, deviceKey: value.deviceKey };
271
+ },
272
+ async send(destination, notification, signal) {
273
+ if (signal.aborted) return { state: "cancelled", code: "cancelled" };
274
+ const valid = this.validate(destination);
275
+ if (valid?.provider !== "bark") return { state: "failed", code: "invalid-destination" };
276
+ const title = truncateUtf8(notification.title, 256);
277
+ let remaining = 3e3 - Buffer.byteLength(JSON.stringify({ title, body: "" }), "utf8");
278
+ let body = "";
279
+ for (const point of truncateUtf8(notification.body, 2048)) {
280
+ const encodedBytes = Buffer.byteLength(JSON.stringify(point), "utf8") - 2;
281
+ if (encodedBytes > remaining) break;
282
+ body += point;
283
+ remaining -= encodedBytes;
284
+ }
285
+ const result = await postJson(
286
+ `${valid.serverUrl}/push`,
287
+ { device_key: valid.deviceKey, title, body },
288
+ signal,
289
+ fetcher
290
+ );
291
+ if (result.state !== "response") return result;
292
+ if (result.status !== 200 || !isObject(result.body) || typeof result.body.code !== "number")
293
+ return { state: "failed", code: "response" };
294
+ return result.body.code === 200 ? { state: "accepted" } : { state: "failed", code: "api" };
295
+ }
296
+ };
297
+ }
298
+
299
+ // src/providers/discord.ts
300
+ import { sanitizeTerminalText } from "@narumitw/pi-tui-kit/terminal-text";
301
+ function isSnowflake(value) {
302
+ return typeof value === "string" && !/\s/.test(value) && /^[1-9][0-9]{0,19}$/.test(value) && BigInt(value) <= 18446744073709551615n;
303
+ }
304
+ function validateDiscordWebhookUrl(value) {
305
+ if (typeof value !== "string" || value.length > 2048 || /[\s\\\p{Cc}]/u.test(value)) return false;
306
+ const match = /^https:\/\/discord\.com\/api\/(?:v10\/)?webhooks\/([1-9][0-9]{0,19})\/[-_A-Za-z0-9]+$/.exec(value);
307
+ return match !== null && isSnowflake(match[1]);
308
+ }
309
+ function createDiscordProvider(fetcher = fetch) {
310
+ return {
311
+ id: "discord",
312
+ label: "Discord",
313
+ validate(value) {
314
+ if (!isObject(value) || value.provider !== "discord") return void 0;
315
+ if (typeof value.label !== "string" || !value.label.trim() || value.label.length > 128) return void 0;
316
+ if (!validateDiscordWebhookUrl(value.webhookUrl)) return void 0;
317
+ return { provider: "discord", label: value.label, webhookUrl: value.webhookUrl };
318
+ },
319
+ async send(destination, notification, signal) {
320
+ if (signal.aborted) return { state: "cancelled", code: "cancelled" };
321
+ const valid = this.validate(destination);
322
+ if (valid?.provider !== "discord") return { state: "failed", code: "invalid-destination" };
323
+ const text = `${notification.title}
324
+ ${notification.body}`.split("\n").map(sanitizeTerminalText).join("\n");
325
+ const result = await postJson(
326
+ `${valid.webhookUrl}?wait=true`,
327
+ {
328
+ content: clipText(text.trim() ? text : "Pi notification", 2e3),
329
+ // Enforce this for direct callers, not only for metadata produced by the coordinator.
330
+ allowed_mentions: { parse: [] },
331
+ flags: 4
332
+ // SUPPRESS_EMBEDS, not SUPPRESS_NOTIFICATIONS (4096).
333
+ },
334
+ signal,
335
+ fetcher,
336
+ {
337
+ // Discord's required bot User-Agent syntax. 1.0 is the adapter version, not the package version.
338
+ "User-Agent": "DiscordBot (https://github.com/narumiruna/pi-extensions, 1.0)"
339
+ }
340
+ );
341
+ if (result.state !== "response") return result;
342
+ const body = result.body;
343
+ return result.status === 200 && isObject(body) && isSnowflake(body.id) && isSnowflake(body.channel_id) && Number.isInteger(body.type) ? { state: "accepted" } : { state: "failed", code: "response" };
344
+ }
345
+ };
346
+ }
347
+
348
+ // src/providers/gotify.ts
349
+ var TIMEOUT_MS2 = 1e4;
350
+ var MAX_RESPONSE_BYTES2 = 65536;
351
+ function normalizeGotifyUrl(value) {
352
+ if (typeof value !== "string" || value.length > 2048 || /[\s\\?#\p{Cc}]/u.test(value)) return void 0;
353
+ try {
354
+ const url = new URL(value);
355
+ if (!/^https?:\/\/[^/@]+(?:\/|$)/i.test(value) || url.username || url.password) return void 0;
356
+ const normalized = url.href.replace(/\/+$/, "");
357
+ return normalized.length <= 2048 ? normalized : void 0;
358
+ } catch {
359
+ return void 0;
360
+ }
361
+ }
362
+ function createGotifyProvider(fetcher = fetch) {
363
+ return {
364
+ id: "gotify",
365
+ label: "Gotify",
366
+ validate(value) {
367
+ if (!isObject(value) || value.provider !== "gotify") return void 0;
368
+ if (typeof value.label !== "string" || !value.label.trim() || value.label.length > 128) return void 0;
369
+ const serverUrl = normalizeGotifyUrl(value.serverUrl);
370
+ if (!serverUrl || typeof value.appToken !== "string" || !/^[\x21-\x7e]{1,512}$/.test(value.appToken))
371
+ return void 0;
372
+ if (value.priority !== void 0 && !Number.isSafeInteger(value.priority)) return void 0;
373
+ return {
374
+ provider: "gotify",
375
+ label: value.label,
376
+ serverUrl,
377
+ appToken: value.appToken,
378
+ priority: value.priority === void 0 ? void 0 : Number(value.priority)
379
+ };
380
+ },
381
+ async send(destination, notification, signal) {
382
+ if (signal.aborted) return { state: "cancelled", code: "cancelled" };
383
+ const valid = this.validate(destination);
384
+ if (valid?.provider !== "gotify") return { state: "failed", code: "invalid-destination" };
385
+ const timeout = new AbortController();
386
+ const timer = setTimeout(() => timeout.abort(), TIMEOUT_MS2);
387
+ const combined = AbortSignal.any([signal, timeout.signal]);
388
+ try {
389
+ const response = await fetcher(`${valid.serverUrl}/message`, {
390
+ method: "POST",
391
+ redirect: "error",
392
+ signal: combined,
393
+ headers: { "content-type": "application/json", "X-Gotify-Key": valid.appToken },
394
+ body: JSON.stringify({
395
+ title: notification.title,
396
+ message: notification.body,
397
+ ...valid.priority === void 0 ? {} : { priority: valid.priority }
398
+ })
399
+ });
400
+ combined.throwIfAborted();
401
+ if (!response.ok) {
402
+ await response.body?.cancel().catch(() => {
403
+ });
404
+ combined.throwIfAborted();
405
+ const retry = response.headers.get("retry-after");
406
+ return {
407
+ state: "failed",
408
+ code: response.status === 429 ? "rate-limit" : "http",
409
+ ...response.status === 429 && retry && /^\d+$/.test(retry) && Number.isSafeInteger(Number(retry)) && Number(retry) > 0 ? { retryAfterSeconds: Number(retry) } : {}
410
+ };
411
+ }
412
+ const reader = response.body?.getReader();
413
+ if (!reader) return { state: "failed", code: "response" };
414
+ let length = 0;
415
+ const chunks = [];
416
+ try {
417
+ while (true) {
418
+ combined.throwIfAborted();
419
+ const part = await reader.read();
420
+ combined.throwIfAborted();
421
+ if (part.done) break;
422
+ length += part.value.byteLength;
423
+ if (length > MAX_RESPONSE_BYTES2) break;
424
+ chunks.push(part.value);
425
+ }
426
+ } finally {
427
+ await reader.cancel().catch(() => {
428
+ });
429
+ reader.releaseLock();
430
+ }
431
+ combined.throwIfAborted();
432
+ if (length > MAX_RESPONSE_BYTES2) return { state: "failed", code: "response" };
433
+ let body;
434
+ try {
435
+ body = JSON.parse(Buffer.concat(chunks).toString("utf8"));
436
+ } catch {
437
+ return { state: "failed", code: "response" };
438
+ }
439
+ return isObject(body) && Number.isSafeInteger(body.id) && Number(body.id) > 0 && Number.isSafeInteger(body.appid) && Number(body.appid) > 0 && typeof body.message === "string" && typeof body.date === "string" && Number.isFinite(Date.parse(body.date)) ? { state: "accepted" } : { state: "failed", code: "response" };
440
+ } catch {
441
+ if (signal.aborted) return { state: "cancelled", code: "cancelled" };
442
+ return { state: "failed", code: timeout.signal.aborted ? "timeout" : "network" };
443
+ } finally {
444
+ clearTimeout(timer);
445
+ }
446
+ }
447
+ };
448
+ }
449
+
450
+ // src/providers/line.ts
451
+ import { sanitizeTerminalText as sanitizeTerminalText2 } from "@narumitw/pi-tui-kit/terminal-text";
452
+ var MAX_TOKEN_LENGTH = 8192;
453
+ function plainText(text) {
454
+ return text.split("\n").map(sanitizeTerminalText2).join("\n");
455
+ }
456
+ function acceptedBody(body) {
457
+ if (!isObject(body)) return false;
458
+ if (Object.keys(body).length === 0) return true;
459
+ return Array.isArray(body.sentMessages) && body.sentMessages.length >= 1 && body.sentMessages.length <= 5 && body.sentMessages.every(
460
+ (message) => isObject(message) && (typeof message.id === "string" && message.id.length > 0 || typeof message.id === "number" && Number.isInteger(message.id) && message.id >= 0) && (message.quoteToken === void 0 || typeof message.quoteToken === "string")
461
+ );
462
+ }
463
+ function createLineProvider(fetcher = fetch) {
464
+ return {
465
+ id: "line",
466
+ label: "LINE",
467
+ validate(value) {
468
+ if (!isObject(value) || value.provider !== "line") return void 0;
469
+ if (typeof value.label !== "string" || !value.label.trim() || value.label.length > 128) return void 0;
470
+ if (typeof value.channelAccessToken !== "string" || value.channelAccessToken.length > MAX_TOKEN_LENGTH || /\s/u.test(value.channelAccessToken) || !/^[A-Za-z0-9._~+/-]+=*$/u.test(value.channelAccessToken))
471
+ return void 0;
472
+ if (typeof value.recipientId !== "string" || value.recipientId.length > 129 || /\s/u.test(value.recipientId) || !/^(?:U[0-9a-f]{32}|[CR][!-~]{1,128})$/u.test(value.recipientId))
473
+ return void 0;
474
+ return {
475
+ provider: "line",
476
+ label: value.label,
477
+ channelAccessToken: value.channelAccessToken,
478
+ recipientId: value.recipientId
479
+ };
480
+ },
481
+ async send(destination, notification, signal) {
482
+ if (signal.aborted) return { state: "cancelled", code: "cancelled" };
483
+ const valid = this.validate(destination);
484
+ if (valid?.provider !== "line") return { state: "failed", code: "invalid-destination" };
485
+ const result = await postJson(
486
+ "https://api.line.me/v2/bot/message/push",
487
+ {
488
+ to: valid.recipientId,
489
+ // No mention/emoji objects, substitutions, formatting, or silent-delivery option.
490
+ // LINE clients can still auto-link literal URLs; this does not promise link suppression.
491
+ messages: [{ type: "text", text: clipText(plainText(`${notification.title}
492
+ ${notification.body}`), 5e3) }]
493
+ },
494
+ signal,
495
+ fetcher,
496
+ { Authorization: `Bearer ${valid.channelAccessToken}` }
497
+ );
498
+ if (result.state !== "response") return result;
499
+ return result.status === 200 && acceptedBody(result.body) ? { state: "accepted" } : { state: "failed", code: "response" };
500
+ }
501
+ };
502
+ }
503
+
504
+ // src/providers/ntfy.ts
505
+ var RESERVED_TOPICS = /* @__PURE__ */ new Set([
506
+ "docs",
507
+ "static",
508
+ "file",
509
+ "app",
510
+ "metrics",
511
+ "account",
512
+ "settings",
513
+ "signup",
514
+ "login",
515
+ "v1"
516
+ ]);
517
+ function createNtfyProvider(fetcher = fetch) {
518
+ return {
519
+ id: "ntfy",
520
+ label: "ntfy",
521
+ validate(value) {
522
+ if (!isObject(value) || value.provider !== "ntfy") return void 0;
523
+ if (typeof value.label !== "string" || !value.label.trim() || value.label.length > 128) return void 0;
524
+ if (!normalizeHttpUrl(value.serverUrl)) return void 0;
525
+ const serverUrl = new URL(String(value.serverUrl)).href;
526
+ if (serverUrl.length > 2048 || typeof value.topic !== "string" || !/^[-_A-Za-z0-9]{1,64}$/.test(value.topic))
527
+ return void 0;
528
+ if (RESERVED_TOPICS.has(value.topic)) return void 0;
529
+ if (value.accessToken !== void 0 && (typeof value.accessToken !== "string" || !/^[\x21-\x7e]{1,512}$/.test(value.accessToken)))
530
+ return void 0;
531
+ if (value.priority !== void 0 && (!Number.isInteger(value.priority) || Number(value.priority) < 1 || Number(value.priority) > 5))
532
+ return void 0;
533
+ return {
534
+ provider: "ntfy",
535
+ label: value.label,
536
+ serverUrl,
537
+ topic: value.topic,
538
+ accessToken: value.accessToken === void 0 ? void 0 : String(value.accessToken),
539
+ priority: value.priority === void 0 ? void 0 : Number(value.priority)
540
+ };
541
+ },
542
+ async send(destination, notification, signal) {
543
+ if (signal.aborted) return { state: "cancelled", code: "cancelled" };
544
+ const valid = this.validate(destination);
545
+ if (valid?.provider !== "ntfy") return { state: "failed", code: "invalid-destination" };
546
+ const payload = {
547
+ topic: valid.topic,
548
+ title: truncateUtf8(notification.title, 1024),
549
+ message: truncateUtf8(notification.body, 4096),
550
+ ...valid.priority === void 0 ? {} : { priority: valid.priority }
551
+ };
552
+ const excess = Buffer.byteLength(JSON.stringify(payload), "utf8") - 8192;
553
+ if (excess > 0)
554
+ payload.message = truncateUtf8(payload.message, Math.max(0, Buffer.byteLength(payload.message) - excess));
555
+ const result = await postJson(
556
+ valid.serverUrl,
557
+ payload,
558
+ signal,
559
+ fetcher,
560
+ valid.accessToken === void 0 ? {} : { Authorization: `Bearer ${valid.accessToken}` }
561
+ );
562
+ if (result.state !== "response") return result;
563
+ const body = result.body;
564
+ return result.status === 200 && isObject(body) && typeof body.id === "string" && body.id.length > 0 && Number.isSafeInteger(body.time) && Number(body.time) > 0 && body.event === "message" && body.topic === valid.topic && typeof body.message === "string" ? { state: "accepted" } : { state: "failed", code: "response" };
565
+ }
566
+ };
567
+ }
568
+
569
+ // src/providers/pushover.ts
570
+ function createPushoverProvider(fetcher = fetch) {
571
+ return {
572
+ id: "pushover",
573
+ label: "Pushover",
574
+ validate(value) {
575
+ if (!isObject(value) || value.provider !== "pushover") return void 0;
576
+ if (typeof value.label !== "string" || !value.label.trim() || value.label.length > 128) return void 0;
577
+ if (typeof value.appToken !== "string" || value.appToken.length !== 30 || !/^[A-Za-z0-9]{30}$/.test(value.appToken))
578
+ return void 0;
579
+ if (typeof value.userKey !== "string" || value.userKey.length !== 30 || !/^[A-Za-z0-9]{30}$/.test(value.userKey))
580
+ return void 0;
581
+ return { provider: "pushover", label: value.label, appToken: value.appToken, userKey: value.userKey };
582
+ },
583
+ async send(destination, notification, signal) {
584
+ if (signal.aborted) return { state: "cancelled", code: "cancelled" };
585
+ const valid = this.validate(destination);
586
+ if (valid?.provider !== "pushover") return { state: "failed", code: "invalid-destination" };
587
+ const result = await postJson(
588
+ "https://api.pushover.net/1/messages.json",
589
+ {
590
+ token: valid.appToken,
591
+ user: valid.userKey,
592
+ // UTF-16 budgets are conservative for the documented character limits.
593
+ title: clipText(notification.title, 250),
594
+ message: clipText(notification.body, 1024),
595
+ priority: 0
596
+ },
597
+ signal,
598
+ fetcher
599
+ );
600
+ if (result.state !== "response") return result;
601
+ if (result.status !== 200 || !isObject(result.body) || typeof result.body.status !== "number")
602
+ return { state: "failed", code: "response" };
603
+ return result.body.status === 1 ? { state: "accepted" } : { state: "failed", code: "api" };
604
+ }
605
+ };
606
+ }
607
+
608
+ // src/providers/slack.ts
609
+ import { sanitizeTerminalText as sanitizeTerminalText3 } from "@narumitw/pi-tui-kit/terminal-text";
610
+ var TIMEOUT_MS3 = 1e4;
611
+ var MAX_RESPONSE_BYTES3 = 65536;
612
+ function slackText(notification) {
613
+ const raw = `${notification.title}
614
+ ${notification.body}`.split("\n").map(sanitizeTerminalText3).join("\n");
615
+ let text = "";
616
+ let beforeLast = 0;
617
+ for (const character of raw) {
618
+ const escaped = character === "&" ? "&amp;" : character === "<" ? "&lt;" : character === ">" ? "&gt;" : character;
619
+ if (text.length + escaped.length > 3e3) return `${text.length === 3e3 ? text.slice(0, beforeLast) : text}\u2026`;
620
+ beforeLast = text.length;
621
+ text += escaped;
622
+ }
623
+ return text.trim() ? text : "Pi notification";
624
+ }
625
+ function validateSlackWebhookUrl(value) {
626
+ return typeof value === "string" && value.length <= 2048 && !/\s/.test(value) && /^https:\/\/hooks\.slack\.com\/services\/T[A-Z0-9]+\/B[A-Z0-9]+\/[A-Za-z0-9]+$/.test(value);
627
+ }
628
+ function createSlackProvider(fetcher = fetch) {
629
+ return {
630
+ id: "slack",
631
+ label: "Slack",
632
+ validate(value) {
633
+ if (!isObject(value) || value.provider !== "slack") return void 0;
634
+ if (typeof value.label !== "string" || !value.label.trim() || value.label.length > 128) return void 0;
635
+ if (!validateSlackWebhookUrl(value.webhookUrl)) return void 0;
636
+ return { provider: "slack", label: value.label, webhookUrl: value.webhookUrl };
637
+ },
638
+ async send(destination, notification, signal) {
639
+ if (signal.aborted) return { state: "cancelled", code: "cancelled" };
640
+ const valid = this.validate(destination);
641
+ if (valid?.provider !== "slack") return { state: "failed", code: "invalid-destination" };
642
+ const timeout = new AbortController();
643
+ const timer = setTimeout(() => timeout.abort(), TIMEOUT_MS3);
644
+ const combined = AbortSignal.any([signal, timeout.signal]);
645
+ try {
646
+ const response = await fetcher(valid.webhookUrl, {
647
+ method: "POST",
648
+ redirect: "error",
649
+ signal: combined,
650
+ headers: { "content-type": "application/json" },
651
+ body: JSON.stringify({
652
+ text: "Pi notification. Open Pi to review.",
653
+ mrkdwn: false,
654
+ parse: "none",
655
+ unfurl_links: false,
656
+ unfurl_media: false,
657
+ blocks: [
658
+ {
659
+ type: "section",
660
+ text: { type: "plain_text", text: slackText(notification), emoji: false }
661
+ }
662
+ ]
663
+ })
664
+ });
665
+ if (combined.aborted || response.status !== 200) {
666
+ void response.body?.cancel().catch(() => {
667
+ });
668
+ combined.throwIfAborted();
669
+ const retry = response.headers.get("retry-after");
670
+ return {
671
+ state: "failed",
672
+ code: response.status === 429 ? "rate-limit" : "http",
673
+ ...response.status === 429 && retry && /^\d+$/.test(retry) && Number.isSafeInteger(Number(retry)) && Number(retry) > 0 ? { retryAfterSeconds: Number(retry) } : {}
674
+ };
675
+ }
676
+ const reader = response.body?.getReader();
677
+ if (!reader) return { state: "failed", code: "response" };
678
+ const cancel = () => {
679
+ void reader.cancel().catch(() => {
680
+ });
681
+ };
682
+ combined.addEventListener("abort", cancel, { once: true });
683
+ let length = 0;
684
+ const chunks = [];
685
+ try {
686
+ while (true) {
687
+ combined.throwIfAborted();
688
+ const part = await reader.read();
689
+ combined.throwIfAborted();
690
+ if (part.done) break;
691
+ length += part.value.byteLength;
692
+ if (length > MAX_RESPONSE_BYTES3) break;
693
+ if (part.value.byteLength) chunks.push(part.value);
694
+ }
695
+ } finally {
696
+ combined.removeEventListener("abort", cancel);
697
+ cancel();
698
+ reader.releaseLock();
699
+ }
700
+ combined.throwIfAborted();
701
+ return length <= MAX_RESPONSE_BYTES3 && Buffer.concat(chunks).equals(Buffer.from("ok")) ? { state: "accepted" } : { state: "failed", code: "response" };
702
+ } catch {
703
+ if (signal.aborted) return { state: "cancelled", code: "cancelled" };
704
+ return { state: "failed", code: timeout.signal.aborted ? "timeout" : "network" };
705
+ } finally {
706
+ clearTimeout(timer);
707
+ }
708
+ }
709
+ };
710
+ }
711
+
712
+ // src/providers/teams.ts
713
+ import { sanitizeTerminalText as sanitizeTerminalText4 } from "@narumitw/pi-tui-kit/terminal-text";
714
+ var MAX_URL_LENGTH = 8192;
715
+ var HOST_SUFFIX = ".environment.api.powerplatform.com";
716
+ var DNS_LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/u;
717
+ var WORKFLOW_PATH = /^\/powerautomate\/automations\/direct\/(?:cu\/[A-Za-z0-9_-]{1,256}\/)?workflows\/[A-Za-z0-9_-]{1,256}\/triggers\/manual\/paths\/invoke$/u;
718
+ function workflowUrl(value) {
719
+ if (typeof value !== "string" || value.length > MAX_URL_LENGTH || /[\s\\\p{Cc}]/u.test(value)) return void 0;
720
+ const parts = /^https:\/\/([^/?#]+)(\/[^?#]+)\?([^#]+)$/u.exec(value);
721
+ if (!parts) return void 0;
722
+ const [, authority = "", path = "", query = ""] = parts;
723
+ const hostname = authority.endsWith(":443") ? authority.slice(0, -4) : authority;
724
+ if (hostname.length > 253 || !hostname.endsWith(HOST_SUFFIX) || hostname.length <= HOST_SUFFIX.length || !hostname.split(".").every((label) => DNS_LABEL.test(label)) || !WORKFLOW_PATH.test(path))
725
+ return void 0;
726
+ const values = /* @__PURE__ */ new Map();
727
+ try {
728
+ for (const pair of query.split("&")) {
729
+ const separator = pair.indexOf("=");
730
+ if (separator < 0) return void 0;
731
+ const key = pair.slice(0, separator);
732
+ const raw = pair.slice(separator + 1);
733
+ if (!["api-version", "sp", "sv", "sig"].includes(key) || values.has(key)) return void 0;
734
+ const decoded = decodeURIComponent(raw);
735
+ if (/[\s\\\p{Cc}]/u.test(decoded)) return void 0;
736
+ if (key === "api-version" && raw !== "1" || key === "sv" && raw !== "1.0") return void 0;
737
+ values.set(key, decoded);
738
+ }
739
+ } catch {
740
+ return void 0;
741
+ }
742
+ if (values.size !== 4 || values.get("sp") !== "/triggers/manual/run" || !/^[A-Za-z0-9_+/-]+={0,2}$/u.test(values.get("sig") ?? ""))
743
+ return void 0;
744
+ return value;
745
+ }
746
+ function card(text) {
747
+ return {
748
+ type: "message",
749
+ attachments: [
750
+ {
751
+ contentType: "application/vnd.microsoft.card.adaptive",
752
+ contentUrl: null,
753
+ content: {
754
+ $schema: "http://adaptivecards.io/schemas/adaptive-card.json",
755
+ type: "AdaptiveCard",
756
+ version: "1.2",
757
+ // TextRun has no Markdown support. No actions, images or mention entities.
758
+ // https://learn.microsoft.com/en-us/adaptive-cards/schema-explorer/text-run
759
+ // Clients can still auto-link text; this does not promise link suppression.
760
+ body: [{ type: "RichTextBlock", inlines: [{ type: "TextRun", text }] }]
761
+ }
762
+ }
763
+ ]
764
+ };
765
+ }
766
+ var MAX_PAYLOAD_BYTES = 24e3;
767
+ var TEXT_BUDGET = MAX_PAYLOAD_BYTES - Buffer.byteLength(JSON.stringify(card("")), "utf8");
768
+ function boundedText(title, body) {
769
+ const text = `${title}
770
+ ${body}`.split("\n").map(sanitizeTerminalText4).join("\n");
771
+ const points = [];
772
+ const costs = [];
773
+ let bytes = 0;
774
+ for (const point of text) {
775
+ const cost = Buffer.byteLength(JSON.stringify(point), "utf8") - 2;
776
+ if (bytes + cost > TEXT_BUDGET) {
777
+ while (bytes + 3 > TEXT_BUDGET) {
778
+ bytes -= costs.pop() ?? 0;
779
+ points.pop();
780
+ }
781
+ return `${points.join("")}\u2026`;
782
+ }
783
+ bytes += cost;
784
+ points.push(point);
785
+ costs.push(cost);
786
+ }
787
+ return points.join("");
788
+ }
789
+ function createTeamsProvider(fetcher = fetch) {
790
+ return {
791
+ id: "teams",
792
+ label: "Microsoft Teams",
793
+ validate(value) {
794
+ if (!isObject(value) || value.provider !== "teams") return void 0;
795
+ if (typeof value.label !== "string" || !value.label.trim() || value.label.length > 128) return void 0;
796
+ const webhookUrl = workflowUrl(value.webhookUrl);
797
+ return webhookUrl ? { provider: "teams", label: value.label, webhookUrl } : void 0;
798
+ },
799
+ async send(destination, notification, signal) {
800
+ if (signal.aborted) return { state: "cancelled", code: "cancelled" };
801
+ const valid = this.validate(destination);
802
+ if (valid?.provider !== "teams") return { state: "failed", code: "invalid-destination" };
803
+ const result = await postJson(
804
+ valid.webhookUrl,
805
+ card(boundedText(notification.title, notification.body)),
806
+ signal,
807
+ fetcher
808
+ );
809
+ if (result.state !== "response") return result;
810
+ return result.status === 202 ? { state: "accepted" } : { state: "failed", code: "response" };
811
+ }
812
+ };
813
+ }
814
+
815
+ // src/providers/telegram.ts
816
+ var TIMEOUT_MS4 = 1e4;
817
+ var MAX_RESPONSE_BYTES4 = 65536;
818
+ function codePointBoundary(text, offset) {
819
+ const before = text.charCodeAt(offset - 1);
820
+ const after = text.charCodeAt(offset);
821
+ return !(before >= 55296 && before <= 56319 && after >= 56320 && after <= 57343);
822
+ }
823
+ function telegramMessage(notification) {
824
+ const source = `${notification.title}
825
+ ${notification.body}`;
826
+ const text = clipText(source, 4096);
827
+ const contentEnd = text.length - (text === source ? 0 : 1);
828
+ const ranges = [
829
+ { style: "bold", offset: 0, length: notification.title.length },
830
+ ...(notification.bodyEmphasis ?? []).flatMap(
831
+ (range) => Number.isSafeInteger(range.offset) && Number.isSafeInteger(range.length) && range.offset >= 0 && range.length > 0 && range.offset + range.length <= notification.body.length ? [{ ...range, offset: notification.title.length + 1 + range.offset }] : []
832
+ )
833
+ ];
834
+ const entities = ranges.flatMap(({ style, offset, length }) => {
835
+ const retained = source.slice(offset, Math.min(offset + length, contentEnd)).trimEnd();
836
+ const end = offset + retained.length;
837
+ if (end <= offset || !codePointBoundary(source, offset) || !codePointBoundary(source, end)) return [];
838
+ return [{ type: style === "bold" ? "bold" : "code", offset, length: end - offset }];
839
+ });
840
+ return { text, entities };
841
+ }
842
+ function createTelegramProvider(fetcher = fetch) {
843
+ return {
844
+ id: "telegram",
845
+ label: "Telegram",
846
+ validate(value) {
847
+ if (!isObject(value) || value.provider !== "telegram") return void 0;
848
+ if (typeof value.label !== "string" || !value.label.trim() || value.label.length > 128) return void 0;
849
+ if (typeof value.botToken !== "string" || !/^\d{1,20}:[A-Za-z0-9_-]{20,200}$/.test(value.botToken))
850
+ return void 0;
851
+ if (typeof value.chatId !== "string" || !/^-?[1-9]\d{0,30}$/.test(value.chatId)) return void 0;
852
+ if (value.messageThreadId !== void 0 && (!Number.isSafeInteger(value.messageThreadId) || Number(value.messageThreadId) <= 0))
853
+ return void 0;
854
+ return {
855
+ provider: "telegram",
856
+ label: value.label,
857
+ botToken: value.botToken,
858
+ chatId: value.chatId,
859
+ messageThreadId: value.messageThreadId === void 0 ? void 0 : Number(value.messageThreadId)
860
+ };
861
+ },
862
+ async send(destination, notification, signal) {
863
+ if (signal.aborted) return { state: "cancelled", code: "cancelled" };
864
+ if (destination.provider !== "telegram") return { state: "failed", code: "invalid-destination" };
865
+ const timeout = new AbortController();
866
+ const timer = setTimeout(() => timeout.abort(), TIMEOUT_MS4);
867
+ const combined = AbortSignal.any([signal, timeout.signal]);
868
+ try {
869
+ const response = await fetcher(`https://api.telegram.org/bot${destination.botToken}/sendMessage`, {
870
+ method: "POST",
871
+ redirect: "error",
872
+ signal: combined,
873
+ headers: { "content-type": "application/json" },
874
+ body: JSON.stringify({
875
+ chat_id: destination.chatId,
876
+ ...destination.messageThreadId === void 0 ? {} : { message_thread_id: destination.messageThreadId },
877
+ ...telegramMessage(notification),
878
+ link_preview_options: { is_disabled: true }
879
+ })
880
+ });
881
+ const reader = response.body?.getReader();
882
+ if (!reader) return { state: "failed", code: "response" };
883
+ let length = 0;
884
+ const chunks = [];
885
+ try {
886
+ while (true) {
887
+ combined.throwIfAborted();
888
+ const part = await reader.read();
889
+ if (part.done) break;
890
+ length += part.value.byteLength;
891
+ if (length > MAX_RESPONSE_BYTES4) return { state: "failed", code: "response" };
892
+ chunks.push(part.value);
893
+ }
894
+ } finally {
895
+ await reader.cancel().catch(() => {
896
+ });
897
+ reader.releaseLock();
898
+ }
899
+ combined.throwIfAborted();
900
+ let body;
901
+ try {
902
+ body = JSON.parse(Buffer.concat(chunks).toString("utf8"));
903
+ } catch {
904
+ return { state: "failed", code: "response" };
905
+ }
906
+ if (!isObject(body)) return { state: "failed", code: "response" };
907
+ if (response.status === 429 || body.error_code === 429) {
908
+ const retry = isObject(body.parameters) ? body.parameters.retry_after : void 0;
909
+ return {
910
+ state: "failed",
911
+ code: "rate-limit",
912
+ ...Number.isSafeInteger(retry) && Number(retry) > 0 ? { retryAfterSeconds: Number(retry) } : {}
913
+ };
914
+ }
915
+ if (!response.ok) return { state: "failed", code: "http" };
916
+ return body.ok === true && isObject(body.result) ? { state: "accepted" } : { state: "failed", code: "api" };
917
+ } catch {
918
+ if (signal.aborted) return { state: "cancelled", code: "cancelled" };
919
+ return { state: "failed", code: timeout.signal.aborted ? "timeout" : "network" };
920
+ } finally {
921
+ clearTimeout(timer);
922
+ }
923
+ }
924
+ };
925
+ }
926
+
927
+ // src/providers/webhook.ts
928
+ function createWebhookProvider(fetcher = fetch) {
929
+ return {
930
+ id: "webhook",
931
+ label: "Generic webhook",
932
+ validate(value) {
933
+ if (!isObject(value) || value.provider !== "webhook") return void 0;
934
+ if (typeof value.label !== "string" || !value.label.trim() || value.label.length > 128) return void 0;
935
+ if (!normalizeHttpUrl(value.webhookUrl)) return void 0;
936
+ const webhookUrl = new URL(String(value.webhookUrl)).href;
937
+ if (webhookUrl.length > 2048) return void 0;
938
+ if (value.bearerToken !== void 0 && (typeof value.bearerToken !== "string" || !/^[\x21-\x7e]{1,512}$/.test(value.bearerToken)))
939
+ return void 0;
940
+ return {
941
+ provider: "webhook",
942
+ label: value.label,
943
+ webhookUrl,
944
+ bearerToken: value.bearerToken === void 0 ? void 0 : String(value.bearerToken)
945
+ };
946
+ },
947
+ async send(destination, notification, signal) {
948
+ if (signal.aborted) return { state: "cancelled", code: "cancelled" };
949
+ const valid = this.validate(destination);
950
+ if (valid?.provider !== "webhook") return { state: "failed", code: "invalid-destination" };
951
+ const result = await postJson(
952
+ valid.webhookUrl,
953
+ {
954
+ id: notification.id,
955
+ title: notification.title,
956
+ body: notification.body,
957
+ settledAt: notification.settledAt
958
+ },
959
+ signal,
960
+ fetcher,
961
+ valid.bearerToken === void 0 ? {} : { Authorization: `Bearer ${valid.bearerToken}` }
962
+ );
963
+ return result.state === "response" ? { state: "accepted" } : result;
964
+ }
965
+ };
966
+ }
967
+
968
+ // src/providers.ts
969
+ var providers = /* @__PURE__ */ new Map([
970
+ ["telegram", createTelegramProvider()],
971
+ ["gotify", createGotifyProvider()],
972
+ ["slack", createSlackProvider()],
973
+ ["ntfy", createNtfyProvider()],
974
+ ["pushover", createPushoverProvider()],
975
+ ["discord", createDiscordProvider()],
976
+ ["bark", createBarkProvider()],
977
+ ["webhook", createWebhookProvider()],
978
+ ["line", createLineProvider()],
979
+ ["teams", createTeamsProvider()]
980
+ ]);
981
+
982
+ // src/notify.ts
983
+ function notify(pi) {
984
+ const owners = /* @__PURE__ */ new Map();
985
+ const current = (ctx) => owners.get(ctx.sessionManager);
986
+ const stop = async (owner) => {
987
+ owner.controller.abort();
988
+ owner.unsubscribe?.();
989
+ owner.unsubscribe = void 0;
990
+ await Promise.allSettled([owner.coordinator.close(), owner.store.flush(), owner.menu]);
991
+ };
992
+ pi.on("session_start", async (_event, ctx) => {
993
+ const previous = current(ctx);
994
+ const controller = new AbortController();
995
+ const store = new SettingsStore(
996
+ join(getAgentDir(), "pi-notify.json"),
997
+ ctx.isProjectTrusted() ? join(ctx.cwd, CONFIG_DIR_NAME, "pi-notify.json") : void 0,
998
+ providers
999
+ );
1000
+ const ui = ctx.ui;
1001
+ const hasUI = ctx.hasUI;
1002
+ const manager = ctx.sessionManager;
1003
+ const owner = {
1004
+ controller,
1005
+ store,
1006
+ coordinator: new Coordinator(defaults(), providers, ctx.mode === "tui", void 0, () => {
1007
+ if (owners.get(manager) === owner && !controller.signal.aborted && hasUI)
1008
+ ui.notify("Notification failed. Open /notify \u2192 Status for a safe error code.", "warning");
1009
+ })
1010
+ };
1011
+ owners.set(manager, owner);
1012
+ if (previous) await stop(previous);
1013
+ if (controller.signal.aborted || owners.get(manager) !== owner) return;
1014
+ const snapshot = await store.load();
1015
+ if (controller.signal.aborted || owners.get(manager) !== owner) return;
1016
+ owner.coordinator.apply(snapshot.effective);
1017
+ if (ctx.mode === "tui") {
1018
+ owner.unsubscribe = ui.onTerminalInput((data) => {
1019
+ owner.coordinator.input(data);
1020
+ });
1021
+ owner.coordinator.observeActivity();
1022
+ }
1023
+ if (snapshot.diagnostics.length && hasUI) ui.notify(snapshot.diagnostics.join(" "), "warning");
1024
+ });
1025
+ pi.on("before_agent_start", (_event, ctx) => {
1026
+ current(ctx)?.coordinator.begin(true);
1027
+ });
1028
+ pi.on("agent_start", (_event, ctx) => {
1029
+ current(ctx)?.coordinator.begin();
1030
+ });
1031
+ pi.on("message_end", (event, ctx) => {
1032
+ if (event.message.role === "assistant") current(ctx)?.coordinator.assistant(event.message.stopReason === "error");
1033
+ });
1034
+ pi.on("agent_settled", (event, ctx) => {
1035
+ current(ctx)?.coordinator.settle(event.aborted, {
1036
+ sessionId: ctx.sessionManager.getSessionId(),
1037
+ sessionName: ctx.sessionManager.getSessionName(),
1038
+ cwd: ctx.cwd
1039
+ });
1040
+ });
1041
+ pi.on("session_shutdown", async (_event, ctx) => {
1042
+ const owner = current(ctx);
1043
+ if (!owner) return;
1044
+ owners.delete(ctx.sessionManager);
1045
+ await stop(owner);
1046
+ });
1047
+ pi.registerCommand("notify", {
1048
+ description: "Configure notification destinations and inactivity reminders",
1049
+ handler: async (args, ctx) => {
1050
+ if (args.trim()) throw new Error("Usage: /notify (no arguments).");
1051
+ const owner = current(ctx);
1052
+ const path = owner?.store.userPath ?? join(getAgentDir(), "pi-notify.json");
1053
+ if (ctx.mode !== "tui") {
1054
+ if (ctx.hasUI) {
1055
+ ctx.ui.notify(
1056
+ `Notify setup requires TUI. Edit ${displayPath(path)} manually; inactivity mode delivers at settlement outside TUI.`,
1057
+ "info"
1058
+ );
1059
+ return;
1060
+ }
1061
+ throw new Error(
1062
+ "/notify setup requires TUI. Edit the user pi-notify.json file and reload; automatic delivery is independent of the menu."
1063
+ );
1064
+ }
1065
+ if (!owner || owner.controller.signal.aborted) throw new Error("Notify session is unavailable. Reload Pi.");
1066
+ if (owner.menu) {
1067
+ ctx.ui.notify("Notify menu is already open.", "info");
1068
+ return;
1069
+ }
1070
+ const isCurrent = () => owners.get(ctx.sessionManager) === owner && !owner.controller.signal.aborted;
1071
+ const { showNotifyMenu } = await import("./chunks/menu-2A2EKOVH.ts");
1072
+ if (!isCurrent()) return;
1073
+ if (owner.menu) {
1074
+ ctx.ui.notify("Notify menu is already open.", "info");
1075
+ return;
1076
+ }
1077
+ const running = showNotifyMenu(ctx, {
1078
+ store: owner.store,
1079
+ coordinator: owner.coordinator,
1080
+ providers,
1081
+ signal: owner.controller.signal,
1082
+ isCurrent
1083
+ });
1084
+ owner.menu = running;
1085
+ try {
1086
+ await running;
1087
+ } finally {
1088
+ if (owner.menu === running) owner.menu = void 0;
1089
+ }
1090
+ }
1091
+ });
1092
+ }
1093
+ export {
1094
+ notify as default
1095
+ };
1096
+ //# sourceMappingURL=index.ts.map