mu-core 0.15.0 → 0.16.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.
- package/esm/agent.d.ts +39 -0
- package/esm/agent.js +96 -0
- package/esm/index.d.ts +4 -0
- package/esm/index.js +2 -0
- package/esm/package.json +3 -0
- package/esm/types.d.ts +59 -0
- package/esm/types.js +3 -0
- package/package.json +14 -10
- package/script/agent.d.ts +39 -0
- package/script/agent.js +101 -0
- package/script/index.d.ts +4 -0
- package/script/index.js +10 -0
- package/script/package.json +3 -0
- package/script/types.d.ts +59 -0
- package/script/types.js +9 -0
- package/README.md +0 -110
- package/src/activity.test.ts +0 -44
- package/src/activity.ts +0 -83
- package/src/agent.test.ts +0 -91
- package/src/agent.ts +0 -249
- package/src/channel.test.ts +0 -52
- package/src/channel.ts +0 -77
- package/src/hooks.test.ts +0 -105
- package/src/hooks.ts +0 -112
- package/src/host/index.ts +0 -135
- package/src/host/startMu.test.ts +0 -66
- package/src/index.ts +0 -74
- package/src/plugin.ts +0 -389
- package/src/provider/adapter.ts +0 -100
- package/src/provider/registry.test.ts +0 -37
- package/src/provider/registry.ts +0 -26
- package/src/provider/transport.test.ts +0 -58
- package/src/provider/transport.ts +0 -103
- package/src/registry.context.test.ts +0 -71
- package/src/registry.ts +0 -484
- package/src/session.test.ts +0 -99
- package/src/session.ts +0 -248
- package/src/types/llm.ts +0 -120
- package/src/ui.ts +0 -49
package/src/activity.ts
DELETED
|
@@ -1,83 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* ActivityBus — pub/sub for high-level events emitted by the agent loop and
|
|
3
|
-
* by tools. Hosts subscribe to render timelines (TUI), broadcast to
|
|
4
|
-
* companion websockets, etc. Independent of the session message store —
|
|
5
|
-
* messages_changed is on Session, ActivityBus is for sidebar/observability.
|
|
6
|
-
*/
|
|
7
|
-
|
|
8
|
-
export type ActivityKind =
|
|
9
|
-
| 'agent_start'
|
|
10
|
-
| 'agent_end'
|
|
11
|
-
| 'tool_start'
|
|
12
|
-
| 'tool_end'
|
|
13
|
-
| 'task_started'
|
|
14
|
-
| 'task_completed'
|
|
15
|
-
| 'task_error';
|
|
16
|
-
|
|
17
|
-
export interface ActivityEvent {
|
|
18
|
-
id: number;
|
|
19
|
-
ts: number;
|
|
20
|
-
kind: ActivityKind;
|
|
21
|
-
source: string;
|
|
22
|
-
summary: string;
|
|
23
|
-
detail?: Record<string, unknown>;
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
export type SubAgentEventKind =
|
|
27
|
-
| 'invocation_start'
|
|
28
|
-
| 'text_delta'
|
|
29
|
-
| 'message_end'
|
|
30
|
-
| 'tool_call_start'
|
|
31
|
-
| 'tool_call_end'
|
|
32
|
-
| 'invocation_end';
|
|
33
|
-
|
|
34
|
-
export interface SubAgentEvent {
|
|
35
|
-
runId: string;
|
|
36
|
-
parentRunId?: string;
|
|
37
|
-
agentId: string;
|
|
38
|
-
kind: SubAgentEventKind;
|
|
39
|
-
ts: number;
|
|
40
|
-
data: Record<string, unknown>;
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
export interface ActivityBus {
|
|
44
|
-
subscribe: (fn: (e: ActivityEvent) => void) => () => void;
|
|
45
|
-
emit: (kind: ActivityKind, source: string, summary: string, detail?: Record<string, unknown>) => void;
|
|
46
|
-
subscribeSubAgent: (fn: (e: SubAgentEvent) => void) => () => void;
|
|
47
|
-
emitSubAgent: (e: SubAgentEvent) => void;
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
export function createActivityBus(): ActivityBus {
|
|
51
|
-
let nextId = 1;
|
|
52
|
-
const listeners = new Set<(e: ActivityEvent) => void>();
|
|
53
|
-
const subListeners = new Set<(e: SubAgentEvent) => void>();
|
|
54
|
-
return {
|
|
55
|
-
subscribe(fn) {
|
|
56
|
-
listeners.add(fn);
|
|
57
|
-
return () => listeners.delete(fn);
|
|
58
|
-
},
|
|
59
|
-
emit(kind, source, summary, detail) {
|
|
60
|
-
const event: ActivityEvent = { id: nextId++, ts: Date.now(), kind, source, summary, detail };
|
|
61
|
-
for (const fn of listeners) {
|
|
62
|
-
try {
|
|
63
|
-
fn(event);
|
|
64
|
-
} catch {
|
|
65
|
-
// listeners must not break the bus
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
|
-
},
|
|
69
|
-
subscribeSubAgent(fn) {
|
|
70
|
-
subListeners.add(fn);
|
|
71
|
-
return () => subListeners.delete(fn);
|
|
72
|
-
},
|
|
73
|
-
emitSubAgent(e) {
|
|
74
|
-
for (const fn of subListeners) {
|
|
75
|
-
try {
|
|
76
|
-
fn(e);
|
|
77
|
-
} catch {
|
|
78
|
-
// ignore
|
|
79
|
-
}
|
|
80
|
-
}
|
|
81
|
-
},
|
|
82
|
-
};
|
|
83
|
-
}
|
package/src/agent.test.ts
DELETED
|
@@ -1,91 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Focused tests for `runAgent`. Most coverage lives in higher layers
|
|
3
|
-
* (session, mu-agents subagent, integration) but we keep a few pinpoint
|
|
4
|
-
* cases here to lock down behaviour that's easy to break:
|
|
5
|
-
*
|
|
6
|
-
* - `display.llmHidden` strips messages from the network payload but
|
|
7
|
-
* keeps them in the streamed transcript surface (regression target
|
|
8
|
-
* for the `@`-mention dispatch flow that injects a UI-only subagent
|
|
9
|
-
* header alongside a real synthetic tool flow).
|
|
10
|
-
*/
|
|
11
|
-
import { describe, expect, it } from 'bun:test';
|
|
12
|
-
import { runAgent } from './agent';
|
|
13
|
-
import { createProviderRegistry } from './provider/registry';
|
|
14
|
-
import { PluginRegistry } from './registry';
|
|
15
|
-
import type { ChatMessage, ProviderConfig, StreamChunk } from './types/llm';
|
|
16
|
-
|
|
17
|
-
interface CapturedCall {
|
|
18
|
-
messages: ChatMessage[];
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
function fakeRegistry(captured: CapturedCall[]): PluginRegistry {
|
|
22
|
-
const providers = createProviderRegistry();
|
|
23
|
-
providers.register({
|
|
24
|
-
id: 'openai',
|
|
25
|
-
async *streamChat(messages: ChatMessage[]): AsyncIterable<StreamChunk> {
|
|
26
|
-
// Snapshot the exact message list the provider receives so the test
|
|
27
|
-
// can assert on what `streamTurn` actually sent over the wire.
|
|
28
|
-
captured.push({ messages: messages.map((m) => ({ ...m })) });
|
|
29
|
-
yield { type: 'content', text: 'ok' };
|
|
30
|
-
},
|
|
31
|
-
async listModels() {
|
|
32
|
-
return [];
|
|
33
|
-
},
|
|
34
|
-
});
|
|
35
|
-
return new PluginRegistry({ cwd: '/tmp', config: {}, providers });
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
const CFG: ProviderConfig = { providerId: 'openai' };
|
|
39
|
-
|
|
40
|
-
describe('runAgent — display.llmHidden filter', () => {
|
|
41
|
-
it('strips llmHidden messages from the provider payload', async () => {
|
|
42
|
-
const captured: CapturedCall[] = [];
|
|
43
|
-
const registry = fakeRegistry(captured);
|
|
44
|
-
|
|
45
|
-
const messages: ChatMessage[] = [
|
|
46
|
-
{ role: 'system', content: 'sys' },
|
|
47
|
-
// UI-only marker — must be filtered before the network call.
|
|
48
|
-
{
|
|
49
|
-
role: 'assistant',
|
|
50
|
-
content: 'phantom header',
|
|
51
|
-
display: { llmHidden: true },
|
|
52
|
-
},
|
|
53
|
-
{ role: 'user', content: 'hi' },
|
|
54
|
-
];
|
|
55
|
-
|
|
56
|
-
for await (const _ of runAgent(messages, CFG, 'm', new AbortController().signal, registry)) {
|
|
57
|
-
// drain
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
expect(captured.length).toBe(1);
|
|
61
|
-
const sent = captured[0].messages;
|
|
62
|
-
// Only system + user reach the provider.
|
|
63
|
-
expect(sent.length).toBe(2);
|
|
64
|
-
expect(sent[0].role).toBe('system');
|
|
65
|
-
expect(sent[1].role).toBe('user');
|
|
66
|
-
expect(sent.find((m) => m.content === 'phantom header')).toBeUndefined();
|
|
67
|
-
});
|
|
68
|
-
|
|
69
|
-
it('keeps non-llmHidden messages even when `display.hidden` is set', async () => {
|
|
70
|
-
// Inverse flag: `display.hidden` is UI-only suppression and must NOT
|
|
71
|
-
// affect the LLM payload. This test pins that the two flags do not
|
|
72
|
-
// accidentally collapse into the same filter.
|
|
73
|
-
const captured: CapturedCall[] = [];
|
|
74
|
-
const registry = fakeRegistry(captured);
|
|
75
|
-
|
|
76
|
-
const messages: ChatMessage[] = [
|
|
77
|
-
{ role: 'system', content: 'sys' },
|
|
78
|
-
{ role: 'user', content: 'silent reminder', display: { hidden: true } },
|
|
79
|
-
{ role: 'user', content: 'hi' },
|
|
80
|
-
];
|
|
81
|
-
|
|
82
|
-
for await (const _ of runAgent(messages, CFG, 'm', new AbortController().signal, registry)) {
|
|
83
|
-
// drain
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
expect(captured.length).toBe(1);
|
|
87
|
-
const sent = captured[0].messages;
|
|
88
|
-
expect(sent.length).toBe(3);
|
|
89
|
-
expect(sent.find((m) => m.content === 'silent reminder')).toBeDefined();
|
|
90
|
-
});
|
|
91
|
-
});
|
package/src/agent.ts
DELETED
|
@@ -1,249 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
runAfterAgentRunHooks,
|
|
3
|
-
runAfterLlmHooks,
|
|
4
|
-
runAfterToolExecHook,
|
|
5
|
-
runBeforeLlmHooks,
|
|
6
|
-
runBeforeToolExecHook,
|
|
7
|
-
runDecorateMessageHooks,
|
|
8
|
-
} from './hooks';
|
|
9
|
-
import type { AgentEvent, PluginTool, ToolResult, TurnResult } from './plugin';
|
|
10
|
-
import type { PluginRegistry } from './registry';
|
|
11
|
-
import type { ChatMessage, ProviderConfig, StreamChunk, StreamOptions, ToolCall } from './types/llm';
|
|
12
|
-
|
|
13
|
-
const DEFAULT_PROVIDER_ID = 'openai';
|
|
14
|
-
|
|
15
|
-
/**
|
|
16
|
-
* Stream a chat completion through the host's provider registry. Resolved
|
|
17
|
-
* by `config.providerId` (default `'openai'`). When no provider matches, we
|
|
18
|
-
* throw — `mu-core` is provider-agnostic, the host is responsible for
|
|
19
|
-
* registering at least one (e.g. via `mu-openai-provider`).
|
|
20
|
-
*/
|
|
21
|
-
function streamChatViaRegistry(
|
|
22
|
-
registry: PluginRegistry,
|
|
23
|
-
messages: ChatMessage[],
|
|
24
|
-
config: ProviderConfig,
|
|
25
|
-
model: string,
|
|
26
|
-
options: StreamOptions,
|
|
27
|
-
): AsyncIterable<StreamChunk> {
|
|
28
|
-
const id = config.providerId ?? DEFAULT_PROVIDER_ID;
|
|
29
|
-
const providers = registry.getProviders();
|
|
30
|
-
const provider = providers?.get(id);
|
|
31
|
-
if (!provider) {
|
|
32
|
-
throw new Error(
|
|
33
|
-
`No provider registered for id "${id}". Register one (e.g. via mu-openai-provider) before calling runAgent.`,
|
|
34
|
-
);
|
|
35
|
-
}
|
|
36
|
-
return provider.streamChat(messages, config, model, options);
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
async function executeTool(call: ToolCall, tools: PluginTool[], signal?: AbortSignal): Promise<ToolResult> {
|
|
40
|
-
let args: Record<string, unknown>;
|
|
41
|
-
try {
|
|
42
|
-
args = JSON.parse(call.function.arguments);
|
|
43
|
-
} catch {
|
|
44
|
-
return { tool_call_id: call.id, name: call.function.name, content: 'Error: Invalid JSON arguments', error: true };
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
const tool = tools.find((t) => t.definition.function.name === call.function.name);
|
|
48
|
-
if (!tool) {
|
|
49
|
-
return {
|
|
50
|
-
tool_call_id: call.id,
|
|
51
|
-
name: call.function.name,
|
|
52
|
-
content: `Error: Unknown tool: ${call.function.name}`,
|
|
53
|
-
error: true,
|
|
54
|
-
};
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
try {
|
|
58
|
-
const result = await tool.execute(args, signal);
|
|
59
|
-
// Tools may return either a plain string (error inferred from "Error:"
|
|
60
|
-
// prefix — legacy/convenience form) or a typed `{ content, error }`
|
|
61
|
-
// object that makes the error flag explicit. Both forms are accepted to
|
|
62
|
-
// avoid breaking existing plugin authors.
|
|
63
|
-
if (typeof result === 'string') {
|
|
64
|
-
return { tool_call_id: call.id, name: call.function.name, content: result, error: result.startsWith('Error:') };
|
|
65
|
-
}
|
|
66
|
-
return {
|
|
67
|
-
tool_call_id: call.id,
|
|
68
|
-
name: call.function.name,
|
|
69
|
-
content: result.content,
|
|
70
|
-
error: result.error ?? false,
|
|
71
|
-
};
|
|
72
|
-
} catch (err) {
|
|
73
|
-
const msg = err instanceof Error ? err.message : 'Unknown error';
|
|
74
|
-
return { tool_call_id: call.id, name: call.function.name, content: `Error: ${msg}`, error: true };
|
|
75
|
-
}
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
async function* streamTurn(
|
|
79
|
-
messages: ChatMessage[],
|
|
80
|
-
config: ProviderConfig,
|
|
81
|
-
model: string,
|
|
82
|
-
signal: AbortSignal,
|
|
83
|
-
registry: PluginRegistry,
|
|
84
|
-
toolDefs: PluginTool[],
|
|
85
|
-
): AsyncGenerator<AgentEvent, TurnResult> {
|
|
86
|
-
let content = '';
|
|
87
|
-
let reasoning = '';
|
|
88
|
-
let usage = 0;
|
|
89
|
-
let cachedPromptTokens = 0;
|
|
90
|
-
let promptTokens = 0;
|
|
91
|
-
const toolCalls: ToolCall[] = [];
|
|
92
|
-
|
|
93
|
-
const hooks = registry.getHooks();
|
|
94
|
-
const hookedMessages = await runBeforeLlmHooks(hooks, messages, config);
|
|
95
|
-
// `display.llmHidden` keeps a message in the on-screen transcript but
|
|
96
|
-
// strips it from the LLM payload. Applied AFTER `beforeLlmHooks` so plugin
|
|
97
|
-
// hooks still see the full transcript if they want it; this is the very
|
|
98
|
-
// last filter before the network call. Inverse of `display.hidden`, which
|
|
99
|
-
// hides from UI but keeps in the LLM payload.
|
|
100
|
-
const llmMessages = hookedMessages.filter((m) => !m.display?.llmHidden);
|
|
101
|
-
const toolDefinitions = toolDefs.map((t) => t.definition);
|
|
102
|
-
|
|
103
|
-
for await (const chunk of streamChatViaRegistry(registry, llmMessages, config, model, {
|
|
104
|
-
signal,
|
|
105
|
-
tools: toolDefinitions,
|
|
106
|
-
onUsage: (u) => {
|
|
107
|
-
usage = u.totalTokens;
|
|
108
|
-
promptTokens = u.promptTokens;
|
|
109
|
-
cachedPromptTokens = u.cachedPromptTokens ?? 0;
|
|
110
|
-
},
|
|
111
|
-
})) {
|
|
112
|
-
if (signal.aborted) {
|
|
113
|
-
break;
|
|
114
|
-
}
|
|
115
|
-
if (chunk.type === 'reasoning') {
|
|
116
|
-
reasoning += chunk.text;
|
|
117
|
-
yield { type: 'reasoning', text: reasoning };
|
|
118
|
-
} else if (chunk.type === 'content') {
|
|
119
|
-
content += chunk.text;
|
|
120
|
-
yield { type: 'content', text: content };
|
|
121
|
-
} else if (chunk.type === 'tool_call') {
|
|
122
|
-
toolCalls.push({ id: chunk.toolCall.id, function: chunk.toolCall.function });
|
|
123
|
-
}
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
const result: TurnResult = { content, reasoning, toolCalls, usage, promptTokens, cachedPromptTokens };
|
|
127
|
-
return await runAfterLlmHooks(hooks, result);
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
async function executeOneToolCall(
|
|
131
|
-
tc: ToolCall,
|
|
132
|
-
tools: PluginTool[],
|
|
133
|
-
signal: AbortSignal,
|
|
134
|
-
registry: PluginRegistry,
|
|
135
|
-
): Promise<ChatMessage> {
|
|
136
|
-
const hooks = registry.getHooks();
|
|
137
|
-
const hookOutcome = await runBeforeToolExecHook(hooks, tc);
|
|
138
|
-
|
|
139
|
-
if ('blocked' in hookOutcome) {
|
|
140
|
-
const content = await runAfterToolExecHook(hooks, tc, hookOutcome.content);
|
|
141
|
-
return runDecorateMessageHooks(hooks, {
|
|
142
|
-
role: 'tool',
|
|
143
|
-
content,
|
|
144
|
-
toolCallId: tc.id,
|
|
145
|
-
toolResult: { name: tc.function.name, content, error: hookOutcome.error ?? true },
|
|
146
|
-
toolCallArgs: { [tc.function.name]: tc.function.arguments },
|
|
147
|
-
});
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
const result = await executeTool(hookOutcome, tools, signal);
|
|
151
|
-
const content = await runAfterToolExecHook(hooks, hookOutcome, result.content);
|
|
152
|
-
return runDecorateMessageHooks(hooks, {
|
|
153
|
-
role: 'tool',
|
|
154
|
-
content,
|
|
155
|
-
toolCallId: result.tool_call_id,
|
|
156
|
-
toolResult: { name: result.name, content, error: result.error },
|
|
157
|
-
toolCallArgs: { [result.name]: tc.function.arguments },
|
|
158
|
-
});
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
async function* executeToolCalls(
|
|
162
|
-
calls: ToolCall[],
|
|
163
|
-
start: ChatMessage[],
|
|
164
|
-
signal: AbortSignal,
|
|
165
|
-
registry: PluginRegistry,
|
|
166
|
-
tools: PluginTool[],
|
|
167
|
-
): AsyncGenerator<AgentEvent, ChatMessage[]> {
|
|
168
|
-
let current = start;
|
|
169
|
-
|
|
170
|
-
for (const tc of calls) {
|
|
171
|
-
if (signal.aborted) break;
|
|
172
|
-
const toolMessage = await executeOneToolCall(tc, tools, signal, registry);
|
|
173
|
-
if (signal.aborted) break;
|
|
174
|
-
current = [...current, toolMessage];
|
|
175
|
-
yield { type: 'messages', messages: current };
|
|
176
|
-
}
|
|
177
|
-
return current;
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
async function buildMergedConfig(config: ProviderConfig, registry: PluginRegistry): Promise<ProviderConfig> {
|
|
181
|
-
const pluginPrompts = await registry.getSystemPrompts();
|
|
182
|
-
const merged = [config.systemPrompt, ...pluginPrompts].filter(Boolean).join('\n\n');
|
|
183
|
-
const transformed = await registry.applySystemPromptTransforms(merged);
|
|
184
|
-
if (!transformed) return config;
|
|
185
|
-
return { ...config, systemPrompt: transformed };
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
export async function* runAgent(
|
|
189
|
-
initialMessages: ChatMessage[],
|
|
190
|
-
config: ProviderConfig,
|
|
191
|
-
model: string,
|
|
192
|
-
signal: AbortSignal,
|
|
193
|
-
registry: PluginRegistry,
|
|
194
|
-
): AsyncGenerator<AgentEvent> {
|
|
195
|
-
const mergedConfig = await buildMergedConfig(config, registry);
|
|
196
|
-
const hooks = registry.getHooks();
|
|
197
|
-
|
|
198
|
-
// Wrap the body in try/finally so `afterAgentRun` fires exactly once per
|
|
199
|
-
// `runAgent` call, regardless of how it terminates: normal completion (LLM
|
|
200
|
-
// produced a final response), abort via `signal.aborted`, or generator
|
|
201
|
-
// cancellation by the consumer (Ink unmount, manual `.return()`).
|
|
202
|
-
try {
|
|
203
|
-
const customLoop = registry.getAgentLoop();
|
|
204
|
-
if (customLoop) {
|
|
205
|
-
const filtered = await registry.getFilteredTools();
|
|
206
|
-
yield* customLoop.run(initialMessages, mergedConfig, model, signal, filtered, hooks);
|
|
207
|
-
return;
|
|
208
|
-
}
|
|
209
|
-
|
|
210
|
-
let current = initialMessages;
|
|
211
|
-
|
|
212
|
-
while (!signal.aborted) {
|
|
213
|
-
// Re-evaluate every turn so per-turn agent switches are honoured.
|
|
214
|
-
const tools = await registry.getFilteredTools();
|
|
215
|
-
const { content, reasoning, toolCalls, usage, promptTokens, cachedPromptTokens } = yield* streamTurn(
|
|
216
|
-
current,
|
|
217
|
-
mergedConfig,
|
|
218
|
-
model,
|
|
219
|
-
signal,
|
|
220
|
-
registry,
|
|
221
|
-
tools,
|
|
222
|
-
);
|
|
223
|
-
|
|
224
|
-
if (usage > 0) {
|
|
225
|
-
yield { type: 'usage', totalTokens: usage, promptTokens, cachedTokens: cachedPromptTokens };
|
|
226
|
-
}
|
|
227
|
-
if (signal.aborted) {
|
|
228
|
-
break;
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
const reasoningField = reasoning || undefined;
|
|
232
|
-
const assistantBase: ChatMessage = { role: 'assistant', content, reasoning: reasoningField };
|
|
233
|
-
if (toolCalls.length === 0) {
|
|
234
|
-
const assistant = await runDecorateMessageHooks(registry.getHooks(), assistantBase);
|
|
235
|
-
current = [...current, assistant];
|
|
236
|
-
yield { type: 'messages', messages: current };
|
|
237
|
-
return;
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
const assistantWithCalls = await runDecorateMessageHooks(registry.getHooks(), { ...assistantBase, toolCalls });
|
|
241
|
-
current = [...current, assistantWithCalls];
|
|
242
|
-
yield { type: 'messages', messages: current };
|
|
243
|
-
current = yield* executeToolCalls(toolCalls, current, signal, registry, tools);
|
|
244
|
-
yield { type: 'turn_end' };
|
|
245
|
-
}
|
|
246
|
-
} finally {
|
|
247
|
-
await runAfterAgentRunHooks(hooks, signal.aborted ? 'aborted' : 'complete');
|
|
248
|
-
}
|
|
249
|
-
}
|
package/src/channel.test.ts
DELETED
|
@@ -1,52 +0,0 @@
|
|
|
1
|
-
import { describe, expect, it } from 'bun:test';
|
|
2
|
-
import { type Channel, createChannelRegistry } from './channel';
|
|
3
|
-
|
|
4
|
-
function makeChannel(id: string, started: { value: boolean }): Channel {
|
|
5
|
-
return {
|
|
6
|
-
id,
|
|
7
|
-
async start() {
|
|
8
|
-
started.value = true;
|
|
9
|
-
},
|
|
10
|
-
async stop() {
|
|
11
|
-
started.value = false;
|
|
12
|
-
},
|
|
13
|
-
};
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
describe('ChannelRegistry', () => {
|
|
17
|
-
it('registers, lists, gets', () => {
|
|
18
|
-
const r = createChannelRegistry();
|
|
19
|
-
const flag = { value: false };
|
|
20
|
-
r.register(makeChannel('tui', flag));
|
|
21
|
-
expect(r.list().map((c) => c.id)).toEqual(['tui']);
|
|
22
|
-
expect(r.get('tui')?.id).toBe('tui');
|
|
23
|
-
expect(r.get('missing')).toBeUndefined();
|
|
24
|
-
});
|
|
25
|
-
|
|
26
|
-
it('rejects duplicate id', () => {
|
|
27
|
-
const r = createChannelRegistry();
|
|
28
|
-
r.register(makeChannel('a', { value: false }));
|
|
29
|
-
expect(() => r.register(makeChannel('a', { value: false }))).toThrow();
|
|
30
|
-
});
|
|
31
|
-
|
|
32
|
-
it('startAll / stopAll', async () => {
|
|
33
|
-
const r = createChannelRegistry();
|
|
34
|
-
const f1 = { value: false };
|
|
35
|
-
const f2 = { value: false };
|
|
36
|
-
r.register(makeChannel('a', f1));
|
|
37
|
-
r.register(makeChannel('b', f2));
|
|
38
|
-
await r.startAll();
|
|
39
|
-
expect(f1.value).toBe(true);
|
|
40
|
-
expect(f2.value).toBe(true);
|
|
41
|
-
await r.stopAll();
|
|
42
|
-
expect(f1.value).toBe(false);
|
|
43
|
-
expect(f2.value).toBe(false);
|
|
44
|
-
});
|
|
45
|
-
|
|
46
|
-
it('unregister callback removes', () => {
|
|
47
|
-
const r = createChannelRegistry();
|
|
48
|
-
const off = r.register(makeChannel('a', { value: false }));
|
|
49
|
-
off();
|
|
50
|
-
expect(r.list()).toEqual([]);
|
|
51
|
-
});
|
|
52
|
-
});
|
package/src/channel.ts
DELETED
|
@@ -1,77 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Channel — input surface for sessions. A channel converts an external
|
|
3
|
-
* trigger (TUI keystroke, Telegram message, voice transcription, websocket
|
|
4
|
-
* frame) into an `InboundMessage` and forwards it to a `Session`.
|
|
5
|
-
*
|
|
6
|
-
* The abstraction is intentionally tiny: a channel knows how to start, stop,
|
|
7
|
-
* and (optionally) respond. The mu-core host owns lifecycle; channels are
|
|
8
|
-
* registered via `PluginContext.channels?.register(...)`.
|
|
9
|
-
*/
|
|
10
|
-
|
|
11
|
-
export type InboundKind = 'text' | 'audio';
|
|
12
|
-
export type ResponseMode = 'text' | 'voice';
|
|
13
|
-
|
|
14
|
-
export interface InboundMessage {
|
|
15
|
-
kind: InboundKind;
|
|
16
|
-
channelId: string;
|
|
17
|
-
sessionId: string;
|
|
18
|
-
messageId?: string;
|
|
19
|
-
userId?: string;
|
|
20
|
-
userName?: string;
|
|
21
|
-
text?: string;
|
|
22
|
-
responseMode?: ResponseMode;
|
|
23
|
-
audio?: { url?: string; mimeType?: string; filePath?: string };
|
|
24
|
-
raw?: unknown;
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
export interface ChannelResponder {
|
|
28
|
-
sendText: (text: string) => Promise<void>;
|
|
29
|
-
sendVoice?: (text: string) => Promise<void>;
|
|
30
|
-
sendAck?: (text: string) => Promise<void>;
|
|
31
|
-
sendError?: (text: string) => Promise<void>;
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
export interface Channel {
|
|
35
|
-
id: string;
|
|
36
|
-
start: () => Promise<void>;
|
|
37
|
-
stop?: () => Promise<void>;
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
export interface ChannelRegistry {
|
|
41
|
-
register: (channel: Channel) => () => void;
|
|
42
|
-
list: () => Channel[];
|
|
43
|
-
get: (id: string) => Channel | undefined;
|
|
44
|
-
startAll: () => Promise<void>;
|
|
45
|
-
stopAll: () => Promise<void>;
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
export function createChannelRegistry(): ChannelRegistry {
|
|
49
|
-
const channels = new Map<string, Channel>();
|
|
50
|
-
return {
|
|
51
|
-
register(channel) {
|
|
52
|
-
if (channels.has(channel.id)) {
|
|
53
|
-
throw new Error(`Channel already registered: ${channel.id}`);
|
|
54
|
-
}
|
|
55
|
-
channels.set(channel.id, channel);
|
|
56
|
-
return () => {
|
|
57
|
-
channels.delete(channel.id);
|
|
58
|
-
};
|
|
59
|
-
},
|
|
60
|
-
list() {
|
|
61
|
-
return Array.from(channels.values());
|
|
62
|
-
},
|
|
63
|
-
get(id) {
|
|
64
|
-
return channels.get(id);
|
|
65
|
-
},
|
|
66
|
-
async startAll() {
|
|
67
|
-
for (const c of channels.values()) {
|
|
68
|
-
await c.start();
|
|
69
|
-
}
|
|
70
|
-
},
|
|
71
|
-
async stopAll() {
|
|
72
|
-
for (const c of channels.values()) {
|
|
73
|
-
if (c.stop) await c.stop();
|
|
74
|
-
}
|
|
75
|
-
},
|
|
76
|
-
};
|
|
77
|
-
}
|
package/src/hooks.test.ts
DELETED
|
@@ -1,105 +0,0 @@
|
|
|
1
|
-
import { describe, expect, it } from 'bun:test';
|
|
2
|
-
import { runBeforeToolExecHook, runTransformUserInputHooks } from './hooks';
|
|
3
|
-
import type { LifecycleHooks } from './plugin';
|
|
4
|
-
|
|
5
|
-
const call = { id: '1', function: { name: 'foo', arguments: '{}' } };
|
|
6
|
-
|
|
7
|
-
describe('runBeforeToolExecHook', () => {
|
|
8
|
-
it('returns the call unchanged when no hook intervenes', async () => {
|
|
9
|
-
const result = await runBeforeToolExecHook([], call);
|
|
10
|
-
expect(result).toEqual(call);
|
|
11
|
-
});
|
|
12
|
-
|
|
13
|
-
it('lets later hooks transform the call', async () => {
|
|
14
|
-
const hooks: LifecycleHooks[] = [
|
|
15
|
-
{
|
|
16
|
-
beforeToolExec: (c) => ({ ...c, function: { ...c.function, name: 'bar' } }),
|
|
17
|
-
},
|
|
18
|
-
{
|
|
19
|
-
beforeToolExec: (c) =>
|
|
20
|
-
'blocked' in c ? c : { ...c, function: { ...c.function, name: c.function.name.toUpperCase() } },
|
|
21
|
-
},
|
|
22
|
-
];
|
|
23
|
-
const result = await runBeforeToolExecHook(hooks, call);
|
|
24
|
-
expect('blocked' in result).toBe(false);
|
|
25
|
-
if (!('blocked' in result)) {
|
|
26
|
-
expect(result.function.name).toBe('BAR');
|
|
27
|
-
}
|
|
28
|
-
});
|
|
29
|
-
|
|
30
|
-
it('short-circuits on first block', async () => {
|
|
31
|
-
let secondCalled = false;
|
|
32
|
-
const hooks: LifecycleHooks[] = [
|
|
33
|
-
{ beforeToolExec: () => ({ blocked: true, content: 'denied', error: true }) },
|
|
34
|
-
{
|
|
35
|
-
beforeToolExec: (c) => {
|
|
36
|
-
secondCalled = true;
|
|
37
|
-
return c;
|
|
38
|
-
},
|
|
39
|
-
},
|
|
40
|
-
];
|
|
41
|
-
const result = await runBeforeToolExecHook(hooks, call);
|
|
42
|
-
expect('blocked' in result && result.content).toBe('denied');
|
|
43
|
-
expect(secondCalled).toBe(false);
|
|
44
|
-
});
|
|
45
|
-
});
|
|
46
|
-
|
|
47
|
-
describe('runTransformUserInputHooks', () => {
|
|
48
|
-
it('returns pass when no hook intervenes', async () => {
|
|
49
|
-
expect(await runTransformUserInputHooks([], 'hello')).toEqual({ kind: 'pass' });
|
|
50
|
-
});
|
|
51
|
-
|
|
52
|
-
it('threads transformed text through subsequent hooks', async () => {
|
|
53
|
-
const hooks: LifecycleHooks[] = [
|
|
54
|
-
{ transformUserInput: (t) => ({ kind: 'transform', text: `[a]${t}` }) },
|
|
55
|
-
{ transformUserInput: (t) => ({ kind: 'transform', text: `${t}[b]` }) },
|
|
56
|
-
];
|
|
57
|
-
const result = await runTransformUserInputHooks(hooks, 'X');
|
|
58
|
-
expect(result.kind === 'transform' && result.text).toBe('[a]X[b]');
|
|
59
|
-
});
|
|
60
|
-
|
|
61
|
-
it('intercept short-circuits the chain', async () => {
|
|
62
|
-
let secondCalled = false;
|
|
63
|
-
const hooks: LifecycleHooks[] = [
|
|
64
|
-
{ transformUserInput: () => ({ kind: 'intercept' }) },
|
|
65
|
-
{
|
|
66
|
-
transformUserInput: () => {
|
|
67
|
-
secondCalled = true;
|
|
68
|
-
return { kind: 'pass' };
|
|
69
|
-
},
|
|
70
|
-
},
|
|
71
|
-
];
|
|
72
|
-
const result = await runTransformUserInputHooks(hooks, 'X');
|
|
73
|
-
expect(result.kind).toBe('intercept');
|
|
74
|
-
expect(secondCalled).toBe(false);
|
|
75
|
-
});
|
|
76
|
-
|
|
77
|
-
it('propagates continue to the caller', async () => {
|
|
78
|
-
// Regression: the composer used to silently drop `continue`, falling
|
|
79
|
-
// back to `pass`. That made the host re-push the user message on top
|
|
80
|
-
// of the one a plugin (mu-agents @-mention dispatch) had already
|
|
81
|
-
// appended, producing a duplicate user bubble in the transcript.
|
|
82
|
-
const hooks: LifecycleHooks[] = [{ transformUserInput: () => ({ kind: 'continue' }) }];
|
|
83
|
-
const result = await runTransformUserInputHooks(hooks, 'X');
|
|
84
|
-
expect(result.kind).toBe('continue');
|
|
85
|
-
});
|
|
86
|
-
|
|
87
|
-
it('continue short-circuits the chain', async () => {
|
|
88
|
-
// Once a plugin has appended the user message itself, downstream
|
|
89
|
-
// hooks can't safely transform absent text — same chain-termination
|
|
90
|
-
// semantics as `intercept`.
|
|
91
|
-
let secondCalled = false;
|
|
92
|
-
const hooks: LifecycleHooks[] = [
|
|
93
|
-
{ transformUserInput: () => ({ kind: 'continue' }) },
|
|
94
|
-
{
|
|
95
|
-
transformUserInput: () => {
|
|
96
|
-
secondCalled = true;
|
|
97
|
-
return { kind: 'transform', text: 'should-not-apply' };
|
|
98
|
-
},
|
|
99
|
-
},
|
|
100
|
-
];
|
|
101
|
-
const result = await runTransformUserInputHooks(hooks, 'X');
|
|
102
|
-
expect(result.kind).toBe('continue');
|
|
103
|
-
expect(secondCalled).toBe(false);
|
|
104
|
-
});
|
|
105
|
-
});
|