forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprotocol.ts
More file actions
1407 lines (1299 loc) · 42.9 KB
/
Copy pathprotocol.ts
File metadata and controls
1407 lines (1299 loc) · 42.9 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
// JSON lines protocol between Swift app and Node.js agent runtime
// Extended from agent protocol with authentication message types
// === Swift → Bridge (stdin) ===
export const PROTOCOL_VERSION = 2 as const;
export const RUNTIME_CAPABILITIES = [
"journal_import_remote_turn",
"runtime_adapter_availability",
"chat_first_capability_projection",
] as const;
export type ProtocolVersion = typeof PROTOCOL_VERSION;
export interface ProtocolEnvelope {
protocolVersion: ProtocolVersion;
requestId: string;
clientId: string;
/** Signed-in Omi/Firebase uid used to scope persisted runtime state. */
ownerId?: string;
}
export interface CanonicalCorrelation {
sessionId?: string;
runId?: string;
attemptId?: string;
eventId?: string;
}
export interface QueryMessage extends ProtocolEnvelope {
type: "query";
sessionId: string;
/** Requested projection surface; the runtime accepts it only when bound to the canonical session. */
surfaceKind: string;
producingTurnId?: string;
prompt: string;
mode?: "ask" | "act";
imageBase64?: string;
attachments?: QueryAttachment[];
/** Freshness precondition only; it cannot select or mutate context. */
expectedContextSnapshotVersion?: string;
expectedContextSnapshotGeneration?: number;
expectedContextRendererFingerprint?: string;
expectedCapabilityVersion?: string;
/**
* Per-turn reasoning-effort lane: "adaptive" for typed chat (model decides
* its own thinking depth), "fast" for PTT/voice (speed-optimized, no
* thinking). Relayed opaquely to the desktop backend as the
* x-omi-reasoning-effort header; never interpreted by the runtime.
*/
reasoningEffort?: string;
/**
* Per-turn client-computed capability flag: true when the desktop's JIT
* knowledge-ledger rollout is enabled for the current user. This is a UX
* gate only — the backend independently re-checks entitlement on every
* `/v1/agent/execute-tool` call, so an absent or stale value only affects
* which tools the model is offered, never authorization.
*/
jitKnowledgeToolsEnabled?: boolean;
/** QA-only source-owned prompt projection; persisted beside the admitted
* snapshot and hashed by the runtime before the run is inserted. */
jitCostEvidenceProjection?: JitCostEvidenceProjection;
/** Qualification-only JIT budget; absent for all normal chat. */
jitBudget?: {
contractVersion: string;
executionID: string;
maxProviderAttempts: number;
maxOutputTokensPerAttempt: number;
maxNormalizedInputTokensPerAttempt: number;
maxEstimatedSpendMicroUSD: number;
};
}
export interface JitCostEvidenceProjection {
schema_version: string;
owner_id: string;
execution_id: string;
producer_lane: "planned" | "ambient";
matched_input: {
evaluation_time: string;
timezone: string;
context_id: string;
evidence_sha256?: string;
};
legacy: {
prompt: string;
uncached_prompt: string;
[key: string]: unknown;
};
nano: {
prompt: string;
[key: string]: unknown;
};
full: {
prompt: string;
[key: string]: unknown;
};
evidence_sha256?: string;
[key: string]: unknown;
}
export interface QueryAttachment {
attachmentId: string;
displayName: string;
mimeType: string;
sizeBytes?: number;
uri?: string;
}
export interface AuthorizedToolExecutionResultMessage {
type: "authorized_tool_execution_result";
protocolVersion: ProtocolVersion;
invocationId: string;
ownerId: string;
sessionId: string;
runId: string;
attemptId: string;
profileGeneration: number;
manifestVersion: number;
manifestDigest: string;
daemonBootEpoch: string;
executionGeneration: number;
inputHash: string;
outcome: "succeeded" | "failed";
result: string;
}
export interface ControlToolRequestMessage extends ProtocolEnvelope {
type: "control_tool";
name: string;
input: Record<string, unknown>;
}
export interface DirectControlToolRequestMessage extends ProtocolEnvelope {
type: "direct_control_tool";
ownerId: string;
name: string;
input: Record<string, unknown>;
}
export interface ExternalSurfaceRunBeginMessage extends ProtocolEnvelope {
type: "external_surface_run_begin";
ownerId: string;
sessionId: string;
turnId: string;
prompt: string;
/** The prompt is an internal instruction, not user speech: it drives the run
* but must never be journaled as the user's turn. */
promptIsSynthetic?: boolean;
mode: "ask" | "act";
}
export interface ExternalSurfaceToolInvokeMessage extends ProtocolEnvelope {
type: "external_surface_tool_invoke";
ownerId: string;
sessionId: string;
runId: string;
attemptId: string;
invocationId: string;
toolName: string;
input: Record<string, unknown>;
}
export interface ExternalSurfaceRunCompleteMessage extends ProtocolEnvelope {
type: "external_surface_run_complete";
ownerId: string;
sessionId: string;
runId: string;
attemptId: string;
terminalStatus: "completed" | "failed" | "cancelled";
/**
* The answer text the external surface reports for this run.
*
* An external surface owns its own streaming, so the kernel never observes this
* run's output — it has to be handed back at terminalization or it is lost.
* Without it `runs.final_text` stays null and every consumer that reads a run's
* answer is content-free: the completion lane can only report that an agent
* finished, and a spawn-agent child's receipt, which builds its journal block
* from the child's final text, has nothing to write (#12731).
*
* What a surface can actually report is its own problem: for a realtime voice
* deferral the text must be accumulated over the turn stream, because the
* turn-end hub property is already cleared by the time terminalization runs.
*/
finalText?: string;
errorCode?: string;
}
export interface StopMessage {
type: "stop";
}
export interface InterruptMessage extends ProtocolEnvelope, CanonicalCorrelation {
type: "interrupt";
}
export interface InvalidateSessionMessage extends ProtocolEnvelope {
type: "invalidate_session";
surfaceKind: string;
externalRefKind: string;
externalRefId: string;
}
/**
* Pre-visibility owner barrier. Swift sends this only while holding the exact
* previous-owner transition cleanup capability and waits for the correlated
* receipt before exposing the replacement owner.
*/
export interface RevokeOwnerRuntimeMessage extends ProtocolEnvelope {
type: "revoke_owner_runtime";
ownerId: string;
}
export interface ImportLegacyMainChatSessionsMessage extends ProtocolEnvelope {
type: "import_legacy_main_chat_sessions";
entries: Array<{ chatId: string; agentSessionId: string }>;
}
/** A warmup can identify a pinned session/profile, but cannot configure it. */
export interface WarmupMessage extends ProtocolEnvelope {
type: "warmup";
sessionId: string;
profileGeneration: number;
}
export interface ConfigureDefaultExecutionProfileMessage extends ProtocolEnvelope {
type: "configure_default_execution_profile";
adapterId: string;
modelProfile: string | null;
workingDirectory: string;
expectedPreferenceGeneration?: number;
}
export interface ResolveSurfaceSessionMessage extends ProtocolEnvelope {
type: "resolve_surface_session";
surfaceKind: string;
externalRefKind: string;
externalRefId: string;
title?: string;
/** Applied atomically only when this resolve creates the surface session. */
creationProfile?: {
adapterId: string;
modelProfile: string | null;
workingDirectory: string;
};
/**
* Ephemeral server-derived capability, accepted only for the main Chat
* surface. It is never persisted to the kernel journal or preferences.
*/
chatFirstCapability?: {
chatFirstUi: boolean;
controlGeneration: number;
};
}
export interface MigrateSessionExecutionProfileMessage extends ProtocolEnvelope {
type: "migrate_session_execution_profile";
sessionId: string;
expectedProfileGeneration: number;
adapterId: string;
modelProfile: string | null;
workingDirectory: string;
reason: "user_requested";
}
export type ContextSourceKind =
| "identity"
| "memories"
| "goals"
| "tasks"
| "screen"
| "workspace"
| "surface";
export type ContextSourceOutcome = "available" | "empty" | "unavailable" | "redacted";
export interface ContextSourceUpdateMessage extends ProtocolEnvelope {
type: "context_source_update";
sessionId: string;
surfaceKind: string;
source: ContextSourceKind;
sourceRevision: string;
outcome: ContextSourceOutcome;
capturedAtMs: number;
expiresAtMs?: number;
payload: Record<string, unknown>;
}
export interface GetContextSnapshotMessage extends ProtocolEnvelope {
type: "get_context_snapshot";
sessionId: string;
surfaceKind: string;
}
export interface JournalTurnWireInput {
turnId?: string;
producerId?: string;
role?: "user" | "assistant";
origin?: string;
status?: string;
content?: string;
contentBlocks?: unknown[];
resources?: unknown[];
metadataJson?: string;
createdAtMs?: number;
}
export function assertPublicJournalRecordAuthority(input: unknown): asserts input is JournalTurnWireInput {
if (!input || typeof input !== "object" || Array.isArray(input)) {
throw new Error("Journal turn input must be an object");
}
for (const field of ["delivery", "producingRunId", "producingAttemptId"] as const) {
if (Object.prototype.hasOwnProperty.call(input, field)) {
throw new Error(`Journal ${field} is kernel-owned`);
}
}
}
export function assertPublicJournalUpdateAuthority(input: unknown): asserts input is Record<string, unknown> {
if (!input || typeof input !== "object" || Array.isArray(input)) {
throw new Error("Journal update input must be an object");
}
for (const field of ["producingRunId", "producingAttemptId"] as const) {
if (Object.prototype.hasOwnProperty.call(input, field)) {
throw new Error(`Journal ${field} is kernel-owned`);
}
}
}
export interface JournalRecordTurnMessage extends ProtocolEnvelope {
type: "journal_record_turn";
surfaceKind: string;
externalRefKind: string;
externalRefId: string;
turn: JournalTurnWireInput;
}
export interface JournalRecordExchangeMessage extends ProtocolEnvelope {
type: "journal_record_exchange";
surfaceKind: string;
externalRefKind: string;
externalRefId: string;
turns: JournalTurnWireInput[];
}
export interface JournalRemoteTurnWireInput {
remoteId: string;
canonicalTurnId?: string;
role: "user" | "assistant";
content: string;
contentBlocks: unknown[];
resources: unknown[];
metadataJson: string;
createdAtMs: number;
}
/**
* Bounded upgrade input for backend rows written before the kernel journal was
* authoritative. The runtime, not Swift, resolves the canonical conversation
* and owns the imported turn projection.
*/
export interface JournalImportRemoteTurnMessage extends ProtocolEnvelope {
type: "journal_import_remote_turn";
surfaceKind: string;
externalRefKind: string;
externalRefId: string;
turn: JournalRemoteTurnWireInput;
}
export function assertJournalRemoteTurnInput(
input: unknown,
): asserts input is JournalRemoteTurnWireInput {
if (!input || typeof input !== "object" || Array.isArray(input)) {
throw new Error("Remote journal turn input must be an object");
}
const turn = input as Partial<JournalRemoteTurnWireInput>;
if (typeof turn.remoteId !== "string" || !turn.remoteId.trim()) {
throw new Error("Remote journal turn requires remoteId");
}
if (turn.canonicalTurnId !== undefined
&& (typeof turn.canonicalTurnId !== "string" || !turn.canonicalTurnId.trim())) {
throw new Error("Remote journal canonicalTurnId must be non-empty when provided");
}
if (turn.role !== "user" && turn.role !== "assistant") {
throw new Error("Remote journal turn requires a valid role");
}
if (typeof turn.content !== "string"
|| !Array.isArray(turn.contentBlocks)
|| !Array.isArray(turn.resources)
|| typeof turn.metadataJson !== "string"
|| typeof turn.createdAtMs !== "number"
|| !Number.isFinite(turn.createdAtMs)) {
throw new Error("Remote journal turn has an invalid payload");
}
}
export interface JournalUpdateTurnMessage extends ProtocolEnvelope {
type: "journal_update_turn";
surfaceKind: string;
externalRefKind: string;
externalRefId: string;
/** Swift may append typed evidence atomically; the kernel still owns turn identity. */
update: Record<string, unknown> & { appendEvidence?: unknown[] };
}
export interface JournalTerminalizeTurnMessage extends ProtocolEnvelope {
type: "journal_terminalize_turn";
surfaceKind: string;
externalRefKind: string;
externalRefId: string;
terminalization: {
turnId: string;
producingRunId: string;
producingAttemptId: string;
disposition: "accept" | "discard";
content?: string;
replaceContentBlocks?: unknown[];
replaceResources?: unknown[];
};
}
export interface JournalRepairTurnsMessage extends ProtocolEnvelope {
type: "journal_repair_turns";
surfaceKind: string;
externalRefKind: string;
externalRefId: string;
turnIds: string[];
}
export function journalTerminalizationDisposition(input: unknown): "accept" | "discard" {
if (!input || typeof input !== "object" || Array.isArray(input)) {
throw new Error("Journal terminalization input must be an object");
}
const disposition = (input as { disposition?: unknown }).disposition;
if (disposition !== "accept" && disposition !== "discard") {
throw new Error("Journal terminalization requires an explicit accept or discard disposition");
}
return disposition;
}
export interface JournalListTurnsMessage extends ProtocolEnvelope {
type: "journal_list_turns";
surfaceKind: string;
externalRefKind: string;
externalRefId: string;
afterTurnSeq?: number;
limit?: number;
}
export interface JournalClearTurnsMessage extends ProtocolEnvelope {
type: "journal_clear_turns";
surfaceKind: string;
externalRefKind: string;
externalRefId: string;
expectedGeneration: number;
// When false, purge the local journal only and leave server-side chat history
// intact (no backend delete). Defaults to true for the explicit user clear.
deleteBackend?: boolean;
}
/**
* Privileged local-only append for server-validated chat-first blocks. The
* capability and producing run/attempt bind this mutation to the assistant
* turn that invoked `render_chat_blocks`; Swift cannot select an arbitrary
* journal turn.
*/
export interface AppendChatFirstBlocksMessage extends ProtocolEnvelope {
type: "append_chat_first_blocks";
ownerId: string;
sessionId: string;
runId: string;
attemptId: string;
capabilityRef: string;
controlGeneration: number;
blocks: unknown[];
}
/**
* Privileged local-only append for one Rewind evidence resource. The same
* capability/run binding prevents a tool from attaching an image to an
* arbitrary Chat turn.
*/
export interface AppendChatFirstEvidenceMessage extends ProtocolEnvelope {
type: "append_chat_first_evidence";
ownerId: string;
sessionId: string;
runId: string;
attemptId: string;
capabilityRef: string;
controlGeneration: number;
resource: unknown;
}
/** Kernel-owned selection for one persisted, tail-actionable question card. */
export interface RecordQuestionInteractionReplyMessage extends ProtocolEnvelope {
type: "record_question_interaction_reply";
surfaceKind: string;
externalRefKind: string;
externalRefId: string;
ownerId: string;
sessionId: string;
questionId: string;
optionId: string;
controlGeneration: number;
}
/**
* Privileged local receipt for an ordered server-owned deterministic-tier
* batch. Swift only transports typed server responses; the kernel derives
* journal identities and enforces tail suppression in one transaction.
*/
export interface MaterializeChatFirstIntentsMessage extends ProtocolEnvelope {
type: "materialize_chat_first_intents";
surfaceKind: string;
externalRefKind: string;
externalRefId: string;
ownerId: string;
sessionId: string;
controlGeneration: number;
intents: Array<{
intentId: string;
continuityKey: string;
source:
| "daily_opener"
| "capture_arrival"
| "deferral_reraise"
| "agent_judgment"
| "cold_start_rich"
| "cold_start_sparse";
blocks: unknown[];
}>;
}
/** Read restart-safe kernel receipts to include in the next server fetch/ack. */
export interface ListChatFirstMaterializationReceiptsMessage extends ProtocolEnvelope {
type: "list_chat_first_materialization_receipts";
surfaceKind: string;
externalRefKind: string;
externalRefId: string;
ownerId: string;
sessionId: string;
controlGeneration: number;
limit?: number;
}
/** Drop only receipts that the server accepted in a successful fetch/ack call. */
export interface AcknowledgeChatFirstMaterializationReceiptsMessage extends ProtocolEnvelope {
type: "acknowledge_chat_first_materialization_receipts";
surfaceKind: string;
externalRefKind: string;
externalRefId: string;
ownerId: string;
sessionId: string;
controlGeneration: number;
receipts: Array<{ intentId: string; receiptId: string }>;
coldStartSequenceTerminalReceipts: Array<{
sequenceId: string;
receiptId: string;
terminalState: "completed" | "abandoned";
}>;
}
export interface EnsureAgentSpawnJournalMessage extends ProtocolEnvelope {
type: "ensure_agent_spawn_journal";
ownerId: string;
sessionId: string;
runId: string;
}
export interface JournalBackendSyncResultMessage extends ProtocolEnvelope {
type: "journal_backend_sync_result";
ownerId: string;
turnId: string;
conversationId: string;
conversationGeneration: number;
attemptCount: number;
deliveryGeneration: number;
payloadHash: string;
ok: boolean;
remoteId?: string;
errorCode?: string;
}
export interface JournalBackendDeleteResultMessage extends ProtocolEnvelope {
type: "journal_backend_delete_result";
ownerId: string;
operationId: string;
conversationId: string;
conversationGeneration: number;
attemptCount: number;
deliveryGeneration: number;
payloadHash: string;
ok: boolean;
errorCode?: string;
}
export interface JournalBackendReconcileResultMessage extends ProtocolEnvelope {
type: "journal_backend_reconcile_result";
ownerId: string;
reconcileId: string;
conversationId: string;
pageCursor: string | null;
nextCursor?: string | null;
ok: boolean;
turns?: Record<string, unknown>[];
hasMore?: boolean;
errorCode?: string;
}
/** Swift's physical transport result for the separate deferral outbox. */
export interface ChatFirstDeferralDeliveryResultMessage extends ProtocolEnvelope {
type: "chat_first_deferral_delivery_result";
ownerId: string;
continuityKey: string;
deliveryGeneration: number;
payloadHash: string;
ok: boolean;
errorCode?: string;
}
/** Swift pushes a refreshed Firebase ID token to the bridge (piMono mode) */
export interface RefreshTokenMessage {
type: "refresh_token";
token: string;
ownerId: string;
}
/** Swift establishes the signed-in owner even when a local adapter needs no Firebase token. */
export interface RefreshOwnerMessage {
type: "refresh_owner";
ownerId: string;
}
/**
* Local/offline-only E2E probe for the real Chat-first Swift tool executor.
* The kernel derives capability from the already-resolved session; this message
* cannot carry or manufacture a rollout projection.
*/
export interface ChatFirstHarnessExecutorBeginMessage extends ProtocolEnvelope {
type: "chat_first_harness_executor_begin";
ownerId: string;
sessionId: string;
producingTurnId: string;
controlGeneration: number;
input: Record<string, unknown>;
}
export type InboundMessage =
| QueryMessage
| AuthorizedToolExecutionResultMessage
| ControlToolRequestMessage
| DirectControlToolRequestMessage
| ExternalSurfaceRunBeginMessage
| ExternalSurfaceToolInvokeMessage
| ExternalSurfaceRunCompleteMessage
| StopMessage
| InterruptMessage
| InvalidateSessionMessage
| RevokeOwnerRuntimeMessage
| ImportLegacyMainChatSessionsMessage
| WarmupMessage
| ConfigureDefaultExecutionProfileMessage
| ResolveSurfaceSessionMessage
| MigrateSessionExecutionProfileMessage
| ContextSourceUpdateMessage
| GetContextSnapshotMessage
| JournalRecordTurnMessage
| JournalRecordExchangeMessage
| JournalImportRemoteTurnMessage
| JournalUpdateTurnMessage
| JournalTerminalizeTurnMessage
| JournalRepairTurnsMessage
| JournalListTurnsMessage
| JournalClearTurnsMessage
| AppendChatFirstBlocksMessage
| AppendChatFirstEvidenceMessage
| RecordQuestionInteractionReplyMessage
| MaterializeChatFirstIntentsMessage
| ListChatFirstMaterializationReceiptsMessage
| AcknowledgeChatFirstMaterializationReceiptsMessage
| EnsureAgentSpawnJournalMessage
| JournalBackendSyncResultMessage
| JournalBackendDeleteResultMessage
| JournalBackendReconcileResultMessage
| ChatFirstDeferralDeliveryResultMessage
| ChatFirstHarnessExecutorBeginMessage
| RefreshTokenMessage
| RefreshOwnerMessage;
const INBOUND_RESPONSE_MESSAGE_TYPES = new Set<InboundMessage["type"]>([
"authorized_tool_execution_result",
"journal_backend_sync_result",
"journal_backend_delete_result",
"journal_backend_reconcile_result",
"chat_first_deferral_delivery_result",
]);
/** Response handlers log invalid replies locally; they never echo request errors back to Swift. */
export function isInboundResponseMessage(message: Pick<InboundMessage, "type">): boolean {
return INBOUND_RESPONSE_MESSAGE_TYPES.has(message.type);
}
// === Bridge → Swift (stdout) ===
export interface OutboundEnvelope {
protocolVersion: ProtocolVersion;
requestId?: string;
clientId?: string;
}
export interface QueryScopedOutbound extends OutboundEnvelope, CanonicalCorrelation {
adapterSessionId?: string;
}
export interface InitMessage extends OutboundEnvelope {
type: "init";
sessionId: string;
agentControlTools: string[];
runtimeVersion: string;
runtimeCapabilities: string[];
/** Exact registry projection used by Swift to build local-provider schemas. */
runtimeAdapterIds: string[];
}
export interface TextDeltaMessage extends QueryScopedOutbound {
type: "text_delta";
text: string;
}
export interface ToolUseMessage extends QueryScopedOutbound {
type: "tool_use";
callId: string;
/** Required together for executable Omi/Swift tool invocations; absent on display-only adapter events. */
invocationId?: string;
capabilityRef?: string;
ownerId?: string;
sessionId?: string;
runId?: string;
attemptId?: string;
name: string;
input: Record<string, unknown>;
}
export interface AuthorizedToolExecutionMessage extends OutboundEnvelope {
type: "authorized_tool_execution";
invocationId: string;
ownerId: string;
sessionId: string;
runId: string;
attemptId: string;
profileGeneration: number;
manifestVersion: number;
manifestDigest: string;
daemonBootEpoch: string;
executionGeneration: number;
capabilityRef: string;
toolName: string;
input: Record<string, unknown>;
inputHash: string;
effectClass: "read_only" | "idempotent_write" | "non_idempotent_write";
retryPolicy: "safe_retry" | "never_auto_retry";
surfaceKind: string;
externalRefKind: string | null;
externalRefId: string | null;
originatingUserText: string;
precedingAssistantText: string | null;
runMode: "ask" | "act";
chatMode: string | null;
/** Present only for the server-authorized Main Chat structured-block tool. */
chatFirstControlGeneration?: number;
/** Bounded policy recovery telemetry; absent for ordinary authorized calls. */
policyRecovery?: "permission_delegation_to_native";
}
export interface ExternalAuthorityError {
code: string;
message: string;
}
export interface ExternalSurfaceRunBeginResultMessage extends OutboundEnvelope {
type: "external_surface_run_begin_result";
ownerId: string;
sessionId: string;
turnId: string;
ok: boolean;
runId?: string;
attemptId?: string;
duplicate?: boolean;
error?: ExternalAuthorityError;
}
export interface ExternalSurfaceToolResultMessage extends OutboundEnvelope {
type: "external_surface_tool_result";
ownerId: string;
sessionId: string;
runId: string;
attemptId: string;
invocationId: string;
ok: boolean;
result?: string;
error?: ExternalAuthorityError;
}
export interface ExternalSurfaceRunCompleteResultMessage extends OutboundEnvelope {
type: "external_surface_run_complete_result";
ownerId: string;
sessionId: string;
runId: string;
attemptId: string;
ok: boolean;
terminalStatus?: "completed" | "failed" | "cancelled";
duplicate?: boolean;
/**
* Whether the kernel stored `finalText` for this run. Absent from an older
* kernel, which lets a surface keep its own journal fallback instead of
* trusting a silent no-op (#12731).
*/
finalTextPersisted?: boolean;
/** Whether completion left a canonical assistant row for this voice turn. */
journalMaterialized?: boolean;
error?: ExternalAuthorityError;
}
/** Shape-only completion for the local/offline Chat-first executor probe. */
export interface ChatFirstHarnessExecutorResultMessage extends OutboundEnvelope {
type: "chat_first_harness_executor_result";
ownerId: string;
sessionId: string;
runId: string;
attemptId: string;
ok: boolean;
executorInvoked: boolean;
validated: boolean;
journalBlockRendered: boolean;
error?: ExternalAuthorityError;
}
export interface OwnerRuntimeRevokedMessage extends OutboundEnvelope {
type: "owner_runtime_revoked";
ownerId: string;
ok: boolean;
duplicate: boolean;
revokedRunIds: string[];
invalidatedBindingIds: string[];
error?: ExternalAuthorityError;
}
export interface ResultMessage extends QueryScopedOutbound {
type: "result";
text: string;
sessionId: string;
terminalStatus?: "succeeded" | "failed" | "cancelled";
failure?: RuntimeFailurePayload;
costUsd?: number;
inputTokens?: number;
outputTokens?: number;
cacheReadTokens?: number;
cacheWriteTokens?: number;
/** Qualification-only gateway attribution; null is explicit unknown. */
jitCostStatus?: "estimated" | "unknown";
jitEstimatedCostUsd?: number | null;
jitProviderAttempts?: number;
jitReceiptAttemptIDs?: string[];
/// Served model identities observed on this run's completions, deduplicated.
modelsUsed?: string[];
artifacts?: SerializedArtifact[];
completionDeltaArtifacts?: SerializedArtifact[];
}
export interface SerializedArtifact {
artifactId: string;
sessionId: string;
runId: string | null;
attemptId: string | null;
kind: string;
role: string;
uri: string;
displayName: string | null;
mimeType: string | null;
contentHash: string | null;
sizeBytes: number | null;
lifecycleState: string;
lifecycleUpdatedAtMs: number | null;
metadata: Record<string, unknown>;
createdAtMs: number;
}
export interface RuntimeFailurePayload {
code: string;
/** Closed failure taxonomy; `code` remains the detailed diagnostic key. */
failureCode?: "authentication" | "quota_exceeded" | "invalid_request" | "timeout" | "transport_interruption" | "adapter_unavailable" | "adapter_incompatible" | "bridge_start_failed" | "provider_setup_needed" | "malformed_or_oversized_tool_result" | "cancelled" | "stale_owner" | "policy_denied" | "unknown";
userMessage: string;
technicalMessage?: string;
source?: string;
adapterId?: string;
provider?: string;
retryable?: boolean;
recoveryAction?: "worker_recycled";
recoveryOutcome?: "recovered" | "stop_failed" | "binding_stale_failed";
retryDisposition?: "next_send";
}
/// One concrete model identity observed serving this turn's completions.
/// `model` is ONLY the SERVED model from the provider's response stream (e.g.
/// the gateway lane's resolved upstream, pi-ai's `responseModel`). A response
/// that names no model produces NO event — the requested id is an alias and
/// must never be presented as the served model (#11521). Deduplicated per
/// turn by the adapter; `requestedModel` is context, not attribution.
export interface ModelUsedMessage extends QueryScopedOutbound {
type: "model_used";
model: string;
requestedModel?: string;
provider?: string;
}
export interface ToolActivityMessage extends QueryScopedOutbound {
type: "tool_activity";
name: string;
status: "started" | "progress" | "completed" | "failed" | "cancelled" | "interrupted";
toolUseId?: string;
input?: Record<string, unknown>;
}
/**
* Content-free proof that the query-owning runtime is still servicing an
* admitted turn. Swift uses this lease to distinguish a quiet provider round
* from a frozen JSONL bridge; it must never be rendered as assistant output.
*/
export interface TurnActivityMessage extends QueryScopedOutbound {
type: "turn_activity";
phase: "running";
}
export interface ToolResultDisplayMessage extends QueryScopedOutbound {
type: "tool_result_display";
toolUseId: string;
name: string;
output: string;
}
export interface ThinkingDeltaMessage extends QueryScopedOutbound {
type: "thinking_delta";
text: string;
}
export interface ErrorMessage extends QueryScopedOutbound {
type: "error";
message: string;
failure?: RuntimeFailurePayload;
/** Qualification-only gateway attribution; failures are always unknown. */
jitCostStatus?: "unknown";
jitEstimatedCostUsd?: null;
}
/** Sent when ACP requires user authentication (OAuth) */
export interface AuthRequiredMessage {
type: "auth_required";
methods: AuthMethod[];
authUrl?: string;
}
export interface AuthMethod {
id: string;
type: "agent_auth" | "env_var" | "terminal";
displayName?: string;
args?: string[];
env?: Record<string, string>;
}
/** Sent after successful authentication */
export interface AuthSuccessMessage {
type: "auth_success";
}
export interface CancelAckMessage extends QueryScopedOutbound {
type: "cancel_ack";
accepted: boolean;
dispatchAttempted: boolean;
adapterAcknowledged: boolean;
}
export interface ControlToolResultMessage extends OutboundEnvelope {
type: "control_tool_result";
/** Required for direct desktop control; legacy rejection receipts omit it. */
ownerId?: string;
name: string;
result: string;
}
export interface ExecutionProfileProjection {
profileGeneration: number;
adapterId: string;
credentialScope: "managed_cloud" | "local_user";
modelProfile: string | null;
workingDirectory: string;
executionRole: "coordinator" | "leaf";
}
export interface DefaultExecutionProfileConfiguredMessage extends OutboundEnvelope {
type: "default_execution_profile_configured";
preferenceGeneration: number;