@kkcode-app/agent 1.0.11 → 1.1.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.
@@ -0,0 +1,189 @@
1
+ /**
2
+ * [INPUT]: 依赖 OpenCode 1 PluginInput/client 与 notification-core 共享上报内核
3
+ * [OUTPUT]: 默认导出 OpenCode 1 函数插件,处理 idle/error/permission/question 事件
4
+ * [POS]: @kkcode-app/agent 的 ./server 与 ./plugin 兼容入口;不承载 OpenCode 2 setup API
5
+ * [PROTOCOL]: 变更时更新此头部,然后检查 CLAUDE.md
6
+ */
7
+
8
+ import {
9
+ compactText,
10
+ debugLog,
11
+ errorSummary,
12
+ reportNotification,
13
+ type NotifyEventType,
14
+ } from "./notification-core.js";
15
+
16
+ type OpenCode1Event = {
17
+ type: string;
18
+ properties: {
19
+ sessionID?: string;
20
+ id?: string;
21
+ requestID?: string;
22
+ permission?: string;
23
+ patterns?: string[];
24
+ description?: string;
25
+ message?: string;
26
+ error?: unknown;
27
+ metadata?: { description?: string };
28
+ questions?: {
29
+ question?: string;
30
+ header?: string;
31
+ options?: { label?: string; description?: string }[];
32
+ }[];
33
+ };
34
+ };
35
+
36
+ function describePermission(properties: OpenCode1Event["properties"]): string {
37
+ const permission = compactText(properties.permission, 80) || "action";
38
+ const description = compactText(properties.description ?? properties.metadata?.description);
39
+ const patterns = (Array.isArray(properties.patterns) ? properties.patterns : [])
40
+ .map((pattern) => compactText(pattern, 160))
41
+ .filter(Boolean)
42
+ .slice(0, 3)
43
+ .join("; ");
44
+ return compactText(
45
+ [
46
+ `Permission: ${permission}`,
47
+ description && `Action: ${description}`,
48
+ patterns && `Scope: ${patterns}`,
49
+ ]
50
+ .filter(Boolean)
51
+ .join("\n"),
52
+ );
53
+ }
54
+
55
+ function describeQuestion(properties: OpenCode1Event["properties"]): string {
56
+ const question = properties.questions?.[0];
57
+ if (!question) return "KKCode is waiting for your answer";
58
+ const header = compactText(question.header, 100);
59
+ const prompt = compactText(question.question, 300);
60
+ const options = (Array.isArray(question.options) ? question.options : [])
61
+ .map((option) => compactText(option.label, 80))
62
+ .filter(Boolean)
63
+ .slice(0, 4)
64
+ .join(", ");
65
+ return compactText(
66
+ [
67
+ header && `Topic: ${header}`,
68
+ prompt && `Question: ${prompt}`,
69
+ options && `Options: ${options}`,
70
+ ]
71
+ .filter(Boolean)
72
+ .join("\n"),
73
+ );
74
+ }
75
+
76
+ function rememberRequest(seen: Set<string>, key: string): boolean {
77
+ if (seen.has(key)) return false;
78
+ seen.add(key);
79
+ if (seen.size > 1_024) seen.delete(seen.values().next().value!);
80
+ return true;
81
+ }
82
+
83
+ const KKCodeOpenCode1NotifyPlugin = async ({ client, directory, project }: any) => {
84
+ const projectLabel =
85
+ project?.name || directory?.split(/[\\/]/u).filter(Boolean).at(-1) || "KKCode";
86
+ const erroredSessions = new Set<string>();
87
+ const notifiedPermission = new Set<string>();
88
+ const notifiedQuestion = new Set<string>();
89
+
90
+ await debugLog(`v1 plugin loaded | project=${projectLabel}`);
91
+
92
+ async function getSessionInfo(
93
+ sessionID: string,
94
+ ): Promise<{ title?: string; isSubSession: boolean }> {
95
+ try {
96
+ const result = await client.session.get({ path: { id: sessionID } });
97
+ return {
98
+ title: result?.data?.title?.trim() || undefined,
99
+ isSubSession: !!result?.data?.parentID,
100
+ };
101
+ } catch (error) {
102
+ await debugLog(`v1 getSessionInfo FAILED | session=${sessionID} | ${error}`);
103
+ return { title: undefined, isSubSession: false };
104
+ }
105
+ }
106
+
107
+ async function report(
108
+ event: OpenCode1Event,
109
+ sessionID: string,
110
+ type: NotifyEventType,
111
+ summary?: string,
112
+ ): Promise<void> {
113
+ const info = await getSessionInfo(sessionID);
114
+ await reportNotification({
115
+ sessionID,
116
+ type,
117
+ projectLabel,
118
+ summary,
119
+ sessionTitle: info.title,
120
+ });
121
+ await debugLog(`v1 ${event.type} REPORTED | ${sessionID} | type=${type}`);
122
+ }
123
+
124
+ return {
125
+ event: async ({ event }: { event: OpenCode1Event }) => {
126
+ if (
127
+ event.type !== "session.idle" &&
128
+ event.type !== "session.error" &&
129
+ event.type !== "permission.asked" &&
130
+ event.type !== "question.asked"
131
+ ) {
132
+ return;
133
+ }
134
+ try {
135
+ const sessionID = event.properties.sessionID;
136
+ if (!sessionID) return;
137
+
138
+ if (event.type === "session.idle") {
139
+ if (erroredSessions.delete(sessionID)) return;
140
+ const info = await getSessionInfo(sessionID);
141
+ await reportNotification({
142
+ sessionID,
143
+ type: info.isSubSession ? "sub_session.completed" : "session.completed",
144
+ projectLabel,
145
+ sessionTitle: info.title,
146
+ });
147
+ return;
148
+ }
149
+ if (event.type === "session.error") {
150
+ erroredSessions.add(sessionID);
151
+ await report(
152
+ event,
153
+ sessionID,
154
+ "session.error",
155
+ errorSummary(event.properties.error ?? event.properties),
156
+ );
157
+ return;
158
+ }
159
+
160
+ const requestKey = `${sessionID}:${event.properties.id ?? event.properties.requestID ?? ""}`;
161
+ const seen = event.type === "permission.asked" ? notifiedPermission : notifiedQuestion;
162
+ if (!rememberRequest(seen, requestKey)) return;
163
+ await report(
164
+ event,
165
+ sessionID,
166
+ event.type === "permission.asked" ? "permission.asked" : "question.asked",
167
+ event.type === "permission.asked"
168
+ ? describePermission(event.properties)
169
+ : describeQuestion(event.properties),
170
+ );
171
+ } catch (error) {
172
+ const message = error instanceof Error ? error.message : String(error);
173
+ await debugLog(`v1 HANDLER ERROR | type=${event.type} | ${message}`);
174
+ await client.app
175
+ .log({
176
+ body: {
177
+ service: "kkcode",
178
+ level: "warn",
179
+ message: "Could not report KKCode session notification.",
180
+ extra: { error: message },
181
+ },
182
+ })
183
+ .catch(() => {});
184
+ }
185
+ },
186
+ };
187
+ };
188
+
189
+ export default KKCodeOpenCode1NotifyPlugin;
package/src/plugin.ts CHANGED
@@ -1,294 +1,232 @@
1
1
  /**
2
- * [INPUT]: 依赖 node:fs 的 appendFile 做追加写日志,依赖 Bun.file 读取配置,依赖 fetch 上报事件
3
- * [OUTPUT]: 对外提供 KKCodeIOSNotifyPlugin(default export),OpenCode 加载后接收 session/permission/question 事件
4
- * [POS]: cli/ 的 OpenCode 插件入口,被 src/config.ts 注册、被 package.json exports 暴露;调试日志写入 ~/.config/kkcode/events-debug.log
5
- * 始终注册事件回调;notify.json 的读取推迟到每次事件触发时(loadConfig),无需重启 OpenCode 即可热加载新 token
2
+ * [INPUT]: 依赖 OpenCode 2 Promise plugin context 的 location/session/event API 与 notification-core
3
+ * [OUTPUT]: 默认导出 `{ id, setup }` OpenCode 2 插件,按 execution/permission/Form 事件上报推送
4
+ * [POS]: @kkcode-app/agent 默认插件入口;OpenCode 1 由独立 ./server export 加载 plugin-v1.ts
6
5
  * [PROTOCOL]: 变更时更新此头部,然后检查 CLAUDE.md
7
6
  */
