@kkcode-app/agent 1.0.11 → 1.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +23 -6
- package/dist/agent-link.js +102 -24
- package/dist/agent-link.js.map +1 -1
- package/dist/entry.js +12 -0
- package/dist/entry.js.map +1 -0
- package/dist/index.js +20 -31
- package/dist/index.js.map +1 -1
- package/dist/notification-core.js +96 -0
- package/dist/notification-core.js.map +1 -0
- package/dist/plugin-v1.js +136 -0
- package/dist/plugin-v1.js.map +1 -0
- package/dist/plugin.js +168 -184
- package/dist/plugin.js.map +1 -1
- package/dist/qr.js +47 -0
- package/dist/qr.js.map +1 -0
- package/dist/service.js +9 -4
- package/dist/service.js.map +1 -1
- package/dist/tunnel.js +35 -1
- package/dist/tunnel.js.map +1 -1
- package/dist/update.js +32 -27
- package/dist/update.js.map +1 -1
- package/dist/version.js +20 -0
- package/dist/version.js.map +1 -0
- package/package.json +8 -4
- package/src/entry.ts +13 -0
- package/src/notification-core.ts +139 -0
- package/src/plugin-v1.ts +189 -0
- package/src/plugin.ts +186 -248
package/src/plugin-v1.ts
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* [INPUT]: 依赖 OpenCode 1 PluginInput/client 与 notification-core 共享上报内核
|
|
3
|
+
* [OUTPUT]: 默认导出 OpenCode 1 函数插件,处理 idle/error/permission/question 事件
|
|
4
|
+
* [POS]: OpenCode 1 插件实现模块,由包入口 entry.ts 以 { id, server } 组合导出;自身不是 exports 解析目标
|
|
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]: 依赖
|
|
3
|
-
* [OUTPUT]:
|
|
4
|
-
* [POS]:
|
|
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]: OpenCode 2 插件实现模块,与 plugin-v1.ts 一起由包入口 entry.ts 组合导出;自身不是 exports 解析目标
|
|
6
5
|
* [PROTOCOL]: 变更时更新此头部,然后检查 CLAUDE.md
|
|
7
6
|
*/
|
|
8
7
|
|
|
9
|
-
import
|
|
8
|
+
import { basename, normalize } from "node:path";
|
|
10
9
|
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
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
|
-
|
|
26
|
-
|
|
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
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
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
|
-
|
|
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
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
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
|
|
117
|
-
|
|
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
|
|
121
|
-
const
|
|
122
|
-
const
|
|
123
|
-
const
|
|
124
|
-
.map((
|
|
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
|
|
140
|
-
const
|
|
141
|
-
if (
|
|
142
|
-
const
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
.
|
|
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
|
-
|
|
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
|
|
161
|
-
const
|
|
162
|
-
|
|
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
|
-
|
|
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?.
|
|
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(
|
|
135
|
+
await debugLog(
|
|
136
|
+
`v2 plugin loaded | version=${ctx.app.version ?? "unknown"} | project=${projectLabel} | directory=${ctx.location.directory ?? ""}`,
|
|
137
|
+
);
|
|
173
138
|
|
|
174
|
-
async
|
|
175
|
-
sessionId: string,
|
|
176
|
-
): Promise<{ title?: string; isSubSession: boolean }> {
|
|
139
|
+
const getSessionInfo = async (sessionID: string): Promise<SessionInfo> => {
|
|
177
140
|
try {
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
return {
|
|
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
|
-
|
|
186
|
-
}
|
|
146
|
+
};
|
|
187
147
|
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
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
|
-
|
|
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 };
|