@narumitw/pi-notify 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -4,12 +4,12 @@
4
4
  [![Pi extension](https://img.shields.io/badge/Pi-extension-blue)](https://pi.dev)
5
5
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](./LICENSE)
6
6
 
7
- Send reminders through Telegram, Gotify, Slack, ntfy, Pushover, Discord, Bark, or a Generic webhook when Pi stops automatic work.
7
+ Send reminders through Telegram, Gotify, Slack, ntfy, Pushover, Discord, Bark, LINE, Microsoft Teams Workflows, or a Generic webhook when Pi stops automatic work.
8
8
 
9
9
  ## ✨ Features
10
10
 
11
- - Notify Telegram chats and forum topics, Gotify applications, Slack or Discord channels, ntfy topics, Pushover users, Bark devices, or your own webhook.
12
- - Select multiple destinations across all eight providers.
11
+ - Notify Telegram chats and forum topics, Gotify applications, Slack or Discord channels, ntfy topics, Pushover users, Bark devices, LINE recipients, Teams Workflows, or your own webhook.
12
+ - Select multiple destinations across all ten providers.
13
13
  - Identify the computer, session, repository, branch, and worktree without forwarding conversations.
14
14
  - Choose immediate notifications or reminders after terminal inactivity.
15
15
  - Configure and test destinations through a masked, menu-first setup flow.
@@ -18,7 +18,7 @@ Telegram uses bold titles and repository names, with inline monospace for branch
18
18
 
19
19
  ## 📦 Install
20
20
 
21
- Extensions run with Pi's permissions. Enable this extension only if the notification metadata may leave your computer. Notification tokens, device keys, and complete Slack, Discord, and Generic webhook URLs are secrets stored in a private User settings file, not Project settings.
21
+ Extensions run with Pi's permissions. Enable this extension only if the notification metadata may leave your computer. Notification tokens, device keys, LINE recipient IDs, and complete Slack, Discord, Teams, and Generic webhook URLs are private values stored in a private User settings file, not Project settings.
22
22
 
23
23
  From a local checkout, run these commands from the repository root:
24
24
 
@@ -47,6 +47,10 @@ Automatic notifications are on by default, so the next eligible settled work per
47
47
 
48
48
  For Slack, create a [Slack app](https://api.slack.com/apps), enable Incoming Webhooks, and choose Add New Webhook to Workspace. Authorize the channel that must receive notifications and copy its webhook URL. Enter it only in the masked setup input or User settings, never in Pi chat. The installation fixes the channel; a destination cannot override it. See [Slack setup and revocation](./docs/settings.md#slack-setup-and-revocation).
49
49
 
50
+ For Microsoft Teams, create a Workflows flow with **When a Teams webhook request is received**, select **Anyone** authentication, and configure its downstream chat/channel action. Paste the current generated URL only into the masked input or User settings. The integration has not been verified live; HTTP 202 means trigger acceptance, not a successful Teams post. Check workflow run history and the receiving chat/channel after a confirmed test. See [Teams setup and revocation](./docs/settings.md#teams-setup-and-revocation).
51
+
52
+ For LINE, enable Messaging API on a LINE Official Account and obtain a channel access token and eligible user, group, or room ID. `/notify` accepts both in masked inputs. Delivery consumes the account's applicable message allowance; quotas and plans vary by region. LINE Notify is not supported. See [LINE setup and revocation](./docs/settings.md#line-setup-and-revocation).
53
+
50
54
  ## 💬 Commands
51
55
 
52
56
  `/notify` opens destination management, Settings, Status, Help, and confirmed test delivery in TUI mode. It accepts no arguments. Settings changes save immediately; closing the screen does not undo them. Destination edits remain unsaved until confirmation. Escape goes back; Ctrl+C closes the flow. Cancelling a running test closes the menu and cannot recall a message already accepted by the provider.
@@ -84,7 +88,7 @@ See the bundled [settings and behavior reference](./docs/settings.md) for accept
84
88
 
85
89
  Notifications send the operating-system hostname, session name and ID, working directory, available Git repository/worktree/branch, elapsed time, and settlement timestamp to the selected notification services or webhook endpoints. Gotify messages are visible to the user who owns the application; Slack messages are visible to people with access to the installed channel. Paths shorten the home prefix to `~` when possible, but names and paths can still disclose private information. They describe the host running Pi, which can differ from your SSH client computer.
86
90
 
87
- No prompts, assistant answers, code, tool output, Git remotes, or raw provider errors are sent. Dynamic metadata is bounded and terminal controls are removed; `@` is replaced with `@` to avoid accidental mentions. Telegram link previews are disabled. Gotify sends plain text without Markdown extras. Slack uses `plain_text` blocks without mention or link expansion and a generic fallback. Slack desktop notifications can still show metadata from the blocks. Discord disables mention parsing and link previews, but does not suppress notifications. Credential values, including complete Slack, Discord, and Generic webhook URLs, never appear in review, preview, status, or error output. POSIX settings writes use `0600` permissions and temporary-file-plus-rename publication. JavaScript memory is not secure credential storage; revoke exposed tokens through BotFather or your Gotify server, or revoke the webhook in Slack before replacing its User setting. Removing a saved destination does not revoke its credential. See [provider revocation instructions](./docs/settings.md#provider-setup-and-revocation) for the new services.
91
+ No prompts, assistant answers, code, tool output, Git remotes, or raw provider errors are sent. Dynamic metadata is bounded and terminal controls are removed; `@` is replaced with `@` to avoid accidental mentions. Telegram link previews are disabled. Gotify sends plain text without Markdown extras. Slack uses `plain_text` blocks without mention or link expansion and a generic fallback. Slack desktop notifications can still show metadata from the blocks. Discord disables mention parsing and link previews, but does not suppress notifications. Credential values, LINE recipient IDs, and complete Slack, Discord, Teams, and Generic webhook URLs never appear in review, preview, status, or error output. LINE receives the selected recipient ID and metadata through its Messaging API; members of a selected group or room can read the message. LINE clients can automatically link URLs in plain text. Teams receives a fixed Adaptive Card with literal text and no actions, images, or mentions; client automatic links are not guaranteed to be suppressed. People with access to the workflow's destination chat/channel can read its metadata. POSIX settings writes use `0600` permissions and temporary-file-plus-rename publication. JavaScript memory is not secure credential storage; revoke exposed tokens through BotFather or your Gotify server, or revoke the webhook in Slack before replacing its User setting. Removing a saved destination does not revoke its credential. See [provider revocation instructions](./docs/settings.md#provider-setup-and-revocation) for the new services.
88
92
 
89
93
  Gotify sends its application token in the `X-Gotify-Key` header, never in the URL. Use HTTPS: HTTP is supported for private self-hosted servers but sends the token and metadata without encryption. Server URLs cannot contain credentials, query strings, or fragments. Redirects are rejected.
90
94
 
@@ -92,7 +96,11 @@ Prefer HTTPS for ntfy, Bark, and Generic webhooks too: HTTP sends credentials an
92
96
 
93
97
  ## 🚧 Limitations
94
98
 
95
- The eight listed providers are built in; third-party provider plugins are not loaded. Slack supports commercial Incoming Webhooks at `https://hooks.slack.com/services/...` only, with the channel selected during installation. GovSlack, channel overrides, OAuth, bot tokens, replies, and file uploads are not supported. No Slack SDK or extension-specific environment variables are required. Gotify uses application tokens, not client tokens or user passwords. It sends messages only; it does not subscribe to messages or manage applications.
99
+ The ten listed providers are built in; third-party provider plugins are not loaded. Slack supports commercial Incoming Webhooks at `https://hooks.slack.com/services/...` only, with the channel selected during installation. GovSlack, channel overrides, OAuth, bot tokens, replies, and file uploads are not supported. No Slack SDK or extension-specific environment variables are required. Gotify uses application tokens, not client tokens or user passwords. It sends messages only; it does not subscribe to messages or manage applications.
100
+
101
+ Teams supports commercial Workflows with Anyone authentication only, without an Authorization header. The workflow owns routing; account permissions, workflow owners/co-owners, tenant policy, and Workflows availability affect delivery. Legacy Office connectors, `logic.azure.com`, government clouds, tenant-authenticated triggers, OAuth, and channel overrides are not supported. The fixed Adaptive Card 1.2 uses literal `RichTextBlock`/`TextRun` text without Markdown. Encoded JSON is capped locally at 24,000 UTF-8 bytes, with Unicode-safe clipping; this is not a downstream rendering guarantee. Only HTTP 202 after a bounded response read counts as trigger acceptance. This explicit client policy awaits live interoperability verification, not a claim of a universal Microsoft URL or response contract. See [Teams URL, payload, and acceptance limits](./docs/settings.md#microsoft-teams).
102
+
103
+ LINE sends one plain-text Messaging API push, clipped to 5,000 UTF-16 code units. It requires an eligible recipient and account allowance; HTTP acceptance does not prove receipt, including when the recipient blocked the account. It does not discover recipient IDs, receive events, manage accounts, or support replies, broadcast, silent delivery, or LINE Notify. See [LINE fields and delivery limits](./docs/settings.md#line).
96
104
 
97
105
  Pushover uses normal priority only, without emergency delivery, acknowledgement, or retry parameters. Discord supports official webhooks for normal text channels, not forum/media channels or thread selection. ntfy and Generic webhooks support no authentication or Bearer authentication only; Bark supports its device key, not native server Basic authentication. No custom headers, templates, scripts, or extension-specific environment variables are supported. See [provider fields and limits](./docs/settings.md#new-provider-fields) for exact URL, credential, and payload bounds.
98
106
 
@@ -104,7 +112,7 @@ Notification delivery is best effort with one attempt and a 10-second deadline c
104
112
 
105
113
  Manual aborts and interactive confirmation prompts do not notify. `agent_settled` means Pi will not continue automatically, not that the requested task succeeded. Preflight errors that do not produce a settled work period cannot generate a completion notification. No cooldown suppresses distinct eligible work periods.
106
114
 
107
- Before reverting to a version without the five new providers, remove their IDs from every affected Project selection, User selections, and saved destinations while the current version is installed. Before reverting to a version without Slack support, remove Slack IDs from User and Project selections and remove the Slack destinations while the current version is installed. Older versions disable automatic delivery for unsupported destinations, even when unselected. See [rollback steps](./docs/settings.md#persistence-and-recovery).
115
+ Before reverting to a version without Teams, remove its IDs from every affected explicit Project selection, User selections, and all saved Teams destinations while this version remains installed. Revoke exposed or unused workflow URLs separately. Before reverting to a version without LINE, remove its destination IDs from explicit Project selections, User selections, and saved destinations while this version is installed; unselected unsupported destinations also disable older routing. Revoke credentials through LINE separately. Before reverting to a version without the five new providers, remove their IDs from every affected Project selection, User selections, and saved destinations while the current version is installed. Before reverting to a version without Slack support, remove Slack IDs from User and Project selections and remove the Slack destinations while the current version is installed. Older versions disable automatic delivery for unsupported destinations, even when unselected. See [rollback steps](./docs/settings.md#persistence-and-recovery).
108
116
 
109
117
  ## 🗂️ Package layout
110
118
 
@@ -118,7 +126,7 @@ The package publishes TypeScript source, documentation, and its license. It does
118
126
 
119
127
  ## 🔎 Keywords
120
128
 
121
- Pi coding agent, Telegram bot, Gotify, Slack Incoming Webhooks, ntfy, Pushover, Discord webhook, Bark, Generic webhook, self-hosted notifications, completion notification, inactivity reminder, Git worktree.
129
+ Pi coding agent, Telegram bot, Gotify, Slack Incoming Webhooks, ntfy, Pushover, Discord webhook, Bark, LINE Messaging API, Microsoft Teams Workflows, Generic webhook, self-hosted notifications, completion notification, inactivity reminder, Git worktree.
122
130
 
123
131
  ## 📄 License
124
132
 
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 five additional 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.
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 eight providers together. For example, with existing `personal` Telegram and `gotify` destinations, add a Slack destination and select their IDs:
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 Generic webhook. Transport results distinguish accepted, failed with a safe code, and cancelled; retry-after is diagnostic, not an automatic retry instruction.
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. The five new providers 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.
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.0",
3
+ "version": "0.4.0",
4
4
  "description": "Multi-provider notifications when Pi settles, with optional inactivity reminders.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -14,6 +14,11 @@
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"
@@ -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,
package/src/menu.ts CHANGED
@@ -59,6 +59,9 @@ type Action =
59
59
  | "addDiscord"
60
60
  | "addBark"
61
61
  | "addWebhook"
62
+ | "addTeams"
63
+ | "addLine"
64
+ | "recipientId"
62
65
  | "userKey"
63
66
  | "bearerToken"
64
67
  | "ntfyTopic"
@@ -94,6 +97,8 @@ export const helpLines = [
94
97
  "Gotify labels are generated automatically. Edit the label or optional safe-integer priority from the destination review. An empty priority uses the server default.",
95
98
  "For Slack, enable Incoming Webhooks in a Slack app and add a webhook to your workspace. Its installation fixes the channel. Paste the complete hooks.slack.com URL only into the masked field; never into Pi chat.",
96
99
  "Slack webhook URLs are secrets. Reviews and Status show only that a webhook is configured. Revoke an exposed webhook in the Slack app before replacing it.",
100
+ "For Microsoft Teams, create a Workflows webhook with Anyone authentication. Enter its complete current signed URL only in the masked field. The workflow owns its target. HTTP 202 means trigger acceptance, not proof of a Teams post; live interoperability is not yet verified. See docs/settings.md for supported URLs, setup, and revocation.",
101
+ "For LINE, enable Messaging API on an Official Account and enter its channel access token and user/group/room ID in masked inputs. Recipient eligibility and account quotas apply. LINE Notify is not supported. See docs/settings.md for setup and revocation.",
97
102
  "For ntfy, subscribe to a topic and configure server authentication and topic permissions. Topic secrecy is not access control. Review the server, optional Bearer token, and priority from 1 to 5.",
98
103
  "For Pushover, enter the application token and user key in masked inputs. Delivery uses normal priority only, without emergency acknowledgement or retries.",
99
104
  "For Discord, paste a normal text-channel webhook URL into the masked input. Mentions and link embeds are disabled; forum/media channels and thread selection are not supported.",
@@ -180,9 +185,12 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
180
185
  draft = undefined;
181
186
  return { kind: "to", screen: "main" } as const;
182
187
  };
183
- const addWebhook = async (provider: "discord" | "webhook", actionSignal: AbortSignal) => {
188
+ const addWebhook = async (provider: "discord" | "webhook" | "teams", actionSignal: AbortSignal) => {
184
189
  const result = await runSecretInput(menuCtx, {
185
- title: `${provider === "discord" ? "Discord" : "Generic webhook"} URL`,
190
+ title:
191
+ provider === "teams"
192
+ ? "Teams workflow webhook URL"
193
+ : `${provider === "discord" ? "Discord" : "Generic webhook"} URL`,
186
194
  signal: actionSignal,
187
195
  isCurrent,
188
196
  onError: reportError,
@@ -193,7 +201,12 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
193
201
  if (result.kind !== "submitted") return { kind: "stay" } as const;
194
202
  const destination = providers.get(provider)?.validate({
195
203
  provider,
196
- label: provider === "discord" ? "Discord notifications" : "Generic webhook notifications",
204
+ label:
205
+ provider === "teams"
206
+ ? "Microsoft Teams notifications"
207
+ : provider === "discord"
208
+ ? "Discord notifications"
209
+ : "Generic webhook notifications",
197
210
  webhookUrl: result.value,
198
211
  });
199
212
  if (!destination) throw new Error("Use a valid webhook URL.");
@@ -248,6 +261,8 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
248
261
  { id: "addDiscord", label: "Add Discord destination", action: "addDiscord" },
249
262
  { id: "addBark", label: "Add Bark destination", action: "addBark" },
250
263
  { id: "addWebhook", label: "Add Generic webhook destination", action: "addWebhook" },
264
+ { id: "addLine", label: "Add LINE destination", action: "addLine" },
265
+ { id: "addTeams", label: "Add Microsoft Teams destination", action: "addTeams" },
251
266
  ],
252
267
  }),
253
268
  destination: () => ({
@@ -429,6 +444,9 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
429
444
  ...(assertDraft().provider === "pushover"
430
445
  ? [{ id: "userKey", label: "Replace user key…", action: "userKey" as const }]
431
446
  : []),
447
+ ...(assertDraft().provider === "line"
448
+ ? [{ id: "recipientId", label: "Replace recipient ID…", action: "recipientId" as const }]
449
+ : []),
432
450
  { id: "label", label: "Change label…", to: "label" },
433
451
  ...(assertDraft().provider === "webhook"
434
452
  ? [{ id: "bearerToken", label: "Set Bearer token (empty for none)…", action: "bearerToken" as const }]
@@ -615,8 +633,60 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
615
633
  draft = destination;
616
634
  return { kind: "to", screen: "review" };
617
635
  },
636
+ addLine: async ({ signal: actionSignal }) => {
637
+ const token = await runSecretInput(menuCtx, {
638
+ title: "LINE channel access token",
639
+ signal: actionSignal,
640
+ isCurrent,
641
+ onError: reportError,
642
+ });
643
+ actionSignal.throwIfAborted();
644
+ current();
645
+ if (token.kind === "closed" && token.reason === "close") return { kind: "close" };
646
+ if (token.kind !== "submitted") return { kind: "stay" };
647
+ const recipient = await runSecretInput(menuCtx, {
648
+ title: "LINE recipient ID (user, group, or room)",
649
+ signal: actionSignal,
650
+ isCurrent,
651
+ onError: reportError,
652
+ });
653
+ actionSignal.throwIfAborted();
654
+ current();
655
+ if (recipient.kind === "closed" && recipient.reason === "close") return { kind: "close" };
656
+ if (recipient.kind !== "submitted") return { kind: "stay" };
657
+ const destination = providers.get("line")?.validate({
658
+ provider: "line",
659
+ label: "LINE notifications",
660
+ channelAccessToken: token.value.trim(),
661
+ recipientId: recipient.value.trim(),
662
+ });
663
+ if (!destination) throw new Error("Use a valid LINE token and recipient ID.");
664
+ selectedId = randomUUID();
665
+ draft = destination;
666
+ return { kind: "to", screen: "review" };
667
+ },
668
+ recipientId: async ({ signal: actionSignal }) => {
669
+ const result = await runSecretInput(menuCtx, {
670
+ title: "Replace LINE recipient ID",
671
+ signal: actionSignal,
672
+ isCurrent,
673
+ onError: reportError,
674
+ });
675
+ actionSignal.throwIfAborted();
676
+ current();
677
+ if (result.kind === "closed" && result.reason === "close") return { kind: "close" };
678
+ if (result.kind === "submitted") {
679
+ const destination = assertDraft();
680
+ const valid = providers.get("line")?.validate({ ...destination, recipientId: result.value.trim() });
681
+ if (destination.provider !== "line" || valid?.provider !== "line")
682
+ throw new Error("Use a valid LINE user, group, or room ID.");
683
+ destination.recipientId = valid.recipientId;
684
+ }
685
+ return { kind: "stay" };
686
+ },
618
687
  addDiscord: ({ signal: actionSignal }) => addWebhook("discord", actionSignal),
619
688
  addWebhook: ({ signal: actionSignal }) => addWebhook("webhook", actionSignal),
689
+ addTeams: ({ signal: actionSignal }) => addWebhook("teams", actionSignal),
620
690
  addBark: async ({ signal: actionSignal }) => {
621
691
  const result = await runSecretInput(menuCtx, {
622
692
  title: "Bark device key",
@@ -759,6 +829,15 @@ export async function showNotifyMenu(ctx: ExtensionCommandContext, options: Menu
759
829
  destination.deviceKey = valid.deviceKey;
760
830
  break;
761
831
  }
832
+ case "line": {
833
+ const valid = providers
834
+ .get("line")
835
+ ?.validate({ ...destination, channelAccessToken: result.value.trim() });
836
+ if (valid?.provider !== "line") throw new Error("Use a valid LINE channel access token.");
837
+ destination.channelAccessToken = valid.channelAccessToken;
838
+ break;
839
+ }
840
+ case "teams":
762
841
  case "discord":
763
842
  case "webhook": {
764
843
  const valid = providers.get(destination.provider)?.validate({ ...destination, webhookUrl: result.value });
package/src/provider.ts CHANGED
@@ -49,6 +49,19 @@ export interface BarkDestination {
49
49
  deviceKey: string;
50
50
  }
51
51
 
52
+ export interface TeamsDestination {
53
+ provider: "teams";
54
+ label: string;
55
+ webhookUrl: string;
56
+ }
57
+
58
+ export interface LineDestination {
59
+ provider: "line";
60
+ label: string;
61
+ channelAccessToken: string;
62
+ recipientId: string;
63
+ }
64
+
52
65
  export interface WebhookDestination {
53
66
  provider: "webhook";
54
67
  label: string;
@@ -64,7 +77,9 @@ export type Destination =
64
77
  | PushoverDestination
65
78
  | DiscordDestination
66
79
  | BarkDestination
67
- | WebhookDestination;
80
+ | WebhookDestination
81
+ | LineDestination
82
+ | TeamsDestination;
68
83
 
69
84
  export interface BodyEmphasis {
70
85
  style: "bold" | "monospace";
@@ -0,0 +1,91 @@
1
+ import { sanitizeTerminalText } from "@narumitw/pi-tui-kit/terminal-text";
2
+ import { type DeliveryResult, isObject, type NotificationProvider } from "../provider.js";
3
+ import { clipText } from "../text.js";
4
+ import { postJson } from "./http.js";
5
+
6
+ // Verified 2026-10-18: https://developers.line.biz/en/reference/messaging-api/#send-push-message
7
+ // https://developers.line.biz/en/docs/messaging-api/text-character-count/: 5,000 UTF-16 units.
8
+ // https://developers.line.biz/en/docs/basics/channel-access-token/: tokens are opaque.
9
+ // RFC 6750 section 2.1 defines Bearer syntax; 8,192 is a local cap, not a LINE token limit.
10
+ const MAX_TOKEN_LENGTH = 8192;
11
+
12
+ function plainText(text: string): string {
13
+ return text.split("\n").map(sanitizeTerminalText).join("\n");
14
+ }
15
+
16
+ function acceptedBody(body: unknown): boolean {
17
+ if (!isObject(body)) return false;
18
+ // Legacy {}: https://github.com/line/line-bot-sdk-nodejs/blob/master/test/line-bot-client.spec.ts
19
+ // Current schema: https://github.com/line/line-openapi/blob/main/messaging-api.yml
20
+ if (Object.keys(body).length === 0) return true;
21
+ // Current reference uses Number for id; official line-openapi and its example use String.
22
+ return (
23
+ Array.isArray(body.sentMessages) &&
24
+ body.sentMessages.length >= 1 &&
25
+ body.sentMessages.length <= 5 &&
26
+ body.sentMessages.every(
27
+ (message) =>
28
+ isObject(message) &&
29
+ ((typeof message.id === "string" && message.id.length > 0) ||
30
+ (typeof message.id === "number" && Number.isInteger(message.id) && message.id >= 0)) &&
31
+ (message.quoteToken === undefined || typeof message.quoteToken === "string"),
32
+ )
33
+ );
34
+ }
35
+
36
+ /** One normal text push; HTTP acceptance does not prove recipient delivery. */
37
+ export function createLineProvider(fetcher: typeof fetch = fetch): NotificationProvider {
38
+ return {
39
+ id: "line",
40
+ label: "LINE",
41
+ validate(value) {
42
+ if (!isObject(value) || value.provider !== "line") return undefined;
43
+ if (typeof value.label !== "string" || !value.label.trim() || value.label.length > 128) return undefined;
44
+ if (
45
+ typeof value.channelAccessToken !== "string" ||
46
+ value.channelAccessToken.length > MAX_TOKEN_LENGTH ||
47
+ /\s/u.test(value.channelAccessToken) ||
48
+ !/^[A-Za-z0-9._~+/-]+=*$/u.test(value.channelAccessToken)
49
+ )
50
+ return undefined;
51
+ // https://developers.line.biz/en/docs/messaging-api/getting-user-ids/: U + 32 lowercase hex.
52
+ // The push reference's webhook source examples use C/R prefixes for group/room IDs.
53
+ // Group/room syntax is not specified: printable ASCII and 128 suffix characters
54
+ // are local safety bounds, not a claimed service grammar.
55
+ if (
56
+ typeof value.recipientId !== "string" ||
57
+ value.recipientId.length > 129 ||
58
+ /\s/u.test(value.recipientId) ||
59
+ !/^(?:U[0-9a-f]{32}|[CR][!-~]{1,128})$/u.test(value.recipientId)
60
+ )
61
+ return undefined;
62
+ return {
63
+ provider: "line",
64
+ label: value.label,
65
+ channelAccessToken: value.channelAccessToken,
66
+ recipientId: value.recipientId,
67
+ };
68
+ },
69
+ async send(destination, notification, signal): Promise<DeliveryResult> {
70
+ if (signal.aborted) return { state: "cancelled", code: "cancelled" };
71
+ const valid = this.validate(destination);
72
+ if (valid?.provider !== "line") return { state: "failed", code: "invalid-destination" };
73
+ const result = await postJson(
74
+ "https://api.line.me/v2/bot/message/push",
75
+ {
76
+ to: valid.recipientId,
77
+ // No mention/emoji objects, substitutions, formatting, or silent-delivery option.
78
+ // LINE clients can still auto-link literal URLs; this does not promise link suppression.
79
+ messages: [{ type: "text", text: clipText(plainText(`${notification.title}\n${notification.body}`), 5000) }],
80
+ },
81
+ signal,
82
+ fetcher,
83
+ { Authorization: `Bearer ${valid.channelAccessToken}` },
84
+ );
85
+ if (result.state !== "response") return result;
86
+ return result.status === 200 && acceptedBody(result.body)
87
+ ? { state: "accepted" }
88
+ : { state: "failed", code: "response" };
89
+ },
90
+ };
91
+ }
@@ -0,0 +1,156 @@
1
+ import { sanitizeTerminalText } from "@narumitw/pi-tui-kit/terminal-text";
2
+ import { type DeliveryResult, isObject, type NotificationProvider } from "../provider.js";
3
+ import { postJson } from "./http.js";
4
+
5
+ // Local support policy, not a complete Microsoft URL grammar. Reviewed 2026-10-18:
6
+ // https://learn.microsoft.com/en-us/power-automate/triggers-troubleshoot
7
+ // documents migration from logic.azure.com and the optional /direct/cu/20 route.
8
+ // https://learn.microsoft.com/en-us/connectors/teams/#microsoft-teams-webhook
9
+ // documents Anyone authentication (no Authorization header) and the card envelope.
10
+ // https://learn.microsoft.com/en-us/azure/logic-apps/logic-apps-http-endpoint
11
+ // documents signed Request URLs; this is corroboration, not a Teams URL/response contract.
12
+ // Public current-format example (corroboration only):
13
+ // https://dev.classmethod.jp/en/articles/aws-step-functions-teams-workflows-new-webhook-url/
14
+ // Support only literal lowercase commercial DNS hosts with one or more valid prefix
15
+ // labels before .environment.api.powerplatform.com; labels <=63, entire host <=253.
16
+ // Require HTTPS, no userinfo, and no port except an explicit generated :443.
17
+ // Paths are exactly /powerautomate/automations/direct/[cu/<route>/]workflows/<id>
18
+ // /triggers/manual/paths/invoke. Route/id are opaque ASCII letters, digits, _ or -,
19
+ // 1..256 characters each: a local bound, NOT an inferred fixed-length service ID.
20
+ // Reject all encoded hosts/paths, dot segments, fragments, whitespace, controls and
21
+ // backslashes before a URL parser could normalize them. Total URL cap: 8,192 chars.
22
+ // Query keys must be literal api-version, sp, sv, sig, exactly once, in any order.
23
+ // api-version=1 and sv=1.0 are literal; decoded sp is /triggers/manual/run.
24
+ // Decoded sig is nonempty opaque base64/base64url syntax (up to two trailing =).
25
+ // Percent escapes must be valid UTF-8. In particular, + is NOT form-decoded to space.
26
+ // Preserve the COMPLETE raw signed URL, including port, escape case and query order.
27
+ const MAX_URL_LENGTH = 8192;
28
+ const HOST_SUFFIX = ".environment.api.powerplatform.com";
29
+ const DNS_LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/u;
30
+ const WORKFLOW_PATH =
31
+ /^\/powerautomate\/automations\/direct\/(?:cu\/[A-Za-z0-9_-]{1,256}\/)?workflows\/[A-Za-z0-9_-]{1,256}\/triggers\/manual\/paths\/invoke$/u;
32
+
33
+ function workflowUrl(value: unknown): string | undefined {
34
+ if (typeof value !== "string" || value.length > MAX_URL_LENGTH || /[\s\\\p{Cc}]/u.test(value)) return undefined;
35
+ const parts = /^https:\/\/([^/?#]+)(\/[^?#]+)\?([^#]+)$/u.exec(value);
36
+ if (!parts) return undefined;
37
+ const [, authority = "", path = "", query = ""] = parts;
38
+ const hostname = authority.endsWith(":443") ? authority.slice(0, -4) : authority;
39
+ if (
40
+ hostname.length > 253 ||
41
+ !hostname.endsWith(HOST_SUFFIX) ||
42
+ hostname.length <= HOST_SUFFIX.length ||
43
+ !hostname.split(".").every((label) => DNS_LABEL.test(label)) ||
44
+ !WORKFLOW_PATH.test(path)
45
+ )
46
+ return undefined;
47
+ const values = new Map<string, string>();
48
+ try {
49
+ for (const pair of query.split("&")) {
50
+ const separator = pair.indexOf("=");
51
+ if (separator < 0) return undefined;
52
+ const key = pair.slice(0, separator);
53
+ const raw = pair.slice(separator + 1);
54
+ if (!["api-version", "sp", "sv", "sig"].includes(key) || values.has(key)) return undefined;
55
+ const decoded = decodeURIComponent(raw);
56
+ // Also reject encoded terminal whitespace: JavaScript's $ can precede a final newline.
57
+ if (/[\s\\\p{Cc}]/u.test(decoded)) return undefined;
58
+ if ((key === "api-version" && raw !== "1") || (key === "sv" && raw !== "1.0")) return undefined;
59
+ values.set(key, decoded);
60
+ }
61
+ } catch {
62
+ return undefined;
63
+ }
64
+ if (
65
+ values.size !== 4 ||
66
+ values.get("sp") !== "/triggers/manual/run" ||
67
+ !/^[A-Za-z0-9_+/-]+={0,2}$/u.test(values.get("sig") ?? "")
68
+ )
69
+ return undefined;
70
+ return value;
71
+ }
72
+
73
+ function card(text: string) {
74
+ return {
75
+ type: "message",
76
+ attachments: [
77
+ {
78
+ contentType: "application/vnd.microsoft.card.adaptive",
79
+ contentUrl: null,
80
+ content: {
81
+ $schema: "http://adaptivecards.io/schemas/adaptive-card.json",
82
+ type: "AdaptiveCard",
83
+ version: "1.2",
84
+ // TextRun has no Markdown support. No actions, images or mention entities.
85
+ // https://learn.microsoft.com/en-us/adaptive-cards/schema-explorer/text-run
86
+ // Clients can still auto-link text; this does not promise link suppression.
87
+ body: [{ type: "RichTextBlock", inlines: [{ type: "TextRun", text }] }],
88
+ },
89
+ },
90
+ ],
91
+ };
92
+ }
93
+
94
+ // A local encoded-JSON budget, NOT proof of Teams' downstream rendered-card size.
95
+ // https://learn.microsoft.com/en-us/connectors/teams/#known-issues-and-limitations
96
+ // The connector's approximate 28 KB limit includes rendered elements.
97
+ const MAX_PAYLOAD_BYTES = 24_000;
98
+ const TEXT_BUDGET = MAX_PAYLOAD_BYTES - Buffer.byteLength(JSON.stringify(card("")), "utf8");
99
+
100
+ function boundedText(title: string, body: string): string {
101
+ const text = `${title}\n${body}`.split("\n").map(sanitizeTerminalText).join("\n");
102
+ const points: string[] = [];
103
+ const costs: number[] = [];
104
+ let bytes = 0;
105
+ for (const point of text) {
106
+ // Count JSON escapes as well as UTF-8, using only constant-sized serializations.
107
+ const cost = Buffer.byteLength(JSON.stringify(point), "utf8") - 2;
108
+ if (bytes + cost > TEXT_BUDGET) {
109
+ while (bytes + 3 > TEXT_BUDGET) {
110
+ bytes -= costs.pop() ?? 0;
111
+ points.pop();
112
+ }
113
+ return `${points.join("")}…`;
114
+ }
115
+ bytes += cost;
116
+ points.push(point);
117
+ costs.push(cost);
118
+ }
119
+ return points.join("");
120
+ }
121
+
122
+ /** One workflow request. Local acceptance is HTTP 202, never downstream-post proof. */
123
+ export function createTeamsProvider(fetcher: typeof fetch = fetch): NotificationProvider {
124
+ return {
125
+ id: "teams",
126
+ label: "Microsoft Teams",
127
+ validate(value) {
128
+ if (!isObject(value) || value.provider !== "teams") return undefined;
129
+ if (typeof value.label !== "string" || !value.label.trim() || value.label.length > 128) return undefined;
130
+ const webhookUrl = workflowUrl(value.webhookUrl);
131
+ return webhookUrl ? { provider: "teams", label: value.label, webhookUrl } : undefined;
132
+ },
133
+ async send(destination, notification, signal): Promise<DeliveryResult> {
134
+ if (signal.aborted) return { state: "cancelled", code: "cancelled" };
135
+ const valid = this.validate(destination);
136
+ if (valid?.provider !== "teams") return { state: "failed", code: "invalid-destination" };
137
+ const result = await postJson(
138
+ valid.webhookUrl,
139
+ card(boundedText(notification.title, notification.body)),
140
+ signal,
141
+ fetcher,
142
+ );
143
+ if (result.state !== "response") return result;
144
+ // Explicit local status-only policy after the FULL bounded response read:
145
+ // https://www.rfc-editor.org/rfc/rfc9110.html#section-15.3.3
146
+ // 202 means accepted for processing, not completed. The Request documentation
147
+ // above corroborates default 202 without a Response action, but does not define
148
+ // Teams responses. A public workflow example also reports 202 despite a later
149
+ // workflow failure (corroboration only, NOT a normative Teams response shape):
150
+ // https://simonscholz.dev/tutorials/microsoft-teams-messages-webhook-workflow/
151
+ // Ignore bounded empty/text/JSON bodies and undocumented fields.
152
+ // Live Teams interoperability and downstream receipt remain unverified.
153
+ return result.status === 202 ? { state: "accepted" } : { state: "failed", code: "response" };
154
+ },
155
+ };
156
+ }
package/src/providers.ts CHANGED
@@ -2,9 +2,11 @@ import type { Providers } from "./provider.js";
2
2
  import { createBarkProvider } from "./providers/bark.js";
3
3
  import { createDiscordProvider } from "./providers/discord.js";
4
4
  import { createGotifyProvider } from "./providers/gotify.js";
5
+ import { createLineProvider } from "./providers/line.js";
5
6
  import { createNtfyProvider } from "./providers/ntfy.js";
6
7
  import { createPushoverProvider } from "./providers/pushover.js";
7
8
  import { createSlackProvider } from "./providers/slack.js";
9
+ import { createTeamsProvider } from "./providers/teams.js";
8
10
  import { createTelegramProvider } from "./providers/telegram.js";
9
11
  import { createWebhookProvider } from "./providers/webhook.js";
10
12
 
@@ -17,4 +19,6 @@ export const providers: Providers = new Map([
17
19
  ["discord", createDiscordProvider()],
18
20
  ["bark", createBarkProvider()],
19
21
  ["webhook", createWebhookProvider()],
22
+ ["line", createLineProvider()],
23
+ ["teams", createTeamsProvider()],
20
24
  ]);