forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontrolTools.ts
More file actions
1423 lines (1356 loc) · 55.5 KB
/
Copy pathcontrolTools.ts
File metadata and controls
1423 lines (1356 loc) · 55.5 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
// Agent-control tool dispatch — Windows port of the macOS agent runtime's
// control-tools.ts (desktop/macos/agent/src/runtime/).
//
// Zod schemas for the 18 manifest tools, the `handleAgentControlToolCall`
// dispatch switch, and the entity serializers. This is the single boundary every
// control-tool call passes through, and therefore the enforcement point for the
// INV-AGENT leaf-role guard (see `assertLeafControlToolsAllowed` below).
//
// Windows deltas from the macOS original:
// - No JSONL/stdio transport. The kernel runs in-process in Electron main, so
// tool results return by direct function call. macOS' tool-correlation.ts
// (which maps a tool call back onto an outbound protocol message) has no
// equivalent and is deliberately not ported.
// - No `buildMcpServers`. macOS builds MCP server configs to hand to a
// subprocess ACP adapter over that same transport. Windows does not host an
// MCP server, so control-initiated runs pass no `mcpServers` — the kernel's
// input types already treat it as optional.
// - The five `*_workstream_continuity` internal RPCs are not ported (the
// workstream model is owned by another track). This file therefore has 18
// schemas, not macOS' 23.
import { randomUUID } from 'node:crypto'
import { z } from 'zod'
import { adapterCredentialScopeFor, isProductionAdapterId } from '../codingAgent/interface'
import type {
AdapterBinding,
AgentArtifact,
AgentDelegation,
AgentEvent,
AgentRun,
AgentSession,
RunAttempt
} from './types'
import type { AgentRuntimeKernel } from './kernel'
import type { DesktopAwarenessSnapshot, ExecuteAgentRunInput } from './kernelTypes'
import { agentControlCapabilityManifest, agentControlInputSchema } from './controlToolManifest'
import { agentCardStampMetadata } from './agentThreadCards'
import { evaluateDesktopToolPolicy, type DesktopCoordinatorBundle } from './desktopToolPolicy'
import {
assertAgentSpawningAllowed,
assertLeafControlToolsAllowed,
providerBoundaryForAdapter,
resolveAdapterWithinBoundary,
type AgentExecutionRole,
type ProviderBoundary
} from './executionPolicy'
const sessionStatusSchema = z.enum(['open', 'archived', 'closed'])
const agentSurfaceKindSchema = z.enum([
'main_chat',
'task_chat',
'realtime',
'delegated_agent',
'background_agent',
'floating_bar',
'floating_pill'
])
const artifactRoleSchema = z.enum(['input', 'result', 'checkpoint', 'tool_output', 'log', 'other'])
const artifactLifecycleStateSchema = z.enum(['retained', 'dismissed', 'opened'])
const runModeSchema = z.enum(['ask', 'act'])
const desktopCoordinatorBundleSchema = z.enum([
'desktop.agent_control.read',
'desktop.agent_control.manage',
'desktop.context.local_read',
'desktop.context.screen_summary',
'desktop.context.screenshot_image',
'desktop.tasks.readwrite',
'desktop.artifacts.manage',
'desktop.automation.read',
'desktop.automation.act_dev_only',
'external.write_prepare',
'external.write_send'
])
const strictObject = <T extends z.ZodRawShape>(shape: T): z.ZodObject<T> => z.object(shape).strict()
const listAgentSessionsSchema = strictObject({
ownerId: z.string().min(1).optional(),
status: sessionStatusSchema.optional(),
surfaceKind: agentSurfaceKindSchema.optional(),
limit: z.coerce.number().int().positive().max(200).default(50),
beforeUpdatedAtMs: z.coerce.number().int().positive().optional()
})
const getAgentRunSchema = strictObject({
runId: z.string().min(1),
ownerId: z.string().min(1).optional(),
includeEvents: z.boolean().default(true),
eventLimit: z.coerce.number().int().positive().max(500).default(100)
})
const buildDesktopAwarenessSnapshotSchema = strictObject({
ownerId: z.string().min(1).optional(),
limit: z.coerce.number().int().positive().max(200).default(50)
})
const listDesktopActionQueueSchema = strictObject({
ownerId: z.string().min(1).optional(),
staleAfterMs: z.coerce.number().int().positive().optional(),
limit: z.coerce.number().int().positive().max(200).default(50)
})
const getDesktopOpenLoopsSchema = strictObject({
ownerId: z.string().min(1).optional(),
limit: z.coerce.number().int().positive().max(200).default(50)
})
const contextSnippetSchema = strictObject({
snippetId: z.string().min(1),
sourceKind: z.enum([
'omi_db',
'rewind_timeline',
'screen_current',
'screenshot_image',
'local_agent_api',
'automation_bridge',
'chat_surface',
'task_chat'
]),
operation: z.string().min(1),
provenance: z.record(z.string(), z.unknown()).default({}),
content: z.string().optional(),
redactedContent: z.string().optional(),
metadata: z.record(z.string(), z.unknown()).default({}),
sensitivityTier: z.string().min(1),
policyDecision: z.enum(['allowed', 'denied', 'dispatch_created']).optional(),
dispatchId: z.string().min(1).nullable().optional(),
selected: z.boolean().optional(),
tokenEstimate: z.coerce.number().int().positive().optional()
})
const buildDesktopContextPacketSchema = strictObject({
ownerId: z.string().min(1).optional(),
sessionId: z.string().min(1).nullable().optional(),
runId: z.string().min(1).nullable().optional(),
surfaceKind: z.string().min(1),
objective: z.string().min(1),
packetJson: strictObject({
snippets: z.array(contextSnippetSchema).default([]),
selectedToolBundles: z.array(desktopCoordinatorBundleSchema).default([]),
constraints: z.array(z.string()).default([]),
evidenceRequired: z.array(z.string()).default([]),
boundaryPolicy: z.record(z.string(), z.unknown()).default({})
}),
ttlMs: z.coerce.number().int().positive(),
retentionClass: z.enum(['ephemeral', 'debug', 'core'])
})
const routeDesktopIntentSchema = strictObject({
ownerId: z.string().min(1).optional(),
utterance: z.string().min(1),
surfaceKind: z.string().min(1),
taskId: z.string().min(1).nullable().optional()
})
const evaluateDesktopToolPolicySchema = strictObject({
// Direct app control authenticates the caller through an owner guard that is
// merged into every strict control-tool input before dispatch.
ownerId: z.string().min(1).optional(),
toolName: z.string().min(1).optional(),
selectedBundles: z.array(desktopCoordinatorBundleSchema),
requestedBundles: z.array(desktopCoordinatorBundleSchema).optional(),
sql: z.string().optional(),
operation: z.string().optional(),
resourceRef: z.string().optional(),
includesScreenshotImageBytes: z.boolean().optional(),
broadScreenHistory: z.boolean().optional(),
externalSend: z.boolean().optional(),
persistentGrant: z.boolean().optional(),
isDevBundle: z.boolean().optional()
})
const createDesktopDispatchSchema = strictObject({
ownerId: z.string().min(1).optional(),
kind: z.enum([
'approval',
'routing_choice',
'failure_recovery',
'artifact_review',
'memory_candidate',
'task_candidate',
'external_draft',
'screen_context'
]),
priority: z.coerce.number().int(),
title: z.string().min(1),
decisionPrompt: z.string().min(1),
recommendedDefault: z.string().nullable().optional(),
sourceSessionId: z.string().min(1).nullable().optional(),
sourceRunId: z.string().min(1).nullable().optional(),
sourceAttemptId: z.string().min(1).nullable().optional(),
sourceArtifactId: z.string().min(1).nullable().optional(),
capability: z.string().nullable().optional(),
operation: z.string().nullable().optional(),
resourceRef: z.string().nullable().optional(),
payload: z.record(z.string(), z.unknown()).default({}),
expiresAtMs: z.coerce.number().int().positive().nullable().optional()
})
const resolveDesktopDispatchSchema = strictObject({
dispatchId: z.string().min(1),
ownerId: z.string().min(1).optional(),
status: z.enum(['resolved', 'cancelled']),
resolvedBy: z.string().nullable().optional(),
resolution: z.record(z.string(), z.unknown()).default({}),
grant: strictObject({
sessionId: z.string().min(1).optional(),
runId: z.string().min(1).nullable().optional(),
capability: z.string().min(1),
operation: z.string().min(1),
resourcePattern: z.string().min(1),
effect: z.enum(['allow', 'deny']).default('allow'),
source: z.enum(['legacy_default', 'policy', 'user', 'system']).default('user'),
constraintsJson: z.string().default('{}'),
expiresAtMs: z.coerce.number().int().positive().nullable().optional()
}).optional()
})
const cancelAgentRunSchema = strictObject({
runId: z.string().min(1),
ownerId: z.string().min(1).optional()
})
const inspectAgentArtifactsSchema = z
.strictObject({
artifactId: z.string().min(1).optional(),
sessionId: z.string().min(1).optional(),
runId: z.string().min(1).optional(),
attemptId: z.string().min(1).optional(),
ownerId: z.string().min(1).optional(),
role: artifactRoleSchema.optional(),
limit: z.coerce.number().int().positive().max(200).default(50)
})
.refine((value) => value.artifactId || value.sessionId || value.runId || value.attemptId, {
message: 'Provide artifactId, sessionId, runId, or attemptId'
})
const updateAgentArtifactLifecycleSchema = strictObject({
artifactId: z.string().min(1),
state: artifactLifecycleStateSchema,
sessionId: z.string().min(1).optional(),
runId: z.string().min(1).optional(),
attemptId: z.string().min(1).optional(),
ownerId: z.string().min(1).optional(),
reason: z.string().min(1).max(500).optional(),
metadata: z.record(z.string(), z.unknown()).default({})
})
const sendAgentMessageSchema = strictObject({
sessionId: z.string().min(1),
ownerId: z.string().min(1).optional(),
prompt: z.string().min(1),
mode: runModeSchema.default('ask'),
adapterId: z.string().min(1).optional(),
cwd: z.string().min(1).optional(),
model: z.string().min(1).optional(),
requestId: z.string().min(1).optional(),
clientId: z.string().min(1).default('omi-control-tools'),
metadata: z.record(z.string(), z.unknown()).default({})
})
const spawnBackgroundAgentSchema = strictObject({
prompt: z.string().min(1),
title: z.string().min(1).optional(),
surfaceKind: z.string().min(1).default('floating_bar'),
externalRefKind: z.string().min(1).optional(),
externalRefId: z.string().min(1).optional(),
ownerId: z.string().min(1).optional(),
adapterId: z.string().min(1).optional(),
defaultAdapterId: z.string().min(1).optional(),
cwd: z.string().min(1).optional(),
model: z.string().min(1).optional(),
mode: runModeSchema.default('act'),
requestId: z.string().min(1).optional(),
clientId: z.string().min(1).default('omi-control-tools'),
metadata: z.record(z.string(), z.unknown()).default({})
})
const spawnAgentSchema = strictObject({
objective: z.string().min(1),
provider: z.enum(['openclaw', 'hermes']).optional(),
parentRunId: z.string().min(1).optional(),
visible: z.boolean().default(true),
title: z.string().min(1).optional(),
externalRefId: z.string().min(1).optional(),
ownerId: z.string().min(1).optional(),
adapterId: z.string().min(1).optional(),
cwd: z.string().min(1).optional(),
model: z.string().min(1).optional(),
requestId: z.string().min(1).optional(),
clientId: z.string().min(1).default('omi-control-tools'),
metadata: z.record(z.string(), z.unknown()).default({})
})
const runAgentAndWaitSchema = strictObject({
objective: z.string().min(1),
parentRunId: z.string().min(1),
context: z.string().max(4000).optional(),
ownerId: z.string().min(1).optional(),
adapterId: z.string().min(1).optional(),
cwd: z.string().min(1).optional(),
model: z.string().min(1).optional(),
runMode: runModeSchema.default('ask'),
requestId: z.string().min(1).optional(),
clientId: z.string().min(1).default('omi-control-tools'),
maxDepth: z.coerce.number().int().min(1).max(5).default(3),
maxBudgetUsd: z.coerce.number().positive().max(10).default(5),
metadata: z.record(z.string(), z.unknown()).default({})
})
const setDesktopAttentionOverrideSchema = strictObject({
ownerId: z.string().min(1).optional(),
subjectKind: z.string().min(1),
subjectId: z.string().min(1),
dismissed: z.boolean().default(true),
hiddenUntilMs: z.coerce.number().int().positive().nullable().optional(),
reason: z.string().min(1).optional()
})
export const agentControlToolSchemas = {
list_agent_sessions: listAgentSessionsSchema,
get_agent_run: getAgentRunSchema,
build_desktop_awareness_snapshot: buildDesktopAwarenessSnapshotSchema,
list_desktop_action_queue: listDesktopActionQueueSchema,
get_desktop_open_loops: getDesktopOpenLoopsSchema,
build_desktop_context_packet: buildDesktopContextPacketSchema,
route_desktop_intent: routeDesktopIntentSchema,
evaluate_desktop_tool_policy: evaluateDesktopToolPolicySchema,
create_desktop_dispatch: createDesktopDispatchSchema,
resolve_desktop_dispatch: resolveDesktopDispatchSchema,
cancel_agent_run: cancelAgentRunSchema,
inspect_agent_artifacts: inspectAgentArtifactsSchema,
update_agent_artifact_lifecycle: updateAgentArtifactLifecycleSchema,
send_agent_message: sendAgentMessageSchema,
spawn_background_agent: spawnBackgroundAgentSchema,
spawn_agent: spawnAgentSchema,
run_agent_and_wait: runAgentAndWaitSchema,
set_desktop_attention_override: setDesktopAttentionOverrideSchema
} as const
export type AgentControlToolName = keyof typeof agentControlToolSchemas
export const AGENT_CONTROL_TOOL_NAMES = agentControlCapabilityManifest.map(
(tool) => tool.name
) as AgentControlToolName[]
const CONTROL_TOOL_NAME_SET = new Set<string>(Object.keys(agentControlToolSchemas))
/**
* Tools that are never advertised to a model-facing surface, only reachable
* through trusted direct control:
* - `spawn_background_agent` — host coordinator entrypoint (`surfaces: []`).
* Unrestricted background-spawn rights: `backgroundSpawnAuthority` hands the
* kernel `trustedUserSpawn` for any non-leaf caller that omits a
* `callerSessionId`.
* - `resolve_desktop_dispatch` — resolving a dispatch IS the user's consent;
* a model may never grant itself one.
*
* Not being advertised is not a gate — a caller can still name a tool it was
* never shown. Every name in this set is therefore ALSO rejected at runtime in
* `handleAgentControlToolCall` when the caller is not trusted direct control,
* which makes the set self-enforcing: adding a name here gates it everywhere.
*
* DELIBERATE DEVIATION FROM macOS. The Mac original advertises-but-does-not-gate
* `spawn_background_agent` (control-tools.ts:555-583, 906-916) — a model-facing
* coordinator there can call it by name. Windows is stricter on purpose. Do not
* "restore parity" by removing this gate.
*/
export const TRUSTED_DIRECT_CONTROL_ONLY_TOOL_NAMES = new Set<string>([
'resolve_desktop_dispatch',
'spawn_background_agent'
])
export interface AgentControlToolDefinition {
name: AgentControlToolName
description: string
inputSchema: Record<string, unknown>
}
export const agentControlToolDefinitions: AgentControlToolDefinition[] =
agentControlCapabilityManifest.map((tool) => ({
name: tool.name,
description: tool.description,
inputSchema: agentControlInputSchema(tool)
}))
/**
* The tool definitions a given caller may see. Belt-and-suspenders with the
* handler-level assertions: a leaf worker is not even shown the tools it would
* be rejected for calling, and a model-facing surface is never shown the
* trusted-direct-control-only tools.
*/
export function agentControlToolDefinitionsFor(input: {
executionRole?: AgentExecutionRole
trustedUserControl?: boolean
surface?: 'desktopChat' | 'realtimeHub'
}): AgentControlToolDefinition[] {
const role = input.executionRole ?? 'coordinator'
return agentControlToolDefinitions.filter((definition) => {
const tool = agentControlCapabilityManifest.find((entry) => entry.name === definition.name)
if (!tool) return false
if (!input.trustedUserControl && TRUSTED_DIRECT_CONTROL_ONLY_TOOL_NAMES.has(definition.name)) {
return false
}
if (!executionRoleAllowsToolName(role, definition.name)) return false
// `spawn_background_agent` declares `allowedSurfaces: []` — it is never
// advertised to any surface.
const allowedSurfaces: readonly string[] = tool.allowedSurfaces
if (input.surface && !allowedSurfaces.includes(input.surface)) return false
return true
})
}
function executionRoleAllowsToolName(role: AgentExecutionRole, name: string): boolean {
try {
assertLeafControlToolsAllowed({ executionRole: role }, name)
return true
} catch {
return false
}
}
export interface AgentControlToolContext {
kernel: AgentRuntimeKernel
/**
* The adapter selected by the owning desktop surface. New background work must
* inherit this route rather than silently selecting a local provider.
*/
defaultAdapterId?: string
/** Kernel-owned provider and role policy for the active control caller. */
providerBoundary?: ProviderBoundary
executionRole?: AgentExecutionRole
/** Persisted caller session used for kernel-level spawn authority checks. */
callerSessionId?: string
/** @deprecated Compatibility for older direct callers; use executionRole. */
canSpawnAgents?: boolean
trustedUserControl?: boolean
getOwnerId?: () => string
recoverRunInput?: (
adapterId: string
) => Pick<ExecuteAgentRunInput, 'maxAttempts' | 'recoverAfterError'>
/**
* Host hook for `spawn_agent`'s adapter fallback: resolve (and register into
* the kernel registry) the default spawnable CODING-AGENT adapter when the
* caller's own default adapter is a managed-cloud chat engine (pi-mono) that
* can never be spawned. Returns the registered adapter id, or null when no
* coding agent is connected. HOST-derived — the model supplies nothing; the
* pick comes from the host's connected-agent detection (INV-AGENT posture is
* unchanged: this widens nothing a `provider` selector could not already do).
*/
resolveSpawnableAdapterId?: () => Promise<string | null>
}
function controlRunRecovery(
context: AgentControlToolContext,
adapterId: string
): Pick<ExecuteAgentRunInput, 'maxAttempts' | 'recoverAfterError'> {
return context.recoverRunInput?.(adapterId) ?? {}
}
function defaultControlAdapterId(context: AgentControlToolContext): string {
return context.defaultAdapterId ?? 'acp'
}
/**
* The agent-control spawn/run tools start LOCAL-provider sub-agents. A
* managed-cloud adapter (pi-mono) must never be spawned or run through them: it
* is the default-chat engine reached via main_chat (PR-E), not a spawnable
* coding agent. Registering pi-mono (PR-D) flipped `isProductionAdapterId` true,
* so without this guard `resolveAdapterWithinBoundary` would accept it — and the
* trusted-direct-control context has no owning session boundary, so
* `assertAdapterAllowedForControlRun` early-returns and would NOT catch it. Reject
* by credential SCOPE (matrix-derived, not an id list) so it stays correct when a
* second managed adapter appears. Keeps pi-mono un-invocable via control tools in
* DARK. Called at the entry of both admission guards so every spawn variant
* (spawn_agent, spawn_background_agent, run_agent_and_wait) is covered.
*/
function isManagedCloudAdapterId(adapterId: string): boolean {
return (
isProductionAdapterId(adapterId) && adapterCredentialScopeFor(adapterId) === 'managed_cloud'
)
}
function assertControlSpawnAdapterNotManagedCloud(adapterId: string): void {
if (isManagedCloudAdapterId(adapterId)) {
throw new Error(
`${adapterId} is a managed-cloud adapter and cannot be spawned or run through the agent-control tools.`
)
}
}
/**
* The adapter a fallback (no explicit adapterId/provider) `spawn_agent` runs on.
*
* The inherited default — the caller session's adapter, or the parent run's —
* is fine when it is itself spawnable. But the DEFAULT chat/voice surface runs
* on pi-mono (managed cloud), which `assertControlSpawnAdapterNotManagedCloud`
* refuses to spawn — so before this helper existed, every "build me X" spawn
* from default chat or voice dead-ended in `pi-mono is a managed-cloud adapter…`
* even with Claude Code connected (the 2026-07-18 live failure; macOS defaults
* the top-level spawn to 'acp' instead of the caller's adapter). In that case,
* ask the host which CONNECTED coding agent to use (`resolveSpawnableAdapterId`,
* which also registers it in the kernel registry). No hook or no connected agent
* is a clear actionable error, not the misleading managed-cloud refusal.
*/
async function resolveSpawnAgentFallbackAdapter(
context: AgentControlToolContext,
inherited: string
): Promise<{ adapterId: string; hostPicked: boolean }> {
if (!isManagedCloudAdapterId(inherited)) {
return { adapterId: inherited, hostPicked: false }
}
const picked = (await context.resolveSpawnableAdapterId?.()) ?? null
if (!picked) {
throw new Error(
'No coding agent is connected to run this as a background agent. Ask the user to connect Claude Code (or another coding agent) in Settings, then try again.'
)
}
return { adapterId: picked, hostPicked: true }
}
function assertAdapterAllowedForControlRun(
context: AgentControlToolContext,
adapterId: string
): void {
assertControlSpawnAdapterNotManagedCloud(adapterId)
if (!context.defaultAdapterId && !context.providerBoundary) {
return
}
const owningAdapterId = defaultControlAdapterId(context)
resolveAdapterWithinBoundary({
providerBoundary: context.providerBoundary ?? providerBoundaryForAdapter(owningAdapterId),
defaultAdapterId: owningAdapterId,
requestedAdapterId: adapterId
})
}
/**
* A signed desktop action, the explicit `provider` selector on the canonical
* top-level spawn_agent tool, or the HOST-picked connected-coding-agent fallback
* (`resolveSpawnAgentFallbackAdapter`) may start a new local-provider session.
* The active bridge can still be a managed-cloud adapter because it is only
* carrying the control RPC; it is not the owner of the new session's
* credentials. The host-picked fallback carries the same authority as the
* `provider` selector: the adapter id comes from the host's connected-agent
* detection, never from the model.
*
* A model-supplied adapterId alone does not get this exception, and neither
* does any parent-linked delegation. Those must stay inside the caller's
* persisted provider boundary.
*/
function assertAdapterAllowedForTopLevelLocalProviderSpawn(
context: AgentControlToolContext,
adapterId: string,
directedProvider?: 'hermes' | 'openclaw',
hostPicked = false
): void {
assertControlSpawnAdapterNotManagedCloud(adapterId)
const hasDirectedLocalProvider = directedProvider === adapterId || hostPicked
if (!context.trustedUserControl && !hasDirectedLocalProvider) {
assertAdapterAllowedForControlRun(context, adapterId)
return
}
if (!isProductionAdapterId(adapterId)) {
throw new Error(`Unknown production adapter: ${adapterId}`)
}
resolveAdapterWithinBoundary({
providerBoundary: providerBoundaryForAdapter(adapterId),
defaultAdapterId: adapterId,
requestedAdapterId: adapterId
})
}
/**
* Signed direct control resumes the target session's persisted boundary. This
* keeps a user-selected local-provider session usable while the coordinator
* bridge itself is using managed cloud routing, and still prevents adapter
* changes on either local or managed sessions.
*/
function assertAdapterAllowedForDirectSessionContinuation(
context: AgentControlToolContext,
adapterId: string,
targetPolicy: Pick<AgentSession, 'providerBoundary' | 'defaultAdapterId'>
): void {
if (!context.trustedUserControl) {
assertAdapterAllowedForControlRun(context, adapterId)
return
}
resolveAdapterWithinBoundary({
providerBoundary: targetPolicy.providerBoundary,
defaultAdapterId: targetPolicy.defaultAdapterId,
requestedAdapterId: adapterId
})
}
function backgroundSpawnAuthority(context: AgentControlToolContext): {
callerSessionId?: string
trustedUserSpawn?: boolean
} {
if (context.callerSessionId) {
return { callerSessionId: context.callerSessionId }
}
if (context.trustedUserControl === true || context.executionRole !== 'leaf') {
return { trustedUserSpawn: true }
}
return {}
}
export const DEFAULT_LOCAL_OWNER_ID = 'desktop-local-user'
export function isAgentControlToolName(name: string): name is AgentControlToolName {
return CONTROL_TOOL_NAME_SET.has(name)
}
export async function handleAgentControlToolCall(
context: AgentControlToolContext,
name: string,
input: Record<string, unknown>
): Promise<string> {
if (!isAgentControlToolName(name)) {
return JSON.stringify({
ok: false,
error: {
code: 'unknown_control_tool',
message: `Unknown control tool: ${name}`
}
})
}
try {
// INV-AGENT leaf-role guard. Runs before ANY tool executes, on every call.
// Kept ahead of the trusted-control gate below so that a leaf caller of a
// tool covered by BOTH is still rejected by this one — each guard keeps its
// own failing test.
assertLeafControlToolsAllowed(context, name)
// Trusted-direct-control gate — still before parsing and before any kernel
// call. Covers EVERY name in TRUSTED_DIRECT_CONTROL_ONLY_TOOL_NAMES: being
// absent from a caller's advertised tool list does not stop it from naming
// the tool anyway.
if (TRUSTED_DIRECT_CONTROL_ONLY_TOOL_NAMES.has(name) && !context.trustedUserControl) {
return JSON.stringify({
ok: false,
error: {
code: 'policy_denied',
message: `${name} requires trusted user control`
}
})
}
switch (name) {
case 'list_agent_sessions': {
const parsed = agentControlToolSchemas.list_agent_sessions.parse(input)
const ownerId = effectiveControlToolOwnerId(context, parsed.ownerId)
const sessions = context.kernel.listSessions({ ...parsed, ownerId })
const overrides = context.kernel.listDesktopAttentionOverrides(ownerId)
return stringifyToolResult(serializeAgentSessionsList(sessions, overrides))
}
case 'get_agent_run': {
const parsed = agentControlToolSchemas.get_agent_run.parse(input)
const details = context.kernel.getRun({
...parsed,
ownerId: effectiveControlToolOwnerId(context, parsed.ownerId)
})
return stringifyToolResult(serializeRunDetails(details))
}
case 'build_desktop_awareness_snapshot': {
const parsed = agentControlToolSchemas.build_desktop_awareness_snapshot.parse(input)
const snapshot = context.kernel.buildDesktopAwarenessSnapshot({
...parsed,
ownerId: effectiveControlToolOwnerId(context, parsed.ownerId)
})
return stringifyToolResult({ snapshot: serializeAwarenessSnapshot(snapshot) })
}
case 'list_desktop_action_queue': {
const parsed = agentControlToolSchemas.list_desktop_action_queue.parse(input)
const actionQueue = context.kernel.listDesktopActionQueue({
...parsed,
ownerId: effectiveControlToolOwnerId(context, parsed.ownerId)
})
return stringifyToolResult({ actionQueue })
}
case 'get_desktop_open_loops': {
const parsed = agentControlToolSchemas.get_desktop_open_loops.parse(input)
const openLoops = context.kernel.getDesktopOpenLoops({
...parsed,
ownerId: effectiveControlToolOwnerId(context, parsed.ownerId)
})
return stringifyToolResult({ openLoops })
}
case 'build_desktop_context_packet': {
const parsed = agentControlToolSchemas.build_desktop_context_packet.parse(input)
const built = context.kernel.persistDesktopContextPacket({
ownerId: effectiveControlToolOwnerId(context, parsed.ownerId),
sessionId: parsed.sessionId ?? null,
runId: parsed.runId ?? null,
surfaceKind: parsed.surfaceKind,
objective: parsed.objective,
snippets: parsed.packetJson.snippets,
selectedToolBundles: parsed.packetJson.selectedToolBundles,
constraints: parsed.packetJson.constraints,
evidenceRequired: parsed.packetJson.evidenceRequired,
boundaryPolicy: parsed.packetJson.boundaryPolicy,
ttlMs: parsed.ttlMs,
retentionClass: parsed.retentionClass
})
return stringifyToolResult({
packet: {
...built.packet,
packetJson: built.packet.packetJson,
redactedPreviewJson: built.packet.redactedPreviewJson
},
accessLogs: built.accessLogs
})
}
case 'route_desktop_intent': {
const parsed = agentControlToolSchemas.route_desktop_intent.parse(input)
const route = context.kernel.routeDesktopIntent({
...parsed,
ownerId: effectiveControlToolOwnerId(context, parsed.ownerId),
taskId: parsed.taskId ?? null
})
return stringifyToolResult({ route })
}
case 'evaluate_desktop_tool_policy': {
const parsed = agentControlToolSchemas.evaluate_desktop_tool_policy.parse(input)
const policy = evaluateDesktopToolPolicy({
...parsed,
selectedBundles: parsed.selectedBundles as DesktopCoordinatorBundle[],
requestedBundles: parsed.requestedBundles as DesktopCoordinatorBundle[] | undefined
})
return stringifyToolResult({ policy })
}
case 'create_desktop_dispatch': {
const parsed = agentControlToolSchemas.create_desktop_dispatch.parse(input)
const dispatch = context.kernel.createDesktopDispatch({
...parsed,
ownerId: effectiveControlToolOwnerId(context, parsed.ownerId),
payloadJson: JSON.stringify(parsed.payload)
})
return stringifyToolResult({ dispatch })
}
case 'resolve_desktop_dispatch': {
const parsed = agentControlToolSchemas.resolve_desktop_dispatch.parse(input)
const result = context.kernel.resolveDesktopDispatch(parsed.dispatchId, {
ownerId: effectiveControlToolOwnerId(context, parsed.ownerId),
status: parsed.status,
resolvedBy: parsed.resolvedBy ?? 'user',
resolutionJson: JSON.stringify(parsed.resolution),
grant: parsed.grant
})
return stringifyToolResult({
dispatch: result.dispatch,
grant: result.grant,
event: result.event ? serializeEvent(result.event) : null
})
}
case 'cancel_agent_run': {
const parsed = agentControlToolSchemas.cancel_agent_run.parse(input)
const ownerId = effectiveControlToolOwnerId(context, parsed.ownerId)
const cancellation = await context.kernel.cancelRun(parsed.runId, { ownerId })
const details = context.kernel.getRun({
runId: parsed.runId,
ownerId,
includeEvents: true,
eventLimit: 100
})
return stringifyToolResult({
cancellation,
run: serializeRun(details.run),
attempts: details.attempts.map(serializeAttempt)
})
}
case 'inspect_agent_artifacts': {
const parsed = agentControlToolSchemas.inspect_agent_artifacts.parse(input)
const artifacts = context.kernel.inspectArtifacts({
...parsed,
ownerId: effectiveControlToolOwnerId(context, parsed.ownerId)
})
return stringifyToolResult({ artifacts: artifacts.map(serializeArtifact) })
}
case 'update_agent_artifact_lifecycle': {
const parsed = agentControlToolSchemas.update_agent_artifact_lifecycle.parse(input)
const result = context.kernel.updateArtifactLifecycle({
...parsed,
ownerId: effectiveControlToolOwnerId(context, parsed.ownerId)
})
return stringifyToolResult({
artifact: serializeArtifact(result.artifact),
changed: result.changed,
event: result.event ? serializeEvent(result.event) : null
})
}
case 'send_agent_message': {
const parsed = agentControlToolSchemas.send_agent_message.parse(input)
const targetPolicy = context.kernel.executionPolicyForSession(parsed.sessionId)
const adapterId = parsed.adapterId ?? targetPolicy.defaultAdapterId
assertAdapterAllowedForDirectSessionContinuation(context, adapterId, targetPolicy)
rejectSynchronousNestedRun(context, adapterId, parsed.sessionId)
const ownerId = effectiveControlToolOwnerId(context, parsed.ownerId)
const requestId =
parsed.requestId ?? `send-${Date.now()}-${Math.random().toString(16).slice(2)}`
const result = await context.kernel.sendAgentMessage({
...parsed,
...controlRunRecovery(context, adapterId),
ownerId,
requestId,
metadata: { ...(parsed.metadata ?? {}) }
})
return stringifyToolResult({
session: serializeSession(result.session),
run: serializeRun(result.run),
attempt: serializeAttempt(result.attempt),
adapterSessionId: result.adapterSessionId,
terminalStatus: result.terminalStatus,
text: result.text,
artifacts: result.artifacts.map(serializeArtifact)
})
}
case 'spawn_background_agent': {
assertAgentSpawningAllowed(context)
const parsed = agentControlToolSchemas.spawn_background_agent.parse(input)
const ownerId = effectiveControlToolOwnerId(context, parsed.ownerId)
const requestId =
parsed.requestId ?? `background-${Date.now()}-${Math.random().toString(16).slice(2)}`
const adapterId =
parsed.adapterId ?? parsed.defaultAdapterId ?? defaultControlAdapterId(context)
assertAdapterAllowedForTopLevelLocalProviderSpawn(context, adapterId)
const result = await context.kernel.spawnBackgroundAgent({
...parsed,
...controlRunRecovery(context, adapterId),
...backgroundSpawnAuthority(context),
adapterId,
defaultAdapterId: adapterId,
ownerId,
requestId,
surfaceKind: parsed.surfaceKind ?? 'floating_bar',
metadata: { ...(parsed.metadata ?? {}) }
})
return stringifyToolResult({
session: serializeSession(result.session),
run: serializeRun(result.run),
attempt: result.attempt ? serializeAttempt(result.attempt) : null
})
}
case 'spawn_agent': {
assertAgentSpawningAllowed(context)
const parsed = agentControlToolSchemas.spawn_agent.parse(input)
if (parsed.parentRunId) {
assertCanonicalRunId(parsed.parentRunId, 'parentRunId')
}
const ownerId = effectiveControlToolOwnerId(context, parsed.ownerId)
const requestId =
parsed.requestId ?? `spawn-agent-${Date.now()}-${Math.random().toString(16).slice(2)}`
if (parsed.provider && parsed.adapterId && parsed.provider !== parsed.adapterId) {
throw new Error('provider and adapterId must match when both are supplied')
}
const directedAdapterId =
parsed.adapterId ??
(parsed.provider === 'openclaw'
? 'openclaw'
: parsed.provider === 'hermes'
? 'hermes'
: undefined)
const fallback = directedAdapterId
? { adapterId: directedAdapterId, hostPicked: false }
: await resolveSpawnAgentFallbackAdapter(
context,
parsed.parentRunId
? context.kernel.defaultAdapterIdForRun(parsed.parentRunId)
: defaultControlAdapterId(context)
)
const adapterId = fallback.adapterId
// A managed-cloud parent run (the pi-mono chat turn itself) cannot own a
// delegation — its provider boundary can never contain a spawnable local
// adapter — so a host-picked fallback reroutes to a TOP-LEVEL background
// spawn (parent recorded in metadata) instead of failing the request.
const delegateUnderParent = Boolean(parsed.parentRunId) && !fallback.hostPicked
if (delegateUnderParent) {
assertAdapterAllowedForControlRun(context, adapterId)
} else {
assertAdapterAllowedForTopLevelLocalProviderSpawn(
context,
adapterId,
parsed.provider,
fallback.hostPicked
)
}
const visiblePillExternalRefId = parsed.visible
? (parsed.externalRefId ?? randomUUID())
: parsed.externalRefId
const childSurfaceKind = parsed.visible ? 'floating_bar' : 'delegated_agent'
const childExternalRefKind = parsed.visible ? 'pill' : undefined
// Shared-thread agent cards (B4, INV-CHAT-1): stamp the background run with
// the PRODUCING surface (the caller's chat/voice conversation), so the
// terminal subscriber can materialize the completion card long after this
// call returned. Resolved from the caller session — a trusted-direct-control
// spawn with no originating chat gets no stamp (and thus no cards). The
// stamp only records provenance; it never widens spawn authority.
const cardTitle = parsed.title ?? `Background: ${parsed.objective.slice(0, 80)}`
let producingSurface: ReturnType<typeof context.kernel.getProducingCardSurface> = null
try {
producingSurface = context.callerSessionId
? context.kernel.getProducingCardSurface(context.callerSessionId)
: null
} catch {
// A provenance lookup must NEVER abort a spawn — fail open to no stamp
// (the run just gets no shared-thread cards).
producingSurface = null
}
const cardStampMetadata = producingSurface
? agentCardStampMetadata({
producingConversationId: producingSurface.conversationId,
producingChatId: producingSurface.chatId,
producingSurfaceKind: producingSurface.surfaceKind,
pillId: visiblePillExternalRefId ?? null,
title: cardTitle,
objective: parsed.objective
})
: {}
if (delegateUnderParent && parsed.parentRunId) {
const result = await context.kernel.delegateAgent({
...controlRunRecovery(context, adapterId),
mode: 'spawn',
parentRunId: parsed.parentRunId,
objective: parsed.objective,
ownerId,
requestId,
adapterId,
defaultAdapterId: adapterId,
childSurfaceKind,
childExternalRefKind,
childExternalRefId: visiblePillExternalRefId,
childTitle: parsed.title ?? `Delegated: ${parsed.objective.slice(0, 80)}`,
cwd: parsed.cwd,
model: parsed.model,
runMode: 'act',
clientId: parsed.clientId,
metadata: { ...(parsed.metadata ?? {}), visible: parsed.visible, ...cardStampMetadata }
})
return stringifyToolResult({
delegation: serializeDelegation(result.delegation),
session: serializeSession(result.childSession),
run: serializeRun(result.childRun),
attempt: result.childAttempt ? serializeAttempt(result.childAttempt) : null
})
}
const result = await context.kernel.spawnBackgroundAgent({
...controlRunRecovery(context, adapterId),
...backgroundSpawnAuthority(context),
ownerId,
clientId: parsed.clientId,
requestId,
prompt: parsed.objective,
title: parsed.title ?? `Background: ${parsed.objective.slice(0, 80)}`,
surfaceKind: childSurfaceKind,
externalRefKind: childExternalRefKind,
externalRefId: visiblePillExternalRefId,
adapterId,
defaultAdapterId: adapterId,
cwd: parsed.cwd,
model: parsed.model,
mode: 'act',
metadata: {
...(parsed.metadata ?? {}),
visible: parsed.visible,
provider: parsed.provider ?? null,
// Kept for traceability when a managed-cloud parent rerouted the
// delegation into a top-level background spawn (see above).
requestedParentRunId: parsed.parentRunId ?? null,
...cardStampMetadata
}
})
return stringifyToolResult({
session: serializeSession(result.session),
run: serializeRun(result.run),
attempt: result.attempt ? serializeAttempt(result.attempt) : null
})
}
case 'run_agent_and_wait': {
assertAgentSpawningAllowed(context)
const parsed = agentControlToolSchemas.run_agent_and_wait.parse(input)
assertCanonicalRunId(parsed.parentRunId, 'parentRunId')
const ownerId = effectiveControlToolOwnerId(context, parsed.ownerId)
const requestId =
parsed.requestId ?? `run-and-wait-${Date.now()}-${Math.random().toString(16).slice(2)}`
const adapterId =
parsed.adapterId ?? context.kernel.defaultAdapterIdForRun(parsed.parentRunId)
assertAdapterAllowedForControlRun(context, adapterId)
const result = await context.kernel.delegateAgent({
...controlRunRecovery(context, adapterId),
mode: 'call',
parentRunId: parsed.parentRunId,
objective: parsed.objective,
context: parsed.context,
ownerId,
requestId,
adapterId,
defaultAdapterId: adapterId,
cwd: parsed.cwd,
model: parsed.model,
runMode: parsed.runMode,