forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathomi-tools-stdio.ts
More file actions
515 lines (474 loc) · 16.6 KB
/
Copy pathomi-tools-stdio.ts
File metadata and controls
515 lines (474 loc) · 16.6 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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
/**
* Stdio-based MCP server for omi tools (execute_sql, semantic_search).
* This script is spawned as a subprocess by the ACP agent.
* It reads JSON-RPC requests from stdin and writes responses to stdout.
*
* Tool calls are forwarded to the parent agent process via a named pipe
* (passed as OMI_BRIDGE_PIPE env var), which then forwards them to Swift.
*/
import { createInterface } from "readline";
import { createConnection } from "net";
import { readFileSync, writeFileSync } from "fs";
import { isAgentControlToolName } from "./runtime/control-tools.js";
import { loadSkillInstructions, searchSkills } from "./runtime/node-tools.js";
import {
buildToolAvailabilitySnapshot,
mcpToolDefinitionsForAdapter,
normalizeOmiToolName,
toolManifestEntry,
toolsForAdapter,
} from "./runtime/omi-tool-manifest.js";
import { PROTOCOL_VERSION } from "./protocol.js";
// Current query mode
let currentMode: "ask" | "act" = process.env.OMI_QUERY_MODE === "ask" ? "ask" : "act";
// Connection to parent bridge for tool forwarding
const bridgePipePath = process.env.OMI_BRIDGE_PIPE;
// Pending tool calls — resolved when parent sends back results via pipe
const pendingToolCalls = new Map<
string,
{ resolve: (result: string) => void }
>();
let callIdCounter = 0;
function nextCallId(): string {
return `omi-${++callIdCounter}-${Date.now()}`;
}
function logErr(msg: string): void {
process.stderr.write(`[omi-tools-stdio] ${msg}\n`);
}
function activeRunCapability(): { capabilityRef?: string; contextError?: string } {
if (process.env.OMI_CONTEXT_FILE) {
try {
const parsed = JSON.parse(readFileSync(process.env.OMI_CONTEXT_FILE, "utf8"));
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
return typeof parsed.capabilityRef === "string" && parsed.capabilityRef.length > 0
? { capabilityRef: parsed.capabilityRef }
: { contextError: "OMI context file did not contain a capabilityRef" };
}
return {
contextError: "OMI context file did not contain an object",
};
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
logErr(`Failed to read OMI context file: ${message}`);
return {
contextError: message,
};
}
}
return { contextError: "OMI_CONTEXT_FILE is not configured" };
}
// --- Communication with parent bridge ---
let pipeConnection: ReturnType<typeof createConnection> | null = null;
let pipeBuffer = "";
function connectToPipe(): Promise<void> {
return new Promise((resolve, reject) => {
if (!bridgePipePath) {
logErr("No OMI_BRIDGE_PIPE set, tool calls will fail");
resolve();
return;
}
pipeConnection = createConnection(bridgePipePath, () => {
logErr(`Connected to bridge pipe: ${bridgePipePath}`);
resolve();
});
pipeConnection.on("data", (data: Buffer) => {
pipeBuffer += data.toString();
// Process complete lines
let newlineIdx;
while ((newlineIdx = pipeBuffer.indexOf("\n")) >= 0) {
const line = pipeBuffer.slice(0, newlineIdx);
pipeBuffer = pipeBuffer.slice(newlineIdx + 1);
if (line.trim()) {
try {
const msg = JSON.parse(line) as {
type: string;
callId: string;
result: string;
};
if (msg.type === "tool_result" && msg.callId) {
const pending = pendingToolCalls.get(msg.callId);
if (pending) {
pending.resolve(msg.result);
pendingToolCalls.delete(msg.callId);
}
}
} catch {
logErr(`Failed to parse pipe message: ${line.slice(0, 200)}`);
}
}
}
});
pipeConnection.on("error", (err) => {
logErr(`Pipe error: ${err.message}`);
reject(err);
});
});
}
async function requestSwiftTool(
name: string,
input: Record<string, unknown>
): Promise<string> {
const callId = nextCallId();
if (!pipeConnection) {
return "Error: not connected to bridge";
}
const capability = activeRunCapability();
if (capability.contextError || !capability.capabilityRef) {
return `Error: missing active Omi run capability for tool relay${capability.contextError ? `: ${capability.contextError}` : ""}`;
}
return new Promise<string>((resolve) => {
pendingToolCalls.set(callId, { resolve });
const msg = JSON.stringify({
type: "tool_use",
callId,
invocationId: callId,
name,
input,
protocolVersion: PROTOCOL_VERSION,
capabilityRef: capability.capabilityRef,
});
pipeConnection!.write(msg + "\n");
});
}
// --- MCP tool definitions ---
const isOnboarding = process.env.OMI_ONBOARDING === "true";
const hasScreenContext = process.env.OMI_SCREEN_CONTEXT === "true";
const hasJitKnowledgeTools = process.env.OMI_JIT_KNOWLEDGE_TOOLS_ENABLED === "true";
const hasJitProactivity = process.env.OMI_JIT_PROACTIVITY_MODE === "true";
const executionRole = process.env.OMI_EXECUTION_ROLE === "leaf" ? "leaf" : "coordinator";
const chatFirstUi = process.env.OMI_CHAT_FIRST_UI === "true" && process.env.OMI_SURFACE_KIND === "main_chat";
const controlGeneration = Number(process.env.OMI_CHAT_FIRST_CONTROL_GENERATION);
const projectionContext = {
onboarding: isOnboarding,
screenContext: hasScreenContext,
jitKnowledgeToolsEnabled: hasJitKnowledgeTools,
jitProactivity: hasJitProactivity,
executionRole,
surfaceKind: process.env.OMI_SURFACE_KIND,
chatFirstUi,
controlGeneration: Number.isSafeInteger(controlGeneration) && controlGeneration >= 0 ? controlGeneration : null,
} as const;
// Tool order is owned by the canonical manifest projection.
const ADVERTISED_TOOLS = toolsForAdapter("omi-tools-stdio", projectionContext);
const ADVERTISED_CANONICAL_TOOL_NAMES = new Set(ADVERTISED_TOOLS.map((tool) => tool.name));
// Filter tools based on session type: onboarding sessions get onboarding tools,
// regular sessions exclude them
const TOOLS = mcpToolDefinitionsForAdapter("omi-tools-stdio", projectionContext);
// --- JSON-RPC handling ---
function send(msg: Record<string, unknown>): void {
try {
process.stdout.write(JSON.stringify(msg) + "\n");
} catch (err) {
logErr(`Failed to write to stdout: ${err}`);
}
}
async function handleJsonRpc(
body: Record<string, unknown>
): Promise<void> {
const id = body.id;
const method = body.method as string;
const params = (body.params ?? {}) as Record<string, unknown>;
// Notifications (no id) don't get responses
const isNotification = id === undefined || id === null;
switch (method) {
case "initialize":
if (!isNotification) {
send({
jsonrpc: "2.0",
id,
result: {
protocolVersion: "2024-11-05",
capabilities: { tools: {} },
serverInfo: { name: "omi-tools", version: "1.0.0" },
},
});
}
break;
case "notifications/initialized":
// No response needed
break;
case "tools/list":
if (!isNotification) {
send({
jsonrpc: "2.0",
id,
result: { tools: TOOLS },
});
}
break;
case "tools/call": {
const normalizedTool = normalizeOmiToolName("omi-tools-stdio", params.name as string);
const toolName = normalizedTool.canonicalName;
const args = (params.arguments ?? {}) as Record<string, unknown>;
if (!ADVERTISED_CANONICAL_TOOL_NAMES.has(toolName)) {
if (!isNotification) {
send({
jsonrpc: "2.0",
id,
error: { code: -32601, message: `Unknown tool: ${params.name as string}` },
});
}
return;
}
if (toolName === "execute_sql") {
const query = args.query as string;
if (currentMode === "ask") {
const normalized = query.trim().toUpperCase();
if (!normalized.startsWith("SELECT")) {
if (!isNotification) {
send({
jsonrpc: "2.0",
id,
result: {
content: [
{
type: "text",
text: "Blocked: Only SELECT queries are allowed in Ask mode.",
},
],
},
});
}
return;
}
}
const input: Record<string, unknown> = { query };
if (args.parameters !== undefined) input.parameters = args.parameters;
const result = await requestSwiftTool("execute_sql", input);
if (!isNotification) {
send({
jsonrpc: "2.0",
id,
result: { content: [{ type: "text", text: result }] },
});
}
} else if (toolName === "semantic_search") {
const input: Record<string, unknown> = {
query: args.query,
days: args.days ?? 7,
};
if (args.app_filter) input.app_filter = args.app_filter;
const result = await requestSwiftTool("semantic_search", input);
if (!isNotification) {
send({
jsonrpc: "2.0",
id,
result: { content: [{ type: "text", text: result }] },
});
}
} else if (toolName === "get_daily_recap") {
const daysAgo = (args.days_ago as number) ?? 1;
const result = await requestSwiftTool("get_daily_recap", { days_ago: daysAgo });
if (!isNotification) {
send({
jsonrpc: "2.0",
id,
result: { content: [{ type: "text", text: result }] },
});
}
} else if (toolName === "search_tasks") {
const input: Record<string, unknown> = { query: args.query };
if (args.include_completed) input.include_completed = args.include_completed;
const result = await requestSwiftTool("search_tasks", input);
if (!isNotification) {
send({
jsonrpc: "2.0",
id,
result: { content: [{ type: "text", text: result }] },
});
}
} else if (toolName === "complete_task") {
const taskId = args.task_id as string;
const result = await requestSwiftTool("complete_task", { task_id: taskId });
if (!isNotification) {
send({
jsonrpc: "2.0",
id,
result: { content: [{ type: "text", text: result }] },
});
}
} else if (toolName === "delete_task") {
const taskId = args.task_id as string;
const result = await requestSwiftTool("delete_task", { task_id: taskId });
if (!isNotification) {
send({
jsonrpc: "2.0",
id,
result: { content: [{ type: "text", text: result }] },
});
}
} else if (toolName === "load_skill") {
const name = (args.name as string || "").trim();
const rawPart = args.part;
const part = rawPart === "all" ? "all" as const : typeof rawPart === "number" ? rawPart : undefined;
const content = await loadSkillInstructions(
name,
process.env.OMI_WORKSPACE ?? "",
part === undefined ? {} : { part }
);
if (!isNotification) {
send({
jsonrpc: "2.0",
id,
result: {
content: [{
type: "text",
text: content,
}],
},
});
}
} else if (toolName === "search_skills") {
const query = (args.query as string || "").trim();
const content = await searchSkills(query);
if (!isNotification) {
send({
jsonrpc: "2.0",
id,
result: {
content: [{
type: "text",
text: content,
}],
},
});
}
} else if (toolName === "search_chat_history") {
// This remains a relay request, not a child-process SQLite read. The
// parent kernel rechecks the run capability then scopes the search to
// the caller's current main-Chat journal generation.
const result = await requestSwiftTool(toolName, args);
if (!isNotification) {
send({
jsonrpc: "2.0",
id,
result: { content: [{ type: "text", text: result }] },
});
}
} else if (
toolName === "read_conversation_evidence" ||
toolName === "search_conversation_evidence"
) {
// Evidence stays in the parent kernel. The child process only relays
// the request so the kernel can recheck capability, owner, and the
// exact conversation binding before reading journal metadata.
const result = await requestSwiftTool(toolName, args);
if (!isNotification) {
send({
jsonrpc: "2.0",
id,
result: { content: [{ type: "text", text: result }] },
});
}
} else if (isAgentControlToolName(toolName)) {
// Runtime control tools are handled by the Node parent/kernel. They
// still travel over the relay so MCP clients use the same tool path.
const result = await requestSwiftTool(toolName, args);
if (!isNotification) {
send({
jsonrpc: "2.0",
id,
result: { content: [{ type: "text", text: result }] },
});
}
} else if (
toolName === "check_permission_status" ||
toolName === "request_permission" ||
toolName === "scan_files" ||
toolName === "set_user_preferences" ||
toolName === "ask_followup" ||
toolName === "complete_onboarding" ||
toolName === "save_knowledge_graph"
) {
// Onboarding tools — forward directly to Swift
const result = await requestSwiftTool(toolName, args);
if (!isNotification) {
send({
jsonrpc: "2.0",
id,
result: { content: [{ type: "text", text: result }] },
});
}
} else if (
toolName === "get_conversations" ||
toolName === "search_conversations" ||
toolName === "get_memories" ||
toolName === "search_memories" ||
toolName === "get_action_items" ||
toolName === "create_action_item" ||
toolName === "update_action_item"
) {
// Backend RAG tools — forward to Swift which calls Python backend
const result = await requestSwiftTool(toolName, args);
if (!isNotification) {
send({
jsonrpc: "2.0",
id,
result: { content: [{ type: "text", text: result }] },
});
}
} else if (toolManifestEntry(toolName)?.executor.kind === "swiftTool") {
const entry = toolManifestEntry(toolName)!;
const result = await requestSwiftTool(entry.executor.executorName ?? entry.name, args);
if (!isNotification) {
send({
jsonrpc: "2.0",
id,
result: { content: [{ type: "text", text: result }] },
});
}
} else if (!isNotification) {
send({
jsonrpc: "2.0",
id,
error: { code: -32601, message: `Unknown tool: ${toolName}` },
});
}
break;
}
default:
if (!isNotification) {
send({
jsonrpc: "2.0",
id,
error: { code: -32601, message: `Method not found: ${method}` },
});
}
}
}
// --- Main ---
async function main(): Promise<void> {
// Connect to parent bridge pipe for tool forwarding
await connectToPipe();
// Read JSON-RPC from stdin
const rl = createInterface({ input: process.stdin, terminal: false });
rl.on("line", (line: string) => {
if (!line.trim()) return;
try {
const msg = JSON.parse(line) as Record<string, unknown>;
handleJsonRpc(msg).catch((err) => {
logErr(`Error handling request: ${err}`);
});
} catch {
logErr(`Invalid JSON: ${line.slice(0, 200)}`);
}
});
rl.on("close", () => {
process.exit(0);
});
const snapshot = buildToolAvailabilitySnapshot("omi-tools-stdio", projectionContext);
if (process.env.OMI_TOOL_AVAILABILITY_SNAPSHOT_PATH) {
try {
writeFileSync(process.env.OMI_TOOL_AVAILABILITY_SNAPSHOT_PATH, `${JSON.stringify(snapshot, null, 2)}\n`);
} catch (err) {
logErr(`Failed to write tool availability snapshot: ${err instanceof Error ? err.message : err}`);
}
}
logErr(
`omi-tools stdio MCP server started adapter=omi-tools-stdio advertisedToolCount=${snapshot.advertisedToolCount} advertisedTools=${snapshot.advertisedToolNames.join(",")}`,
);
}
main().catch((err) => {
logErr(`Fatal: ${err}`);
process.exit(1);
});