@moxxy/sdk 0.1.0

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 (211) hide show
  1. package/dist/agent.d.ts +39 -0
  2. package/dist/agent.d.ts.map +1 -0
  3. package/dist/agent.js +2 -0
  4. package/dist/agent.js.map +1 -0
  5. package/dist/cache-strategy.d.ts +35 -0
  6. package/dist/cache-strategy.d.ts.map +1 -0
  7. package/dist/cache-strategy.js +2 -0
  8. package/dist/cache-strategy.js.map +1 -0
  9. package/dist/channel.d.ts +146 -0
  10. package/dist/channel.d.ts.map +1 -0
  11. package/dist/channel.js +2 -0
  12. package/dist/channel.js.map +1 -0
  13. package/dist/client-session.d.ts +83 -0
  14. package/dist/client-session.d.ts.map +1 -0
  15. package/dist/client-session.js +2 -0
  16. package/dist/client-session.js.map +1 -0
  17. package/dist/command.d.ts +90 -0
  18. package/dist/command.d.ts.map +1 -0
  19. package/dist/command.js +15 -0
  20. package/dist/command.js.map +1 -0
  21. package/dist/compactor-helpers.d.ts +34 -0
  22. package/dist/compactor-helpers.d.ts.map +1 -0
  23. package/dist/compactor-helpers.js +156 -0
  24. package/dist/compactor-helpers.js.map +1 -0
  25. package/dist/compactor.d.ts +20 -0
  26. package/dist/compactor.d.ts.map +1 -0
  27. package/dist/compactor.js +2 -0
  28. package/dist/compactor.js.map +1 -0
  29. package/dist/define.d.ts +51 -0
  30. package/dist/define.d.ts.map +1 -0
  31. package/dist/define.js +71 -0
  32. package/dist/define.js.map +1 -0
  33. package/dist/elision-helpers.d.ts +27 -0
  34. package/dist/elision-helpers.d.ts.map +1 -0
  35. package/dist/elision-helpers.js +109 -0
  36. package/dist/elision-helpers.js.map +1 -0
  37. package/dist/elision-state.d.ts +49 -0
  38. package/dist/elision-state.d.ts.map +1 -0
  39. package/dist/elision-state.js +144 -0
  40. package/dist/elision-state.js.map +1 -0
  41. package/dist/embedding-cache.d.ts +32 -0
  42. package/dist/embedding-cache.d.ts.map +1 -0
  43. package/dist/embedding-cache.js +0 -0
  44. package/dist/embedding-cache.js.map +1 -0
  45. package/dist/embedding.d.ts +21 -0
  46. package/dist/embedding.d.ts.map +1 -0
  47. package/dist/embedding.js +2 -0
  48. package/dist/embedding.js.map +1 -0
  49. package/dist/errors.d.ts +81 -0
  50. package/dist/errors.d.ts.map +1 -0
  51. package/dist/errors.js +241 -0
  52. package/dist/errors.js.map +1 -0
  53. package/dist/events.d.ts +193 -0
  54. package/dist/events.d.ts.map +1 -0
  55. package/dist/events.js +2 -0
  56. package/dist/events.js.map +1 -0
  57. package/dist/hooks.d.ts +52 -0
  58. package/dist/hooks.d.ts.map +1 -0
  59. package/dist/hooks.js +2 -0
  60. package/dist/hooks.js.map +1 -0
  61. package/dist/ids.d.ts +18 -0
  62. package/dist/ids.d.ts.map +1 -0
  63. package/dist/ids.js +7 -0
  64. package/dist/ids.js.map +1 -0
  65. package/dist/index.d.ts +45 -0
  66. package/dist/index.d.ts.map +1 -0
  67. package/dist/index.js +18 -0
  68. package/dist/index.js.map +1 -0
  69. package/dist/install-hints.d.ts +26 -0
  70. package/dist/install-hints.d.ts.map +1 -0
  71. package/dist/install-hints.js +15 -0
  72. package/dist/install-hints.js.map +1 -0
  73. package/dist/isolation.d.ts +125 -0
  74. package/dist/isolation.d.ts.map +1 -0
  75. package/dist/isolation.js +11 -0
  76. package/dist/isolation.js.map +1 -0
  77. package/dist/log.d.ts +11 -0
  78. package/dist/log.d.ts.map +1 -0
  79. package/dist/log.js +2 -0
  80. package/dist/log.js.map +1 -0
  81. package/dist/mode-helpers.d.ts +99 -0
  82. package/dist/mode-helpers.d.ts.map +1 -0
  83. package/dist/mode-helpers.js +368 -0
  84. package/dist/mode-helpers.js.map +1 -0
  85. package/dist/mode.d.ts +133 -0
  86. package/dist/mode.d.ts.map +1 -0
  87. package/dist/mode.js +2 -0
  88. package/dist/mode.js.map +1 -0
  89. package/dist/permission.d.ts +35 -0
  90. package/dist/permission.d.ts.map +1 -0
  91. package/dist/permission.js +2 -0
  92. package/dist/permission.js.map +1 -0
  93. package/dist/plugin.d.ts +88 -0
  94. package/dist/plugin.d.ts.map +1 -0
  95. package/dist/plugin.js +2 -0
  96. package/dist/plugin.js.map +1 -0
  97. package/dist/provider-utils.d.ts +40 -0
  98. package/dist/provider-utils.d.ts.map +1 -0
  99. package/dist/provider-utils.js +163 -0
  100. package/dist/provider-utils.js.map +1 -0
  101. package/dist/provider.d.ts +219 -0
  102. package/dist/provider.d.ts.map +1 -0
  103. package/dist/provider.js +2 -0
  104. package/dist/provider.js.map +1 -0
  105. package/dist/requirements.d.ts +22 -0
  106. package/dist/requirements.d.ts.map +1 -0
  107. package/dist/requirements.js +2 -0
  108. package/dist/requirements.js.map +1 -0
  109. package/dist/schemas.d.ts +228 -0
  110. package/dist/schemas.d.ts.map +1 -0
  111. package/dist/schemas.js +88 -0
  112. package/dist/schemas.js.map +1 -0
  113. package/dist/session-like.d.ts +111 -0
  114. package/dist/session-like.d.ts.map +1 -0
  115. package/dist/session-like.js +2 -0
  116. package/dist/session-like.js.map +1 -0
  117. package/dist/skill.d.ts +30 -0
  118. package/dist/skill.d.ts.map +1 -0
  119. package/dist/skill.js +2 -0
  120. package/dist/skill.js.map +1 -0
  121. package/dist/subagent.d.ts +45 -0
  122. package/dist/subagent.d.ts.map +1 -0
  123. package/dist/subagent.js +11 -0
  124. package/dist/subagent.js.map +1 -0
  125. package/dist/token-accounting.d.ts +73 -0
  126. package/dist/token-accounting.d.ts.map +1 -0
  127. package/dist/token-accounting.js +129 -0
  128. package/dist/token-accounting.js.map +1 -0
  129. package/dist/tool-dispatch.d.ts +19 -0
  130. package/dist/tool-dispatch.d.ts.map +1 -0
  131. package/dist/tool-dispatch.js +118 -0
  132. package/dist/tool-dispatch.js.map +1 -0
  133. package/dist/tool-gating.d.ts +32 -0
  134. package/dist/tool-gating.d.ts.map +1 -0
  135. package/dist/tool-gating.js +83 -0
  136. package/dist/tool-gating.js.map +1 -0
  137. package/dist/tool.d.ts +166 -0
  138. package/dist/tool.d.ts.map +1 -0
  139. package/dist/tool.js +2 -0
  140. package/dist/tool.js.map +1 -0
  141. package/dist/transcriber.d.ts +64 -0
  142. package/dist/transcriber.d.ts.map +1 -0
  143. package/dist/transcriber.js +21 -0
  144. package/dist/transcriber.js.map +1 -0
  145. package/dist/tunnel.d.ts +25 -0
  146. package/dist/tunnel.d.ts.map +1 -0
  147. package/dist/tunnel.js +2 -0
  148. package/dist/tunnel.js.map +1 -0
  149. package/dist/type-contracts.d.ts +2 -0
  150. package/dist/type-contracts.d.ts.map +1 -0
  151. package/dist/type-contracts.js +4 -0
  152. package/dist/type-contracts.js.map +1 -0
  153. package/dist/types.test-d.d.ts +2 -0
  154. package/dist/types.test-d.d.ts.map +1 -0
  155. package/dist/types.test-d.js +22 -0
  156. package/dist/types.test-d.js.map +1 -0
  157. package/dist/view-renderer.d.ts +97 -0
  158. package/dist/view-renderer.d.ts.map +1 -0
  159. package/dist/view-renderer.js +72 -0
  160. package/dist/view-renderer.js.map +1 -0
  161. package/package.json +38 -0
  162. package/src/agent.ts +38 -0
  163. package/src/cache-strategy.ts +39 -0
  164. package/src/channel.ts +158 -0
  165. package/src/client-session.ts +88 -0
  166. package/src/command.ts +86 -0
  167. package/src/compactor-helpers.test.ts +206 -0
  168. package/src/compactor-helpers.ts +163 -0
  169. package/src/compactor.ts +20 -0
  170. package/src/define.test.ts +76 -0
  171. package/src/define.ts +113 -0
  172. package/src/elision-helpers.ts +143 -0
  173. package/src/elision-state.ts +170 -0
  174. package/src/embedding-cache.ts +0 -0
  175. package/src/embedding.ts +22 -0
  176. package/src/errors.test.ts +176 -0
  177. package/src/errors.ts +308 -0
  178. package/src/events.ts +250 -0
  179. package/src/hooks.ts +54 -0
  180. package/src/ids.ts +16 -0
  181. package/src/index.ts +304 -0
  182. package/src/install-hints.ts +43 -0
  183. package/src/isolation.ts +148 -0
  184. package/src/log.ts +11 -0
  185. package/src/loop-helpers.test.ts +78 -0
  186. package/src/mode-helpers.ts +483 -0
  187. package/src/mode.ts +139 -0
  188. package/src/package-root.test.ts +40 -0
  189. package/src/permission.ts +37 -0
  190. package/src/plugin.ts +92 -0
  191. package/src/provider-utils.test.ts +84 -0
  192. package/src/provider-utils.ts +171 -0
  193. package/src/provider.ts +195 -0
  194. package/src/requirements.ts +35 -0
  195. package/src/schemas.test.ts +106 -0
  196. package/src/schemas.ts +97 -0
  197. package/src/session-like.ts +118 -0
  198. package/src/skill.ts +34 -0
  199. package/src/subagent.ts +46 -0
  200. package/src/token-accounting.test.ts +93 -0
  201. package/src/token-accounting.ts +202 -0
  202. package/src/token-efficiency.test.ts +459 -0
  203. package/src/tool-dispatch.ts +137 -0
  204. package/src/tool-gating.ts +107 -0
  205. package/src/tool.ts +175 -0
  206. package/src/transcriber.ts +71 -0
  207. package/src/tunnel.ts +26 -0
  208. package/src/type-contracts.ts +4 -0
  209. package/src/types.test-d.ts +29 -0
  210. package/src/view-renderer.test.ts +90 -0
  211. package/src/view-renderer.ts +156 -0
