forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkernelCore.ts
More file actions
2252 lines (2158 loc) · 74.9 KB
/
Copy pathkernelCore.ts
File metadata and controls
2252 lines (2158 loc) · 74.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
// KernelCore — Windows port of the macOS agent runtime's kernel-core.ts
// (desktop/macos/agent/src/runtime/kernel-core.ts).
//
// The bottom of the kernel class chain:
// KernelCore -> KernelRuns -> KernelArtifacts -> KernelSessions -> AgentRuntimeKernel
//
// It owns the run/attempt/binding state machine — accepting a run, resolving (or
// opening, resuming, replacing) the adapter binding, assembling the turn prompt,
// dispatching the attempt to a pooled worker, and recording every terminal
// transition as a persisted event. Everything above it is API surface over these
// primitives.
//
// INV-AGENT: the Omi-owned `sessionId` and the adapter-owned
// `adapterNativeSessionId` are distinct throughout; `createAttempt` refuses a
// second active attempt on a run (single-active-run enforcement); and the
// provider boundary of a session is re-checked on every accepted run so a session
// can never be rerouted to a different credential scope.
//
// Windows delta: the kernel runs in-process in Electron main, so there is no
// JSONL/stdio transport — subscribers receive persisted AgentEvents directly.
import type {
AdapterAttemptResult,
AdapterBindingHandle,
AdapterStreamEvent,
RuntimeAdapter
} from '../codingAgent/interface'
import { homedir } from 'node:os'
import { AdapterRegistry } from './adapterRegistry'
import { failureFromError, type RuntimeFailure } from '../codingAgent/failures'
import { generateAgentId } from './store'
import { resolveSurfaceSession, type SurfaceRef } from './surfaceSession'
import {
advanceBindingTurnDelivery,
appendConversationTurn,
conversationIdForSession
} from './conversationTurns'
import {
acknowledgeCompletionDelta,
assembleTurnContext,
bindingCarriesNativeHistory,
type TurnContextServices
} from './turnContext'
import type {
AdapterBinding,
AgentArtifact,
AgentDelegation,
AgentEvent,
AgentExecutionRole,
AgentRun,
AgentSession,
AgentStore,
AttemptStatus,
DelegationStatus,
DesktopArtifactDelivery,
DesktopAttentionOverride,
DesktopCoordinatorDispatch,
DesktopMemoryCandidate,
DesktopTaskCandidate,
NewAgentArtifact,
RunAttempt,
RunStatus
} from './types'
import type { QueueRunInput } from './desktopActionQueue'
import type {
BuiltDesktopContextPacket,
DesktopContextPacketBuildInput
} from './desktopContextPacket'
import type {
DesktopIntentRoute,
DesktopIntentRouteInput,
DesktopIntentSessionCandidate
} from './desktopIntentRouter'
import { OmiArtifactStorage } from './artifactStorage'
import {
ACTIVE_STATUSES,
DEFAULT_DELEGATION_MAX_BUDGET_USD,
DEFAULT_DELEGATION_MAX_DEPTH,
HARD_DELEGATION_MAX_BUDGET_USD,
HARD_DELEGATION_MAX_DEPTH,
KERNEL_MCP_PROTOCOL_VERSION,
TERMINAL_STATUSES,
artifactFromRow,
attemptColumnMap,
attemptFromRow,
bindingColumnMap,
bindingFromRow,
bindingMetadata,
boundedLimit,
canonicalAdapterEventType,
delegationFromRow,
delegationValues,
desktopArtifactDeliveryFromRow,
desktopAttentionOverrideFromRow,
desktopDispatchFromRow,
desktopMemoryCandidateFromRow,
desktopTaskCandidateFromRow,
eventFromRow,
intentCandidateStatus,
isStaleBindingError,
mcpServersForBinding,
messageFrom,
nullableNumber,
nullableString,
numberValue,
parseJsonObject,
placeholders,
queueRunGoalText,
refreshMcpAttemptContext,
requiresVerifiedContextDispatch,
runColumnMap,
runFromRow,
sessionFromRow,
stableHash,
stableJsonHash,
stableMcpServerConfig,
stringValue,
updateByColumns
} from './kernelSupport'
import type {
AgentRuntimeKernelOptions,
DelegateAgentInput,
DelegateAgentResult,
ExecuteAgentRunInput,
InspectArtifactsInput,
KernelEventSubscriber,
KernelRunResult,
KernelSessionResolutionInput,
KernelSessionSummary,
ListSessionsInput,
PersistArtifactInput,
UpdateArtifactLifecycleInput
} from './kernelTypes'
import { StaleAdapterBindingError } from './kernelTypes'
import {
executionRoleForSurface,
providerBoundaryForAdapter,
resolveAdapterWithinBoundary
} from './executionPolicy'
interface ActiveExecution {
adapter: RuntimeAdapter
abortController: AbortController
binding: AdapterBindingHandle
attemptId: string
sessionId: string
}
/**
* A sane, writable fallback cwd for an agent run/binding that specifies none.
*
* `process.cwd()` is wrong in a packaged app: launched from a Start-menu shortcut
* its working directory is the shortcut's "Start in" dir — often `C:\Windows\System32`
* or another unwritable/surprising path — not the repo dir it is in `pnpm dev`. That
* silently changed where a no-cwd agent run executed (dev vs packaged). The user's
* home dir is a stable, writable default on every platform. Pure (node `os` only) so
* kernelCore stays electron-free and hermetically testable; `process.cwd()` remains
* the last resort only if homedir() is somehow empty.
*/
export function fallbackCwd(): string {
return homedir() || process.cwd()
}
export class KernelCore {
protected readonly store: AgentStore
protected readonly registry: AdapterRegistry
protected readonly runtimeNodeId: string
protected readonly artifactStorage?: OmiArtifactStorage
protected readonly recoverRunInput?: AgentRuntimeKernelOptions['recoverRunInput']
protected readonly controlMcpServers?: AgentRuntimeKernelOptions['controlMcpServers']
protected readonly subscribers = new Set<KernelEventSubscriber>()
protected readonly activeExecutions = new Map<string, ActiveExecution>()
protected readonly bindingResolutionLocks = new Map<string, Promise<void>>()
private transactionDepth = 0
private pendingSubscriberEvents: AgentEvent[] = []
constructor(options: AgentRuntimeKernelOptions) {
this.store = options.store
this.registry = options.registry
this.runtimeNodeId = options.runtimeNodeId ?? 'desktop-local'
this.artifactStorage = options.artifactStorage
this.recoverRunInput = options.recoverRunInput
this.controlMcpServers = options.controlMcpServers
}
/**
* The MCP servers a binding is opened/resumed with: the caller's own, plus the
* agent-control server that makes the control plane reachable by the model.
*
* The control server is deliberately NOT part of `bindingMetadata`'s hash — that
* hashes `input.mcpServers` only — so adding it does not invalidate binding
* reuse, and its per-binding pipe/token env is already excluded from the hash by
* `REQUEST_SCOPED_MCP_ENV_KEYS`.
*/
protected bindingMcpServers(
input: ExecuteAgentRunInput,
sessionId: string,
adapterId: string
): Record<string, unknown>[] {
return [
...mcpServersForBinding(input.mcpServers ?? [], sessionId, adapterId, this.runtimeNodeId),
...(this.controlMcpServers?.(sessionId, adapterId) ?? [])
]
}
subscribe(subscriber: KernelEventSubscriber): () => void {
this.subscribers.add(subscriber)
return () => this.subscribers.delete(subscriber)
}
protected createAcceptedRun(input: ExecuteAgentRunInput): {
session: AgentSession
run: AgentRun
} {
return this.withTransaction(() => {
const session = this.resolveSession(input)
resolveAdapterWithinBoundary({
providerBoundary: session.providerBoundary,
defaultAdapterId: session.defaultAdapterId,
requestedAdapterId: input.adapterId ?? session.defaultAdapterId
})
const run = this.store.insertRun({
sessionId: session.sessionId,
parentRunId: input.parentRunId ?? null,
clientId: input.clientId,
requestId: input.requestId,
status: 'queued',
mode: input.mode ?? 'ask',
inputJson: JSON.stringify({
prompt: input.prompt,
systemPrompt: input.systemPrompt ?? '',
metadata: input.metadata ?? {}
}),
requestedModelId: input.model ?? null,
cwd: input.cwd ?? session.defaultCwd
})
this.appendEvent({
sessionId: session.sessionId,
runId: run.runId,
type: 'run.queued',
payload: { runId: run.runId, requestId: run.requestId, clientId: run.clientId }
})
this.touchSession(session.sessionId)
return { session, run }
})
}
protected async executeAcceptedRun(
input: ExecuteAgentRunInput,
accepted: { session: AgentSession; run: AgentRun }
): Promise<KernelRunResult> {
const adapterId = input.adapterId ?? accepted.session.defaultAdapterId
if (!input.recoverAfterError) {
const recovery = this.recoverRunInput?.(adapterId)
if (recovery) {
input = {
...input,
maxAttempts: input.maxAttempts ?? recovery.maxAttempts,
recoverAfterError: recovery.recoverAfterError
}
}
}
const maxAttempts = Math.max(1, input.maxAttempts ?? 2)
let retryReason: string | null = null
let resumeFromAttemptId: string | null = null
let lastAttempt: RunAttempt | undefined
let completionDeltaArtifacts: AgentArtifact[] = []
const surfaceRef = this.surfaceRefForInput(input)
const conversationId = conversationIdForSession(this.store, accepted.session.sessionId)
for (let attemptNo = 1; attemptNo <= maxAttempts; attemptNo += 1) {
const attempt = this.createAttempt({
runId: accepted.run.runId,
attemptNo,
adapterId,
retryReason,
resumeFromAttemptId
})
lastAttempt = attempt
const attemptInput = this.inputWithManagedArtifactCwd(
input,
accepted.session,
accepted.run.runId,
attempt.attemptId
)
if (
attemptInput.cwd &&
attemptInput.cwd !== (input.cwd ?? accepted.session.defaultCwd ?? undefined)
) {
this.withTransaction(() => {
this.updateRun(accepted.run.runId, { cwd: attemptInput.cwd, updatedAtMs: Date.now() })
})
}
if (!this.registry.has(adapterId)) {
const failure: RuntimeFailure = {
code: 'adapter_not_registered',
source: 'runtime',
adapterId,
retryable: false,
userMessage: `Adapter not registered: ${adapterId}`,
technicalMessage: `Adapter not registered: ${adapterId}`
}
this.failAttemptBeforeExecution(
attempt,
'adapter_not_registered',
failure.userMessage,
false,
failure
)
break
}
const pool = this.registry.get(adapterId)
let binding: AdapterBinding
let handle: AdapterBindingHandle
let bindingResolutionProtectedBindingId: string | null = null
try {
const resolved = await this.withBindingResolutionLock(
accepted.session.sessionId,
adapterId,
async () => {
const existingBinding = this.readActiveBinding(accepted.session.sessionId, adapterId)
const bindingQueueKey = existingBinding
? this.handleForExistingBinding(existingBinding)
: undefined
return pool.runExclusiveQueued(
bindingQueueKey,
`${attempt.attemptId}:binding`,
async (worker) => {
const resolved = await this.resolveBindingForAttempt({
input: attemptInput,
session: accepted.session,
adapter: worker.adapter,
attempt,
adapterId
})
if (worker.adapter.capabilities.requiresPinnedWorker) {
if (resolved.replacesBindingId) {
worker.replacePinnedBinding(resolved.replacesBindingId, resolved.handle)
} else {
worker.pinBinding(resolved.handle)
}
}
return resolved
},
{
...(bindingQueueKey
? {}
: {
onIdlePinnedBindingEvicted: (evictedBindingId: string) => {
this.markEvictedBindingStale(evictedBindingId, 'pinned_worker_reassigned')
}
}),
protectPinnedBindingAfterWork: true
}
)
}
)
binding = resolved.binding
handle = resolved.handle
bindingResolutionProtectedBindingId = pool.requiresPinnedWorkers
? (handle.bindingId ?? null)
: null
} catch (error) {
pool.unprotectPinnedBinding(bindingResolutionProtectedBindingId)
if (isStaleBindingError(error)) {
const failure = failureFromError(error, {
code: 'stale_binding',
source: 'adapter_process',
adapterId: attempt.adapterId,
retryable: attemptNo < maxAttempts
})
this.failAttemptBeforeExecution(
attempt,
'stale_binding',
failure.userMessage,
attemptNo < maxAttempts,
failure
)
retryReason = 'stale_binding'
resumeFromAttemptId = attempt.attemptId
continue
}
if (
await this.tryRecoverAttempt(
input,
attempt,
error,
'binding_failed',
attemptNo < maxAttempts
)
) {
retryReason = 'recoverable_error'
resumeFromAttemptId = attempt.attemptId
continue
}
const failure = failureFromError(error, {
code: 'binding_failed',
source: 'adapter_process',
adapterId: attempt.adapterId,
retryable: false
})
this.failAttemptBeforeExecution(
attempt,
'binding_failed',
failure.userMessage,
false,
failure
)
break
}
const abortController = new AbortController()
const protectedPinnedBindingId = pool.requiresPinnedWorkers ? handle.bindingId : null
pool.protectPinnedBinding(protectedPinnedBindingId)
let effectivePrompt = attemptInput.prompt
let effectivePromptBlocks = attemptInput.promptBlocks
let acknowledgedCompletionDelta: {
ids: string[]
completedAtHighWaterMs?: number
} | null = null
if (surfaceRef && conversationId) {
const assembled = assembleTurnContext({
store: this.store,
services: this.turnContextServices(),
ownerId: input.ownerId,
sessionId: accepted.session.sessionId,
conversationId,
surfaceRef,
executionRole: accepted.session.executionRole,
userText: input.prompt,
attachmentMetadataJson: input.attachmentMetadataJson,
surfaceContextJson: input.surfaceContextJson,
imagePresent: Boolean(input.imagePresent),
bindingCarriesNativeHistory: bindingCarriesNativeHistory(binding),
lastDeliveredTurnCreatedAtMs: binding.lastDeliveredTurnCreatedAtMs,
runId: accepted.run.runId
})
effectivePrompt = assembled.prompt
effectivePromptBlocks = attemptInput.promptBlocks
? attemptInput.promptBlocks.map((block) =>
block.type === 'text' ? { ...block, text: assembled.prompt } : block
)
: undefined
completionDeltaArtifacts = assembled.completionDeltaArtifacts
if (assembled.acknowledgedCompletionDeltaIds.length > 0) {
acknowledgedCompletionDelta = {
ids: assembled.acknowledgedCompletionDeltaIds,
completedAtHighWaterMs:
assembled.completionDeltaArtifacts
.map((artifact) => artifact.createdAtMs)
.reduce((max, value) => Math.max(max, value), 0) || undefined
}
}
}
if (conversationId && surfaceRef && attemptNo === 1) {
appendConversationTurn(this.store, {
conversationId,
role: 'user',
surfaceKind: surfaceRef.surfaceKind,
content: input.prompt,
createdAtMs: Date.now(),
metadataJson: JSON.stringify({ runId: accepted.run.runId })
})
advanceBindingTurnDelivery(this.store, binding.bindingId, conversationId)
}
try {
const result = await pool.runExclusiveQueued(handle, attempt.attemptId, async (worker) => {
if (this.runStatus(accepted.run.runId) === 'cancelling') {
throw new Error('cancelled_before_adapter_dispatch')
}
this.activeExecutions.set(accepted.run.runId, {
adapter: worker.adapter,
abortController,
binding: handle,
attemptId: attempt.attemptId,
sessionId: accepted.session.sessionId
})
refreshMcpAttemptContext(
mcpServersForBinding(
input.mcpServers ?? [],
accepted.session.sessionId,
adapterId,
this.runtimeNodeId
),
{
ownerId: input.ownerId,
requestId: accepted.run.requestId,
clientId: accepted.run.clientId,
protocolVersion: KERNEL_MCP_PROTOCOL_VERSION,
sessionId: accepted.session.sessionId,
runId: accepted.run.runId,
attemptId: attempt.attemptId,
adapterSessionId: handle.adapterNativeSessionId
}
)
this.markAttemptRunning(attempt, binding)
return worker.adapter.executeAttempt(
{
sessionId: accepted.session.sessionId,
ownerId: input.ownerId,
requestId: accepted.run.requestId,
clientId: accepted.run.clientId,
runId: accepted.run.runId,
attemptId: attempt.attemptId,
binding: handle,
prompt: effectivePromptBlocks ?? [{ type: 'text', text: effectivePrompt }],
mode: input.mode ?? 'ask',
model: input.model,
tools: input.tools ?? [],
metadata: input.metadata
},
(event) =>
this.persistAdapterEvent(
accepted.session.sessionId,
accepted.run.runId,
attempt.attemptId,
event
),
abortController.signal
)
})
this.activeExecutions.delete(accepted.run.runId)
if (acknowledgedCompletionDelta && surfaceRef) {
acknowledgeCompletionDelta(this.store, {
ownerId: input.ownerId,
surfaceRef,
ids: acknowledgedCompletionDelta.ids,
completedAtHighWaterMs: acknowledgedCompletionDelta.completedAtHighWaterMs ?? null
})
}
const completed = this.completeAttemptAndRun(
accepted.session,
accepted.run.runId,
attempt,
binding,
result,
{
conversationId,
surfaceKind: surfaceRef?.surfaceKind ?? accepted.session.surfaceKind
}
)
return { ...completed, completionDeltaArtifacts }
} catch (error) {
this.activeExecutions.delete(accepted.run.runId)
if (isStaleBindingError(error)) {
this.markBindingStale(binding, attempt, messageFrom(error))
const failure = failureFromError(error, {
code: 'stale_binding',
source: 'adapter_execution',
adapterId: attempt.adapterId,
retryable: attemptNo < maxAttempts
})
this.failAttemptBeforeExecution(
attempt,
'stale_binding',
failure.userMessage,
attemptNo < maxAttempts,
failure
)
retryReason = 'stale_binding'
resumeFromAttemptId = attempt.attemptId
continue
}
if (
await this.tryRecoverAttempt(
input,
attempt,
error,
'adapter_execution_failed',
attemptNo < maxAttempts
)
) {
retryReason = 'recoverable_error'
resumeFromAttemptId = attempt.attemptId
continue
}
const wasCancelling = this.runStatus(accepted.run.runId) === 'cancelling'
const status: AttemptStatus = wasCancelling ? 'cancelled' : 'failed'
const failure = wasCancelling
? null
: failureFromError(error, {
code: 'adapter_execution_failed',
source: 'adapter_execution',
adapterId: attempt.adapterId,
retryable: false
})
this.finishAttemptAndRun({
sessionId: accepted.session.sessionId,
runId: accepted.run.runId,
attemptId: attempt.attemptId,
status,
finalText: null,
errorCode: wasCancelling ? null : 'adapter_execution_failed',
errorMessage: failure?.userMessage ?? null,
failure
})
break
} finally {
pool.unprotectPinnedBinding(protectedPinnedBindingId)
}
}
const finalRun = this.readRun(accepted.run.runId)
const attempt = lastAttempt ?? this.readLatestAttempt(accepted.run.runId)
return {
session: accepted.session,
run: finalRun,
attempt,
artifacts: this.readArtifacts({ runId: accepted.run.runId, limit: 50 }),
adapterSessionId: null,
terminalStatus: finalRun.status === 'cancelled' ? 'cancelled' : 'failed',
text: finalRun.finalText ?? '',
completionDeltaArtifacts
}
}
/**
* The `this`-cast service host that lets turn-context call back up the class
* chain. `listSessions` lands on KernelSessions, `inspectArtifacts` on
* KernelArtifacts, and `persistDesktopContextPacket` / `routeDesktopIntent` on
* AgentRuntimeKernel — none of which exist at this level. Ported from macOS
* as-is; the recursion is real and resolves at construction time because only a
* fully-built AgentRuntimeKernel is ever instantiated.
*/
protected turnContextServices(): TurnContextServices {
const host = this as unknown as KernelCore & {
persistDesktopContextPacket(
packetInput: DesktopContextPacketBuildInput
): BuiltDesktopContextPacket
routeDesktopIntent(
routeInput: Omit<DesktopIntentRouteInput, 'nowMs' | 'actionQueue' | 'sessionCandidates'> & {
ownerId?: string
}
): DesktopIntentRoute
listSessions(listInput: ListSessionsInput): KernelSessionSummary[]
inspectArtifacts(inspectInput: InspectArtifactsInput): AgentArtifact[]
}
return {
persistDesktopContextPacket: (packetInput: DesktopContextPacketBuildInput) =>
host.persistDesktopContextPacket(packetInput),
routeDesktopIntent: (routeInput: Parameters<typeof host.routeDesktopIntent>[0]) =>
host.routeDesktopIntent(routeInput),
listSessions: (listInput: ListSessionsInput) => host.listSessions(listInput),
inspectArtifacts: (inspectInput: InspectArtifactsInput) => host.inspectArtifacts(inspectInput)
}
}
protected surfaceRefForInput(input: ExecuteAgentRunInput): SurfaceRef | null {
if (!input.surfaceKind || !input.externalRefKind || !input.externalRefId) return null
return {
surfaceKind: input.surfaceKind,
externalRefKind: input.externalRefKind,
externalRefId: input.externalRefId
}
}
protected validateSensitiveContextDispatches(input: DesktopContextPacketBuildInput): void {
for (const snippet of input.snippets) {
if (snippet.selected === false || !requiresVerifiedContextDispatch(snippet)) continue
const dispatchId = snippet.dispatchId?.trim()
if (!dispatchId) {
throw new Error(`Sensitive context snippet ${snippet.snippetId} requires a dispatch id`)
}
const row = this.store.getOptionalRow(
'SELECT * FROM desktop_dispatches WHERE dispatch_id = ? AND owner_id = ?',
[dispatchId, input.ownerId]
)
if (!row) {
throw new Error(`Sensitive context dispatch ${dispatchId} was not found for owner`)
}
const dispatch = desktopDispatchFromRow(row)
const resolution = parseJsonObject(dispatch.resolutionJson)
if (!['approval', 'screen_context'].includes(dispatch.kind)) {
throw new Error(`Sensitive context dispatch ${dispatchId} has invalid kind`)
}
if (dispatch.status !== 'resolved' || resolution.decision !== 'allow') {
throw new Error(`Sensitive context dispatch ${dispatchId} is not approved`)
}
if (dispatch.operation && dispatch.operation !== snippet.operation) {
throw new Error(`Sensitive context dispatch ${dispatchId} operation does not match snippet`)
}
}
}
protected createDelegatedRun(
parentSession: AgentSession,
parentRun: AgentRun,
childRunInput: ExecuteAgentRunInput,
input: DelegateAgentInput
): { session: AgentSession; run: AgentRun; delegation: AgentDelegation } {
return this.withTransaction(() => {
const session = this.resolveSession(childRunInput)
if (session.sessionId === parentSession.sessionId) {
throw new Error('Delegated child session must be distinct from parent session')
}
const run = this.store.insertRun({
sessionId: session.sessionId,
parentRunId: parentRun.runId,
clientId: childRunInput.clientId,
requestId: childRunInput.requestId,
status: 'queued',
mode: childRunInput.mode ?? 'ask',
inputJson: JSON.stringify({
prompt: childRunInput.prompt,
systemPrompt: childRunInput.systemPrompt ?? '',
metadata: childRunInput.metadata ?? {}
}),
requestedModelId: childRunInput.model ?? null,
cwd: childRunInput.cwd ?? session.defaultCwd
})
const now = Date.now()
const delegation: AgentDelegation = {
delegationId: generateAgentId('delegation'),
parentSessionId: parentSession.sessionId,
parentRunId: parentRun.runId,
childSessionId: session.sessionId,
childRunId: run.runId,
mode: input.mode,
status: 'pending',
objective: input.objective,
requestJson: JSON.stringify({
mode: input.mode,
objective: input.objective,
contextProvided: Boolean(input.context),
childSurfaceKind: childRunInput.surfaceKind,
childExternalRefKind: childRunInput.externalRefKind ?? null,
childExternalRefId: childRunInput.externalRefId ?? null,
maxDepth: input.maxDepth ?? DEFAULT_DELEGATION_MAX_DEPTH,
maxBudgetUsd: input.maxBudgetUsd ?? DEFAULT_DELEGATION_MAX_BUDGET_USD
}),
resultArtifactId: null,
createdAtMs: now,
completedAtMs: null
}
this.store.execute(
`INSERT INTO delegations (
delegation_id, parent_session_id, parent_run_id, child_session_id, child_run_id,
mode, status, objective, request_json, result_artifact_id, created_at_ms, completed_at_ms
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
delegationValues(delegation)
)
this.appendEvent({
sessionId: parentSession.sessionId,
runId: parentRun.runId,
type: 'delegation.created',
payload: {
delegationId: delegation.delegationId,
mode: delegation.mode,
childSessionId: session.sessionId,
childRunId: run.runId
}
})
this.appendEvent({
sessionId: session.sessionId,
runId: run.runId,
type: 'run.queued',
payload: {
runId: run.runId,
requestId: run.requestId,
clientId: run.clientId,
parentRunId: parentRun.runId,
delegationId: delegation.delegationId
}
})
this.touchSession(session.sessionId)
return { session, run, delegation }
})
}
protected async executeDelegationAsync(
childRunInput: ExecuteAgentRunInput,
created: { session: AgentSession; run: AgentRun; delegation: AgentDelegation },
markRunning = true
): Promise<DelegateAgentResult> {
if (markRunning) {
created = {
...created,
delegation: this.updateDelegationStatus(created.delegation, 'running')
}
}
const result = await this.executeAcceptedRun(childRunInput, {
session: created.session,
run: created.run
})
const status = result.terminalStatus === 'succeeded' ? 'succeeded' : result.terminalStatus
const delegation = this.updateDelegationStatus(created.delegation, status)
const artifacts = this.readArtifacts({ runId: result.run.runId, limit: 50 })
return {
delegation,
childSession: result.session,
childRun: result.run,
childAttempt: result.attempt,
adapterSessionId: result.adapterSessionId,
terminalStatus: result.terminalStatus,
result: {
summary: result.text,
artifacts,
verifiedEffects: [],
openQuestions: [],
usage: {
inputTokens: result.run.inputTokens,
outputTokens: result.run.outputTokens,
cacheReadTokens: result.run.cacheReadTokens,
cacheWriteTokens: result.run.cacheWriteTokens,
costUsd: result.run.costUsd
}
}
}
}
protected updateDelegationStatus(
delegation: AgentDelegation,
status: DelegationStatus,
errorMessage?: string
): AgentDelegation {
const now = Date.now()
this.withTransaction(() => {
this.store.execute(
`UPDATE delegations
SET status = ?, completed_at_ms = ?, result_artifact_id = result_artifact_id
WHERE delegation_id = ?`,
[status, status === 'running' || status === 'pending' ? null : now, delegation.delegationId]
)
if (status !== 'running') {
this.appendEvent({
sessionId: delegation.parentSessionId,
runId: delegation.parentRunId,
type: 'delegation.completed',
payload: {
delegationId: delegation.delegationId,
childSessionId: delegation.childSessionId,
childRunId: delegation.childRunId,
status,
errorMessage
}
})
}
})
return this.readDelegation(delegation.delegationId)
}
protected assertDelegationConstraints(input: DelegateAgentInput): void {
const maxDepth = input.maxDepth ?? DEFAULT_DELEGATION_MAX_DEPTH
if (!Number.isInteger(maxDepth) || maxDepth < 1 || maxDepth > HARD_DELEGATION_MAX_DEPTH) {
throw new Error(`Delegation maxDepth must be between 1 and ${HARD_DELEGATION_MAX_DEPTH}`)
}
const maxBudgetUsd = input.maxBudgetUsd ?? DEFAULT_DELEGATION_MAX_BUDGET_USD
if (
!Number.isFinite(maxBudgetUsd) ||
maxBudgetUsd <= 0 ||
maxBudgetUsd > HARD_DELEGATION_MAX_BUDGET_USD
) {
throw new Error(
`Delegation maxBudgetUsd must be greater than 0 and at most ${HARD_DELEGATION_MAX_BUDGET_USD}`
)
}
const parentDepth = this.delegationDepth(input.parentRunId)
if (parentDepth + 1 > maxDepth) {
throw new Error(`Delegation depth ${parentDepth + 1} exceeds maxDepth ${maxDepth}`)
}
}
/**
* The execution role a new session gets. An explicit role from the caller wins
* (spawnBackgroundAgent and delegateAgent both pass 'leaf'); otherwise it is
* DERIVED FROM THE SURFACE, never defaulted to 'coordinator'.
*
* macOS derives this at its transport boundary (jsonl-transport.ts calls
* executionRoleForSurface on every inbound run). Windows runs the kernel
* in-process and has no transport, so there is no single chokepoint above this
* one — the kernel itself must be the funnel. Without this, a run created
* directly on a leaf surface (background_agent / delegated_agent / floating_bar
* pill) silently became a coordinator and kept coordinator spawn rights for the
* life of the session, defeating the INV-AGENT leaf guard.
*/
protected executionRoleFor(input: KernelSessionResolutionInput): AgentExecutionRole {
return (
input.executionRole ??
executionRoleForSurface({
surfaceKind: input.surfaceKind,
externalRefKind: input.externalRefKind
})
)
}
protected resolveSession(input: KernelSessionResolutionInput): AgentSession {
// An explicit canonical session is authoritative even when the caller also
// supplies a new surface reference. This is how one long-running thread can
// move between task scopes without silently forking its runtime identity.
if (input.sessionId) {
const existing = this.findExistingSession(input)
if (existing) return existing
}
if (input.surfaceKind && input.externalRefKind && input.externalRefId) {
const resolved = resolveSurfaceSession(
this.store,
{
ownerId: input.ownerId,
surfaceRef: {
surfaceKind: input.surfaceKind,
externalRefKind: input.externalRefKind,
externalRefId: input.externalRefId
},
defaultAdapterId: input.defaultAdapterId,
executionRole: this.executionRoleFor(input),
providerBoundary: input.providerBoundary,
title: input.title ?? null
},
() => Date.now()
)
const session = this.readSession(resolved.agentSessionId)
const hasCreationEvent = this.store.getOptionalRow(
"SELECT event_id FROM events WHERE session_id = ? AND type = 'session.created' LIMIT 1",
[session.sessionId]
)
if (!hasCreationEvent) {
this.appendEvent({
sessionId: session.sessionId,
type: 'session.created',
payload: {
sessionId: session.sessionId,
ownerId: session.ownerId,
surfaceKind: session.surfaceKind
}
})
}
return session
}
const existing = this.findExistingSession(input)
if (existing) return existing
const session = this.store.insertSession({
ownerId: input.ownerId,
surfaceKind: input.surfaceKind,
externalRefKind: input.externalRefKind ?? null,
externalRefId: input.externalRefId ?? null,
title: input.title ?? null,
defaultAdapterId: input.defaultAdapterId ?? 'acp',
executionRole: this.executionRoleFor(input),
providerBoundary:
input.providerBoundary ?? providerBoundaryForAdapter(input.defaultAdapterId ?? 'acp')
})
this.appendEvent({
sessionId: session.sessionId,
type: 'session.created',
payload: {
sessionId: session.sessionId,
ownerId: session.ownerId,
surfaceKind: session.surfaceKind
}
})
return session
}
protected findExistingSession(input: KernelSessionResolutionInput): AgentSession | undefined {
if (input.sessionId) {
const session = this.readSession(input.sessionId)
if (session.ownerId !== input.ownerId) {
throw new Error(`Session ${input.sessionId} does not belong to owner ${input.ownerId}`)
}
return session
}
if (input.surfaceKind && input.externalRefKind && input.externalRefId) {
const mapped = this.store.getOptionalRow(
`SELECT agent_session_id FROM surface_conversations
WHERE owner_id = ? AND surface_kind = ? AND external_ref_kind = ? AND external_ref_id = ?`,
[input.ownerId, input.surfaceKind, input.externalRefKind, input.externalRefId]
)
if (mapped) {
return this.readSession(String(mapped.agent_session_id))
}
}
if (input.externalRefKind && input.externalRefId) {
const row = this.store.getOptionalRow(
'SELECT * FROM sessions WHERE owner_id = ? AND external_ref_kind = ? AND external_ref_id = ?',
[input.ownerId, input.externalRefKind, input.externalRefId]
)
if (row) return sessionFromRow(row)
return undefined
}
return undefined
}
protected findInvalidationSessionIds(input: KernelSessionResolutionInput): string[] {
if (input.sessionId || input.externalRefKind || input.externalRefId) {
return []
}
return this.store
.allRows('SELECT session_id FROM sessions WHERE owner_id = ?', [input.ownerId])
.map((row) => String(row.session_id))
}
protected createAttempt(input: {
runId: string
attemptNo: number
adapterId: string