@moxxy/sdk 0.14.2 → 0.14.3

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,851 +1,33 @@
1
- import type { ContentBlock, ProviderEvent, ProviderMessage, TokenUsage } from './provider.js';
2
- import type { ModeContext } from './mode.js';
3
- import type { StopReason } from './provider-utils.js';
4
- import type { Skill } from './skill.js';
5
- import type { CompactionEvent, MoxxyEvent } from './events.js';
6
- import {
7
- computeElisionState,
8
- conversationalStub,
9
- conversationalStubbed,
10
- toolResultBytes,
11
- toolResultStub,
12
- toolResultStubbed,
13
- } from './elision-state.js';
14
- import { isToolDisplayResult } from './tool-display.js';
15
- import { applyLazyTools } from './tool-gating.js';
16
- import { runCompactionIfNeeded } from './compactor-helpers.js';
17
- import { runElisionIfNeeded } from './elision-helpers.js';
18
- import { usageEventFields } from './token-accounting.js';
19
-
20
- /**
21
- * Shared bits used by every loop strategy: a typed tool-use struct and a
22
- * common stream-collection helper that runs `onBeforeProviderCall` hooks
23
- * and reduces a provider stream down to `{text, toolUses, stopReason}`.
24
- *
25
- * Lives in core (not in each loop package) so a new loop strategy stays
26
- * consistent — and so behavioral fixes here propagate. Previously
27
- * loop-plan-execute had its own copy that skipped the hook (audit bug).
28
- */
29
-
30
- export interface CollectedToolUse {
31
- readonly id: string;
32
- readonly name: string;
33
- readonly input: unknown;
34
- }
35
-
36
- /** Appended to the system prompt while elision is active (see projection). */
37
- export const ELISION_SYSTEM_NOTE =
38
- 'Context note: to stay within budget, older turns may appear as stubs like ' +
39
- '`[output elided — recall("id") to view]` or `[elided user turn · recall({ seq: N })]`. ' +
40
- 'These are NOT the real content — call the `recall` tool with the given id/seq to fetch ' +
41
- 'the full text before relying on any detail from an elided turn. Recent turns are always ' +
42
- 'shown verbatim.';
43
-
44
- /**
45
- * Compose a model-facing system prompt that includes any base prompt
46
- * plus a COMPACT skill index (name + description + triggers only).
47
- *
48
- * Lazy-loading design: the body is intentionally NOT inlined. The model
49
- * matches user intent against the description/triggers, then calls the
50
- * `load_skill` tool to fetch the body of the skill it picked. This keeps
51
- * the system prompt small even with many skills installed and avoids
52
- * paying for skill bodies the model never actually follows.
53
- */
54
- export function buildSystemPromptWithSkills(
55
- baseSystemPrompt: string | undefined,
56
- skills: ReadonlyArray<Skill>,
57
- ): string | undefined {
58
- if (skills.length === 0) return baseSystemPrompt;
59
- const header =
60
- `## Available skills\n\n` +
61
- `Each line below is a pre-authored playbook for a specific intent. ` +
62
- `When the user's request matches one of these (by name, description, ` +
63
- `or triggers), call \`load_skill({ name: "<skill-name>" })\` FIRST to ` +
64
- `fetch the full instructions, then follow them verbatim. Prefer using ` +
65
- `a skill over re-deriving the workflow with ad-hoc tools.\n`;
66
- const entries = skills
67
- .map((s) => {
68
- const fm = s.frontmatter;
69
- const triggerHint = fm.triggers?.length
70
- ? ` (triggers: ${fm.triggers.map((t) => `"${t}"`).join(', ')})`
71
- : '';
72
- return `- **${fm.name}** — ${fm.description}${triggerHint}`;
73
- })
74
- .join('\n');
75
- const skillBlock = `${header}\n${entries}`;
76
- return baseSystemPrompt ? `${baseSystemPrompt}\n\n${skillBlock}` : skillBlock;
77
- }
78
-
79
- export interface ProjectMessagesOptions {
80
- /** Optional system prompt; emitted as the first message when set. */
81
- readonly systemPrompt?: string;
82
- /** Optional trailing user message — useful for plan-execute's "Focus on this step now: X". */
83
- readonly trailingUserText?: string;
84
- }
85
-
86
- interface CompactionRange {
87
- readonly from: number;
88
- readonly to: number;
89
- readonly summary: string;
90
- }
91
-
92
- function activeCompactionRanges(events: ReadonlyArray<MoxxyEvent>): ReadonlyArray<CompactionRange> {
93
- return events
94
- .filter((event): event is CompactionEvent =>
95
- event.type === 'compaction' &&
96
- event.tokensSaved > 0 &&
97
- event.summary.trim().length > 0 &&
98
- event.replacedRange[0] <= event.replacedRange[1],
99
- )
100
- .map((event) => ({
101
- from: event.replacedRange[0],
102
- to: event.replacedRange[1],
103
- summary: event.summary,
104
- }));
105
- }
106
-
107
- function eventInCompactionRange(
108
- seq: number,
109
- ranges: ReadonlyArray<CompactionRange>,
110
- ): CompactionRange | null {
111
- for (const range of ranges) {
112
- if (seq >= range.from && seq <= range.to) return range;
113
- }
114
- return null;
115
- }
116
-
117
- /**
118
- * A compaction lookup that answers "which range (if any) contains `seq`" in
119
- * O(log ranges) instead of {@link eventInCompactionRange}'s O(ranges) linear
120
- * scan per event. Compaction ranges are non-overlapping ascending seq prefixes,
121
- * so a seq belongs to at most one range and binary search over the
122
- * sorted-by-`from` array returns the SAME range the linear first-match did —
123
- * byte-identical projection.
124
- *
125
- * Defensive fallback: if the ranges are NOT strictly non-overlapping (which the
126
- * compaction invariant forbids, but a hand-crafted/corrupt log could violate),
127
- * we keep the exact linear first-match semantics so the projection can never
128
- * diverge from the old code.
129
- */
130
- function makeCompactionLookup(
131
- ranges: ReadonlyArray<CompactionRange>,
132
- ): (seq: number) => CompactionRange | null {
133
- if (ranges.length === 0) return () => null;
134
- if (ranges.length === 1) {
135
- const only = ranges[0]!;
136
- return (seq) => (seq >= only.from && seq <= only.to ? only : null);
137
- }
138
- // Sort a copy by `from` (stable enough — ranges are non-overlapping). Verify
139
- // the non-overlap invariant on the sorted copy; only then is binary search
140
- // provably equivalent to the linear first-match.
141
- const sorted = [...ranges].sort((a, b) => a.from - b.from);
142
- let nonOverlapping = true;
143
- for (let i = 1; i < sorted.length; i++) {
144
- if (sorted[i]!.from <= sorted[i - 1]!.to) {
145
- nonOverlapping = false;
146
- break;
147
- }
148
- }
149
- if (!nonOverlapping) return (seq) => eventInCompactionRange(seq, ranges);
150
- return (seq) => {
151
- // Largest `from <= seq`, then a single containment check.
152
- let lo = 0;
153
- let hi = sorted.length - 1;
154
- let cand = -1;
155
- while (lo <= hi) {
156
- const mid = (lo + hi) >> 1;
157
- if (sorted[mid]!.from <= seq) {
158
- cand = mid;
159
- lo = mid + 1;
160
- } else {
161
- hi = mid - 1;
162
- }
163
- }
164
- if (cand < 0) return null;
165
- const range = sorted[cand]!;
166
- return seq <= range.to ? range : null;
167
- };
168
- }
169
-
170
- /**
171
- * Project the session's event log to a flat list of ProviderMessages
172
- * suitable for handing to `provider.stream`. Used by every loop strategy.
173
- *
174
- * Handles user_prompt, assistant_message, tool_call_requested (grouped
175
- * into a single assistant message of tool_use blocks), and tool_result.
176
- * Other event types are passed through as a no-op.
177
- *
178
- * This is THE projection every loop strategy uses; it honors compaction
179
- * events, turn-boundary elision, and the orphan-tool_use fallback. It lives in
180
- * the SDK so loop plugins stay independent of core.
181
- */
182
- export interface ProjectedMessages {
183
- readonly messages: ProviderMessage[];
184
- /**
185
- * Index (into `messages`) of the last message belonging to the stable,
186
- * byte-identical prefix — i.e. produced entirely from events at or below the
187
- * elision high-water mark (which only advances on whole-turn boundaries, so
188
- * the cut never splits a message). -1 when no elision is active. The
189
- * `stable-prefix` cache strategy places its long-lived cross-turn breakpoint
190
- * here; see {@link collectProviderStream}'s `stablePrefixIndex` option.
191
- */
192
- readonly stablePrefixIndex: number;
193
- }
194
-
195
- export function projectMessagesFromLog(
196
- ctx: Pick<ModeContext, 'log'>,
197
- opts: ProjectMessagesOptions = {},
198
- ): ProviderMessage[] {
199
- return projectMessages(ctx, opts).messages;
200
- }
201
-
202
1
  /**
203
- * Same projection as {@link projectMessagesFromLog} but also reports the
204
- * stable-prefix boundary so the active cache strategy can place a cross-turn
205
- * breakpoint. Modes that build messages this way should thread the returned
206
- * `stablePrefixIndex` into {@link collectProviderStream}.
207
- */
208
- export function projectMessages(
209
- ctx: Pick<ModeContext, 'log'>,
210
- opts: ProjectMessagesOptions = {},
211
- ): ProjectedMessages {
212
- const allEvents = ctx.log.slice();
213
- const compactions = activeCompactionRanges(allEvents);
214
- const compactionFor = makeCompactionLookup(compactions);
215
- const emittedCompactions = new Set<CompactionRange>();
216
- const el = computeElisionState(allEvents);
217
-
218
- const messages: ProviderMessage[] = [];
219
- // The stable prefix is every message produced from events at/below the
220
- // elision HWM. Record the latest such message index as we push.
221
- let stablePrefixIndex = -1;
222
- const recordStable = (maxSeq: number): void => {
223
- if (el.hwm >= 0 && maxSeq >= 0 && maxSeq <= el.hwm) {
224
- stablePrefixIndex = messages.length - 1;
225
- }
226
- };
227
- if (opts.systemPrompt) {
228
- // When elision is active, tell the model that older turns may be shown as
229
- // stubs and how to expand them — so it recalls instead of hallucinating.
230
- // Constant text → busts the system cache once (when elision starts), stable
231
- // thereafter.
232
- const sysText = el.hwm >= 0 ? `${opts.systemPrompt}\n\n${ELISION_SYSTEM_NOTE}` : opts.systemPrompt;
233
- messages.push({ role: 'system', content: [{ type: 'text', text: sysText }] });
234
- }
235
- // Pre-scan: build the set of callIds that have a matching tool_result
236
- // (or tool_call_denied) somewhere in the log. Used to synthesize a
237
- // fallback `[interrupted]` tool_result for orphan tool_use blocks
238
- // when the assistant message gets flushed.
239
- //
240
- // Without this fallback the provider rejects the whole conversation
241
- // with "assistant message with 'tool_calls' must be followed by tool
242
- // messages responding to each 'tool_call_id'". Orphans typically
243
- // appear after a cancelled turn, an aborted process, or a tool
244
- // exception that bypassed the loop's tool_result emit path.
245
- const resolvedCallIds = new Set<string>();
246
- for (const e of allEvents) {
247
- if (e.type === 'tool_result' || e.type === 'tool_call_denied') {
248
- resolvedCallIds.add(e.callId);
249
- }
250
- }
251
-
252
- let pendingAssistant: ProviderMessage | null = null;
253
- let pendingAssistantMaxSeq = -1;
254
- // Reasoning block awaiting attachment to the current assistant turn. Only set
255
- // for REPLAYABLE reasoning (Anthropic signature / redacted-or-Codex encrypted
256
- // blob) — render-only reasoning is never sent back. Attached as content[0] of
257
- // the turn's assistant message (Anthropic requires the signed thinking block
258
- // first on an interleaved-thinking tool-use continuation; a missing/unsigned
259
- // one is a hard 400). Dropped at any turn/compaction boundary it doesn't reach.
260
- let pendingReasoning: Extract<ContentBlock, { type: 'reasoning' }> | null = null;
261
- let pendingReasoningSeq = -1;
262
- const flush = (): void => {
263
- if (!pendingAssistant) return;
264
- const flushed = pendingAssistant;
265
- const groupMaxSeq = pendingAssistantMaxSeq;
266
- pendingAssistant = null;
267
- pendingAssistantMaxSeq = -1;
268
- messages.push(flushed);
269
- recordStable(groupMaxSeq);
270
- // Synthesize fallback tool_result messages for any tool_use blocks
271
- // whose callId never resolved in the event log. Has to land
272
- // immediately after the assistant message (and before any
273
- // subsequent user_prompt / assistant_message) so the provider sees
274
- // a clean assistant→tool-result chain.
275
- for (const block of flushed.content) {
276
- if (block.type === 'tool_use' && !resolvedCallIds.has(block.id)) {
277
- messages.push({
278
- role: 'tool_result',
279
- content: [
280
- {
281
- type: 'tool_result',
282
- toolUseId: block.id,
283
- content: '[tool call did not return a result — possibly interrupted or cancelled]',
284
- isError: true,
285
- },
286
- ],
287
- });
288
- recordStable(groupMaxSeq);
289
- // Mark synthesized so we don't double-emit if the same orphan
290
- // appears in multiple groups (defensive — shouldn't normally
291
- // happen since each tool_call_requested has a unique callId).
292
- resolvedCallIds.add(block.id);
293
- }
294
- }
295
- };
296
-
297
- for (const e of allEvents) {
298
- const compaction = compactionFor(e.seq);
299
- if (compaction) {
300
- if (!emittedCompactions.has(compaction)) {
301
- emittedCompactions.add(compaction);
302
- flush();
303
- pendingReasoning = null;
304
- messages.push({
305
- role: 'user',
306
- content: [{ type: 'text', text: `[summary of earlier turns]\n${compaction.summary}` }],
307
- });
308
- recordStable(compaction.to);
309
- }
310
- continue;
311
- }
312
-
313
- switch (e.type) {
314
- case 'user_prompt': {
315
- flush();
316
- pendingReasoning = null;
317
- // Elided + conversational: collapse to a stub (anchor/tiny kept full).
318
- if (conversationalStubbed(e, el)) {
319
- messages.push({
320
- role: 'user',
321
- content: [{ type: 'text', text: conversationalStub('user', e.seq) }],
322
- });
323
- recordStable(e.seq);
324
- break;
325
- }
326
- const blocks: ContentBlock[] = [{ type: 'text', text: e.text }];
327
- if (e.attachments) {
328
- for (const att of e.attachments) {
329
- if (att.kind === 'image') {
330
- blocks.push({
331
- type: 'image',
332
- mediaType: att.mediaType ?? 'image/png',
333
- data: att.content,
334
- });
335
- } else if (att.kind === 'document') {
336
- blocks.push({
337
- type: 'document',
338
- mediaType: att.mediaType ?? 'application/pdf',
339
- data: att.content,
340
- ...(att.name ? { name: att.name } : {}),
341
- });
342
- } else {
343
- blocks.push({
344
- type: 'text',
345
- text: `[${att.kind}${att.name ? ` ${att.name}` : ''}]\n${att.content}`,
346
- });
347
- }
348
- }
349
- }
350
- messages.push({ role: 'user', content: blocks });
351
- recordStable(e.seq);
352
- break;
353
- }
354
- case 'reasoning_message': {
355
- // Render-only reasoning (no signature/encrypted) is never replayed —
356
- // it exists only for the live/scrollback "Thinking" view. Replayable
357
- // reasoning is stashed for content[0] of this turn's assistant message.
358
- if (e.signature || e.encrypted) {
359
- pendingReasoning = {
360
- type: 'reasoning',
361
- text: e.content,
362
- ...(e.signature ? { signature: e.signature } : {}),
363
- ...(e.redacted ? { redacted: true } : {}),
364
- ...(e.encrypted ? { encrypted: e.encrypted } : {}),
365
- };
366
- pendingReasoningSeq = e.seq;
367
- }
368
- break;
369
- }
370
- case 'assistant_message':
371
- flush();
372
- if (conversationalStubbed(e, el)) {
373
- pendingReasoning = null;
374
- messages.push({
375
- role: 'assistant',
376
- content: [{ type: 'text', text: conversationalStub('assistant', e.seq) }],
377
- });
378
- recordStable(e.seq);
379
- break;
380
- }
381
- // A tool-only turn can log an assistant_message with empty content
382
- // (end_turn + tool calls, no prose). Projecting it as an empty text
383
- // block makes some providers (Anthropic) reject the NEXT request and
384
- // permanently wedges the session. Skip the block — the turn's
385
- // tool_use blocks are projected from tool_call_requested events —
386
- // which also un-wedges historical logs that already contain one.
387
- if (e.content.trim().length === 0) {
388
- pendingReasoning = null;
389
- recordStable(e.seq);
390
- break;
391
- }
392
- {
393
- const content: Array<ProviderMessage['content'][number]> = [];
394
- if (pendingReasoning) {
395
- content.push(pendingReasoning);
396
- pendingReasoning = null;
397
- }
398
- content.push({ type: 'text', text: e.content });
399
- messages.push({ role: 'assistant', content });
400
- }
401
- recordStable(e.seq);
402
- break;
403
- case 'tool_call_requested': {
404
- if (!pendingAssistant) {
405
- // Seed the assistant turn so the signed reasoning block is content[0],
406
- // ahead of every tool_use (Anthropic's interleaved-thinking ordering).
407
- pendingAssistant = { role: 'assistant', content: pendingReasoning ? [pendingReasoning] : [] };
408
- if (pendingReasoning) {
409
- pendingAssistantMaxSeq = Math.max(pendingAssistantMaxSeq, pendingReasoningSeq);
410
- pendingReasoning = null;
411
- }
412
- }
413
- pendingAssistantMaxSeq = Math.max(pendingAssistantMaxSeq, e.seq);
414
- (pendingAssistant.content as Array<ProviderMessage['content'][number]>).push({
415
- type: 'tool_use',
416
- id: e.callId,
417
- name: e.name,
418
- input: e.input,
419
- });
420
- break;
421
- }
422
- case 'tool_result': {
423
- flush();
424
- // Stub bulky old tool output to a recall-able marker (decision shared
425
- // with estimateContextTokens via toolResultStubbed).
426
- let text: string;
427
- if (toolResultStubbed(e, el)) {
428
- const recalled = el.recalledCallIds.has(e.callId) || el.recalledSeqs.has(e.seq);
429
- text = toolResultStub(e.callId, toolResultBytes(e.output), recalled);
430
- } else if (e.error) {
431
- text = `[error:${e.error.kind}] ${e.error.message}`;
432
- } else if (isToolDisplayResult(e.output)) {
433
- // Rich result (e.g. a file diff): the model only needs the short
434
- // `forModel` summary — the structured `display` is for channels.
435
- text = e.output.forModel;
436
- } else {
437
- text = typeof e.output === 'string' ? e.output : JSON.stringify(e.output ?? '');
438
- }
439
- messages.push({
440
- role: 'tool_result',
441
- content: [{ type: 'tool_result', toolUseId: e.callId, content: text, isError: !e.ok }],
442
- });
443
- recordStable(e.seq);
444
- break;
445
- }
446
- default:
447
- break;
448
- }
449
- }
450
- flush();
451
-
452
- if (opts.trailingUserText) {
453
- // The trailing step nudge is volatile (changes per step), never part of
454
- // the stable prefix — don't record it.
455
- messages.push({ role: 'user', content: [{ type: 'text', text: opts.trailingUserText }] });
456
- }
457
- return { messages, stablePrefixIndex };
458
- }
459
-
460
- export interface StreamResult {
461
- readonly text: string;
462
- readonly toolUses: ReadonlyArray<CollectedToolUse>;
463
- readonly stopReason: StopReason;
464
- readonly error: { readonly message: string; readonly retryable: boolean } | null;
465
- /** Token usage reported by the provider on `message_end`, including cache hits/writes. */
466
- readonly usage?: TokenUsage;
467
- /**
468
- * Reasoning/thinking summary for this provider call, when the model emitted
469
- * any. The mode emits it as a `reasoning_message` event (so it persists and
470
- * round-trips). `signature`/`encrypted` carry Anthropic's signed thinking
471
- * block / redacted blob; `redacted` marks display-suppressed reasoning.
472
- */
473
- readonly reasoning?: {
474
- readonly text: string;
475
- readonly signature?: string;
476
- readonly redacted?: boolean;
477
- readonly encrypted?: string;
478
- };
479
- }
480
-
481
- /**
482
- * Pulls a provider stream, emits `assistant_chunk` events for text deltas,
483
- * collects tool_use blocks, and returns the final `{text, toolUses, stopReason}`.
484
- * Runs `onBeforeProviderCall` lifecycle hooks before the call.
485
- */
486
- export async function collectProviderStream(
487
- ctx: ModeContext,
488
- messages: ReadonlyArray<ProviderMessage>,
489
- opts: {
490
- iteration?: number;
491
- includeTools?: boolean;
492
- maxTokens?: number;
493
- /**
494
- * Index (into `messages`) of the last stable-prefix message, from
495
- * {@link projectMessages}. Passed to the active cache strategy as
496
- * `stablePrefixMessageIndex` so it can place a long-lived cross-turn
497
- * breakpoint at the elision boundary. Omit (or -1) when unknown — the
498
- * strategy then falls back to its tools/system/tail breakpoints only.
499
- */
500
- stablePrefixIndex?: number;
501
- /**
502
- * Number of trailing messages in `messages` that are volatile — injected
503
- * for this call only (e.g. goal mode's `trailingUserText` nudge) and
504
- * absent from the append-only log, so they won't recur at the same
505
- * position next call. Forwarded to the cache strategy as
506
- * `volatileTailMessageCount` so it keeps its rolling tail breakpoint
507
- * before them instead of paying a guaranteed-wasted cache write.
508
- */
509
- volatileTailCount?: number;
510
- } = {},
511
- ): Promise<StreamResult> {
512
- // Lazy tool gating (opt-in): send only always-on + loaded tool schemas, and
513
- // index the rest in the system prompt. Runs BEFORE cache planning since it
514
- // rewrites the system message and the tool list.
515
- let effectiveMessages = messages;
516
- let toolList: ReadonlyArray<import('./tool.js').ToolDef> | undefined =
517
- opts.includeTools === false ? undefined : ctx.tools.list();
518
- if (ctx.lazyTools && toolList) {
519
- const gated = applyLazyTools(messages, toolList, ctx.log);
520
- effectiveMessages = gated.messages;
521
- toolList = gated.tools;
522
- }
523
-
524
- // Ask the active cache strategy where to place prompt-cache breakpoints.
525
- // The strategy is provider-neutral (returns CacheHints); the provider
526
- // translates them (Anthropic → cache_control). Falls back to no hints when
527
- // no strategy is registered. The onBeforeProviderCall hook can still adjust.
528
- const descriptor = ctx.provider.models.find((m) => m.id === ctx.model);
529
- const cacheHints = ctx.cacheStrategy
530
- ? ctx.cacheStrategy.plan(effectiveMessages, {
531
- model: ctx.model,
532
- contextWindow: descriptor?.contextWindow ?? 0,
533
- log: ctx.log,
534
- ...(opts.stablePrefixIndex != null && opts.stablePrefixIndex >= 0
535
- ? { stablePrefixMessageIndex: opts.stablePrefixIndex }
536
- : {}),
537
- ...(opts.volatileTailCount != null && opts.volatileTailCount > 0
538
- ? { volatileTailMessageCount: opts.volatileTailCount }
539
- : {}),
540
- })
541
- : undefined;
542
-
543
- // NOTE: `system` is deliberately NOT prefilled with ctx.systemPrompt — the
544
- // composed system prompt already rides as the leading system-role message
545
- // (see projectMessages), and providers deliver `req.system` IN ADDITION to
546
- // message-derived system text. Prefilling it would duplicate the prompt.
547
- // It stays as the side channel `onBeforeProviderCall` hooks use to inject
548
- // per-request system text (e.g. the memory consolidation nudge).
549
- // Forward the per-provider reasoning preference, but only when THIS model
550
- // advertises `supportsReasoning` — providers ignore the knob otherwise, but
551
- // gating here keeps requests clean and avoids unsupported-param errors.
552
- const reqReasoning = descriptor?.supportsReasoning ? ctx.reasoning : undefined;
553
- const req = {
554
- model: ctx.model,
555
- messages: effectiveMessages,
556
- ...(toolList ? { tools: toolList } : {}),
557
- ...(cacheHints && cacheHints.length > 0 ? { cacheHints } : {}),
558
- ...(opts.maxTokens !== undefined ? { maxTokens: opts.maxTokens } : {}),
559
- ...(reqReasoning ? { reasoning: reqReasoning } : {}),
560
- signal: ctx.signal,
561
- };
562
- const transformed = await ctx.hooks.dispatchBeforeProviderCall(req, {
563
- sessionId: ctx.sessionId,
564
- cwd: '',
565
- log: ctx.log,
566
- env: {},
567
- turnId: ctx.turnId,
568
- iteration: opts.iteration ?? 0,
569
- });
570
-
571
- let text = '';
572
- const toolUses = new Map<string, { name?: string; input?: unknown }>();
573
- let stopReason: StopReason = 'end_turn';
574
- let error: StreamResult['error'] = null;
575
- let usage: TokenUsage | undefined;
576
- // Reasoning/thinking accumulation for this single provider call. Emitted as a
577
- // finalized `reasoning_message` by the mode (turn-iterator / goal-loop) so it
578
- // persists and round-trips; `signature`/`encrypted` carry Anthropic's signed
579
- // thinking block / redacted blob for replay.
580
- let reasoningText = '';
581
- let reasoningSignature: string | undefined;
582
- let reasoningRedacted = false;
583
- let reasoningEncrypted: string | undefined;
584
-
585
- let stream: AsyncIterable<ProviderEvent>;
586
- try {
587
- stream = ctx.provider.stream(transformed);
588
- } catch (err) {
589
- return {
590
- text: '',
591
- toolUses: [],
592
- stopReason: 'error',
593
- error: { message: err instanceof Error ? err.message : String(err), retryable: false },
594
- };
595
- }
596
-
597
- try {
598
- for await (const event of stream) {
599
- switch (event.type) {
600
- case 'text_delta': {
601
- text += event.delta;
602
- await ctx.emit({
603
- type: 'assistant_chunk',
604
- sessionId: ctx.sessionId,
605
- turnId: ctx.turnId,
606
- source: 'model',
607
- delta: event.delta,
608
- });
609
- break;
610
- }
611
- case 'tool_use_start': {
612
- toolUses.set(event.id, { name: event.name });
613
- break;
614
- }
615
- case 'tool_use_end': {
616
- const existing = toolUses.get(event.id) ?? {};
617
- toolUses.set(event.id, { ...existing, input: event.input });
618
- break;
619
- }
620
- case 'message_end': {
621
- stopReason = event.stopReason;
622
- if (event.usage) usage = event.usage;
623
- break;
624
- }
625
- case 'error': {
626
- error = { message: event.message, retryable: event.retryable };
627
- break;
628
- }
629
- case 'reasoning_delta': {
630
- reasoningText += event.delta;
631
- // Live preview only — parallels `assistant_chunk`; renderers
632
- // accumulate ephemerally and clear on the finalized reasoning_message.
633
- await ctx.emit({
634
- type: 'reasoning_chunk',
635
- sessionId: ctx.sessionId,
636
- turnId: ctx.turnId,
637
- source: 'model',
638
- delta: event.delta,
639
- });
640
- break;
641
- }
642
- case 'reasoning_signature': {
643
- if (event.signature) reasoningSignature = event.signature;
644
- if (event.encrypted) reasoningEncrypted = event.encrypted;
645
- if (event.redacted) reasoningRedacted = true;
646
- break;
647
- }
648
- case 'message_start':
649
- case 'tool_use_delta':
650
- default:
651
- break;
652
- }
653
- }
654
- } catch (err) {
655
- error = {
656
- message: err instanceof Error ? err.message : String(err),
657
- retryable: false,
658
- };
659
- }
660
-
661
- const finalToolUses: CollectedToolUse[] = [];
662
- for (const [id, partial] of toolUses) {
663
- if (!partial.name) continue;
664
- finalToolUses.push({ id, name: partial.name, input: partial.input ?? {} });
665
- }
666
- // Surface reasoning when there's visible text OR an opaque blob to replay
667
- // (a redacted_thinking block has no text but must still round-trip).
668
- const reasoning =
669
- reasoningText.trim().length > 0 || reasoningEncrypted
670
- ? {
671
- text: reasoningText,
672
- ...(reasoningSignature ? { signature: reasoningSignature } : {}),
673
- ...(reasoningRedacted ? { redacted: true } : {}),
674
- ...(reasoningEncrypted ? { encrypted: reasoningEncrypted } : {}),
675
- }
676
- : undefined;
677
- return {
678
- text,
679
- toolUses: finalToolUses,
680
- stopReason,
681
- error,
682
- ...(usage ? { usage } : {}),
683
- ...(reasoning ? { reasoning } : {}),
684
- };
685
- }
686
-
687
- /**
688
- * Run a single-shot (no-tools) provider turn — the shape every planner /
689
- * synthesis phase shares. Runs context management (compaction + elision),
690
- * emits the `provider_request` bookend, streams the response with tools
691
- * disabled, then emits either an `error` event (returning `null`) or the
692
- * `provider_response` bookend (returning the collected text).
693
- *
694
- * Replaces the ~40-line block each mode phase used to inline; centralizing it
695
- * keeps event emission uniform and means a fix here (e.g. always running
696
- * elision) lands for every loop strategy at once.
697
- */
698
- export async function runSingleShotTurn(
699
- ctx: ModeContext,
700
- messages: ReadonlyArray<ProviderMessage>,
701
- opts: { maxTokens?: number } = {},
702
- ): Promise<string | null> {
703
- await runCompactionIfNeeded(ctx);
704
- await runElisionIfNeeded(ctx);
705
-
706
- await ctx.emit({
707
- type: 'provider_request',
708
- sessionId: ctx.sessionId,
709
- turnId: ctx.turnId,
710
- source: 'system',
711
- provider: ctx.provider.name,
712
- model: ctx.model,
713
- });
714
-
715
- const { text, usage, error } = await collectProviderStream(ctx, messages, {
716
- includeTools: false,
717
- ...(opts.maxTokens !== undefined ? { maxTokens: opts.maxTokens } : {}),
718
- });
719
- if (error) {
720
- await ctx.emit({
721
- type: 'error',
722
- sessionId: ctx.sessionId,
723
- turnId: ctx.turnId,
724
- source: 'system',
725
- kind: error.retryable ? 'retryable' : 'fatal',
726
- message: error.message,
727
- });
728
- return null;
729
- }
730
-
731
- await ctx.emit({
732
- type: 'provider_response',
733
- sessionId: ctx.sessionId,
734
- turnId: ctx.turnId,
735
- source: 'system',
736
- provider: ctx.provider.name,
737
- model: ctx.model,
738
- ...usageEventFields(usage),
739
- });
740
-
741
- return text;
742
- }
743
-
744
- /**
745
- * Sliding-window detector for "model keeps making the same tool call".
746
- *
747
- * When the same `(toolName, input)` pair appears `repeatThreshold` times in
748
- * the last `windowSize` calls, the model is almost certainly stuck — polling a
749
- * tool that returns the same thing, mis-handling an error, etc. Bail early
750
- * instead of burning through the iteration cap.
751
- *
752
- * Shared across every loop strategy so detection is uniform — previously each
753
- * mode re-rolled this, and one copy used a non-canonical `JSON.stringify`
754
- * signature that silently missed key-reordered repeats.
755
- */
756
- export interface StuckSignal {
757
- /** True when the loop guard should trip. */
758
- readonly stuck: boolean;
759
- /** Repeat count behind the trip — for the error message. */
760
- readonly count: number;
761
- /**
762
- * `exact` = the same (tool, full-input) repeated `repeatThreshold` times.
763
- * `near` = the same (tool, identity arg — url / file_path / command / …)
764
- * repeated `nearThreshold` times while only volatile args (maxBytes,
765
- * timeoutMs) varied. Catches the "refetch the same URL with a bigger
766
- * maxBytes over and over" loop the exact check sails past.
767
- */
768
- readonly kind: 'exact' | 'near';
769
- }
770
-
771
- export interface StuckLoopDetector {
772
- readonly windowSize: number;
773
- readonly repeatThreshold: number;
774
- /** Record the call and report whether the loop guard should trip. */
775
- record(toolName: string, input: unknown): StuckSignal;
776
- }
777
-
778
- /** Identity arguments that pin "the same target" across volatile-arg variation,
779
- * best-first. The first present string field wins. */
780
- const IDENTITY_ARG_KEYS = ['url', 'file_path', 'path', 'command', 'cmd', 'query', 'pattern'];
781
-
782
- function identityArg(input: unknown): string | null {
783
- if (!input || typeof input !== 'object' || Array.isArray(input)) return null;
784
- const o = input as Record<string, unknown>;
785
- for (const k of IDENTITY_ARG_KEYS) {
786
- const v = o[k];
787
- if (typeof v === 'string' && v.trim().length > 0) return `${k}=${v}`;
788
- }
789
- return null;
790
- }
791
-
792
- export function createStuckLoopDetector(
793
- opts: {
794
- windowSize?: number;
795
- repeatThreshold?: number;
796
- nearWindowSize?: number;
797
- nearThreshold?: number;
798
- } = {},
799
- ): StuckLoopDetector {
800
- const windowSize = opts.windowSize ?? 8;
801
- const repeatThreshold = opts.repeatThreshold ?? 3;
802
- // Near-dups need a higher count + a wider window (they're spread out across a
803
- // burst of other calls), and tolerate a couple of legit "bigger refetch" tries.
804
- const nearWindowSize = opts.nearWindowSize ?? Math.max(windowSize * 2, 16);
805
- const nearThreshold = opts.nearThreshold ?? Math.max(repeatThreshold + 2, 5);
806
- const recent: string[] = [];
807
- const recentNear: string[] = [];
808
- return {
809
- windowSize,
810
- repeatThreshold,
811
- record(toolName, input): StuckSignal {
812
- const key = `${toolName}|${stableHash(input)}`;
813
- recent.push(key);
814
- if (recent.length > windowSize) recent.shift();
815
- const exactCount = recent.filter((k) => k === key).length;
816
- if (exactCount >= repeatThreshold) return { stuck: true, count: exactCount, kind: 'exact' };
817
-
818
- let nearCount = 0;
819
- const id = identityArg(input);
820
- if (id !== null) {
821
- const nearKey = `${toolName}|${id}`;
822
- recentNear.push(nearKey);
823
- if (recentNear.length > nearWindowSize) recentNear.shift();
824
- nearCount = recentNear.filter((k) => k === nearKey).length;
825
- if (nearCount >= nearThreshold) return { stuck: true, count: nearCount, kind: 'near' };
826
- }
827
- return { stuck: false, count: Math.max(exactCount, nearCount), kind: 'exact' };
828
- },
829
- };
830
- }
831
-
832
- /**
833
- * Stable, key-order-canonical hash of a tool call's input, so `{a:1,b:2}` and
834
- * `{b:2,a:1}` produce the same key. Use for any "have I seen this call before"
835
- * comparison — a raw `JSON.stringify` is NOT order-stable.
836
- */
837
- export function stableHash(input: unknown): string {
838
- return canonicalize(input);
839
- }
840
-
841
- function canonicalize(value: unknown): string {
842
- if (value === null || value === undefined) return 'null';
843
- if (typeof value !== 'object') return JSON.stringify(value);
844
- if (Array.isArray(value)) {
845
- return '[' + value.map(canonicalize).join(',') + ']';
846
- }
847
- const entries = Object.entries(value as Record<string, unknown>).sort(
848
- ([a], [b]) => (a < b ? -1 : a > b ? 1 : 0),
849
- );
850
- return '{' + entries.map(([k, v]) => JSON.stringify(k) + ':' + canonicalize(v)).join(',') + '}';
851
- }
2
+ * Barrel for the shared mode/loop helpers. The implementations now live in
3
+ * focused single-responsibility modules under `./mode/`; this file re-exports
4
+ * them so every existing `from './mode-helpers.js'` import (and the
5
+ * `@moxxy/sdk` index barrel) keeps working byte-identically.
6
+ *
7
+ * - `./mode/project-messages.ts` — event-log → ProviderMessage projection
8
+ * - `./mode/collect-stream.ts` — provider-stream collection
9
+ * - `./mode/single-shot.ts` — single-shot (no-tools) provider turn
10
+ * - `./mode/stuck-loop.ts` — sliding-window stuck-tool-call detector
11
+ * - `./mode/stable-hash.ts` — key-order-canonical input hash util
12
+ */
13
+
14
+ export {
15
+ ELISION_SYSTEM_NOTE,
16
+ buildSystemPromptWithSkills,
17
+ projectMessagesFromLog,
18
+ projectMessages,
19
+ type ProjectMessagesOptions,
20
+ type ProjectedMessages,
21
+ } from './mode/project-messages.js';
22
+ export {
23
+ collectProviderStream,
24
+ type CollectedToolUse,
25
+ type StreamResult,
26
+ } from './mode/collect-stream.js';
27
+ export { runSingleShotTurn } from './mode/single-shot.js';
28
+ export {
29
+ createStuckLoopDetector,
30
+ type StuckLoopDetector,
31
+ type StuckSignal,
32
+ } from './mode/stuck-loop.js';
33
+ export { stableHash } from './mode/stable-hash.js';