@@ -0,0 +1,483 @@
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 { applyLazyTools } from './tool-gating.js';
15
+
16
+ /**
17
+ * Shared bits used by every loop strategy: a typed tool-use struct and a
18
+ * common stream-collection helper that runs `onBeforeProviderCall` hooks
19
+ * and reduces a provider stream down to `{text, toolUses, stopReason}`.
20
+ *
21
+ * Lives in core (not in each loop package) so a new loop strategy stays
22
+ * consistent — and so behavioral fixes here propagate. Previously
23
+ * loop-plan-execute had its own copy that skipped the hook (audit bug).
24
+ */
25
+
26
+ export interface CollectedToolUse {
27
+ readonly id: string;
28
+ readonly name: string;
29
+ readonly input: unknown;
30
+ }
31
+
32
+ /** Appended to the system prompt while elision is active (see projection). */
33
+ export const ELISION_SYSTEM_NOTE =
34
+ 'Context note: to stay within budget, older turns may appear as stubs like ' +
35
+ '`[output elided — recall("id") to view]` or `[elided user turn · recall({ seq: N })]`. ' +
36
+ 'These are NOT the real content — call the `recall` tool with the given id/seq to fetch ' +
37
+ 'the full text before relying on any detail from an elided turn. Recent turns are always ' +
38
+ 'shown verbatim.';
39
+
40
+ /**
41
+ * Compose a model-facing system prompt that includes any base prompt
42
+ * plus a COMPACT skill index (name + description + triggers only).
43
+ *
44
+ * Lazy-loading design: the body is intentionally NOT inlined. The model
45
+ * matches user intent against the description/triggers, then calls the
46
+ * `load_skill` tool to fetch the body of the skill it picked. This keeps
47
+ * the system prompt small even with many skills installed and avoids
48
+ * paying for skill bodies the model never actually follows.
49
+ */
50
+ export function buildSystemPromptWithSkills(
51
+ baseSystemPrompt: string | undefined,
52
+ skills: ReadonlyArray<Skill>,
53
+ ): string | undefined {
54
+ if (skills.length === 0) return baseSystemPrompt;
55
+ const header =
56
+ `## Available skills\n\n` +
57
+ `Each line below is a pre-authored playbook for a specific intent. ` +
58
+ `When the user's request matches one of these (by name, description, ` +
59
+ `or triggers), call \`load_skill({ name: "<skill-name>" })\` FIRST to ` +
60
+ `fetch the full instructions, then follow them verbatim. Prefer using ` +
61
+ `a skill over re-deriving the workflow with ad-hoc tools.\n`;
62
+ const entries = skills
63
+ .map((s) => {
64
+ const fm = s.frontmatter;
65
+ const triggerHint = fm.triggers?.length
66
+ ? ` (triggers: ${fm.triggers.map((t) => `"${t}"`).join(', ')})`
67
+ : '';
68
+ return `- **${fm.name}** — ${fm.description}${triggerHint}`;
69
+ })
70
+ .join('\n');
71
+ const skillBlock = `${header}\n${entries}`;
72
+ return baseSystemPrompt ? `${baseSystemPrompt}\n\n${skillBlock}` : skillBlock;
73
+ }
74
+
75
+ export interface ProjectMessagesOptions {
76
+ /** Optional system prompt; emitted as the first message when set. */
77
+ readonly systemPrompt?: string;
78
+ /** Optional trailing user message — useful for plan-execute's "Focus on this step now: X". */
79
+ readonly trailingUserText?: string;
80
+ }
81
+
82
+ interface CompactionRange {
83
+ readonly from: number;
84
+ readonly to: number;
85
+ readonly summary: string;
86
+ }
87
+
88
+ function activeCompactionRanges(events: ReadonlyArray<MoxxyEvent>): ReadonlyArray<CompactionRange> {
89
+ return events
90
+ .filter((event): event is CompactionEvent =>
91
+ event.type === 'compaction' &&
92
+ event.tokensSaved > 0 &&
93
+ event.summary.trim().length > 0 &&
94
+ event.replacedRange[0] <= event.replacedRange[1],
95
+ )
96
+ .map((event) => ({
97
+ from: event.replacedRange[0],
98
+ to: event.replacedRange[1],
99
+ summary: event.summary,
100
+ }));
101
+ }
102
+
103
+ function eventInCompactionRange(
104
+ seq: number,
105
+ ranges: ReadonlyArray<CompactionRange>,
106
+ ): CompactionRange | null {
107
+ for (const range of ranges) {
108
+ if (seq >= range.from && seq <= range.to) return range;
109
+ }
110
+ return null;
111
+ }
112
+
113
+ /**
114
+ * Project the session's event log to a flat list of ProviderMessages
115
+ * suitable for handing to `provider.stream`. Used by every loop strategy.
116
+ *
117
+ * Handles user_prompt, assistant_message, tool_call_requested (grouped
118
+ * into a single assistant message of tool_use blocks), and tool_result.
119
+ * Other event types are passed through as a no-op.
120
+ *
121
+ * This is THE projection every loop strategy uses; it honors compaction
122
+ * events, turn-boundary elision, and the orphan-tool_use fallback. It lives in
123
+ * the SDK so loop plugins stay independent of core.
124
+ */
125
+ export interface ProjectedMessages {
126
+ readonly messages: ProviderMessage[];
127
+ /**
128
+ * Index (into `messages`) of the last message belonging to the stable,
129
+ * byte-identical prefix — i.e. produced entirely from events at or below the
130
+ * elision high-water mark (which only advances on whole-turn boundaries, so
131
+ * the cut never splits a message). -1 when no elision is active. The
132
+ * `stable-prefix` cache strategy places its long-lived cross-turn breakpoint
133
+ * here; see {@link collectProviderStream}'s `stablePrefixIndex` option.
134
+ */
135
+ readonly stablePrefixIndex: number;
136
+ }
137
+
138
+ export function projectMessagesFromLog(
139
+ ctx: Pick<ModeContext, 'log'>,
140
+ opts: ProjectMessagesOptions = {},
141
+ ): ProviderMessage[] {
142
+ return projectMessages(ctx, opts).messages;
143
+ }
144
+
145
+ /**
146
+ * Same projection as {@link projectMessagesFromLog} but also reports the
147
+ * stable-prefix boundary so the active cache strategy can place a cross-turn
148
+ * breakpoint. Modes that build messages this way should thread the returned
149
+ * `stablePrefixIndex` into {@link collectProviderStream}.
150
+ */
151
+ export function projectMessages(
152
+ ctx: Pick<ModeContext, 'log'>,
153
+ opts: ProjectMessagesOptions = {},
154
+ ): ProjectedMessages {
155
+ const allEvents = ctx.log.slice();
156
+ const compactions = activeCompactionRanges(allEvents);
157
+ const emittedCompactions = new Set<CompactionRange>();
158
+ const el = computeElisionState(allEvents);
159
+
160
+ const messages: ProviderMessage[] = [];
161
+ // The stable prefix is every message produced from events at/below the
162
+ // elision HWM. Record the latest such message index as we push.
163
+ let stablePrefixIndex = -1;
164
+ const recordStable = (maxSeq: number): void => {
165
+ if (el.hwm >= 0 && maxSeq >= 0 && maxSeq <= el.hwm) {
166
+ stablePrefixIndex = messages.length - 1;
167
+ }
168
+ };
169
+ if (opts.systemPrompt) {
170
+ // When elision is active, tell the model that older turns may be shown as
171
+ // stubs and how to expand them — so it recalls instead of hallucinating.
172
+ // Constant text → busts the system cache once (when elision starts), stable
173
+ // thereafter.
174
+ const sysText = el.hwm >= 0 ? `${opts.systemPrompt}\n\n${ELISION_SYSTEM_NOTE}` : opts.systemPrompt;
175
+ messages.push({ role: 'system', content: [{ type: 'text', text: sysText }] });
176
+ }
177
+ // Pre-scan: build the set of callIds that have a matching tool_result
178
+ // (or tool_call_denied) somewhere in the log. Used to synthesize a
179
+ // fallback `[interrupted]` tool_result for orphan tool_use blocks
180
+ // when the assistant message gets flushed.
181
+ //
182
+ // Without this fallback the provider rejects the whole conversation
183
+ // with "assistant message with 'tool_calls' must be followed by tool
184
+ // messages responding to each 'tool_call_id'". Orphans typically
185
+ // appear after a cancelled turn, an aborted process, or a tool
186
+ // exception that bypassed the loop's tool_result emit path.
187
+ const resolvedCallIds = new Set<string>();
188
+ for (const e of allEvents) {
189
+ if (e.type === 'tool_result' || e.type === 'tool_call_denied') {
190
+ resolvedCallIds.add(e.callId);
191
+ }
192
+ }
193
+
194
+ let pendingAssistant: ProviderMessage | null = null;
195
+ let pendingAssistantMaxSeq = -1;
196
+ const flush = (): void => {
197
+ if (!pendingAssistant) return;
198
+ const flushed = pendingAssistant;
199
+ const groupMaxSeq = pendingAssistantMaxSeq;
200
+ pendingAssistant = null;
201
+ pendingAssistantMaxSeq = -1;
202
+ messages.push(flushed);
203
+ recordStable(groupMaxSeq);
204
+ // Synthesize fallback tool_result messages for any tool_use blocks
205
+ // whose callId never resolved in the event log. Has to land
206
+ // immediately after the assistant message (and before any
207
+ // subsequent user_prompt / assistant_message) so the provider sees
208
+ // a clean assistant→tool-result chain.
209
+ for (const block of flushed.content) {
210
+ if (block.type === 'tool_use' && !resolvedCallIds.has(block.id)) {
211
+ messages.push({
212
+ role: 'tool_result',
213
+ content: [
214
+ {
215
+ type: 'tool_result',
216
+ toolUseId: block.id,
217
+ content: '[tool call did not return a result — possibly interrupted or cancelled]',
218
+ isError: true,
219
+ },
220
+ ],
221
+ });
222
+ recordStable(groupMaxSeq);
223
+ // Mark synthesized so we don't double-emit if the same orphan
224
+ // appears in multiple groups (defensive — shouldn't normally
225
+ // happen since each tool_call_requested has a unique callId).
226
+ resolvedCallIds.add(block.id);
227
+ }
228
+ }
229
+ };
230
+
231
+ for (const e of allEvents) {
232
+ const compaction = eventInCompactionRange(e.seq, compactions);
233
+ if (compaction) {
234
+ if (!emittedCompactions.has(compaction)) {
235
+ emittedCompactions.add(compaction);
236
+ flush();
237
+ messages.push({
238
+ role: 'user',
239
+ content: [{ type: 'text', text: `[summary of earlier turns]\n${compaction.summary}` }],
240
+ });
241
+ recordStable(compaction.to);
242
+ }
243
+ continue;
244
+ }
245
+
246
+ switch (e.type) {
247
+ case 'user_prompt': {
248
+ flush();
249
+ // Elided + conversational: collapse to a stub (anchor/tiny kept full).
250
+ if (conversationalStubbed(e, el)) {
251
+ messages.push({
252
+ role: 'user',
253
+ content: [{ type: 'text', text: conversationalStub('user', e.seq) }],
254
+ });
255
+ recordStable(e.seq);
256
+ break;
257
+ }
258
+ const blocks: ContentBlock[] = [{ type: 'text', text: e.text }];
259
+ if (e.attachments) {
260
+ for (const att of e.attachments) {
261
+ if (att.kind === 'image') {
262
+ blocks.push({
263
+ type: 'image',
264
+ mediaType: att.mediaType ?? 'image/png',
265
+ data: att.content,
266
+ });
267
+ } else {
268
+ blocks.push({
269
+ type: 'text',
270
+ text: `[${att.kind}${att.name ? ` ${att.name}` : ''}]\n${att.content}`,
271
+ });
272
+ }
273
+ }
274
+ }
275
+ messages.push({ role: 'user', content: blocks });
276
+ recordStable(e.seq);
277
+ break;
278
+ }
279
+ case 'assistant_message':
280
+ flush();
281
+ if (conversationalStubbed(e, el)) {
282
+ messages.push({
283
+ role: 'assistant',
284
+ content: [{ type: 'text', text: conversationalStub('assistant', e.seq) }],
285
+ });
286
+ recordStable(e.seq);
287
+ break;
288
+ }
289
+ messages.push({ role: 'assistant', content: [{ type: 'text', text: e.content }] });
290
+ recordStable(e.seq);
291
+ break;
292
+ case 'tool_call_requested': {
293
+ pendingAssistant ??= { role: 'assistant', content: [] };
294
+ pendingAssistantMaxSeq = Math.max(pendingAssistantMaxSeq, e.seq);
295
+ (pendingAssistant.content as Array<ProviderMessage['content'][number]>).push({
296
+ type: 'tool_use',
297
+ id: e.callId,
298
+ name: e.name,
299
+ input: e.input,
300
+ });
301
+ break;
302
+ }
303
+ case 'tool_result': {
304
+ flush();
305
+ // Stub bulky old tool output to a recall-able marker (decision shared
306
+ // with estimateContextTokens via toolResultStubbed).
307
+ let text: string;
308
+ if (toolResultStubbed(e, el)) {
309
+ const recalled = el.recalledCallIds.has(e.callId) || el.recalledSeqs.has(e.seq);
310
+ text = toolResultStub(e.callId, toolResultBytes(e.output), recalled);
311
+ } else if (e.error) {
312
+ text = `[error:${e.error.kind}] ${e.error.message}`;
313
+ } else {
314
+ text = typeof e.output === 'string' ? e.output : JSON.stringify(e.output ?? '');
315
+ }
316
+ messages.push({
317
+ role: 'tool_result',
318
+ content: [{ type: 'tool_result', toolUseId: e.callId, content: text, isError: !e.ok }],
319
+ });
320
+ recordStable(e.seq);
321
+ break;
322
+ }
323
+ default:
324
+ break;
325
+ }
326
+ }
327
+ flush();
328
+
329
+ if (opts.trailingUserText) {
330
+ // The trailing step nudge is volatile (changes per step), never part of
331
+ // the stable prefix — don't record it.
332
+ messages.push({ role: 'user', content: [{ type: 'text', text: opts.trailingUserText }] });
333
+ }
334
+ return { messages, stablePrefixIndex };
335
+ }
336
+
337
+ export interface StreamResult {
338
+ readonly text: string;
339
+ readonly toolUses: ReadonlyArray<CollectedToolUse>;
340
+ readonly stopReason: StopReason;
341
+ readonly error: { readonly message: string; readonly retryable: boolean } | null;
342
+ /** Token usage reported by the provider on `message_end`, including cache hits/writes. */
343
+ readonly usage?: TokenUsage;
344
+ }
345
+
346
+ /**
347
+ * Pulls a provider stream, emits `assistant_chunk` events for text deltas,
348
+ * collects tool_use blocks, and returns the final `{text, toolUses, stopReason}`.
349
+ * Runs `onBeforeProviderCall` lifecycle hooks before the call.
350
+ */
351
+ export async function collectProviderStream(
352
+ ctx: ModeContext,
353
+ messages: ReadonlyArray<ProviderMessage>,
354
+ opts: {
355
+ iteration?: number;
356
+ includeTools?: boolean;
357
+ maxTokens?: number;
358
+ /**
359
+ * Index (into `messages`) of the last stable-prefix message, from
360
+ * {@link projectMessages}. Passed to the active cache strategy as
361
+ * `stablePrefixMessageIndex` so it can place a long-lived cross-turn
362
+ * breakpoint at the elision boundary. Omit (or -1) when unknown — the
363
+ * strategy then falls back to its tools/system/tail breakpoints only.
364
+ */
365
+ stablePrefixIndex?: number;
366
+ } = {},
367
+ ): Promise<StreamResult> {
368
+ // Lazy tool gating (opt-in): send only always-on + loaded tool schemas, and
369
+ // index the rest in the system prompt. Runs BEFORE cache planning since it
370
+ // rewrites the system message and the tool list.
371
+ let effectiveMessages = messages;
372
+ let toolList: ReadonlyArray<import('./tool.js').ToolDef> | undefined =
373
+ opts.includeTools === false ? undefined : ctx.tools.list();
374
+ if (ctx.lazyTools && toolList) {
375
+ const gated = applyLazyTools(messages, toolList, ctx.log);
376
+ effectiveMessages = gated.messages;
377
+ toolList = gated.tools;
378
+ }
379
+
380
+ // Ask the active cache strategy where to place prompt-cache breakpoints.
381
+ // The strategy is provider-neutral (returns CacheHints); the provider
382
+ // translates them (Anthropic → cache_control). Falls back to no hints when
383
+ // no strategy is registered. The onBeforeProviderCall hook can still adjust.
384
+ const descriptor = ctx.provider.models.find((m) => m.id === ctx.model);
385
+ const cacheHints = ctx.cacheStrategy
386
+ ? ctx.cacheStrategy.plan(effectiveMessages, {
387
+ model: ctx.model,
388
+ contextWindow: descriptor?.contextWindow ?? 0,
389
+ log: ctx.log,
390
+ ...(opts.stablePrefixIndex != null && opts.stablePrefixIndex >= 0
391
+ ? { stablePrefixMessageIndex: opts.stablePrefixIndex }
392
+ : {}),
393
+ })
394
+ : undefined;
395
+
396
+ const req = {
397
+ model: ctx.model,
398
+ system: ctx.systemPrompt,
399
+ messages: effectiveMessages,
400
+ ...(toolList ? { tools: toolList } : {}),
401
+ ...(cacheHints && cacheHints.length > 0 ? { cacheHints } : {}),
402
+ ...(opts.maxTokens !== undefined ? { maxTokens: opts.maxTokens } : {}),
403
+ signal: ctx.signal,
404
+ };
405
+ const transformed = await ctx.hooks.dispatchBeforeProviderCall(req, {
406
+ sessionId: ctx.sessionId,
407
+ cwd: '',
408
+ log: ctx.log,
409
+ env: {},
410
+ turnId: ctx.turnId,
411
+ iteration: opts.iteration ?? 0,
412
+ });
413
+
414
+ let text = '';
415
+ const toolUses = new Map<string, { name?: string; input?: unknown }>();
416
+ let stopReason: StopReason = 'end_turn';
417
+ let error: StreamResult['error'] = null;
418
+ let usage: TokenUsage | undefined;
419
+
420
+ let stream: AsyncIterable<ProviderEvent>;
421
+ try {
422
+ stream = ctx.provider.stream(transformed);
423
+ } catch (err) {
424
+ return {
425
+ text: '',
426
+ toolUses: [],
427
+ stopReason: 'error',
428
+ error: { message: err instanceof Error ? err.message : String(err), retryable: false },
429
+ };
430
+ }
431
+
432
+ try {
433
+ for await (const event of stream) {
434
+ switch (event.type) {
435
+ case 'text_delta': {
436
+ text += event.delta;
437
+ await ctx.emit({
438
+ type: 'assistant_chunk',
439
+ sessionId: ctx.sessionId,
440
+ turnId: ctx.turnId,
441
+ source: 'model',
442
+ delta: event.delta,
443
+ });
444
+ break;
445
+ }
446
+ case 'tool_use_start': {
447
+ toolUses.set(event.id, { name: event.name });
448
+ break;
449
+ }
450
+ case 'tool_use_end': {
451
+ const existing = toolUses.get(event.id) ?? {};
452
+ toolUses.set(event.id, { ...existing, input: event.input });
453
+ break;
454
+ }
455
+ case 'message_end': {
456
+ stopReason = event.stopReason;
457
+ if (event.usage) usage = event.usage;
458
+ break;
459
+ }
460
+ case 'error': {
461
+ error = { message: event.message, retryable: event.retryable };
462
+ break;
463
+ }
464
+ case 'message_start':
465
+ case 'tool_use_delta':
466
+ default:
467
+ break;
468
+ }
469
+ }
470
+ } catch (err) {
471
+ error = {
472
+ message: err instanceof Error ? err.message : String(err),
473
+ retryable: false,
474
+ };
475
+ }
476
+
477
+ const finalToolUses: CollectedToolUse[] = [];
478
+ for (const [id, partial] of toolUses) {
479
+ if (!partial.name) continue;
480
+ finalToolUses.push({ id, name: partial.name, input: partial.input ?? {} });
481
+ }
482
+ return { text, toolUses: finalToolUses, stopReason, error, ...(usage ? { usage } : {}) };
483
+ }
package/src/mode.ts ADDED
@@ -0,0 +1,139 @@
1
+ import type { CacheStrategyDef } from './cache-strategy.js';
2
+ import type { CompactorDef } from './compactor.js';
3
+ import type { EmittedEvent, MoxxyEvent } from './events.js';
4
+ import type { HookDispatcher } from './hooks.js';
5
+ import type { SessionId, TurnId } from './ids.js';
6
+ import type { EventLogReader } from './log.js';
7
+ import type { PermissionResolver } from './permission.js';
8
+ import type { LLMProvider } from './provider.js';
9
+ import type { Skill } from './skill.js';
10
+ import type { SubagentSpawner } from './subagent.js';
11
+ import type { ToolDef } from './tool.js';
12
+
13
+ export interface ToolRegistry {
14
+ list(): ReadonlyArray<ToolDef>;
15
+ get(name: string): ToolDef | undefined;
16
+ execute(name: string, input: unknown, signal: AbortSignal, opts?: ToolExecuteOpts): Promise<unknown>;
17
+ }
18
+
19
+ export interface ToolExecuteOpts {
20
+ readonly callId?: string;
21
+ readonly sessionId?: string;
22
+ readonly turnId?: string;
23
+ readonly log?: EventLogReader;
24
+ readonly cwd?: string;
25
+ }
26
+
27
+ export interface SkillRegistry {
28
+ list(): ReadonlyArray<Skill>;
29
+ get(id: string): Skill | undefined;
30
+ byName(name: string): Skill | undefined;
31
+ filterByTriggers(prompt: string): ReadonlyArray<Skill>;
32
+ }
33
+
34
+ export interface PluginHostHandle {
35
+ list(): ReadonlyArray<{ name: string; version: string; loaded: boolean }>;
36
+ reload(): Promise<void>;
37
+ }
38
+
39
+ /**
40
+ * Turn-boundary elision (context-on-demand) settings, resolved from config and
41
+ * carried on the ModeContext. All fields optional; {@link runElisionIfNeeded}
42
+ * applies defaults and floors (e.g. keepRecentTurns is floored at 2).
43
+ */
44
+ export interface ElisionSettings {
45
+ readonly enabled?: boolean;
46
+ readonly keepRecentTurns?: number;
47
+ readonly minContextRatioToElide?: number;
48
+ readonly elideConversational?: boolean;
49
+ readonly conversationalRecallThreshold?: number;
50
+ readonly maxRecallBytes?: number;
51
+ readonly neverElideTools?: ReadonlyArray<string>;
52
+ }
53
+
54
+ export interface ModeContext {
55
+ readonly sessionId: SessionId;
56
+ readonly turnId: TurnId;
57
+ readonly model: string;
58
+ readonly systemPrompt?: string;
59
+ readonly provider: LLMProvider;
60
+ readonly tools: ToolRegistry;
61
+ readonly skills: SkillRegistry;
62
+ readonly log: EventLogReader;
63
+ readonly compactor: CompactorDef | null;
64
+ /** Active prompt-caching strategy (or null when none is registered). */
65
+ readonly cacheStrategy: CacheStrategyDef | null;
66
+ /** Elision (context-on-demand) settings; undefined → defaults apply. */
67
+ readonly elision?: ElisionSettings;
68
+ /** When true, send only always-on + loaded tool schemas; index the rest. */
69
+ readonly lazyTools?: boolean;
70
+ readonly permissions: PermissionResolver;
71
+ /**
72
+ * Optional generic "ask the user a question" gate. Any loop strategy can
73
+ * call this to surface a checkpoint to the user — plan-execute uses it
74
+ * after producing a plan, but a code-execution loop could use it for
75
+ * "run this command?" or a refactor loop for "apply this diff?". When
76
+ * absent (headless / non-TTY), strategies should proceed as if the user
77
+ * picked the default option, or fail closed depending on the strategy.
78
+ */
79
+ readonly approval?: ApprovalResolver;
80
+ readonly hooks: HookDispatcher;
81
+ readonly pluginHost: PluginHostHandle;
82
+ readonly signal: AbortSignal;
83
+ readonly maxIterations?: number;
84
+ /**
85
+ * Spawn one or more child agents that share the parent's registries
86
+ * but run in isolation. Children stream their events back to the
87
+ * parent log as `plugin_event` records with `subagent_*` subtypes.
88
+ * Absent in synthetic test contexts that don't model a full Session.
89
+ */
90
+ readonly subagents?: SubagentSpawner;
91
+ emit(event: EmittedEvent): Promise<MoxxyEvent>;
92
+ }
93
+
94
+ /**
95
+ * Generic approval-dialog request. The TUI renders `title` as the header,
96
+ * `body` as a verbatim block (plan text, diff, command preview, etc.), and
97
+ * a single-select list of `options`. An option may set `requestsText` so
98
+ * the dialog prompts for follow-up text after selection (e.g. redraft
99
+ * feedback). `kind` is a loose tag the dialog/CLI can use for styling.
100
+ */
101
+ export interface ApprovalRequest {
102
+ readonly title: string;
103
+ readonly body: string;
104
+ readonly options: ReadonlyArray<ApprovalOption>;
105
+ readonly defaultOptionId?: string;
106
+ readonly kind?: string;
107
+ }
108
+
109
+ export interface ApprovalOption {
110
+ readonly id: string;
111
+ readonly label: string;
112
+ readonly hotkey?: string;
113
+ readonly description?: string;
114
+ readonly requestsText?: boolean;
115
+ readonly textPrompt?: string;
116
+ readonly danger?: boolean;
117
+ }
118
+
119
+ export interface ApprovalDecision {
120
+ readonly optionId: string;
121
+ /** Free-text follow-up the user typed when the option had `requestsText: true`. */
122
+ readonly text?: string;
123
+ }
124
+
125
+ export interface ApprovalResolver {
126
+ readonly name: string;
127
+ confirm(req: ApprovalRequest): Promise<ApprovalDecision>;
128
+ }
129
+
130
+ export interface ModeDef {
131
+ readonly name: string;
132
+ /**
133
+ * One-line summary of what this mode does. Rendered next to the mode
134
+ * name in the TUI /mode picker so users have context without
135
+ * memorising plugin internals. Keep short — the picker truncates.
136
+ */
137
+ readonly description?: string;
138
+ run(ctx: ModeContext): AsyncIterable<MoxxyEvent>;
139
+ }
@@ -0,0 +1,40 @@
1
+ import { describe, expect, it } from 'vitest';
2
+
3
+ describe('@moxxy/sdk package root', () => {
4
+ it('exports defineTranscriber for workspace consumers', async () => {
5
+ const sdk = await import('@moxxy/sdk');
6
+
7
+ expect(typeof sdk.defineTranscriber).toBe('function');
8
+
9
+ const def = sdk.defineTranscriber({
10
+ name: 'package-root-transcriber',
11
+ createClient: () => ({
12
+ name: 'package-root-transcriber',
13
+ transcribe: async () => ({ text: 'ok' }),
14
+ }),
15
+ });
16
+
17
+ expect(def.name).toBe('package-root-transcriber');
18
+ expect(Object.isFrozen(def)).toBe(true);
19
+ });
20
+
21
+ it('exports requirement types through package root declarations', async () => {
22
+ const requirement: import('@moxxy/sdk').MoxxyRequirement = {
23
+ kind: 'runtime',
24
+ name: 'auth:provider:openai-codex',
25
+ state: 'ready',
26
+ };
27
+ const check: import('@moxxy/sdk').RequirementCheck = {
28
+ ready: false,
29
+ issues: [
30
+ {
31
+ requirement,
32
+ code: 'not_ready',
33
+ message: 'OAuth is not ready',
34
+ },
35
+ ],
36
+ };
37
+
38
+ expect(check.issues[0]?.requirement.name).toBe('auth:provider:openai-codex');
39
+ });
40
+ });
@@ -0,0 +1,37 @@
1
+ import type { ToolCallRequestedEvent } from './events.js';
2
+
3
+ export type PermissionMode = 'allow' | 'allow_session' | 'allow_always' | 'deny';
4
+
5
+ export interface PermissionDecision {
6
+ readonly mode: PermissionMode;
7
+ readonly reason?: string;
8
+ }
9
+
10
+ export interface PermissionRule {
11
+ readonly action: 'allow' | 'deny' | 'prompt';
12
+ readonly pattern?: { name?: string | RegExp; inputMatches?: Record<string, string | RegExp> };
13
+ readonly reason?: string;
14
+ }
15
+
16
+ export interface PendingToolCall {
17
+ readonly callId: ToolCallRequestedEvent['callId'];
18
+ readonly name: string;
19
+ readonly input: unknown;
20
+ /**
21
+ * Sequence number of the `tool_call_requested` event in the EventLog.
22
+ * Optional because permission resolvers may construct PendingToolCalls
23
+ * for evaluations that aren't yet on the log (e.g., hook rewrites).
24
+ */
25
+ readonly requestedAtSeq?: number;
26
+ }
27
+
28
+ export interface PermissionContext {
29
+ readonly toolDescription?: string;
30
+ readonly skillContext?: string;
31
+ readonly sessionId: string;
32
+ }
33
+
34
+ export interface PermissionResolver {
35
+ readonly name: string;
36
+ check(call: PendingToolCall, ctx: PermissionContext): Promise<PermissionDecision>;
37
+ }