@istarry/dsh-chat-edit 0.0.0-stage → 0.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/lib/index.js ADDED
@@ -0,0 +1,652 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { Remote, RemoteError, TypertRemoteService } from "@deepseek-ai/dsh-typert-protocol";
3
+ import { SessionId } from "@deepseek-ai/dsh-session";
4
+ import { AttachmentError } from "@deepseek-ai/dsh-attachment";
5
+ //#region ../.build/tsc/index.js
6
+ var __runInitializers = function(thisArg, initializers, value) {
7
+ var useValue = arguments.length > 2;
8
+ for (var i = 0; i < initializers.length; i++) value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
9
+ return useValue ? value : void 0;
10
+ };
11
+ var __esDecorate = function(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
12
+ function accept(f) {
13
+ if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected");
14
+ return f;
15
+ }
16
+ var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
17
+ var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
18
+ var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
19
+ var _, done = false;
20
+ for (var i = decorators.length - 1; i >= 0; i--) {
21
+ var context = {};
22
+ for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
23
+ for (var p in contextIn.access) context.access[p] = contextIn.access[p];
24
+ context.addInitializer = function(f) {
25
+ if (done) throw new TypeError("Cannot add initializers after decoration has completed");
26
+ extraInitializers.push(accept(f || null));
27
+ };
28
+ var result = (0, decorators[i])(kind === "accessor" ? {
29
+ get: descriptor.get,
30
+ set: descriptor.set
31
+ } : descriptor[key], context);
32
+ if (kind === "accessor") {
33
+ if (result === void 0) continue;
34
+ if (result === null || typeof result !== "object") throw new TypeError("Object expected");
35
+ if (_ = accept(result.get)) descriptor.get = _;
36
+ if (_ = accept(result.set)) descriptor.set = _;
37
+ if (_ = accept(result.init)) initializers.unshift(_);
38
+ } else if (_ = accept(result)) if (kind === "field") initializers.unshift(_);
39
+ else descriptor[key] = _;
40
+ }
41
+ if (target) Object.defineProperty(target, contextIn.name, descriptor);
42
+ done = true;
43
+ };
44
+ var __addDisposableResource = function(env, value, async) {
45
+ if (value !== null && value !== void 0) {
46
+ if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
47
+ var dispose, inner;
48
+ if (async) {
49
+ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
50
+ dispose = value[Symbol.asyncDispose];
51
+ }
52
+ if (dispose === void 0) {
53
+ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
54
+ dispose = value[Symbol.dispose];
55
+ if (async) inner = dispose;
56
+ }
57
+ if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
58
+ if (inner) dispose = function() {
59
+ try {
60
+ inner.call(this);
61
+ } catch (e) {
62
+ return Promise.reject(e);
63
+ }
64
+ };
65
+ env.stack.push({
66
+ value,
67
+ dispose,
68
+ async
69
+ });
70
+ } else if (async) env.stack.push({ async: true });
71
+ return value;
72
+ };
73
+ var __disposeResources = (function(SuppressedError) {
74
+ return function(env) {
75
+ function fail(e) {
76
+ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
77
+ env.hasError = true;
78
+ }
79
+ var r, s = 0;
80
+ function next() {
81
+ while (r = env.stack.pop()) try {
82
+ if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
83
+ if (r.dispose) {
84
+ var result = r.dispose.call(r.value);
85
+ if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
86
+ fail(e);
87
+ return next();
88
+ });
89
+ } else s |= 1;
90
+ } catch (e) {
91
+ fail(e);
92
+ }
93
+ if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
94
+ if (env.hasError) throw env.error;
95
+ }
96
+ return next();
97
+ };
98
+ })(typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
99
+ var e = new Error(message);
100
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
101
+ });
102
+ /** 单次读回的最大字节数(base64 会再放大 4/3)。 */
103
+ const MAX_READ_BYTES = 128 * 1024 * 1024;
104
+ let ChatEdit = (() => {
105
+ let _classSuper = TypertRemoteService;
106
+ let _instanceExtraInitializers = [];
107
+ let _readFileAttachment_decorators;
108
+ let _rewriteBoundary_decorators;
109
+ let _readReply_decorators;
110
+ let _rewriteReply_decorators;
111
+ let _clearInbox_decorators;
112
+ let _discardSession_decorators;
113
+ return class ChatEdit extends _classSuper {
114
+ static {
115
+ const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
116
+ _readFileAttachment_decorators = [Remote("readFileAttachment")];
117
+ _rewriteBoundary_decorators = [Remote("rewriteBoundary")];
118
+ _readReply_decorators = [Remote("readReply")];
119
+ _rewriteReply_decorators = [Remote("rewriteReply")];
120
+ _clearInbox_decorators = [Remote("clearInbox")];
121
+ _discardSession_decorators = [Remote("discardSession")];
122
+ __esDecorate(this, null, _readFileAttachment_decorators, {
123
+ kind: "method",
124
+ name: "readFileAttachment",
125
+ static: false,
126
+ private: false,
127
+ access: {
128
+ has: (obj) => "readFileAttachment" in obj,
129
+ get: (obj) => obj.readFileAttachment
130
+ },
131
+ metadata: _metadata
132
+ }, null, _instanceExtraInitializers);
133
+ __esDecorate(this, null, _rewriteBoundary_decorators, {
134
+ kind: "method",
135
+ name: "rewriteBoundary",
136
+ static: false,
137
+ private: false,
138
+ access: {
139
+ has: (obj) => "rewriteBoundary" in obj,
140
+ get: (obj) => obj.rewriteBoundary
141
+ },
142
+ metadata: _metadata
143
+ }, null, _instanceExtraInitializers);
144
+ __esDecorate(this, null, _readReply_decorators, {
145
+ kind: "method",
146
+ name: "readReply",
147
+ static: false,
148
+ private: false,
149
+ access: {
150
+ has: (obj) => "readReply" in obj,
151
+ get: (obj) => obj.readReply
152
+ },
153
+ metadata: _metadata
154
+ }, null, _instanceExtraInitializers);
155
+ __esDecorate(this, null, _rewriteReply_decorators, {
156
+ kind: "method",
157
+ name: "rewriteReply",
158
+ static: false,
159
+ private: false,
160
+ access: {
161
+ has: (obj) => "rewriteReply" in obj,
162
+ get: (obj) => obj.rewriteReply
163
+ },
164
+ metadata: _metadata
165
+ }, null, _instanceExtraInitializers);
166
+ __esDecorate(this, null, _clearInbox_decorators, {
167
+ kind: "method",
168
+ name: "clearInbox",
169
+ static: false,
170
+ private: false,
171
+ access: {
172
+ has: (obj) => "clearInbox" in obj,
173
+ get: (obj) => obj.clearInbox
174
+ },
175
+ metadata: _metadata
176
+ }, null, _instanceExtraInitializers);
177
+ __esDecorate(this, null, _discardSession_decorators, {
178
+ kind: "method",
179
+ name: "discardSession",
180
+ static: false,
181
+ private: false,
182
+ access: {
183
+ has: (obj) => "discardSession" in obj,
184
+ get: (obj) => obj.discardSession
185
+ },
186
+ metadata: _metadata
187
+ }, null, _instanceExtraInitializers);
188
+ if (_metadata) Object.defineProperty(this, Symbol.metadata, {
189
+ enumerable: true,
190
+ configurable: true,
191
+ writable: true,
192
+ value: _metadata
193
+ });
194
+ }
195
+ /** 读文件必须拿到附件服务;否则本插件激活前就把 `this.ctx.attachments` 读穿。 */
196
+ static inject = ["attachments"];
197
+ /** @param ctx - 携带会话、附件与可选清理存储的宿主上下文。 */
198
+ constructor(ctx) {
199
+ super(ctx, "chatEdit");
200
+ __runInitializers(this, _instanceExtraInitializers);
201
+ }
202
+ /**
203
+ * 读回一个文件附件的原始字节,用会话自己的事件日志做授权。
204
+ * @param request - 会话与附件标识。
205
+ * @returns 存储时的显示名与 base64 字节。
206
+ */
207
+ async readFileAttachment(request) {
208
+ const ref = referencedFile(await this.sessionEvents(request.sessionId), request.attachmentId);
209
+ if (ref === void 0) throw new RemoteError("session/attachment-invalid", "File is not referenced by this session.", { reason: "ATTACHMENT_NOT_REFERENCED" });
210
+ if (ref.bytes > MAX_READ_BYTES) throw new RemoteError("session/attachment-invalid", `File exceeds the read-back size limit (${String(MAX_READ_BYTES)} bytes).`, { reason: "ATTACHMENT_TOO_LARGE" });
211
+ try {
212
+ const chunks = [];
213
+ let total = 0;
214
+ for await (const chunk of this.ctx.attachments.readFileStream(ref)) {
215
+ chunks.push(chunk);
216
+ total += chunk.byteLength;
217
+ }
218
+ const bytes = new Uint8Array(total);
219
+ let offset = 0;
220
+ for (const chunk of chunks) {
221
+ bytes.set(chunk, offset);
222
+ offset += chunk.byteLength;
223
+ }
224
+ return {
225
+ name: ref.name,
226
+ data: Buffer.from(bytes).toString("base64")
227
+ };
228
+ } catch (error) {
229
+ if (error instanceof AttachmentError) throw new RemoteError("session/attachment-invalid", error.message, { reason: error.code });
230
+ throw new RemoteError("gateway/internal", "Unable to read file attachment.", {});
231
+ }
232
+ }
233
+ /**
234
+ * 为一条持久 `user/message` 定位改写用的分叉边界。
235
+ *
236
+ * 切点只有一个含义:**前一个轮次自己的 `turn/end`**。绝不能在「下一个 turn/start
237
+ * 减一」或「seq 减一」这类事件间隙里切:那条消息之前的空隙里既有会话开场事件,也有
238
+ * 用 queue 模式发消息时写下的 `agent/inbox/spliced`——它们承载着源会话自己的待发
239
+ * 消息。在空隙处分叉会把它们原样搬进子会话的收件箱,子会话的下一轮再把它们当成
240
+ * 注入的用户消息重发一遍:**表现就是「第一条消息编辑重发会连发两次」**。
241
+ *
242
+ * 所以这条消息之前**没有已完成的轮次**时(也就是它本来就是第一条消息),一律返回
243
+ * null,让调用方走「干净新建」的路径;预设、模型这类东西由客户端另行继承。
244
+ * @param request - 会话与锚定消息的 seq。
245
+ * @returns 前缀的含端边界;没有已完成的轮次时 null。
246
+ */
247
+ async rewriteBoundary(request) {
248
+ const events = await this.sessionEvents(request.sessionId);
249
+ let lastTurnEnd;
250
+ for (const event of events) {
251
+ if (event.seq >= request.seq) break;
252
+ if (event.type === "turn/end") lastTurnEnd = event.seq;
253
+ }
254
+ return { atSeq: lastTurnEnd ?? null };
255
+ }
256
+ /**
257
+ * 读一条 AI 回复里可编辑的正文——**返回这一轮的全部正文段**。
258
+ *
259
+ * 一轮里往往有多条 `assistant/message`(工具调用密集时几十条),带正文的那几条在
260
+ * 界面上显示成一段段文字。只给最后一条会改不到前面的段,所以这里整轮列出来,
261
+ * 由界面让哥哥挑哪一段。
262
+ * @param request - 会话与定位锚点(界面给的是 messageId)。
263
+ * @returns 轮次号与所有带正文的段。
264
+ */
265
+ async readReply(request) {
266
+ const events = await this.sessionEvents(request.sessionId);
267
+ const anchor = locateReply(events, request.sessionId, request.messageId, request.turn, request.step);
268
+ const replies = [];
269
+ for (const event of events) {
270
+ if (event.type !== "assistant/message") continue;
271
+ const data = event.data;
272
+ if (data.turn !== anchor.turn) continue;
273
+ const content = data.message?.content ?? [];
274
+ const textBlocks = content.filter((block) => block.type === "text").map((block) => block.text ?? "");
275
+ if (textBlocks.length === 0) continue;
276
+ replies.push({
277
+ step: data.step ?? 0,
278
+ textBlocks,
279
+ hasToolCalls: content.some((block) => block.type === "tool-call"),
280
+ preview: textBlocks.join("").replace(/\s+/gu, " ").slice(0, 120)
281
+ });
282
+ }
283
+ replies.sort((left, right) => left.step - right.step);
284
+ return {
285
+ turn: anchor.turn,
286
+ replies
287
+ };
288
+ }
289
+ /**
290
+ * 改掉一条 AI 回复的正文,产出一条新会话。
291
+ *
292
+ * 做法是**整份复制 + 只替换那一条**:源会话的全部事件原样搬进新会话,只在目标
293
+ * `assistant/message` 上换掉 text 块。这样轮次数量、消息条数、工具调用、思考块
294
+ * 一个不少,只有那句字变了。
295
+ *
296
+ * 为什么不用 fork:fork 的语义是「从切点重新开始」,它只保留切点之前的内容、后面
297
+ * 全丢(表现为「改一条回复,后续消息全消失」),而且会给未闭合的轮次补一个
298
+ * `turn/end(forked)`,界面因此多出一个「已完成」横条。
299
+ *
300
+ * 为什么只换 text:思考块回传后会被服务器整段丢弃、不计 token,改了也读不到;
301
+ * 工具调用块动了会破坏 `tool_use` / `tool_result` 配对。
302
+ * @param request - 会话、定位锚点与改写后的正文。
303
+ * @returns 新会话 id。
304
+ */
305
+ async rewriteReply(request) {
306
+ const events = await this.sessionEvents(request.sessionId);
307
+ const reply = locateReply(events, request.sessionId, request.messageId, request.turn, request.step);
308
+ const originalTextCount = reply.content.filter((block) => block.type === "text").length;
309
+ if (request.textBlocks.length !== originalTextCount) throw new RemoteError("reply-edit/block-mismatch", `this reply has ${String(originalTextCount)} text block(s), but ${String(request.textBlocks.length)} were given`, {
310
+ expected: originalTextCount,
311
+ actual: request.textBlocks.length
312
+ });
313
+ let cursor = 0;
314
+ const newContent = reply.content.map((block) => {
315
+ if (block.type !== "text") return block;
316
+ const next = request.textBlocks[cursor] ?? "";
317
+ cursor += 1;
318
+ return {
319
+ ...block,
320
+ text: next
321
+ };
322
+ });
323
+ const seed = events.map((event) => {
324
+ if (event.seq !== reply.seq) return event;
325
+ const data = event.data;
326
+ return {
327
+ ...event,
328
+ data: {
329
+ ...event.data,
330
+ message: {
331
+ ...data.message,
332
+ content: newContent
333
+ }
334
+ }
335
+ };
336
+ });
337
+ return { sessionId: await createSeededSession(this.ctx, seed, request.sessionId) };
338
+ }
339
+ /**
340
+ * 清空一个会话的待发消息队列。
341
+ *
342
+ * 为什么需要它:「编辑重发」会 fork 出一份前缀,而前缀里可能带着**没被清理掉**的
343
+ * `agent/inbox/spliced` 插入记录(DSH 在轮末偶尔漏掉配对的移除)。子会话回放这些
344
+ * 记录后,认为「队列里还有一条待发消息」,于是先把那条老消息发一遍,再发哥哥新编辑
345
+ * 的内容 —— 表现就是「先重复一遍原内容」。
346
+ *
347
+ * 继承来的排队消息对「从这条重新生成」毫无意义,所以这里整队清掉:回放算出每个
348
+ * 队列的当前长度,再追加一条等量的移除记录。
349
+ * @param request - 要清空队列的会话。
350
+ * @returns 实际移除的条数。
351
+ */
352
+ async clearInbox(request) {
353
+ const child = liveSession(this.ctx, request.sessionId);
354
+ if (child === void 0) return { removed: 0 };
355
+ const events = await this.sessionEvents(request.sessionId);
356
+ const pending = /* @__PURE__ */ new Map();
357
+ for (const event of events) {
358
+ if (event.type !== "agent/inbox/spliced") continue;
359
+ const data = event.data;
360
+ const target = data.target ?? "next-turn";
361
+ const before = pending.get(target) ?? 0;
362
+ const removed = Math.min(data.removedCount ?? 0, before);
363
+ pending.set(target, before - removed + (data.inserted?.length ?? 0));
364
+ }
365
+ let total = 0;
366
+ for (const [target, count] of pending) {
367
+ if (count <= 0) continue;
368
+ child.appendAny("agent/inbox/spliced", {
369
+ target,
370
+ start: 0,
371
+ removedCount: count,
372
+ inserted: []
373
+ });
374
+ total += count;
375
+ }
376
+ return { removed: total };
377
+ }
378
+ /**
379
+ * 持久删除一个会话:日志产物、投影缓存行、工作区分账。运行中的 Agent 拒绝;已打开
380
+ * 但空闲的 Agent 走注册表的内部 detach 摘除;运行时存储不支持删除时返回稳定错误码,
381
+ * 前端据此降级。
382
+ * @param request - 要从存储里移除的会话。
383
+ */
384
+ async discardSession(request) {
385
+ const sessionId = request.sessionId;
386
+ const agents = this.ctx.get("agents");
387
+ if ((agents?.get(sessionId))?.status === "running") throw new RemoteError("edit-regen/session-busy", `session "${sessionId}" is running; stop its conversation before deleting`, {
388
+ sessionId,
389
+ reason: "running"
390
+ });
391
+ if (agents?.get(sessionId) !== void 0 && !detachIdleAgent(this.ctx, sessionId)) throw new RemoteError("edit-regen/session-busy", `session "${sessionId}" is still open; close its conversation before deleting`, {
392
+ sessionId,
393
+ reason: "open"
394
+ });
395
+ const persistence = this.ctx.get("sessionPersistence");
396
+ if (persistence?.remove === void 0) throw new RemoteError("edit-regen/remove-unavailable", `this deployment's session storage does not support deletion`, {
397
+ sessionId,
398
+ reason: "storage without deletion support"
399
+ });
400
+ if (!await persistence.remove(sessionId)) throw new RemoteError("edit-regen/session-not-found", `session "${sessionId}" not found`, { sessionId });
401
+ await this.ctx.get("sessionProjectionCache")?.forget?.(sessionId);
402
+ await this.ctx.get("workspaceRegistry")?.forgetSession?.(sessionId);
403
+ this.ctx.emit("api-session/removed", SessionId(sessionId));
404
+ }
405
+ /**
406
+ * 取指定会话的事件:已挂载 Agent 用它的快照,否则走一次冷查询(不修复、不恢复、
407
+ * 不发布)。
408
+ *
409
+ * 一律走 `ctx.get(...)` 软取,不用 `this.ctx.sessions`:属性访问是按 fiber 注入检查
410
+ * 过的,本插件只 inject 了 `attachments`,读别的服务会直接抛
411
+ * "cannot get property … without inject"(网关把这条当 gateway/internal 抛给前端)。
412
+ */
413
+ async sessionEvents(sessionId) {
414
+ const env_1 = {
415
+ stack: [],
416
+ error: void 0,
417
+ hasError: false
418
+ };
419
+ try {
420
+ const id = SessionId(sessionId);
421
+ const attached = this.ctx.get("sessions")?.get(id);
422
+ if (attached !== void 0) return attached.snapshotEvents();
423
+ const query = this.ctx.get("sessionQuery");
424
+ if (query === void 0) throw new RemoteError("gateway/internal", `session "${sessionId}" cannot be inspected: no session query service`, { sessionId });
425
+ return [...__addDisposableResource(env_1, await query.observeSession(id, { projectionMode: "none" }), false).events];
426
+ } catch (e_1) {
427
+ env_1.error = e_1;
428
+ env_1.hasError = true;
429
+ } finally {
430
+ __disposeResources(env_1);
431
+ }
432
+ }
433
+ };
434
+ })();
435
+ /**
436
+ * 取一个已创建(不必被持有)的会话对象,用于追加事件。
437
+ * @param ctx - 宿主上下文。
438
+ * @param sessionId - 会话 id。
439
+ * @returns 可追加的会话面;会话不存在时 undefined。
440
+ */
441
+ function liveSession(ctx, sessionId) {
442
+ const raw = ctx.get("sessions")?.get(SessionId(sessionId));
443
+ if (raw === void 0) return void 0;
444
+ return { appendAny: (type, data) => raw.append(type, data) };
445
+ }
446
+ /**
447
+ * 通过注册表的内部 detach 摘除一个空闲 Agent。
448
+ * @param ctx - 携带 agents 服务的宿主上下文。
449
+ * @param sessionId - 要摘除的 Agent / 会话 id。
450
+ * @returns 是否真的摘除了注册表条目。
451
+ */
452
+ function detachIdleAgent(ctx, sessionId) {
453
+ const registry = ctx.get("agents");
454
+ const entry = registry?.store?.get(sessionId);
455
+ if (entry === void 0 || typeof registry?.detachEntered !== "function") return false;
456
+ try {
457
+ registry.detachEntered(entry);
458
+ return true;
459
+ } catch {
460
+ return false;
461
+ }
462
+ }
463
+ /**
464
+ * 在会话事件里找第一条 attachment id 命中的 `file` 内容块(与官方图片扫描同构)。
465
+ * @param events - 授权用的事件序列。
466
+ * @param attachmentId - 请求的附件 id。
467
+ * @returns 存储引用;未被引用时 undefined。
468
+ */
469
+ function referencedFile(events, attachmentId) {
470
+ for (const event of events) {
471
+ const found = fileInEvent(event, (ref) => String(ref.attachmentId) === attachmentId);
472
+ if (found !== void 0) return found;
473
+ }
474
+ }
475
+ function fileInEvent(event, match) {
476
+ const data = event.data;
477
+ switch (event.type) {
478
+ case "user/message":
479
+ case "tool/ptc-dispatch": return fileBlockIn(data.content, match);
480
+ case "system/message":
481
+ case "developer/message":
482
+ case "tool/result":
483
+ case "team/message/queued": return fileBlockIn(data.message?.content, match);
484
+ case "agent/inbox/spliced": {
485
+ const messages = data.inserted;
486
+ if (!Array.isArray(messages)) return void 0;
487
+ for (const message of messages) {
488
+ if (typeof message !== "object" || message === null || Array.isArray(message)) continue;
489
+ const found = fileBlockIn(message.content, match);
490
+ if (found !== void 0) return found;
491
+ }
492
+ return;
493
+ }
494
+ default: return;
495
+ }
496
+ }
497
+ function fileBlockIn(content, match) {
498
+ if (!Array.isArray(content)) return void 0;
499
+ for (const value of content) {
500
+ if (typeof value !== "object" || value === null || Array.isArray(value)) continue;
501
+ const block = value;
502
+ if (block.type === "file" && typeof block.attachment === "object" && block.attachment !== null) {
503
+ const ref = block.attachment;
504
+ if (match(ref)) return ref;
505
+ }
506
+ }
507
+ }
508
+ /**
509
+ * 定位一条 AI 回复:先按消息 id,找不到再按 `turn` + `step` 取那个步里最后一条。
510
+ *
511
+ * 双锚点的原因:界面的 `finalNode.messageId` 只在「这一块由一条 assistant/message
512
+ * 定型」时才有;中断补齐或未定型时它是 undefined,只靠它会让入口根本不出现。
513
+ * @param events - 会话事件。
514
+ * @param sessionId - 仅用于错误详情。
515
+ * @param messageId - 目标消息 id(可缺)。
516
+ * @param turn - 目标轮次号(可缺)。
517
+ * @param step - 目标步号(可缺)。
518
+ * @returns 定位结果。
519
+ */
520
+ function locateReply(events, sessionId, messageId, turn, step) {
521
+ if (messageId !== void 0 && messageId !== "") for (const event of events) {
522
+ const data = event.data;
523
+ if (data.message?.id !== messageId) continue;
524
+ if (event.type !== "assistant/message") throw new RemoteError("reply-edit/not-assistant", `message "${messageId}" belongs to a "${event.type}" event, not an assistant reply`, {
525
+ sessionId,
526
+ messageId
527
+ });
528
+ return {
529
+ seq: event.seq,
530
+ turn: data.turn ?? 0,
531
+ step: data.step ?? 0,
532
+ content: data.message.content ?? []
533
+ };
534
+ }
535
+ if (turn !== void 0 && step !== void 0) {
536
+ let found;
537
+ for (const event of events) {
538
+ if (event.type !== "assistant/message") continue;
539
+ const data = event.data;
540
+ if (data.turn !== turn || data.step !== step) continue;
541
+ if (data.message === void 0) continue;
542
+ found = {
543
+ seq: event.seq,
544
+ turn: data.turn ?? 0,
545
+ step: data.step ?? 0,
546
+ content: data.message.content ?? []
547
+ };
548
+ }
549
+ if (found !== void 0) return found;
550
+ }
551
+ throw new RemoteError("reply-edit/missing-event", `session "${sessionId}" has no assistant reply for ${messageId !== void 0 ? `message "${messageId}"` : `turn ${String(turn ?? "?")} step ${String(step ?? "?")}`}`, {
552
+ sessionId,
553
+ messageId: messageId ?? ""
554
+ });
555
+ }
556
+ /**
557
+ * 用一份完整事件序列创建一个新会话。
558
+ *
559
+ * 照官方 `fork` 的创建方式(`ctx.agents.create` + `seed`),但不做「切前缀」——
560
+ * 整份喂进去,所以新会话与源会话结构完全一致。建完还要把它挂到源会话所属的工作区,
561
+ * 否则侧栏里会掉进「未分组」。
562
+ *
563
+ * cwd、模型、预设、setup 都从源会话继承,新会话才能接着正常干活。
564
+ * @param ctx - 宿主上下文。
565
+ * @param seed - 要写入的完整事件序列。
566
+ * @param sourceSessionId - 源会话 id(继承 cwd、模型与工作区)。
567
+ * @returns 新会话 id。
568
+ */
569
+ async function createSeededSession(ctx, seed, sourceSessionId) {
570
+ const agents = ctx.get("agents");
571
+ if (agents === void 0) throw new RemoteError("gateway/internal", "agents service is unavailable", {});
572
+ const cwd = ctx.get("sessions")?.get(SessionId(sourceSessionId))?.header?.cwd;
573
+ let provider;
574
+ let model;
575
+ let reasoningEffort;
576
+ for (const event of seed) {
577
+ if (event.type !== "model/selection") continue;
578
+ const data = event.data;
579
+ if (data?.provider !== void 0 && data.model !== void 0) {
580
+ provider = data.provider;
581
+ model = data.model;
582
+ reasoningEffort = data.reasoningEffort;
583
+ }
584
+ }
585
+ if (provider === void 0 || model === void 0) {
586
+ const defaults = ctx.get("agentDefaultModel");
587
+ try {
588
+ const sel = defaults?.currentSelection();
589
+ provider = sel?.provider;
590
+ model = sel?.model;
591
+ reasoningEffort = sel?.reasoningEffort;
592
+ } catch {}
593
+ }
594
+ const query = ctx.get("sessionQuery");
595
+ const composer = ctx.get("sessionController")?.agents;
596
+ const presets = ctx.get("agentPresets");
597
+ if (query === void 0 || composer === void 0 && presets === void 0) throw new RemoteError("gateway/internal", "reply-edit: cannot compose an Agent preset for the new session; refusing to create a crippled session", {});
598
+ const composition = await (async () => {
599
+ const env_2 = {
600
+ stack: [],
601
+ error: void 0,
602
+ hasError: false
603
+ };
604
+ try {
605
+ const observation = __addDisposableResource(env_2, await query.observeSession(SessionId(sourceSessionId)), false);
606
+ if (composer !== void 0 && typeof composer.composeAgent === "function" && typeof composer.presetForObservation === "function") return await composer.composeAgent(composer.presetForObservation(observation));
607
+ if (presets === void 0) throw new RemoteError("gateway/internal", "reply-edit: no Agent preset service; refusing to create a crippled session", {});
608
+ const projected = observation;
609
+ const resolvedId = (await presets.resolve(projected.projections?.values?.agentPreset)).id;
610
+ return {
611
+ agentPreset: resolvedId,
612
+ setup: (agentCtx) => presets.mount(agentCtx, resolvedId)
613
+ };
614
+ } catch (e_2) {
615
+ env_2.error = e_2;
616
+ env_2.hasError = true;
617
+ } finally {
618
+ __disposeResources(env_2);
619
+ }
620
+ })();
621
+ const agentPreset = composition.agentPreset;
622
+ const setup = composition.setup;
623
+ if (setup === void 0) throw new RemoteError("gateway/internal", "reply-edit: Agent composition produced no setup; refusing to create a crippled session", {});
624
+ const childId = `session-${randomUUID()}`;
625
+ let inheritedEventCount = seed.length;
626
+ for (const [index, event] of seed.entries()) if (event.type === "session/end-seed" && event.data.inherited === true) inheritedEventCount = index;
627
+ await agents.create({
628
+ sessionId: childId,
629
+ seed,
630
+ inheritedEventCount,
631
+ meta: {
632
+ ...cwd === void 0 ? {} : { cwd },
633
+ isSeeded: true,
634
+ ...agentPreset === void 0 ? {} : { agentPreset }
635
+ },
636
+ ...provider === void 0 || model === void 0 ? {} : { agentOptions: {
637
+ provider,
638
+ model,
639
+ ...reasoningEffort === void 0 ? {} : { reasoningEffort }
640
+ } },
641
+ ...setup === void 0 ? {} : { setup }
642
+ });
643
+ const workspace = ctx.get("workspaceRegistry")?.list().find((candidate) => candidate.sessionIds.includes(sourceSessionId));
644
+ if (workspace?.attachSession !== void 0) try {
645
+ await workspace.attachSession(childId);
646
+ } catch (reason) {
647
+ console.warn("reply-edit: created the new session but could not attach it to its workspace:", reason);
648
+ }
649
+ return childId;
650
+ }
651
+ //#endregion
652
+ export { ChatEdit as default };