@narumitw/pi-notify 0.3.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/README.md +23 -12
- package/dist/chunks/chunk-YXQ43SWY.ts +318 -0
- package/dist/chunks/chunk-YXQ43SWY.ts.map +7 -0
- package/dist/chunks/menu-2A2EKOVH.ts +988 -0
- package/dist/chunks/menu-2A2EKOVH.ts.map +7 -0
- package/dist/index.ts +1096 -0
- package/dist/index.ts.map +7 -0
- package/docs/settings.md +109 -5
- package/package.json +11 -2
- package/src/destination-ui.ts +22 -0
- package/src/menu.ts +82 -3
- package/src/provider.ts +16 -1
- package/src/providers/line.ts +91 -0
- package/src/providers/teams.ts +156 -0
- package/src/providers.ts +4 -0
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/notify.ts", "../src/coordinator.ts", "../src/activity.ts", "../src/providers/http.ts", "../src/providers/bark.ts", "../src/providers/discord.ts", "../src/providers/gotify.ts", "../src/providers/line.ts", "../src/providers/ntfy.ts", "../src/providers/pushover.ts", "../src/providers/slack.ts", "../src/providers/teams.ts", "../src/providers/telegram.ts", "../src/providers/webhook.ts", "../src/providers.ts"],
|
|
4
|
+
"sourcesContent": ["import { join } from \"node:path\";\nimport {\n CONFIG_DIR_NAME,\n type ExtensionAPI,\n type ExtensionContext,\n getAgentDir,\n} from \"@earendil-works/pi-coding-agent\";\nimport { Coordinator } from \"./coordinator.js\";\nimport { displayPath } from \"./metadata.js\";\nimport { providers } from \"./providers.js\";\nimport { defaults, SettingsStore } from \"./settings.js\";\n\ninterface Owner {\n controller: AbortController;\n store: SettingsStore;\n coordinator: Coordinator;\n unsubscribe?: () => void;\n menu?: Promise<unknown>;\n}\n\nexport default function notify(pi: ExtensionAPI): void {\n const owners = new Map<ExtensionContext[\"sessionManager\"], Owner>();\n const current = (ctx: ExtensionContext) => owners.get(ctx.sessionManager);\n const stop = async (owner: Owner) => {\n owner.controller.abort();\n owner.unsubscribe?.();\n owner.unsubscribe = undefined;\n await Promise.allSettled([owner.coordinator.close(), owner.store.flush(), owner.menu]);\n };\n pi.on(\"session_start\", async (_event, ctx) => {\n const previous = current(ctx);\n const controller = new AbortController();\n const store = new SettingsStore(\n join(getAgentDir(), \"pi-notify.json\"),\n ctx.isProjectTrusted() ? join(ctx.cwd, CONFIG_DIR_NAME, \"pi-notify.json\") : undefined,\n providers,\n );\n const ui = ctx.ui;\n const hasUI = ctx.hasUI;\n const manager = ctx.sessionManager;\n const owner: Owner = {\n controller,\n store,\n coordinator: new Coordinator(defaults(), providers, ctx.mode === \"tui\", undefined, () => {\n if (owners.get(manager) === owner && !controller.signal.aborted && hasUI)\n ui.notify(\"Notification failed. Open /notify \u2192 Status for a safe error code.\", \"warning\");\n }),\n };\n owners.set(manager, owner);\n if (previous) await stop(previous);\n if (controller.signal.aborted || owners.get(manager) !== owner) return;\n const snapshot = await store.load();\n if (controller.signal.aborted || owners.get(manager) !== owner) return;\n owner.coordinator.apply(snapshot.effective);\n if (ctx.mode === \"tui\") {\n // Public listeners run after Pi viewport input handling. Focus, mouse, and\n // viewport/search keys can be consumed first; this observes forwarded input only.\n owner.unsubscribe = ui.onTerminalInput((data) => {\n owner.coordinator.input(data);\n });\n owner.coordinator.observeActivity();\n }\n if (snapshot.diagnostics.length && hasUI) ui.notify(snapshot.diagnostics.join(\" \"), \"warning\");\n });\n pi.on(\"before_agent_start\", (_event, ctx) => {\n current(ctx)?.coordinator.begin(true);\n });\n pi.on(\"agent_start\", (_event, ctx) => {\n current(ctx)?.coordinator.begin();\n });\n pi.on(\"message_end\", (event, ctx) => {\n if (event.message.role === \"assistant\") current(ctx)?.coordinator.assistant(event.message.stopReason === \"error\");\n });\n pi.on(\"agent_settled\", (event, ctx) => {\n current(ctx)?.coordinator.settle(event.aborted, {\n sessionId: ctx.sessionManager.getSessionId(),\n sessionName: ctx.sessionManager.getSessionName(),\n cwd: ctx.cwd,\n });\n });\n pi.on(\"session_shutdown\", async (_event, ctx) => {\n const owner = current(ctx);\n if (!owner) return;\n owners.delete(ctx.sessionManager);\n await stop(owner);\n });\n pi.registerCommand(\"notify\", {\n description: \"Configure notification destinations and inactivity reminders\",\n handler: async (args, ctx) => {\n if (args.trim()) throw new Error(\"Usage: /notify (no arguments).\");\n const owner = current(ctx);\n const path = owner?.store.userPath ?? join(getAgentDir(), \"pi-notify.json\");\n if (ctx.mode !== \"tui\") {\n if (ctx.hasUI) {\n ctx.ui.notify(\n `Notify setup requires TUI. Edit ${displayPath(path)} manually; inactivity mode delivers at settlement outside TUI.`,\n \"info\",\n );\n return;\n }\n throw new Error(\n \"/notify setup requires TUI. Edit the user pi-notify.json file and reload; automatic delivery is independent of the menu.\",\n );\n }\n if (!owner || owner.controller.signal.aborted) throw new Error(\"Notify session is unavailable. Reload Pi.\");\n if (owner.menu) {\n ctx.ui.notify(\"Notify menu is already open.\", \"info\");\n return;\n }\n const isCurrent = () => owners.get(ctx.sessionManager) === owner && !owner.controller.signal.aborted;\n const { showNotifyMenu } = await import(\"./menu.js\");\n if (!isCurrent()) return;\n // Dynamic import can race a second invocation of this command.\n if (owner.menu) {\n ctx.ui.notify(\"Notify menu is already open.\", \"info\");\n return;\n }\n const running = showNotifyMenu(ctx, {\n store: owner.store,\n coordinator: owner.coordinator,\n providers,\n signal: owner.controller.signal,\n isCurrent,\n });\n owner.menu = running;\n try {\n await running;\n } finally {\n if (owner.menu === running) owner.menu = undefined;\n }\n },\n });\n}\n", "import { randomUUID } from \"node:crypto\";\nimport { isUserActivity } from \"./activity.js\";\nimport { type Metadata, notificationMetadata } from \"./metadata.js\";\nimport { type DeliveryResult, type Destination, deliver, type Notification, type Providers } from \"./provider.js\";\nimport type { Settings } from \"./settings.js\";\n\ninterface Work {\n id: string;\n startedAt: number;\n error: boolean;\n revision: number;\n}\ninterface Pending {\n work: Work;\n dueAt: number;\n controller: AbortController;\n timer?: ReturnType<typeof setTimeout>;\n notification?: Notification;\n}\nexport interface DeliveryStatus {\n sequence: number;\n result: DeliveryResult | { state: \"sending\" };\n}\n\n/** Session-owned policy. Providers receive only immutable notification data and cancellation. */\nexport class Coordinator {\n private alive = true;\n private revision = 0;\n private sequence = 0;\n private work?: Work;\n private pending?: Pending;\n private lastActivity = Date.now();\n private readonly tasks = new Map<Promise<unknown>, AbortController>();\n readonly statuses = new Map<string, DeliveryStatus>();\n constructor(\n private settings: Settings,\n private readonly providers: Providers,\n private readonly tui: boolean,\n private readonly metadata: typeof notificationMetadata = notificationMetadata,\n private readonly onFailure: () => void = () => {},\n ) {}\n get pendingAt(): number | undefined {\n return this.pending?.dueAt;\n }\n observeActivity(): void {\n // Loading settings can take time; do not infer absence before observation starts.\n this.lastActivity = Date.now();\n }\n begin(replace = false): void {\n if (!this.alive) return;\n this.cancelPending();\n if (!this.work || replace)\n this.work = { id: randomUUID(), startedAt: Date.now(), error: false, revision: this.revision };\n }\n assistant(error: boolean): void {\n if (this.work) this.work.error = error;\n }\n input(data: string): void {\n if (this.tui && this.alive && isUserActivity(data)) {\n this.lastActivity = Date.now();\n this.cancelPending();\n }\n }\n apply(settings: Settings): void {\n this.cancelPending();\n this.revision++;\n this.settings = settings;\n for (const id of this.statuses.keys()) if (!Object.hasOwn(settings.destinations, id)) this.statuses.delete(id);\n }\n private cancelPending(): void {\n const pending = this.pending;\n this.pending = undefined;\n if (pending) {\n clearTimeout(pending.timer);\n pending.controller.abort();\n }\n }\n settle(aborted: boolean, data: Pick<Metadata, \"sessionId\" | \"sessionName\" | \"cwd\">): void {\n const work = this.work;\n this.work = undefined;\n if (\n !this.alive ||\n !work ||\n work.revision !== this.revision ||\n aborted ||\n !this.settings.enabled ||\n !this.settings.targetIds.length\n )\n return;\n this.cancelPending();\n const now = Date.now();\n const dueAt =\n this.tui && this.settings.mode === \"after-inactivity\"\n ? Math.max(now, this.lastActivity + this.settings.inactivitySeconds * 1000)\n : now;\n const pending: Pending = { work, dueAt, controller: new AbortController() };\n this.pending = pending;\n if (dueAt > now) pending.timer = setTimeout(() => this.trySend(pending), dueAt - now);\n const task = this.metadata({ ...data, ...work, settledAt: now }, pending.controller.signal)\n .then((notification) => {\n if (this.pending !== pending || !this.alive || pending.controller.signal.aborted) return;\n pending.notification = notification;\n this.trySend(pending);\n })\n .catch(() => {\n if (this.pending === pending) this.cancelPending();\n });\n this.track(task, pending.controller);\n }\n private trySend(pending: Pending): void {\n if (\n !this.alive ||\n this.pending !== pending ||\n pending.controller.signal.aborted ||\n this.work ||\n Date.now() < pending.dueAt ||\n !pending.notification ||\n !this.settings.enabled\n )\n return;\n this.pending = undefined;\n clearTimeout(pending.timer);\n const notification = pending.notification;\n for (const id of this.settings.targetIds) {\n const destination = this.settings.destinations[id];\n if (destination) void this.send(id, destination, notification);\n }\n }\n private track<T>(promise: Promise<T>, controller: AbortController): Promise<T> {\n this.tasks.set(promise, controller);\n void promise.finally(() => this.tasks.delete(promise)).catch(() => {});\n return promise;\n }\n send(\n id: string,\n destination: Destination,\n notification: Notification,\n signal?: AbortSignal,\n ): Promise<DeliveryResult> {\n const controller = new AbortController();\n const combined = signal ? AbortSignal.any([signal, controller.signal]) : controller.signal;\n if (!this.alive) controller.abort();\n const sequence = ++this.sequence;\n this.statuses.set(id, { sequence, result: { state: \"sending\" } });\n const task = deliver(this.providers, destination, notification, combined).then((result) => {\n if (this.alive && this.statuses.get(id)?.sequence === sequence) {\n this.statuses.set(id, { sequence, result });\n if (result.state === \"failed\") this.onFailure();\n }\n return result;\n });\n return this.track(task, controller);\n }\n async close(): Promise<void> {\n this.alive = false;\n this.work = undefined;\n this.cancelPending();\n for (const controller of this.tasks.values()) controller.abort();\n await Promise.allSettled(this.tasks.keys());\n this.statuses.clear();\n }\n}\n", "import { isKeyRelease, parseKey } from \"@earendil-works/pi-tui\";\n\n/** Classify forwarded input, not all terminal activity. Pi can consume events before this hook. */\nexport function isUserActivity(data: string): boolean {\n if (!data || isKeyRelease(data)) return false;\n if (data.startsWith(\"\\x1b[200~\") && data.endsWith(\"\\x1b[201~\")) return true;\n if (data === \"\\x1b[I\") return true;\n if (data === \"\\x1b[O\") return false;\n // biome-ignore lint/suspicious/noControlCharactersInRegex: Match the terminal's SGR protocol envelope.\n const sgr = /^\\x1b\\[<(\\d+);\\d+;\\d+([Mm])$/.exec(data);\n if (sgr) return sgr[2] === \"M\" && (Number(sgr[1]) & 32) === 0;\n if (data.length === 6 && data.startsWith(\"\\x1b[M\")) {\n const button = data.charCodeAt(3) - 32;\n return (button & 32) === 0 && (button & 3) !== 3;\n }\n // Keys, modified keys, Escape and control keys use Pi's authoritative parser.\n if (parseKey(data) !== undefined) return true;\n // Plain Unicode/pasted characters without an escape/control envelope.\n // biome-ignore lint/suspicious/noControlCharactersInRegex: Capability reports are not user activity.\n return !/[\\x00-\\x1f\\x7f-\\x9f]/.test(data);\n}\n", "import type { DeliveryResult } from \"../provider.js\";\n\nconst TIMEOUT_MS = 10_000;\nconst MAX_RESPONSE_BYTES = 65_536;\n\n/** Explicit HTTP(S) endpoints may reach local networks; never accept URL credentials or query auth. */\nexport function normalizeHttpUrl(value: unknown): string | undefined {\n if (typeof value !== \"string\" || value.length > 2048 || /[\\s\\\\?#\\p{Cc}]/u.test(value)) return undefined;\n if (!/^https?:\\/\\/[^/@]+(?:\\/|$)/i.test(value)) return undefined;\n try {\n // Reject encoded controls, backslashes, and malformed percent escapes before URL parsing.\n if (/[\\\\\\p{Cc}]/u.test(decodeURIComponent(value))) return undefined;\n const raw = /^https?:\\/\\/([^/]+)(\\/.*)?$/i.exec(value);\n if (\n !raw ||\n decodeURIComponent(raw[2] ?? \"\")\n .split(\"/\")\n .some((part) => part === \".\" || part === \"..\")\n )\n return undefined;\n const url = new URL(value);\n if (url.username || url.password || !url.hostname) return undefined;\n // WHATWG rewrites numeric IPv4 aliases (hex, octal, shortened, or integer) to a different host spelling.\n // Accept explicit private addresses, but require canonical dotted-decimal IPv4 input.\n const rawHost = raw[1]?.split(\":\")[0];\n if (/^(?:\\d{1,3}\\.){3}\\d{1,3}$/.test(url.hostname) && rawHost !== url.hostname) return undefined;\n const normalized = url.href.replace(/\\/+$/, \"\");\n return normalized.length <= 2048 ? normalized : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** Keep complete Unicode code points within a UTF-8 byte budget. */\nexport function truncateUtf8(value: string, maxBytes: number): string {\n let bytes = 0;\n let result = \"\";\n for (const point of value) {\n bytes += Buffer.byteLength(point, \"utf8\");\n if (bytes > maxBytes) break;\n result += point;\n }\n return result;\n}\n\n/** POST once. A response is transport acceptance only; the provider checks its service contract. */\nexport async function postJson(\n url: string,\n payload: unknown,\n signal: AbortSignal,\n fetcher: typeof fetch = fetch,\n headers: Record<string, string> = {},\n): Promise<{ state: \"response\"; body: unknown; status: number } | DeliveryResult> {\n if (signal.aborted) return { state: \"cancelled\", code: \"cancelled\" };\n const timeout = new AbortController();\n const timer = setTimeout(() => timeout.abort(), TIMEOUT_MS);\n const combined = AbortSignal.any([signal, timeout.signal]);\n let rejectAbort!: (reason: unknown) => void;\n const aborted = new Promise<never>((_resolve, reject) => {\n rejectAbort = reject;\n });\n const onAbort = () => rejectAbort(combined.reason);\n combined.addEventListener(\"abort\", onAbort, { once: true });\n let reader: ReadableStreamDefaultReader<Uint8Array> | undefined;\n try {\n const fetching = fetcher(url, {\n method: \"POST\",\n redirect: \"error\",\n signal: combined,\n headers: { \"content-type\": \"application/json\", ...headers },\n body: JSON.stringify(payload),\n }).then((response) => {\n // An injected fetch can ignore abort and settle after this request has ended.\n if (combined.aborted) void response.body?.cancel().catch(() => {});\n return response;\n });\n const response = await Promise.race([fetching, aborted]);\n combined.throwIfAborted();\n if (!response.ok) {\n void response.body?.cancel().catch(() => {});\n const retry = response.headers.get(\"retry-after\");\n return {\n state: \"failed\",\n code: response.status === 429 ? \"rate-limit\" : \"http\",\n ...(response.status === 429 &&\n retry &&\n /^\\d+$/.test(retry) &&\n Number.isSafeInteger(Number(retry)) &&\n Number(retry) > 0\n ? { retryAfterSeconds: Number(retry) }\n : {}),\n };\n }\n reader = response.body?.getReader();\n const chunks: Uint8Array[] = [];\n let length = 0;\n while (reader) {\n const part = await Promise.race([reader.read(), aborted]);\n combined.throwIfAborted();\n if (part.done) break;\n length += part.value.byteLength;\n if (length > MAX_RESPONSE_BYTES) return { state: \"failed\", code: \"response\" };\n if (part.value.byteLength) chunks.push(part.value);\n }\n let body: unknown;\n try {\n body = JSON.parse(Buffer.concat(chunks, length).toString(\"utf8\"));\n } catch {\n // Empty/non-JSON success is valid for some endpoints, but not for service-specific JSON APIs.\n body = undefined;\n }\n return { state: \"response\", body, status: response.status };\n } catch {\n if (signal.aborted) return { state: \"cancelled\", code: \"cancelled\" };\n return { state: \"failed\", code: timeout.signal.aborted ? \"timeout\" : \"network\" };\n } finally {\n if (reader) {\n // Stream cancellation itself can stall. Do not await an untrusted underlying source.\n void reader.cancel().catch(() => {});\n reader.releaseLock();\n }\n combined.removeEventListener(\"abort\", onAbort);\n clearTimeout(timer);\n }\n}\n", "import { type DeliveryResult, isObject, type NotificationProvider } from \"../provider.js\";\nimport { normalizeHttpUrl, postJson, truncateUtf8 } from \"./http.js\";\n\n// Official contract: https://bark.day.app/#/tutorial and Finb/bark-server at\n// 640deaa151ddf79193202927b35ca2f14f65ee1d: docs/API_V2.md, route_push.go,\n// router.go, and route_auth.go. POST /push accepts JSON; numeric code 200 means acceptance.\n// Native Basic authentication is not supported. Keys and messages stay in the JSON body.\nexport function createBarkProvider(fetcher: typeof fetch = fetch): NotificationProvider {\n return {\n id: \"bark\",\n label: \"Bark\",\n validate(value) {\n if (!isObject(value) || value.provider !== \"bark\") return undefined;\n if (typeof value.label !== \"string\" || !value.label.trim() || value.label.length > 128) return undefined;\n const serverUrl = normalizeHttpUrl(value.serverUrl);\n // Local printable-ASCII safety limit (no spaces), not an upstream device-key format claim.\n if (!serverUrl || typeof value.deviceKey !== \"string\" || !/^[\\x21-\\x7e]{1,512}$/.test(value.deviceKey))\n return undefined;\n return { provider: \"bark\", label: value.label, serverUrl, deviceKey: value.deviceKey };\n },\n async send(destination, notification, signal): Promise<DeliveryResult> {\n if (signal.aborted) return { state: \"cancelled\", code: \"cancelled\" };\n const valid = this.validate(destination);\n if (valid?.provider !== \"bark\") return { state: \"failed\", code: \"invalid-destination\" };\n // Local limits, not upstream limits: title 256 and body 2048 UTF-8 bytes.\n // Keep encoded {title,body} within 3000 bytes to leave room in APNs' default\n // 4096-byte envelope. Count JSON escapes, not only decoded text bytes.\n const title = truncateUtf8(notification.title, 256);\n let remaining = 3000 - Buffer.byteLength(JSON.stringify({ title, body: \"\" }), \"utf8\");\n let body = \"\";\n for (const point of truncateUtf8(notification.body, 2048)) {\n const encodedBytes = Buffer.byteLength(JSON.stringify(point), \"utf8\") - 2;\n if (encodedBytes > remaining) break;\n body += point;\n remaining -= encodedBytes;\n }\n const result = await postJson(\n `${valid.serverUrl}/push`,\n { device_key: valid.deviceKey, title, body },\n signal,\n fetcher,\n );\n if (result.state !== \"response\") return result;\n if (result.status !== 200 || !isObject(result.body) || typeof result.body.code !== \"number\")\n return { state: \"failed\", code: \"response\" };\n return result.body.code === 200 ? { state: \"accepted\" } : { state: \"failed\", code: \"api\" };\n },\n };\n}\n", "import { sanitizeTerminalText } from \"@narumitw/pi-tui-kit/terminal-text\";\nimport { type DeliveryResult, isObject, type NotificationProvider } from \"../provider.js\";\nimport { clipText } from \"../text.js\";\nimport { postJson } from \"./http.js\";\n\n// https://discord.com/developers/docs/resources/webhook#execute-webhook\n// https://discord.com/developers/docs/resources/message#allowed-mentions-object\n// Official OpenAPI: discord/discord-api-spec@ed014089afa986f2b532ae081c456a85de074d0c.\nfunction isSnowflake(value: unknown): value is string {\n return (\n typeof value === \"string\" &&\n !/\\s/.test(value) &&\n /^[1-9][0-9]{0,19}$/.test(value) &&\n BigInt(value) <= 18446744073709551615n\n );\n}\n\n/** Match the literal official endpoint; do not accept URL parser normalization aliases. */\nexport function validateDiscordWebhookUrl(value: unknown): value is string {\n if (typeof value !== \"string\" || value.length > 2048 || /[\\s\\\\\\p{Cc}]/u.test(value)) return false;\n const match = /^https:\\/\\/discord\\.com\\/api\\/(?:v10\\/)?webhooks\\/([1-9][0-9]{0,19})\\/[-_A-Za-z0-9]+$/.exec(value);\n return match !== null && isSnowflake(match[1]);\n}\n\nexport function createDiscordProvider(fetcher: typeof fetch = fetch): NotificationProvider {\n return {\n id: \"discord\",\n label: \"Discord\",\n validate(value) {\n if (!isObject(value) || value.provider !== \"discord\") return undefined;\n if (typeof value.label !== \"string\" || !value.label.trim() || value.label.length > 128) return undefined;\n if (!validateDiscordWebhookUrl(value.webhookUrl)) return undefined;\n return { provider: \"discord\", label: value.label, webhookUrl: value.webhookUrl };\n },\n async send(destination, notification, signal): Promise<DeliveryResult> {\n if (signal.aborted) return { state: \"cancelled\", code: \"cancelled\" };\n const valid = this.validate(destination);\n if (valid?.provider !== \"discord\") return { state: \"failed\", code: \"invalid-destination\" };\n const text = `${notification.title}\\n${notification.body}`.split(\"\\n\").map(sanitizeTerminalText).join(\"\\n\");\n const result = await postJson(\n `${valid.webhookUrl}?wait=true`,\n {\n content: clipText(text.trim() ? text : \"Pi notification\", 2000),\n // Enforce this for direct callers, not only for metadata produced by the coordinator.\n allowed_mentions: { parse: [] },\n flags: 4, // SUPPRESS_EMBEDS, not SUPPRESS_NOTIFICATIONS (4096).\n },\n signal,\n fetcher,\n {\n // Discord's required bot User-Agent syntax. 1.0 is the adapter version, not the package version.\n \"User-Agent\": \"DiscordBot (https://github.com/narumiruna/pi-extensions, 1.0)\",\n },\n );\n if (result.state !== \"response\") return result;\n const body = result.body;\n return result.status === 200 &&\n isObject(body) &&\n isSnowflake(body.id) &&\n isSnowflake(body.channel_id) &&\n Number.isInteger(body.type)\n ? { state: \"accepted\" }\n : { state: \"failed\", code: \"response\" };\n },\n };\n}\n", "import { type DeliveryResult, isObject, type NotificationProvider } from \"../provider.js\";\n\nconst TIMEOUT_MS = 10_000;\nconst MAX_RESPONSE_BYTES = 65_536;\n\n/** Accept self-hosted HTTP(S), including reverse-proxy paths, but no URL credentials. */\nexport function normalizeGotifyUrl(value: unknown): string | undefined {\n if (typeof value !== \"string\" || value.length > 2048 || /[\\s\\\\?#\\p{Cc}]/u.test(value)) return undefined;\n try {\n const url = new URL(value);\n if (!/^https?:\\/\\/[^/@]+(?:\\/|$)/i.test(value) || url.username || url.password) return undefined;\n const normalized = url.href.replace(/\\/+$/, \"\");\n return normalized.length <= 2048 ? normalized : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** Application-token auth only; no redirects, retries, Markdown extras, or client subscriptions. */\nexport function createGotifyProvider(fetcher: typeof fetch = fetch): NotificationProvider {\n return {\n id: \"gotify\",\n label: \"Gotify\",\n validate(value) {\n if (!isObject(value) || value.provider !== \"gotify\") return undefined;\n if (typeof value.label !== \"string\" || !value.label.trim() || value.label.length > 128) return undefined;\n const serverUrl = normalizeGotifyUrl(value.serverUrl);\n if (!serverUrl || typeof value.appToken !== \"string\" || !/^[\\x21-\\x7e]{1,512}$/.test(value.appToken))\n return undefined;\n if (value.priority !== undefined && !Number.isSafeInteger(value.priority)) return undefined;\n return {\n provider: \"gotify\",\n label: value.label,\n serverUrl,\n appToken: value.appToken,\n priority: value.priority === undefined ? undefined : Number(value.priority),\n };\n },\n async send(destination, notification, signal): Promise<DeliveryResult> {\n if (signal.aborted) return { state: \"cancelled\", code: \"cancelled\" };\n // Validate again for direct callers and use the normalized reverse-proxy base path.\n const valid = this.validate(destination);\n if (valid?.provider !== \"gotify\") return { state: \"failed\", code: \"invalid-destination\" };\n const timeout = new AbortController();\n const timer = setTimeout(() => timeout.abort(), TIMEOUT_MS);\n const combined = AbortSignal.any([signal, timeout.signal]);\n try {\n const response = await fetcher(`${valid.serverUrl}/message`, {\n method: \"POST\",\n redirect: \"error\",\n signal: combined,\n headers: { \"content-type\": \"application/json\", \"X-Gotify-Key\": valid.appToken },\n body: JSON.stringify({\n title: notification.title,\n message: notification.body,\n ...(valid.priority === undefined ? {} : { priority: valid.priority }),\n }),\n });\n combined.throwIfAborted();\n if (!response.ok) {\n await response.body?.cancel().catch(() => {});\n combined.throwIfAborted();\n const retry = response.headers.get(\"retry-after\");\n return {\n state: \"failed\",\n code: response.status === 429 ? \"rate-limit\" : \"http\",\n ...(response.status === 429 &&\n retry &&\n /^\\d+$/.test(retry) &&\n Number.isSafeInteger(Number(retry)) &&\n Number(retry) > 0\n ? { retryAfterSeconds: Number(retry) }\n : {}),\n };\n }\n const reader = response.body?.getReader();\n if (!reader) return { state: \"failed\", code: \"response\" };\n let length = 0;\n const chunks: Uint8Array[] = [];\n try {\n while (true) {\n combined.throwIfAborted();\n const part = await reader.read();\n combined.throwIfAborted();\n if (part.done) break;\n length += part.value.byteLength;\n if (length > MAX_RESPONSE_BYTES) break;\n chunks.push(part.value);\n }\n } finally {\n await reader.cancel().catch(() => {});\n reader.releaseLock();\n }\n combined.throwIfAborted();\n if (length > MAX_RESPONSE_BYTES) return { state: \"failed\", code: \"response\" };\n let body: unknown;\n try {\n body = JSON.parse(Buffer.concat(chunks).toString(\"utf8\"));\n } catch {\n return { state: \"failed\", code: \"response\" };\n }\n // The documented success is a Message, not merely any HTTP 2xx response.\n return isObject(body) &&\n Number.isSafeInteger(body.id) &&\n Number(body.id) > 0 &&\n Number.isSafeInteger(body.appid) &&\n Number(body.appid) > 0 &&\n typeof body.message === \"string\" &&\n typeof body.date === \"string\" &&\n Number.isFinite(Date.parse(body.date))\n ? { state: \"accepted\" }\n : { state: \"failed\", code: \"response\" };\n } catch {\n if (signal.aborted) return { state: \"cancelled\", code: \"cancelled\" };\n return { state: \"failed\", code: timeout.signal.aborted ? \"timeout\" : \"network\" };\n } finally {\n clearTimeout(timer);\n }\n },\n };\n}\n", "import { sanitizeTerminalText } from \"@narumitw/pi-tui-kit/terminal-text\";\nimport { type DeliveryResult, isObject, type NotificationProvider } from \"../provider.js\";\nimport { clipText } from \"../text.js\";\nimport { postJson } from \"./http.js\";\n\n// Verified 2026-10-18: https://developers.line.biz/en/reference/messaging-api/#send-push-message\n// https://developers.line.biz/en/docs/messaging-api/text-character-count/: 5,000 UTF-16 units.\n// https://developers.line.biz/en/docs/basics/channel-access-token/: tokens are opaque.\n// RFC 6750 section 2.1 defines Bearer syntax; 8,192 is a local cap, not a LINE token limit.\nconst MAX_TOKEN_LENGTH = 8192;\n\nfunction plainText(text: string): string {\n return text.split(\"\\n\").map(sanitizeTerminalText).join(\"\\n\");\n}\n\nfunction acceptedBody(body: unknown): boolean {\n if (!isObject(body)) return false;\n // Legacy {}: https://github.com/line/line-bot-sdk-nodejs/blob/master/test/line-bot-client.spec.ts\n // Current schema: https://github.com/line/line-openapi/blob/main/messaging-api.yml\n if (Object.keys(body).length === 0) return true;\n // Current reference uses Number for id; official line-openapi and its example use String.\n return (\n Array.isArray(body.sentMessages) &&\n body.sentMessages.length >= 1 &&\n body.sentMessages.length <= 5 &&\n body.sentMessages.every(\n (message) =>\n isObject(message) &&\n ((typeof message.id === \"string\" && message.id.length > 0) ||\n (typeof message.id === \"number\" && Number.isInteger(message.id) && message.id >= 0)) &&\n (message.quoteToken === undefined || typeof message.quoteToken === \"string\"),\n )\n );\n}\n\n/** One normal text push; HTTP acceptance does not prove recipient delivery. */\nexport function createLineProvider(fetcher: typeof fetch = fetch): NotificationProvider {\n return {\n id: \"line\",\n label: \"LINE\",\n validate(value) {\n if (!isObject(value) || value.provider !== \"line\") return undefined;\n if (typeof value.label !== \"string\" || !value.label.trim() || value.label.length > 128) return undefined;\n if (\n typeof value.channelAccessToken !== \"string\" ||\n value.channelAccessToken.length > MAX_TOKEN_LENGTH ||\n /\\s/u.test(value.channelAccessToken) ||\n !/^[A-Za-z0-9._~+/-]+=*$/u.test(value.channelAccessToken)\n )\n return undefined;\n // https://developers.line.biz/en/docs/messaging-api/getting-user-ids/: U + 32 lowercase hex.\n // The push reference's webhook source examples use C/R prefixes for group/room IDs.\n // Group/room syntax is not specified: printable ASCII and 128 suffix characters\n // are local safety bounds, not a claimed service grammar.\n if (\n typeof value.recipientId !== \"string\" ||\n value.recipientId.length > 129 ||\n /\\s/u.test(value.recipientId) ||\n !/^(?:U[0-9a-f]{32}|[CR][!-~]{1,128})$/u.test(value.recipientId)\n )\n return undefined;\n return {\n provider: \"line\",\n label: value.label,\n channelAccessToken: value.channelAccessToken,\n recipientId: value.recipientId,\n };\n },\n async send(destination, notification, signal): Promise<DeliveryResult> {\n if (signal.aborted) return { state: \"cancelled\", code: \"cancelled\" };\n const valid = this.validate(destination);\n if (valid?.provider !== \"line\") return { state: \"failed\", code: \"invalid-destination\" };\n const result = await postJson(\n \"https://api.line.me/v2/bot/message/push\",\n {\n to: valid.recipientId,\n // No mention/emoji objects, substitutions, formatting, or silent-delivery option.\n // LINE clients can still auto-link literal URLs; this does not promise link suppression.\n messages: [{ type: \"text\", text: clipText(plainText(`${notification.title}\\n${notification.body}`), 5000) }],\n },\n signal,\n fetcher,\n { Authorization: `Bearer ${valid.channelAccessToken}` },\n );\n if (result.state !== \"response\") return result;\n return result.status === 200 && acceptedBody(result.body)\n ? { state: \"accepted\" }\n : { state: \"failed\", code: \"response\" };\n },\n };\n}\n", "import { type DeliveryResult, isObject, type NotificationProvider } from \"../provider.js\";\nimport { normalizeHttpUrl, postJson, truncateUtf8 } from \"./http.js\";\n\n// Official contract: https://docs.ntfy.sh/publish/#publish-as-json\n// Topics: https://docs.ntfy.sh/publish/#picking-a-topic\n// Reserved names: https://github.com/binwiederhier/ntfy/blob/main/server/config.go (DefaultDisallowedTopics).\n// These names are case-sensitive; self-hosted servers can forbid additional topics.\nconst RESERVED_TOPICS = new Set([\n \"docs\",\n \"static\",\n \"file\",\n \"app\",\n \"metrics\",\n \"account\",\n \"settings\",\n \"signup\",\n \"login\",\n \"v1\",\n]);\n\n/** Anonymous or Bearer publishing only. Topic secrecy does not replace server access control. */\nexport function createNtfyProvider(fetcher: typeof fetch = fetch): NotificationProvider {\n return {\n id: \"ntfy\",\n label: \"ntfy\",\n validate(value) {\n if (!isObject(value) || value.provider !== \"ntfy\") return undefined;\n if (typeof value.label !== \"string\" || !value.label.trim() || value.label.length > 128) return undefined;\n if (!normalizeHttpUrl(value.serverUrl)) return undefined;\n // Publishing targets the base itself; preserve its trailing slash for exact proxy mounts.\n const serverUrl = new URL(String(value.serverUrl)).href;\n if (serverUrl.length > 2048 || typeof value.topic !== \"string\" || !/^[-_A-Za-z0-9]{1,64}$/.test(value.topic))\n return undefined;\n if (RESERVED_TOPICS.has(value.topic)) return undefined;\n // Local header-safety limit, not a claim that the server accepts any such token.\n if (\n value.accessToken !== undefined &&\n (typeof value.accessToken !== \"string\" || !/^[\\x21-\\x7e]{1,512}$/.test(value.accessToken))\n )\n return undefined;\n if (\n value.priority !== undefined &&\n (!Number.isInteger(value.priority) || Number(value.priority) < 1 || Number(value.priority) > 5)\n )\n return undefined;\n return {\n provider: \"ntfy\",\n label: value.label,\n serverUrl,\n topic: value.topic,\n accessToken: value.accessToken === undefined ? undefined : String(value.accessToken),\n priority: value.priority === undefined ? undefined : Number(value.priority),\n };\n },\n async send(destination, notification, signal): Promise<DeliveryResult> {\n if (signal.aborted) return { state: \"cancelled\", code: \"cancelled\" };\n const valid = this.validate(destination);\n if (valid?.provider !== \"ntfy\") return { state: \"failed\", code: \"invalid-destination\" };\n // https://docs.ntfy.sh/publish/#limitations: title 1 KiB, message 4096 UTF-8 bytes.\n const payload = {\n topic: valid.topic,\n title: truncateUtf8(notification.title, 1024),\n message: truncateUtf8(notification.body, 4096),\n ...(valid.priority === undefined ? {} : { priority: valid.priority }),\n };\n // The server's transformBodyJSON also caps the complete JSON envelope at 2 * message-size-limit.\n // Escaped controls can exceed that limit even when the decoded strings fit their byte limits.\n const excess = Buffer.byteLength(JSON.stringify(payload), \"utf8\") - 8192;\n if (excess > 0)\n payload.message = truncateUtf8(payload.message, Math.max(0, Buffer.byteLength(payload.message) - excess));\n const result = await postJson(\n valid.serverUrl,\n payload,\n signal,\n fetcher,\n valid.accessToken === undefined ? {} : { Authorization: `Bearer ${valid.accessToken}` },\n );\n if (result.state !== \"response\") return result;\n // Publish returns a Message: https://docs.ntfy.sh/subscribe/api/#json-message-format\n const body = result.body;\n return result.status === 200 &&\n isObject(body) &&\n typeof body.id === \"string\" &&\n body.id.length > 0 &&\n Number.isSafeInteger(body.time) &&\n Number(body.time) > 0 &&\n body.event === \"message\" &&\n body.topic === valid.topic &&\n typeof body.message === \"string\"\n ? { state: \"accepted\" }\n : { state: \"failed\", code: \"response\" };\n },\n };\n}\n", "import { type DeliveryResult, isObject, type NotificationProvider } from \"../provider.js\";\nimport { clipText } from \"../text.js\";\nimport { postJson } from \"./http.js\";\n\n// https://pushover.net/api: Messages API, response format, and limitations.\n// Tokens and user/group keys are exactly 30 case-sensitive ASCII alphanumeric characters.\nexport function createPushoverProvider(fetcher: typeof fetch = fetch): NotificationProvider {\n return {\n id: \"pushover\",\n label: \"Pushover\",\n validate(value) {\n if (!isObject(value) || value.provider !== \"pushover\") return undefined;\n if (typeof value.label !== \"string\" || !value.label.trim() || value.label.length > 128) return undefined;\n if (\n typeof value.appToken !== \"string\" ||\n value.appToken.length !== 30 ||\n !/^[A-Za-z0-9]{30}$/.test(value.appToken)\n )\n return undefined;\n if (typeof value.userKey !== \"string\" || value.userKey.length !== 30 || !/^[A-Za-z0-9]{30}$/.test(value.userKey))\n return undefined;\n return { provider: \"pushover\", label: value.label, appToken: value.appToken, userKey: value.userKey };\n },\n async send(destination, notification, signal): Promise<DeliveryResult> {\n if (signal.aborted) return { state: \"cancelled\", code: \"cancelled\" };\n const valid = this.validate(destination);\n if (valid?.provider !== \"pushover\") return { state: \"failed\", code: \"invalid-destination\" };\n const result = await postJson(\n \"https://api.pushover.net/1/messages.json\",\n {\n token: valid.appToken,\n user: valid.userKey,\n // UTF-16 budgets are conservative for the documented character limits.\n title: clipText(notification.title, 250),\n message: clipText(notification.body, 1024),\n priority: 0,\n },\n signal,\n fetcher,\n );\n if (result.state !== \"response\") return result;\n if (result.status !== 200 || !isObject(result.body) || typeof result.body.status !== \"number\")\n return { state: \"failed\", code: \"response\" };\n return result.body.status === 1 ? { state: \"accepted\" } : { state: \"failed\", code: \"api\" };\n },\n };\n}\n", "import { sanitizeTerminalText } from \"@narumitw/pi-tui-kit/terminal-text\";\nimport { type DeliveryResult, isObject, type Notification, type NotificationProvider } from \"../provider.js\";\n\nconst TIMEOUT_MS = 10_000;\nconst MAX_RESPONSE_BYTES = 65_536;\n\n/** Slack decodes these entities even in plain_text. Bound encoded length without cutting an entity. */\nfunction slackText(notification: Notification): string {\n const raw = `${notification.title}\\n${notification.body}`.split(\"\\n\").map(sanitizeTerminalText).join(\"\\n\");\n let text = \"\";\n let beforeLast = 0;\n for (const character of raw) {\n const escaped = character === \"&\" ? \"&\" : character === \"<\" ? \"<\" : character === \">\" ? \">\" : character;\n if (text.length + escaped.length > 3000) return `${text.length === 3000 ? text.slice(0, beforeLast) : text}\u2026`;\n beforeLast = text.length;\n text += escaped;\n }\n return text.trim() ? text : \"Pi notification\";\n}\n\n/** Match the commercial webhook literal, not a URL parser's normalized interpretation.\n * https://docs.slack.dev/messaging/sending-messages-using-incoming-webhooks/\n */\nexport function validateSlackWebhookUrl(value: unknown): value is string {\n return (\n typeof value === \"string\" &&\n value.length <= 2048 &&\n !/\\s/.test(value) &&\n /^https:\\/\\/hooks\\.slack\\.com\\/services\\/T[A-Z0-9]+\\/B[A-Z0-9]+\\/[A-Za-z0-9]+$/.test(value)\n );\n}\n\n/** Fixed channel, no redirects or retries; the entire URL is a credential. */\nexport function createSlackProvider(fetcher: typeof fetch = fetch): NotificationProvider {\n return {\n id: \"slack\",\n label: \"Slack\",\n validate(value) {\n if (!isObject(value) || value.provider !== \"slack\") return undefined;\n if (typeof value.label !== \"string\" || !value.label.trim() || value.label.length > 128) return undefined;\n if (!validateSlackWebhookUrl(value.webhookUrl)) return undefined;\n return { provider: \"slack\", label: value.label, webhookUrl: value.webhookUrl };\n },\n async send(destination, notification, signal): Promise<DeliveryResult> {\n if (signal.aborted) return { state: \"cancelled\", code: \"cancelled\" };\n const valid = this.validate(destination);\n if (valid?.provider !== \"slack\") return { state: \"failed\", code: \"invalid-destination\" };\n const timeout = new AbortController();\n const timer = setTimeout(() => timeout.abort(), TIMEOUT_MS);\n const combined = AbortSignal.any([signal, timeout.signal]);\n try {\n // Plain text disables Slack formatting. Keep untrusted metadata out of the\n // fallback, which Slack also uses for notifications and screen readers.\n // https://docs.slack.dev/messaging/formatting-message-text/#disabling-formatting\n // Escape Slack control characters exactly once, including existing entity-like text.\n // https://docs.slack.dev/messaging/formatting-message-text/#escaping\n // Section text is limited to 3,000 characters; UTF-16 length is conservative.\n // https://docs.slack.dev/reference/block-kit/blocks/section-block/\n const response = await fetcher(valid.webhookUrl, {\n method: \"POST\",\n redirect: \"error\",\n signal: combined,\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({\n text: \"Pi notification. Open Pi to review.\",\n mrkdwn: false,\n parse: \"none\",\n unfurl_links: false,\n unfurl_media: false,\n blocks: [\n {\n type: \"section\",\n text: { type: \"plain_text\", text: slackText(notification), emoji: false },\n },\n ],\n }),\n });\n if (combined.aborted || response.status !== 200) {\n // Do not await an untrusted stream's potentially stalled cancellation.\n void response.body?.cancel().catch(() => {});\n combined.throwIfAborted();\n const retry = response.headers.get(\"retry-after\");\n return {\n state: \"failed\",\n code: response.status === 429 ? \"rate-limit\" : \"http\",\n ...(response.status === 429 &&\n retry &&\n /^\\d+$/.test(retry) &&\n Number.isSafeInteger(Number(retry)) &&\n Number(retry) > 0\n ? { retryAfterSeconds: Number(retry) }\n : {}),\n };\n }\n const reader = response.body?.getReader();\n if (!reader) return { state: \"failed\", code: \"response\" };\n // Also interrupt injected streams that do not observe the fetch signal.\n const cancel = () => {\n void reader.cancel().catch(() => {});\n };\n combined.addEventListener(\"abort\", cancel, { once: true });\n let length = 0;\n const chunks: Uint8Array[] = [];\n try {\n while (true) {\n combined.throwIfAborted();\n const part = await reader.read();\n combined.throwIfAborted();\n if (part.done) break;\n length += part.value.byteLength;\n if (length > MAX_RESPONSE_BYTES) break;\n if (part.value.byteLength) chunks.push(part.value);\n }\n } finally {\n combined.removeEventListener(\"abort\", cancel);\n cancel();\n reader.releaseLock();\n }\n combined.throwIfAborted();\n // Only the documented HTTP 200 and exact plain-text `ok` is acceptance.\n return length <= MAX_RESPONSE_BYTES && Buffer.concat(chunks).equals(Buffer.from(\"ok\"))\n ? { state: \"accepted\" }\n : { state: \"failed\", code: \"response\" };\n } catch {\n if (signal.aborted) return { state: \"cancelled\", code: \"cancelled\" };\n return { state: \"failed\", code: timeout.signal.aborted ? \"timeout\" : \"network\" };\n } finally {\n clearTimeout(timer);\n }\n },\n };\n}\n", "import { sanitizeTerminalText } from \"@narumitw/pi-tui-kit/terminal-text\";\nimport { type DeliveryResult, isObject, type NotificationProvider } from \"../provider.js\";\nimport { postJson } from \"./http.js\";\n\n// Local support policy, not a complete Microsoft URL grammar. Reviewed 2026-10-18:\n// https://learn.microsoft.com/en-us/power-automate/triggers-troubleshoot\n// documents migration from logic.azure.com and the optional /direct/cu/20 route.\n// https://learn.microsoft.com/en-us/connectors/teams/#microsoft-teams-webhook\n// documents Anyone authentication (no Authorization header) and the card envelope.\n// https://learn.microsoft.com/en-us/azure/logic-apps/logic-apps-http-endpoint\n// documents signed Request URLs; this is corroboration, not a Teams URL/response contract.\n// Public current-format example (corroboration only):\n// https://dev.classmethod.jp/en/articles/aws-step-functions-teams-workflows-new-webhook-url/\n// Support only literal lowercase commercial DNS hosts with one or more valid prefix\n// labels before .environment.api.powerplatform.com; labels <=63, entire host <=253.\n// Require HTTPS, no userinfo, and no port except an explicit generated :443.\n// Paths are exactly /powerautomate/automations/direct/[cu/<route>/]workflows/<id>\n// /triggers/manual/paths/invoke. Route/id are opaque ASCII letters, digits, _ or -,\n// 1..256 characters each: a local bound, NOT an inferred fixed-length service ID.\n// Reject all encoded hosts/paths, dot segments, fragments, whitespace, controls and\n// backslashes before a URL parser could normalize them. Total URL cap: 8,192 chars.\n// Query keys must be literal api-version, sp, sv, sig, exactly once, in any order.\n// api-version=1 and sv=1.0 are literal; decoded sp is /triggers/manual/run.\n// Decoded sig is nonempty opaque base64/base64url syntax (up to two trailing =).\n// Percent escapes must be valid UTF-8. In particular, + is NOT form-decoded to space.\n// Preserve the COMPLETE raw signed URL, including port, escape case and query order.\nconst MAX_URL_LENGTH = 8192;\nconst HOST_SUFFIX = \".environment.api.powerplatform.com\";\nconst DNS_LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/u;\nconst WORKFLOW_PATH =\n /^\\/powerautomate\\/automations\\/direct\\/(?:cu\\/[A-Za-z0-9_-]{1,256}\\/)?workflows\\/[A-Za-z0-9_-]{1,256}\\/triggers\\/manual\\/paths\\/invoke$/u;\n\nfunction workflowUrl(value: unknown): string | undefined {\n if (typeof value !== \"string\" || value.length > MAX_URL_LENGTH || /[\\s\\\\\\p{Cc}]/u.test(value)) return undefined;\n const parts = /^https:\\/\\/([^/?#]+)(\\/[^?#]+)\\?([^#]+)$/u.exec(value);\n if (!parts) return undefined;\n const [, authority = \"\", path = \"\", query = \"\"] = parts;\n const hostname = authority.endsWith(\":443\") ? authority.slice(0, -4) : authority;\n if (\n hostname.length > 253 ||\n !hostname.endsWith(HOST_SUFFIX) ||\n hostname.length <= HOST_SUFFIX.length ||\n !hostname.split(\".\").every((label) => DNS_LABEL.test(label)) ||\n !WORKFLOW_PATH.test(path)\n )\n return undefined;\n const values = new Map<string, string>();\n try {\n for (const pair of query.split(\"&\")) {\n const separator = pair.indexOf(\"=\");\n if (separator < 0) return undefined;\n const key = pair.slice(0, separator);\n const raw = pair.slice(separator + 1);\n if (![\"api-version\", \"sp\", \"sv\", \"sig\"].includes(key) || values.has(key)) return undefined;\n const decoded = decodeURIComponent(raw);\n // Also reject encoded terminal whitespace: JavaScript's $ can precede a final newline.\n if (/[\\s\\\\\\p{Cc}]/u.test(decoded)) return undefined;\n if ((key === \"api-version\" && raw !== \"1\") || (key === \"sv\" && raw !== \"1.0\")) return undefined;\n values.set(key, decoded);\n }\n } catch {\n return undefined;\n }\n if (\n values.size !== 4 ||\n values.get(\"sp\") !== \"/triggers/manual/run\" ||\n !/^[A-Za-z0-9_+/-]+={0,2}$/u.test(values.get(\"sig\") ?? \"\")\n )\n return undefined;\n return value;\n}\n\nfunction card(text: string) {\n return {\n type: \"message\",\n attachments: [\n {\n contentType: \"application/vnd.microsoft.card.adaptive\",\n contentUrl: null,\n content: {\n $schema: \"http://adaptivecards.io/schemas/adaptive-card.json\",\n type: \"AdaptiveCard\",\n version: \"1.2\",\n // TextRun has no Markdown support. No actions, images or mention entities.\n // https://learn.microsoft.com/en-us/adaptive-cards/schema-explorer/text-run\n // Clients can still auto-link text; this does not promise link suppression.\n body: [{ type: \"RichTextBlock\", inlines: [{ type: \"TextRun\", text }] }],\n },\n },\n ],\n };\n}\n\n// A local encoded-JSON budget, NOT proof of Teams' downstream rendered-card size.\n// https://learn.microsoft.com/en-us/connectors/teams/#known-issues-and-limitations\n// The connector's approximate 28 KB limit includes rendered elements.\nconst MAX_PAYLOAD_BYTES = 24_000;\nconst TEXT_BUDGET = MAX_PAYLOAD_BYTES - Buffer.byteLength(JSON.stringify(card(\"\")), \"utf8\");\n\nfunction boundedText(title: string, body: string): string {\n const text = `${title}\\n${body}`.split(\"\\n\").map(sanitizeTerminalText).join(\"\\n\");\n const points: string[] = [];\n const costs: number[] = [];\n let bytes = 0;\n for (const point of text) {\n // Count JSON escapes as well as UTF-8, using only constant-sized serializations.\n const cost = Buffer.byteLength(JSON.stringify(point), \"utf8\") - 2;\n if (bytes + cost > TEXT_BUDGET) {\n while (bytes + 3 > TEXT_BUDGET) {\n bytes -= costs.pop() ?? 0;\n points.pop();\n }\n return `${points.join(\"\")}\u2026`;\n }\n bytes += cost;\n points.push(point);\n costs.push(cost);\n }\n return points.join(\"\");\n}\n\n/** One workflow request. Local acceptance is HTTP 202, never downstream-post proof. */\nexport function createTeamsProvider(fetcher: typeof fetch = fetch): NotificationProvider {\n return {\n id: \"teams\",\n label: \"Microsoft Teams\",\n validate(value) {\n if (!isObject(value) || value.provider !== \"teams\") return undefined;\n if (typeof value.label !== \"string\" || !value.label.trim() || value.label.length > 128) return undefined;\n const webhookUrl = workflowUrl(value.webhookUrl);\n return webhookUrl ? { provider: \"teams\", label: value.label, webhookUrl } : undefined;\n },\n async send(destination, notification, signal): Promise<DeliveryResult> {\n if (signal.aborted) return { state: \"cancelled\", code: \"cancelled\" };\n const valid = this.validate(destination);\n if (valid?.provider !== \"teams\") return { state: \"failed\", code: \"invalid-destination\" };\n const result = await postJson(\n valid.webhookUrl,\n card(boundedText(notification.title, notification.body)),\n signal,\n fetcher,\n );\n if (result.state !== \"response\") return result;\n // Explicit local status-only policy after the FULL bounded response read:\n // https://www.rfc-editor.org/rfc/rfc9110.html#section-15.3.3\n // 202 means accepted for processing, not completed. The Request documentation\n // above corroborates default 202 without a Response action, but does not define\n // Teams responses. A public workflow example also reports 202 despite a later\n // workflow failure (corroboration only, NOT a normative Teams response shape):\n // https://simonscholz.dev/tutorials/microsoft-teams-messages-webhook-workflow/\n // Ignore bounded empty/text/JSON bodies and undocumented fields.\n // Live Teams interoperability and downstream receipt remain unverified.\n return result.status === 202 ? { state: \"accepted\" } : { state: \"failed\", code: \"response\" };\n },\n };\n}\n", "import { type DeliveryResult, isObject, type Notification, type NotificationProvider } from \"../provider.js\";\nimport { clipText } from \"../text.js\";\n\nconst TIMEOUT_MS = 10_000;\nconst MAX_RESPONSE_BYTES = 65_536;\n\nfunction codePointBoundary(text: string, offset: number): boolean {\n const before = text.charCodeAt(offset - 1);\n const after = text.charCodeAt(offset);\n return !(before >= 0xd800 && before <= 0xdbff && after >= 0xdc00 && after <= 0xdfff);\n}\n\nfunction telegramMessage(notification: Notification) {\n const source = `${notification.title}\\n${notification.body}`;\n const text = clipText(source, 4096);\n // Telegram entities use UTF-16 units. Do not style the clipping ellipsis.\n // https://core.telegram.org/bots/api#messageentity\n const contentEnd = text.length - (text === source ? 0 : 1);\n const ranges = [\n { style: \"bold\" as const, offset: 0, length: notification.title.length },\n ...(notification.bodyEmphasis ?? []).flatMap((range) =>\n Number.isSafeInteger(range.offset) &&\n Number.isSafeInteger(range.length) &&\n range.offset >= 0 &&\n range.length > 0 &&\n range.offset + range.length <= notification.body.length\n ? [{ ...range, offset: notification.title.length + 1 + range.offset }]\n : [],\n ),\n ];\n const entities = ranges.flatMap(({ style, offset, length }) => {\n // Trim only the retained entity, not the text or later offsets.\n // https://core.telegram.org/api/entities#entity-length\n const retained = source.slice(offset, Math.min(offset + length, contentEnd)).trimEnd();\n const end = offset + retained.length;\n if (end <= offset || !codePointBoundary(source, offset) || !codePointBoundary(source, end)) return [];\n return [{ type: style === \"bold\" ? \"bold\" : \"code\", offset, length: end - offset }];\n });\n return { text, entities };\n}\n\n/** No user-configurable origin, redirects, paid broadcasts, parse mode, or retries. */\nexport function createTelegramProvider(fetcher: typeof fetch = fetch): NotificationProvider {\n return {\n id: \"telegram\",\n label: \"Telegram\",\n validate(value) {\n if (!isObject(value) || value.provider !== \"telegram\") return undefined;\n if (typeof value.label !== \"string\" || !value.label.trim() || value.label.length > 128) return undefined;\n if (typeof value.botToken !== \"string\" || !/^\\d{1,20}:[A-Za-z0-9_-]{20,200}$/.test(value.botToken))\n return undefined;\n if (typeof value.chatId !== \"string\" || !/^-?[1-9]\\d{0,30}$/.test(value.chatId)) return undefined;\n if (\n value.messageThreadId !== undefined &&\n (!Number.isSafeInteger(value.messageThreadId) || Number(value.messageThreadId) <= 0)\n )\n return undefined;\n return {\n provider: \"telegram\",\n label: value.label,\n botToken: value.botToken,\n chatId: value.chatId,\n messageThreadId: value.messageThreadId === undefined ? undefined : Number(value.messageThreadId),\n };\n },\n async send(destination, notification, signal): Promise<DeliveryResult> {\n if (signal.aborted) return { state: \"cancelled\", code: \"cancelled\" };\n if (destination.provider !== \"telegram\") return { state: \"failed\", code: \"invalid-destination\" };\n const timeout = new AbortController();\n const timer = setTimeout(() => timeout.abort(), TIMEOUT_MS);\n const combined = AbortSignal.any([signal, timeout.signal]);\n try {\n const response = await fetcher(`https://api.telegram.org/bot${destination.botToken}/sendMessage`, {\n method: \"POST\",\n redirect: \"error\",\n signal: combined,\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({\n chat_id: destination.chatId,\n ...(destination.messageThreadId === undefined ? {} : { message_thread_id: destination.messageThreadId }),\n ...telegramMessage(notification),\n link_preview_options: { is_disabled: true },\n }),\n });\n const reader = response.body?.getReader();\n if (!reader) return { state: \"failed\", code: \"response\" };\n let length = 0;\n const chunks: Uint8Array[] = [];\n try {\n while (true) {\n combined.throwIfAborted();\n const part = await reader.read();\n if (part.done) break;\n length += part.value.byteLength;\n if (length > MAX_RESPONSE_BYTES) return { state: \"failed\", code: \"response\" };\n chunks.push(part.value);\n }\n } finally {\n await reader.cancel().catch(() => {});\n reader.releaseLock();\n }\n combined.throwIfAborted();\n let body: unknown;\n try {\n body = JSON.parse(Buffer.concat(chunks).toString(\"utf8\"));\n } catch {\n return { state: \"failed\", code: \"response\" };\n }\n if (!isObject(body)) return { state: \"failed\", code: \"response\" };\n if (response.status === 429 || body.error_code === 429) {\n const retry = isObject(body.parameters) ? body.parameters.retry_after : undefined;\n return {\n state: \"failed\",\n code: \"rate-limit\",\n ...(Number.isSafeInteger(retry) && Number(retry) > 0 ? { retryAfterSeconds: Number(retry) } : {}),\n };\n }\n if (!response.ok) return { state: \"failed\", code: \"http\" };\n return body.ok === true && isObject(body.result) ? { state: \"accepted\" } : { state: \"failed\", code: \"api\" };\n } catch {\n if (signal.aborted) return { state: \"cancelled\", code: \"cancelled\" };\n return { state: \"failed\", code: timeout.signal.aborted ? \"timeout\" : \"network\" };\n } finally {\n clearTimeout(timer);\n }\n },\n };\n}\n", "import { type DeliveryResult, isObject, type NotificationProvider } from \"../provider.js\";\nimport { normalizeHttpUrl, postJson } from \"./http.js\";\n\n/** A fixed metadata contract; HTTP 2xx means endpoint acceptance, not downstream delivery. */\nexport function createWebhookProvider(fetcher: typeof fetch = fetch): NotificationProvider {\n return {\n id: \"webhook\",\n label: \"Generic webhook\",\n validate(value) {\n if (!isObject(value) || value.provider !== \"webhook\") return undefined;\n if (typeof value.label !== \"string\" || !value.label.trim() || value.label.length > 128) return undefined;\n if (!normalizeHttpUrl(value.webhookUrl)) return undefined;\n // This is an exact endpoint, not a server base: trailing slashes can select a different route.\n const webhookUrl = new URL(String(value.webhookUrl)).href;\n if (webhookUrl.length > 2048) return undefined;\n // Local printable-ASCII header-safety limit (no spaces), not an endpoint token-format claim.\n if (\n value.bearerToken !== undefined &&\n (typeof value.bearerToken !== \"string\" || !/^[\\x21-\\x7e]{1,512}$/.test(value.bearerToken))\n )\n return undefined;\n return {\n provider: \"webhook\",\n label: value.label,\n webhookUrl,\n bearerToken: value.bearerToken === undefined ? undefined : String(value.bearerToken),\n };\n },\n async send(destination, notification, signal): Promise<DeliveryResult> {\n if (signal.aborted) return { state: \"cancelled\", code: \"cancelled\" };\n const valid = this.validate(destination);\n if (valid?.provider !== \"webhook\") return { state: \"failed\", code: \"invalid-destination\" };\n const result = await postJson(\n valid.webhookUrl,\n {\n id: notification.id,\n title: notification.title,\n body: notification.body,\n settledAt: notification.settledAt,\n },\n signal,\n fetcher,\n valid.bearerToken === undefined ? {} : { Authorization: `Bearer ${valid.bearerToken}` },\n );\n return result.state === \"response\" ? { state: \"accepted\" } : result;\n },\n };\n}\n", "import type { Providers } from \"./provider.js\";\nimport { createBarkProvider } from \"./providers/bark.js\";\nimport { createDiscordProvider } from \"./providers/discord.js\";\nimport { createGotifyProvider } from \"./providers/gotify.js\";\nimport { createLineProvider } from \"./providers/line.js\";\nimport { createNtfyProvider } from \"./providers/ntfy.js\";\nimport { createPushoverProvider } from \"./providers/pushover.js\";\nimport { createSlackProvider } from \"./providers/slack.js\";\nimport { createTeamsProvider } from \"./providers/teams.js\";\nimport { createTelegramProvider } from \"./providers/telegram.js\";\nimport { createWebhookProvider } from \"./providers/webhook.js\";\n\nexport const providers: Providers = new Map([\n [\"telegram\", createTelegramProvider()],\n [\"gotify\", createGotifyProvider()],\n [\"slack\", createSlackProvider()],\n [\"ntfy\", createNtfyProvider()],\n [\"pushover\", createPushoverProvider()],\n [\"discord\", createDiscordProvider()],\n [\"bark\", createBarkProvider()],\n [\"webhook\", createWebhookProvider()],\n [\"line\", createLineProvider()],\n [\"teams\", createTeamsProvider()],\n]);\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;AAAA,SAAS,YAAY;AACrB;AAAA,EACE;AAAA,EAGA;AAAA,OACK;;;ACNP,SAAS,kBAAkB;;;ACA3B,SAAS,cAAc,gBAAgB;AAGhC,SAAS,eAAe,MAAuB;AACpD,MAAI,CAAC,QAAQ,aAAa,IAAI,EAAG,QAAO;AACxC,MAAI,KAAK,WAAW,WAAW,KAAK,KAAK,SAAS,WAAW,EAAG,QAAO;AACvE,MAAI,SAAS,SAAU,QAAO;AAC9B,MAAI,SAAS,SAAU,QAAO;AAE9B,QAAM,MAAM,+BAA+B,KAAK,IAAI;AACpD,MAAI,IAAK,QAAO,IAAI,CAAC,MAAM,QAAQ,OAAO,IAAI,CAAC,CAAC,IAAI,QAAQ;AAC5D,MAAI,KAAK,WAAW,KAAK,KAAK,WAAW,QAAQ,GAAG;AAClD,UAAM,SAAS,KAAK,WAAW,CAAC,IAAI;AACpC,YAAQ,SAAS,QAAQ,MAAM,SAAS,OAAO;AAAA,EACjD;AAEA,MAAI,SAAS,IAAI,MAAM,OAAW,QAAO;AAGzC,SAAO,CAAC,uBAAuB,KAAK,IAAI;AAC1C;;;ADKO,IAAM,cAAN,MAAkB;AAAA,EASvB,YACU,UACSA,YACA,KACA,WAAwC,sBACxC,YAAwB,MAAM;AAAA,EAAC,GAChD;AALQ;AACS,qBAAAA;AACA;AACA;AACA;AAAA,EAChB;AAAA,EALO;AAAA,EACS;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAbX,QAAQ;AAAA,EACR,WAAW;AAAA,EACX,WAAW;AAAA,EACX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_BYTES", "sanitizeTerminalText", "sanitizeTerminalText", "sanitizeTerminalText", "TIMEOUT_MS", "MAX_RESPONSE_BYTES", "sanitizeTerminalText", "sanitizeTerminalText", "sanitizeTerminalText", "TIMEOUT_MS", "MAX_RESPONSE_BYTES"]
|
|
7
|
+
}
|
package/docs/settings.md
CHANGED
|
@@ -14,7 +14,7 @@ Use `/notify` for setup or edit the canonical user JSON file. Settings load on s
|
|
|
14
14
|
|
|
15
15
|
Destination IDs contain 1–64 ASCII letters, digits, underscores, or hyphens, starting with a letter or digit; `constructor`, `prototype`, and `__proto__` are reserved. The menu creates IDs automatically.
|
|
16
16
|
|
|
17
|
-
Telegram setup requires a bot token and chat ID; Gotify setup requires an application token and server URL; Slack setup requires a complete Incoming Webhook URL. The
|
|
17
|
+
Telegram setup requires a bot token and chat ID; Gotify setup requires an application token and server URL; Slack setup requires a complete Incoming Webhook URL. The other providers use the [fields below](#new-provider-fields). Add destinations through the provider-choice screen in `/notify`. The menu generates a label and opens a review for edits before saving. Editing an existing destination opens the same review with its current values. Destination changes take effect only after confirmation. For a new destination, Save and use adds it to User `targetIds` in the same atomic save; Save only stores it without selecting it. Editing an existing destination preserves its selection state. Explicit Project selections and saved `enabled: false` values are unchanged. Automatic notifications default to On; Off pauses automatic delivery but still allows manual tests. No delivery occurs without a selected destination.
|
|
18
18
|
|
|
19
19
|
Each Telegram destination has `provider: "telegram"`, a nonempty `label` of at most 128 characters, `botToken`, a numeric string `chatId`, and optional positive safe-integer `messageThreadId`. A group or supergroup ID can be negative. Store IDs as strings, not JSON numbers. Forum topic IDs use Telegram's `message_thread_id` field. Other Telegram chat products with additional required fields are not supported.
|
|
20
20
|
|
|
@@ -37,7 +37,7 @@ Each Gotify destination has `provider: "gotify"`, a nonempty `label` of at most
|
|
|
37
37
|
|
|
38
38
|
Each Slack destination has `provider: "slack"`, a nonempty `label` of at most 128 characters, and `webhookUrl`. The complete URL is a credential and belongs only in the canonical User file. The channel comes from the webhook installation, not the label or a settings field. URLs must be at most 2048 characters and match `https://hooks.slack.com/services/T[A-Z0-9]+/B[A-Z0-9]+/[A-Za-z0-9]+` exactly: a `T` workspace segment, a `B` installation segment, and an alphanumeric secret. Ports, URL credentials, query strings, fragments, redirects, alternate hosts, whitespace, control characters, backslashes, and encoded or normalized URL alternatives are rejected. GovSlack is not supported.
|
|
39
39
|
|
|
40
|
-
A User file can select all
|
|
40
|
+
A User file can select all ten providers together. For example, with existing `personal` Telegram and `gotify` destinations, add a Slack destination and select their IDs:
|
|
41
41
|
|
|
42
42
|
```json
|
|
43
43
|
{
|
|
@@ -69,6 +69,8 @@ All destinations require `provider` and a nonempty `label` of at most 128 charac
|
|
|
69
69
|
| `discord` | `webhookUrl` | None |
|
|
70
70
|
| `bark` | `serverUrl`, `deviceKey` | None |
|
|
71
71
|
| `webhook` | `webhookUrl` | `bearerToken` |
|
|
72
|
+
| `line` | `channelAccessToken`, `recipientId` | None |
|
|
73
|
+
| `teams` | `webhookUrl` | None |
|
|
72
74
|
|
|
73
75
|
For ntfy and Bark, enter the server base URL including any reverse-proxy base path. Do not append the topic or `/push`. Generic `webhookUrl` is the complete receiving endpoint. These configurable URLs must be absolute HTTP(S) URLs, at most 2048 characters both before and after normalization. URL user information, whitespace, control characters, encoded controls, backslashes (including encoded backslashes), malformed percent escapes, query strings, and fragments are rejected. Bark server bases remove trailing slashes before appending `/push`. ntfy publish URLs and Generic webhook endpoints preserve trailing slashes because they can select a different route. Literal or encoded dot segments and noncanonical numeric IPv4 aliases are rejected instead of silently selecting a different path or host. Prefer HTTPS; HTTP does not encrypt credentials or metadata. Explicit local/private addresses are allowed and can reach the Pi host's network. Use only trusted endpoints.
|
|
74
76
|
|
|
@@ -122,6 +124,74 @@ Local title and body caps are 256 and 2048 UTF-8 bytes. The encoded `{title,body
|
|
|
122
124
|
|
|
123
125
|
`settledAt` is Unix epoch milliseconds, not seconds. No internal emphasis, destination credentials, or configurable fields are added. Any HTTP 2xx response counts as endpoint acceptance, including empty or non-JSON responses, after the bounded response read completes. This is not proof of downstream delivery. An oversized or stalled 2xx response body can still fail with `response` or `timeout`.
|
|
124
126
|
|
|
127
|
+
### LINE
|
|
128
|
+
|
|
129
|
+
Use `provider: "line"`, a `channelAccessToken`, and a `recipientId`. LINE Notify tokens and public LINE IDs are not accepted. The token must contain 1–8192 characters in the Bearer token alphabet (`A–Z`, `a–z`, digits, `-._~+/`, with optional trailing `=`), without whitespace. The 8192-character cap is a local header safety bound, not a LINE service limit. A user ID must match `U[0-9a-f]{32}`. Group and room IDs must start with `C` or `R`; the provider accepts an opaque suffix of 1–128 printable ASCII characters without spaces. Both the ASCII restriction and suffix cap are local safety policies, not a claimed LINE group/room ID grammar. Use the complete ID from LINE, not a shortened example. The token and raw recipient ID stay hidden in all menus, previews, Status, and errors.
|
|
130
|
+
|
|
131
|
+
The transport posts one `{ "type": "text", "text": "..." }` message to `https://api.line.me/v2/bot/message/push`, with the recipient in `to` and the token only in the Authorization header. Title and metadata body are combined, terminal controls removed, and text clipped to 5,000 UTF-16 code units, including an ellipsis when clipped, without splitting Unicode code points. No mention objects, formatting, silent-delivery fields, or emphasis offsets are sent. Client automatic links are not suppressed.
|
|
132
|
+
|
|
133
|
+
Only HTTP 200 with a legacy empty JSON object or a valid current `sentMessages` response counts as accepted. The current response must contain 1–5 message objects with a nonempty string or nonnegative integer `id`; `quoteToken` is an optional string. Empty/non-JSON, unrelated, malformed, or oversized success bodies fail safely. HTTP 429 can indicate a rate limit or an exhausted account allowance; retry-after is diagnostic only and no retry occurs.
|
|
134
|
+
|
|
135
|
+
For example, add this fragment to the existing User document and include `line-personal` in `targetIds` if automatic notifications should use it. Replace both private placeholders outside Pi chat; do not replace unrelated destinations or settings.
|
|
136
|
+
|
|
137
|
+
```json
|
|
138
|
+
{
|
|
139
|
+
"destinations": {
|
|
140
|
+
"line-personal": {
|
|
141
|
+
"provider": "line",
|
|
142
|
+
"label": "Personal LINE",
|
|
143
|
+
"channelAccessToken": "<channel-access-token>",
|
|
144
|
+
"recipientId": "<complete-user-group-or-room-id>"
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
Recipient eligibility and message allowances apply. A user generally must be a friend of the Official Account or have messaged it in a one-to-one chat within the past seven days; group/room delivery requires the account to participate. HTTP 200 does not prove receipt: blocked or deleted accounts and ineligible users can still produce acceptance without delivery. Monthly allowances, pricing, and group message counting depend on the account's region and plan. Check the account before enabling automatic notifications. The extension does not obtain recipient IDs, run an inbound webhook, inspect quota, or manage account access.
|
|
151
|
+
|
|
152
|
+
### Microsoft Teams
|
|
153
|
+
|
|
154
|
+
Use `provider: "teams"`, a `label`, and `webhookUrl`. This supports the commercial Teams Workflows trigger **When a Teams webhook request is received**, with **Anyone** authentication only. No Authorization header is sent. The complete signed URL, including its host, path, and query, is a credential. It is never shown in menus, reviews, test previews, Status, or errors. Keep it only in User settings; never paste it into Pi chat or Project settings.
|
|
155
|
+
|
|
156
|
+
**The current Teams integration has not been verified live.** The following is an explicit supported client policy awaiting live interoperability verification, not a complete Microsoft endpoint grammar or a resolved global response contract. Microsoft documents trigger authentication, payload examples, and URL migration, but observed URL examples do not define every possible service URL.
|
|
157
|
+
|
|
158
|
+
The local validator accepts only:
|
|
159
|
+
|
|
160
|
+
- A URL of at most 8192 characters, with the exact lowercase `https://` scheme and one or more lowercase DNS labels before `.environment.api.powerplatform.com`. Each label contains 1–63 lowercase ASCII letters, digits, or hyphens and starts and ends with a letter or digit; the complete hostname is at most 253 characters. Only an omitted port or explicit `:443` is allowed.
|
|
161
|
+
- One of these literal paths, without a trailing slash or encoded/normalized alternatives:
|
|
162
|
+
|
|
163
|
+
```text
|
|
164
|
+
/powerautomate/automations/direct/workflows/<opaqueID>/triggers/manual/paths/invoke
|
|
165
|
+
/powerautomate/automations/direct/cu/<opaqueRoute>/workflows/<opaqueID>/triggers/manual/paths/invoke
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
Each `opaqueID` and `opaqueRoute` must match `[A-Za-z0-9_-]{1,256}`. This is a local safety policy, not a universal Microsoft ID or routing grammar.
|
|
169
|
+
- Exactly four query keys, each present once: literal `api-version=1`, `sp` decoded to `/triggers/manual/run`, literal `sv=1.0`, and `sig` with a nonempty decoded value in the base64/base64url alphabet (`A–Z`, `a–z`, digits, `+`, `/`, `_`, `-`) and at most two trailing `=` padding characters. Query order may vary. Values use percent decoding, not form decoding: `+` remains `+`, not a space. Encoded key names, duplicate keys, unknown keys, and malformed percent escapes or UTF-8 are rejected. The original signed URL is preserved, including escape case, query order, and explicit `:443`; it is not rebuilt from decoded values.
|
|
170
|
+
|
|
171
|
+
Whitespace, controls, backslashes, URL user information, fragments, other ports, malformed encoding, and alternatives that require case or path normalization are rejected. Legacy Office connectors, obsolete `logic.azure.com` endpoints, government clouds, and tenant-authenticated triggers are unsupported. If a current generated URL falls outside this policy, do not edit or reconstruct its signature to make it fit.
|
|
172
|
+
|
|
173
|
+
The request contains a fixed Adaptive Card 1.2 message attachment. `RichTextBlock`/`TextRun` elements carry sanitized title and metadata as literal text; `TextRun` does not support Markdown. No actions, images, user templates, or routing overrides are included. Terminal controls are removed. Provider-neutral metadata replaces `@` with `@`; no mention entities are sent. Client automatic links are not guaranteed to be suppressed. The workflow selects the destination chat/channel, whose members can read the metadata.
|
|
174
|
+
|
|
175
|
+
The entire encoded JSON request is capped locally at 24,000 UTF-8 bytes, including its envelope and JSON escaping. Clipping preserves complete Unicode code points and includes an ellipsis within the budget. This conservative local bound is not proof that every downstream Teams action accepts the rendered card: Microsoft's approximate 28 KB action limit includes rendered elements.
|
|
176
|
+
|
|
177
|
+
Delivery reuses the bounded JSON transport unchanged: one attempt, no retry, redirects rejected, a 10-second total request/response deadline, and a 65,536-byte response-read cap. **Only HTTP 202** counts as trigger acceptance after that read completes. A bounded empty, text, or JSON body is allowed; no response-body meaning is inferred. Other 2xx statuses are not accepted. Oversized or stalled 202 bodies can still fail with `response` or `timeout`. HTTP 429 reports a safe `rate-limit` and an available positive integer `Retry-After`, without retrying. Under [HTTP 202 semantics](https://www.rfc-editor.org/rfc/rfc9110.html#name-202-accepted), acceptance does not establish completed processing. It proves neither that a workflow posted to Teams nor that a recipient read the message; check run history and the receiving chat/channel separately.
|
|
178
|
+
|
|
179
|
+
Add this fragment to the existing User document and include `teams-workflow` in `targetIds` to select it. Replace the placeholder with the exact current generated URL outside Pi chat; preserve unrelated destinations and settings.
|
|
180
|
+
|
|
181
|
+
```json
|
|
182
|
+
{
|
|
183
|
+
"destinations": {
|
|
184
|
+
"teams-workflow": {
|
|
185
|
+
"provider": "teams",
|
|
186
|
+
"label": "Build Teams workflow",
|
|
187
|
+
"webhookUrl": "<current-generated-workflow-url>"
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
No extension OAuth flow, inbound server, SDK, or channel override is needed or supported. See [Teams setup and revocation](#teams-setup-and-revocation) for workflow ownership, permissions, and operational checks.
|
|
194
|
+
|
|
125
195
|
### Mixed User settings example
|
|
126
196
|
|
|
127
197
|
Replace placeholders with real values. `appToken` and `userKey` must meet the Pushover length rule; the Discord URL must be copied from Discord. This fragment does not replace existing Telegram, Gotify, Slack, or unknown settings. Omit optional tokens when using anonymous delivery.
|
|
@@ -167,7 +237,7 @@ Replace placeholders with real values. `appToken` and `userKey` must meet the Pu
|
|
|
167
237
|
|
|
168
238
|
## Provider setup and revocation
|
|
169
239
|
|
|
170
|
-
Use `/notify` to add a destination, complete its review, and choose Save only or Save and use. Labels are generated automatically and can be changed. Secret inputs are masked; complete Discord and Generic webhook URLs remain hidden in lists, reviews, tests, Status, and errors. Optional ntfy tokens and priority, and Generic tokens, can be cleared in review. Send test previews the metadata and requires confirmation before an external request. Unsaved cancellation does not save a draft; cancelling delivery cannot recall an accepted message.
|
|
240
|
+
Use `/notify` to add a destination, complete its review, and choose Save only or Save and use. Labels are generated automatically and can be changed. Secret inputs are masked; complete Discord, Teams, and Generic webhook URLs remain hidden in lists, reviews, tests, Status, and errors. Optional ntfy tokens and priority, and Generic tokens, can be cleared in review. Send test previews the metadata and requires confirmation before an external request. Unsaved cancellation does not save a draft; cancelling delivery cannot recall an accepted message.
|
|
171
241
|
|
|
172
242
|
### Telegram and Gotify
|
|
173
243
|
|
|
@@ -196,6 +266,25 @@ To change channels, authorize a webhook for the new channel and replace the save
|
|
|
196
266
|
|
|
197
267
|
Treat an exposed URL as a compromised credential. Revoke or remove that webhook through Slack app management before replacing it in User settings; ask the workspace administrator if you cannot manage the installation. Slack can also revoke leaked webhooks automatically. Merely editing or removing a destination does not revoke the old webhook. Confirm a replacement with Send test. A disabled webhook, archived channel, or workspace restriction can prevent delivery; repair the installation instead of expecting a retry. Cancelling a request cannot recall a message Slack has already accepted.
|
|
198
268
|
|
|
269
|
+
## LINE setup and revocation
|
|
270
|
+
|
|
271
|
+
1. Create a [LINE Official Account](https://developers.line.biz/en/docs/messaging-api/getting-started/) and enable Messaging API from its administration interface. Open the linked channel in LINE Developers Console and obtain a channel access token. Account policy, plan, and region can restrict availability or message allowance.
|
|
272
|
+
2. For personal delivery, add the account as a friend and use your developer-console user ID for the same provider. For groups or rooms, permit the account to join and obtain the full `groupId` or `roomId` from an authorized webhook event through an existing receiver. See [user ID discovery](https://developers.line.biz/en/docs/messaging-api/getting-user-ids/) and [group chats](https://developers.line.biz/en/docs/messaging-api/group-chats/). The extension does not install a receiver or discover IDs. A display name or public LINE ID is not the recipient ID.
|
|
273
|
+
3. Run `/notify`, add a LINE destination, and enter the token and recipient ID in separate masked inputs. Review the generated label. Replace either private value from review; replacement inputs start empty and never display the saved value. Cancellation leaves the draft unsaved.
|
|
274
|
+
4. Choose Save only or Save and use, then Send test. Check the metadata preview before confirming the external request, and check the receiving LINE chat after acceptance. Confirm account allowance and recipient eligibility before expecting automatic delivery.
|
|
275
|
+
|
|
276
|
+
For exposed credentials, follow the [channel token rules](https://developers.line.biz/en/docs/basics/channel-access-token/) for that token type: revoke a revocable token and replace it, or reissue a long-lived token and end any old-token grace period. Stateless tokens cannot be revoked and expire after their short validity period. Do not rely on removing a destination to revoke a token. Recheck receipt after replacement; cancellation cannot recall an accepted push. Recipient IDs are private identifiers, not authentication credentials; do not publish them with example settings.
|
|
277
|
+
|
|
278
|
+
## Teams setup and revocation
|
|
279
|
+
|
|
280
|
+
1. Open Workflows in Teams or Power Automate and create a flow with **When a Teams webhook request is received**. Choose **Anyone** authentication, not a tenant/user-authenticated mode. Configure the downstream Teams action and its target chat/channel for the fixed Adaptive Card. See [Workflows webhook setup](https://learn.microsoft.com/en-us/microsoftteams/platform/webhooks-and-connectors/how-to/add-incoming-webhook); use its Workflows instructions, not legacy Office connector instructions.
|
|
281
|
+
2. Confirm Workflows is available under the account, tenant policy, and applicable licensing. The workflow owner's connection and chat/channel posting privileges must permit the downstream action. Add appropriate co-owners and maintain its connections so an owner leaving does not leave an unmanaged flow. The extension cannot grant channel access, repair credentials, or change tenant policy.
|
|
282
|
+
3. Save the workflow and copy its current generated URL from the trigger. Use the [trigger URL migration guidance](https://learn.microsoft.com/en-us/power-automate/triggers-troubleshoot) if a URL changed; do not use an obsolete `logic.azure.com` URL or convert it by hand. Compare it with the [supported local URL policy](#microsoft-teams).
|
|
283
|
+
4. Run `/notify`, add a Microsoft Teams destination, and paste the complete URL into the masked input. Review the label and choose Save only or Save and use. Replacing the URL uses an empty masked input; the stored value is not displayed. Unsaved cancellation keeps the saved destination unchanged.
|
|
284
|
+
5. Use Send test, review the metadata, and confirm one external request. HTTP 202 reports trigger acceptance only. Check workflow run history, downstream action success, and the target chat/channel for the card. A local accepted result does not verify routing, account permissions, or receipt. The current integration remains unverified live; this is a user verification procedure, not a completed smoke result.
|
|
285
|
+
|
|
286
|
+
Anyone authentication makes URL secrecy essential. If it is exposed, disable the owning workflow to stop use, then revoke/replace the endpoint through the workflow's available controls or delete and recreate the workflow. Ensure the old endpoint is no longer usable before relying on a replacement; ask a workflow owner or administrator if needed. Copy the new generated URL into User settings and confirm its downstream result with Send test. Removing a destination or changing its label does not revoke the old URL. A cancelled HTTP request cannot recall an accepted trigger or Teams post.
|
|
287
|
+
|
|
199
288
|
## Persistence and recovery
|
|
200
289
|
|
|
201
290
|
Settings operations are ordered within the process, including across store instances for the same user path. Reads wait for pending writes. This is not a cross-process lock: simultaneous menu edits in different Pi processes can conflict.
|
|
@@ -204,6 +293,14 @@ Writes read the latest valid document, preserve unrelated fields and destination
|
|
|
204
293
|
|
|
205
294
|
If a file is malformed, repair it manually before saving. Disable notifications in every effective scope to stop new attempts and cancel pending reminders. Unloading the extension aborts owned delivery work, but cannot recall accepted messages. Revoke exposed tokens or Slack webhooks before replacing them in User settings.
|
|
206
295
|
|
|
296
|
+
### Reverting to a version without Teams
|
|
297
|
+
|
|
298
|
+
While the Teams-capable version is installed, remove Teams IDs from explicit Project selections in every affected project, then remove them from User selections and delete every saved Teams destination, including unselected ones. Confirm all remaining destinations and effective selections are supported before installing the older version and reloading. Unsupported saved destinations disable older routing even when unselected. Existing providers need no migration. Revoke exposed or unused workflow URLs separately through the owning workflow; removing settings does not revoke them.
|
|
299
|
+
|
|
300
|
+
### Reverting to a version without LINE
|
|
301
|
+
|
|
302
|
+
While this version is installed, remove LINE destination IDs from explicit Project selections in every affected project, then remove them from User selections and delete all saved LINE destinations, including unselected ones. Preserve the other supported providers and unrelated fields. Confirm the older version supports every saved destination and selected ID before installing it and reloading. Removing selections alone is insufficient: an unsupported unselected destination also disables older routing. Revoke unused or exposed channel tokens separately through LINE.
|
|
303
|
+
|
|
207
304
|
### Reverting to a version without the new providers
|
|
208
305
|
|
|
209
306
|
1. While the new build is still installed, remove the IDs of destinations whose provider is `ntfy`, `pushover`, `discord`, `bark`, or `webhook` from explicit Project selections in every affected project. Clear those overrides or select destinations the older version supports; Project arrays replace User selections.
|
|
@@ -238,9 +335,9 @@ The coordinator observes `before_agent_start`, with `agent_start` as a fallback,
|
|
|
238
335
|
|
|
239
336
|
Metadata is collected at settlement through bounded Git subprocesses. Missing Git information is omitted. Pending metadata work is cancelled with its reminder. Once a delivery attempt starts, new user work does not cancel it; session replacement, reload, shutdown, or explicit test cancellation does. Late results cannot replace newer per-destination status. Test delivery bypasses automatic enablement and inactivity, requires explicit confirmation, and never changes automatic arming or history.
|
|
240
337
|
|
|
241
|
-
The provider contract validates destinations and sends a provider-neutral notification with a cancellation signal. Providers do not read sessions, change settings, schedule timers, or decide notification policy. The built-in provider map contains Telegram, Gotify, Slack, ntfy, Pushover, Discord, Bark, and
|
|
338
|
+
The provider contract validates destinations and sends a provider-neutral notification with a cancellation signal. Providers do not read sessions, change settings, schedule timers, or decide notification policy. The built-in provider map contains Telegram, Gotify, Slack, ntfy, Pushover, Discord, Bark, Generic webhook, LINE, and Microsoft Teams. Transport results distinguish accepted, failed with a safe code, and cancelled; retry-after is diagnostic, not an automatic retry instruction.
|
|
242
339
|
|
|
243
|
-
All transports reject redirects, use a 10-second deadline covering the request and response read, make one attempt, and cap success response reads at 65,536 bytes. Errors expose only fixed codes, never tokens, request URLs, response bodies, or raw transport exceptions.
|
|
340
|
+
All transports reject redirects, use a 10-second deadline covering the request and response read, make one attempt, and cap success response reads at 65,536 bytes. Errors expose only fixed codes, never tokens, request URLs, response bodies, or raw transport exceptions. ntfy, Pushover, Discord, Bark, Generic webhook, LINE, and Teams report HTTP 429 as `rate-limit`, with a positive integer `Retry-After` in seconds when available; fractional Discord retry values are not displayed. Retry-after is diagnostic only. Service acceptance does not prove device receipt, downstream delivery, or reading. Text clipping preserves Unicode code points; the [provider limits](#new-provider-fields) specify each byte or UTF-16 budget.
|
|
244
341
|
|
|
245
342
|
Telegram requests use its fixed HTTPS origin and do not enable paid broadcasts. Text is clipped to at most 4096 UTF-16 code units without splitting a Unicode code point. Telegram's JSON `ok` field and HTTP status are both checked.
|
|
246
343
|
|
|
@@ -269,6 +366,13 @@ Slack combines the title and body into one section block with a `plain_text` tex
|
|
|
269
366
|
- [Discord Execute Webhook](https://discord.com/developers/docs/resources/webhook#execute-webhook): endpoint, `wait=true`, content limits, Message response, and flags; [allowed mentions](https://discord.com/developers/docs/resources/message#allowed-mentions-object): explicit empty mention parsing.
|
|
270
367
|
- [Bark tutorial](https://bark.day.app/#/tutorial) and official server source at commit `640deaa151ddf79193202927b35ca2f14f65ee1d`: [JSON API](https://github.com/Finb/bark-server/blob/640deaa151ddf79193202927b35ca2f14f65ee1d/docs/API_V2.md), [push handler](https://github.com/Finb/bark-server/blob/640deaa151ddf79193202927b35ca2f14f65ee1d/route_push.go), [router](https://github.com/Finb/bark-server/blob/640deaa151ddf79193202927b35ca2f14f65ee1d/router.go), and [Basic authentication](https://github.com/Finb/bark-server/blob/640deaa151ddf79193202927b35ca2f14f65ee1d/route_auth.go). These establish `/push`, `device_key`, numeric acceptance, body logging, and the unsupported native Basic-auth mode.
|
|
271
368
|
- [Apple APNs payloads](https://developer.apple.com/documentation/usernotifications/generating-a-remote-notification): the 4096-byte regular notification payload limit; Bark's smaller local text budgets leave envelope space.
|
|
369
|
+
- [LINE push messages](https://developers.line.biz/en/reference/messaging-api/#send-push-message) and [text character count](https://developers.line.biz/en/docs/messaging-api/text-character-count/): fixed endpoint, eligibility, UTF-16 budget, and response conditions.
|
|
370
|
+
- [LINE OpenAPI](https://github.com/line/line-openapi/blob/main/messaging-api.yml) and [official SDK push tests](https://github.com/line/line-bot-sdk-nodejs/blob/master/test/line-bot-client.spec.ts): current `sentMessages` and legacy empty-object acceptance.
|
|
371
|
+
- [LINE channel access tokens](https://developers.line.biz/en/docs/basics/channel-access-token/), [user IDs](https://developers.line.biz/en/docs/messaging-api/getting-user-ids/), [group chats](https://developers.line.biz/en/docs/messaging-api/group-chats/), and [pricing](https://developers.line.biz/en/docs/messaging-api/pricing/): setup, revocation, recipient acquisition, and account-dependent message allowance.
|
|
372
|
+
- [Teams connector: Microsoft Teams Webhook](https://learn.microsoft.com/en-us/connectors/teams/#microsoft-teams-webhook): trigger authentication and card envelope; Anyone requests omit Authorization. This does not establish a complete URL or HTTP response contract.
|
|
373
|
+
- [Teams Workflows webhook setup](https://learn.microsoft.com/en-us/microsoftteams/platform/webhooks-and-connectors/how-to/add-incoming-webhook) and [trigger troubleshooting/URL migration](https://learn.microsoft.com/en-us/power-automate/triggers-troubleshoot): workflow creation, ownership, and current generated URLs. Published examples inform the supported client policy; they are not a normative universal URL grammar.
|
|
374
|
+
- [Adaptive Cards TextRun schema](https://learn.microsoft.com/en-us/adaptive-cards/schema-explorer/text-run) and [RichTextBlock schema](https://learn.microsoft.com/en-us/adaptive-cards/schema-explorer/rich-text-block): literal text without Markdown in TextRun.
|
|
375
|
+
- [RFC 9110: 202 Accepted](https://www.rfc-editor.org/rfc/rfc9110.html#name-202-accepted): acceptance is not completed processing; it does not establish which status every Teams workflow returns.
|
|
272
376
|
- [Pi extension lifecycle](https://github.com/earendil-works/pi/blob/main/packages/coding-agent/docs/extensions.md#agent_start--agent_end--agent_before_settle--agent_settled).
|
|
273
377
|
|
|
274
378
|
Input classification follows the installed Pi `ProcessTerminal` and `StdinBuffer` sequence splitting, Pi's `parseKey`/`isKeyRelease`, and `TuiAltScreen` SGR mouse handling. Pure classifier tests cover keyboard, Unicode, paste, focus, press/release, motion, wheel, legacy mouse, CSI/OSC/DCS/APC replies, and unknown input. These tests do not prove that an event reaches the extension. Installed-runtime tests also pass events through real regular/fullscreen Pi renderers and check listener order, viewport keys, and focused-overlay branches. Physical terminal and multiplexer behavior remains unverified.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@narumitw/pi-notify",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.1",
|
|
4
4
|
"description": "Multi-provider notifications when Pi settles, with optional inactivity reminders.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -14,22 +14,31 @@
|
|
|
14
14
|
"pushover",
|
|
15
15
|
"discord",
|
|
16
16
|
"bark",
|
|
17
|
+
"line",
|
|
18
|
+
"line-messaging-api",
|
|
19
|
+
"microsoft-teams",
|
|
20
|
+
"teams-workflows",
|
|
21
|
+
"power-automate",
|
|
17
22
|
"webhook",
|
|
18
23
|
"incoming-webhook",
|
|
19
24
|
"notifications"
|
|
20
25
|
],
|
|
21
26
|
"files": [
|
|
22
27
|
"src",
|
|
28
|
+
"dist",
|
|
23
29
|
"README.md",
|
|
24
30
|
"LICENSE",
|
|
25
31
|
"docs"
|
|
26
32
|
],
|
|
27
33
|
"pi": {
|
|
28
34
|
"extensions": [
|
|
29
|
-
"./
|
|
35
|
+
"./dist/index.ts"
|
|
30
36
|
]
|
|
31
37
|
},
|
|
32
38
|
"scripts": {
|
|
39
|
+
"build": "node scripts/build-runtime.mjs",
|
|
40
|
+
"benchmark:first-use": "node scripts/benchmark-first-use.mjs",
|
|
41
|
+
"prepack": "npm run build",
|
|
33
42
|
"typecheck": "tsc --noEmit"
|
|
34
43
|
},
|
|
35
44
|
"dependencies": {
|
package/src/destination-ui.ts
CHANGED
|
@@ -10,6 +10,8 @@ export const providerLabels: Record<Destination["provider"], string> = {
|
|
|
10
10
|
discord: "Discord",
|
|
11
11
|
bark: "Bark",
|
|
12
12
|
webhook: "Generic webhook",
|
|
13
|
+
line: "LINE",
|
|
14
|
+
teams: "Microsoft Teams",
|
|
13
15
|
};
|
|
14
16
|
export const providerLabel = (destination: Destination) => providerLabels[destination.provider];
|
|
15
17
|
export const credentialLabels: Record<Destination["provider"], string> = {
|
|
@@ -21,6 +23,8 @@ export const credentialLabels: Record<Destination["provider"], string> = {
|
|
|
21
23
|
discord: "webhook URL",
|
|
22
24
|
bark: "device key",
|
|
23
25
|
webhook: "webhook URL",
|
|
26
|
+
line: "channel access token",
|
|
27
|
+
teams: "webhook URL",
|
|
24
28
|
};
|
|
25
29
|
export function displayServerUrl(raw: string): string {
|
|
26
30
|
try {
|
|
@@ -39,6 +43,10 @@ export function destinationDescription(destination: Destination): string {
|
|
|
39
43
|
return `Gotify · ${displayServerUrl(destination.serverUrl)} · token configured`;
|
|
40
44
|
case "slack":
|
|
41
45
|
return "Slack · webhook configured";
|
|
46
|
+
case "line":
|
|
47
|
+
return "LINE · channel access token and recipient configured";
|
|
48
|
+
case "teams":
|
|
49
|
+
return "Microsoft Teams · workflow webhook configured";
|
|
42
50
|
case "pushover":
|
|
43
51
|
return "Pushover · application token and user key configured";
|
|
44
52
|
case "discord":
|
|
@@ -70,6 +78,20 @@ export function destinationLines(destination: Destination): string[] {
|
|
|
70
78
|
];
|
|
71
79
|
case "slack":
|
|
72
80
|
return [label, "Channel: fixed by webhook installation", "Webhook URL: configured (hidden)"];
|
|
81
|
+
case "line":
|
|
82
|
+
return [
|
|
83
|
+
label,
|
|
84
|
+
"Channel access token: configured (hidden)",
|
|
85
|
+
"Recipient ID: configured (hidden)",
|
|
86
|
+
"Messaging API only, not LINE Notify. Account quotas and recipient eligibility apply.",
|
|
87
|
+
];
|
|
88
|
+
case "teams":
|
|
89
|
+
return [
|
|
90
|
+
label,
|
|
91
|
+
"Webhook URL: configured (hidden)",
|
|
92
|
+
"Target: fixed by the owning workflow",
|
|
93
|
+
"Anyone authentication only. HTTP acceptance does not confirm a Teams post.",
|
|
94
|
+
];
|
|
73
95
|
case "pushover":
|
|
74
96
|
return [
|
|
75
97
|
label,
|