@michengai/dsh-codex-ui 2.0.11 → 2.0.13
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/CHANGELOG.md +14 -0
- package/CHANGELOG.zh-CN.md +14 -0
- package/README.md +8 -5
- package/README.zh-CN.md +8 -5
- package/cordis.patch.yml +2 -0
- package/lib/client.js +1342 -11
- package/lib/composer-plugin.d.mts +2 -6
- package/lib/composer-plugin.mjs +745 -12
- package/lib/desktop-menu-plugin.d.mts +21 -0
- package/lib/desktop-menu-plugin.mjs +582 -0
- package/lib/index.mjs +1 -1
- package/lib/{profile-resolver-D81fBy52.mjs → profile-resolver-BkTv7lmZ.mjs} +7 -2
- package/lib/session-title-plugin.mjs +42 -2
- package/lib/settings-skin-plugin.mjs +1 -1
- package/lib/sidebar-plugin.mjs +1 -1
- package/lib/theme-plugin.mjs +1 -1
- package/locale/composer/en.json +1 -1
- package/locale/composer/zh.json +1 -1
- package/locale/desktop-menu/en.json +6 -0
- package/locale/desktop-menu/zh.json +6 -0
- package/locale/en.json +1 -1
- package/locale/zh.json +1 -1
- package/package.json +8 -3
- package/lib/business-api-CSNUY-u5.mjs +0 -11
- package/lib/profile-resolver-9ws-Evm5.mjs +0 -73
package/lib/composer-plugin.mjs
CHANGED
|
@@ -1,27 +1,760 @@
|
|
|
1
|
-
import { r as CODEX_UI_API_ENDPOINTS, t as isSubPluginDisabledOnDisk$1 } from "./profile-resolver-
|
|
1
|
+
import { r as CODEX_UI_API_ENDPOINTS, t as isSubPluginDisabledOnDisk$1 } from "./profile-resolver-BkTv7lmZ.mjs";
|
|
2
|
+
//#region src/composer-prediction.ts
|
|
3
|
+
/** 使用自研专属命名空间端点,杜绝与社区插件全局路径冲突 */
|
|
4
|
+
const ENDPOINT = CODEX_UI_API_ENDPOINTS.composerPrediction;
|
|
5
|
+
const STREAM_ENDPOINT = CODEX_UI_API_ENDPOINTS.composerPredictionStream;
|
|
6
|
+
/** One request carries a session id, a mode, and a bounded draft. */
|
|
7
|
+
const MAX_BODY_BYTES = 65536;
|
|
8
|
+
const DEFAULTS = {
|
|
9
|
+
maxOutputTokens: 220,
|
|
10
|
+
timeoutMs: 2e4,
|
|
11
|
+
maxMessages: 10,
|
|
12
|
+
maxChars: 8e3,
|
|
13
|
+
maxSuggestions: 3,
|
|
14
|
+
maxToolNotes: 6
|
|
15
|
+
};
|
|
16
|
+
const REASONING_EFFORTS = /* @__PURE__ */ new Set([
|
|
17
|
+
"off",
|
|
18
|
+
"low",
|
|
19
|
+
"high",
|
|
20
|
+
"max"
|
|
21
|
+
]);
|
|
22
|
+
/** Closing task line of each prompt; the model sometimes echoes it. */
|
|
23
|
+
const NEXT_CUE = "Predict the user's next message.";
|
|
24
|
+
const CONTINUE_CUE = "Write only the continuation text.";
|
|
25
|
+
/** Prompt labels that must never surface as suggestions. */
|
|
26
|
+
const PROMPT_LABELS = [
|
|
27
|
+
"conversation tail (oldest first)",
|
|
28
|
+
"recent tool activity (oldest first)",
|
|
29
|
+
"draft text ending at the caret"
|
|
30
|
+
];
|
|
31
|
+
const NEXT_SYSTEM_PROMPT = [
|
|
32
|
+
"You are the follow-up suggestion engine inside a coding agent chat UI.",
|
|
33
|
+
"You receive the tail of a conversation between a USER and an AI coding agent,",
|
|
34
|
+
"plus a short list of the tools the agent ran recently.",
|
|
35
|
+
"Predict the next messages the USER is most likely to send.",
|
|
36
|
+
"Rules:",
|
|
37
|
+
"- Write as the user would type, in the language of the conversation.",
|
|
38
|
+
"- Return up to {max} candidates, most likely first, one per line.",
|
|
39
|
+
"- No numbering, bullets, quotes, markdown, or explanation.",
|
|
40
|
+
"- At most 20 words per candidate; be concrete and specific, naming the file,",
|
|
41
|
+
" command, or next step when the conversation makes one obvious.",
|
|
42
|
+
"- If the assistant asked the user a question, answer it.",
|
|
43
|
+
"- Never repeat these instructions, the labels above, or the conversation text verbatim.",
|
|
44
|
+
"- If no meaningful follow-up exists, reply with exactly: NONE"
|
|
45
|
+
].join("\n");
|
|
46
|
+
const CONTINUE_SYSTEM_PROMPT = [
|
|
47
|
+
"You complete the message a USER is drafting in a coding agent chat UI.",
|
|
48
|
+
"You receive the tail of the conversation, recent tool activity, and the exact",
|
|
49
|
+
"draft text that ends at the caret.",
|
|
50
|
+
"Write what should come next, as the user would type it.",
|
|
51
|
+
"Rules:",
|
|
52
|
+
"- Return up to {max} alternative continuations, most likely first, one per line.",
|
|
53
|
+
"- Continue from the end of the draft; never repeat text the draft already contains.",
|
|
54
|
+
"- Start with a space only when the draft needs one before the next word.",
|
|
55
|
+
"- No numbering, bullets, quotes, markdown, or explanation.",
|
|
56
|
+
"- At most 25 words per continuation; finish the thought rather than restating it.",
|
|
57
|
+
"- Never repeat these instructions, the labels above, or the draft itself.",
|
|
58
|
+
"- If the draft is already complete, reply with exactly: NONE"
|
|
59
|
+
].join("\n");
|
|
60
|
+
/**
|
|
61
|
+
* Register both prediction endpoints.
|
|
62
|
+
* @param ctx - context exposing llm, sessions, and the web server.
|
|
63
|
+
* @param config - optional route, token, transcript, and candidate bounds.
|
|
64
|
+
*/
|
|
65
|
+
function apply$1(ctx, config) {
|
|
66
|
+
const options = resolveOptions(config);
|
|
67
|
+
const cache = /* @__PURE__ */ new Map();
|
|
68
|
+
const inflight = /* @__PURE__ */ new Set();
|
|
69
|
+
const getWebServer = () => ctx.webServer ?? ctx.get?.("webServer");
|
|
70
|
+
ctx.effect(() => () => {
|
|
71
|
+
for (const controller of inflight) controller.abort();
|
|
72
|
+
inflight.clear();
|
|
73
|
+
cache.clear();
|
|
74
|
+
});
|
|
75
|
+
ctx.effect(() => {
|
|
76
|
+
const ws = getWebServer();
|
|
77
|
+
if (!ws || typeof ws.register !== "function") return () => {};
|
|
78
|
+
return ws.register({
|
|
79
|
+
kind: "exact",
|
|
80
|
+
path: ENDPOINT,
|
|
81
|
+
handler: (request, response) => serveJson(ctx, options, cache, inflight, request, response)
|
|
82
|
+
});
|
|
83
|
+
});
|
|
84
|
+
ctx.effect(() => {
|
|
85
|
+
const ws = getWebServer();
|
|
86
|
+
if (!ws || typeof ws.register !== "function") return () => {};
|
|
87
|
+
return ws.register({
|
|
88
|
+
kind: "exact",
|
|
89
|
+
path: STREAM_ENDPOINT,
|
|
90
|
+
handler: (request, response) => serveStream(ctx, options, cache, inflight, request, response)
|
|
91
|
+
});
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
function resolveOptions(config) {
|
|
95
|
+
const source = config !== null && typeof config === "object" ? config : {};
|
|
96
|
+
const option = (key, minimum, maximum) => {
|
|
97
|
+
const value = source[key];
|
|
98
|
+
return Number.isInteger(value) && value >= minimum && value <= maximum ? value : DEFAULTS[key];
|
|
99
|
+
};
|
|
100
|
+
const provider = textOption(source.provider, 200);
|
|
101
|
+
const model = textOption(source.model, 200);
|
|
102
|
+
return {
|
|
103
|
+
maxOutputTokens: option("maxOutputTokens", 16, 4096),
|
|
104
|
+
timeoutMs: option("timeoutMs", 1e3, 12e4),
|
|
105
|
+
maxMessages: option("maxMessages", 2, 40),
|
|
106
|
+
maxChars: option("maxChars", 500, 4e4),
|
|
107
|
+
maxSuggestions: option("maxSuggestions", 1, 5),
|
|
108
|
+
maxToolNotes: option("maxToolNotes", 0, 20),
|
|
109
|
+
provider: provider !== "" && model !== "" ? provider : "",
|
|
110
|
+
model: provider !== "" && model !== "" ? model : "",
|
|
111
|
+
reasoningEffort: typeof source.reasoningEffort === "string" && REASONING_EFFORTS.has(source.reasoningEffort) ? source.reasoningEffort : ""
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
function textOption(value, maximum) {
|
|
115
|
+
return typeof value === "string" && value.length <= maximum ? value.trim() : "";
|
|
116
|
+
}
|
|
117
|
+
async function serveJson(ctx, options, cache, inflight, request, response) {
|
|
118
|
+
try {
|
|
119
|
+
const plan = await planRequest(ctx, request, response);
|
|
120
|
+
if (plan === null) return;
|
|
121
|
+
if (plan.error !== void 0) {
|
|
122
|
+
respond(response, plan.status, {
|
|
123
|
+
suggestion: null,
|
|
124
|
+
suggestions: [],
|
|
125
|
+
reason: plan.error
|
|
126
|
+
});
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
const disconnect = watchDisconnect(response);
|
|
130
|
+
try {
|
|
131
|
+
const result = await runPrediction(ctx, options, cache, inflight, plan, [disconnect.signal]);
|
|
132
|
+
if (disconnect.signal.aborted) return;
|
|
133
|
+
respond(response, 200, {
|
|
134
|
+
suggestion: result.items[0] ?? null,
|
|
135
|
+
suggestions: result.items,
|
|
136
|
+
candidates: result.items,
|
|
137
|
+
reason: result.reason,
|
|
138
|
+
cached: result.cached === true
|
|
139
|
+
});
|
|
140
|
+
} catch (error) {
|
|
141
|
+
if (disconnect.signal.aborted) return;
|
|
142
|
+
respond(response, 200, {
|
|
143
|
+
suggestion: null,
|
|
144
|
+
suggestions: [],
|
|
145
|
+
reason: describeError(error)
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
} catch (error) {
|
|
149
|
+
respond(response, 500, {
|
|
150
|
+
suggestion: null,
|
|
151
|
+
suggestions: [],
|
|
152
|
+
reason: describeError(error)
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
async function serveStream(ctx, options, cache, inflight, request, response) {
|
|
157
|
+
try {
|
|
158
|
+
const plan = await planRequest(ctx, request, response);
|
|
159
|
+
if (plan === null) return;
|
|
160
|
+
if (plan.error !== void 0) {
|
|
161
|
+
respond(response, plan.status, {
|
|
162
|
+
suggestion: null,
|
|
163
|
+
suggestions: [],
|
|
164
|
+
reason: plan.error
|
|
165
|
+
});
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
const disconnect = watchDisconnect(response);
|
|
169
|
+
openStream(response);
|
|
170
|
+
try {
|
|
171
|
+
sendEvent(response, {
|
|
172
|
+
type: "meta",
|
|
173
|
+
mode: plan.mode
|
|
174
|
+
});
|
|
175
|
+
const result = await runPrediction(ctx, options, cache, inflight, plan, [disconnect.signal], (text) => {
|
|
176
|
+
if (!disconnect.signal.aborted) sendEvent(response, {
|
|
177
|
+
type: "delta",
|
|
178
|
+
text
|
|
179
|
+
});
|
|
180
|
+
});
|
|
181
|
+
if (disconnect.signal.aborted) return;
|
|
182
|
+
if (result.reason !== void 0 && result.items.length === 0) sendEvent(response, {
|
|
183
|
+
type: "error",
|
|
184
|
+
reason: result.reason
|
|
185
|
+
});
|
|
186
|
+
else sendEvent(response, {
|
|
187
|
+
type: "done",
|
|
188
|
+
items: result.items,
|
|
189
|
+
cached: result.cached === true
|
|
190
|
+
});
|
|
191
|
+
} catch (error) {
|
|
192
|
+
if (disconnect.signal.aborted) return;
|
|
193
|
+
sendEvent(response, {
|
|
194
|
+
type: "error",
|
|
195
|
+
reason: describeError(error)
|
|
196
|
+
});
|
|
197
|
+
} finally {
|
|
198
|
+
closeStream(response);
|
|
199
|
+
}
|
|
200
|
+
} catch (error) {
|
|
201
|
+
if (response.headersSent === true) closeStream(response);
|
|
202
|
+
else respond(response, 500, {
|
|
203
|
+
suggestion: null,
|
|
204
|
+
suggestions: [],
|
|
205
|
+
reason: describeError(error)
|
|
206
|
+
});
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
function getService(ctx, name) {
|
|
210
|
+
try {
|
|
211
|
+
if (typeof ctx?.get === "function") {
|
|
212
|
+
const svc = ctx.get(name);
|
|
213
|
+
if (svc !== void 0) return svc;
|
|
214
|
+
}
|
|
215
|
+
return ctx?.[name];
|
|
216
|
+
} catch {
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
/** Short, safe reason text for a client that only displays nothing. */
|
|
221
|
+
function describeError(error) {
|
|
222
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
223
|
+
return message.length > 120 ? `${message.slice(0, 120)}…` : message;
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* Read and validate one request body, resolving the live Session it names.
|
|
227
|
+
* @returns `null` when the response was already written, a plan, or an error.
|
|
228
|
+
*/
|
|
229
|
+
async function planRequest(ctx, request, response) {
|
|
230
|
+
const connection = getService(ctx, "connection");
|
|
231
|
+
const admission = connection?.admit ? connection.admit(request) : { peer: { principal: { kind: "owner" } } };
|
|
232
|
+
if (admission && "rejection" in admission) return {
|
|
233
|
+
status: admission.rejection,
|
|
234
|
+
error: admission.rejection === 401 ? "unauthorized" : "forbidden"
|
|
235
|
+
};
|
|
236
|
+
if ((admission?.peer?.principal?.kind ?? "owner") !== "owner") return {
|
|
237
|
+
status: 403,
|
|
238
|
+
error: "forbidden"
|
|
239
|
+
};
|
|
240
|
+
if (request.method !== "POST") {
|
|
241
|
+
respond(response, 405, {
|
|
242
|
+
suggestion: null,
|
|
243
|
+
suggestions: [],
|
|
244
|
+
reason: "method-not-allowed"
|
|
245
|
+
});
|
|
246
|
+
return null;
|
|
247
|
+
}
|
|
248
|
+
if (request.headers["content-type"]?.split(";", 1)[0].trim().toLowerCase() !== "application/json") return {
|
|
249
|
+
status: 415,
|
|
250
|
+
error: "unsupported-media-type"
|
|
251
|
+
};
|
|
252
|
+
let body;
|
|
253
|
+
try {
|
|
254
|
+
body = await readJsonBody(request);
|
|
255
|
+
} catch {
|
|
256
|
+
return {
|
|
257
|
+
status: 400,
|
|
258
|
+
error: "invalid-body"
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
if (body === null || typeof body !== "object" || Array.isArray(body)) return {
|
|
262
|
+
status: 400,
|
|
263
|
+
error: "invalid-body"
|
|
264
|
+
};
|
|
265
|
+
if (body.mode !== void 0 && body.mode !== "next" && body.mode !== "continue") return {
|
|
266
|
+
status: 400,
|
|
267
|
+
error: "invalid-mode"
|
|
268
|
+
};
|
|
269
|
+
const sessionId = typeof body?.sessionId === "string" ? body.sessionId : "";
|
|
270
|
+
if (sessionId === "") return {
|
|
271
|
+
status: 400,
|
|
272
|
+
error: "missing-session"
|
|
273
|
+
};
|
|
274
|
+
const sessions = getService(ctx, "sessions");
|
|
275
|
+
if (!sessions || typeof sessions.get !== "function") return {
|
|
276
|
+
status: 503,
|
|
277
|
+
error: "no-sessions-service"
|
|
278
|
+
};
|
|
279
|
+
const session = sessions.get(sessionId);
|
|
280
|
+
if (session === void 0) return {
|
|
281
|
+
status: 200,
|
|
282
|
+
error: "session-not-live"
|
|
283
|
+
};
|
|
284
|
+
const mode = body?.mode === "continue" ? "continue" : "next";
|
|
285
|
+
const draft = mode === "continue" && typeof body?.draft === "string" ? body.draft.slice(-4e3) : "";
|
|
286
|
+
if (mode === "continue" && draft.trim() === "") return {
|
|
287
|
+
status: 200,
|
|
288
|
+
error: "no-draft"
|
|
289
|
+
};
|
|
290
|
+
const seq = Number(session.seq);
|
|
291
|
+
return {
|
|
292
|
+
sessionId,
|
|
293
|
+
session,
|
|
294
|
+
mode,
|
|
295
|
+
draft,
|
|
296
|
+
seq,
|
|
297
|
+
key: JSON.stringify([
|
|
298
|
+
sessionId,
|
|
299
|
+
seq,
|
|
300
|
+
mode,
|
|
301
|
+
draft
|
|
302
|
+
])
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
/**
|
|
306
|
+
* Run one prediction, serving from or filling the bounded result cache.
|
|
307
|
+
* @returns `{ items, reason }`.
|
|
308
|
+
*/
|
|
309
|
+
async function runPrediction(ctx, options, cache, inflight, plan, signals, onDelta) {
|
|
310
|
+
const remembered = cache.get(plan.key);
|
|
311
|
+
if (remembered !== void 0) return {
|
|
312
|
+
items: remembered.items,
|
|
313
|
+
reason: void 0,
|
|
314
|
+
cached: true
|
|
315
|
+
};
|
|
316
|
+
const controller = new AbortController();
|
|
317
|
+
inflight.add(controller);
|
|
318
|
+
try {
|
|
319
|
+
const result = await predict(ctx, options, plan.session, plan.mode, plan.draft, joinSignals([controller.signal, ...signals]), onDelta);
|
|
320
|
+
if (result.items.length > 0 && !controller.signal.aborted && !signals.some((signal) => signal.aborted)) remember(cache, plan.key, { items: result.items });
|
|
321
|
+
return result;
|
|
322
|
+
} finally {
|
|
323
|
+
inflight.delete(controller);
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
/**
|
|
327
|
+
* Run one auxiliary model call over the transcript tail and tool activity.
|
|
328
|
+
* @returns `{ items }` on success or `{ items: [], reason }` when none is usable.
|
|
329
|
+
*/
|
|
330
|
+
async function predict(ctx, options, session, mode, draft, signal, onDelta) {
|
|
331
|
+
const prompt = buildPrompt(session, options, mode, draft);
|
|
332
|
+
if (prompt === null) return {
|
|
333
|
+
items: [],
|
|
334
|
+
reason: "no-conversation"
|
|
335
|
+
};
|
|
336
|
+
const route = resolveRoute(ctx, session, options);
|
|
337
|
+
if (route === void 0) return {
|
|
338
|
+
items: [],
|
|
339
|
+
reason: "no-route"
|
|
340
|
+
};
|
|
341
|
+
const system = (mode === "continue" ? CONTINUE_SYSTEM_PROMPT : NEXT_SYSTEM_PROMPT).replace("{max}", String(options.maxSuggestions));
|
|
342
|
+
const deadline = timedSignal(signal, options.timeoutMs);
|
|
343
|
+
let text = "";
|
|
344
|
+
let finish;
|
|
345
|
+
try {
|
|
346
|
+
deadline.signal.throwIfAborted();
|
|
347
|
+
const llm = getService(ctx, "llm");
|
|
348
|
+
if (!llm || typeof llm.prepareCall !== "function") return {
|
|
349
|
+
items: [],
|
|
350
|
+
reason: "no-llm"
|
|
351
|
+
};
|
|
352
|
+
let targetEffort = void 0;
|
|
353
|
+
if (typeof llm.resolveModelInfo === "function") {
|
|
354
|
+
const cacheKey = `${route.provider}:${route.model}`;
|
|
355
|
+
let effortIds = modelEffortsCache.get(cacheKey);
|
|
356
|
+
if (effortIds === void 0) try {
|
|
357
|
+
const efforts = (await llm.resolveModelInfo(route.provider, route.model, deadline.signal))?.reasoning?.efforts;
|
|
358
|
+
effortIds = Array.isArray(efforts) ? efforts.map((e) => e?.id).filter(Boolean) : [];
|
|
359
|
+
remember(modelEffortsCache, cacheKey, effortIds);
|
|
360
|
+
} catch {
|
|
361
|
+
effortIds = [];
|
|
362
|
+
}
|
|
363
|
+
if (effortIds && effortIds.length > 0) {
|
|
364
|
+
const requested = options.reasoningEffort || "off";
|
|
365
|
+
if (effortIds.includes(requested)) targetEffort = requested;
|
|
366
|
+
else if (effortIds.includes("off")) targetEffort = "off";
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
const baseConfig = {
|
|
370
|
+
provider: route.provider,
|
|
371
|
+
model: route.model,
|
|
372
|
+
maxTokens: options.maxOutputTokens
|
|
373
|
+
};
|
|
374
|
+
const callConfig = { ...baseConfig };
|
|
375
|
+
if (targetEffort !== void 0) callConfig.reasoningEffort = targetEffort;
|
|
376
|
+
let call;
|
|
377
|
+
try {
|
|
378
|
+
call = await llm.prepareCall(callConfig, deadline.signal);
|
|
379
|
+
} catch (error) {
|
|
380
|
+
const msg = String(error?.message || error?.code || "");
|
|
381
|
+
if (targetEffort !== void 0 && (error?.code === "UNSUPPORTED_REASONING_EFFORT" || msg.includes("does not support reasoning effort"))) call = await llm.prepareCall(baseConfig, deadline.signal);
|
|
382
|
+
else throw error;
|
|
383
|
+
}
|
|
384
|
+
const messages = [{
|
|
385
|
+
role: "user",
|
|
386
|
+
content: [{
|
|
387
|
+
type: "text",
|
|
388
|
+
text: prompt
|
|
389
|
+
}]
|
|
390
|
+
}];
|
|
391
|
+
for await (const chunk of call.stream({
|
|
392
|
+
...call.config,
|
|
393
|
+
messages,
|
|
394
|
+
system,
|
|
395
|
+
signal: deadline.signal
|
|
396
|
+
})) {
|
|
397
|
+
deadline.signal.throwIfAborted();
|
|
398
|
+
if (chunk.type === "text-delta") {
|
|
399
|
+
text += chunk.text;
|
|
400
|
+
onDelta?.(chunk.text);
|
|
401
|
+
} else if (chunk.type === "finish") finish = chunk.reason;
|
|
402
|
+
}
|
|
403
|
+
deadline.signal.throwIfAborted();
|
|
404
|
+
} finally {
|
|
405
|
+
deadline.dispose();
|
|
406
|
+
}
|
|
407
|
+
const failure = finishFailure(finish);
|
|
408
|
+
if (failure !== void 0) return {
|
|
409
|
+
items: [],
|
|
410
|
+
reason: failure
|
|
411
|
+
};
|
|
412
|
+
if (finish.kind === "max-tokens") text = text.slice(0, text.lastIndexOf("\n") + 1);
|
|
413
|
+
const cue = mode === "continue" ? CONTINUE_CUE : NEXT_CUE;
|
|
414
|
+
const items = normalizeCandidates(text, options.maxSuggestions, mode === "continue" ? draft : "", cue);
|
|
415
|
+
return items.length === 0 ? {
|
|
416
|
+
items: [],
|
|
417
|
+
reason: "empty"
|
|
418
|
+
} : { items };
|
|
419
|
+
}
|
|
420
|
+
/**
|
|
421
|
+
* The llm service ends a failed or cancelled stream with a `finish` chunk whose
|
|
422
|
+
* reason carries the normalized failure; only a missing terminal chunk is
|
|
423
|
+
* genuinely "unfinished".
|
|
424
|
+
*/
|
|
425
|
+
function finishFailure(finish) {
|
|
426
|
+
if (finish === void 0) return "unfinished";
|
|
427
|
+
if (finish.kind === "stop" || finish.kind === "max-tokens") return void 0;
|
|
428
|
+
const failure = finish.failure;
|
|
429
|
+
if (typeof failure?.message === "string" && failure.message !== "") return shortReason(failure.message);
|
|
430
|
+
if (typeof failure?.code === "string" && failure.code !== "") return failure.code;
|
|
431
|
+
return typeof finish.kind === "string" ? finish.kind : "unfinished";
|
|
432
|
+
}
|
|
433
|
+
function shortReason(text) {
|
|
434
|
+
return text.length > 200 ? `${text.slice(0, 200)}…` : text;
|
|
435
|
+
}
|
|
436
|
+
const modelEffortsCache = /* @__PURE__ */ new Map();
|
|
437
|
+
function remember(cache, key, entry) {
|
|
438
|
+
cache.delete(key);
|
|
439
|
+
cache.set(key, entry);
|
|
440
|
+
if (cache.size <= 200) return;
|
|
441
|
+
const oldest = cache.keys().next();
|
|
442
|
+
if (!oldest.done) cache.delete(oldest.value);
|
|
443
|
+
}
|
|
444
|
+
/** Prefer the route the Session already used, unless a fixed route is configured. */
|
|
445
|
+
function resolveRoute(ctx, session, options) {
|
|
446
|
+
if (options.provider !== "" && options.model !== "") return {
|
|
447
|
+
provider: options.provider,
|
|
448
|
+
model: options.model
|
|
449
|
+
};
|
|
450
|
+
const route = session.requestHeader()?.config;
|
|
451
|
+
if (typeof route?.provider === "string" && typeof route.model === "string") return route;
|
|
452
|
+
const fallback = ctx.get("agentDefaultModel")?.currentSelection();
|
|
453
|
+
if (typeof fallback?.provider === "string" && typeof fallback.model === "string") return fallback;
|
|
454
|
+
}
|
|
455
|
+
function extractToolResultText(block) {
|
|
456
|
+
if (block === null || typeof block !== "object") return "";
|
|
457
|
+
if (Array.isArray(block.content)) {
|
|
458
|
+
const text = block.content.map((item) => {
|
|
459
|
+
if (!item || typeof item !== "object") return "";
|
|
460
|
+
if (typeof item.text === "string") return item.text;
|
|
461
|
+
if (typeof item.result === "string") return item.result;
|
|
462
|
+
return "";
|
|
463
|
+
}).filter((t) => t !== "").join("\n").trim();
|
|
464
|
+
if (text !== "") return text;
|
|
465
|
+
}
|
|
466
|
+
if (typeof block.content === "string" && block.content !== "") return block.content.trim();
|
|
467
|
+
if (typeof block.result === "string" && block.result !== "") return block.result.trim();
|
|
468
|
+
if (typeof block.text === "string" && block.text !== "") return block.text.trim();
|
|
469
|
+
return "";
|
|
470
|
+
}
|
|
471
|
+
/**
|
|
472
|
+
* Render the conversation tail, recent tool activity, and (in continuation
|
|
473
|
+
* mode) the draft as one bounded prompt.
|
|
474
|
+
* @returns `null` when `next` mode has no completed assistant reply to follow.
|
|
475
|
+
*/
|
|
476
|
+
function buildPrompt(session, options, mode, draft) {
|
|
477
|
+
const picked = [];
|
|
478
|
+
const notes = [];
|
|
479
|
+
const callsById = /* @__PURE__ */ new Map();
|
|
480
|
+
for (const message of session.deriveMessages()) {
|
|
481
|
+
if (message === null || typeof message !== "object") continue;
|
|
482
|
+
const blocks = Array.isArray(message.content) ? message.content : [];
|
|
483
|
+
if (message.role === "user" || message.role === "assistant") {
|
|
484
|
+
const text = plainText(blocks);
|
|
485
|
+
if (text !== "") picked.push({
|
|
486
|
+
role: message.role,
|
|
487
|
+
text: clip(text, 1500)
|
|
488
|
+
});
|
|
489
|
+
if (message.role === "assistant" && options.maxToolNotes > 0) for (const block of blocks) {
|
|
490
|
+
if (block === null || typeof block !== "object" || block.type !== "tool-call") continue;
|
|
491
|
+
const note = {
|
|
492
|
+
name: typeof block.name === "string" ? block.name : "tool",
|
|
493
|
+
input: clip(typeof block.arguments === "string" ? block.arguments : "", 400),
|
|
494
|
+
result: "",
|
|
495
|
+
failed: false
|
|
496
|
+
};
|
|
497
|
+
notes.push(note);
|
|
498
|
+
if (typeof block.id === "string" && block.id !== "") callsById.set(block.id, note);
|
|
499
|
+
}
|
|
500
|
+
if (options.maxToolNotes > 0) for (const block of blocks) {
|
|
501
|
+
if (block === null || typeof block !== "object" || block.type !== "tool-result") continue;
|
|
502
|
+
const callId = typeof block.toolCallId === "string" ? block.toolCallId : typeof block.id === "string" ? block.id : "";
|
|
503
|
+
const resText = clip(extractToolResultText(block), 500);
|
|
504
|
+
const note = callId !== "" ? callsById.get(callId) : void 0;
|
|
505
|
+
if (note !== void 0) {
|
|
506
|
+
note.result = resText;
|
|
507
|
+
note.failed = block.isError === true;
|
|
508
|
+
} else notes.push({
|
|
509
|
+
name: "tool",
|
|
510
|
+
input: "",
|
|
511
|
+
result: resText,
|
|
512
|
+
failed: block.isError === true
|
|
513
|
+
});
|
|
514
|
+
}
|
|
515
|
+
continue;
|
|
516
|
+
}
|
|
517
|
+
if ((message.role === "tool" || message.source?.kind === "tool") && options.maxToolNotes > 0) {
|
|
518
|
+
let text = "";
|
|
519
|
+
for (const block of blocks) if (block !== null && typeof block === "object" && block.type === "tool-result") {
|
|
520
|
+
const callId = typeof block.toolCallId === "string" ? block.toolCallId : "";
|
|
521
|
+
const resText = clip(extractToolResultText(block), 500);
|
|
522
|
+
const note = callId !== "" ? callsById.get(callId) : void 0;
|
|
523
|
+
if (note !== void 0) {
|
|
524
|
+
note.result = resText;
|
|
525
|
+
note.failed = block.isError === true;
|
|
526
|
+
} else notes.push({
|
|
527
|
+
name: "tool",
|
|
528
|
+
input: "",
|
|
529
|
+
result: resText,
|
|
530
|
+
failed: block.isError === true
|
|
531
|
+
});
|
|
532
|
+
text = resText;
|
|
533
|
+
}
|
|
534
|
+
if (text === "") {
|
|
535
|
+
text = clip(plainText(blocks) || extractToolResultText(message), 500);
|
|
536
|
+
const callId = typeof message.toolCallId === "string" ? message.toolCallId : "";
|
|
537
|
+
const note = callId !== "" ? callsById.get(callId) : void 0;
|
|
538
|
+
if (note !== void 0) {
|
|
539
|
+
note.result = text;
|
|
540
|
+
note.failed = message.isError === true;
|
|
541
|
+
} else notes.push({
|
|
542
|
+
name: "tool",
|
|
543
|
+
input: "",
|
|
544
|
+
result: text,
|
|
545
|
+
failed: message.isError === true
|
|
546
|
+
});
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
if (mode === "next" && (picked.length === 0 || picked.at(-1)?.role !== "assistant")) return null;
|
|
551
|
+
const tail = picked.slice(-options.maxMessages);
|
|
552
|
+
const kept = [];
|
|
553
|
+
let budget = options.maxChars;
|
|
554
|
+
for (let index = tail.length - 1; index >= 0; index -= 1) {
|
|
555
|
+
const message = tail[index];
|
|
556
|
+
if (message.text.length > budget) {
|
|
557
|
+
if (budget > 200) kept.unshift({
|
|
558
|
+
role: message.role,
|
|
559
|
+
text: `…${message.text.slice(-budget)}`
|
|
560
|
+
});
|
|
561
|
+
break;
|
|
562
|
+
}
|
|
563
|
+
budget -= message.text.length;
|
|
564
|
+
kept.unshift(message);
|
|
565
|
+
}
|
|
566
|
+
const lines = ["Conversation tail (oldest first):", JSON.stringify(kept)];
|
|
567
|
+
const recent = options.maxToolNotes > 0 ? notes.slice(-options.maxToolNotes) : [];
|
|
568
|
+
if (recent.length > 0) {
|
|
569
|
+
lines.push("", "Recent tool activity (oldest first):");
|
|
570
|
+
for (const note of recent) {
|
|
571
|
+
const status = note.failed ? "failed" : "ok";
|
|
572
|
+
const result = note.result === "" ? "" : ` result=${JSON.stringify(clip(note.result, 320))}`;
|
|
573
|
+
lines.push(`- ${note.name}(${clip(note.input, 320)}) -> ${status}${result}`);
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
if (mode === "continue") lines.push("", "Draft text ending at the caret:", JSON.stringify(draft), "", CONTINUE_CUE);
|
|
577
|
+
else lines.push("", NEXT_CUE);
|
|
578
|
+
return lines.join("\n");
|
|
579
|
+
}
|
|
580
|
+
function plainText(blocks) {
|
|
581
|
+
return blocks.filter((block) => block !== null && typeof block === "object" && block.type === "text" && typeof block.text === "string").map((block) => block.text).join("\n").trim();
|
|
582
|
+
}
|
|
583
|
+
function clip(text, maximum) {
|
|
584
|
+
return text.length > maximum ? `${text.slice(0, maximum)}…` : text;
|
|
585
|
+
}
|
|
586
|
+
/** Split model output into clean, de-duplicated, bounded candidates. */
|
|
587
|
+
function normalizeCandidates(text, maximum, draft, cue = "") {
|
|
588
|
+
const items = [];
|
|
589
|
+
const seen = /* @__PURE__ */ new Set();
|
|
590
|
+
const prefix = draft === "" ? "" : draft.trimEnd();
|
|
591
|
+
const prefixLower = prefix.toLocaleLowerCase();
|
|
592
|
+
const cueIdentity = identityOf(cue);
|
|
593
|
+
for (const raw of text.split(/\r?\n/)) {
|
|
594
|
+
const hadLeadingSpace = /^\s/u.test(raw);
|
|
595
|
+
const line = raw.replace(/^(?:[-*•]|\d+[.)])\s+/u, "").replace(/^user\s*:\s*/iu, "").trim();
|
|
596
|
+
if (line === "") continue;
|
|
597
|
+
let body = line.replace(/^["'`\u201c\u201d]+|["'`\u201c\u201d]+$/gu, "").replace(/\s+/gu, " ");
|
|
598
|
+
if (body === "" || /^none$/iu.test(body)) continue;
|
|
599
|
+
if (prefixLower !== "" && body.toLocaleLowerCase().startsWith(prefixLower)) body = body.slice(prefix.length).replace(/^\s+/u, " ");
|
|
600
|
+
else if (draft !== "" && hadLeadingSpace && !/^\s/u.test(body)) body = ` ${body}`;
|
|
601
|
+
body = draft === "" ? body.trim() : body.replace(/\s+$/u, "");
|
|
602
|
+
if (body.trim() === "") continue;
|
|
603
|
+
body = boundSuggestion(body);
|
|
604
|
+
if (body === "") continue;
|
|
605
|
+
const identity = identityOf(body);
|
|
606
|
+
if (isInstructionEcho(identity, cueIdentity)) continue;
|
|
607
|
+
if (seen.has(identity)) continue;
|
|
608
|
+
seen.add(identity);
|
|
609
|
+
items.push(body);
|
|
610
|
+
if (items.length >= maximum) break;
|
|
611
|
+
}
|
|
612
|
+
return items;
|
|
613
|
+
}
|
|
614
|
+
/** Normalize a line for echo comparison: lowercase, no trailing punctuation. */
|
|
615
|
+
function identityOf(text) {
|
|
616
|
+
return text.replace(/[.:!?]+$/u, "").trim().toLocaleLowerCase();
|
|
617
|
+
}
|
|
618
|
+
/** Drop the prompt's own labels and task line when the model echoes them. */
|
|
619
|
+
function isInstructionEcho(identity, cueIdentity) {
|
|
620
|
+
if (identity === "") return true;
|
|
621
|
+
if (cueIdentity !== "" && (identity === cueIdentity || identity.startsWith(`${cueIdentity} `))) return true;
|
|
622
|
+
return PROMPT_LABELS.some((label) => identity === label || identity.startsWith(`${label} `));
|
|
623
|
+
}
|
|
624
|
+
function boundSuggestion(line) {
|
|
625
|
+
if (line.length <= 240) return line;
|
|
626
|
+
const cut = line.slice(0, 240);
|
|
627
|
+
const space = cut.lastIndexOf(" ");
|
|
628
|
+
return space > 120 ? cut.slice(0, space) : cut;
|
|
629
|
+
}
|
|
630
|
+
async function readJsonBody(request) {
|
|
631
|
+
if (typeof request.on === "function") return new Promise((resolve, reject) => {
|
|
632
|
+
const chunks = [];
|
|
633
|
+
let size = 0;
|
|
634
|
+
let settled = false;
|
|
635
|
+
const fail = (error) => {
|
|
636
|
+
if (settled) return;
|
|
637
|
+
settled = true;
|
|
638
|
+
request.resume?.();
|
|
639
|
+
reject(error);
|
|
640
|
+
};
|
|
641
|
+
request.on("data", (chunk) => {
|
|
642
|
+
if (settled) return;
|
|
643
|
+
size += chunk.length;
|
|
644
|
+
if (size > MAX_BODY_BYTES) {
|
|
645
|
+
fail(/* @__PURE__ */ new Error("body-too-large"));
|
|
646
|
+
return;
|
|
647
|
+
}
|
|
648
|
+
chunks.push(chunk);
|
|
649
|
+
});
|
|
650
|
+
request.on("end", () => {
|
|
651
|
+
if (settled) return;
|
|
652
|
+
settled = true;
|
|
653
|
+
try {
|
|
654
|
+
resolve(JSON.parse(Buffer.concat(chunks).toString("utf8")));
|
|
655
|
+
} catch (error) {
|
|
656
|
+
reject(error);
|
|
657
|
+
}
|
|
658
|
+
});
|
|
659
|
+
request.on("error", fail);
|
|
660
|
+
request.on("aborted", () => fail(/* @__PURE__ */ new Error("request-aborted")));
|
|
661
|
+
request.on("close", () => fail(/* @__PURE__ */ new Error("request-closed")));
|
|
662
|
+
});
|
|
663
|
+
if (request[Symbol.asyncIterator] !== void 0) {
|
|
664
|
+
const chunks = [];
|
|
665
|
+
let size = 0;
|
|
666
|
+
for await (const chunk of request) {
|
|
667
|
+
const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
668
|
+
size += buf.length;
|
|
669
|
+
if (size > MAX_BODY_BYTES) throw new Error("body-too-large");
|
|
670
|
+
chunks.push(buf);
|
|
671
|
+
}
|
|
672
|
+
return JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
673
|
+
}
|
|
674
|
+
throw new Error("unsupported-request-stream");
|
|
675
|
+
}
|
|
676
|
+
function openStream(response) {
|
|
677
|
+
response.writeHead(200, {
|
|
678
|
+
"content-type": "text/event-stream; charset=utf-8",
|
|
679
|
+
"cache-control": "no-store, no-transform",
|
|
680
|
+
"x-accel-buffering": "no"
|
|
681
|
+
});
|
|
682
|
+
response.flushHeaders?.();
|
|
683
|
+
}
|
|
684
|
+
function sendEvent(response, event) {
|
|
685
|
+
if (response.writableEnded || response.destroyed) return;
|
|
686
|
+
response.write(`data: ${JSON.stringify(event)}\n\n`);
|
|
687
|
+
}
|
|
688
|
+
function closeStream(response) {
|
|
689
|
+
if (response.writableEnded || response.destroyed) return;
|
|
690
|
+
response.end();
|
|
691
|
+
}
|
|
692
|
+
function watchDisconnect(response) {
|
|
693
|
+
const controller = new AbortController();
|
|
694
|
+
response.on("close", () => {
|
|
695
|
+
if (!response.writableEnded) controller.abort();
|
|
696
|
+
});
|
|
697
|
+
return controller;
|
|
698
|
+
}
|
|
699
|
+
function respond(response, status, payload) {
|
|
700
|
+
if (response.writableEnded || response.headersSent === true) return;
|
|
701
|
+
response.writeHead(status, {
|
|
702
|
+
"content-type": "application/json; charset=utf-8",
|
|
703
|
+
"cache-control": "no-store"
|
|
704
|
+
});
|
|
705
|
+
response.end(JSON.stringify(payload));
|
|
706
|
+
}
|
|
707
|
+
function joinSignals(signals) {
|
|
708
|
+
if (typeof AbortSignal.any === "function") return AbortSignal.any(signals);
|
|
709
|
+
const controller = new AbortController();
|
|
710
|
+
for (const signal of signals) {
|
|
711
|
+
if (signal.aborted) {
|
|
712
|
+
controller.abort();
|
|
713
|
+
break;
|
|
714
|
+
}
|
|
715
|
+
signal.addEventListener("abort", () => controller.abort(), { once: true });
|
|
716
|
+
}
|
|
717
|
+
return controller.signal;
|
|
718
|
+
}
|
|
719
|
+
function timedSignal(signal, timeoutMs) {
|
|
720
|
+
const controller = new AbortController();
|
|
721
|
+
const abort = () => controller.abort();
|
|
722
|
+
if (signal.aborted) controller.abort();
|
|
723
|
+
else signal.addEventListener("abort", abort, { once: true });
|
|
724
|
+
const timer = setTimeout(abort, timeoutMs);
|
|
725
|
+
return {
|
|
726
|
+
signal: controller.signal,
|
|
727
|
+
dispose() {
|
|
728
|
+
clearTimeout(timer);
|
|
729
|
+
signal.removeEventListener("abort", abort);
|
|
730
|
+
}
|
|
731
|
+
};
|
|
732
|
+
}
|
|
733
|
+
//#endregion
|
|
2
734
|
//#region src/composer-plugin.ts
|
|
3
735
|
const name = "codex-ui-composer";
|
|
4
736
|
const inject = ["webServer"];
|
|
5
|
-
/**
|
|
6
|
-
* 检查 profile 的 cordis.patch.yml 中是否显式配置了 disabled: true
|
|
7
|
-
* 避免在 DSH 桌面端未开启 HMR 或未重启时,内存 fiber 依然错误响应 enabled: true。
|
|
8
|
-
*/
|
|
9
737
|
function isSubPluginDisabledOnDisk(id, homeDir, ctx) {
|
|
10
738
|
return isSubPluginDisabledOnDisk$1(id, homeDir, ctx);
|
|
11
739
|
}
|
|
12
740
|
/**
|
|
13
741
|
* Composer 输入框增强子组件 (Host 侧)
|
|
14
|
-
*
|
|
15
|
-
*
|
|
742
|
+
* 1. 暴露 /api/michengai/dsh-codex-ui/composer (启停状态)
|
|
743
|
+
* 2. 暴露 /composer-prediction 与 /composer-prediction/v2 (参考插件标准流式预测)
|
|
16
744
|
*/
|
|
17
745
|
function apply(ctx) {
|
|
18
|
-
const
|
|
746
|
+
const statusEndpoint = CODEX_UI_API_ENDPOINTS.composer;
|
|
747
|
+
ctx.effect(() => {
|
|
748
|
+
if (isSubPluginDisabledOnDisk("codex-ui-composer", void 0, ctx)) return () => {};
|
|
749
|
+
apply$1(ctx);
|
|
750
|
+
return () => {};
|
|
751
|
+
}, "michengai-codex-ui: composer predictions engine");
|
|
19
752
|
ctx.effect(() => {
|
|
20
|
-
const webServer = ctx.get("webServer");
|
|
753
|
+
const webServer = ctx.webServer ?? ctx.get?.("webServer");
|
|
21
754
|
if (!webServer || typeof webServer.register !== "function") return () => {};
|
|
22
|
-
const
|
|
755
|
+
const disposeStatus = webServer.register({
|
|
23
756
|
kind: "exact",
|
|
24
|
-
path:
|
|
757
|
+
path: statusEndpoint,
|
|
25
758
|
handler: (_request, response) => {
|
|
26
759
|
const disabled = isSubPluginDisabledOnDisk("codex-ui-composer", void 0, ctx);
|
|
27
760
|
response.writeHead(200, {
|
|
@@ -32,7 +765,7 @@ function apply(ctx) {
|
|
|
32
765
|
}
|
|
33
766
|
});
|
|
34
767
|
return () => {
|
|
35
|
-
|
|
768
|
+
disposeStatus?.();
|
|
36
769
|
};
|
|
37
770
|
}, "michengai-codex-ui: composer state");
|
|
38
771
|
}
|