@kkcode-app/agent 1.1.3 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +40 -99
- package/dist/agent-link.js +55 -93
- package/dist/agent-link.js.map +1 -1
- package/dist/config.js +101 -69
- package/dist/config.js.map +1 -1
- package/dist/crypto.js +151 -0
- package/dist/crypto.js.map +1 -0
- package/dist/entry.js +5 -9
- package/dist/entry.js.map +1 -1
- package/dist/index.js +71 -83
- package/dist/index.js.map +1 -1
- package/dist/local-server.js +58 -27
- package/dist/local-server.js.map +1 -1
- package/dist/notification-core.js +131 -59
- package/dist/notification-core.js.map +1 -1
- package/dist/plugin.js +183 -67
- package/dist/plugin.js.map +1 -1
- package/dist/protocol.js +62 -6
- package/dist/protocol.js.map +1 -1
- package/dist/qr.js +31 -20
- package/dist/qr.js.map +1 -1
- package/dist/service.js +24 -8
- package/dist/service.js.map +1 -1
- package/dist/tunnel.js +406 -200
- package/dist/tunnel.js.map +1 -1
- package/dist/update.js +13 -5
- package/dist/update.js.map +1 -1
- package/package.json +4 -3
- package/src/config.ts +144 -0
- package/src/crypto.ts +193 -0
- package/src/entry.ts +5 -11
- package/src/notification-core.ts +139 -71
- package/src/plugin.ts +161 -71
- package/dist/plugin-v1.js +0 -136
- package/dist/plugin-v1.js.map +0 -1
- package/src/plugin-v1.ts +0 -189
package/src/notification-core.ts
CHANGED
|
@@ -1,19 +1,16 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* [INPUT]: 依赖 node:fs
|
|
3
|
-
* [OUTPUT]:
|
|
4
|
-
* [POS]: cli
|
|
5
|
-
* [PROTOCOL]:
|
|
2
|
+
* [INPUT]: 依赖 node:fs、node:os、node:path、./config.ts(热读 host.json)与 ./crypto.ts(派生 hostId/relayAuth)
|
|
3
|
+
* [OUTPUT]: 提供 Notify 2.0 通知类型、UTF-8 字节安全截断、2 MiB 日志轮转及带重试的 /v2/events 上报
|
|
4
|
+
* [POS]: cli 推送插件的协议无关内核,被 OpenCode 2 插件调用,支持不开隧道独立推送
|
|
5
|
+
* [PROTOCOL]: Update this header on change, then check CLAUDE.md
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
8
|
import fs from "node:fs";
|
|
9
|
-
import {
|
|
9
|
+
import { homedir } from "node:os";
|
|
10
|
+
import { dirname, join } from "node:path";
|
|
10
11
|
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
node_secret: string;
|
|
14
|
-
service_id: string;
|
|
15
|
-
api_url?: string;
|
|
16
|
-
};
|
|
12
|
+
import { loadHostConfig } from "./config.js";
|
|
13
|
+
import { deriveKeys } from "./crypto.js";
|
|
17
14
|
|
|
18
15
|
export type NotifyEventType =
|
|
19
16
|
| "session.completed"
|
|
@@ -22,71 +19,94 @@ export type NotifyEventType =
|
|
|
22
19
|
| "permission.asked"
|
|
23
20
|
| "question.asked";
|
|
24
21
|
|
|
25
|
-
type
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
project_label: string;
|
|
31
|
-
occurred_at: string;
|
|
32
|
-
session_title?: string;
|
|
22
|
+
type NotifyV2Payload = {
|
|
23
|
+
eventId: string;
|
|
24
|
+
sessionId: string;
|
|
25
|
+
eventType: NotifyEventType;
|
|
26
|
+
sessionTitle?: string;
|
|
33
27
|
summary?: string;
|
|
28
|
+
occurredAt: string;
|
|
34
29
|
};
|
|
35
30
|
|
|
36
31
|
export type NotificationIntent = {
|
|
37
32
|
eventID?: string;
|
|
38
33
|
sessionID: string;
|
|
39
34
|
type: NotifyEventType;
|
|
40
|
-
projectLabel: string;
|
|
41
35
|
summary?: string;
|
|
42
36
|
sessionTitle?: string;
|
|
43
37
|
occurredAt?: number;
|
|
44
38
|
};
|
|
45
39
|
|
|
46
|
-
|
|
47
|
-
|
|
40
|
+
export type ReportOptions = {
|
|
41
|
+
timeoutMs?: number;
|
|
42
|
+
retryDelaysMs?: readonly number[];
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
export const DEFAULT_NOTIFY_API_URL = "https://api.kkcode.app";
|
|
46
|
+
export const MAX_SESSION_TITLE_BYTES = 200;
|
|
47
|
+
export const MAX_SUMMARY_BYTES = 480;
|
|
48
|
+
export const MAX_EVENT_ID_BYTES = 200;
|
|
49
|
+
export const MAX_DEBUG_LOG_BYTES = 2 * 1024 * 1024;
|
|
50
|
+
|
|
51
|
+
const DEFAULT_TIMEOUT_MS = 8_000;
|
|
52
|
+
const DEFAULT_RETRY_DELAYS_MS: readonly number[] = [500, 1_500];
|
|
48
53
|
|
|
49
|
-
|
|
50
|
-
return (
|
|
51
|
-
process.env.KKCODE_AGENT_CONFIG ??
|
|
52
|
-
`${process.env.XDG_CONFIG_HOME ?? `${process.env.HOME ?? "~"}/.config`}/kkcode/agent.json`
|
|
53
|
-
);
|
|
54
|
+
function configBaseDir(): string {
|
|
55
|
+
return process.env.XDG_CONFIG_HOME ?? join(homedir(), ".config");
|
|
54
56
|
}
|
|
55
57
|
|
|
56
|
-
function debugLogPath(): string {
|
|
57
|
-
return (
|
|
58
|
-
process.env.KKCODE_DEBUG_LOG ??
|
|
59
|
-
`${process.env.XDG_CONFIG_HOME ?? `${process.env.HOME ?? "~"}/.config`}/kkcode/events-debug.log`
|
|
60
|
-
);
|
|
58
|
+
export function debugLogPath(): string {
|
|
59
|
+
return process.env.KKCODE_DEBUG_LOG ?? join(configBaseDir(), "kkcode", "events-debug.log");
|
|
61
60
|
}
|
|
62
61
|
|
|
63
62
|
export async function debugLog(message: string): Promise<void> {
|
|
64
63
|
try {
|
|
65
64
|
const path = debugLogPath();
|
|
66
65
|
await fs.promises.mkdir(dirname(path), { recursive: true });
|
|
67
|
-
|
|
66
|
+
let rotated = false;
|
|
67
|
+
try {
|
|
68
|
+
const stat = await fs.promises.stat(path);
|
|
69
|
+
if (stat.size >= MAX_DEBUG_LOG_BYTES) {
|
|
70
|
+
await fs.promises.truncate(path, 0);
|
|
71
|
+
rotated = true;
|
|
72
|
+
}
|
|
73
|
+
} catch (error) {
|
|
74
|
+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
|
75
|
+
}
|
|
76
|
+
const prefix = rotated ? `[${new Date().toISOString()}] [log rotated at ${MAX_DEBUG_LOG_BYTES} bytes]\n` : "";
|
|
77
|
+
await fs.promises.appendFile(path, `${prefix}[${new Date().toISOString()}] ${message}\n`);
|
|
68
78
|
} catch {}
|
|
69
79
|
}
|
|
70
80
|
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
81
|
+
/**
|
|
82
|
+
* 折叠空白并按 UTF-8 字节上限安全截断,保证绝不截断多字节字符(如中文或 emoji)。
|
|
83
|
+
*/
|
|
84
|
+
export function truncateUtf8Bytes(value: unknown, maxBytes: number): string {
|
|
85
|
+
if (typeof value !== "string" || maxBytes <= 0) return "";
|
|
86
|
+
const normalized = value.replace(/\s+/gu, " ").trim();
|
|
87
|
+
if (!normalized) return "";
|
|
88
|
+
if (Buffer.byteLength(normalized, "utf8") <= maxBytes) return normalized;
|
|
89
|
+
|
|
90
|
+
let out = "";
|
|
91
|
+
let usedBytes = 0;
|
|
92
|
+
for (const ch of normalized) {
|
|
93
|
+
const chBytes = Buffer.byteLength(ch, "utf8");
|
|
94
|
+
if (usedBytes + chBytes > maxBytes) break;
|
|
95
|
+
out += ch;
|
|
96
|
+
usedBytes += chBytes;
|
|
78
97
|
}
|
|
98
|
+
return out;
|
|
79
99
|
}
|
|
80
100
|
|
|
81
|
-
export function compactText(value: unknown,
|
|
82
|
-
return
|
|
101
|
+
export function compactText(value: unknown, maxBytes = MAX_SUMMARY_BYTES): string {
|
|
102
|
+
return truncateUtf8Bytes(value, maxBytes);
|
|
83
103
|
}
|
|
84
104
|
|
|
85
105
|
export function errorSummary(value: unknown): string | undefined {
|
|
86
|
-
if (typeof value === "string") return compactText(value) || undefined;
|
|
106
|
+
if (typeof value === "string") return compactText(value, MAX_SUMMARY_BYTES) || undefined;
|
|
87
107
|
if (!value || typeof value !== "object") return undefined;
|
|
88
108
|
const error = value as { message?: unknown; type?: unknown; name?: unknown; data?: unknown };
|
|
89
|
-
const message = compactText(error.message);
|
|
109
|
+
const message = compactText(error.message, MAX_SUMMARY_BYTES);
|
|
90
110
|
if (message) return message;
|
|
91
111
|
const nested = errorSummary(error.data);
|
|
92
112
|
if (nested) return nested;
|
|
@@ -94,46 +114,94 @@ export function errorSummary(value: unknown): string | undefined {
|
|
|
94
114
|
return kind || undefined;
|
|
95
115
|
}
|
|
96
116
|
|
|
117
|
+
class NonRetryableHttpError extends Error {
|
|
118
|
+
constructor(
|
|
119
|
+
public readonly status: number,
|
|
120
|
+
message: string,
|
|
121
|
+
) {
|
|
122
|
+
super(message);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function sleep(ms: number): Promise<void> {
|
|
127
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
128
|
+
}
|
|
129
|
+
|
|
97
130
|
export async function reportNotification(
|
|
98
131
|
intent: NotificationIntent,
|
|
132
|
+
options?: ReportOptions,
|
|
99
133
|
): Promise<"reported" | "skipped"> {
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
await
|
|
134
|
+
let hostConfig: Awaited<ReturnType<typeof loadHostConfig>>;
|
|
135
|
+
try {
|
|
136
|
+
hostConfig = await loadHostConfig();
|
|
137
|
+
} catch (error) {
|
|
138
|
+
await debugLog(`host.json unreadable, skipping ${intent.type}: ${error}`);
|
|
139
|
+
return "skipped";
|
|
140
|
+
}
|
|
141
|
+
if (!hostConfig) {
|
|
142
|
+
await debugLog(`host.json missing, skipping ${intent.type}`);
|
|
103
143
|
return "skipped";
|
|
104
144
|
}
|
|
105
145
|
|
|
106
|
-
const
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
146
|
+
const keys = deriveKeys(hostConfig.secret);
|
|
147
|
+
const apiBase = (
|
|
148
|
+
process.env.KKCODE_NOTIFY_API_URL ??
|
|
149
|
+
hostConfig.notifyApiUrl ??
|
|
150
|
+
DEFAULT_NOTIFY_API_URL
|
|
151
|
+
).replace(/\/$/u, "");
|
|
152
|
+
|
|
153
|
+
const payload: NotifyV2Payload = {
|
|
154
|
+
eventId: truncateUtf8Bytes(intent.eventID, MAX_EVENT_ID_BYTES) || crypto.randomUUID(),
|
|
155
|
+
sessionId: intent.sessionID,
|
|
156
|
+
eventType: intent.type,
|
|
157
|
+
occurredAt: new Date(intent.occurredAt ?? Date.now()).toISOString(),
|
|
113
158
|
};
|
|
114
|
-
|
|
115
|
-
const sessionTitle =
|
|
159
|
+
|
|
160
|
+
const sessionTitle = truncateUtf8Bytes(intent.sessionTitle, MAX_SESSION_TITLE_BYTES);
|
|
161
|
+
const summary = truncateUtf8Bytes(intent.summary, MAX_SUMMARY_BYTES);
|
|
162
|
+
if (sessionTitle) payload.sessionTitle = sessionTitle;
|
|
116
163
|
if (summary) payload.summary = summary;
|
|
117
|
-
if (sessionTitle) payload.session_title = sessionTitle;
|
|
118
164
|
|
|
119
|
-
const
|
|
120
|
-
const
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
165
|
+
const timeoutMs = options?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
166
|
+
const retryDelays = options?.retryDelaysMs ?? DEFAULT_RETRY_DELAYS_MS;
|
|
167
|
+
const endpoint = `${apiBase}/v2/events`;
|
|
168
|
+
const body = JSON.stringify(payload);
|
|
169
|
+
|
|
170
|
+
let lastError: unknown;
|
|
171
|
+
for (let attempt = 0; attempt <= retryDelays.length; attempt += 1) {
|
|
172
|
+
const controller = new AbortController();
|
|
173
|
+
const timeout = setTimeout(() => controller.abort(), timeoutMs);
|
|
174
|
+
try {
|
|
175
|
+
const response = await fetch(endpoint, {
|
|
125
176
|
method: "POST",
|
|
126
177
|
signal: controller.signal,
|
|
127
178
|
headers: {
|
|
128
|
-
Authorization: `Bearer ${config.node_secret}`,
|
|
129
179
|
"Content-Type": "application/json",
|
|
180
|
+
"X-KKCode-Host-Id": keys.hostId,
|
|
181
|
+
"X-KKCode-Auth": keys.relayAuth,
|
|
130
182
|
},
|
|
131
|
-
body
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
183
|
+
body,
|
|
184
|
+
});
|
|
185
|
+
if (response.ok) {
|
|
186
|
+
return "reported";
|
|
187
|
+
}
|
|
188
|
+
const errMsg = `Notification API returned ${response.status}`;
|
|
189
|
+
if (response.status >= 400 && response.status < 500) {
|
|
190
|
+
throw new NonRetryableHttpError(response.status, errMsg);
|
|
191
|
+
}
|
|
192
|
+
throw new Error(errMsg);
|
|
193
|
+
} catch (error) {
|
|
194
|
+
if (error instanceof NonRetryableHttpError) {
|
|
195
|
+
throw error;
|
|
196
|
+
}
|
|
197
|
+
lastError = error;
|
|
198
|
+
if (attempt < retryDelays.length) {
|
|
199
|
+
await sleep(retryDelays[attempt]);
|
|
200
|
+
}
|
|
201
|
+
} finally {
|
|
202
|
+
clearTimeout(timeout);
|
|
203
|
+
}
|
|
138
204
|
}
|
|
205
|
+
|
|
206
|
+
throw lastError instanceof Error ? lastError : new Error(String(lastError));
|
|
139
207
|
}
|
package/src/plugin.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* [INPUT]: 依赖 OpenCode 2 Promise plugin context 的 location/session/event API 与 notification-core
|
|
3
|
-
* [OUTPUT]: 默认导出 `{ id, setup }` OpenCode 2
|
|
4
|
-
* [POS]: OpenCode 2
|
|
5
|
-
* [PROTOCOL]:
|
|
2
|
+
* [INPUT]: 依赖 OpenCode 2 Promise plugin context 的 location/session/event API 与 ./notification-core.ts
|
|
3
|
+
* [OUTPUT]: 默认导出 `{ id, setup }` OpenCode 2 插件;支持单事件会话查询缓存、上报成功后去重、订阅断流指数退避重连与全量上报调试日志
|
|
4
|
+
* [POS]: OpenCode 2 插件实现模块,由包入口 entry.ts 直接导出
|
|
5
|
+
* [PROTOCOL]: Update this header on change, then check CLAUDE.md
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
8
|
import { basename, normalize } from "node:path";
|
|
@@ -11,6 +11,7 @@ import {
|
|
|
11
11
|
compactText,
|
|
12
12
|
debugLog,
|
|
13
13
|
errorSummary,
|
|
14
|
+
MAX_SESSION_TITLE_BYTES,
|
|
14
15
|
reportNotification,
|
|
15
16
|
type NotificationIntent,
|
|
16
17
|
} from "./notification-core.js";
|
|
@@ -31,13 +32,8 @@ type V2Context = {
|
|
|
31
32
|
session: { get(input: { sessionID: string }): Promise<unknown> };
|
|
32
33
|
};
|
|
33
34
|
|
|
34
|
-
type SessionInfo = { title?: string; parentID?: string };
|
|
35
|
+
type SessionInfo = { title?: string; parentID?: string; directory?: string; workspaceID?: string };
|
|
35
36
|
|
|
36
|
-
/**
|
|
37
|
-
* 本插件打算推送的事件类型。handle() 只对这些类型写丢弃日志——流式期间
|
|
38
|
-
* session.step.* / message.updated 等高频事件数量极大,全量记录会刷爆调试日志。
|
|
39
|
-
* handle() 末尾还有一处 UNHANDLED 兜底,用于捕捉本表与分支实现之间的漂移。
|
|
40
|
-
*/
|
|
41
37
|
const NOTIFIABLE_EVENT_TYPES: readonly string[] = [
|
|
42
38
|
"session.execution.succeeded",
|
|
43
39
|
"session.execution.failed",
|
|
@@ -47,6 +43,8 @@ const NOTIFIABLE_EVENT_TYPES: readonly string[] = [
|
|
|
47
43
|
"question.v2.asked",
|
|
48
44
|
];
|
|
49
45
|
|
|
46
|
+
const RECONNECT_BACKOFF_MS: readonly number[] = [1_000, 2_000, 4_000, 10_000];
|
|
47
|
+
|
|
50
48
|
function isNotifiable(type: string): boolean {
|
|
51
49
|
return NOTIFIABLE_EVENT_TYPES.includes(type);
|
|
52
50
|
}
|
|
@@ -57,16 +55,49 @@ function record(value: unknown): Record<string, unknown> {
|
|
|
57
55
|
: {};
|
|
58
56
|
}
|
|
59
57
|
|
|
60
|
-
function
|
|
58
|
+
function sessionIDOf(event: V2Event): string | undefined {
|
|
59
|
+
const data = event.data ?? {};
|
|
60
|
+
if (typeof data.sessionID === "string") return data.sessionID;
|
|
61
|
+
const form = record(data.form);
|
|
62
|
+
return typeof form.sessionID === "string" ? form.sessionID : undefined;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function requestIDOf(event: V2Event): string | undefined {
|
|
66
|
+
const data = event.data ?? {};
|
|
67
|
+
if (typeof data.id === "string") return data.id;
|
|
68
|
+
if (typeof data.requestID === "string") return data.requestID;
|
|
69
|
+
const form = record(data.form);
|
|
70
|
+
return typeof form.id === "string" ? form.id : undefined;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* OpenCode 2 的 session.execution.* 生命周期事件由全局协调器发布,事件信封不含 location,
|
|
75
|
+
* 此时回退用会话登记的 location 判定归属;查不到时丢弃,不做跨项目广播。
|
|
76
|
+
*/
|
|
77
|
+
async function eventBelongsToLocation(
|
|
78
|
+
event: V2Event,
|
|
79
|
+
location: V2Location,
|
|
80
|
+
getSessionInfo: (sessionID: string) => Promise<SessionInfo>,
|
|
81
|
+
): Promise<boolean> {
|
|
61
82
|
const eventDirectory = event.location?.directory;
|
|
62
83
|
const pluginDirectory = location.directory;
|
|
63
|
-
if (
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
84
|
+
if (eventDirectory) {
|
|
85
|
+
if (!pluginDirectory || normalize(eventDirectory) !== normalize(pluginDirectory)) return false;
|
|
86
|
+
if (
|
|
87
|
+
event.location?.workspaceID &&
|
|
88
|
+
location.workspaceID &&
|
|
89
|
+
event.location.workspaceID !== location.workspaceID
|
|
90
|
+
) {
|
|
91
|
+
return false;
|
|
92
|
+
}
|
|
93
|
+
return true;
|
|
94
|
+
}
|
|
95
|
+
const sessionID = sessionIDOf(event);
|
|
96
|
+
if (!sessionID) return false;
|
|
97
|
+
const info = await getSessionInfo(sessionID);
|
|
98
|
+
if (!info.directory) return false;
|
|
99
|
+
if (!pluginDirectory || normalize(info.directory) !== normalize(pluginDirectory)) return false;
|
|
100
|
+
return !info.workspaceID || !location.workspaceID || info.workspaceID === location.workspaceID;
|
|
70
101
|
}
|
|
71
102
|
|
|
72
103
|
function permissionSummary(data: Record<string, unknown>): string {
|
|
@@ -112,38 +143,53 @@ function questionSummary(data: Record<string, unknown>): string | undefined {
|
|
|
112
143
|
);
|
|
113
144
|
}
|
|
114
145
|
|
|
115
|
-
function
|
|
116
|
-
const data = event.data ?? {};
|
|
117
|
-
if (typeof data.sessionID === "string") return data.sessionID;
|
|
118
|
-
const form = record(data.form);
|
|
119
|
-
return typeof form.sessionID === "string" ? form.sessionID : undefined;
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
function requestIDOf(event: V2Event): string | undefined {
|
|
123
|
-
const data = event.data ?? {};
|
|
124
|
-
if (typeof data.id === "string") return data.id;
|
|
125
|
-
if (typeof data.requestID === "string") return data.requestID;
|
|
126
|
-
const form = record(data.form);
|
|
127
|
-
return typeof form.id === "string" ? form.id : undefined;
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
function rememberRequest(seen: Set<string>, key: string): boolean {
|
|
131
|
-
if (seen.has(key)) return false;
|
|
146
|
+
function markRequestSeen(seen: Set<string>, key: string): void {
|
|
132
147
|
seen.add(key);
|
|
133
|
-
if (seen.size > 1_024)
|
|
134
|
-
|
|
148
|
+
if (seen.size > 1_024) {
|
|
149
|
+
seen.delete(seen.values().next().value!);
|
|
150
|
+
}
|
|
135
151
|
}
|
|
136
152
|
|
|
137
153
|
function unwrapSessionInfo(value: unknown): SessionInfo {
|
|
138
154
|
const outer = record(value);
|
|
139
155
|
const wrapped = record(outer.data);
|
|
140
156
|
const candidate = Object.keys(wrapped).length > 0 ? wrapped : outer;
|
|
157
|
+
const location = record(candidate.location);
|
|
141
158
|
return {
|
|
142
|
-
title: compactText(candidate.title,
|
|
159
|
+
title: compactText(candidate.title, MAX_SESSION_TITLE_BYTES) || undefined,
|
|
143
160
|
parentID: typeof candidate.parentID === "string" ? candidate.parentID : undefined,
|
|
161
|
+
directory: typeof location.directory === "string" ? location.directory : undefined,
|
|
162
|
+
workspaceID: typeof location.workspaceID === "string" ? location.workspaceID : undefined,
|
|
144
163
|
};
|
|
145
164
|
}
|
|
146
165
|
|
|
166
|
+
function waitWithAbort(ms: number, signal: AbortSignal): Promise<void> {
|
|
167
|
+
if (signal.aborted || ms <= 0) return Promise.resolve();
|
|
168
|
+
return new Promise((resolve) => {
|
|
169
|
+
const timer = setTimeout(() => {
|
|
170
|
+
signal.removeEventListener("abort", onAbort);
|
|
171
|
+
resolve();
|
|
172
|
+
}, ms);
|
|
173
|
+
const onAbort = () => {
|
|
174
|
+
clearTimeout(timer);
|
|
175
|
+
resolve();
|
|
176
|
+
};
|
|
177
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function reconnectDelays(): readonly number[] {
|
|
182
|
+
const override = process.env.KKCODE_PLUGIN_RECONNECT_MS;
|
|
183
|
+
if (override) {
|
|
184
|
+
const parsed = override
|
|
185
|
+
.split(",")
|
|
186
|
+
.map((item) => Number(item.trim()))
|
|
187
|
+
.filter((n) => Number.isFinite(n) && n >= 0);
|
|
188
|
+
if (parsed.length > 0) return parsed;
|
|
189
|
+
}
|
|
190
|
+
return RECONNECT_BACKOFF_MS;
|
|
191
|
+
}
|
|
192
|
+
|
|
147
193
|
async function setup(ctx: V2Context): Promise<() => void> {
|
|
148
194
|
const controller = new AbortController();
|
|
149
195
|
const seenRequests = new Set<string>();
|
|
@@ -154,7 +200,7 @@ async function setup(ctx: V2Context): Promise<() => void> {
|
|
|
154
200
|
`v2 plugin loaded | version=${ctx.app.version ?? "unknown"} | project=${projectLabel} | directory=${ctx.location.directory ?? ""}`,
|
|
155
201
|
);
|
|
156
202
|
|
|
157
|
-
const
|
|
203
|
+
const fetchSessionInfo = async (sessionID: string): Promise<SessionInfo> => {
|
|
158
204
|
try {
|
|
159
205
|
return unwrapSessionInfo(await ctx.session.get({ sessionID }));
|
|
160
206
|
} catch (error) {
|
|
@@ -163,29 +209,42 @@ async function setup(ctx: V2Context): Promise<() => void> {
|
|
|
163
209
|
}
|
|
164
210
|
};
|
|
165
211
|
|
|
166
|
-
const report = async (event: V2Event, intent: Omit<NotificationIntent, "projectLabel">) => {
|
|
167
|
-
const info = await getSessionInfo(intent.sessionID);
|
|
168
|
-
await reportNotification({
|
|
169
|
-
...intent,
|
|
170
|
-
eventID: event.id ?? intent.eventID,
|
|
171
|
-
occurredAt: event.created ?? intent.occurredAt,
|
|
172
|
-
projectLabel,
|
|
173
|
-
sessionTitle: info.title,
|
|
174
|
-
});
|
|
175
|
-
await debugLog(`v2 ${event.type} REPORTED | ${intent.sessionID} | type=${intent.type}`);
|
|
176
|
-
};
|
|
177
|
-
|
|
178
212
|
const handle = async (event: V2Event) => {
|
|
179
|
-
|
|
213
|
+
// 同一事件生命周期内复用 session.get 结果,避免归属判断与上报各查一次。
|
|
214
|
+
const sessionInfoCache = new Map<string, Promise<SessionInfo>>();
|
|
215
|
+
const getSessionInfo = (sessionID: string): Promise<SessionInfo> => {
|
|
216
|
+
let pending = sessionInfoCache.get(sessionID);
|
|
217
|
+
if (!pending) {
|
|
218
|
+
pending = fetchSessionInfo(sessionID);
|
|
219
|
+
sessionInfoCache.set(sessionID, pending);
|
|
220
|
+
}
|
|
221
|
+
return pending;
|
|
222
|
+
};
|
|
223
|
+
|
|
224
|
+
const report = async (intent: NotificationIntent): Promise<"reported" | "skipped"> => {
|
|
225
|
+
const info = await getSessionInfo(intent.sessionID);
|
|
226
|
+
const outcome = await reportNotification({
|
|
227
|
+
...intent,
|
|
228
|
+
eventID: event.id ?? intent.eventID,
|
|
229
|
+
occurredAt: event.created ?? intent.occurredAt,
|
|
230
|
+
sessionTitle: intent.sessionTitle ?? info.title,
|
|
231
|
+
});
|
|
232
|
+
await debugLog(
|
|
233
|
+
`v2 ${event.type} ${outcome === "reported" ? "REPORTED" : "SKIPPED"} | ${intent.sessionID} | type=${intent.type}`,
|
|
234
|
+
);
|
|
235
|
+
return outcome;
|
|
236
|
+
};
|
|
237
|
+
|
|
238
|
+
const data = event.data ?? {};
|
|
239
|
+
const sessionID = sessionIDOf(event);
|
|
240
|
+
if (!(await eventBelongsToLocation(event, ctx.location, getSessionInfo))) {
|
|
180
241
|
if (isNotifiable(event.type)) {
|
|
181
242
|
await debugLog(
|
|
182
|
-
`v2 ${event.type} DROPPED | location mismatch | event=${event.location?.directory ?? "none"} plugin=${ctx.location.directory ?? "none"}`,
|
|
243
|
+
`v2 ${event.type} DROPPED | location mismatch | event=${event.location?.directory ?? (sessionID ? "session-resolved" : "none")} plugin=${ctx.location.directory ?? "none"}`,
|
|
183
244
|
);
|
|
184
245
|
}
|
|
185
246
|
return;
|
|
186
247
|
}
|
|
187
|
-
const data = event.data ?? {};
|
|
188
|
-
const sessionID = sessionIDOf(event);
|
|
189
248
|
if (!sessionID) {
|
|
190
249
|
if (isNotifiable(event.type)) {
|
|
191
250
|
await debugLog(`v2 ${event.type} DROPPED | no sessionID | id=${event.id ?? "none"}`);
|
|
@@ -195,18 +254,15 @@ async function setup(ctx: V2Context): Promise<() => void> {
|
|
|
195
254
|
|
|
196
255
|
if (event.type === "session.execution.succeeded") {
|
|
197
256
|
const info = await getSessionInfo(sessionID);
|
|
198
|
-
await
|
|
199
|
-
eventID: event.id,
|
|
257
|
+
await report({
|
|
200
258
|
sessionID,
|
|
201
259
|
type: info.parentID ? "sub_session.completed" : "session.completed",
|
|
202
|
-
projectLabel,
|
|
203
260
|
sessionTitle: info.title,
|
|
204
|
-
occurredAt: event.created,
|
|
205
261
|
});
|
|
206
262
|
return;
|
|
207
263
|
}
|
|
208
264
|
if (event.type === "session.execution.failed") {
|
|
209
|
-
await report(
|
|
265
|
+
await report({
|
|
210
266
|
sessionID,
|
|
211
267
|
type: "session.error",
|
|
212
268
|
summary: errorSummary(data.error) ?? "OpenCode session failed",
|
|
@@ -216,15 +272,18 @@ async function setup(ctx: V2Context): Promise<() => void> {
|
|
|
216
272
|
if (event.type === "permission.v2.asked" || event.type === "permission.asked") {
|
|
217
273
|
const requestID = requestIDOf(event) ?? event.id;
|
|
218
274
|
const key = `permission:${sessionID}:${requestID ?? ""}`;
|
|
219
|
-
if (
|
|
275
|
+
if (seenRequests.has(key)) {
|
|
220
276
|
await debugLog(`v2 ${event.type} DEDUPED | ${sessionID} | key=${key}`);
|
|
221
277
|
return;
|
|
222
278
|
}
|
|
223
|
-
await report(
|
|
279
|
+
const outcome = await report({
|
|
224
280
|
sessionID,
|
|
225
281
|
type: "permission.asked",
|
|
226
282
|
summary: permissionSummary(data),
|
|
227
283
|
});
|
|
284
|
+
if (outcome === "reported") {
|
|
285
|
+
markRequestSeen(seenRequests, key);
|
|
286
|
+
}
|
|
228
287
|
return;
|
|
229
288
|
}
|
|
230
289
|
if (event.type === "form.created") {
|
|
@@ -234,27 +293,33 @@ async function setup(ctx: V2Context): Promise<() => void> {
|
|
|
234
293
|
return;
|
|
235
294
|
}
|
|
236
295
|
const key = `question:${sessionID}:${requestIDOf(event) ?? event.id ?? ""}`;
|
|
237
|
-
if (
|
|
296
|
+
if (seenRequests.has(key)) {
|
|
238
297
|
await debugLog(`v2 form.created DEDUPED | ${sessionID} | key=${key}`);
|
|
239
298
|
return;
|
|
240
299
|
}
|
|
241
|
-
await report(
|
|
300
|
+
const outcome = await report({ sessionID, type: "question.asked", summary });
|
|
301
|
+
if (outcome === "reported") {
|
|
302
|
+
markRequestSeen(seenRequests, key);
|
|
303
|
+
}
|
|
242
304
|
return;
|
|
243
305
|
}
|
|
244
306
|
if (event.type === "question.v2.asked") {
|
|
245
307
|
const key = `question:${sessionID}:${requestIDOf(event) ?? event.id ?? ""}`;
|
|
246
|
-
if (
|
|
308
|
+
if (seenRequests.has(key)) {
|
|
247
309
|
await debugLog(`v2 ${event.type} DEDUPED | ${sessionID} | key=${key}`);
|
|
248
310
|
return;
|
|
249
311
|
}
|
|
250
312
|
const questions = Array.isArray(data.questions) ? data.questions.map(record) : [];
|
|
251
313
|
const first = questions[0] ?? {};
|
|
252
|
-
await report(
|
|
314
|
+
const outcome = await report({
|
|
253
315
|
sessionID,
|
|
254
316
|
type: "question.asked",
|
|
255
317
|
summary:
|
|
256
318
|
compactText(first.question ?? first.header, 400) || "KKCode is waiting for your answer",
|
|
257
319
|
});
|
|
320
|
+
if (outcome === "reported") {
|
|
321
|
+
markRequestSeen(seenRequests, key);
|
|
322
|
+
}
|
|
258
323
|
return;
|
|
259
324
|
}
|
|
260
325
|
if (isNotifiable(event.type)) {
|
|
@@ -263,12 +328,37 @@ async function setup(ctx: V2Context): Promise<() => void> {
|
|
|
263
328
|
};
|
|
264
329
|
|
|
265
330
|
void (async () => {
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
331
|
+
const delays = reconnectDelays();
|
|
332
|
+
let reconnectAttempt = 0;
|
|
333
|
+
|
|
334
|
+
while (!controller.signal.aborted) {
|
|
335
|
+
let receivedAny = false;
|
|
336
|
+
try {
|
|
337
|
+
for await (const event of ctx.event.subscribe({ signal: controller.signal })) {
|
|
338
|
+
receivedAny = true;
|
|
339
|
+
reconnectAttempt = 0;
|
|
340
|
+
try {
|
|
341
|
+
await handle(event);
|
|
342
|
+
} catch (error) {
|
|
343
|
+
await debugLog(`v2 event handle FAILED | ${event.type} | ${error}`);
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
if (!controller.signal.aborted) {
|
|
347
|
+
await debugLog("v2 event stream ENDED unexpectedly, reconnecting");
|
|
348
|
+
}
|
|
349
|
+
} catch (error) {
|
|
350
|
+
if (!controller.signal.aborted) {
|
|
351
|
+
await debugLog(`v2 event stream FAILED | ${error}`);
|
|
352
|
+
}
|
|
269
353
|
}
|
|
270
|
-
|
|
271
|
-
if (
|
|
354
|
+
|
|
355
|
+
if (controller.signal.aborted) break;
|
|
356
|
+
const delayMs = delays[Math.min(reconnectAttempt, delays.length - 1)];
|
|
357
|
+
if (!receivedAny || delayMs > 0) {
|
|
358
|
+
await debugLog(`v2 event stream reconnecting in ${delayMs}ms (attempt=${reconnectAttempt + 1})`);
|
|
359
|
+
await waitWithAbort(delayMs, controller.signal);
|
|
360
|
+
}
|
|
361
|
+
reconnectAttempt += 1;
|
|
272
362
|
}
|
|
273
363
|
})();
|
|
274
364
|
|