dsh-wechat-access 0.0.0-stage → 0.0.2

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.
Files changed (45) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/LICENSE +675 -0
  3. package/README.md +278 -2
  4. package/cordis.patch.yml +5 -0
  5. package/examples/config.example.json +98 -0
  6. package/index.mjs +123 -0
  7. package/lib/access.mjs +131 -0
  8. package/lib/anysearch.mjs +143 -0
  9. package/lib/capabilities.mjs +312 -0
  10. package/lib/client.js +2532 -0
  11. package/lib/config.mjs +509 -0
  12. package/lib/emotion-store.mjs +352 -0
  13. package/lib/emotion.mjs +428 -0
  14. package/lib/endocrine/LICENSE +21 -0
  15. package/lib/endocrine/README.md +39 -0
  16. package/lib/endocrine/diseases.js +791 -0
  17. package/lib/endocrine/engine.mjs +131 -0
  18. package/lib/endocrine/store.mjs +253 -0
  19. package/lib/endocrine/upstream.mjs +1230 -0
  20. package/lib/group-gate.mjs +305 -0
  21. package/lib/imagegen.mjs +360 -0
  22. package/lib/lock.mjs +204 -0
  23. package/lib/meme-classify.mjs +190 -0
  24. package/lib/memes.mjs +442 -0
  25. package/lib/memory.mjs +437 -0
  26. package/lib/normalize.mjs +230 -0
  27. package/lib/parser.mjs +602 -0
  28. package/lib/reply-settled.mjs +130 -0
  29. package/lib/runtime.mjs +3367 -0
  30. package/lib/startup.mjs +70 -0
  31. package/lib/steam-binding.mjs +144 -0
  32. package/lib/steam.mjs +334 -0
  33. package/lib/store.mjs +259 -0
  34. package/lib/thoughts.mjs +149 -0
  35. package/lib/time-context.mjs +182 -0
  36. package/lib/tools.mjs +583 -0
  37. package/lib/ui.mjs +997 -0
  38. package/lib/util.mjs +489 -0
  39. package/lib/virtual-life-generate.mjs +421 -0
  40. package/lib/virtual-life.mjs +971 -0
  41. package/lib/weather.mjs +172 -0
  42. package/lib/wechat-client.mjs +476 -0
  43. package/lib/wechat-events.mjs +269 -0
  44. package/locale/zh.json +6 -0
  45. package/package.json +77 -4
