@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 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,13 +18,13 @@ 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
 
25
25
  ```sh
26
26
  npm install
27
- npm run build
27
+ npm --workspace @narumitw/pi-notify run build
28
28
  pi -e ./packages/pi-notify
29
29
  ```
30
30
 
@@ -35,7 +35,7 @@ pi install npm:@narumitw/pi-notify
35
35
  pi -e npm:@narumitw/pi-notify
36
36
  ```
37
37
 
38
- Restart Pi or run `/reload` after persistent installation. The extension uses Pi's TypeScript loader and does not require a package-owned build. It requires Pi APIs for `agent_settled`, `getAgentDir()`, and trusted project settings, plus Node.js with native `fetch` and `AbortSignal.any()`.
38
+ Restart Pi or run `/reload` after persistent installation. Published packages include a generated split `dist/index.ts` runtime for Pi's Jiti loader. Build an unbuilt local checkout before loading the package directory; repository Git/source installation retains `src/index.ts`. The `/notify` menu loads only when opened. The extension requires Pi APIs for `agent_settled`, `getAgentDir()`, and trusted project settings, plus Node.js with native `fetch` and `AbortSignal.any()`.
39
39
 
40
40
  ## 🚀 Quick start
41
41
 
@@ -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,21 +112,24 @@ 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
 
111
- - `src/index.ts`: Pi entrypoint forwarding to `src/notify.ts`.
119
+ - `dist/index.ts`: generated package entrypoint with split runtime chunks and source maps.
120
+ - `src/index.ts`: repository source entrypoint forwarding to `src/notify.ts`.
112
121
  - `src/`: session coordination, metadata, settings, menu, and provider contract.
113
122
  - `src/providers/`: provider-specific transports and shared bounded HTTP handling.
114
123
  - `docs/`: installed settings and behavior reference.
124
+ - [benchmarks/](https://github.com/narumiruna/pi-extensions/tree/main/packages/pi-notify/benchmarks): repository-only startup measurements and reproduction commands; not published.
125
+ - `scripts/`: repository-only runtime builder wrapper.
115
126
  - `test/`: repository-only deterministic tests.
116
127
 
117
- The package publishes TypeScript source, documentation, and its license. It does not publish test fixtures or credentials.
128
+ The package publishes the generated runtime, TypeScript source, documentation, and its license. It does not publish build scripts, test fixtures, or credentials.
118
129
 
119
130
  ## 🔎 Keywords
120
131
 
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.
132
+ 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
133
 
123
134
  ## 📄 License
124
135
 
@@ -0,0 +1,318 @@
1
+ // @generated by scripts/build-runtime.mjs; do not edit.
2
+ // @ts-nocheck -- generated JavaScript uses a .ts extension for Pi's Jiti loader.
3
+
4
+ // src/metadata.ts
5
+ import { execFile } from "node:child_process";
6
+ import { homedir, hostname } from "node:os";
7
+ import { basename, dirname, isAbsolute, sep } from "node:path";
8
+ import { sanitizeTerminalText } from "@narumitw/pi-tui-kit/terminal-text";
9
+
10
+ // src/text.ts
11
+ function clipText(text, limit) {
12
+ if (text.length <= limit) return text;
13
+ let result = "";
14
+ for (const character of text) {
15
+ if (result.length + character.length > limit - 1) break;
16
+ result += character;
17
+ }
18
+ return `${result}\u2026`;
19
+ }
20
+
21
+ // src/metadata.ts
22
+ var safeText = (value) => clipText(sanitizeTerminalText(value).replaceAll("@", "\uFF20"), 400);
23
+ function displayPath(raw) {
24
+ const path = safeText(raw);
25
+ const home = safeText(homedir());
26
+ return path === home ? "~" : path.startsWith(`${home}${sep}`) ? `~${path.slice(home.length)}` : path;
27
+ }
28
+ function git(cwd, args, signal) {
29
+ return new Promise((resolve2) => {
30
+ execFile(
31
+ "git",
32
+ ["-C", cwd, "rev-parse", ...args],
33
+ { signal, timeout: 1500, maxBuffer: 8192, encoding: "utf8", windowsHide: true },
34
+ (error, stdout) => resolve2(error ? void 0 : stdout.trim())
35
+ );
36
+ });
37
+ }
38
+ async function notificationMetadata(data, signal) {
39
+ const [root, common, branch] = await Promise.all([
40
+ git(data.cwd, ["--show-toplevel"], signal),
41
+ git(data.cwd, ["--git-common-dir"], signal),
42
+ git(data.cwd, ["--abbrev-ref", "HEAD"], signal)
43
+ ]);
44
+ signal.throwIfAborted();
45
+ const detached = branch === "HEAD" ? await git(data.cwd, ["--short", "HEAD"], signal) : void 0;
46
+ signal.throwIfAborted();
47
+ let body = "";
48
+ const bodyEmphasis = [];
49
+ const line = (label, value, style, prefix = "", suffix = "") => {
50
+ if (body) body += "\n";
51
+ body += `${label}: ${prefix}`;
52
+ if (style && value.length) bodyEmphasis.push({ style, offset: body.length, length: value.length });
53
+ body += value + suffix;
54
+ };
55
+ line("Computer", safeText(hostname()));
56
+ line(
57
+ "Session",
58
+ safeText(data.sessionId),
59
+ "monospace",
60
+ `${data.sessionName ? `${safeText(data.sessionName)} ` : ""}(`,
61
+ ")"
62
+ );
63
+ line("Workspace", displayPath(data.cwd), "monospace");
64
+ if (root) {
65
+ const cleanRoot = safeText(root);
66
+ const cleanCommon = common ? safeText(common) : void 0;
67
+ const commonDirectory = cleanCommon && isAbsolute(cleanCommon) ? cleanCommon : void 0;
68
+ const repository = commonDirectory && basename(commonDirectory) === ".git" ? basename(dirname(commonDirectory)) : basename(cleanRoot);
69
+ line("Repository", repository, "bold");
70
+ line("Worktree", displayPath(root), "monospace");
71
+ if (branch) line("Branch", safeText(branch === "HEAD" ? `detached ${detached ?? "HEAD"}` : branch), "monospace");
72
+ }
73
+ line("Elapsed", `${Math.max(0, Math.floor((data.settledAt - data.startedAt) / 1e3))}s`);
74
+ line("Stopped", new Date(data.settledAt).toISOString());
75
+ return {
76
+ id: data.id,
77
+ title: data.error ? "Pi stopped with an error" : "Pi is ready for review",
78
+ body,
79
+ bodyEmphasis,
80
+ settledAt: data.settledAt
81
+ };
82
+ }
83
+
84
+ // src/settings.ts
85
+ import { randomUUID } from "node:crypto";
86
+ import fs from "node:fs/promises";
87
+ import { dirname as dirname2, join, resolve } from "node:path";
88
+ import { withFileMutationQueue } from "@earendil-works/pi-coding-agent";
89
+
90
+ // src/provider.ts
91
+ function isObject(value) {
92
+ return value !== null && typeof value === "object" && !Array.isArray(value);
93
+ }
94
+ function validateDestination(value, providers) {
95
+ if (!isObject(value) || typeof value.provider !== "string") return void 0;
96
+ return providers.get(value.provider)?.validate(value);
97
+ }
98
+ async function deliver(providers, destination, notification, signal) {
99
+ if (signal.aborted) return { state: "cancelled", code: "cancelled" };
100
+ const provider = providers.get(destination.provider);
101
+ if (!provider) return { state: "failed", code: "unsupported-provider" };
102
+ if (!provider.validate(destination)) return { state: "failed", code: "invalid-destination" };
103
+ try {
104
+ return await provider.send(destination, notification, signal);
105
+ } catch {
106
+ return signal.aborted ? { state: "cancelled", code: "cancelled" } : { state: "failed", code: "network" };
107
+ }
108
+ }
109
+
110
+ // src/settings.ts
111
+ var MAX_INACTIVITY_SECONDS = 86400;
112
+ var MAX_DESTINATIONS = 32;
113
+ var policyKeys = ["enabled", "mode", "inactivitySeconds", "targetIds"];
114
+ var defaults = () => ({
115
+ enabled: true,
116
+ mode: "immediate",
117
+ inactivitySeconds: 30,
118
+ targetIds: [],
119
+ destinations: {}
120
+ });
121
+ var validId = (id) => /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/.test(id) && !["constructor", "prototype", "__proto__"].includes(id);
122
+ var validSeconds = (value) => Number.isInteger(value) && Number(value) >= 1 && Number(value) <= MAX_INACTIVITY_SECONDS;
123
+ function policy(document, diagnostics) {
124
+ const result = {};
125
+ for (const key of policyKeys) {
126
+ if (!Object.hasOwn(document, key)) continue;
127
+ const value = document[key];
128
+ if (key === "enabled" && typeof value === "boolean") result.enabled = value;
129
+ else if (key === "mode" && (value === "immediate" || value === "after-inactivity")) result.mode = value;
130
+ else if (key === "inactivitySeconds" && validSeconds(value)) result.inactivitySeconds = value;
131
+ else if (key === "targetIds" && Array.isArray(value) && value.length <= MAX_DESTINATIONS && value.every((id) => typeof id === "string" && validId(id)) && new Set(value).size === value.length)
132
+ result.targetIds = [...value];
133
+ else diagnostics.push(`Invalid ${key} setting.`);
134
+ }
135
+ return result;
136
+ }
137
+ function resolveSettings(user, project, providers, diagnostics = []) {
138
+ const effective = { ...defaults(), ...policy(user, diagnostics), ...policy(project, diagnostics) };
139
+ if (Object.hasOwn(project, "destinations"))
140
+ diagnostics.push("Project destinations are forbidden; use User settings.");
141
+ if (user.destinations !== void 0) {
142
+ if (!isObject(user.destinations) || Object.keys(user.destinations).length > MAX_DESTINATIONS)
143
+ diagnostics.push("Invalid destinations setting.");
144
+ else
145
+ for (const [id, raw] of Object.entries(user.destinations)) {
146
+ const destination = validId(id) ? validateDestination(raw, providers) : void 0;
147
+ if (destination) effective.destinations[id] = destination;
148
+ else diagnostics.push("Invalid destination or unsupported provider; edit User settings.");
149
+ }
150
+ }
151
+ if (effective.targetIds.some((id) => !Object.hasOwn(effective.destinations, id)))
152
+ diagnostics.push("Selected destination is missing or unsupported; update targetIds.");
153
+ if (diagnostics.length) effective.enabled = false;
154
+ return { user, project, effective, diagnostics };
155
+ }
156
+ async function readDocument(path) {
157
+ try {
158
+ const value = JSON.parse(await fs.readFile(path, "utf8"));
159
+ if (!isObject(value)) throw new Error("invalid");
160
+ return value;
161
+ } catch (error) {
162
+ if (isObject(error) && error.code === "ENOENT") return {};
163
+ throw new Error("Settings cannot be read as a JSON object. Repair the file before saving.");
164
+ }
165
+ }
166
+ var SettingsStore = class {
167
+ constructor(userPath, projectPath, providers) {
168
+ this.userPath = userPath;
169
+ this.providers = providers;
170
+ this.projectPath = projectPath && resolve(projectPath) !== resolve(userPath) ? projectPath : void 0;
171
+ this.snapshot = resolveSettings({}, {}, providers);
172
+ }
173
+ userPath;
174
+ providers;
175
+ snapshot;
176
+ tail = Promise.resolve();
177
+ projectPath;
178
+ enqueue(operation) {
179
+ const task = this.tail.catch(() => {
180
+ }).then(() => withFileMutationQueue(this.userPath, operation));
181
+ this.tail = task.catch(() => {
182
+ });
183
+ return task;
184
+ }
185
+ validate(value) {
186
+ return validateDestination(value, this.providers);
187
+ }
188
+ async flush() {
189
+ await this.tail;
190
+ }
191
+ load() {
192
+ return this.enqueue(async () => {
193
+ const diagnostics = [];
194
+ const read = async (path, scope) => {
195
+ if (!path) return {};
196
+ try {
197
+ return await (path === this.userPath ? readDocument(path) : withFileMutationQueue(path, () => readDocument(path)));
198
+ } catch {
199
+ diagnostics.push(`${scope} settings cannot be read. Repair the JSON file before saving.`);
200
+ return {};
201
+ }
202
+ };
203
+ const user = await read(this.userPath, "user");
204
+ const project = await read(this.projectPath, "project");
205
+ this.snapshot = resolveSettings(user, project, this.providers, diagnostics);
206
+ return this.snapshot;
207
+ });
208
+ }
209
+ change(scope, mutate, signal) {
210
+ return this.enqueue(async () => {
211
+ const path = scope === "user" ? this.userPath : this.projectPath;
212
+ if (!path) throw new Error("Project settings require a trusted project.");
213
+ const operation = async () => {
214
+ signal.throwIfAborted();
215
+ const document = await readDocument(path);
216
+ signal.throwIfAborted();
217
+ const user = scope === "user" ? document : await readDocument(this.userPath);
218
+ const projectPath = this.projectPath;
219
+ const project = scope === "project" ? document : projectPath ? await withFileMutationQueue(projectPath, () => readDocument(projectPath)) : {};
220
+ signal.throwIfAborted();
221
+ const previousEnabled = document.enabled;
222
+ mutate(document, project, user);
223
+ const next = resolveSettings(user, project, this.providers);
224
+ if (next.effective.targetIds.some((id) => !Object.hasOwn(next.effective.destinations, id)))
225
+ throw new Error("Selected destination is missing or unsupported. Repair targetIds before saving.");
226
+ if (next.diagnostics.length && document.enabled === true && previousEnabled !== true)
227
+ throw new Error(
228
+ "Settings contain invalid fields or destinations. Repair them before enabling notifications."
229
+ );
230
+ const temporary = join(dirname2(path), `.pi-notify-${randomUUID()}.tmp`);
231
+ try {
232
+ await fs.mkdir(dirname2(path), { recursive: true });
233
+ signal.throwIfAborted();
234
+ await fs.writeFile(temporary, `${JSON.stringify(document, null, 2)}
235
+ `, { mode: 384, flag: "wx" });
236
+ signal.throwIfAborted();
237
+ await fs.rename(temporary, path);
238
+ } catch {
239
+ throw new Error("Settings were not saved. Check file permissions and available disk space.");
240
+ } finally {
241
+ await fs.rm(temporary, { force: true }).catch(() => {
242
+ });
243
+ }
244
+ this.snapshot = next;
245
+ return next;
246
+ };
247
+ return path === this.userPath ? operation() : withFileMutationQueue(path, operation);
248
+ });
249
+ }
250
+ };
251
+ function savePolicy(store, scope, key, value, signal) {
252
+ const diagnostics = [];
253
+ if (value !== void 0) policy({ [key]: value }, diagnostics);
254
+ if (diagnostics.length) return Promise.reject(new Error("Invalid notification policy value."));
255
+ return store.change(
256
+ scope,
257
+ (document) => {
258
+ if (value === void 0) delete document[key];
259
+ else document[key] = value;
260
+ },
261
+ signal
262
+ );
263
+ }
264
+ function saveDestination(store, id, destination, signal, selectNew = true) {
265
+ if (!validId(id)) throw new Error("Invalid destination ID.");
266
+ const normalized = destination ? store.validate(destination) : void 0;
267
+ if (destination && !normalized) throw new Error("Invalid destination settings.");
268
+ return store.change(
269
+ "user",
270
+ (document, project) => {
271
+ if (document.destinations !== void 0 && !isObject(document.destinations))
272
+ throw new Error("Invalid destinations setting. Repair the file before changing destinations.");
273
+ const destinations = isObject(document.destinations) ? { ...document.destinations } : {};
274
+ if (normalized) {
275
+ if (selectNew && !Object.hasOwn(destinations, id)) {
276
+ const diagnostics = [];
277
+ const selection = policy(
278
+ Object.hasOwn(document, "targetIds") ? { targetIds: document.targetIds } : {},
279
+ diagnostics
280
+ );
281
+ if (diagnostics.length)
282
+ throw new Error("Invalid selected destinations. Repair targetIds before adding a destination.");
283
+ document.targetIds = [.../* @__PURE__ */ new Set([...selection.targetIds ?? [], id])];
284
+ }
285
+ if (Object.hasOwn(destinations, id) && !isObject(destinations[id]))
286
+ throw new Error("Invalid stored destination. Repair the file before replacing this entry.");
287
+ destinations[id] = { ...isObject(destinations[id]) ? destinations[id] : {}, ...normalized };
288
+ if (Object.keys(destinations).length > MAX_DESTINATIONS)
289
+ throw new Error("At most 32 destinations are supported.");
290
+ } else {
291
+ if (Array.isArray(project.targetIds) && project.targetIds.includes(id))
292
+ throw new Error("Remove this destination from Project selections first.");
293
+ delete destinations[id];
294
+ if (Array.isArray(document.targetIds))
295
+ document.targetIds = document.targetIds.filter((target) => target !== id);
296
+ }
297
+ document.destinations = destinations;
298
+ },
299
+ signal
300
+ );
301
+ }
302
+
303
+ export {
304
+ clipText,
305
+ safeText,
306
+ displayPath,
307
+ notificationMetadata,
308
+ isObject,
309
+ deliver,
310
+ policyKeys,
311
+ defaults,
312
+ validSeconds,
313
+ resolveSettings,
314
+ SettingsStore,
315
+ savePolicy,
316
+ saveDestination
317
+ };
318
+ //# sourceMappingURL=chunk-YXQ43SWY.ts.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/metadata.ts", "../../src/text.ts", "../../src/settings.ts", "../../src/provider.ts"],
4
+ "sourcesContent": ["import { execFile } from \"node:child_process\";\nimport { homedir, hostname } from \"node:os\";\nimport { basename, dirname, isAbsolute, sep } from \"node:path\";\nimport { sanitizeTerminalText } from \"@narumitw/pi-tui-kit/terminal-text\";\nimport type { BodyEmphasis, Notification } from \"./provider.js\";\nimport { clipText } from \"./text.js\";\n\nexport interface Metadata {\n id: string;\n sessionId: string;\n sessionName?: string;\n cwd: string;\n startedAt: number;\n settledAt: number;\n error: boolean;\n}\nexport const safeText = (value: string) => clipText(sanitizeTerminalText(value).replaceAll(\"@\", \"\uFF20\"), 400);\nexport function displayPath(raw: string): string {\n const path = safeText(raw);\n const home = safeText(homedir());\n return path === home ? \"~\" : path.startsWith(`${home}${sep}`) ? `~${path.slice(home.length)}` : path;\n}\nfunction git(cwd: string, args: string[], signal: AbortSignal): Promise<string | undefined> {\n return new Promise((resolve) => {\n execFile(\n \"git\",\n [\"-C\", cwd, \"rev-parse\", ...args],\n { signal, timeout: 1500, maxBuffer: 8192, encoding: \"utf8\", windowsHide: true },\n (error, stdout) => resolve(error ? undefined : stdout.trim()),\n );\n });\n}\nexport async function notificationMetadata(data: Metadata, signal: AbortSignal): Promise<Notification> {\n const [root, common, branch] = await Promise.all([\n git(data.cwd, [\"--show-toplevel\"], signal),\n git(data.cwd, [\"--git-common-dir\"], signal),\n git(data.cwd, [\"--abbrev-ref\", \"HEAD\"], signal),\n ]);\n signal.throwIfAborted();\n const detached = branch === \"HEAD\" ? await git(data.cwd, [\"--short\", \"HEAD\"], signal) : undefined;\n signal.throwIfAborted();\n let body = \"\";\n const bodyEmphasis: BodyEmphasis[] = [];\n const line = (label: string, value: string, style?: BodyEmphasis[\"style\"], prefix = \"\", suffix = \"\") => {\n if (body) body += \"\\n\";\n body += `${label}: ${prefix}`;\n if (style && value.length) bodyEmphasis.push({ style, offset: body.length, length: value.length });\n body += value + suffix;\n };\n line(\"Computer\", safeText(hostname()));\n line(\n \"Session\",\n safeText(data.sessionId),\n \"monospace\",\n `${data.sessionName ? `${safeText(data.sessionName)} ` : \"\"}(`,\n \")\",\n );\n line(\"Workspace\", displayPath(data.cwd), \"monospace\");\n if (root) {\n // Sanitize before splitting paths. Common Git directory names identify linked worktrees.\n const cleanRoot = safeText(root);\n const cleanCommon = common ? safeText(common) : undefined;\n const commonDirectory = cleanCommon && isAbsolute(cleanCommon) ? cleanCommon : undefined;\n const repository =\n commonDirectory && basename(commonDirectory) === \".git\"\n ? basename(dirname(commonDirectory))\n : basename(cleanRoot);\n line(\"Repository\", repository, \"bold\");\n line(\"Worktree\", displayPath(root), \"monospace\");\n if (branch) line(\"Branch\", safeText(branch === \"HEAD\" ? `detached ${detached ?? \"HEAD\"}` : branch), \"monospace\");\n }\n line(\"Elapsed\", `${Math.max(0, Math.floor((data.settledAt - data.startedAt) / 1000))}s`);\n line(\"Stopped\", new Date(data.settledAt).toISOString());\n return {\n id: data.id,\n title: data.error ? \"Pi stopped with an error\" : \"Pi is ready for review\",\n body,\n bodyEmphasis,\n settledAt: data.settledAt,\n };\n}\n", "/** Limit UTF-16 length conservatively without splitting a Unicode code point. */\nexport function clipText(text: string, limit: number): string {\n if (text.length <= limit) return text;\n let result = \"\";\n for (const character of text) {\n if (result.length + character.length > limit - 1) break;\n result += character;\n }\n return `${result}\u2026`;\n}\n", "import { randomUUID } from \"node:crypto\";\nimport fs from \"node:fs/promises\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { withFileMutationQueue } from \"@earendil-works/pi-coding-agent\";\nimport { type Destination, isObject, type Providers, validateDestination } from \"./provider.js\";\n\nexport type Mode = \"immediate\" | \"after-inactivity\";\nexport type Scope = \"user\" | \"project\";\nexport interface Settings {\n enabled: boolean;\n mode: Mode;\n inactivitySeconds: number;\n targetIds: string[];\n destinations: Record<string, Destination>;\n}\nexport interface Snapshot {\n user: Record<string, unknown>;\n project: Record<string, unknown>;\n effective: Settings;\n diagnostics: string[];\n}\nexport const MAX_INACTIVITY_SECONDS = 86_400;\nexport const MAX_DESTINATIONS = 32;\nexport const policyKeys = [\"enabled\", \"mode\", \"inactivitySeconds\", \"targetIds\"] as const;\nexport const defaults = (): Settings => ({\n enabled: true,\n mode: \"immediate\",\n inactivitySeconds: 30,\n targetIds: [],\n destinations: {},\n});\nexport const validId = (id: string) =>\n /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/.test(id) && ![\"constructor\", \"prototype\", \"__proto__\"].includes(id);\nexport const validSeconds = (value: unknown): value is number =>\n Number.isInteger(value) && Number(value) >= 1 && Number(value) <= MAX_INACTIVITY_SECONDS;\n\nfunction policy(document: Record<string, unknown>, diagnostics: string[]): Partial<Settings> {\n const result: Partial<Settings> = {};\n for (const key of policyKeys) {\n if (!Object.hasOwn(document, key)) continue;\n const value = document[key];\n if (key === \"enabled\" && typeof value === \"boolean\") result.enabled = value;\n else if (key === \"mode\" && (value === \"immediate\" || value === \"after-inactivity\")) result.mode = value;\n else if (key === \"inactivitySeconds\" && validSeconds(value)) result.inactivitySeconds = value;\n else if (\n key === \"targetIds\" &&\n Array.isArray(value) &&\n value.length <= MAX_DESTINATIONS &&\n value.every((id) => typeof id === \"string\" && validId(id)) &&\n new Set(value).size === value.length\n )\n result.targetIds = [...value];\n else diagnostics.push(`Invalid ${key} setting.`);\n }\n return result;\n}\n\nexport function resolveSettings(\n user: Record<string, unknown>,\n project: Record<string, unknown>,\n providers: Providers,\n diagnostics: string[] = [],\n): Snapshot {\n const effective = { ...defaults(), ...policy(user, diagnostics), ...policy(project, diagnostics) };\n if (Object.hasOwn(project, \"destinations\"))\n diagnostics.push(\"Project destinations are forbidden; use User settings.\");\n if (user.destinations !== undefined) {\n if (!isObject(user.destinations) || Object.keys(user.destinations).length > MAX_DESTINATIONS)\n diagnostics.push(\"Invalid destinations setting.\");\n else\n for (const [id, raw] of Object.entries(user.destinations)) {\n const destination = validId(id) ? validateDestination(raw, providers) : undefined;\n if (destination) effective.destinations[id] = destination;\n else diagnostics.push(\"Invalid destination or unsupported provider; edit User settings.\");\n }\n }\n if (effective.targetIds.some((id) => !Object.hasOwn(effective.destinations, id)))\n diagnostics.push(\"Selected destination is missing or unsupported; update targetIds.\");\n // Fail closed rather than sending with partial or invalid routing settings.\n if (diagnostics.length) effective.enabled = false;\n return { user, project, effective, diagnostics };\n}\n\nasync function readDocument(path: string): Promise<Record<string, unknown>> {\n try {\n const value: unknown = JSON.parse(await fs.readFile(path, \"utf8\"));\n if (!isObject(value)) throw new Error(\"invalid\");\n return value;\n } catch (error) {\n if (isObject(error) && error.code === \"ENOENT\") return {};\n throw new Error(\"Settings cannot be read as a JSON object. Repair the file before saving.\");\n }\n}\n\n/** Per-instance transactions plus Pi's process-wide path queue; no cross-process lock. */\nexport class SettingsStore {\n snapshot: Snapshot;\n private tail: Promise<unknown> = Promise.resolve();\n readonly projectPath: string | undefined;\n constructor(\n readonly userPath: string,\n projectPath: string | undefined,\n private readonly providers: Providers,\n ) {\n // A customized agent directory can coincide with the project's settings directory.\n // One physical path cannot be both credential storage and a project overlay.\n this.projectPath = projectPath && resolve(projectPath) !== resolve(userPath) ? projectPath : undefined;\n this.snapshot = resolveSettings({}, {}, providers);\n }\n private enqueue<T>(operation: () => Promise<T>): Promise<T> {\n // Always lock User before Project across instances to avoid lock-order deadlocks.\n const task = this.tail.catch(() => {}).then(() => withFileMutationQueue(this.userPath, operation));\n this.tail = task.catch(() => {});\n return task;\n }\n validate(value: unknown): Destination | undefined {\n return validateDestination(value, this.providers);\n }\n async flush(): Promise<void> {\n await this.tail;\n }\n load(): Promise<Snapshot> {\n return this.enqueue(async () => {\n const diagnostics: string[] = [];\n const read = async (path: string | undefined, scope: Scope) => {\n if (!path) return {};\n try {\n return await (path === this.userPath\n ? readDocument(path)\n : withFileMutationQueue(path, () => readDocument(path)));\n } catch {\n diagnostics.push(`${scope} settings cannot be read. Repair the JSON file before saving.`);\n return {};\n }\n };\n const user = await read(this.userPath, \"user\");\n const project = await read(this.projectPath, \"project\");\n this.snapshot = resolveSettings(user, project, this.providers, diagnostics);\n return this.snapshot;\n });\n }\n change(\n scope: Scope,\n mutate: (\n document: Record<string, unknown>,\n project: Record<string, unknown>,\n user: Record<string, unknown>,\n ) => void,\n signal: AbortSignal,\n ): Promise<Snapshot> {\n return this.enqueue(async () => {\n const path = scope === \"user\" ? this.userPath : this.projectPath;\n if (!path) throw new Error(\"Project settings require a trusted project.\");\n const operation = async () => {\n signal.throwIfAborted();\n const document = await readDocument(path);\n signal.throwIfAborted();\n const user = scope === \"user\" ? document : await readDocument(this.userPath);\n const projectPath = this.projectPath;\n const project =\n scope === \"project\"\n ? document\n : projectPath\n ? await withFileMutationQueue(projectPath, () => readDocument(projectPath))\n : {};\n signal.throwIfAborted();\n const previousEnabled = document.enabled;\n mutate(document, project, user);\n const next = resolveSettings(user, project, this.providers);\n if (next.effective.targetIds.some((id) => !Object.hasOwn(next.effective.destinations, id)))\n throw new Error(\"Selected destination is missing or unsupported. Repair targetIds before saving.\");\n // Preserve unrecognized destinations on unrelated saves, but never enable invalid routing.\n if (next.diagnostics.length && document.enabled === true && previousEnabled !== true)\n throw new Error(\n \"Settings contain invalid fields or destinations. Repair them before enabling notifications.\",\n );\n const temporary = join(dirname(path), `.pi-notify-${randomUUID()}.tmp`);\n try {\n await fs.mkdir(dirname(path), { recursive: true });\n signal.throwIfAborted();\n await fs.writeFile(temporary, `${JSON.stringify(document, null, 2)}\\n`, { mode: 0o600, flag: \"wx\" });\n signal.throwIfAborted();\n await fs.rename(temporary, path);\n } catch {\n throw new Error(\"Settings were not saved. Check file permissions and available disk space.\");\n } finally {\n await fs.rm(temporary, { force: true }).catch(() => {});\n }\n this.snapshot = next;\n return next;\n };\n return path === this.userPath ? operation() : withFileMutationQueue(path, operation);\n });\n }\n}\n\nexport function savePolicy(\n store: SettingsStore,\n scope: Scope,\n key: (typeof policyKeys)[number],\n value: unknown,\n signal: AbortSignal,\n) {\n const diagnostics: string[] = [];\n if (value !== undefined) policy({ [key]: value }, diagnostics);\n if (diagnostics.length) return Promise.reject(new Error(\"Invalid notification policy value.\"));\n return store.change(\n scope,\n (document) => {\n if (value === undefined) delete document[key];\n else document[key] = value;\n },\n signal,\n );\n}\n\nexport function saveDestination(\n store: SettingsStore,\n id: string,\n destination: Destination | undefined,\n signal: AbortSignal,\n selectNew = true,\n) {\n if (!validId(id)) throw new Error(\"Invalid destination ID.\");\n const normalized = destination ? store.validate(destination) : undefined;\n if (destination && !normalized) throw new Error(\"Invalid destination settings.\");\n return store.change(\n \"user\",\n (document, project) => {\n if (document.destinations !== undefined && !isObject(document.destinations))\n throw new Error(\"Invalid destinations setting. Repair the file before changing destinations.\");\n const destinations = isObject(document.destinations) ? { ...document.destinations } : {};\n if (normalized) {\n if (selectNew && !Object.hasOwn(destinations, id)) {\n const diagnostics: string[] = [];\n const selection = policy(\n Object.hasOwn(document, \"targetIds\") ? { targetIds: document.targetIds } : {},\n diagnostics,\n );\n if (diagnostics.length)\n throw new Error(\"Invalid selected destinations. Repair targetIds before adding a destination.\");\n document.targetIds = [...new Set([...(selection.targetIds ?? []), id])];\n }\n if (Object.hasOwn(destinations, id) && !isObject(destinations[id]))\n throw new Error(\"Invalid stored destination. Repair the file before replacing this entry.\");\n // Validators return owned optional keys as undefined so JSON publication removes them.\n destinations[id] = { ...(isObject(destinations[id]) ? destinations[id] : {}), ...normalized };\n if (Object.keys(destinations).length > MAX_DESTINATIONS)\n throw new Error(\"At most 32 destinations are supported.\");\n } else {\n if (Array.isArray(project.targetIds) && project.targetIds.includes(id))\n throw new Error(\"Remove this destination from Project selections first.\");\n delete destinations[id];\n if (Array.isArray(document.targetIds))\n document.targetIds = document.targetIds.filter((target) => target !== id);\n }\n document.destinations = destinations;\n },\n signal,\n );\n}\n", "export interface TelegramDestination {\n provider: \"telegram\";\n label: string;\n botToken: string;\n chatId: string;\n messageThreadId?: number;\n}\n\nexport interface GotifyDestination {\n provider: \"gotify\";\n label: string;\n serverUrl: string;\n appToken: string;\n priority?: number;\n}\n\nexport interface NtfyDestination {\n provider: \"ntfy\";\n label: string;\n serverUrl: string;\n topic: string;\n accessToken?: string;\n priority?: number;\n}\n\nexport interface SlackDestination {\n provider: \"slack\";\n label: string;\n webhookUrl: string;\n}\n\nexport interface PushoverDestination {\n provider: \"pushover\";\n label: string;\n appToken: string;\n userKey: string;\n}\n\nexport interface DiscordDestination {\n provider: \"discord\";\n label: string;\n webhookUrl: string;\n}\n\nexport interface BarkDestination {\n provider: \"bark\";\n label: string;\n serverUrl: string;\n deviceKey: string;\n}\n\nexport interface TeamsDestination {\n provider: \"teams\";\n label: string;\n webhookUrl: string;\n}\n\nexport interface LineDestination {\n provider: \"line\";\n label: string;\n channelAccessToken: string;\n recipientId: string;\n}\n\nexport interface WebhookDestination {\n provider: \"webhook\";\n label: string;\n webhookUrl: string;\n bearerToken?: string;\n}\n\nexport type Destination =\n | TelegramDestination\n | GotifyDestination\n | SlackDestination\n | NtfyDestination\n | PushoverDestination\n | DiscordDestination\n | BarkDestination\n | WebhookDestination\n | LineDestination\n | TeamsDestination;\n\nexport interface BodyEmphasis {\n style: \"bold\" | \"monospace\";\n /** Offset and length in UTF-16 code units of the sanitized body. */\n offset: number;\n length: number;\n}\n\nexport interface Notification {\n id: string;\n title: string;\n body: string;\n bodyEmphasis?: BodyEmphasis[];\n settledAt: number;\n}\n\nexport type DeliveryCode =\n | \"invalid-destination\"\n | \"unsupported-provider\"\n | \"network\"\n | \"timeout\"\n | \"http\"\n | \"api\"\n | \"rate-limit\"\n | \"response\"\n | \"cancelled\";\nexport type DeliveryResult =\n | { state: \"accepted\" }\n | { state: \"failed\"; code: DeliveryCode; retryAfterSeconds?: number }\n | { state: \"cancelled\"; code: \"cancelled\" };\n\nexport interface NotificationProvider {\n readonly id: string;\n readonly label: string;\n /** Return all owned fields, using undefined for absent optional fields, or reject. */\n validate(value: unknown): Destination | undefined;\n send(destination: Destination, notification: Notification, signal: AbortSignal): Promise<DeliveryResult>;\n}\n\nexport type Providers = ReadonlyMap<string, NotificationProvider>;\n\nexport function isObject(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\n/** Unknown providers never fall back to Telegram. Raw settings remain storage-owned. */\nexport function validateDestination(value: unknown, providers: Providers): Destination | undefined {\n if (!isObject(value) || typeof value.provider !== \"string\") return undefined;\n return providers.get(value.provider)?.validate(value);\n}\n\nexport async function deliver(\n providers: Providers,\n destination: Destination,\n notification: Notification,\n signal: AbortSignal,\n): Promise<DeliveryResult> {\n if (signal.aborted) return { state: \"cancelled\", code: \"cancelled\" };\n const provider = providers.get(destination.provider);\n if (!provider) return { state: \"failed\", code: \"unsupported-provider\" };\n if (!provider.validate(destination)) return { state: \"failed\", code: \"invalid-destination\" };\n try {\n return await provider.send(destination, notification, signal);\n } catch {\n return signal.aborted ? { state: \"cancelled\", code: \"cancelled\" } : { state: \"failed\", code: \"network\" };\n }\n}\n"],
5
+ "mappings": ";;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,SAAS,gBAAgB;AAClC,SAAS,UAAU,SAAS,YAAY,WAAW;AACnD,SAAS,4BAA4B;;;ACF9B,SAAS,SAAS,MAAc,OAAuB;AAC5D,MAAI,KAAK,UAAU,MAAO,QAAO;AACjC,MAAI,SAAS;AACb,aAAW,aAAa,MAAM;AAC5B,QAAI,OAAO,SAAS,UAAU,SAAS,QAAQ,EAAG;AAClD,cAAU;AAAA,EACZ;AACA,SAAO,GAAG,MAAM;AAClB;;;ADOO,IAAM,WAAW,CAAC,UAAkB,SAAS,qBAAqB,KAAK,EAAE,WAAW,KAAK,QAAG,GAAG,GAAG;AAClG,SAAS,YAAY,KAAqB;AAC/C,QAAM,OAAO,SAAS,GAAG;AACzB,QAAM,OAAO,SAAS,QAAQ,CAAC;AAC/B,SAAO,SAAS,OAAO,MAAM,KAAK,WAAW,GAAG,IAAI,GAAG,GAAG,EAAE,IAAI,IAAI,KAAK,MAAM,KAAK,MAAM,CAAC,KAAK;AAClG;AACA,SAAS,IAAI,KAAa,MAAgB,QAAkD;AAC1F,SAAO,IAAI,QAAQ,CAACA,aAAY;AAC9B;AAAA,MACE;AAAA,MACA,CAAC,MAAM,KAAK,aAAa,GAAG,IAAI;AAAA,MAChC,EAAE,QAAQ,SAAS,MAAM,WAAW,MAAM,UAAU,QAAQ,aAAa,KAAK;AAAA,MAC9E,CAAC,OAAO,WAAWA,SAAQ,QAAQ,SAAY,OAAO,KAAK,CAAC;AAAA,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