-
-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathindex.js
More file actions
319 lines (293 loc) · 9.06 KB
/
Copy pathindex.js
File metadata and controls
319 lines (293 loc) · 9.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
// Runtime — wires LLM + tool dispatch + speech + memory into a single agent brain.
// Replaces the pattern-matched chatbot stub in nich-agent.js.
import { createProvider } from './providers.js';
import { createTTS, createSTT } from './speech.js';
import { BUILTIN_TOOLS, BUILTIN_HANDLERS, STAGE_TOOLS } from './tools.js';
import { protocol } from '../agent-protocol.js';
import { PaymentRequiredError, alwaysAllow } from './skill-access.js';
export { PaymentRequiredError, alwaysAllow } from './skill-access.js';
export {
fromAgentDetail as skillAccessFromAgentDetail,
remoteCheck as skillAccessRemote,
autoBuying as skillAccessAutoBuying,
} from './skill-access.js';
const MAX_TOOL_ITERATIONS = 8;
export class Runtime extends EventTarget {
constructor({
manifest,
viewer,
memory,
skills,
providerConfig = {},
voiceConfig = {},
stage = null,
agentId = null,
skillAccess = null,
} = {}) {
super();
this.manifest = manifest || {};
this.viewer = viewer;
this.memory = memory;
this.skills = skills;
this.stage = stage;
this.agentId = agentId;
this.skillAccess = skillAccess || alwaysAllow();
this.provider = createProvider({
...this.manifest.brain,
...providerConfig,
});
this.tts = createTTS({ ...this.manifest.voice?.tts, ...voiceConfig.tts });
this.stt = createSTT({ ...this.manifest.voice?.stt, ...voiceConfig.stt });
this.messages = [];
this._busy = false;
}
get systemPrompt() {
const parts = [];
if (this.manifest.instructions) parts.push(this.manifest.instructions);
if (this.memory) {
parts.push(
'\n\n<memory>\n' +
this.memory.contextBlock({
maxTokens: this.manifest.memory?.maxTokens || 8192,
}) +
'\n</memory>',
);
}
if (this.skills) parts.push(this.skills.systemPrompt());
return parts.join('');
}
get tools() {
const builtinNames = new Set(this.manifest.tools || BUILTIN_TOOLS.map((t) => t.name));
const builtins = BUILTIN_TOOLS.filter((t) => builtinNames.has(t.name));
const skillTools = this.skills ? this.skills.allTools() : [];
const stageTools = this.stage ? STAGE_TOOLS : [];
return [...builtins, ...stageTools, ...skillTools];
}
/**
* Abort the current in-flight LLM request, if any.
* Resolves the pending `send()` call immediately.
*/
cancel() {
this._abortController?.abort();
}
async send(userText, { voice = false } = {}) {
if (this._busy) {
throw new Error('Runtime busy — wait for current turn to finish');
}
this._busy = true;
this._abortController = new AbortController();
try {
this.memory?.note('user_said', { text: userText });
this.messages.push({ role: 'user', content: userText });
this.dispatchEvent(
new CustomEvent('brain:message', {
detail: { role: 'user', content: userText },
}),
);
const reply = await this._loop(this._abortController.signal);
if (voice && reply.text && this.tts) {
this.dispatchEvent(
new CustomEvent('voice:speech-start', { detail: { text: reply.text } }),
);
await this.tts.speak(reply.text, { scene: this.viewer?.content });
this.dispatchEvent(new CustomEvent('voice:speech-end', {}));
}
return reply;
} finally {
this._busy = false;
this._abortController = null;
}
}
async _loop(signal) {
let iter = 0;
let finalText = '';
while (iter++ < MAX_TOOL_ITERATIONS) {
this.dispatchEvent(new CustomEvent('brain:thinking', { detail: { thinking: true } }));
const response = await this.provider.complete({
system: this.systemPrompt,
messages: this.messages,
tools: this.tools,
signal,
onChunk: (chunk) => {
if (signal?.aborted) return;
this.dispatchEvent(new CustomEvent('brain:stream', { detail: { chunk } }));
},
});
this.dispatchEvent(
new CustomEvent('brain:thinking', {
detail: { thinking: false, content: response.thinking || '' },
}),
);
if (!response.toolCalls.length) {
finalText = response.text;
this.messages.push({ role: 'assistant', content: response.text });
this.dispatchEvent(
new CustomEvent('brain:message', {
detail: { role: 'assistant', content: response.text },
}),
);
break;
}
// Record assistant turn with tool calls
this.messages.push(
this.provider.formatAssistantWithToolCalls(response.text, response.toolCalls),
);
if (response.text) {
this.dispatchEvent(
new CustomEvent('brain:message', {
detail: { role: 'assistant', content: response.text },
}),
);
}
// Dispatch each tool call
const results = [];
for (const call of response.toolCalls) {
this.dispatchEvent(
new CustomEvent('skill:tool-start', {
detail: { tool: call.name, args: call.input },
}),
);
let output,
isError = false;
try {
output = await this._dispatchTool(call);
} catch (err) {
if (err instanceof PaymentRequiredError) {
// Surface payment requirements as a structured event so the host
// page can pop the purchase modal. Feed a 402-style result back
// to the LLM so it can react gracefully (or, for autonomous
// agents, trigger its own purchase via skillAccess.autoPay).
this.dispatchEvent(
new CustomEvent('skill:payment-required', { detail: err.payload }),
);
output = {
error: 'payment_required',
skill: err.payload.skill,
price: err.payload.price,
message:
err.payload.message ||
`Skill '${err.payload.skill}' requires a purchase before it can be used.`,
};
} else {
output = { error: err.message || String(err) };
}
isError = true;
}
this.dispatchEvent(
new CustomEvent('skill:tool-called', {
detail: { tool: call.name, args: call.input, result: output },
}),
);
results.push({ id: call.id, output, isError });
}
const hasImage = results.some((r) => r.output?.imageData);
if (hasImage) {
const content = results.map((r) => {
const block = {
type: 'tool_result',
tool_use_id: r.id,
is_error: !!r.isError,
};
if (r.output?.imageData) {
const b64 = r.output.imageData.replace(/^data:[^;]+;base64,/, '');
block.content = [
{ type: 'text', text: r.output.description || 'Screen captured.' },
{
type: 'image',
source: { type: 'base64', media_type: 'image/jpeg', data: b64 },
},
];
} else {
block.content =
typeof r.output === 'string' ? r.output : JSON.stringify(r.output);
}
return block;
});
this.messages.push({ role: 'user', content });
} else {
this.messages.push(this.provider.formatToolResults(results));
}
}
return { text: finalText };
}
async _dispatchTool(call) {
const ctx = this._context();
// Skill-provided tools first (they can shadow built-ins intentionally)
const skill = this.skills?.findSkillForTool(call.name);
if (skill) {
// Paid-skill gate: ask the access checker before invoking. Built-in
// and stage tools never go through the gate — only skill-provided ones.
const access = await this.skillAccess(call.name);
if (!access?.allowed) {
throw new PaymentRequiredError({ skill: call.name, ...access });
}
return skill.invoke(call.name, call.input, ctx);
}
// Built-in
const handler = BUILTIN_HANDLERS[call.name];
if (!handler) throw new Error(`Unknown tool: ${call.name}`);
return handler(call.input, ctx);
}
_context() {
const skills = this.skills;
return {
viewer: this.viewer,
memory: this.memory,
llm: {
complete: (prompt, opts) =>
this.provider.complete({
system: opts?.system || '',
messages: [{ role: 'user', content: prompt }],
tools: opts?.tools,
}),
},
speak: async (text) => {
if (!this.tts) return;
this.dispatchEvent(new CustomEvent('voice:speech-start', { detail: { text } }));
await this.tts.speak(text, { scene: this.viewer?.content });
this.dispatchEvent(new CustomEvent('voice:speech-end', {}));
},
listen: (opts) => this.stt?.listen(opts),
fetch: (url, opts) => fetch(url, opts),
loadGLB: async (uri) => {
// Delegates to viewer's loader. Actual wiring in element.js binds this.
return this.viewer.loadGLB?.(uri);
},
loadClip: async (uri) => this.viewer.loadClip?.(uri),
loadJSON: async (uri) => (await fetch(uri)).json(),
call: async (toolName, args) => this._dispatchTool({ name: toolName, input: args }),
stage: this.stage,
agentId: this.agentId,
};
}
async listen({ onInterim, onFinal } = {}) {
if (!this.stt) throw new Error('STT not configured');
this.dispatchEvent(new CustomEvent('voice:listen-start', {}));
const text = await this.stt.listen({
onInterim: (t) => {
this.dispatchEvent(
new CustomEvent('voice:transcript', { detail: { text: t, final: false } }),
);
onInterim?.(t);
},
onFinal: (t) => {
this.dispatchEvent(
new CustomEvent('voice:transcript', { detail: { text: t, final: true } }),
);
onFinal?.(t);
},
});
return text;
}
clearConversation() {
this.messages = [];
}
pause() {
this.tts?.cancel(protocol);
this.stt?.stop();
}
destroy() {
this.pause();
this.messages = [];
}
}