@@ -0,0 +1,421 @@
1
+ /**
2
+ * One-shot generation of the virtual life.
3
+ *
4
+ * A single agent turn produces the whole package: a seven-day schedule with real
5
+ * variation between days, a wardrobe pool and a meal pool. That is deliberately
6
+ * one call instead of one per day -- the persona keeps a stable life, and the user
7
+ * pays for generation once per week rather than every morning.
8
+ *
9
+ * The prompt is strict about JSON and about the two invariants that matter for
10
+ * lookup: the timeline must cover 00:00..24:00 with no gaps, and the seven days
11
+ * must actually differ. Everything else is validated and repaired afterwards by
12
+ * normalizeTimeline / normalizeOutfit / normalizeMeal, because a model that gets
13
+ * one boundary wrong should cost a repaired schedule, not a failed week.
14
+ */
15
+ import { normalizeTimeline, normalizeOutfit, normalizeMeal, WEEKDAYS, weekStartKey } from './virtual-life.mjs';
16
+ import { sessionEventList } from './runtime.mjs';
17
+ import { describeDay } from './weather.mjs';
18
+ import { hostSelection, stripHostPrompt } from './util.mjs';
19
+
20
+ const SYSTEM_PROMPT = `你是一个结构化生活生成器。只输出一个可被 JSON.parse 直接解析的 JSON 对象,禁止 Markdown 代码块、解释或任何额外文字。
21
+
22
+ 输出结构(字段名必须完全一致):
23
+ {
24
+ "longTerm": "一两句话说明当前人生阶段(学期/工作/假期等)",
25
+ "week": [
26
+ {
27
+ "weekday": 0,
28
+ "theme": "这一天的主题,4-10 字",
29
+ "mood": "这一天的基调心情,2-6 字",
30
+ "timeline": [
31
+ { "start": "00:00", "end": "07:00", "activity": "睡觉", "location": "宿舍", "state": "sleep", "availability": "blocked" }
32
+ ],
33
+ "proactiveWindows": [
34
+ { "at": "12:30", "intent": "想分享午饭吃了什么", "audience": "private" }
35
+ ]
36
+ }
37
+ ],
38
+ "outfits": [
39
+ { "style": "风格", "summary": "一句话概括", "weather": ["rain"], "tempMin": 10, "tempMax": 17, "pieces": [ { "category": "top", "name": "具体单品", "detail": "颜色材质等细节" } ] }
40
+ ],
41
+ "meals": [
42
+ { "slot": "breakfast", "place": "地点", "dishes": ["菜名"], "note": "一句话" }
43
+ ]
44
+ }
45
+
46
+ 硬性规则:
47
+ 1. week 必须正好 7 项,weekday 从 0 到 6,0 表示周一。
48
+ 2. 每天的 timeline 必须从 00:00 开始、到 24:00 结束,相邻项首尾相接,不得有空档、重叠或倒序。
49
+ 3. 只有最后一项的 end 可以是 24:00;其他时间一律补零 HH:MM。
50
+ 4. state 只能是 sleep / busy / focus / transit / available / social。
51
+ 5. availability 只能是 blocked / low / normal / high。
52
+ 6. 七天必须有实质差异:活动、地点、节奏至少两项不同,不能只换主题名。
53
+ 7. 工作日与周末的作息要明显不同(起床时间、安排密度)。
54
+ 8. outfits 生成 12-20 套,覆盖不同场合与季节感,pieces 至少 3 件且要具体(含颜色/材质/品牌感描述)。
55
+ 每套必须有这三个字段,缺任何一个这套就不合格:
56
+ - weather:这套适合的天气,只能从 rain / snow / sun / cloud / wind / any 里选,可多选。
57
+ any 只给打底衫、家居服、内衣这种确实不分天气的用,外套和下装一律写具体天气。
58
+ - tempMin:这套能穿的最低温度,单个整数,单位摄氏度。
59
+ - tempMax:这套能穿的最高温度,单个整数,单位摄氏度。
60
+ tempMin 和 tempMax 要写这套衣服实际能穿的范围,必须是你真的会穿的那个区间。
61
+ 例如厚羽绒服 tempMin=0 tempMax=10,薄卫衣 tempMin=12 tempMax=20,短袖 tempMin=22 tempMax=32。
62
+ 不要为了保险写成 0 和 40 这种什么都覆盖的范围,那等于没写。
63
+ 完整示例:
64
+ { "style": "雨天通勤", "weather": ["rain", "wind"], "tempMin": 10, "tempMax": 17,
65
+ "summary": "下雨降温也能干爽地走完早八",
66
+ "pieces": [{ "category": "outer", "name": "藏青色防水风衣", "detail": "哑光涂层" }] }
67
+ rain 至少 3 套、sun 至少 2 套、cloud 至少 3 套,否则某个天气永远只有一件可选。
68
+ 9. meals 每个 slot(breakfast / lunch / dinner)各生成 8-12 条,菜名具体,不要重复。
69
+ 10. proactiveWindows 每天 0-2 条,at 必须落在当天某个 timeline 时段内,intent 写成第一人称想做的事。`;
70
+
71
+ const GENERIC_ACTIVITIES = new Set([
72
+ '睡觉', '午休', '休息', '吃饭', '早餐', '午餐', '晚餐', '上课', '下课',
73
+ '通勤', '洗漱', '玩手机', '刷手机', '发呆', '回宿舍', '去教室',
74
+ '吃早饭', '吃午饭', '吃晚饭', '早饭', '午饭', '晚饭',
75
+ ]);
76
+
77
+ function uniqueElements(values, limit = 16) {
78
+ const seen = new Set();
79
+ const out = [];
80
+ for (const raw of Array.isArray(values) ? values : []) {
81
+ const text = String(raw ?? '').trim();
82
+ if (!text || seen.has(text)) continue;
83
+ seen.add(text);
84
+ out.push(text);
85
+ if (out.length >= limit) break;
86
+ }
87
+ return out;
88
+ }
89
+
90
+ function elementsOf(source) {
91
+ const week = source?.week && typeof source.week === 'object' ? Object.values(source.week) : [];
92
+ const themes = uniqueElements(week.map((day) => day?.theme), 12);
93
+ const activities = uniqueElements(week.flatMap((day) => (day?.timeline ?? []).map((item) => item?.activity)), 32)
94
+ .filter((text) => !GENERIC_ACTIVITIES.has(text))
95
+ .slice(0, 16);
96
+ const meals = uniqueElements((source?.meals ?? []).flatMap((meal) => meal?.dishes ?? []), 24);
97
+ const styles = uniqueElements((source?.outfits ?? []).map((outfit) => outfit?.style), 12);
98
+ return { themes, activities, meals, styles };
99
+ }
100
+
101
+ function overlapRatio(left, right) {
102
+ if (!left.length || !right.length) return null;
103
+ const set = new Set(left);
104
+ let hits = 0;
105
+ for (const item of right) if (set.has(item)) hits += 1;
106
+ return hits / Math.max(left.length, right.length);
107
+ }
108
+
109
+ /** 0..1,越高说明新一周和上一周越像。只比较有辨识度的元素。 */
110
+ export function lifeSimilarity(previous, next) {
111
+ const before = elementsOf(previous);
112
+ const after = elementsOf(next);
113
+ const parts = [
114
+ ['themes', '主题', 0.25],
115
+ ['activities', '活动', 0.5],
116
+ ['meals', '餐食', 0.15],
117
+ ['styles', '穿搭', 0.1],
118
+ ];
119
+ let weighted = 0;
120
+ let totalWeight = 0;
121
+ const repeated = [];
122
+ for (const [key, label, weight] of parts) {
123
+ const ratio = overlapRatio(before[key], after[key]);
124
+ if (ratio == null) continue;
125
+ weighted += ratio * weight;
126
+ totalWeight += weight;
127
+ if (ratio > 0) {
128
+ const set = new Set(before[key]);
129
+ const hits = after[key].filter((item) => set.has(item)).slice(0, 4);
130
+ if (hits.length) repeated.push(label + ':' + hits.join('、'));
131
+ }
132
+ }
133
+ return {
134
+ score: totalWeight ? Math.min(1, weighted / totalWeight) : 0,
135
+ repeated,
136
+ };
137
+ }
138
+
139
+ /**
140
+ * Build the user prompt from the persona and the previous life (if any).
141
+ *
142
+ * The previous week is summarised rather than pasted: reusing it verbatim makes
143
+ * the model repeat itself, while omitting it entirely loses continuity.
144
+ */
145
+ export function buildPrompt({ persona, previous, now = new Date(), weather = null, city = '' }) {
146
+ const lines = [];
147
+ lines.push('人格设定:');
148
+ lines.push(String(persona ?? '').slice(0, 6000) || '(未设置,按普通大学生写)');
149
+ lines.push('');
150
+ lines.push(`当前日期:${now.getFullYear()}年${now.getMonth() + 1}月${now.getDate()}日(${WEEKDAYS[(now.getDay() + 6) % 7]})`);
151
+
152
+ // 天气预报是这次生成里最实在的一条输入:没有它,模型只能按月份猜,
153
+ // 于是会出现「20 度的大晴天穿羽绒服」或者「下雨天没带伞」。
154
+ if (Array.isArray(weather) && weather.length) {
155
+ lines.push('');
156
+ lines.push(`未来一周${city ? '(' + city + ')' : ''}的天气预报:`);
157
+ for (const day of weather.slice(0, 7)) {
158
+ lines.push(`- ${day.date}:${describeDay(day)}`);
159
+ }
160
+ lines.push('');
161
+ lines.push('穿搭和日程必须按上面的实际天气来写:降温就加衣服,下雨就带伞、穿防水的鞋,');
162
+ lines.push('晴天热就别写厚外套。不要写和当天温度明显不符的搭配。');
163
+ }
164
+
165
+ if (previous?.ready) {
166
+ const prev = elementsOf(previous);
167
+ lines.push('');
168
+ lines.push('上一周的设定(保持人物连续性,但不要照抄):');
169
+ if (previous.longTerm) lines.push(`- 人生阶段:${previous.longTerm}`);
170
+ if (previous.weekStart) lines.push(`- 上周锚点:${previous.weekStart}`);
171
+ if (prev.themes.length) lines.push(`- 上周主题:${prev.themes.join('、')}`);
172
+ if (prev.activities.length) lines.push(`- 上周用过的具体活动:${prev.activities.slice(0, 12).join('、')}`);
173
+ if (prev.meals.length) lines.push(`- 上周吃过的菜:${prev.meals.slice(0, 12).join('、')}`);
174
+ if (prev.styles.length) lines.push(`- 上周的穿搭风格:${prev.styles.slice(0, 8).join('、')}`);
175
+ lines.push('- 新一周至少换掉 5 个每日主题;不要复用上面的具体活动、地点、菜品和穿搭风格。');
176
+ lines.push('- 只保留人物设定、性格和 longTerm 的连续性,不要把上一周当成模板。');
177
+ }
178
+ lines.push('');
179
+ lines.push('请按系统提示的 JSON 结构生成完整的一周。');
180
+ return lines.join('\n');
181
+ }
182
+
183
+ /** Pull a JSON object out of whatever the model returned. */
184
+ export function extractJsonObject(text) {
185
+ const source = String(text ?? '');
186
+ const fenced = source.match(/```(?:json)?\s*([\s\S]*?)```/i);
187
+ const body = fenced ? fenced[1] : source;
188
+ const start = body.indexOf('{');
189
+ if (start < 0) return null;
190
+ // Walk braces with string awareness: the payload contains quoted Chinese text
191
+ // and escaped quotes, so indexOf('}') is not enough.
192
+ let depth = 0, inString = false, escaped = false, end = -1;
193
+ for (let i = start; i < body.length; i++) {
194
+ const ch = body[i];
195
+ if (inString) {
196
+ if (escaped) { escaped = false; continue; }
197
+ if (ch === '\\') { escaped = true; continue; }
198
+ if (ch === '"') inString = false;
199
+ continue;
200
+ }
201
+ if (ch === '"') { inString = true; continue; }
202
+ if (ch === '{') depth++;
203
+ else if (ch === '}') { depth--; if (depth === 0) { end = i; break; } }
204
+ }
205
+ if (end < 0) return null;
206
+ try { return JSON.parse(body.slice(start, end + 1)); }
207
+ catch { return null; }
208
+ }
209
+
210
+ /**
211
+ * Turn a raw model payload into the shape VirtualLife stores.
212
+ *
213
+ * Days are placed by `weekday` when the model supplied one, and by position
214
+ * otherwise, so a model that forgets the field still produces a usable week.
215
+ */
216
+ export function normalizeGenerated(payload) {
217
+ const problems = [];
218
+ if (!payload || typeof payload !== 'object') return { ok: false, problems: ['不是对象'] };
219
+
220
+ const week = {};
221
+ const rawWeek = Array.isArray(payload.week) ? payload.week : [];
222
+ rawWeek.forEach((day, index) => {
223
+ if (!day || typeof day !== 'object') return;
224
+ const declared = Number(day.weekday);
225
+ const slot = Number.isInteger(declared) && declared >= 0 && declared <= 6 ? declared : index;
226
+ if (slot > 6) return;
227
+ const timeline = normalizeTimeline(day.timeline);
228
+ if (!timeline.length) { problems.push(`第 ${slot + 1} 天时间线为空`); return; }
229
+ const windows = (Array.isArray(day.proactiveWindows) ? day.proactiveWindows : [])
230
+ .map((w, wi) => {
231
+ const at = String(w?.at ?? '').trim();
232
+ if (!/^\d{1,2}:\d{2}$/.test(at)) return null;
233
+ return {
234
+ id: String(w?.id ?? `w-${slot}-${wi}`).trim() || `w-${slot}-${wi}`,
235
+ at,
236
+ intent: String(w?.intent ?? '').trim().slice(0, 120),
237
+ audience: ['private', 'group', 'both'].includes(String(w?.audience)) ? String(w.audience) : 'private',
238
+ };
239
+ })
240
+ .filter(Boolean)
241
+ .slice(0, 3);
242
+ week[String(slot)] = {
243
+ theme: String(day.theme ?? '').trim().slice(0, 40) || `第${slot + 1}天`,
244
+ mood: String(day.mood ?? '').trim().slice(0, 20) || '平静',
245
+ timeline,
246
+ proactiveWindows: windows,
247
+ };
248
+ });
249
+
250
+ if (Object.keys(week).length < 7) problems.push(`只有 ${Object.keys(week).length}/7 天有效`);
251
+
252
+ const outfits = (Array.isArray(payload.outfits) ? payload.outfits : []).map(normalizeOutfit).filter(Boolean);
253
+ const meals = (Array.isArray(payload.meals) ? payload.meals : []).map(normalizeMeal).filter(Boolean);
254
+ if (!outfits.length) problems.push('没有有效穿搭');
255
+ if (!meals.length) problems.push('没有有效餐食');
256
+
257
+ return {
258
+ ok: Object.keys(week).length === 7,
259
+ week,
260
+ longTerm: String(payload.longTerm ?? '').trim().slice(0, 1200),
261
+ outfits,
262
+ meals,
263
+ problems,
264
+ };
265
+ }
266
+
267
+ export class VirtualLifeGenerator {
268
+ constructor(runtime, { logger = console } = {}) {
269
+ this.runtime = runtime;
270
+ this.logger = logger;
271
+ this.running = false;
272
+ }
273
+
274
+ /**
275
+ * Generate and store a new week.
276
+ *
277
+ * One retry: a model that emits malformed JSON on the first attempt often gets
278
+ * it right on the second with the failure named. More retries than that just
279
+ * spends tokens on the same mistake.
280
+ */
281
+ async generate({ force = false } = {}) {
282
+ if (this.running) return { ok: false, reason: '已有生成任务在进行' };
283
+ const life = this.runtime.life;
284
+ if (!life) return { ok: false, reason: '虚拟人生未启用' };
285
+ await life.init();
286
+ if (life.ready && !force) return { ok: true, skipped: true, snapshot: life.snapshot() };
287
+
288
+ this.running = true;
289
+ const started = Date.now();
290
+ try {
291
+ const persona = this.runtime.config.persona ?? '';
292
+ const weatherCfg = this.runtime.config.weather ?? {};
293
+ // 天气拿不到就返回 null,这里不 try/catch 也不会炸 —— forecast() 自己吞掉了失败。
294
+ const forecast = weatherCfg.enabled
295
+ ? await this.runtime.weather?.forecast?.({ days: 7 })
296
+ : null;
297
+ if (weatherCfg.enabled && !forecast) {
298
+ this.logger?.warn?.('天气没拿到,这次生成会退化成按季节猜');
299
+ }
300
+ const previous = life.snapshot();
301
+ const prompt = buildPrompt({
302
+ persona,
303
+ previous,
304
+ weather: forecast,
305
+ city: weatherCfg.city ?? '',
306
+ });
307
+ let lastProblems = [];
308
+ for (let attempt = 1; attempt <= 2; attempt++) {
309
+ const text = await this.#ask(prompt, attempt > 1 ? lastProblems : null);
310
+ const payload = extractJsonObject(text);
311
+ if (!payload) { lastProblems = ['返回内容不是合法 JSON']; continue; }
312
+ const result = normalizeGenerated(payload);
313
+ if (result.ok) {
314
+ const similarity = previous.ready
315
+ ? lifeSimilarity(previous, { week: result.week, outfits: result.outfits, meals: result.meals })
316
+ : { score: 0, repeated: [] };
317
+ const tooSimilar = previous.ready && similarity.score >= 0.5;
318
+ if (tooSimilar && attempt === 1) {
319
+ lastProblems = [
320
+ `和上一周重复度 ${Math.round(similarity.score * 100)}%`
321
+ + (similarity.repeated.length ? `(重复:${similarity.repeated.join(';')})` : '')
322
+ + '。请换掉至少 5 个每日主题,并更换具体活动、地点、餐食和穿搭风格后重新输出。',
323
+ ];
324
+ continue;
325
+ }
326
+ const warnings = [...result.problems];
327
+ if (tooSimilar) {
328
+ warnings.push(`和上一周仍有一定重复(${Math.round(similarity.score * 100)}%),已接受本次结果。`);
329
+ this.logger?.warn?.('虚拟人生周计划与上一周仍有重复:' + similarity.repeated.join(';'));
330
+ }
331
+ const snapshot = await life.setWeek({
332
+ week: result.week,
333
+ longTerm: result.longTerm,
334
+ outfits: result.outfits,
335
+ meals: result.meals,
336
+ personaHash: null,
337
+ weekStart: weekStartKey(),
338
+ // 存下预报,drawFor 按当天天气挑穿搭要用。
339
+ forecast,
340
+ });
341
+ return {
342
+ ok: true,
343
+ attempt,
344
+ elapsedMs: Date.now() - started,
345
+ counts: snapshot.counts,
346
+ weekStart: snapshot.weekStart,
347
+ similarity: Math.round(similarity.score * 100) / 100,
348
+ warnings,
349
+ };
350
+ }
351
+ lastProblems = result.problems;
352
+ }
353
+ this.logger?.warn?.('虚拟人生生成结果不合格:' + lastProblems.join(';'));
354
+ return { ok: false, reason: '生成结果不合格:' + lastProblems.join(';'), problems: lastProblems, elapsedMs: Date.now() - started };
355
+ } catch (error) {
356
+ const reason = String(error?.message ?? error).slice(0, 300);
357
+ // A generation failure is invisible in the panel beyond a red line, and the
358
+ // panel is easy to miss. Record it where it can be found afterwards.
359
+ try {
360
+ const { appendFileSync } = await import('node:fs');
361
+ const { join } = await import('node:path');
362
+ const { homedir } = await import('node:os');
363
+ appendFileSync(join(homedir(), '.dsh-qq-access', 'debug.log'),
364
+ new Date().toISOString() + ' life generate FAILED: ' + String(error?.stack ?? error).slice(0, 2000) + '\n');
365
+ } catch { /* diagnostics must never break generation */ }
366
+ this.logger?.warn?.('虚拟人生生成失败:' + reason);
367
+ return { ok: false, reason, elapsedMs: Date.now() - started };
368
+ } finally {
369
+ this.running = false;
370
+ }
371
+ }
372
+
373
+ /** One throwaway agent turn; the reply is raw text. */
374
+ async #ask(prompt, problems) {
375
+ const runtime = this.runtime;
376
+ const defaultSelection = runtime.ctx.get?.('agentDefaultModel')?.currentSelection?.();
377
+ const route = Object.keys(runtime.config.route ?? {}).length ? runtime.config.route : undefined;
378
+ const agentOptions = route ?? hostSelection(defaultSelection);
379
+ const id = `qq-life-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
380
+ const handle = await runtime.ctx.agents.create({
381
+ sessionId: id,
382
+ meta: { cwd: runtime.config.dataDir },
383
+ ...(agentOptions ? { agentOptions } : {}),
384
+ setup: async (agentCtx) => {
385
+ stripHostPrompt(agentCtx);
386
+ // No tools: this turn must answer, not act.
387
+ if (typeof agentCtx.tools?.restrict === 'function') agentCtx.tools.restrict({ allow: [] });
388
+ agentCtx.systemPrompt.section({ name: 'virtual-life-generator', order: 500, text: SYSTEM_PROMPT });
389
+ },
390
+ });
391
+ try {
392
+ const content = [{ type: 'text', text: problems?.length
393
+ ? prompt + '\n\n上一次生成有以下问题,请修正后重新输出完整 JSON:\n- ' + problems.join('\n- ')
394
+ : prompt }];
395
+ const before = Number.isInteger(handle.agent.session?.seq) ? handle.agent.session.seq : 0;
396
+ handle.agent.followup(runtime.createUserMessage({ content, source: { kind: 'user' } }));
397
+ // A1 补漏:与 runtime 的 #waitAgentIdle 同款硬超时。
398
+ // 规划生成是面板触发的一次性操作,挂住会让面板请求一直 pending。
399
+ const idleMs = 180_000;
400
+ const idleOk = await Promise.race([
401
+ Promise.resolve().then(() => handle.agent.whenIdle()).then(() => true).catch(() => true),
402
+ new Promise((resolve) => { const t = setTimeout(() => resolve(false), idleMs); t.unref?.(); }),
403
+ ]);
404
+ if (!idleOk) {
405
+ try { handle.agent.cancel({ kind: 'user' }); } catch {}
406
+ throw new Error('规划生成回合超时(' + idleMs + 'ms)');
407
+ }
408
+ const events = sessionEventList(handle.agent.session).slice(before);
409
+ const texts = [];
410
+ for (const event of events) {
411
+ if (event.type !== 'assistant/message') continue;
412
+ for (const part of event.data?.message?.content ?? []) {
413
+ if (part?.type === 'text' && part.text) texts.push(part.text);
414
+ }
415
+ }
416
+ return texts.join('\n');
417
+ } finally {
418
+ try { await handle?.dispose?.(); } catch { /* the turn is over */ }
419
+ }
420
+ }
421
+ }