opencode-gchat-notification-plugin 0.0.0-stage → 1.0.2

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Garrick Lam
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,91 @@
1
- # Temporary Holding Version
1
+ # opencode-gchat-notification-plugin
2
+
3
+ An [OpenCode](https://opencode.ai) V2 server plugin that sends push notifications to
4
+ **Google Chat** when a session finishes its task, fails, or is blocked waiting for you —
5
+ so you can context-switch away during long agent runs.
6
+
7
+ ## Notifications
8
+
9
+ | Event | Card |
10
+ | --- | --- |
11
+ | Task completed (`session.execution.succeeded`) | ✅ **Task Completed** — with elapsed time when known |
12
+ | Permission prompt (`permission.asked`) | ⚠️ **Approval Required** — action + resources |
13
+ | Clarification question (`question` tool) | 💬 **User Input Needed** — quotes the first question |
14
+ | Failure / interrupt (`session.execution.failed` / `.interrupted`) | 🛑 **Session Interrupted** — error message or reason |
15
+
16
+ Noise filters:
17
+
18
+ - Sub-agent sessions (child sessions with a `parentID`) are never notified.
19
+ - Sessions outside this project's directory tree are skipped, so per-project instances
20
+ don't double-notify.
21
+ - Short runs below `minDurationSec` don't ping.
22
+ - Repeated events inside `cooldownMs` are deduplicated.
23
+ - Timestamps honor `timeZone` (defaults to the host machine's local timezone).
24
+ - User-initiated interrupts (`reason: "user"`) are silent — you're already at the keyboard.
25
+ - A failed run doesn't also send a follow-up ✅.
26
+
27
+ ## Google Chat webhook
28
+
29
+ Create an incoming webhook for your space:
30
+ [Google Chat apps → Webhooks](https://developers.google.com/hangouts/chat/how-tos/webhooks).
31
+ Copy the resulting URL — it looks like
32
+ `https://chat.googleapis.com/v1/spaces/AAA…/messages?key=…&token=…`.
33
+
34
+ ## Install
35
+
36
+ ```shell
37
+ yarn add opencode-gchat-notification-plugin
38
+ ```
39
+
40
+ ## Configure
41
+
42
+ Add the plugin to `opencode.json(c)` (per project) or `~/.config/opencode/opencode.json(c)` (global):
43
+
44
+ ```jsonc
45
+ {
46
+ "$schema": "https://opencode.ai/config.json",
47
+ "plugins": [
48
+ {
49
+ "package": "opencode-gchat-notification-plugin",
50
+ "options": {
51
+ "webhookUrl": "https://chat.googleapis.com/v1/spaces/…",
52
+ "minDurationSec": 30,
53
+ "cooldownMs": 3000,
54
+ "timeZone": "Asia/Hong_Kong"
55
+ }
56
+ }
57
+ ]
58
+ }
59
+ ```
60
+
61
+ ### Options
62
+
63
+ | Option | Env fallback | Default | Meaning |
64
+ | --- | --- | --- | --- |
65
+ | `webhookUrl` | `OPENCODE_GCHAT_WEBHOOK_URL` | — | Google Chat webhook URL. Options win over env. Without it the plugin stays inert (one log line). |
66
+ | `minDurationSec` | `OPENCODE_GCHAT_MIN_DURATION_SEC` | `0` | Skip the ✅ notification for runs shorter than this. |
67
+ | `cooldownMs` | — | `3000` | Dedupe window per session + event kind. |
68
+ | `timeZone` | `OPENCODE_GCHAT_TIMEZONE` | host-local | IANA timezone (e.g. `Asia/Hong_Kong`) for card timestamps. Invalid values warn once at startup and fall back to host-local. When set, the time shows a short zone name (`14:32 HKT`). |
69
+
70
+ The webhook URL is a secret: prefer the env var (or options in a config file you don't commit)
71
+ over committing it to a shared repository.
72
+
73
+ ## Development
74
+
75
+ ```shell
76
+ yarn build # tsc --noEmit typecheck (OpenCode loads the TS source directly)
77
+ yarn test # jest
78
+ yarn lint # eslint
79
+ ```
80
+
81
+ This repo dogfoods the plugin: `.opencode/plugins/gchat-notify/index.ts` re-exports the
82
+ package default, so the plugin auto-loads for OpenCode sessions started in this directory.
83
+ It has no `options`, so set the webhook via the environment:
84
+
85
+ ```shell
86
+ export OPENCODE_GCHAT_WEBHOOK_URL="https://chat.googleapis.com/v1/spaces/…"
87
+ export OPENCODE_GCHAT_TIMEZONE="Asia/Hong_Kong"
88
+ ```
89
+
90
+ Publishing is automated by semantic-release through GitHub Actions on the default branch.
2
91
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
package/package.json CHANGED
@@ -1,6 +1,42 @@
1
1
  {
2
2
  "name": "opencode-gchat-notification-plugin",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.2",
4
+ "type": "module",
5
+ "exports": {
6
+ ".": "./src/index.ts"
7
+ },
8
+ "files": [
9
+ "src"
10
+ ],
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "git+https://github.com/garrick-lam/opencode-gchat-notification-plugin.git"
14
+ },
15
+ "bugs": "https://github.com/garrick-lam/opencode-gchat-notification-plugin/issues",
16
+ "homepage": "https://github.com/garrick-lam/opencode-gchat-notification-plugin#readme",
17
+ "author": "Garrick Lam",
18
+ "license": "MIT",
19
+ "scripts": {
20
+ "lint": "oxlint src tests",
21
+ "lint:fix": "oxlint --fix src tests",
22
+ "build": "tsc --noEmit",
23
+ "test": "jest",
24
+ "test:watch": "jest --watch",
25
+ "test:coverage": "jest --coverage"
26
+ },
27
+ "devDependencies": {
28
+ "@semantic-release/git": "^10.0.1",
29
+ "@semantic-release/github": "^12.0.11",
30
+ "@types/jest": "^29.5.1",
31
+ "@types/node": "^20.2.1",
32
+ "jest": "^29.5.0",
33
+ "oxlint": "^1.94.0",
34
+ "prettier": "^3.2.5",
35
+ "semantic-release": "^21.0.2",
36
+ "ts-jest": "^29.1.0",
37
+ "typescript": "*"
38
+ },
39
+ "dependencies": {
40
+ "@opencode/plugin": "^2.2.7"
41
+ }
42
+ }
package/src/config.ts ADDED
@@ -0,0 +1,55 @@
1
+ export interface ResolvedConfig {
2
+ readonly webhookUrl?: string;
3
+ readonly minDurationSec: number;
4
+ readonly cooldownMs: number;
5
+ readonly timeZone?: string;
6
+ }
7
+
8
+ function readString(value: unknown): string | undefined {
9
+ if (typeof value !== 'string') return undefined;
10
+ const trimmed = value.trim();
11
+ return trimmed.length > 0 ? trimmed : undefined;
12
+ }
13
+
14
+ function readNumber(value: unknown, fallback: number): number {
15
+ if (value === undefined || value === null) return fallback;
16
+ const parsed = Number(value);
17
+ return Number.isFinite(parsed) ? parsed : fallback;
18
+ }
19
+
20
+ function isValidTimeZone(tz: string): boolean {
21
+ try {
22
+ // Callable without `new`; invalid timeZone names throw RangeError.
23
+ Intl.DateTimeFormat('en-US', { timeZone: tz });
24
+ return true;
25
+ } catch {
26
+ return false;
27
+ }
28
+ }
29
+
30
+ export function resolveConfig(
31
+ options: Record<string, unknown> | undefined,
32
+ env: NodeJS.ProcessEnv,
33
+ ): ResolvedConfig {
34
+ const opts = options ?? {};
35
+ const rawTimeZone =
36
+ readString(opts.timeZone) ?? readString(env.OPENCODE_GCHAT_TIMEZONE);
37
+ let timeZone = rawTimeZone;
38
+ if (rawTimeZone !== undefined && !isValidTimeZone(rawTimeZone)) {
39
+ // eslint-disable-next-line no-console -- a plugin's only logging channel
40
+ console.warn(
41
+ `[gchat-notify] Invalid timeZone "${rawTimeZone}"; using host-local time`,
42
+ );
43
+ timeZone = undefined;
44
+ }
45
+ return {
46
+ webhookUrl:
47
+ readString(opts.webhookUrl) ?? readString(env.OPENCODE_GCHAT_WEBHOOK_URL),
48
+ minDurationSec: readNumber(
49
+ opts.minDurationSec,
50
+ readNumber(env.OPENCODE_GCHAT_MIN_DURATION_SEC, 0),
51
+ ),
52
+ cooldownMs: readNumber(opts.cooldownMs, 3000),
53
+ timeZone,
54
+ };
55
+ }
@@ -0,0 +1,111 @@
1
+ export interface GoogleChatCardPayload {
2
+ text: string;
3
+ cardsV2: Array<{
4
+ cardId: string;
5
+ card: {
6
+ header: {
7
+ title: string;
8
+ subtitle: string;
9
+ };
10
+ sections: Array<{
11
+ widgets: Array<
12
+ | {
13
+ decoratedText: {
14
+ topLabel: string;
15
+ text: string;
16
+ wrapText?: boolean;
17
+ };
18
+ }
19
+ | { textParagraph: { text: string; textSyntax: 'MARKDOWN' } }
20
+ >;
21
+ }>;
22
+ };
23
+ }>;
24
+ }
25
+
26
+ export interface CardParams {
27
+ readonly badge: string;
28
+ readonly title: string;
29
+ readonly sessionTitle: string;
30
+ readonly details: string;
31
+ readonly timestamp: string;
32
+ readonly codeBlock?: boolean;
33
+ readonly codeDetails?: string;
34
+ }
35
+
36
+ function fenceCodeBlock(details: string): string {
37
+ const longestRun =
38
+ details.match(/`+/g)?.reduce((max, run) => Math.max(max, run.length), 0) ??
39
+ 0;
40
+ const fence = '`'.repeat(Math.max(3, longestRun + 1));
41
+ return `${fence}\n${details}\n${fence}`;
42
+ }
43
+
44
+ export function buildCardPayload(
45
+ params: CardParams & { readonly projectName: string },
46
+ ): GoogleChatCardPayload {
47
+ return {
48
+ text: `${params.badge} [${params.projectName}] ${params.title}`,
49
+ cardsV2: [
50
+ {
51
+ cardId: `opencode-${Date.now()}`,
52
+ card: {
53
+ header: {
54
+ title: params.title,
55
+ subtitle: `Project: ${params.projectName} • ${params.timestamp}`,
56
+ },
57
+ sections: [
58
+ {
59
+ widgets: [
60
+ {
61
+ decoratedText: {
62
+ topLabel: 'Session',
63
+ text: params.sessionTitle,
64
+ },
65
+ },
66
+ params.codeBlock
67
+ ? {
68
+ textParagraph: {
69
+ text: params.codeDetails
70
+ ? `${params.details}\n${fenceCodeBlock(params.codeDetails)}`
71
+ : params.details,
72
+ textSyntax: 'MARKDOWN' as const,
73
+ },
74
+ }
75
+ : {
76
+ decoratedText: {
77
+ topLabel: 'Details',
78
+ text: params.details,
79
+ wrapText: true,
80
+ },
81
+ },
82
+ ],
83
+ },
84
+ ],
85
+ },
86
+ },
87
+ ],
88
+ };
89
+ }
90
+
91
+ export async function sendCard(
92
+ webhookUrl: string,
93
+ payload: GoogleChatCardPayload,
94
+ ): Promise<void> {
95
+ try {
96
+ const response = await fetch(webhookUrl, {
97
+ method: 'POST',
98
+ headers: { 'Content-Type': 'application/json; charset=UTF-8' },
99
+ body: JSON.stringify(payload),
100
+ });
101
+ if (!response.ok) {
102
+ // eslint-disable-next-line no-console -- a plugin's only logging channel
103
+ console.error(
104
+ `[gchat-notify] Webhook error: ${response.status} ${response.statusText}`,
105
+ );
106
+ }
107
+ } catch (error) {
108
+ // eslint-disable-next-line no-console -- a plugin's only logging channel
109
+ console.error('[gchat-notify] Failed to send notification:', error);
110
+ }
111
+ }
package/src/index.ts ADDED
@@ -0,0 +1,122 @@
1
+ import { basename } from 'node:path';
2
+ // eslint-disable-next-line import/no-unresolved -- resolved via tsconfig "paths" (package is exports-only, no "main")
3
+ import { Plugin } from '@opencode/plugin';
4
+ import { resolveConfig } from './config';
5
+ import { buildCardPayload, sendCard } from './google-chat';
6
+ import { Notifier } from './notifier';
7
+
8
+ export default Plugin.define({
9
+ id: 'gchat-notify',
10
+ async setup(ctx) {
11
+ const config = resolveConfig(
12
+ ctx.options as Record<string, unknown>,
13
+ process.env,
14
+ );
15
+ if (!config.webhookUrl) {
16
+ // eslint-disable-next-line no-console -- a plugin's only logging channel
17
+ console.log(
18
+ '[gchat-notify] No webhook URL configured (options.webhookUrl or OPENCODE_GCHAT_WEBHOOK_URL); notifications disabled',
19
+ );
20
+ return;
21
+ }
22
+ const { webhookUrl } = config;
23
+ const projectName = basename(ctx.location.directory);
24
+
25
+ const notifier = new Notifier({
26
+ config,
27
+ projectName,
28
+ locationDirectory: ctx.location.directory,
29
+ now: () => Date.now(),
30
+ getSession: async (sessionID) => {
31
+ try {
32
+ const session = await ctx.session.get({ sessionID });
33
+ return {
34
+ parentID: session.parentID,
35
+ title: session.title,
36
+ location: session.location
37
+ ? { directory: session.location.directory }
38
+ : undefined,
39
+ };
40
+ } catch {
41
+ return undefined;
42
+ }
43
+ },
44
+ send: async (request) => {
45
+ try {
46
+ await sendCard(
47
+ webhookUrl,
48
+ buildCardPayload({ ...request, projectName }),
49
+ );
50
+ } catch (error) {
51
+ // eslint-disable-next-line no-console -- a plugin's only logging channel
52
+ console.error('[gchat-notify]', error);
53
+ }
54
+ },
55
+ });
56
+
57
+ const controller = new AbortController();
58
+ const consume = async (): Promise<void> => {
59
+ // eslint-disable-next-line no-restricted-syntax -- for-await is the idiomatic async-iterator consumption
60
+ for await (const event of ctx.event.subscribe({
61
+ types: [
62
+ 'session.execution.started',
63
+ 'session.execution.succeeded',
64
+ 'session.execution.failed',
65
+ 'session.execution.interrupted',
66
+ 'permission.asked',
67
+ ],
68
+ signal: controller.signal,
69
+ })) {
70
+ switch (event.type) {
71
+ case 'session.execution.started':
72
+ notifier.onExecutionStarted(event.data.sessionID);
73
+ break;
74
+ case 'session.execution.succeeded':
75
+ await notifier.onIdle(event.data.sessionID);
76
+ break;
77
+ case 'session.execution.failed':
78
+ await notifier.onFailed(event.data.sessionID, event.data.error);
79
+ break;
80
+ case 'session.execution.interrupted':
81
+ await notifier.onInterrupted(
82
+ event.data.sessionID,
83
+ event.data.reason,
84
+ );
85
+ break;
86
+ case 'permission.asked':
87
+ await notifier.onPermissionAsked(
88
+ event.data.sessionID,
89
+ event.data.action,
90
+ event.data.resources,
91
+ );
92
+ break;
93
+ default:
94
+ break;
95
+ }
96
+ }
97
+ };
98
+ consume().catch((error: unknown) => {
99
+ // eslint-disable-next-line no-console -- a plugin's only logging channel
100
+ console.error('[gchat-notify] Event stream failed:', error);
101
+ });
102
+
103
+ const toolRegistration = await ctx.tool.hook('execute.before', (event) => {
104
+ if (event.tool !== 'question') return;
105
+ try {
106
+ const input = event.input as
107
+ | { questions?: Array<{ question?: string }> }
108
+ | undefined;
109
+ notifier.onQuestion(event.sessionID, input?.questions ?? []);
110
+ } catch (error) {
111
+ // eslint-disable-next-line no-console -- a plugin's only logging channel
112
+ console.error('[gchat-notify]', error);
113
+ }
114
+ });
115
+
116
+ // eslint-disable-next-line consistent-return -- plugin API: cleanup is returned only when active
117
+ return () => {
118
+ controller.abort();
119
+ toolRegistration.dispose().catch(() => undefined);
120
+ };
121
+ },
122
+ });
@@ -0,0 +1,224 @@
1
+ import type { ResolvedConfig } from './config';
2
+
3
+ export interface SessionSummary {
4
+ readonly parentID?: string;
5
+ readonly title?: string;
6
+ readonly location?: { readonly directory: string };
7
+ }
8
+
9
+ export interface NotificationRequest {
10
+ readonly badge: string;
11
+ readonly title: string;
12
+ readonly sessionTitle: string;
13
+ readonly details: string;
14
+ readonly timestamp: string;
15
+ readonly codeBlock?: boolean;
16
+ readonly codeDetails?: string;
17
+ }
18
+
19
+ export interface NotifierDeps {
20
+ readonly config: ResolvedConfig;
21
+ readonly projectName: string;
22
+ readonly locationDirectory?: string;
23
+ readonly now: () => number;
24
+ readonly getSession: (
25
+ sessionID: string,
26
+ ) => Promise<SessionSummary | undefined>;
27
+ readonly send: (request: NotificationRequest) => Promise<void>;
28
+ }
29
+
30
+ function sameLocationTree(
31
+ sessionDirectory: string,
32
+ pluginDirectory: string | undefined,
33
+ ): boolean {
34
+ if (!pluginDirectory) return true;
35
+ return (
36
+ sessionDirectory === pluginDirectory ||
37
+ sessionDirectory.startsWith(`${pluginDirectory}/`) ||
38
+ pluginDirectory.startsWith(`${sessionDirectory}/`)
39
+ );
40
+ }
41
+
42
+ export class Notifier {
43
+ private readonly busySince = new Map<string, number>();
44
+
45
+ private readonly lastNotified = new Map<string, number>();
46
+
47
+ private readonly lastOutcome = new Map<string, 'failed'>();
48
+
49
+ constructor(private readonly deps: NotifierDeps) {}
50
+
51
+ onExecutionStarted(sessionID: string): void {
52
+ this.busySince.set(sessionID, this.deps.now());
53
+ this.lastOutcome.delete(sessionID);
54
+ }
55
+
56
+ async onIdle(sessionID: string): Promise<void> {
57
+ try {
58
+ if (this.lastOutcome.get(sessionID) === 'failed') {
59
+ this.lastOutcome.delete(sessionID);
60
+ this.busySince.delete(sessionID);
61
+ return;
62
+ }
63
+ const startedAt = this.busySince.get(sessionID);
64
+ this.busySince.delete(sessionID);
65
+ if (startedAt !== undefined && this.deps.config.minDurationSec > 0) {
66
+ const elapsedMs = this.deps.now() - startedAt;
67
+ if (elapsedMs < this.deps.config.minDurationSec * 1000) return;
68
+ }
69
+ const elapsedSec =
70
+ startedAt !== undefined
71
+ ? Math.max(1, Math.round((this.deps.now() - startedAt) / 1000))
72
+ : null;
73
+ const details = elapsedSec
74
+ ? `Agent finished processing (${elapsedSec}s) and is ready for your next prompt.`
75
+ : 'Agent finished processing and is ready for your next prompt.';
76
+ await this.emit(`idle:${sessionID}`, sessionID, {
77
+ badge: '✅',
78
+ title: 'Task Completed',
79
+ details,
80
+ });
81
+ } catch (error) {
82
+ this.logFailure(error);
83
+ }
84
+ }
85
+
86
+ async onFailed(
87
+ sessionID: string,
88
+ error: { readonly message?: string },
89
+ ): Promise<void> {
90
+ try {
91
+ this.lastOutcome.set(sessionID, 'failed');
92
+ await this.emit(`err:${sessionID}`, sessionID, {
93
+ badge: '🛑',
94
+ title: 'Session Interrupted',
95
+ details: error.message || 'An unexpected error stopped execution.',
96
+ });
97
+ } catch (err) {
98
+ this.logFailure(err);
99
+ }
100
+ }
101
+
102
+ async onInterrupted(sessionID: string, reason: string): Promise<void> {
103
+ try {
104
+ this.lastOutcome.set(sessionID, 'failed');
105
+ if (reason === 'user') return;
106
+ await this.emit(`err:${sessionID}`, sessionID, {
107
+ badge: '🛑',
108
+ title: 'Session Interrupted',
109
+ details: `Session was interrupted: ${reason}.`,
110
+ });
111
+ } catch (err) {
112
+ this.logFailure(err);
113
+ }
114
+ }
115
+
116
+ async onPermissionAsked(
117
+ sessionID: string,
118
+ action: string,
119
+ resources: readonly string[],
120
+ ): Promise<void> {
121
+ try {
122
+ const hasResources = resources.length > 0;
123
+ await this.emit(`perm:${sessionID}`, sessionID, {
124
+ badge: '⚠️',
125
+ title: 'Approval Required',
126
+ details: hasResources
127
+ ? `Permission requested for ${action}:`
128
+ : `Permission requested for ${action}.`,
129
+ codeBlock: true,
130
+ codeDetails: hasResources ? resources.join('\n') : undefined,
131
+ });
132
+ } catch (err) {
133
+ this.logFailure(err);
134
+ }
135
+ }
136
+
137
+ async onQuestion(
138
+ sessionID: string,
139
+ questions: readonly { readonly question?: string }[],
140
+ ): Promise<void> {
141
+ try {
142
+ const first = questions[0]?.question;
143
+ const details = first
144
+ ? `OpenCode asked: "${first}"`
145
+ : 'OpenCode is waiting for your answer to a clarification question.';
146
+ await this.emit(`question:${sessionID}`, sessionID, {
147
+ badge: '💬',
148
+ title: 'User Input Needed',
149
+ details,
150
+ });
151
+ } catch (err) {
152
+ this.logFailure(err);
153
+ }
154
+ }
155
+
156
+ /**
157
+ * Resolves the session title to display, or null when the notification
158
+ * should be dropped (sub-agent session, or session outside this location tree).
159
+ */
160
+ private async gate(sessionID: string): Promise<string | null> {
161
+ let session: SessionSummary | undefined;
162
+ try {
163
+ session = await this.deps.getSession(sessionID);
164
+ } catch {
165
+ session = undefined;
166
+ }
167
+ if (!session) return sessionID.slice(0, 12);
168
+ if (session.parentID) return null;
169
+ const sessionDirectory = session.location?.directory;
170
+ if (
171
+ sessionDirectory &&
172
+ !sameLocationTree(sessionDirectory, this.deps.locationDirectory)
173
+ ) {
174
+ return null;
175
+ }
176
+ return session.title || sessionID.slice(0, 12);
177
+ }
178
+
179
+ private passesDedupe(key: string): boolean {
180
+ const now = this.deps.now();
181
+ const previous = this.lastNotified.get(key);
182
+ if (previous !== undefined && now - previous < this.deps.config.cooldownMs)
183
+ return false;
184
+ this.lastNotified.set(key, now);
185
+ return true;
186
+ }
187
+
188
+ private async emit(
189
+ key: string,
190
+ sessionID: string,
191
+ opts: {
192
+ badge: string;
193
+ title: string;
194
+ details: string;
195
+ codeBlock?: boolean;
196
+ codeDetails?: string;
197
+ },
198
+ ): Promise<void> {
199
+ const sessionTitle = await this.gate(sessionID);
200
+ if (sessionTitle === null) return;
201
+ if (!this.passesDedupe(key)) return;
202
+ const timestamp = new Date(this.deps.now()).toLocaleTimeString(
203
+ [],
204
+ this.deps.config.timeZone
205
+ ? {
206
+ hour: '2-digit',
207
+ minute: '2-digit',
208
+ timeZone: this.deps.config.timeZone,
209
+ timeZoneName: 'short',
210
+ }
211
+ : { hour: '2-digit', minute: '2-digit' },
212
+ );
213
+ try {
214
+ await this.deps.send({ sessionTitle, timestamp, ...opts });
215
+ } catch (error) {
216
+ this.logFailure(error);
217
+ }
218
+ }
219
+
220
+ private logFailure(error: unknown): void {
221
+ // eslint-disable-next-line no-console -- a plugin's only logging channel
222
+ console.error('[gchat-notify]', error);
223
+ }
224
+ }