forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
4087 lines (3939 loc) · 162 KB
/
Copy pathindex.ts
File metadata and controls
4087 lines (3939 loc) · 162 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
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* ACP Bridge — translates between OMI's JSON-lines protocol and the
* Agent Client Protocol (ACP) used by claude-code-acp.
*
* THIS IS THE DESKTOP APP FLOW. It is unrelated to the VM agent flow, which
* runs the Claude Agent SDK on a remote VM for
* the Omi Agent feature. This bridge runs locally on the user's Mac.
*
* Session lifecycle:
* 1. resolve_surface_session pins an immutable kernel-owned execution profile.
* 2. warmup validates that session/profile generation without configuring it.
* 3. query names only the session and user input; the kernel supplies provider,
* model, working directory, system policy, and the admitted context snapshot.
*
* Token counts:
* session/prompt drives one or more internal Anthropic API calls (initial
* response + one per tool-use round). The usage returned in the result is
* the AGGREGATE across all those rounds. There are no separate sub-agents.
*
* Implementation flow:
* 1. Create Unix socket server for omi-tools relay
* 2. Spawn claude-code-acp as subprocess (JSON-RPC over stdio)
* 3. Initialize ACP connection
* 4. Handle auth if required (forward to Swift; never await OAuth inside a query/run)
* 5. On query: reuse or create session, send prompt, translate notifications → JSON-lines
* 6. On interrupt: cancel the session
*/
import { createInterface } from "readline";
import packageMetadata from "../package.json" with { type: "json" };
import { dirname, join } from "path";
import { fileURLToPath } from "url";
import { createServer as createNetServer, type Socket } from "net";
import { homedir, tmpdir } from "os";
import { unlinkSync, appendFileSync } from "fs";
import type {
InboundMessage,
ControlToolRequestMessage,
DirectControlToolRequestMessage,
ExternalSurfaceRunBeginMessage,
ExternalSurfaceToolInvokeMessage,
ExternalSurfaceRunCompleteMessage,
OutboundMessage,
OutboundMessageDraft,
QueryMessage,
WarmupMessage,
AuthorizedToolExecutionResultMessage,
ConfigureDefaultExecutionProfileMessage,
ResolveSurfaceSessionMessage,
MigrateSessionExecutionProfileMessage,
ContextSourceUpdateMessage,
ImportLegacyMainChatSessionsMessage,
InvalidateSessionMessage,
JournalRecordTurnMessage,
JournalRecordExchangeMessage,
JournalImportRemoteTurnMessage,
JournalUpdateTurnMessage,
JournalTerminalizeTurnMessage,
JournalRepairTurnsMessage,
JournalListTurnsMessage,
JournalClearTurnsMessage,
AppendChatFirstBlocksMessage,
AppendChatFirstEvidenceMessage,
RecordQuestionInteractionReplyMessage,
MaterializeChatFirstIntentsMessage,
ListChatFirstMaterializationReceiptsMessage,
AcknowledgeChatFirstMaterializationReceiptsMessage,
EnsureAgentSpawnJournalMessage,
JournalBackendSyncResultMessage,
JournalBackendDeleteResultMessage,
JournalBackendReconcileResultMessage,
ChatFirstDeferralDeliveryResultMessage,
ChatFirstHarnessExecutorBeginMessage,
RefreshOwnerMessage,
RevokeOwnerRuntimeMessage,
RefreshTokenMessage,
AuthMethod,
} from "./protocol.js";
import {
PROTOCOL_VERSION,
RUNTIME_CAPABILITIES,
assertJournalRemoteTurnInput,
assertPublicJournalRecordAuthority,
assertPublicJournalUpdateAuthority,
ensureOutboundProtocolVersion,
isInboundResponseMessage,
journalTerminalizationDisposition,
} from "./protocol.js";
import { startOAuthFlow, type OAuthFlowHandle } from "./oauth-flow.js";
import { isProductionAdapterId, type PromptBlock, type RuntimeAdapter } from "./adapters/interface.js";
import { detectImageMimeType } from "./mime-detect.js";
import {
AcpError,
AcpRuntimeAdapter,
beginProviderAuthWithoutBlocking,
isAcpProviderAuthFailure,
} from "./adapters/acp.js";
import { AdapterRegistry } from "./runtime/adapter-registry.js";
import { backendOutboxRetryAtMs } from "./runtime/durable-queue.js";
import { nextJournalPumpDelayMs } from "./runtime/journal-pump-backoff.js";
import { pumpJournalOutboxDeliveries } from "./runtime/journal-outbox-pump.js";
import { JsonlTransport, type McpServerBuildContext } from "./runtime/jsonl-transport.js";
import { AgentRuntimeKernel } from "./runtime/kernel.js";
import {
adapterActivationError,
adapterIdForHarnessMode,
ensureRegisteredAdapter,
} from "./runtime/adapter-selection.js";
import {
SWIFT_ADVERTISED_AGENT_CONTROL_TOOL_NAMES,
handleAgentControlToolCall,
isAgentControlToolName,
DEFAULT_LOCAL_OWNER_ID,
type AgentControlToolContext,
} from "./runtime/control-tools.js";
import { SqliteAgentStore } from "./runtime/sqlite-store.js";
import { OmiArtifactStorage, defaultArtifactRoot } from "./runtime/artifact-storage.js";
import { configuredPiMonoMaxWorkers } from "./runtime/worker-pool.js";
import {
failureFromError,
sanitizeProcessDiagnostic,
unexpectedQueryErrorDiagnostic,
} from "./runtime/failures.js";
import { providerBoundaryForAdapter } from "./runtime/execution-policy.js";
import { executionRoleForSurface } from "./runtime/execution-policy.js";
import type { AuthorizedRunToolInvocation, RunToolExecutionLease } from "./runtime/run-tool-capability.js";
import {
compactRealtimeSpawnToolResult,
parseAgentSpawnProducerJournalDescriptor,
} from "./runtime/agent-spawn-journal.js";
import {
finalizeRelayToolResult,
finalizedToolResultOutcome,
type RelayToolResultIdentity,
} from "./runtime/relay-tool-result.js";
import { LEGACY_MAIN_CHAT_SESSION_COMPATIBILITY } from "./runtime/surface-session.js";
import {
ackBackendConversationDeleteOutbox,
ackBackendTurnOutboxWithWakes,
appendChatFirstBlocksToProducingTurn,
appendChatFirstEvidenceToProducingTurn,
applyBackendReconcilePage,
beginBackendReconcilesForOwner,
clearJournalConversation,
chatFirstMaterializationDeferrals,
classifyBackendTurnResultDisposition,
failBackendConversationDeleteOutbox,
failBackendReconcile,
failBackendTurnOutbox,
journalTurnForSurfaceProjection,
journalTurnChangedWakes,
importRemoteJournalTurn,
listJournalTurns,
listChatFirstMaterializationReceipts,
acknowledgeChatFirstMaterializationReceipts,
materializeChatFirstIntents,
recordJournalExchange,
recordQuestionInteractionReply,
recordJournalTurn,
repairOrphanedJournalTurns,
settleClearedBackendTurnClaim,
assertPublicJournalUpdatePolicy,
terminalizeJournalTurn,
settleChatFirstDeferralOutbox,
updateJournalTurn,
} from "./runtime/conversation-journal.js";
import { DirectControlExecutionBroker } from "./runtime/direct-control-execution.js";
import {
authorizeRuntimeTokenRefresh,
establishRuntimeOwner,
requireActiveRuntimeOwner,
runRuntimeOwnerRevocationBarrier,
runtimeOwnerForEffects,
} from "./runtime/runtime-owner-authority.js";
import type {
ConversationContentBlock,
AgentEvent,
ConversationResource,
ConversationTurn,
ConversationTurnOrigin,
ConversationTurnStatus,
} from "./runtime/types.js";
import {
conversationEvidenceRelayDiagnostic,
type ConversationEvidence,
} from "./runtime/conversation-evidence.js";
import { createStdoutLineSender } from "./stdout-line-sender.js";
import { loadLocalMcpConfig, type UserMcpServer } from "./runtime/user-extensions.js";
const __dirname = dirname(fileURLToPath(import.meta.url));
// Resolve paths to bundled tools
const playwrightCli = join(
__dirname,
"..",
"node_modules",
"@playwright",
"mcp",
"cli.js"
);
const omiToolsStdioScript = join(__dirname, "omi-tools-stdio.js");
// --- Helpers ---
function logErr(msg: string): void {
// Wrap to swallow EPIPE/ERR_STREAM_DESTROYED so a closed parent pipe
// doesn't bubble out as an uncaughtException and re-enter our handlers.
try {
process.stderr.write(`[agent] ${msg}\n`);
} catch {
// ignore — parent pipe is gone; we'll exit shortly anyway
}
}
// Queue stdout lines so a full parent pipe waits on `drain` instead of
// blocking the event loop inside kernel subscribers / query completion.
const writeStdoutLine = createStdoutLineSender(
(chunk) => process.stdout.write(chunk),
(listener) => {
process.stdout.once("drain", listener);
},
(err) => {
logErr(`Failed to write to stdout: ${err}`);
}
);
function send(msg: OutboundMessageDraft): void {
writeStdoutLine(JSON.stringify(ensureOutboundProtocolVersion(msg)) + "\n");
}
function runtimeErrorEnvelope(error: unknown): { message: string; failure: ReturnType<typeof failureFromError> } {
const message = sanitizeProcessDiagnostic(error instanceof Error ? error.message : String(error))
|| "Runtime request rejected";
const failure = {
code: "runtime_error",
source: "runtime" as const,
retryable: false,
userMessage: message,
};
return { message: failure.userMessage, failure };
}
function agentStateDir(): string {
return process.env.OMI_AGENT_STATE_DIR ?? join(homedir(), "Library", "Application Support", "Omi", "agent");
}
function agentArtifactsDir(): string {
return defaultArtifactRoot(process.env);
}
// --- OMI tools relay via Unix socket ---
let omiToolsPipePath = "";
let omiToolsClients: Socket[] = [];
let agentControlToolContext: AgentControlToolContext | undefined;
let runtimeKernel: AgentRuntimeKernel | undefined;
let currentOwnerId = DEFAULT_LOCAL_OWNER_ID;
let ownerAuthorityEstablished = false;
interface OwnerRuntimeRevocationReceipt {
ownerId: string;
revokedRunIds: string[];
invalidatedBindingIds: string[];
}
let lastOwnerRuntimeRevocation: OwnerRuntimeRevocationReceipt | null = null;
const establishedOwnerId = () => runtimeOwnerForEffects({
ownerId: currentOwnerId,
established: ownerAuthorityEstablished,
});
const directControlExecutions = new DirectControlExecutionBroker({
activeOwnerId: establishedOwnerId,
});
const capabilityRejectionCounts = new Map<string, number>();
function resolveActiveOwner(requestedOwnerId: string | undefined): string {
return requireActiveRuntimeOwner(
{ ownerId: currentOwnerId, established: ownerAuthorityEstablished },
requestedOwnerId,
);
}
function journalOrigin(raw: unknown): ConversationTurnOrigin {
switch (raw) {
case "typed_chat":
case "floating_chat":
case "realtime_voice":
case "agent_runtime":
case "notification":
case "tool_runtime":
case "task_chat":
case "workstream":
case "swift_backfill":
case "legacy":
return raw;
case "proactive_notification":
return "notification";
case "floating_spawn":
return "agent_runtime";
case "floating_provider_unavailable":
case "floating_invalid_brief":
return "floating_chat";
default:
throw new Error("Unknown journal turn origin");
}
}
// Pending Swift execution is keyed only by the canonical run capability tuple.
const pendingToolCalls = new Map<
string,
{
client: Socket;
callId: string;
invocation: AuthorizedRunToolInvocation;
timeout: ReturnType<typeof setTimeout>;
}
>();
const pendingExternalToolCalls = new Map<
string,
{
request: ExternalSurfaceToolInvokeMessage;
invocation: AuthorizedRunToolInvocation;
timeout: ReturnType<typeof setTimeout>;
}
>();
/**
* This exists solely for the local/offline desktop E2E fixture. Unlike the
* external-surface bridge, it cannot accept a user/model-selected tool or
* capability: the kernel derives the one permitted capability from an
* already-mounted Main Chat session.
*/
const pendingChatFirstHarnessExecutors = new Map<
string,
{
requestId: string;
clientId: string;
invocation: AuthorizedRunToolInvocation;
timeout: ReturnType<typeof setTimeout>;
}
>();
const CHAT_FIRST_HARNESS_TASK_ID = "chat-first-e2e-task-v1";
function isLocalChatFirstExecutorHarnessEnabled(): boolean {
return (process.env.OMI_ENV_STAGE === "local" || process.env.OMI_ENV_STAGE === "offline")
&& process.env.OMI_AGENT_ALLOW_CONTROL_ONLY === "1";
}
function isBoundedChatFirstHarnessInput(input: unknown): input is Record<string, unknown> {
if (!input || typeof input !== "object" || Array.isArray(input)) return false;
const outer = input as Record<string, unknown>;
if (Object.keys(outer).length !== 1 || !Array.isArray(outer.blocks) || outer.blocks.length !== 1) return false;
const block = outer.blocks[0];
if (!block || typeof block !== "object" || Array.isArray(block)) return false;
const taskCard = block as Record<string, unknown>;
return Object.keys(taskCard).length === 2
&& taskCard.type === "taskCard"
&& taskCard.taskId === CHAT_FIRST_HARNESS_TASK_ID;
}
const TERMINAL_RUN_TOOL_EVENTS = new Set([
"run.succeeded",
"run.failed",
"run.cancelled",
"run.timed_out",
"run.orphaned",
"attempt.succeeded",
"attempt.failed",
"attempt.cancelled",
"attempt.timed_out",
"attempt.orphaned",
]);
function toolCallPendingKey(input: {
invocationId: string;
}): string {
return input.invocationId;
}
function relayResultIdentity(
callId: string,
invocation?: AuthorizedRunToolInvocation,
): RelayToolResultIdentity {
if (invocation) {
return {
invocationId: invocation.invocationId,
ownerId: invocation.ownerId,
sessionId: invocation.sessionId,
runId: invocation.runId,
attemptId: invocation.attemptId,
toolName: invocation.canonicalToolName,
surfaceKind: invocation.surfaceKind,
purpose: invocation.originatingUserText,
};
}
// Capability rejection occurs before a kernel-owned invocation exists. It
// still receives a canonical envelope, but cannot claim a fabricated run.
return {
invocationId: `relay:${callId}`,
ownerId: currentOwnerId,
sessionId: "unknown",
runId: "unknown",
attemptId: "unknown",
toolName: "unknown_relay_tool",
};
}
function finalizeRelayResult(
callId: string,
result: string,
invocation?: AuthorizedRunToolInvocation,
outcome?: "succeeded" | "failed",
): string {
return finalizeRelayToolResult({
identity: relayResultIdentity(callId, invocation),
result,
outcome,
kernel: runtimeKernel,
artifactRoot: agentArtifactsDir(),
onDegraded: (record) => {
// Projecting a large-but-successful result down to its model budget is
// the intended path here, not an error. logErr keeps the write pipe-safe
// (a destroyed stderr during shutdown must not throw) and off the
// error-level stream.
logErr(`fallback area=tool_result_projection outcome=degraded ${JSON.stringify(record)}`);
},
});
}
/** Resolve a pending tool call with a result from Swift */
function resolveToolCall(msg: AuthorizedToolExecutionResultMessage): void {
const key = toolCallPendingKey(msg);
const chatFirstHarness = pendingChatFirstHarnessExecutors.get(key);
if (chatFirstHarness) {
pendingChatFirstHarnessExecutors.delete(key);
clearTimeout(chatFirstHarness.timeout);
const invocation = chatFirstHarness.invocation;
const identityMatches = msg.ownerId === invocation.ownerId
&& msg.sessionId === invocation.sessionId
&& msg.runId === invocation.runId
&& msg.attemptId === invocation.attemptId
&& msg.profileGeneration === invocation.profileGeneration
&& msg.manifestVersion === invocation.manifestVersion
&& msg.manifestDigest === invocation.manifestDigest
&& msg.daemonBootEpoch === invocation.daemonBootEpoch
&& msg.executionGeneration === invocation.executionGeneration
&& msg.inputHash === invocation.inputHash;
let validated = false;
try {
if (!runtimeKernel) throw new Error("Agent runtime kernel is not ready");
if (!identityMatches) {
runtimeKernel.markRunToolInvocationOutcomeUnknown(invocation, "chat_first_e2e_result_mismatch");
} else {
runtimeKernel.completeRunToolInvocation({
invocationId: invocation.invocationId,
ownerId: invocation.ownerId,
sessionId: invocation.sessionId,
runId: invocation.runId,
attemptId: invocation.attemptId,
profileGeneration: invocation.profileGeneration,
manifestVersion: invocation.manifestVersion,
manifestDigest: invocation.manifestDigest,
daemonBootEpoch: invocation.daemonBootEpoch,
executionGeneration: invocation.executionGeneration,
inputHash: invocation.inputHash,
capabilityRef: invocation.capabilityRef,
activeOwnerId: currentOwnerId,
outcome: msg.outcome,
result: msg.result,
});
const result = JSON.parse(msg.result) as Record<string, unknown>;
validated = msg.outcome === "succeeded" && result.ok === true && result.rendered === 1;
}
runtimeKernel.completeChatFirstHarnessExecutor({
ownerId: invocation.ownerId,
sessionId: invocation.sessionId,
runId: invocation.runId,
attemptId: invocation.attemptId,
succeeded: validated,
});
send({
type: "chat_first_harness_executor_result",
requestId: chatFirstHarness.requestId,
clientId: chatFirstHarness.clientId,
ownerId: invocation.ownerId,
sessionId: invocation.sessionId,
runId: invocation.runId,
attemptId: invocation.attemptId,
ok: validated,
executorInvoked: true,
validated,
journalBlockRendered: validated,
...(validated ? {} : { error: { code: "chat_first_e2e_executor_failed", message: "The executor did not render the fixture block" } }),
});
} catch (error) {
logErr(`Rejected Chat-first E2E executor result invocation=${msg.invocationId}: ${error}`);
try {
runtimeKernel?.markRunToolInvocationOutcomeUnknown(invocation, "chat_first_e2e_result_rejected");
runtimeKernel?.completeChatFirstHarnessExecutor({
ownerId: invocation.ownerId,
sessionId: invocation.sessionId,
runId: invocation.runId,
attemptId: invocation.attemptId,
succeeded: false,
});
} catch (terminalizeError) {
logErr(`Failed to terminalize rejected Chat-first E2E executor: ${terminalizeError}`);
}
send({
type: "chat_first_harness_executor_result",
requestId: chatFirstHarness.requestId,
clientId: chatFirstHarness.clientId,
ownerId: invocation.ownerId,
sessionId: invocation.sessionId,
runId: invocation.runId,
attemptId: invocation.attemptId,
ok: false,
executorInvoked: true,
validated: false,
journalBlockRendered: false,
error: externalAuthorityError(error, "chat_first_e2e_result_rejected"),
});
}
return;
}
const pending = pendingToolCalls.get(key);
if (pending) {
try {
const result = finalizeRelayResult(pending.callId, msg.result, pending.invocation, msg.outcome);
const finalizedOutcome = controlToolInvocationOutcome(result);
runtimeKernel?.completeRunToolInvocation({
invocationId: msg.invocationId,
ownerId: msg.ownerId,
sessionId: msg.sessionId,
runId: msg.runId,
attemptId: msg.attemptId,
profileGeneration: msg.profileGeneration,
manifestVersion: msg.manifestVersion,
manifestDigest: msg.manifestDigest,
daemonBootEpoch: msg.daemonBootEpoch,
executionGeneration: msg.executionGeneration,
inputHash: msg.inputHash,
capabilityRef: pending.invocation.capabilityRef,
activeOwnerId: currentOwnerId,
outcome: finalizedOutcome,
result,
});
pendingToolCalls.delete(key);
clearTimeout(pending.timeout);
writeFinalizedRelayToolResult(pending.client, pending.callId, result);
} catch (error) {
logErr(`Rejected authorized tool execution result invocation=${msg.invocationId}: ${error}`);
pendingToolCalls.delete(key);
clearTimeout(pending.timeout);
const failure = finalizeRelayResult(
pending.callId,
JSON.stringify({
ok: false,
error: {
code: "tool_result_finalization_failed",
message: "The authorized tool result could not be finalized.",
},
}),
pending.invocation,
"failed",
);
writeFinalizedRelayToolResult(pending.client, pending.callId, failure);
}
return;
}
const external = pendingExternalToolCalls.get(key);
if (external) {
try {
const result = finalizeRelayResult(external.request.requestId, msg.result, external.invocation, msg.outcome);
const finalizedOutcome = controlToolInvocationOutcome(result);
runtimeKernel?.completeRunToolInvocation({
invocationId: msg.invocationId,
ownerId: msg.ownerId,
sessionId: msg.sessionId,
runId: msg.runId,
attemptId: msg.attemptId,
profileGeneration: msg.profileGeneration,
manifestVersion: msg.manifestVersion,
manifestDigest: msg.manifestDigest,
daemonBootEpoch: msg.daemonBootEpoch,
executionGeneration: msg.executionGeneration,
inputHash: msg.inputHash,
capabilityRef: external.invocation.capabilityRef,
activeOwnerId: currentOwnerId,
outcome: finalizedOutcome,
result,
});
pendingExternalToolCalls.delete(key);
clearTimeout(external.timeout);
send({
type: "external_surface_tool_result",
requestId: external.request.requestId,
clientId: external.request.clientId,
ownerId: external.invocation.ownerId,
sessionId: external.invocation.sessionId,
runId: external.invocation.runId,
attemptId: external.invocation.attemptId,
invocationId: external.invocation.invocationId,
// This acknowledges the correlated protocol request. The model-facing
// tool outcome remains in the canonical `result` envelope; Swift
// requires this transport acknowledgement to read that typed failure.
ok: true,
result,
});
} catch (error) {
logErr(`Rejected external authorized tool result invocation=${msg.invocationId}: ${error}`);
pendingExternalToolCalls.delete(key);
clearTimeout(external.timeout);
const failure = finalizeRelayResult(
external.request.requestId,
JSON.stringify({
ok: false,
error: {
code: "tool_result_finalization_failed",
message: "The authorized tool result could not be finalized.",
},
}),
external.invocation,
"failed",
);
send({
type: "external_surface_tool_result",
requestId: external.request.requestId,
clientId: external.request.clientId,
ownerId: external.invocation.ownerId,
sessionId: external.invocation.sessionId,
runId: external.invocation.runId,
attemptId: external.invocation.attemptId,
invocationId: external.invocation.invocationId,
ok: true,
result: failure,
});
}
return;
}
logErr(`Warning: no pending tool invocation for invocation=${msg.invocationId}`);
}
function externalAuthorityError(error: unknown, fallbackCode: string): { code: string; message: string } {
const rawCode = error && typeof error === "object" && "code" in error
? String((error as { code: unknown }).code)
: fallbackCode;
const code = /^[a-z0-9_]{1,64}$/.test(rawCode) ? rawCode : fallbackCode;
return {
code,
message: error instanceof Error ? error.message : "External surface authority rejected the request",
};
}
function registerPendingExternalToolCall(
request: ExternalSurfaceToolInvokeMessage,
invocation: AuthorizedRunToolInvocation,
): { request: ExternalSurfaceToolInvokeMessage; invocation: AuthorizedRunToolInvocation; timeout: ReturnType<typeof setTimeout> } {
const key = toolCallPendingKey(invocation);
if (pendingExternalToolCalls.has(key) || pendingToolCalls.has(key)) {
throw Object.assign(new Error("Duplicate tool invocation"), { code: "invocation_replayed" });
}
const pending = {
request,
invocation,
timeout: setTimeout(() => {
const active = pendingExternalToolCalls.get(key);
if (!active) return;
pendingExternalToolCalls.delete(key);
try {
runtimeKernel?.markRunToolInvocationOutcomeUnknown(active.invocation, "swift_tool_timeout");
} catch (error) {
logErr(`Failed to mark external invocation outcome unknown: ${error}`);
}
send({
type: "external_surface_tool_result",
requestId: active.request.requestId,
clientId: active.request.clientId,
ownerId: active.invocation.ownerId,
sessionId: active.invocation.sessionId,
runId: active.invocation.runId,
attemptId: active.invocation.attemptId,
invocationId: active.invocation.invocationId,
ok: false,
error: { code: "swift_tool_timeout", message: "Timed out waiting for the authorized tool executor" },
});
}, 120_000),
};
pendingExternalToolCalls.set(key, pending);
return pending;
}
function finishPendingChatFirstHarnessExecutor(
pending: {
requestId: string;
clientId: string;
invocation: AuthorizedRunToolInvocation;
timeout: ReturnType<typeof setTimeout>;
},
errorCode: string,
message: string,
): void {
try {
runtimeKernel?.markRunToolInvocationOutcomeUnknown(pending.invocation, errorCode);
runtimeKernel?.completeChatFirstHarnessExecutor({
ownerId: pending.invocation.ownerId,
sessionId: pending.invocation.sessionId,
runId: pending.invocation.runId,
attemptId: pending.invocation.attemptId,
succeeded: false,
});
} catch (error) {
logErr(`Failed to terminalize Chat-first E2E executor: ${error}`);
}
send({
type: "chat_first_harness_executor_result",
requestId: pending.requestId,
clientId: pending.clientId,
ownerId: pending.invocation.ownerId,
sessionId: pending.invocation.sessionId,
runId: pending.invocation.runId,
attemptId: pending.invocation.attemptId,
ok: false,
executorInvoked: true,
validated: false,
journalBlockRendered: false,
error: { code: errorCode, message },
});
}
function registerPendingChatFirstHarnessExecutor(input: {
requestId: string;
clientId: string;
invocation: AuthorizedRunToolInvocation;
}): void {
const key = toolCallPendingKey(input.invocation);
if (pendingChatFirstHarnessExecutors.has(key) || pendingExternalToolCalls.has(key) || pendingToolCalls.has(key)) {
throw Object.assign(new Error("Duplicate tool invocation"), { code: "invocation_replayed" });
}
const pending = {
...input,
timeout: setTimeout(() => {
const active = pendingChatFirstHarnessExecutors.get(key);
if (!active) return;
pendingChatFirstHarnessExecutors.delete(key);
finishPendingChatFirstHarnessExecutor(
active,
"swift_tool_timeout",
"Timed out waiting for the authorized Chat-first block executor",
);
}, 120_000),
};
pendingChatFirstHarnessExecutors.set(key, pending);
}
function cancelPendingExternalToolCallsForAttempt(input: {
ownerId: string;
runId: string;
attemptId: string;
errorCode: string;
}): void {
for (const [key, pending] of pendingExternalToolCalls) {
if (
pending.invocation.ownerId !== input.ownerId
|| pending.invocation.runId !== input.runId
|| pending.invocation.attemptId !== input.attemptId
) continue;
pendingExternalToolCalls.delete(key);
clearTimeout(pending.timeout);
try {
runtimeKernel?.markRunToolInvocationOutcomeUnknown(pending.invocation, input.errorCode);
} catch (error) {
logErr(`Failed to terminalize external invocation: ${error}`);
}
send({
type: "external_surface_tool_result",
requestId: pending.request.requestId,
clientId: pending.request.clientId,
ownerId: pending.invocation.ownerId,
sessionId: pending.invocation.sessionId,
runId: pending.invocation.runId,
attemptId: pending.invocation.attemptId,
invocationId: pending.invocation.invocationId,
ok: false,
error: { code: input.errorCode, message: "External surface run terminated during tool execution" },
});
}
}
function rejectPendingToolCallsForOwner(
ownerId: string,
errorCode = "owner_changed",
message = "Active owner changed during tool execution",
): void {
for (const [key, pending] of pendingToolCalls) {
if (pending.invocation.ownerId !== ownerId) continue;
pendingToolCalls.delete(key);
clearTimeout(pending.timeout);
writeRelayToolResult(
pending.client,
pending.callId,
relayError(errorCode, message),
pending.invocation,
"failed",
);
}
for (const [key, pending] of pendingExternalToolCalls) {
if (pending.invocation.ownerId !== ownerId) continue;
pendingExternalToolCalls.delete(key);
clearTimeout(pending.timeout);
send({
type: "external_surface_tool_result",
requestId: pending.request.requestId,
clientId: pending.request.clientId,
ownerId: pending.invocation.ownerId,
sessionId: pending.invocation.sessionId,
runId: pending.invocation.runId,
attemptId: pending.invocation.attemptId,
invocationId: pending.invocation.invocationId,
ok: false,
error: { code: errorCode, message },
});
}
for (const [key, pending] of pendingChatFirstHarnessExecutors) {
if (pending.invocation.ownerId !== ownerId) continue;
pendingChatFirstHarnessExecutors.delete(key);
clearTimeout(pending.timeout);
finishPendingChatFirstHarnessExecutor(pending, errorCode, message);
}
}
/** The broker terminalizes the ledger before subscribers see terminal events. */
function rejectPendingToolCallsForKernelEvent(event: AgentEvent): void {
if (!TERMINAL_RUN_TOOL_EVENTS.has(event.type)) return;
const matches = (invocation: AuthorizedRunToolInvocation): boolean =>
!!event.runId
&& invocation.runId === event.runId
&& (!event.attemptId || invocation.attemptId === event.attemptId);
const errorCode = event.type.startsWith("attempt.") ? "attempt_terminal" : "run_terminal";
for (const [key, pending] of pendingToolCalls) {
if (!matches(pending.invocation)) continue;
pendingToolCalls.delete(key);
clearTimeout(pending.timeout);
writeRelayToolResult(
pending.client,
pending.callId,
relayError(errorCode, "Run tool authority ended before Swift returned a result"),
pending.invocation,
"failed",
);
}
for (const [key, pending] of pendingExternalToolCalls) {
if (!matches(pending.invocation)) continue;
pendingExternalToolCalls.delete(key);
clearTimeout(pending.timeout);
send({
type: "external_surface_tool_result",
requestId: pending.request.requestId,
clientId: pending.request.clientId,
ownerId: pending.invocation.ownerId,
sessionId: pending.invocation.sessionId,
runId: pending.invocation.runId,
attemptId: pending.invocation.attemptId,
invocationId: pending.invocation.invocationId,
ok: false,
error: { code: errorCode, message: "Run tool authority ended before Swift returned a result" },
});
}
for (const [key, pending] of pendingChatFirstHarnessExecutors) {
if (!matches(pending.invocation)) continue;
pendingChatFirstHarnessExecutors.delete(key);
clearTimeout(pending.timeout);
finishPendingChatFirstHarnessExecutor(
pending,
errorCode,
"Run tool authority ended before Swift returned a result",
);
}
}
function resolveClientToolCalls(client: Socket, result: string): void {
for (const [key, pending] of pendingToolCalls) {
if (pending.client !== client) continue;
pendingToolCalls.delete(key);
clearTimeout(pending.timeout);
try {
runtimeKernel?.markRunToolInvocationOutcomeUnknown(pending.invocation, "relay_client_disconnected");
} catch (error) {
logErr(`Failed to mark disconnected tool invocation outcome unknown: ${error}`);
}
writeRelayToolResult(client, pending.callId, result, pending.invocation, "failed");
}
}
function relayError(code: string, message: string): string {
return JSON.stringify({ ok: false, error: { code, message } });
}
function journalLocalReadToolRelayFailure(
canonicalToolName: string,
): { code: string; message: string } {
if (canonicalToolName === "search_chat_history") {
return { code: "chat_history_search_failed", message: "Chat history search could not be completed" };
}
if (canonicalToolName === "read_conversation_evidence") {
return conversationEvidenceRelayDiagnostic("read_conversation_evidence");
}
return conversationEvidenceRelayDiagnostic("search_conversation_evidence");
}
function controlToolInvocationOutcome(result: string): "succeeded" | "failed" {
return finalizedToolResultOutcome(result);
}
function writeRelayToolResult(
client: Socket,
callId: string,
result: string,
invocation?: AuthorizedRunToolInvocation,
outcome?: "succeeded" | "failed",
): string {
const finalized = finalizeRelayResult(callId, result, invocation, outcome);
writeFinalizedRelayToolResult(client, callId, finalized);
return finalized;
}
function writeFinalizedRelayToolResult(client: Socket, callId: string, result: string): void {
try {
client.write(JSON.stringify({ type: "tool_result", callId, result }) + "\n");
} catch (error) {
logErr(`Failed to write relay tool result: ${error}`);
}
}
/** Start Unix socket server for omi-tools stdio processes to connect to */
function startOmiToolsRelay(): Promise<string> {
const pipePath = join(tmpdir(), `omi-tools-${process.pid}.sock`);
// Clean up any stale socket
try {
unlinkSync(pipePath);
} catch {
// ignore
}
return new Promise((resolve, reject) => {
const server = createNetServer((client: Socket) => {
omiToolsClients.push(client);
let buffer = "";
client.on("data", (data: Buffer) => {
buffer += data.toString();
let newlineIdx;
while ((newlineIdx = buffer.indexOf("\n")) >= 0) {
const line = buffer.slice(0, newlineIdx);
buffer = buffer.slice(newlineIdx + 1);
if (!line.trim()) continue;
try {
const msg = JSON.parse(line) as {
type: string;
callId: string;
invocationId?: string;
name: string;
input: Record<string, unknown>;
capabilityRef?: string;
};
if (msg.type === "tool_use") {
const capabilityRef = msg.capabilityRef?.trim();
const invocationId = msg.invocationId?.trim() || msg.callId?.trim();
if (!runtimeKernel || !capabilityRef || !invocationId) {
writeRelayToolResult(
client,
msg.callId,
relayError("missing_run_capability", "Tool relay requires an active run capability"),
);
continue;
}
let authorized;
let routedProposal;
try {
routedProposal = runtimeKernel.routeRelayedRunToolProposal({
capabilityRef,
toolName: msg.name,
toolInput: msg.input ?? {},
activeOwnerId: currentOwnerId,
});
authorized = runtimeKernel.authorizeRelayedRunToolInvocation({
capabilityRef,
invocationId,
toolName: routedProposal.toolName,
toolInput: routedProposal.toolInput,
activeOwnerId: currentOwnerId,
});
} catch (error) {
const code = error && typeof error === "object" && "code" in error
? String((error as { code: unknown }).code)
: "capability_rejected";