forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinterface.ts
More file actions
521 lines (470 loc) · 19.6 KB
/
Copy pathinterface.ts
File metadata and controls
521 lines (470 loc) · 19.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
516
517
518
519
520
521
// Coding-agent adapter contract — Windows port of the macOS agent runtime's
// adapter layer (desktop/macos/agent/src/adapters/interface.ts), trimmed to the
// adapters that exist on Windows: Claude Code (adapter id "acp", built-in ACP
// bridge, no external install) plus three user-connected external ACP commands
// (OpenClaw, Hermes, Codex), plus the managed-cloud default-chat adapter pi-mono
// (a production adapter but not a user-selectable coding agent). macOS's `a2a`
// placeholder is deliberately not ported.
/** How a run's tool use is gated: "ask" surfaces approvals, "act" auto-approves. */
export type RunMode = 'ask' | 'act'
/** Whether an adapter's native session survives an adapter process restart. */
export type ResumeFidelity = 'native' | 'reconstructed' | 'none'
export type ArtifactRole = 'input' | 'result' | 'checkpoint' | 'tool_output' | 'log' | 'other'
import type { RuntimeFailure } from './failures'
// === Streaming events ========================================================
// Trimmed port of macOS protocol.ts's OutboundMessageDraft: only the event
// shapes the ACP client actually emits while an attempt streams. Field names
// match macOS exactly so PR2's IPC layer can stay wire-compatible if we ever
// share tooling.
export interface TextDeltaEvent {
type: 'text_delta'
text: string
}
export interface ThinkingDeltaEvent {
type: 'thinking_delta'
text: string
}
export interface ToolActivityEvent {
type: 'tool_activity'
name: string
status: 'started' | 'completed' | 'failed'
toolUseId?: string
input?: Record<string, unknown>
}
export interface ToolResultDisplayEvent {
type: 'tool_result_display'
toolUseId: string
name: string
output: string
}
/** The managed-cloud adapter successfully dispatched the prompt to its provider
* transport. Local binding/session/concurrency failures never emit this. */
export interface HostedRequestStartedEvent {
type: 'hosted_request_started'
}
export type AdapterStreamEvent =
| TextDeltaEvent
| ThinkingDeltaEvent
| ToolActivityEvent
| ToolResultDisplayEvent
| HostedRequestStartedEvent
export type AdapterEventSink = (event: AdapterStreamEvent) => void
// === Capabilities ============================================================
export interface AdapterCapabilities {
readonly resumeFidelity: ResumeFidelity
readonly supportsNativeResume: boolean
readonly supportsCancellation: boolean
readonly acknowledgesCancellation: boolean
readonly requiresPinnedWorker: boolean
readonly supportsModelSwitching: boolean
readonly supportsArtifactEmission: boolean
readonly supportsTools: boolean
readonly restartBehavior:
| 'native_bindings_survive'
| 'process_local_bindings_stale'
| 'attempts_orphaned'
}
export type AdapterCapabilityKey =
| 'nativeResume'
| 'cancellationDispatch'
| 'cancellationAck'
| 'pinnedWorker'
| 'modelSwitching'
| 'artifactEmission'
| 'toolSupport'
| 'restartOrphanSemantics'
export type AdapterCapabilityExpectationStatus = 'required' | 'unsupported' | 'known_limitation'
export interface AdapterCapabilityExpectation {
readonly status: AdapterCapabilityExpectationStatus
readonly reason: string
readonly followUpTicket?: string
}
/**
* Where an adapter's credentials come from. Windows ships local-user coding
* agents (Claude Code plus user-connected external ACP commands) and the
* `managed_cloud` default-chat adapter (pi-mono). The kernel's execution-policy
* boundary checks read this so a session pinned to a local provider can never be
* rerouted to a managed one (or vice versa).
*/
export type AdapterCredentialScope = 'managed_cloud' | 'local_user'
export interface AdapterCapabilityMatrixEntry {
readonly adapterId: string
readonly credentialScope: AdapterCredentialScope
readonly expectations: Record<AdapterCapabilityKey, AdapterCapabilityExpectation>
}
const required = (reason: string): AdapterCapabilityExpectation => ({ status: 'required', reason })
const unsupported = (reason: string): AdapterCapabilityExpectation => ({
status: 'unsupported',
reason
})
const knownLimitation = (reason: string, followUpTicket: string): AdapterCapabilityExpectation => ({
status: 'known_limitation',
reason,
followUpTicket
})
export const ADAPTER_CAPABILITY_MATRIX = {
// "acp" is Claude Code: the bundled @agentclientprotocol/claude-agent-acp bridge
// spawned as a node subprocess. The id stays "acp" for parity with macOS.
acp: {
adapterId: 'acp',
credentialScope: 'local_user',
expectations: {
nativeResume: required('ACP exposes native session ids and session/resume.'),
cancellationDispatch: required('ACP exposes session/cancel dispatch.'),
cancellationAck: knownLimitation(
'ACP cancellation is fire-and-forget; no terminal ack is exposed yet.',
'win-agents-cancel-ack'
),
pinnedWorker: unsupported(
'ACP bindings are resumable by native session id and do not require process-local pinning.'
),
modelSwitching: required('ACP supports session/set_model during open and resume.'),
artifactEmission: unsupported('ACP adapter does not emit artifact references yet.'),
toolSupport: required(
'ACP session/update tool events are projected into canonical adapter events.'
),
restartOrphanSemantics: required(
'Native-resumable bindings survive adapter restarts; active attempts are abandoned.'
)
}
},
openclaw: {
adapterId: 'openclaw',
credentialScope: 'local_user',
expectations: {
nativeResume: required(
'OpenClaw ACP exposes native sessions through the Gateway-backed ACP bridge.'
),
cancellationDispatch: required(
'OpenClaw ACP accepts cancellation through the shared ACP interrupt path.'
),
cancellationAck: knownLimitation(
'OpenClaw cancellation resolves locally without an independent adapter ack.',
'win-agents-cancel-ack'
),
pinnedWorker: unsupported(
'OpenClaw ACP sessions are native and do not require process-local pinned workers.'
),
modelSwitching: unsupported(
'OpenClaw ACP does not expose session/set_model; model selection is configured in the OpenClaw gateway/agent.'
),
artifactEmission: unsupported('OpenClaw ACP adapter does not emit artifact references yet.'),
toolSupport: unsupported(
'OpenClaw ACP rejects per-session MCP servers; Omi tools are unavailable until configured through the OpenClaw gateway/agent.'
),
restartOrphanSemantics: required(
'Native-resumable OpenClaw bindings survive adapter restarts; active attempts are abandoned.'
)
}
},
hermes: {
adapterId: 'hermes',
credentialScope: 'local_user',
expectations: {
// Hermes ACP sessions live in the running server's in-memory session
// manager and are only valid for that process.
nativeResume: unsupported(
'Hermes ACP session ids are process-local and are stale after adapter process restart.'
),
cancellationDispatch: required('Hermes supports cancellation dispatch for active attempts.'),
cancellationAck: knownLimitation(
'Hermes cancellation is dispatchable but no terminal adapter ack is exposed yet.',
'win-agents-cancel-ack'
),
pinnedWorker: required(
'Hermes keeps session state in the adapter process and must stay worker-pinned while active.'
),
modelSwitching: required('Hermes supports model selection during session open and resume.'),
artifactEmission: unsupported('Hermes ACP adapter does not emit artifact references yet.'),
toolSupport: required('Hermes projects tool calls through canonical adapter tool events.'),
restartOrphanSemantics: required(
'Process-local Hermes bindings are stale after adapter restarts; active attempts are abandoned.'
)
}
},
// Codex is net-new on Windows (no macOS precedent). Driven through the
// official ACP bridge (@agentclientprotocol/codex-acp) as a user-configured
// external command. Capabilities are conservative until verified against the
// real bridge — treat sessions as process-local like Hermes.
codex: {
adapterId: 'codex',
credentialScope: 'local_user',
expectations: {
nativeResume: knownLimitation(
'Codex ACP session persistence across bridge restarts is unverified; treated as process-local.',
'win-agents-codex-verify'
),
cancellationDispatch: required('Codex ACP accepts session/cancel dispatch.'),
cancellationAck: knownLimitation(
'Codex cancellation resolves locally without an independent adapter ack.',
'win-agents-cancel-ack'
),
pinnedWorker: required(
'Codex sessions are treated as process-local and must stay worker-pinned while active.'
),
modelSwitching: knownLimitation(
'Codex ACP session/set_model support is unverified; model selection is configured in the Codex CLI.',
'win-agents-codex-verify'
),
artifactEmission: unsupported('Codex ACP adapter does not emit artifact references yet.'),
toolSupport: required('Codex projects tool calls through canonical adapter tool events.'),
restartOrphanSemantics: required(
'Process-local Codex bindings are stale after adapter restarts; active attempts are abandoned.'
)
}
},
// pi-mono is the Omi-managed-cloud DEFAULT-CHAT engine (macOS parity). Unlike
// acp/openclaw/hermes/codex it is NOT a user-selectable coding agent — it is
// reached only through the default-chat (main_chat) path, never a pill or a
// delegated-task fallback (see PRODUCTION_ADAPTER_IDS below). Its matrix
// membership is what makes `isProductionAdapterId('pi-mono')` true, which pins
// its sessions to the `managed_cloud` provider boundary.
'pi-mono': {
adapterId: 'pi-mono',
credentialScope: 'managed_cloud',
expectations: {
nativeResume: unsupported(
'pi-mono session ids are process-local and are stale after daemon restart.'
),
cancellationDispatch: required('pi-mono supports abort dispatch for the active prompt.'),
cancellationAck: knownLimitation(
'pi-mono abort resolves locally without an independent adapter ack.',
'win-agents-cancel-ack'
),
pinnedWorker: required(
'pi-mono keeps session state in the adapter process and must stay worker-pinned while active.'
),
modelSwitching: required('pi-mono maps desktop model ids and sends set_model.'),
artifactEmission: unsupported('pi-mono runtime does not emit artifact references yet.'),
toolSupport: required('pi-mono uses the Omi extension/tool relay path for tools.'),
restartOrphanSemantics: required(
'Startup reconciliation orphans active attempts and marks non-resumable bindings stale.'
)
}
}
} as const satisfies Record<string, AdapterCapabilityMatrixEntry>
export type ProductionAdapterId = keyof typeof ADAPTER_CAPABILITY_MATRIX
/**
* The user-selectable coding agents surfaced as pills and usable as delegated-
* task fallbacks (== the shared `CodingAgentId` union). This intentionally
* EXCLUDES managed-cloud default-chat adapters like `pi-mono`: pi-mono's
* production-ness comes structurally from ADAPTER_CAPABILITY_MATRIX membership
* via `isProductionAdapterId`, NOT from this list. Do not add pi-mono here — it
* is the default-chat engine (reached via the `chatEngine` flag + main_chat
* routing), never a coding-agent pill or fallback.
*/
export const PRODUCTION_ADAPTER_IDS = [
'acp',
'openclaw',
'hermes',
'codex'
] as const satisfies readonly ProductionAdapterId[]
/**
* The user-selectable coding-agent ids (structurally == the shared `CodingAgentId`
* union). Narrower than `ProductionAdapterId`, which also includes managed-cloud
* default-chat adapters like `pi-mono`. Coding-agent-task code (taskRunner,
* failures) uses THIS so pi-mono can never leak into a pill, a task fallback, or
* a failure label.
*/
export type CodingAgentAdapterId = (typeof PRODUCTION_ADAPTER_IDS)[number]
export function isProductionAdapterId(adapterId: string): adapterId is ProductionAdapterId {
return Object.prototype.hasOwnProperty.call(ADAPTER_CAPABILITY_MATRIX, adapterId)
}
/**
* Windows ships no placeholder adapters (macOS's `a2a` scaffold is not ported;
* pi-mono IS ported as a real managed_cloud adapter, so it is not a placeholder).
* The kernel adapter-registry still calls this guard before registering a
* factory, so it exists for parity and always returns false.
*/
export function isPlaceholderAdapterId(_adapterId: string): boolean {
return false
}
export function adapterCredentialScopeFor(adapterId: ProductionAdapterId): AdapterCredentialScope {
return ADAPTER_CAPABILITY_MATRIX[adapterId].credentialScope
}
function restartBehaviorFor(
expectations: Record<AdapterCapabilityKey, AdapterCapabilityExpectation>
): AdapterCapabilities['restartBehavior'] {
if (expectations.nativeResume.status === 'required') return 'native_bindings_survive'
if (expectations.pinnedWorker.status === 'required') return 'process_local_bindings_stale'
return 'attempts_orphaned'
}
export function adapterCapabilitiesFor(adapterId: ProductionAdapterId): AdapterCapabilities {
const expectations = ADAPTER_CAPABILITY_MATRIX[adapterId].expectations
return {
resumeFidelity: expectations.nativeResume.status === 'required' ? 'native' : 'none',
supportsNativeResume: expectations.nativeResume.status === 'required',
supportsCancellation: expectations.cancellationDispatch.status === 'required',
acknowledgesCancellation: expectations.cancellationAck.status === 'required',
requiresPinnedWorker: expectations.pinnedWorker.status === 'required',
supportsModelSwitching: expectations.modelSwitching.status === 'required',
supportsArtifactEmission: expectations.artifactEmission.status === 'required',
supportsTools: expectations.toolSupport.status === 'required',
restartBehavior: restartBehaviorFor(expectations)
}
}
// === Prompt & tool shapes ====================================================
export type PromptBlock =
| { type: 'text'; text: string }
| { type: 'image'; data: string; mimeType: string }
export interface ToolDef {
name: string
description: string
inputSchema: Record<string, unknown>
}
// === Binding / attempt contracts =============================================
export interface OpenBindingInput {
/** Omi-owned correlation id. Adapters must not treat this as their native session id. */
sessionId: string
cwd: string
model?: string
systemPrompt?: string
mcpServers?: Record<string, unknown>[]
metadata?: Record<string, unknown>
}
export interface ResumeBindingInput extends OpenBindingInput {
/** Adapter-owned native session id recovered from the active binding. */
adapterNativeSessionId: string
}
export interface AdapterBindingHandle {
/**
* Kernel-owned persistent binding row id. Populated once the kernel
* (agentKernel/) persists a binding; unset for the pre-kernel in-memory task
* path and for freshly-opened handles the adapter returns. The worker pool
* keys pinned-worker reuse on this.
*/
bindingId?: string
/** Omi-owned correlation id. */
sessionId: string
adapterId: string
/** Adapter-owned native session id. */
adapterNativeSessionId: string
resumeFidelity: ResumeFidelity
cwd: string
model?: string
metadata?: Record<string, unknown>
}
export type OpenedBinding = AdapterBindingHandle
export interface AdapterAttemptContext {
/** Omi-owned correlation id for host bookkeeping only. */
sessionId: string
/**
* Host-owned identity fields. Optional so the pre-kernel in-memory task path
* (which has no owner/request/client context) still satisfies the contract;
* the kernel (agentKernel/) always supplies them. Adapter payloads must never
* override the ownerId — it is authoritative host identity (INV-AGENT).
*/
ownerId?: string
requestId?: string
clientId?: string
runId: string
attemptId: string
binding: AdapterBindingHandle
prompt: PromptBlock[]
mode: RunMode
model?: string
tools?: ToolDef[]
metadata?: Record<string, unknown>
}
export interface AdapterArtifactReference {
kind: string
role: ArtifactRole
uri: string
displayName?: string | null
mimeType?: string | null
contentHash?: string | null
sizeBytes?: number | null
metadata?: Record<string, unknown>
}
export interface AdapterAttemptResult {
text: string
costUsd?: number
inputTokens?: number
outputTokens?: number
cacheReadTokens?: number
cacheWriteTokens?: number
/** Adapter-owned native session id. */
adapterSessionId: string
terminalStatus: 'succeeded' | 'failed' | 'cancelled'
failure?: RuntimeFailure
artifacts?: AdapterArtifactReference[]
}
export interface CancelAttemptContext {
sessionId: string
/**
* Host-owned identity fields, same contract as AdapterAttemptContext: optional
* so the pre-kernel in-memory task path still satisfies it, always supplied by
* the kernel. Adapter payloads must never override the ownerId (INV-AGENT).
*/
ownerId?: string
requestId?: string
clientId?: string
runId?: string
attemptId?: string
binding?: AdapterBindingHandle
}
export interface CancelDispatchResult {
accepted: boolean
dispatchAttempted: boolean
adapterAcknowledged: boolean
message?: string
}
export interface RuntimeAdapter {
readonly adapterId: string
readonly capabilities: AdapterCapabilities
start(): Promise<void>
stop(): Promise<void>
openBinding(input: OpenBindingInput): Promise<OpenedBinding>
resumeBinding(input: ResumeBindingInput): Promise<OpenedBinding>
executeAttempt(
context: AdapterAttemptContext,
sink: AdapterEventSink,
signal: AbortSignal
): Promise<AdapterAttemptResult>
cancelAttempt(context: CancelAttemptContext): Promise<CancelDispatchResult>
closeBinding?(binding: AdapterBindingHandle): Promise<void>
/**
* Return the MCP server configuration this adapter actually passes to its
* underlying session. Adapters that strip per-session MCP servers (e.g.
* OpenClaw, which rejects them) should return an empty array so the kernel's
* binding-compatibility hash reflects what the adapter truly saw. Adapters
* that pass MCP servers through unchanged omit this; the kernel treats an
* absent implementation as identity (passthrough).
*/
effectiveMcpServers?(mcpServers: Record<string, unknown>[]): Record<string, unknown>[]
}
// === Contract assertions =====================================================
// Guard against the id-conflation bugs macOS's tests caught: an adapter must
// never echo the Omi correlation id back as its native session id.
export function assertAdapterBindingContract(
binding: AdapterBindingHandle,
operation: string
): void {
if (!binding.adapterNativeSessionId) {
throw new Error(`${operation} returned an empty adapterNativeSessionId`)
}
if (binding.adapterNativeSessionId === binding.sessionId) {
throw new Error(
`${operation} conflated Omi sessionId ${binding.sessionId} with adapterNativeSessionId`
)
}
}
export function assertAdapterAttemptResultContract(
context: AdapterAttemptContext,
result: AdapterAttemptResult,
operation: string
): void {
if (!result.adapterSessionId) {
throw new Error(`${operation} returned an empty adapterSessionId`)
}
if (result.adapterSessionId === context.sessionId) {
throw new Error(
`${operation} conflated Omi sessionId ${context.sessionId} with adapter native session id`
)
}
if (result.adapterSessionId !== context.binding.adapterNativeSessionId) {
throw new Error(
`${operation} returned adapterSessionId ${result.adapterSessionId} for binding ${context.binding.adapterNativeSessionId}`
)
}
}