8
7
 
9
- import fs from "node:fs";
8
+ import { basename, normalize } from "node:path";
10
9
 
11
- type AgentConfig = {
12
- node_id: string;
13
- node_secret: string;
14
- service_id: string;
15
- api_url?: string;
16
- };
17
- type NotifyEventType =
18
- | "session.completed"
19
- | "sub_session.completed"
20
- | "session.error"
21
- | "permission.asked"
22
- | "question.asked";
23
- type OpenCodeEvent = {
10
+ import {
11
+ compactText,
12
+ debugLog,
13
+ errorSummary,
14
+ reportNotification,
15
+ type NotificationIntent,
16
+ } from "./notification-core.js";
17
+
18
+ type V2Location = { directory?: string; workspaceID?: string };
19
+ type V2Event = {
20
+ id?: string;
21
+ created?: number;
24
22
  type: string;
25
- properties: {
26
- sessionID?: string;
27
- id?: string;
28
- requestID?: string;
29
- permission?: string;
30
- patterns?: string[];
31
- description?: string;
32
- message?: string;
33
- error?: string;
34
- metadata?: { description?: string };
35
- questions?: {
36
- question?: string;
37
- header?: string;
38
- options?: { label?: string; description?: string }[];
39
- }[];
40
- };
23
+ data?: Record<string, unknown>;
24
+ location?: V2Location;
41
25
  };
42
- type NotifyPayload = {
43
- event_id: string;
44
- service_id: string;
45
- session_id: string;
46
- type: NotifyEventType;
47
- project_label: string;
48
- occurred_at: string;
49
- session_title?: string;
50
- summary?: string;
51
- };
52
-
53
- const DEFAULT_API_URL = "https://api.kkcode.app";
54
- const MAX_NOTIFICATION_CONTEXT_LENGTH = 480;
55
- const configPath =
56
- process.env.KKCODE_AGENT_CONFIG ??
57
- `${process.env.XDG_CONFIG_HOME ?? `${process.env.HOME ?? "~"}/.config`}/kkcode/agent.json`;
58
- const debugLogPath =
59
- process.env.KKCODE_DEBUG_LOG ??
60
- `${process.env.XDG_CONFIG_HOME ?? `${process.env.HOME ?? "~"}/.config`}/kkcode/events-debug.log`;
61
26
 
62
- async function debugLog(message: string): Promise<void> {
63
- try {
64
- const line = `[${new Date().toISOString()}] ${message}\n`;
65
- await fs.promises.appendFile(debugLogPath, line);
66
- } catch {}
67
- }
27
+ type V2Context = {
28
+ app: { version?: string };
29
+ location: V2Location & { project?: { id?: string; canonical?: string } };
30
+ event: { subscribe(options?: { signal?: AbortSignal }): AsyncIterable<V2Event> };
31
+ session: { get(input: { sessionID: string }): Promise<unknown> };
32
+ };
68
33
 
69
- async function loadConfig(): Promise<AgentConfig | null> {
70
- try {
71
- const config = (await Bun.file(configPath).json()) as AgentConfig;
72
- if (!config.node_secret || !config.service_id) return null;
73
- return config;
74
- } catch {
75
- return null;
76
- }
77
- }
34
+ type SessionInfo = { title?: string; parentID?: string };
78
35
 
79
- async function reportEvent(
80
- config: AgentConfig,
81
- sessionId: string,
82
- type: NotifyEventType,
83
- projectLabel: string,
84
- summary?: string,
85
- sessionTitle?: string,
86
- ): Promise<void> {
87
- const controller = new AbortController();
88
- const timeout = setTimeout(() => controller.abort(), 3_000);
89
- try {
90
- const payload: NotifyPayload = {
91
- event_id: crypto.randomUUID(),
92
- service_id: config.service_id,
93
- session_id: sessionId,
94
- type,
95
- project_label: projectLabel,
96
- occurred_at: new Date().toISOString(),
97
- };
98
- if (summary) payload.summary = summary;
99
- if (sessionTitle) payload.session_title = sessionTitle;
100
- const apiUrl = `${config.api_url ?? DEFAULT_API_URL}/v1/notification-events`;
101
- const response = await fetch(apiUrl, {
102
- method: "POST",
103
- signal: controller.signal,
104
- headers: {
105
- Authorization: `Bearer ${config.node_secret}`,
106
- "Content-Type": "application/json",
107
- },
108
- body: JSON.stringify(payload),
109
- });
110
- if (!response.ok) throw new Error(`Notification API returned ${response.status}`);
111
- } finally {
112
- clearTimeout(timeout);
113
- }
36
+ function record(value: unknown): Record<string, unknown> {
37
+ return value && typeof value === "object" && !Array.isArray(value)
38
+ ? (value as Record<string, unknown>)
39
+ : {};
114
40
  }
115
41
 
116
- function compactText(value: unknown, maxLength = MAX_NOTIFICATION_CONTEXT_LENGTH): string {
117
- return typeof value === "string" ? value.replace(/\s+/gu, " ").trim().slice(0, maxLength) : "";
42
+ function eventBelongsToLocation(event: V2Event, location: V2Location): boolean {
43
+ const eventDirectory = event.location?.directory;
44
+ const pluginDirectory = location.directory;
45
+ if (!eventDirectory || !pluginDirectory) return false;
46
+ if (normalize(eventDirectory) !== normalize(pluginDirectory)) return false;
47
+ return (
48
+ !event.location?.workspaceID ||
49
+ !location.workspaceID ||
50
+ event.location.workspaceID === location.workspaceID
51
+ );
118
52
  }
119
53
 
120
- function describePermission(properties: OpenCodeEvent["properties"]): string {
121
- const permission = compactText(properties.permission, 80) || "action";
122
- const description = compactText(properties.description ?? properties.metadata?.description);
123
- const patterns = (Array.isArray(properties.patterns) ? properties.patterns : [])
124
- .map((pattern) => compactText(pattern, 160))
54
+ function permissionSummary(data: Record<string, unknown>): string {
55
+ const action = compactText(data.action ?? data.permission, 80) || "action";
56
+ const message = compactText(data.message ?? record(data.metadata).description);
57
+ const resources = (Array.isArray(data.resources) ? data.resources : [])
58
+ .map((value) => compactText(value, 160))
125
59
  .filter(Boolean)
126
60
  .slice(0, 3)
127
61
  .join("; ");
128
62
  return compactText(
129
- [
130
- `Permission: ${permission}`,
131
- description && `Action: ${description}`,
132
- patterns && `Scope: ${patterns}`,
133
- ]
63
+ [`Permission: ${action}`, message && `Action: ${message}`, resources && `Scope: ${resources}`]
134
64
  .filter(Boolean)
135
65
  .join("\n"),
136
66
  );
137
67
  }
138
68
 
139
- function describeQuestion(properties: OpenCodeEvent["properties"]): string {
140
- const question = properties.questions?.[0];
141
- if (!question) return "KKCode is waiting for your answer";
142
- const header = compactText(question.header, 100);
143
- const prompt = compactText(question.question, 300);
144
- const options = (Array.isArray(question.options) ? question.options : [])
145
- .map((option) => compactText(option.label, 80))
69
+ function questionSummary(data: Record<string, unknown>): string | undefined {
70
+ const form = record(data.form);
71
+ if (record(form.metadata).kind !== "question") return undefined;
72
+ const fields = (Array.isArray(form.fields) ? form.fields : [])
73
+ .map(record)
74
+ .filter((field) => /^q\d+$/u.test(String(field.key ?? "")))
75
+ .sort((a, b) => Number(String(a.key).slice(1)) - Number(String(b.key).slice(1)));
76
+ const first = fields[0];
77
+ if (!first) return "KKCode is waiting for your answer";
78
+ const options = (Array.isArray(first.options) ? first.options : [])
79
+ .map((option) => compactText(record(option).label, 80))
146
80
  .filter(Boolean)
147
81
  .slice(0, 4)
148
82
  .join(", ");
83
+ const topic = compactText(first.title, 100);
84
+ const prompt = compactText(first.description, 300);
149
85
  return compactText(
150
86
  [
151
- header && `Topic: ${header}`,
87
+ topic && `Topic: ${topic}`,
152
88
  prompt && `Question: ${prompt}`,
153
89
  options && `Options: ${options}`,
90
+ fields.length > 1 && `${fields.length} questions`,
154
91
  ]
155
92
  .filter(Boolean)
156
93
  .join("\n"),
157
94
  );
158
95
  }
159
96
 
160
- function describeError(properties: OpenCodeEvent["properties"]): string | undefined {
161
- const detail = compactText(properties.error ?? properties.message ?? properties.description);
162
- return detail || undefined;
97
+ function sessionIDOf(event: V2Event): string | undefined {
98
+ const data = event.data ?? {};
99
+ if (typeof data.sessionID === "string") return data.sessionID;
100
+ const form = record(data.form);
101
+ return typeof form.sessionID === "string" ? form.sessionID : undefined;
102
+ }
103
+
104
+ function requestIDOf(event: V2Event): string | undefined {
105
+ const data = event.data ?? {};
106
+ if (typeof data.id === "string") return data.id;
107
+ if (typeof data.requestID === "string") return data.requestID;
108
+ const form = record(data.form);
109
+ return typeof form.id === "string" ? form.id : undefined;
110
+ }
111
+
112
+ function rememberRequest(seen: Set<string>, key: string): boolean {
113
+ if (seen.has(key)) return false;
114
+ seen.add(key);
115
+ if (seen.size > 1_024) seen.delete(seen.values().next().value!);
116
+ return true;
163
117
  }
164
118
 
165
- export const KKCodeIOSNotifyPlugin = async ({ client, directory, project }: any) => {
119
+ function unwrapSessionInfo(value: unknown): SessionInfo {
120
+ const outer = record(value);
121
+ const wrapped = record(outer.data);
122
+ const candidate = Object.keys(wrapped).length > 0 ? wrapped : outer;
123
+ return {
124
+ title: compactText(candidate.title, 200) || undefined,
125
+ parentID: typeof candidate.parentID === "string" ? candidate.parentID : undefined,
126
+ };
127
+ }
128
+
129
+ async function setup(ctx: V2Context): Promise<() => void> {
130
+ const controller = new AbortController();
131
+ const seenRequests = new Set<string>();
166
132
  const projectLabel =
167
- project?.name || directory?.split(/[\\/]/u).filter(Boolean).at(-1) || "KKCode";
168
- const erroredSessions = new Set<string>();
169
- const notifiedPermission = new Set<string>();
170
- const notifiedQuestion = new Set<string>();
133
+ basename(ctx.location.directory ?? ctx.location.project?.canonical ?? "") || "KKCode";
171
134
 
172
- await debugLog(`plugin loaded | project=${projectLabel} | config=${configPath}`);
135
+ await debugLog(
136
+ `v2 plugin loaded | version=${ctx.app.version ?? "unknown"} | project=${projectLabel} | directory=${ctx.location.directory ?? ""}`,
137
+ );
173
138
 
174
- async function getSessionInfo(
175
- sessionId: string,
176
- ): Promise<{ title?: string; isSubSession: boolean }> {
139
+ const getSessionInfo = async (sessionID: string): Promise<SessionInfo> => {
177
140
  try {
178
- const result = await client.session.get({ path: { id: sessionId } });
179
- const title = result?.data?.title?.trim() || undefined;
180
- const parentID = result?.data?.parentID || undefined;
181
- return { title, isSubSession: !!parentID };
182
- } catch (err) {
183
- await debugLog(`getSessionInfo FAILED | session=${sessionId} | ${err}`);
141
+ return unwrapSessionInfo(await ctx.session.get({ sessionID }));
142
+ } catch (error) {
143
+ await debugLog(`v2 getSessionInfo FAILED | session=${sessionID} | ${error}`);
144
+ return {};
184
145
  }
185
- return { title: undefined, isSubSession: false };
186
- }
146
+ };
187
147
 
188
- return {
189
- event: async ({ event }: { event: OpenCodeEvent }) => {
190
- const caredTypes = new Set([
191
- "session.idle",
192
- "session.error",
193
- "permission.asked",
194
- "question.asked",
195
- ]);
196
- if (!caredTypes.has(event.type)) return;
197
- await debugLog(`EVENT type=${event.type} | props=${JSON.stringify(event.properties)}`);
198
- const config = await loadConfig();
199
- if (!config) {
200
- await debugLog("config missing or unreadable, skipping event");
201
- return;
202
- }
203
- try {
204
- if (event.type === "session.idle") {
205
- const sessionId = event.properties.sessionID;
206
- if (!sessionId) {
207
- await debugLog("session.idle SKIP: no sessionID");
208
- return;
209
- }
210
- if (erroredSessions.delete(sessionId)) {
211
- await debugLog(`session.idle SKIP: ${sessionId} was errored, suppressed`);
212
- return;
213
- }
214
- const info = await getSessionInfo(sessionId);
215
- const eventType: NotifyEventType = info.isSubSession
216
- ? "sub_session.completed"
217
- : "session.completed";
218
- await reportEvent(config, sessionId, eventType, projectLabel, undefined, info.title);
219
- await debugLog(`session.idle REPORTED | ${sessionId} | type=${eventType}`);
220
- } else if (event.type === "session.error") {
221
- const sessionId = event.properties.sessionID;
222
- if (sessionId) erroredSessions.add(sessionId);
223
- const info = sessionId ? await getSessionInfo(sessionId) : { title: undefined };
224
- if (sessionId) {
225
- await reportEvent(
226
- config,
227
- sessionId,
228
- "session.error",
229
- projectLabel,
230
- describeError(event.properties),
231
- info.title,
232
- );
233
- await debugLog(`session.error REPORTED | ${sessionId}`);
234
- } else {
235
- await debugLog("session.error SKIP: no sessionID");
236
- }
237
- } else if (event.type === "permission.asked") {
238
- const sessionId = event.properties.sessionID;
239
- const requestKey = `${sessionId}:${event.properties.id ?? event.properties.requestID ?? ""}`;
240
- if (!sessionId || notifiedPermission.has(requestKey)) {
241
- await debugLog(
242
- `permission.asked SKIP | key=${requestKey} | dup=${notifiedPermission.has(requestKey)}`,
243
- );
244
- return;
245
- }
246
- notifiedPermission.add(requestKey);
247
- const info = await getSessionInfo(sessionId);
248
- await reportEvent(
249
- config,
250
- sessionId,
251
- "permission.asked",
252
- projectLabel,
253
- describePermission(event.properties),
254
- info.title,
255
- );
256
- await debugLog(`permission.asked REPORTED | ${sessionId} | key=${requestKey}`);
257
- } else if (event.type === "question.asked") {
258
- const sessionId = event.properties.sessionID;
259
- const requestKey = `${sessionId}:${event.properties.id ?? event.properties.requestID ?? ""}`;
260
- if (!sessionId || notifiedQuestion.has(requestKey)) {
261
- await debugLog(
262
- `question.asked SKIP | key=${requestKey} | dup=${notifiedQuestion.has(requestKey)}`,
263
- );
264
- return;
265
- }
266
- notifiedQuestion.add(requestKey);
267
- const info = await getSessionInfo(sessionId);
268
- await reportEvent(
269
- config,
270
- sessionId,
271
- "question.asked",
272
- projectLabel,
273
- describeQuestion(event.properties),
274
- info.title,
275
- );
276
- await debugLog(`question.asked REPORTED | ${sessionId} | key=${requestKey}`);
277
- }
278
- } catch (error) {
279
- const msg = error instanceof Error ? error.message : String(error);
280
- await debugLog(`HANDLER ERROR | type=${event.type} | ${msg}`);
281
- await client.app.log({
282
- body: {
283
- service: "kkcode",
284
- level: "warn",
285
- message: "Could not report KKCode session notification.",
286
- extra: { error: msg },
287
- },
288
- });
289
- }
290
- },
148
+ const report = async (event: V2Event, intent: Omit<NotificationIntent, "projectLabel">) => {
149
+ const info = await getSessionInfo(intent.sessionID);
150
+ await reportNotification({
151
+ ...intent,
152
+ eventID: event.id ?? intent.eventID,
153
+ occurredAt: event.created ?? intent.occurredAt,
154
+ projectLabel,
155
+ sessionTitle: info.title,
156
+ });
157
+ await debugLog(`v2 ${event.type} REPORTED | ${intent.sessionID} | type=${intent.type}`);
291
158
  };
292
- };
293
159
 
294
- export default KKCodeIOSNotifyPlugin;
160
+ const handle = async (event: V2Event) => {
161
+ if (!eventBelongsToLocation(event, ctx.location)) return;
162
+ const data = event.data ?? {};
163
+ const sessionID = sessionIDOf(event);
164
+ if (!sessionID) return;
165
+
166
+ if (event.type === "session.execution.succeeded") {
167
+ const info = await getSessionInfo(sessionID);
168
+ await reportNotification({
169
+ eventID: event.id,
170
+ sessionID,
171
+ type: info.parentID ? "sub_session.completed" : "session.completed",
172
+ projectLabel,
173
+ sessionTitle: info.title,
174
+ occurredAt: event.created,
175
+ });
176
+ return;
177
+ }
178
+ if (event.type === "session.execution.failed") {
179
+ await report(event, {
180
+ sessionID,
181
+ type: "session.error",
182
+ summary: errorSummary(data.error) ?? "OpenCode session failed",
183
+ });
184
+ return;
185
+ }
186
+ if (event.type === "permission.v2.asked" || event.type === "permission.asked") {
187
+ const requestID = requestIDOf(event) ?? event.id;
188
+ const key = `permission:${sessionID}:${requestID ?? ""}`;
189
+ if (!rememberRequest(seenRequests, key)) return;
190
+ await report(event, {
191
+ sessionID,
192
+ type: "permission.asked",
193
+ summary: permissionSummary(data),
194
+ });
195
+ return;
196
+ }
197
+ if (event.type === "form.created") {
198
+ const summary = questionSummary(data);
199
+ if (!summary) return;
200
+ const key = `question:${sessionID}:${requestIDOf(event) ?? event.id ?? ""}`;
201
+ if (!rememberRequest(seenRequests, key)) return;
202
+ await report(event, { sessionID, type: "question.asked", summary });
203
+ return;
204
+ }
205
+ if (event.type === "question.v2.asked") {
206
+ const key = `question:${sessionID}:${requestIDOf(event) ?? event.id ?? ""}`;
207
+ if (!rememberRequest(seenRequests, key)) return;
208
+ const questions = Array.isArray(data.questions) ? data.questions.map(record) : [];
209
+ const first = questions[0] ?? {};
210
+ await report(event, {
211
+ sessionID,
212
+ type: "question.asked",
213
+ summary:
214
+ compactText(first.question ?? first.header, 400) || "KKCode is waiting for your answer",
215
+ });
216
+ }
217
+ };
218
+
219
+ void (async () => {
220
+ try {
221
+ for await (const event of ctx.event.subscribe({ signal: controller.signal })) {
222
+ await handle(event);
223
+ }
224
+ } catch (error) {
225
+ if (!controller.signal.aborted) await debugLog(`v2 event stream FAILED | ${error}`);
226
+ }
227
+ })();
228
+
229
+ return () => controller.abort();
230
+ }
231
+
232
+ export default { id: "kkcode.notify", setup };