@yeaft/webchat-agent 1.0.440 → 1.0.442

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.
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * dream/segment.js.
3
3
  *
4
- * Three independent length-control concerns, kept pure so they can be
4
+ * Four independent length-control concerns, kept pure so they can be
5
5
  * unit-tested without touching disk or any LLM:
6
6
  *
7
7
  * 1. truncateMessage — clamp a single message body to
@@ -21,15 +21,21 @@
21
21
  *
22
22
  * 4. needsBatchedApply / batchSourcesForApply — when an Apply target's
23
23
  * memory + summary + sources cumulatively exceed MAX_APPLY_TOKENS,
24
- * split the sources (one source = one group's contribution) into
25
- * batches; the LLM is then called once per batch, threading the
26
- * written-back memory.md as input to the next batch. (§17.2)
24
+ * split source messages into bounded batches; the LLM is then called
25
+ * once per batch, threading the written-back memory.md as input to the
26
+ * next batch. A single Session source may therefore produce multiple
27
+ * ordered batches.
28
+ *
29
+ * Dream only needs durable user/assistant prose. Tool results are execution
30
+ * history and can be enormous; `compressDreamMessages()` drops them before
31
+ * triage/apply while preserving the original conversation on disk.
27
32
  *
28
33
  * No side-effects. All functions are deterministic given their inputs.
29
34
  */
30
35
 
31
36
  import {
32
37
  MAX_SINGLE_MESSAGE_CHARS,
38
+ MAX_DREAM_PROMPT_CHARS,
33
39
  MAX_DIFF_TOKENS_PER_TRIAGE,
34
40
  MAX_APPLY_TOKENS,
35
41
  DREAM_OVERLAP,
@@ -80,6 +86,67 @@ export function estimateMessagesTokens(msgs) {
80
86
  return n;
81
87
  }
82
88
 
89
+ /**
90
+ * Remove execution-only messages from the Dream input. The transcript remains
91
+ * the source of truth; this is only a prompt projection. Overlap messages are
92
+ * retained for triage context but never become new durable evidence.
93
+ *
94
+ * @param {Array<object>} messages
95
+ * @returns {Array<object>}
96
+ */
97
+ export function compressDreamMessages(messages) {
98
+ if (!Array.isArray(messages)) return [];
99
+ return messages
100
+ .filter(message => message && typeof message === 'object')
101
+ .filter(message => ['user', 'assistant'].includes(String(message.role || '').toLowerCase()))
102
+ .map(message => ({
103
+ ...message,
104
+ body: truncateMessage(message.body || message.content || ''),
105
+ }))
106
+ .filter(message => String(message.body || '').trim());
107
+ }
108
+
109
+ /**
110
+ * Keep only newly observed messages when applying/extracting. Triage may use
111
+ * overlap context, but re-feeding it to Apply causes old Dreamed content to be
112
+ * processed again on every pass.
113
+ *
114
+ * @param {Array<object>} messages
115
+ * @returns {Array<object>}
116
+ */
117
+ export function selectDreamNewMessages(messages) {
118
+ return (Array.isArray(messages) ? messages : [])
119
+ .filter(message => message && message.kind !== 'overlap');
120
+ }
121
+
122
+ /**
123
+ * Hard cap the final Dream prompt at the provider boundary. Keep both the
124
+ * prompt contract (head) and the JSON/output instruction (tail); discard only
125
+ * the middle source transcript. The durable transcript and canonical memory
126
+ * remain on disk.
127
+ *
128
+ * @param {string} prompt
129
+ * @param {number} [maxChars=MAX_DREAM_PROMPT_CHARS]
130
+ * @returns {string}
131
+ */
132
+ export function boundDreamPrompt(prompt, maxChars = MAX_DREAM_PROMPT_CHARS) {
133
+ const text = String(prompt || '');
134
+ const cap = Number.isFinite(maxChars) && maxChars > 0
135
+ ? Math.floor(maxChars)
136
+ : MAX_DREAM_PROMPT_CHARS;
137
+ if (text.length <= cap) return text;
138
+ const marker = '\n\n[Dream prompt compressed: middle transcript omitted; durable source remains on disk]\n\n';
139
+ if (cap <= marker.length) {
140
+ const head = Math.ceil(cap / 2);
141
+ const tail = cap - head;
142
+ return text.slice(0, head) + (tail > 0 ? text.slice(-tail) : '');
143
+ }
144
+ const room = cap - marker.length;
145
+ const head = Math.ceil(room * 0.62);
146
+ const tail = room - head;
147
+ return text.slice(0, head) + marker + (tail > 0 ? text.slice(-tail) : '');
148
+ }
149
+
83
150
  /**
84
151
  * Split a contiguous group diff into ≤MAX-token segments, with a
85
152
  * DREAM_OVERLAP-message tail/head overlap between consecutive segments.
@@ -99,14 +166,19 @@ export function estimateMessagesTokens(msgs) {
99
166
  * @param {Array<{id?: string, role?: string, body?: string}>} diff
100
167
  * @param {number} [maxTokens=MAX_DIFF_TOKENS_PER_TRIAGE]
101
168
  * @param {number} [overlap=DREAM_OVERLAP]
169
+ * @param {number} [maxPromptChars=MAX_DREAM_PROMPT_CHARS]
102
170
  * @returns {Array<{ messages: Array<object>, overlapCount: number, newCount: number }>}
103
171
  */
104
- export function segmentDiff(diff, maxTokens = MAX_DIFF_TOKENS_PER_TRIAGE, overlap = DREAM_OVERLAP) {
172
+ export function segmentDiff(diff, maxTokens = MAX_DIFF_TOKENS_PER_TRIAGE, overlap = DREAM_OVERLAP, maxPromptChars = MAX_DREAM_PROMPT_CHARS) {
105
173
  const msgs = Array.isArray(diff) ? diff : [];
174
+ const boundedPromptChars = Number.isFinite(maxPromptChars) && maxPromptChars > 0
175
+ ? maxPromptChars
176
+ : MAX_DREAM_PROMPT_CHARS;
177
+ const boundedMaxTokens = Math.min(maxTokens, Math.max(1, Math.floor(boundedPromptChars / 4) - 2048));
106
178
  if (msgs.length === 0) return [];
107
179
 
108
180
  // Fast path: whole diff fits in one segment.
109
- if (estimateMessagesTokens(msgs) <= maxTokens) {
181
+ if (estimateMessagesTokens(msgs) <= boundedMaxTokens) {
110
182
  return [{ messages: msgs, overlapCount: 0, newCount: msgs.length }];
111
183
  }
112
184
 
@@ -120,7 +192,7 @@ export function segmentDiff(diff, maxTokens = MAX_DIFF_TOKENS_PER_TRIAGE, overla
120
192
  let end = cursor;
121
193
  while (end < msgs.length) {
122
194
  const cost = estimateTokens(msgs[end].body || '') + estimateTokens(msgs[end].role || '') + 2;
123
- if (used + cost > maxTokens && end > cursor) break;
195
+ if (used + cost > boundedMaxTokens && end > cursor) break;
124
196
  used += cost;
125
197
  end += 1;
126
198
  }
@@ -161,9 +233,9 @@ function totalApplyTokens(merged) {
161
233
  * previous-batch output replaces memoryMd, so we account for the same
162
234
  * baseline cost in each batch.
163
235
  *
164
- * If a single source (one group's diff) alone would overflow, it still
165
- * goes into its own batch — we never split a source diff here (segment
166
- * happens earlier, in triage).
236
+ * Sources are split into ordered message chunks when one Session's diff is
237
+ * larger than the apply budget. This is required because a single Session
238
+ * can contribute thousands of messages after a long gap between Dream runs.
167
239
  *
168
240
  * @param {{ memoryMd?: string, summaryMd?: string, sources: Array<{ sessionId: string, diff: any }> }} merged
169
241
  * @param {number} [maxTokens=MAX_APPLY_TOKENS]
@@ -173,10 +245,11 @@ export function batchSourcesForApply(merged, maxTokens = MAX_APPLY_TOKENS) {
173
245
  const sources = Array.isArray(merged.sources) ? merged.sources : [];
174
246
  if (sources.length === 0) return [];
175
247
  const baseline = estimateTokens(merged.memoryMd || '') + estimateTokens(merged.summaryMd || '');
248
+ const sourceChunks = sources.flatMap(source => splitApplySource(source, Math.max(1, maxTokens - baseline)));
176
249
  const batches = [];
177
250
  let cur = [];
178
251
  let used = baseline;
179
- for (const src of sources) {
252
+ for (const src of sourceChunks) {
180
253
  const cost = estimateMessagesTokens(src.diff || []);
181
254
  if (cur.length > 0 && used + cost > maxTokens) {
182
255
  batches.push(cur);
@@ -189,3 +262,23 @@ export function batchSourcesForApply(merged, maxTokens = MAX_APPLY_TOKENS) {
189
262
  if (cur.length > 0) batches.push(cur);
190
263
  return batches;
191
264
  }
265
+
266
+ function splitApplySource(source, budget) {
267
+ const messages = Array.isArray(source?.diff) ? source.diff : [];
268
+ if (messages.length === 0) return [{ ...source, diff: [] }];
269
+ const chunks = [];
270
+ let current = [];
271
+ let used = 0;
272
+ for (const message of messages) {
273
+ const cost = estimateMessagesTokens([message]);
274
+ if (current.length > 0 && used + cost > budget) {
275
+ chunks.push({ ...source, diff: current });
276
+ current = [];
277
+ used = 0;
278
+ }
279
+ current.push(message);
280
+ used += cost;
281
+ }
282
+ if (current.length > 0) chunks.push({ ...source, diff: current });
283
+ return chunks;
284
+ }
@@ -46,7 +46,8 @@ import { parseMessage, parseSeqFromId } from '../conversation/persist.js';
46
46
  import { loadSessionConfig, resolveSessionConfig } from '../sessions/session-config.js';
47
47
  import { listSessions as listSessionMetas } from '../sessions/session-store.js';
48
48
  import { readSessionState } from './state.js';
49
- import { DREAM_NUDGE_AFTER_MESSAGES, DREAM_INTERVAL_HOURS } from './limits.js';
49
+ import { boundDreamPrompt } from './segment.js';
50
+ import { DREAM_NUDGE_AFTER_MESSAGES, DREAM_INTERVAL_HOURS, loadLimitsFromConfig } from './limits.js';
50
51
 
51
52
  /**
52
53
  * Build the per-call options for runDream. Pure: takes a session and returns
@@ -83,6 +84,7 @@ export function buildRunDreamOpts(session, onProgress) {
83
84
  root: memoryRoot,
84
85
  language: session.config?.language || 'en',
85
86
  segmentIndex: session.memoryIndex || null,
87
+ limits: loadLimitsFromConfig(session.config),
86
88
  llm: makeLlm(session),
87
89
  listSessions: async () => {
88
90
  try { return listRegisteredSessions([sessionConversationsRoot, legacySessionConversationsRoot]); }
@@ -355,7 +357,11 @@ function makeLlm(session) {
355
357
  return async ({ pass, prompt, system, sessionId }) => {
356
358
  const adapter = session.adapter;
357
359
  const effectiveConfig = resolveDreamSessionConfig(session, sessionId);
358
- const model = effectiveConfig?.model || effectiveConfig?.primaryModel;
360
+ // Session model overrides may be stored provider-qualified while the
361
+ // resolved config also exposes a provider-local `model` id. Dream must
362
+ // route through the exact Session selection first; otherwise a short id
363
+ // can resolve to another provider or fail as unsupported.
364
+ const model = effectiveConfig?.primaryModel || effectiveConfig?.model;
359
365
  if (!model) {
360
366
  throw new Error(`dream: no session model configured (pass=${pass}, sessionId=${sessionId || 'unknown'})`);
361
367
  }
@@ -371,11 +377,13 @@ function makeLlm(session) {
371
377
  const effectiveSystem = system || (String(effectiveConfig?.language || '').toLowerCase().startsWith('zh')
372
378
  ? `你是梦境流水线 — pass: ${pass}。请用中文生成自然语言内容;JSON key 保持英文。`
373
379
  : `You are the dream pipeline — pass: ${pass}.`);
380
+ const dreamLimits = loadLimitsFromConfig(effectiveConfig);
381
+ const boundedPrompt = boundDreamPrompt(prompt, dreamLimits.MAX_DREAM_PROMPT_CHARS);
374
382
 
375
383
  const r = await adapter.call({
376
384
  model,
377
385
  system: effectiveSystem,
378
- messages: [{ role: 'user', content: prompt }],
386
+ messages: [{ role: 'user', content: boundedPrompt }],
379
387
  maxTokens: 2048,
380
388
  modelEffort: effectiveConfig?.modelEffort || undefined,
381
389
  });
@@ -402,7 +410,8 @@ function makeLlm(session) {
402
410
  model: model || 'unknown',
403
411
  sessionId: sessionId || null,
404
412
  systemPrompt: effectiveSystem,
405
- messages: [{ role: 'user', content: prompt }],
413
+ messages: [{ role: 'user', content: boundedPrompt }],
414
+ promptChars: boundedPrompt.length,
406
415
  response: typeof r?.text === 'string' ? r.text : '',
407
416
  toolCalls: [],
408
417
  usage,
@@ -18,6 +18,7 @@ import {
18
18
  TOPIC_REDIRECT_FILE,
19
19
  } from '../memory/topic-redirect.js';
20
20
  import { render } from './prompts/index.js';
21
+ import { boundDreamPrompt } from './segment.js';
21
22
  import { parseJsonSafe } from './triage.js';
22
23
  import { snapshotScope } from './snapshot.js';
23
24
 
@@ -54,9 +55,9 @@ export async function consolidateSessionTopics(opts) {
54
55
  const parsed = parseJsonSafe(await opts.llm({
55
56
  pass: 'topic-consolidation',
56
57
  system: topicConsolidationSystem(opts.language),
57
- prompt: render('consolidateTopics', {
58
+ prompt: boundDreamPrompt(render('consolidateTopics', {
58
59
  topics: batch.map(topic => `- ${topic.path}: ${topic.summary}`).join('\n'),
59
- }, { language: opts.language }),
60
+ }, { language: opts.language }), opts.maxPromptChars),
60
61
  }));
61
62
  if (!Array.isArray(parsed?.groups)) continue;
62
63
  groups.push(...validateGroups(parsed.groups, topics));
@@ -128,13 +129,13 @@ async function applyConsolidationGroup(group, opts) {
128
129
  const raw = await opts.llm({
129
130
  pass: 'topic-merge',
130
131
  system: topicConsolidationSystem(opts.language),
131
- prompt: render('mergeTopics', {
132
+ prompt: boundDreamPrompt(render('mergeTopics', {
132
133
  canonical: canonical.path,
133
134
  topicContents: available.map(record => [
134
135
  `## ${record.path}`,
135
136
  record.content || record.memory || record.summary,
136
137
  ].join('\n')).join('\n\n'),
137
- }, { language: opts.language }),
138
+ }, { language: opts.language }), opts.maxPromptChars),
138
139
  });
139
140
  const parsed = parseJsonSafe(raw);
140
141
  const mergedContent = String(parsed?.content_md || '').trim();
@@ -36,7 +36,7 @@ import { isValidTopic } from '../memory/store.js';
36
36
  * below.)
37
37
  */
38
38
 
39
- import { truncateMessage } from './segment.js';
39
+ import { boundDreamPrompt, truncateMessage } from './segment.js';
40
40
  import { render } from './prompts/index.js';
41
41
  import { resolveTopicRedirect } from '../memory/topic-redirect.js';
42
42
 
@@ -106,7 +106,7 @@ export function applyHardRules({ sessionId, chatId, messages }) {
106
106
  /**
107
107
  * Build the prompt used for Pass-1.
108
108
  *
109
- * @param {{ sessionId: string, messages: Array<object>, topicSummaries: Array<{ path: string, summary: string }> }} ctx
109
+ * @param {{ sessionId: string, messages: Array<object>, topicSummaries: Array<{ path: string, summary: string }>, maxPromptChars?: number }} ctx
110
110
  */
111
111
  export function buildPass1Prompt(ctx) {
112
112
  const topicSummaries = (!ctx.topicSummaries || ctx.topicSummaries.length === 0)
@@ -119,11 +119,11 @@ export function buildPass1Prompt(ctx) {
119
119
  conv.push(truncateMessage(m.body || ''));
120
120
  conv.push('');
121
121
  }
122
- return render('triagePass1', {
122
+ return boundDreamPrompt(render('triagePass1', {
123
123
  sessionId: ctx.sessionId,
124
124
  topicSummaries,
125
125
  conversation: conv.join('\n').trimEnd(),
126
- }, { language: ctx.language });
126
+ }, { language: ctx.language }), ctx.maxPromptChars);
127
127
  }
128
128
 
129
129
  /**
@@ -135,10 +135,10 @@ export function buildPass2Prompt(ctx) {
135
135
  const existingTopics = (!ctx.existingTopics || ctx.existingTopics.length === 0)
136
136
  ? (String(ctx.language || '').toLowerCase().startsWith('zh') ? ' (无)' : ' (none)')
137
137
  : ctx.existingTopics.map(t => ` - ${t.path} — ${oneLine(t.summary)}`).join('\n');
138
- return render('triagePass2', {
138
+ return boundDreamPrompt(render('triagePass2', {
139
139
  description: ctx.description,
140
140
  existingTopics,
141
- }, { language: ctx.language });
141
+ }, { language: ctx.language }), ctx.maxPromptChars);
142
142
  }
143
143
 
144
144
  /**
@@ -150,12 +150,13 @@ export function buildPass2Prompt(ctx) {
150
150
  * messages: Array<object>,
151
151
  * topicSummaries: Array<{ path: string, summary: string }>,
152
152
  * llm: (req: { pass: string, prompt: string, system: string }) => Promise<string>,
153
+ * maxPromptChars?: number,
153
154
  * }} args
154
155
  * @returns {Promise<Array<{ kind: 'update'|'create', scope: string }>>}
155
156
  */
156
- export async function classifySoft({ root, sessionId, messages, topicSummaries, llm, language }) {
157
+ export async function classifySoft({ root, sessionId, messages, topicSummaries, llm, language, maxPromptChars }) {
157
158
  if (!llm) throw new Error('triage.classifySoft: llm callable required');
158
- const pass1Prompt = buildPass1Prompt({ sessionId, messages, topicSummaries, language });
159
+ const pass1Prompt = buildPass1Prompt({ sessionId, messages, topicSummaries, language, maxPromptChars });
159
160
  const pass1Raw = await llm({ pass: 'triage-pass1', prompt: pass1Prompt, system: triageSystem(language) });
160
161
  const pass1 = parseJsonSafe(pass1Raw);
161
162
  const out = [];
@@ -174,6 +175,7 @@ export async function classifySoft({ root, sessionId, messages, topicSummaries,
174
175
  description: description.trim(),
175
176
  existingTopics: topicSummaries || [],
176
177
  language,
178
+ maxPromptChars,
177
179
  });
178
180
  const pass2Raw = await llm({ pass: 'triage-pass2', prompt: pass2Prompt, system: triageSystem(language) });
179
181
  const pass2 = parseJsonSafe(pass2Raw);
@@ -224,11 +226,12 @@ export async function triageOneSegment(args) {
224
226
  * segments: Array<{ messages: Array<object> }>,
225
227
  * topicSummaries: Array<{ path: string, summary: string }>,
226
228
  * llm: (req: { pass: string, prompt: string, system: string }) => Promise<string>,
229
+ * maxPromptChars?: number,
227
230
  * onProgress?: (event: object) => void,
228
231
  * }} args
229
232
  * @returns {Promise<Array<{ kind: 'update'|'create', scope: string }>>}
230
233
  */
231
- export async function triageGroupSegments({ root, sessionId, segments, topicSummaries, llm, onProgress, language }) {
234
+ export async function triageGroupSegments({ root, sessionId, segments, topicSummaries, llm, onProgress, language, maxPromptChars }) {
232
235
  let acc = [];
233
236
  let i = 0;
234
237
  for (const seg of (segments || [])) {
@@ -241,6 +244,7 @@ export async function triageGroupSegments({ root, sessionId, segments, topicSumm
241
244
  topicSummaries,
242
245
  llm,
243
246
  language,
247
+ maxPromptChars,
244
248
  });
245
249
  acc = dedupeActions([...acc, ...segActions]);
246
250
  }
package/yeaft/engine.js CHANGED
@@ -691,7 +691,7 @@ export class Engine {
691
691
  /** @type {import('./stats/tool-usage.js').ToolUsageStats|null} — per-tool call/latency counters */
692
692
  #toolStats = null;
693
693
 
694
- /** @type {object|null} — Config override for internal tasks (recall, consolidation, dream) using fastModel */
694
+ /** @type {object|null} — Config override for internal compact/recall tasks using fastModel; Dream uses the Session primary model */
695
695
  #fastConfig;
696
696
 
697
697
  /** @type {((agentId: string, evt: object) => void) | null} */
@@ -5437,7 +5437,7 @@ export class Engine {
5437
5437
  /** @returns {string|null} */
5438
5438
  get yeaftDir() { return this.#yeaftDir; }
5439
5439
 
5440
- /** @returns {object} — Config with fastModel as model (for internal tasks) */
5440
+ /** @returns {object} — Config with fastModel as model (for compact and other non-Dream internal tasks) */
5441
5441
  get fastConfig() { return this.#fastConfig; }
5442
5442
 
5443
5443
  /**