deus-machine 0.3.3 → 0.3.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -14880,7 +14880,7 @@ module.exports = __toCommonJS(index_exports);
14880
14880
  var Sentry = __toESM(require("@sentry/node"), 1);
14881
14881
  var fs5 = __toESM(require("fs"), 1);
14882
14882
  var util = __toESM(require("util"), 1);
14883
- var import_child_process7 = require("child_process");
14883
+ var import_child_process8 = require("child_process");
14884
14884
  var import_http = require("http");
14885
14885
  var import_ws = require("ws");
14886
14886
 
@@ -28779,7 +28779,7 @@ var WorkspaceStatusSchema = external_exports.enum([
28779
28779
  "canceled"
28780
28780
  ]);
28781
28781
  var WORKFLOW_STATUSES = WorkspaceStatusSchema.options;
28782
- var AgentTypeSchema = external_exports.enum(["claude", "codex"]);
28782
+ var AgentHarnessSchema = external_exports.enum(["claude", "codex"]);
28783
28783
  var ErrorCategorySchema = external_exports.enum([
28784
28784
  "auth",
28785
28785
  "rate_limit",
@@ -28796,36 +28796,21 @@ var ErrorCategorySchema = external_exports.enum([
28796
28796
  var MessageResponseSchema = external_exports.object({
28797
28797
  id: external_exports.string(),
28798
28798
  type: external_exports.literal("message"),
28799
- agentType: AgentTypeSchema,
28799
+ agentHarness: AgentHarnessSchema,
28800
28800
  data: external_exports.unknown()
28801
28801
  });
28802
28802
  var ErrorResponseSchema = external_exports.object({
28803
28803
  id: external_exports.string(),
28804
28804
  type: external_exports.literal("error"),
28805
28805
  error: external_exports.string(),
28806
- agentType: AgentTypeSchema,
28806
+ agentHarness: AgentHarnessSchema,
28807
28807
  category: ErrorCategorySchema.optional()
28808
28808
  });
28809
28809
  var EnterPlanModeNotificationSchema = external_exports.object({
28810
28810
  type: external_exports.literal("enter_plan_mode_notification"),
28811
28811
  id: external_exports.string(),
28812
- agentType: AgentTypeSchema
28812
+ agentHarness: AgentHarnessSchema
28813
28813
  });
28814
- var StatusChangedNotificationSchema = external_exports.object({
28815
- type: external_exports.literal("status_changed"),
28816
- id: external_exports.string(),
28817
- agentType: AgentTypeSchema,
28818
- status: SessionStatusSchema,
28819
- errorMessage: external_exports.string().optional(),
28820
- errorCategory: ErrorCategorySchema.optional(),
28821
- workspaceId: external_exports.string().optional()
28822
- });
28823
- var SessionNotificationSchema = external_exports.union([
28824
- MessageResponseSchema,
28825
- ErrorResponseSchema,
28826
- EnterPlanModeNotificationSchema,
28827
- StatusChangedNotificationSchema
28828
- ]);
28829
28814
 
28830
28815
  // shared/protocol.ts
28831
28816
  var PermissionModeSchema = external_exports.enum([
@@ -28835,10 +28820,11 @@ var PermissionModeSchema = external_exports.enum([
28835
28820
  "plan",
28836
28821
  "dontAsk"
28837
28822
  ]);
28823
+ var ThinkingLevelSchema = external_exports.enum(["NONE", "LOW", "MEDIUM", "HIGH", "XHIGH"]);
28838
28824
  var QueryOptionsSchema = external_exports.object({
28839
28825
  cwd: external_exports.string().min(1),
28840
28826
  model: external_exports.string().min(1).optional(),
28841
- maxThinkingTokens: external_exports.number().int().positive().optional(),
28827
+ thinkingLevel: ThinkingLevelSchema.optional(),
28842
28828
  maxTurns: external_exports.number().int().positive().optional(),
28843
28829
  turnId: external_exports.string().min(1).optional(),
28844
28830
  permissionMode: PermissionModeSchema.optional(),
@@ -28855,7 +28841,7 @@ var QueryOptionsSchema = external_exports.object({
28855
28841
  var QueryRequestSchema = external_exports.object({
28856
28842
  type: external_exports.literal("query"),
28857
28843
  id: external_exports.string().min(1),
28858
- agentType: AgentTypeSchema,
28844
+ agentHarness: AgentHarnessSchema,
28859
28845
  prompt: external_exports.string().min(1),
28860
28846
  options: QueryOptionsSchema
28861
28847
  });
@@ -28972,6 +28958,10 @@ var ReasoningPartSchema = external_exports.object({
28972
28958
  partIndex: external_exports.number().optional(),
28973
28959
  text: external_exports.string(),
28974
28960
  state: external_exports.enum(["STREAMING", "DONE"]).optional(),
28961
+ time: external_exports.object({
28962
+ start: external_exports.string(),
28963
+ end: external_exports.string().optional()
28964
+ }).optional(),
28975
28965
  providerMetadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional(),
28976
28966
  parentToolCallId: external_exports.string().optional()
28977
28967
  });
@@ -29006,7 +28996,6 @@ var PartSchema = external_exports.discriminatedUnion("type", [
29006
28996
  ToolPartSchema,
29007
28997
  CompactionPartSchema
29008
28998
  ]);
29009
- var PartTypeSchema = external_exports.enum(["TEXT", "REASONING", "TOOL", "COMPACTION"]);
29010
28999
 
29011
29000
  // shared/agent-events.ts
29012
29001
  var AGENT_EVENT_NAMES = {
@@ -29052,7 +29041,7 @@ var AgentCapabilitiesSchema = external_exports.object({
29052
29041
  permissionMode: external_exports.boolean()
29053
29042
  });
29054
29043
  var AgentInfoSchema = external_exports.object({
29055
- type: AgentTypeSchema,
29044
+ type: AgentHarnessSchema,
29056
29045
  capabilities: AgentCapabilitiesSchema,
29057
29046
  initialized: external_exports.boolean()
29058
29047
  });
@@ -29060,28 +29049,11 @@ var InitializeResultSchema = external_exports.object({
29060
29049
  version: external_exports.string(),
29061
29050
  agents: external_exports.array(AgentInfoSchema)
29062
29051
  });
29063
- var TurnOptionsSchema = external_exports.object({
29064
- cwd: external_exports.string().min(1),
29065
- model: external_exports.string().min(1).optional(),
29066
- maxThinkingTokens: external_exports.number().int().positive().optional(),
29067
- maxTurns: external_exports.number().int().positive().optional(),
29068
- turnId: external_exports.string().min(1).optional(),
29069
- permissionMode: external_exports.string().optional(),
29070
- providerEnvVars: external_exports.string().optional(),
29071
- ghToken: external_exports.string().optional(),
29072
- deusEnv: external_exports.record(external_exports.string(), external_exports.string()).optional(),
29073
- additionalDirectories: external_exports.array(external_exports.string()).optional(),
29074
- chromeEnabled: external_exports.boolean().optional(),
29075
- strictDataPrivacy: external_exports.boolean().optional(),
29076
- shouldResetGenerator: external_exports.boolean().optional(),
29077
- resume: external_exports.string().min(1).optional(),
29078
- resumeSessionAt: external_exports.string().min(1).optional()
29079
- });
29080
29052
  var TurnStartRequestSchema = external_exports.object({
29081
29053
  sessionId: external_exports.string().min(1),
29082
- agentType: AgentTypeSchema,
29054
+ agentHarness: AgentHarnessSchema,
29083
29055
  prompt: external_exports.string().min(1),
29084
- options: TurnOptionsSchema
29056
+ options: QueryOptionsSchema
29085
29057
  });
29086
29058
  var TurnStartResponseSchema = external_exports.object({
29087
29059
  accepted: external_exports.boolean(),
@@ -29102,11 +29074,11 @@ var SessionStopRequestSchema = external_exports.object({
29102
29074
  sessionId: external_exports.string().min(1)
29103
29075
  });
29104
29076
  var ProviderAuthRequestSchema = external_exports.object({
29105
- agentType: AgentTypeSchema,
29077
+ agentHarness: AgentHarnessSchema,
29106
29078
  cwd: external_exports.string().min(1)
29107
29079
  });
29108
29080
  var ProviderInitWorkspaceRequestSchema = external_exports.object({
29109
- agentType: AgentTypeSchema,
29081
+ agentHarness: AgentHarnessSchema,
29110
29082
  cwd: external_exports.string().min(1),
29111
29083
  ghToken: external_exports.string().optional(),
29112
29084
  providerEnvVars: external_exports.string().optional()
@@ -29140,47 +29112,42 @@ var FRONTEND_RPC_METHODS = {
29140
29112
  BROWSER_NETWORK_REQUESTS: "browserNetworkRequests",
29141
29113
  BROWSER_SCREENSHOT: "browserScreenshot",
29142
29114
  BROWSER_SCROLL: "browserScroll",
29143
- SIM_SCREENSHOT: "simScreenshot",
29144
- SIM_TAP: "simTap",
29145
- SIM_SWIPE: "simSwipe",
29146
- SIM_TYPE_TEXT: "simTypeText",
29147
- SIM_PRESS_KEY: "simPressKey",
29148
- SIM_BUILD_AND_RUN: "simBuildAndRun",
29149
- SIM_LIST_DEVICES: "simListDevices",
29150
- SIM_START: "simStart"
29115
+ // Simulator context — backend-only method (handled in onFrontendRpc before
29116
+ // the frontend relay). Resolves the agent's session to its workspace's UDID.
29117
+ GET_SIMULATOR_CONTEXT: "getSimulatorContext"
29151
29118
  };
29152
29119
  var SessionStartedEventSchema = external_exports.object({
29153
29120
  type: external_exports.literal("session.started"),
29154
29121
  sessionId: external_exports.string(),
29155
- agentType: AgentTypeSchema
29122
+ agentHarness: AgentHarnessSchema
29156
29123
  });
29157
29124
  var SessionIdleEventSchema = external_exports.object({
29158
29125
  type: external_exports.literal("session.idle"),
29159
29126
  sessionId: external_exports.string(),
29160
- agentType: AgentTypeSchema
29127
+ agentHarness: AgentHarnessSchema
29161
29128
  });
29162
29129
  var SessionErrorEventSchema = external_exports.object({
29163
29130
  type: external_exports.literal("session.error"),
29164
29131
  sessionId: external_exports.string(),
29165
- agentType: AgentTypeSchema,
29132
+ agentHarness: AgentHarnessSchema,
29166
29133
  error: external_exports.string(),
29167
29134
  category: ErrorCategorySchema
29168
29135
  });
29169
29136
  var SessionCancelledEventSchema = external_exports.object({
29170
29137
  type: external_exports.literal("session.cancelled"),
29171
29138
  sessionId: external_exports.string(),
29172
- agentType: AgentTypeSchema
29139
+ agentHarness: AgentHarnessSchema
29173
29140
  });
29174
29141
  var MessageSystemEventSchema = external_exports.object({
29175
29142
  type: external_exports.literal("message.system"),
29176
29143
  sessionId: external_exports.string(),
29177
- agentType: AgentTypeSchema,
29144
+ agentHarness: AgentHarnessSchema,
29178
29145
  data: external_exports.unknown()
29179
29146
  });
29180
29147
  var MessageAssistantEventSchema = external_exports.object({
29181
29148
  type: external_exports.literal("message.assistant"),
29182
29149
  sessionId: external_exports.string(),
29183
- agentType: AgentTypeSchema,
29150
+ agentHarness: AgentHarnessSchema,
29184
29151
  message: external_exports.object({
29185
29152
  id: external_exports.string(),
29186
29153
  role: external_exports.literal("assistant"),
@@ -29193,7 +29160,7 @@ var MessageAssistantEventSchema = external_exports.object({
29193
29160
  var MessageToolResultEventSchema = external_exports.object({
29194
29161
  type: external_exports.literal("message.tool_result"),
29195
29162
  sessionId: external_exports.string(),
29196
- agentType: AgentTypeSchema,
29163
+ agentHarness: AgentHarnessSchema,
29197
29164
  message: external_exports.object({
29198
29165
  id: external_exports.string(),
29199
29166
  role: external_exports.literal("user"),
@@ -29205,26 +29172,26 @@ var MessageToolResultEventSchema = external_exports.object({
29205
29172
  var MessageResultEventSchema = external_exports.object({
29206
29173
  type: external_exports.literal("message.result"),
29207
29174
  sessionId: external_exports.string(),
29208
- agentType: AgentTypeSchema,
29175
+ agentHarness: AgentHarnessSchema,
29209
29176
  subtype: external_exports.string(),
29210
29177
  usage: external_exports.unknown().optional()
29211
29178
  });
29212
29179
  var MessageCancelledEventSchema = external_exports.object({
29213
29180
  type: external_exports.literal("message.cancelled"),
29214
29181
  sessionId: external_exports.string(),
29215
- agentType: AgentTypeSchema
29182
+ agentHarness: AgentHarnessSchema
29216
29183
  });
29217
29184
  var TurnStartedEventSchema = external_exports.object({
29218
29185
  type: external_exports.literal("turn.started"),
29219
29186
  sessionId: external_exports.string(),
29220
- agentType: AgentTypeSchema,
29187
+ agentHarness: AgentHarnessSchema,
29221
29188
  messageId: external_exports.string(),
29222
29189
  turnId: external_exports.string().optional()
29223
29190
  });
29224
29191
  var MessageCreatedEventSchema = external_exports.object({
29225
29192
  type: external_exports.literal("message.created"),
29226
29193
  sessionId: external_exports.string(),
29227
- agentType: AgentTypeSchema,
29194
+ agentHarness: AgentHarnessSchema,
29228
29195
  messageId: external_exports.string(),
29229
29196
  role: external_exports.literal("assistant"),
29230
29197
  parentToolCallId: external_exports.string().optional()
@@ -29232,7 +29199,7 @@ var MessageCreatedEventSchema = external_exports.object({
29232
29199
  var PartCreatedEventSchema = external_exports.object({
29233
29200
  type: external_exports.literal("part.created"),
29234
29201
  sessionId: external_exports.string(),
29235
- agentType: AgentTypeSchema,
29202
+ agentHarness: AgentHarnessSchema,
29236
29203
  messageId: external_exports.string(),
29237
29204
  partId: external_exports.string(),
29238
29205
  part: PartSchema
@@ -29240,14 +29207,14 @@ var PartCreatedEventSchema = external_exports.object({
29240
29207
  var PartDeltaEventSchema = external_exports.object({
29241
29208
  type: external_exports.literal("part.delta"),
29242
29209
  sessionId: external_exports.string(),
29243
- agentType: AgentTypeSchema,
29210
+ agentHarness: AgentHarnessSchema,
29244
29211
  partId: external_exports.string(),
29245
29212
  delta: external_exports.string()
29246
29213
  });
29247
29214
  var PartDoneEventSchema = external_exports.object({
29248
29215
  type: external_exports.literal("part.done"),
29249
29216
  sessionId: external_exports.string(),
29250
- agentType: AgentTypeSchema,
29217
+ agentHarness: AgentHarnessSchema,
29251
29218
  messageId: external_exports.string(),
29252
29219
  partId: external_exports.string(),
29253
29220
  part: PartSchema
@@ -29255,7 +29222,7 @@ var PartDoneEventSchema = external_exports.object({
29255
29222
  var MessageDoneEventSchema = external_exports.object({
29256
29223
  type: external_exports.literal("message.done"),
29257
29224
  sessionId: external_exports.string(),
29258
- agentType: AgentTypeSchema,
29225
+ agentHarness: AgentHarnessSchema,
29259
29226
  messageId: external_exports.string(),
29260
29227
  stopReason: external_exports.string().optional(),
29261
29228
  parts: external_exports.array(PartSchema),
@@ -29264,7 +29231,7 @@ var MessageDoneEventSchema = external_exports.object({
29264
29231
  var TurnCompletedEventSchema = external_exports.object({
29265
29232
  type: external_exports.literal("turn.completed"),
29266
29233
  sessionId: external_exports.string(),
29267
- agentType: AgentTypeSchema,
29234
+ agentHarness: AgentHarnessSchema,
29268
29235
  messageId: external_exports.string(),
29269
29236
  turnId: external_exports.string().optional(),
29270
29237
  finishReason: FinishReasonSchema.optional(),
@@ -29281,7 +29248,7 @@ var RequestOpenedEventSchema = external_exports.object({
29281
29248
  type: external_exports.literal("request.opened"),
29282
29249
  requestId: external_exports.string(),
29283
29250
  sessionId: external_exports.string(),
29284
- agentType: AgentTypeSchema,
29251
+ agentHarness: AgentHarnessSchema,
29285
29252
  requestType: InteractionRequestTypeSchema,
29286
29253
  data: external_exports.unknown()
29287
29254
  });
@@ -29306,7 +29273,7 @@ var AgentSessionIdEventSchema = external_exports.object({
29306
29273
  var SessionTitleEventSchema = external_exports.object({
29307
29274
  type: external_exports.literal("session.title"),
29308
29275
  sessionId: external_exports.string(),
29309
- agentType: AgentTypeSchema,
29276
+ agentHarness: AgentHarnessSchema,
29310
29277
  title: external_exports.string()
29311
29278
  });
29312
29279
  var AgentEventSchema = external_exports.discriminatedUnion("type", [
@@ -29585,104 +29552,69 @@ var BrowserScreenshotResponseSchema = external_exports.object({
29585
29552
  title: external_exports.string().optional(),
29586
29553
  error: external_exports.string().optional()
29587
29554
  });
29588
- var SimScreenshotRequestSchema = external_exports.object({
29589
- sessionId: external_exports.string()
29590
- });
29591
- var SimScreenshotResponseSchema = external_exports.object({
29592
- image: external_exports.string().describe("Base64-encoded PNG screenshot"),
29593
- error: external_exports.string().optional()
29594
- });
29595
- var NormalizedCoord = external_exports.number().min(0).max(1);
29596
- var SimTapRequestSchema = external_exports.object({
29597
- sessionId: external_exports.string(),
29598
- x: NormalizedCoord.describe("Normalized X coordinate (0.0\u20131.0)"),
29599
- y: NormalizedCoord.describe("Normalized Y coordinate (0.0\u20131.0)")
29600
- });
29601
- var SimTapResponseSchema = external_exports.object({
29602
- success: external_exports.boolean(),
29603
- error: external_exports.string().optional()
29555
+ var InstalledAppSchema = external_exports.object({
29556
+ id: external_exports.string(),
29557
+ name: external_exports.string(),
29558
+ description: external_exports.string(),
29559
+ version: external_exports.string(),
29560
+ icon: external_exports.string().optional(),
29561
+ bootstrap: external_exports.string().optional()
29604
29562
  });
29605
- var SimSwipeRequestSchema = external_exports.object({
29606
- sessionId: external_exports.string(),
29607
- startX: NormalizedCoord.describe("Normalized start X (0.0\u20131.0)"),
29608
- startY: NormalizedCoord.describe("Normalized start Y (0.0\u20131.0)"),
29609
- endX: NormalizedCoord.describe("Normalized end X (0.0\u20131.0)"),
29610
- endY: NormalizedCoord.describe("Normalized end Y (0.0\u20131.0)"),
29611
- durationMs: external_exports.number().int().positive().max(3e4).optional().describe("Swipe duration in ms (default: 300)")
29563
+ var ListAppsRequestSchema = external_exports.object({
29564
+ sessionId: external_exports.string()
29612
29565
  });
29613
- var SimSwipeResponseSchema = external_exports.object({
29614
- success: external_exports.boolean(),
29615
- error: external_exports.string().optional()
29566
+ var ListAppsResponseSchema = external_exports.object({
29567
+ apps: external_exports.array(InstalledAppSchema),
29568
+ runningAppIds: external_exports.array(external_exports.string())
29616
29569
  });
29617
- var SimTypeTextRequestSchema = external_exports.object({
29618
- sessionId: external_exports.string(),
29619
- text: external_exports.string().describe("Text to type")
29570
+ var LaunchAppRequestSchema = external_exports.object({
29571
+ appId: external_exports.string(),
29572
+ sessionId: external_exports.string()
29620
29573
  });
29621
- var SimTypeTextResponseSchema = external_exports.object({
29622
- success: external_exports.boolean(),
29623
- error: external_exports.string().optional()
29574
+ var LaunchAppResponseSchema = external_exports.object({
29575
+ runningAppId: external_exports.string(),
29576
+ url: external_exports.string(),
29577
+ bootstrap: external_exports.string().optional()
29624
29578
  });
29625
- var SimPressKeyRequestSchema = external_exports.object({
29626
- sessionId: external_exports.string(),
29627
- keycode: external_exports.number().int().min(0).max(65535).describe("USB HID usage code"),
29628
- direction: external_exports.enum(["down", "up"]).optional().describe("Key direction (default: down+up)")
29579
+ var StopAppRequestSchema = external_exports.object({
29580
+ runningAppId: external_exports.string()
29629
29581
  });
29630
- var SimPressKeyResponseSchema = external_exports.object({
29631
- success: external_exports.boolean(),
29632
- error: external_exports.string().optional()
29582
+ var StopAppResponseSchema = external_exports.object({
29583
+ success: external_exports.boolean()
29633
29584
  });
29634
- var SimBuildAndRunRequestSchema = external_exports.object({
29635
- sessionId: external_exports.string(),
29636
- workspacePath: external_exports.string().describe("Path to the workspace containing the Xcode project")
29585
+ var ReadAppSkillRequestSchema = external_exports.object({
29586
+ appId: external_exports.string()
29637
29587
  });
29638
- var SimBuildAndRunResponseSchema = external_exports.object({
29639
- success: external_exports.boolean(),
29640
- bundleId: external_exports.string().optional(),
29641
- appName: external_exports.string().optional(),
29642
- error: external_exports.string().optional()
29588
+ var ReadAppSkillResponseSchema = external_exports.object({
29589
+ /** Concatenated markdown of every skill file the manifest declares, with
29590
+ * `# <path>` dividers. Empty string when the manifest has no skills. */
29591
+ content: external_exports.string()
29643
29592
  });
29644
- var SimListDevicesRequestSchema = external_exports.object({
29645
- sessionId: external_exports.string()
29593
+ var RegisterAppMcpRequestSchema = external_exports.object({
29594
+ serverName: external_exports.string(),
29595
+ url: external_exports.string()
29646
29596
  });
29647
- var SimListDevicesResponseSchema = external_exports.object({
29648
- devices: external_exports.array(
29649
- external_exports.object({
29650
- name: external_exports.string(),
29651
- udid: external_exports.string(),
29652
- state: external_exports.enum(["Booted", "Shutdown", "Unknown"]),
29653
- runtime: external_exports.string(),
29654
- deviceType: external_exports.string(),
29655
- isAvailable: external_exports.boolean()
29656
- })
29657
- ),
29658
- error: external_exports.string().optional()
29597
+ var RegisterAppMcpResponseSchema = external_exports.object({
29598
+ added: external_exports.array(external_exports.string()),
29599
+ errors: external_exports.record(external_exports.string(), external_exports.string()).optional()
29659
29600
  });
29660
- var SimStartRequestSchema = external_exports.object({
29661
- sessionId: external_exports.string(),
29662
- udid: external_exports.string().describe("UDID of the simulator to boot and start streaming")
29601
+ var UnregisterAppMcpRequestSchema = external_exports.object({
29602
+ serverName: external_exports.string()
29663
29603
  });
29664
- var SimStartResponseSchema = external_exports.object({
29665
- success: external_exports.boolean(),
29666
- url: external_exports.string().optional().describe("MJPEG stream URL"),
29667
- port: external_exports.number().optional(),
29668
- hidAvailable: external_exports.boolean().optional().describe("Whether HID touch/key injection is available"),
29669
- error: external_exports.string().optional()
29604
+ var UnregisterAppMcpResponseSchema = external_exports.object({
29605
+ removed: external_exports.array(external_exports.string())
29670
29606
  });
29671
29607
 
29672
29608
  // apps/agent-server/protocol.ts
29673
29609
  var FRONTEND_NOTIFICATIONS = {
29674
29610
  MESSAGE: "message",
29675
29611
  QUERY_ERROR: "queryError",
29676
- ENTER_PLAN_MODE: "enterPlanModeNotification",
29677
- STATUS_CHANGED: "statusChanged"
29612
+ ENTER_PLAN_MODE: "enterPlanModeNotification"
29678
29613
  };
29679
29614
 
29680
29615
  // apps/agent-server/event-broadcaster.ts
29681
29616
  var DATA_QUERY_TIMEOUT_MS = 1e4;
29682
- var SIMULATOR_SCREENSHOT_TIMEOUT_MS = 1e4;
29683
- var SIMULATOR_INTERACTION_TIMEOUT_MS = 1e4;
29684
- var SIMULATOR_BOOT_TIMEOUT_MS = 3e4;
29685
- var SIMULATOR_BUILD_TIMEOUT_MS = 6e5;
29617
+ var AAP_LAUNCH_TIMEOUT_MS = 6e4;
29686
29618
  var EventBroadcasterClass = class {
29687
29619
  // Multi-tunnel: all connected clients receive notifications.
29688
29620
  // The relay and desktop app can be connected simultaneously.
@@ -29720,13 +29652,6 @@ var EventBroadcasterClass = class {
29720
29652
  "sendEnterPlanModeNotification"
29721
29653
  );
29722
29654
  }
29723
- sendStatusChanged(notification) {
29724
- this.broadcastNotification(
29725
- FRONTEND_NOTIFICATIONS.STATUS_CHANGED,
29726
- notification,
29727
- "sendStatusChanged"
29728
- );
29729
- }
29730
29655
  // ==========================================================================
29731
29656
  // CANONICAL EVENT EMISSION (agent-server protocol — dual-write period)
29732
29657
  //
@@ -29740,88 +29665,88 @@ var EventBroadcasterClass = class {
29740
29665
  this.broadcastNotification(event.type, event, `emitEvent(${event.type})`);
29741
29666
  }
29742
29667
  // --- Session lifecycle ---
29743
- emitSessionStarted(sessionId, agentType) {
29668
+ emitSessionStarted(sessionId, agentHarness) {
29744
29669
  this.emitEvent({
29745
29670
  type: AGENT_EVENT_NAMES.SESSION_STARTED,
29746
29671
  sessionId,
29747
- agentType
29672
+ agentHarness
29748
29673
  });
29749
29674
  }
29750
- emitSessionIdle(sessionId, agentType) {
29675
+ emitSessionIdle(sessionId, agentHarness) {
29751
29676
  this.emitEvent({
29752
29677
  type: AGENT_EVENT_NAMES.SESSION_IDLE,
29753
29678
  sessionId,
29754
- agentType
29679
+ agentHarness
29755
29680
  });
29756
29681
  }
29757
- emitSessionError(sessionId, agentType, error48, category) {
29682
+ emitSessionError(sessionId, agentHarness, error48, category) {
29758
29683
  this.emitEvent({
29759
29684
  type: AGENT_EVENT_NAMES.SESSION_ERROR,
29760
29685
  sessionId,
29761
- agentType,
29686
+ agentHarness,
29762
29687
  error: error48,
29763
29688
  category
29764
29689
  });
29765
29690
  }
29766
- emitSessionCancelled(sessionId, agentType) {
29691
+ emitSessionCancelled(sessionId, agentHarness) {
29767
29692
  this.emitEvent({
29768
29693
  type: AGENT_EVENT_NAMES.SESSION_CANCELLED,
29769
29694
  sessionId,
29770
- agentType
29695
+ agentHarness
29771
29696
  });
29772
29697
  }
29773
29698
  // --- Messages ---
29774
- emitSystemMessage(sessionId, agentType, data) {
29699
+ emitSystemMessage(sessionId, agentHarness, data) {
29775
29700
  this.emitEvent({
29776
29701
  type: AGENT_EVENT_NAMES.MESSAGE_SYSTEM,
29777
29702
  sessionId,
29778
- agentType,
29703
+ agentHarness,
29779
29704
  data
29780
29705
  });
29781
29706
  }
29782
- emitAssistantMessage(sessionId, agentType, message, model) {
29707
+ emitAssistantMessage(sessionId, agentHarness, message, model) {
29783
29708
  this.emitEvent({
29784
29709
  type: AGENT_EVENT_NAMES.MESSAGE_ASSISTANT,
29785
29710
  sessionId,
29786
- agentType,
29711
+ agentHarness,
29787
29712
  message,
29788
29713
  ...model ? { model } : {}
29789
29714
  });
29790
29715
  }
29791
- emitToolResultMessage(sessionId, agentType, message, model) {
29716
+ emitToolResultMessage(sessionId, agentHarness, message, model) {
29792
29717
  this.emitEvent({
29793
29718
  type: AGENT_EVENT_NAMES.MESSAGE_TOOL_RESULT,
29794
29719
  sessionId,
29795
- agentType,
29720
+ agentHarness,
29796
29721
  message,
29797
29722
  ...model ? { model } : {}
29798
29723
  });
29799
29724
  }
29800
- emitMessageResult(sessionId, agentType, subtype, usage) {
29725
+ emitMessageResult(sessionId, agentHarness, subtype, usage) {
29801
29726
  this.emitEvent({
29802
29727
  type: AGENT_EVENT_NAMES.MESSAGE_RESULT,
29803
29728
  sessionId,
29804
- agentType,
29729
+ agentHarness,
29805
29730
  subtype,
29806
29731
  ...usage !== void 0 ? { usage } : {}
29807
29732
  });
29808
29733
  }
29809
- emitMessageCancelled(sessionId, agentType) {
29734
+ emitMessageCancelled(sessionId, agentHarness) {
29810
29735
  this.emitEvent({
29811
29736
  type: AGENT_EVENT_NAMES.MESSAGE_CANCELLED,
29812
29737
  sessionId,
29813
- agentType
29738
+ agentHarness
29814
29739
  });
29815
29740
  }
29816
29741
  // --- Turn & part lifecycle ---
29817
29742
  /** Dispatch a single PartEvent from an adapter. */
29818
- emitPartEvent(sessionId, agentType, messageId, event) {
29743
+ emitPartEvent(sessionId, agentHarness, messageId, event) {
29819
29744
  switch (event.type) {
29820
29745
  case "turn.started":
29821
29746
  this.emitEvent({
29822
29747
  type: AGENT_EVENT_NAMES.TURN_STARTED,
29823
29748
  sessionId,
29824
- agentType,
29749
+ agentHarness,
29825
29750
  messageId,
29826
29751
  turnId: event.turnId
29827
29752
  });
@@ -29830,7 +29755,7 @@ var EventBroadcasterClass = class {
29830
29755
  this.emitEvent({
29831
29756
  type: AGENT_EVENT_NAMES.MESSAGE_CREATED,
29832
29757
  sessionId,
29833
- agentType,
29758
+ agentHarness,
29834
29759
  messageId: event.messageId,
29835
29760
  role: event.role,
29836
29761
  ...event.parentToolCallId ? { parentToolCallId: event.parentToolCallId } : {}
@@ -29840,7 +29765,7 @@ var EventBroadcasterClass = class {
29840
29765
  this.emitEvent({
29841
29766
  type: AGENT_EVENT_NAMES.PART_CREATED,
29842
29767
  sessionId,
29843
- agentType,
29768
+ agentHarness,
29844
29769
  messageId: event.part.messageId,
29845
29770
  partId: event.part.id,
29846
29771
  part: event.part
@@ -29850,7 +29775,7 @@ var EventBroadcasterClass = class {
29850
29775
  this.emitEvent({
29851
29776
  type: AGENT_EVENT_NAMES.PART_DELTA,
29852
29777
  sessionId,
29853
- agentType,
29778
+ agentHarness,
29854
29779
  partId: event.partId,
29855
29780
  delta: event.delta
29856
29781
  });
@@ -29859,7 +29784,7 @@ var EventBroadcasterClass = class {
29859
29784
  this.emitEvent({
29860
29785
  type: AGENT_EVENT_NAMES.PART_DONE,
29861
29786
  sessionId,
29862
- agentType,
29787
+ agentHarness,
29863
29788
  messageId: event.part.messageId,
29864
29789
  partId: event.part.id,
29865
29790
  part: event.part
@@ -29869,7 +29794,7 @@ var EventBroadcasterClass = class {
29869
29794
  this.emitEvent({
29870
29795
  type: AGENT_EVENT_NAMES.MESSAGE_DONE,
29871
29796
  sessionId,
29872
- agentType,
29797
+ agentHarness,
29873
29798
  messageId: event.messageId,
29874
29799
  ...event.stopReason ? { stopReason: event.stopReason } : {},
29875
29800
  parts: event.parts,
@@ -29880,7 +29805,7 @@ var EventBroadcasterClass = class {
29880
29805
  this.emitEvent({
29881
29806
  type: AGENT_EVENT_NAMES.TURN_COMPLETED,
29882
29807
  sessionId,
29883
- agentType,
29808
+ agentHarness,
29884
29809
  messageId,
29885
29810
  turnId: event.turnId,
29886
29811
  ...event.finishReason ? { finishReason: event.finishReason } : {},
@@ -29891,12 +29816,12 @@ var EventBroadcasterClass = class {
29891
29816
  }
29892
29817
  }
29893
29818
  // --- Interaction requests ---
29894
- emitRequestOpened(requestId, sessionId, agentType, requestType, data) {
29819
+ emitRequestOpened(requestId, sessionId, agentHarness, requestType, data) {
29895
29820
  this.emitEvent({
29896
29821
  type: AGENT_EVENT_NAMES.REQUEST_OPENED,
29897
29822
  requestId,
29898
29823
  sessionId,
29899
- agentType,
29824
+ agentHarness,
29900
29825
  requestType,
29901
29826
  data
29902
29827
  });
@@ -29913,11 +29838,11 @@ var EventBroadcasterClass = class {
29913
29838
  });
29914
29839
  }
29915
29840
  // --- Metadata ---
29916
- emitSessionTitle(sessionId, agentType, title) {
29841
+ emitSessionTitle(sessionId, agentHarness, title) {
29917
29842
  this.emitEvent({
29918
29843
  type: AGENT_EVENT_NAMES.SESSION_TITLE,
29919
29844
  sessionId,
29920
- agentType,
29845
+ agentHarness,
29921
29846
  title
29922
29847
  });
29923
29848
  }
@@ -29964,59 +29889,36 @@ var EventBroadcasterClass = class {
29964
29889
  DATA_QUERY_TIMEOUT_MS
29965
29890
  );
29966
29891
  }
29967
- // --- Simulator automation RPCs ---
29968
- requestSimScreenshot(r2) {
29969
- return this.rpc(
29970
- FRONTEND_RPC_METHODS.SIM_SCREENSHOT,
29971
- r2,
29972
- SIMULATOR_SCREENSHOT_TIMEOUT_MS
29973
- );
29974
- }
29975
- requestSimTap(r2) {
29976
- return this.rpc(
29977
- FRONTEND_RPC_METHODS.SIM_TAP,
29978
- r2,
29979
- SIMULATOR_INTERACTION_TIMEOUT_MS
29980
- );
29981
- }
29982
- requestSimSwipe(r2) {
29983
- return this.rpc(
29984
- FRONTEND_RPC_METHODS.SIM_SWIPE,
29985
- r2,
29986
- SIMULATOR_INTERACTION_TIMEOUT_MS
29987
- );
29892
+ // --- AAP (Agentic Apps) RPCs (handled by backend's apps.service) ---
29893
+ //
29894
+ // Method names are stringly-typed because FRONTEND_RPC_METHODS is a frozen
29895
+ // enum canonical in shared/agent-events. AAP methods target the backend
29896
+ // directly (not forwarded to frontend), so they don't belong there.
29897
+ requestListApps(r2) {
29898
+ return this.rpc("aap/list-apps", r2, DATA_QUERY_TIMEOUT_MS);
29988
29899
  }
29989
- requestSimTypeText(r2) {
29990
- return this.rpc(
29991
- FRONTEND_RPC_METHODS.SIM_TYPE_TEXT,
29992
- r2,
29993
- SIMULATOR_INTERACTION_TIMEOUT_MS
29994
- );
29900
+ requestLaunchApp(r2) {
29901
+ return this.rpc("aap/launch-app", r2, AAP_LAUNCH_TIMEOUT_MS);
29995
29902
  }
29996
- requestSimPressKey(r2) {
29997
- return this.rpc(
29998
- FRONTEND_RPC_METHODS.SIM_PRESS_KEY,
29999
- r2,
30000
- SIMULATOR_INTERACTION_TIMEOUT_MS
30001
- );
29903
+ requestStopApp(r2) {
29904
+ return this.rpc("aap/stop-app", r2, DATA_QUERY_TIMEOUT_MS);
30002
29905
  }
30003
- requestSimBuildAndRun(r2) {
30004
- return this.rpc(
30005
- FRONTEND_RPC_METHODS.SIM_BUILD_AND_RUN,
30006
- r2,
30007
- SIMULATOR_BUILD_TIMEOUT_MS
30008
- );
29906
+ requestReadAppSkill(r2) {
29907
+ return this.rpc("aap/read-app-skill", r2, DATA_QUERY_TIMEOUT_MS);
30009
29908
  }
30010
- requestSimListDevices(r2) {
29909
+ // --- Simulator context RPC (handled by backend, not forwarded to frontend) ---
29910
+ /**
29911
+ * Query the backend for the simulator UDID assigned to this session's workspace.
29912
+ * The backend handles this directly from its in-memory simulator context map.
29913
+ * Returns null if no simulator is assigned to the workspace.
29914
+ */
29915
+ requestSimulatorContext(r2) {
30011
29916
  return this.rpc(
30012
- FRONTEND_RPC_METHODS.SIM_LIST_DEVICES,
29917
+ "getSimulatorContext",
30013
29918
  r2,
30014
29919
  DATA_QUERY_TIMEOUT_MS
30015
29920
  );
30016
29921
  }
30017
- requestSimStart(r2) {
30018
- return this.rpc(FRONTEND_RPC_METHODS.SIM_START, r2, SIMULATOR_BOOT_TIMEOUT_MS);
30019
- }
30020
29922
  // ==========================================================================
30021
29923
  // Internal helpers
30022
29924
  // ==========================================================================
@@ -30134,33 +30036,33 @@ function classifyStopReason(stopReason) {
30134
30036
  return null;
30135
30037
  }
30136
30038
  }
30137
- function persistCancellation(sessionId, agentType, _model) {
30138
- EventBroadcaster.emitSessionCancelled(sessionId, agentType);
30139
- EventBroadcaster.emitMessageCancelled(sessionId, agentType);
30039
+ function persistCancellation(sessionId, agentHarness) {
30040
+ EventBroadcaster.emitSessionCancelled(sessionId, agentHarness);
30041
+ EventBroadcaster.emitMessageCancelled(sessionId, agentHarness);
30140
30042
  }
30141
- function notifyAndRecordError(sessionId, agentType, classified, enrichMessage) {
30043
+ function notifyAndRecordError(sessionId, agentHarness, classified, enrichMessage) {
30142
30044
  const errorMessage = enrichMessage ? enrichMessage(classified) : classified.message;
30143
30045
  EventBroadcaster.emitSessionError(
30144
30046
  sessionId,
30145
- agentType,
30047
+ agentHarness,
30146
30048
  errorMessage,
30147
30049
  classified.category
30148
30050
  );
30149
30051
  }
30150
- function handleCancellation(sessionId, agentType, model, wasCancelled) {
30052
+ function handleCancellation(sessionId, agentHarness, wasCancelled) {
30151
30053
  if (!wasCancelled) return false;
30152
- persistCancellation(sessionId, agentType, model);
30054
+ persistCancellation(sessionId, agentHarness);
30153
30055
  return true;
30154
30056
  }
30155
- function handleQueryError(sessionId, agentType, error48, enrichMessage) {
30057
+ function handleQueryError(sessionId, agentHarness, error48, enrichMessage) {
30156
30058
  const classified = classifyError(error48);
30157
- notifyAndRecordError(sessionId, agentType, classified, enrichMessage);
30059
+ notifyAndRecordError(sessionId, agentHarness, classified, enrichMessage);
30158
30060
  }
30159
30061
 
30160
30062
  // apps/agent-server/agents/registry.ts
30161
30063
  var registry2 = /* @__PURE__ */ new Map();
30162
30064
  function registerAgent(handler) {
30163
- registry2.set(handler.agentType, handler);
30065
+ registry2.set(handler.agentHarness, handler);
30164
30066
  }
30165
30067
  function getAgent(type) {
30166
30068
  return registry2.get(type);
@@ -30180,7 +30082,7 @@ function initializeAllAgents() {
30180
30082
  }
30181
30083
  return results;
30182
30084
  }
30183
- function getRegisteredAgentTypes() {
30085
+ function getRegisteredAgentHarnesses() {
30184
30086
  return Array.from(registry2.keys());
30185
30087
  }
30186
30088
 
@@ -30414,7 +30316,32 @@ function createTextPart(sessionId, messageId, text, state3, partIndex) {
30414
30316
  return { id: uuidv72(), sessionId, messageId, type: "TEXT", partIndex, text, state: state3 };
30415
30317
  }
30416
30318
  function createReasoningPart(sessionId, messageId, text, state3, partIndex) {
30417
- return { id: uuidv72(), sessionId, messageId, type: "REASONING", partIndex, text, state: state3 };
30319
+ const now = (/* @__PURE__ */ new Date()).toISOString();
30320
+ return {
30321
+ id: uuidv72(),
30322
+ sessionId,
30323
+ messageId,
30324
+ type: "REASONING",
30325
+ partIndex,
30326
+ text,
30327
+ state: state3,
30328
+ time: {
30329
+ start: now,
30330
+ ...state3 === "DONE" ? { end: now } : {}
30331
+ }
30332
+ };
30333
+ }
30334
+ function completeReasoningPart(part, text = part.text) {
30335
+ const end = (/* @__PURE__ */ new Date()).toISOString();
30336
+ return {
30337
+ ...part,
30338
+ text,
30339
+ state: "DONE",
30340
+ time: {
30341
+ start: part.time?.start ?? end,
30342
+ end
30343
+ }
30344
+ };
30418
30345
  }
30419
30346
  function createToolPart(sessionId, messageId, opts) {
30420
30347
  return {
@@ -30551,15 +30478,18 @@ var ClaudeCodeTransformer = class {
30551
30478
  }
30552
30479
  process(event) {
30553
30480
  const parentToolCallId = this.extractParentToolCallId(event);
30481
+ const boundaryEvents = [];
30554
30482
  if (parentToolCallId !== this.lastParentToolCallId) {
30555
- this.closeText();
30556
- this.closeThinking();
30483
+ boundaryEvents.push(...this.closeActiveParts());
30484
+ const boundaryMessageDone = this.closeMessage();
30485
+ if (boundaryMessageDone) boundaryEvents.push(boundaryMessageDone);
30557
30486
  this.lastParentToolCallId = parentToolCallId;
30558
30487
  }
30559
30488
  let emitted = [];
30560
30489
  switch (event.type) {
30561
30490
  case "system":
30562
- return this.handleSystem(event);
30491
+ emitted = this.handleSystem(event);
30492
+ break;
30563
30493
  case "user":
30564
30494
  emitted = this.handleUser(event);
30565
30495
  break;
@@ -30570,21 +30500,18 @@ var ClaudeCodeTransformer = class {
30570
30500
  emitted = this.handleStream(event);
30571
30501
  break;
30572
30502
  case "result":
30573
- return this.handleResult(event);
30503
+ emitted = this.handleResult(event);
30504
+ break;
30574
30505
  default:
30575
- return [];
30506
+ return boundaryEvents;
30576
30507
  }
30577
30508
  if (parentToolCallId) {
30578
30509
  emitted = this.applyParentTag(emitted, parentToolCallId);
30579
30510
  }
30580
- return emitted;
30511
+ return [...boundaryEvents, ...emitted];
30581
30512
  }
30582
30513
  finish() {
30583
- const events = [];
30584
- const doneText = this.closeText();
30585
- if (doneText) events.push(doneText);
30586
- const doneThinking = this.closeThinking();
30587
- if (doneThinking) events.push(doneThinking);
30514
+ const events = [...this.closeActiveParts()];
30588
30515
  const usage = this.resultUsage.input > 0 ? this.resultUsage : this.accumulatedUsage;
30589
30516
  if (!this.turnCompletedEmitted) {
30590
30517
  events.push({
@@ -30634,11 +30561,10 @@ var ClaudeCodeTransformer = class {
30634
30561
  // -------------------------------------------------------------------------
30635
30562
  // Subagent lifecycle
30636
30563
  // -------------------------------------------------------------------------
30637
- registerSubagent(toolCallId, toolPartId, subagentType) {
30564
+ registerSubagent(toolCallId, toolPartId) {
30638
30565
  this.activeSubagents.set(toolCallId, {
30639
30566
  toolCallId,
30640
30567
  toolPartId,
30641
- subagentType,
30642
30568
  hasReceivedResult: false
30643
30569
  });
30644
30570
  }
@@ -30656,7 +30582,7 @@ var ClaudeCodeTransformer = class {
30656
30582
  const tr = block;
30657
30583
  const existing = this.toolParts.get(tr.tool_use_id);
30658
30584
  if (!existing) continue;
30659
- const output = typeof tr.content === "string" ? tr.content : JSON.stringify(tr.content);
30585
+ const output = typeof tr.content === "string" || Array.isArray(tr.content) ? tr.content : JSON.stringify(tr.content);
30660
30586
  const metadata = this.taskUsage.get(tr.tool_use_id);
30661
30587
  const updated = completeToolPart(existing, output, tr.is_error ?? false, metadata);
30662
30588
  this.replacePart(existing, updated);
@@ -30692,11 +30618,7 @@ var ClaudeCodeTransformer = class {
30692
30618
  return this.processStreamEvent(event.event);
30693
30619
  }
30694
30620
  handleResult(event) {
30695
- const events = [];
30696
- const doneText = this.closeText();
30697
- if (doneText) events.push(doneText);
30698
- const doneThinking = this.closeThinking();
30699
- if (doneThinking) events.push(doneThinking);
30621
+ const events = [...this.closeActiveParts()];
30700
30622
  if (event.usage) {
30701
30623
  this.resultUsage = mapSdkUsage(event.usage);
30702
30624
  }
@@ -30797,10 +30719,10 @@ var ClaudeCodeTransformer = class {
30797
30719
  case "thinking": {
30798
30720
  this.closeText();
30799
30721
  if (this.currentThinkingPart) {
30800
- const updated = {
30801
- ...this.currentThinkingPart,
30802
- text: this.currentThinkingPart.text + block.thinking
30803
- };
30722
+ const updated = completeReasoningPart(
30723
+ this.currentThinkingPart,
30724
+ this.currentThinkingPart.text + block.thinking
30725
+ );
30804
30726
  this.replacePart(this.currentThinkingPart, updated);
30805
30727
  this.currentThinkingPart = updated;
30806
30728
  return partDone(updated);
@@ -30835,7 +30757,7 @@ var ClaudeCodeTransformer = class {
30835
30757
  this.parts.push(part);
30836
30758
  this.toolParts.set(block.id, part);
30837
30759
  if (isAgent) {
30838
- this.registerSubagent(block.id, part.id, part.subagent?.type ?? "unknown");
30760
+ this.registerSubagent(block.id, part.id);
30839
30761
  }
30840
30762
  return created(part);
30841
30763
  }
@@ -30883,56 +30805,10 @@ var ClaudeCodeTransformer = class {
30883
30805
  onBlockDelta(event) {
30884
30806
  const delta = event.delta;
30885
30807
  switch (delta.type) {
30886
- case "text_delta": {
30887
- const closed = [];
30888
- const dt = this.closeThinking();
30889
- if (dt) closed.push(dt);
30890
- if (this.currentTextPart) {
30891
- const accumulated = {
30892
- ...this.currentTextPart,
30893
- text: this.currentTextPart.text + delta.text,
30894
- state: "STREAMING"
30895
- };
30896
- this.replacePart(this.currentTextPart, accumulated);
30897
- this.currentTextPart = accumulated;
30898
- return [...closed, { type: "part.delta", partId: accumulated.id, delta: delta.text }];
30899
- }
30900
- const part = createTextPart(
30901
- this.ctx.sessionId,
30902
- this.activeMessageId,
30903
- delta.text,
30904
- "STREAMING",
30905
- this.nextPartIndex
30906
- );
30907
- this.parts.push(part);
30908
- this.currentTextPart = part;
30909
- return [...closed, created(part)];
30910
- }
30911
- case "thinking_delta": {
30912
- const closed = [];
30913
- const dt = this.closeText();
30914
- if (dt) closed.push(dt);
30915
- if (this.currentThinkingPart) {
30916
- const accumulated = {
30917
- ...this.currentThinkingPart,
30918
- text: this.currentThinkingPart.text + delta.thinking,
30919
- state: "STREAMING"
30920
- };
30921
- this.replacePart(this.currentThinkingPart, accumulated);
30922
- this.currentThinkingPart = accumulated;
30923
- return [...closed, { type: "part.delta", partId: accumulated.id, delta: delta.thinking }];
30924
- }
30925
- const part = createReasoningPart(
30926
- this.ctx.sessionId,
30927
- this.activeMessageId,
30928
- delta.thinking,
30929
- "STREAMING",
30930
- this.nextPartIndex
30931
- );
30932
- this.parts.push(part);
30933
- this.currentThinkingPart = part;
30934
- return [...closed, created(part)];
30935
- }
30808
+ case "text_delta":
30809
+ return this.accumulateStreamDelta("text", delta.text);
30810
+ case "thinking_delta":
30811
+ return this.accumulateStreamDelta("reasoning", delta.thinking);
30936
30812
  case "input_json_delta": {
30937
30813
  const toolId = this.blockIndexToToolId.get(event.index);
30938
30814
  if (!toolId) return [];
@@ -30947,11 +30823,7 @@ var ClaudeCodeTransformer = class {
30947
30823
  }
30948
30824
  }
30949
30825
  onBlockStop(event) {
30950
- const closed = [];
30951
- const dt = this.closeText();
30952
- if (dt) closed.push(dt);
30953
- const dr = this.closeThinking();
30954
- if (dr) closed.push(dr);
30826
+ const closed = this.closeActiveParts();
30955
30827
  const toolId = this.blockIndexToToolId.get(event.index);
30956
30828
  if (toolId) {
30957
30829
  const existing = this.toolParts.get(toolId);
@@ -30967,7 +30839,7 @@ var ClaudeCodeTransformer = class {
30967
30839
  if (isSubagentTool(existing.toolName)) {
30968
30840
  const subagent = extractSubagentMetadata(input);
30969
30841
  updated = { ...updated, kind: "task", subagent };
30970
- this.registerSubagent(toolId, updated.id, subagent.type);
30842
+ this.registerSubagent(toolId, updated.id);
30971
30843
  }
30972
30844
  this.replacePart(existing, updated);
30973
30845
  this.toolParts.set(toolId, updated);
@@ -30997,11 +30869,7 @@ var ClaudeCodeTransformer = class {
30997
30869
  return [];
30998
30870
  }
30999
30871
  onMessageStop() {
31000
- const events = [];
31001
- const dt = this.closeText();
31002
- if (dt) events.push(dt);
31003
- const dr = this.closeThinking();
31004
- if (dr) events.push(dr);
30872
+ const events = this.closeActiveParts();
31005
30873
  const msgDone = this.closeMessage();
31006
30874
  if (msgDone) events.push(msgDone);
31007
30875
  return events;
@@ -31054,7 +30922,7 @@ var ClaudeCodeTransformer = class {
31054
30922
  closeThinking() {
31055
30923
  if (!this.currentThinkingPart) return null;
31056
30924
  if (this.currentThinkingPart.state === "STREAMING") {
31057
- const donePart = { ...this.currentThinkingPart, state: "DONE" };
30925
+ const donePart = completeReasoningPart(this.currentThinkingPart);
31058
30926
  this.replacePart(this.currentThinkingPart, donePart);
31059
30927
  this.currentThinkingPart = null;
31060
30928
  return partDone(donePart);
@@ -31062,6 +30930,48 @@ var ClaudeCodeTransformer = class {
31062
30930
  this.currentThinkingPart = null;
31063
30931
  return null;
31064
30932
  }
30933
+ closeActiveParts() {
30934
+ const events = [];
30935
+ const dt = this.closeText();
30936
+ if (dt) events.push(dt);
30937
+ const dr = this.closeThinking();
30938
+ if (dr) events.push(dr);
30939
+ return events;
30940
+ }
30941
+ /** Accumulate a streaming text or reasoning delta, closing the other part type first. */
30942
+ accumulateStreamDelta(kind, deltaText) {
30943
+ const closed = kind === "text" ? this.closeThinking() : this.closeText();
30944
+ const events = closed ? [closed] : [];
30945
+ const current = kind === "text" ? this.currentTextPart : this.currentThinkingPart;
30946
+ if (current) {
30947
+ const accumulated = {
30948
+ ...current,
30949
+ text: current.text + deltaText,
30950
+ state: "STREAMING"
30951
+ };
30952
+ this.replacePart(current, accumulated);
30953
+ if (kind === "text") this.currentTextPart = accumulated;
30954
+ else this.currentThinkingPart = accumulated;
30955
+ return [...events, { type: "part.delta", partId: accumulated.id, delta: deltaText }];
30956
+ }
30957
+ const part = kind === "text" ? createTextPart(
30958
+ this.ctx.sessionId,
30959
+ this.activeMessageId,
30960
+ deltaText,
30961
+ "STREAMING",
30962
+ this.nextPartIndex
30963
+ ) : createReasoningPart(
30964
+ this.ctx.sessionId,
30965
+ this.activeMessageId,
30966
+ deltaText,
30967
+ "STREAMING",
30968
+ this.nextPartIndex
30969
+ );
30970
+ this.parts.push(part);
30971
+ if (kind === "text") this.currentTextPart = part;
30972
+ else this.currentThinkingPart = part;
30973
+ return [...events, created(part)];
30974
+ }
31065
30975
  replacePart(old, next) {
31066
30976
  const i8 = this.parts.indexOf(old);
31067
30977
  if (i8 !== -1) this.parts[i8] = next;
@@ -31213,7 +31123,7 @@ function buildWorkspaceContext(cwd) {
31213
31123
  const projectName = getProjectName(cwd);
31214
31124
  return `You are working inside Deus, a desktop app that orchestrates multiple AI coding agents in parallel.
31215
31125
  Project: **${projectName}**. Your working directory is a git worktree at \`${cwd}\` \u2014 the directory name is the workspace name, not the project name. You can only edit files within this worktree. Each workspace has a .context directory (gitignored) for cross-agent collaboration.
31216
- A built-in browser and iOS Simulator are available for visually testing UI changes. If you don't see these tools, ask the user to enable them in Settings > Experimental Features.
31126
+ A built-in browser and iOS Simulator are available for testing UI changes. Simulator tools (SimulatorListDevices, SimulatorScreenshot, SimulatorTap, SimulatorTypeText, SimulatorSwipe, SimulatorPressKey, SimulatorBuild, SimulatorLaunch, SimulatorReadScreen, SimulatorWaitFor, SimulatorGetProjectInfo) are built-in. If you don't see these tools, ask the user to enable them in Settings > Experimental Features.
31217
31127
  You can render live HTML+CSS previews inline in chat using the \`html-preview\` code fence \u2014 it renders in an isolated Shadow DOM instead of showing code. Use this naturally whenever showing is clearer than describing (design options, component variations, layout ideas).`;
31218
31128
  }
31219
31129
 
@@ -31289,20 +31199,15 @@ function verifyCandidate(candidate, versionFlag) {
31289
31199
  }
31290
31200
  return (0, import_child_process5.execFileSync)(candidate, [versionFlag], opts).trim();
31291
31201
  }
31292
- function blockIfNotInitialized(state3, agentType, sessionId) {
31202
+ function blockIfNotInitialized(state3, agentHarness, sessionId) {
31293
31203
  if (!state3.result?.success) {
31294
31204
  const errorMsg = `Cannot process request: ${state3.result?.error || "Initialization failed"}`;
31295
31205
  try {
31296
- EventBroadcaster.emitSessionError(sessionId, agentType, errorMsg, "internal");
31297
- } catch (error48) {
31298
- console.warn(`[CLI-DISCOVERY] Failed to emit init error:`, error48);
31299
- }
31300
- try {
31301
- EventBroadcaster.emitSessionError(sessionId, agentType, errorMsg, "internal");
31206
+ EventBroadcaster.emitSessionError(sessionId, agentHarness, errorMsg, "internal");
31302
31207
  } catch (error48) {
31303
31208
  console.warn(`[CLI-DISCOVERY] Failed to emit session error:`, error48);
31304
31209
  }
31305
- console.log(`Blocked ${agentType} request due to initialization failure`);
31210
+ console.log(`Blocked ${agentHarness} request due to initialization failure`);
31306
31211
  return true;
31307
31212
  }
31308
31213
  return false;
@@ -31317,7 +31222,7 @@ function getClaudeExecutablePath() {
31317
31222
  function initializeClaude() {
31318
31223
  return discoverExecutable(
31319
31224
  {
31320
- agentType: "claude",
31225
+ agentHarness: "claude",
31321
31226
  displayName: "Claude",
31322
31227
  envVar: "CLAUDE_CLI_PATH",
31323
31228
  staticCandidates: [
@@ -31334,28 +31239,6 @@ function blockIfNotInitialized2(sessionId) {
31334
31239
  return blockIfNotInitialized(state, "claude", sessionId);
31335
31240
  }
31336
31241
 
31337
- // apps/agent-server/agents/claude/claude-models.ts
31338
- var BEDROCK_MAPPINGS = {
31339
- opus: "global.anthropic.claude-opus-4-5-20251101-v1:0",
31340
- sonnet: "global.anthropic.claude-sonnet-4-6-20260217-v1:0",
31341
- haiku: "global.anthropic.claude-haiku-4-5-20251001-v1:0"
31342
- };
31343
- var VERTEX_MAPPINGS = {
31344
- opus: "claude-opus-4-5@20251101",
31345
- sonnet: "claude-sonnet-4-6@20260217",
31346
- haiku: "claude-haiku-4-5@20251001"
31347
- };
31348
- function mapModelForProvider(simpleModel, envVars) {
31349
- if (!simpleModel) return void 0;
31350
- if (envVars.CLAUDE_CODE_USE_BEDROCK === "1") {
31351
- return BEDROCK_MAPPINGS[simpleModel] ?? simpleModel;
31352
- }
31353
- if (envVars.CLAUDE_CODE_USE_VERTEX === "1") {
31354
- return VERTEX_MAPPINGS[simpleModel] ?? simpleModel;
31355
- }
31356
- return simpleModel;
31357
- }
31358
-
31359
31242
  // apps/agent-server/agents/claude/claude-sdk-options.ts
31360
31243
  var fs2 = __toESM(require("fs"), 1);
31361
31244
  var path4 = __toESM(require("path"), 1);
@@ -32560,403 +32443,924 @@ Returns a fresh snapshot after scrolling.`,
32560
32443
  ];
32561
32444
  }
32562
32445
 
32563
- // apps/agent-server/agents/deus-tools/simulator.ts
32446
+ // apps/agent-server/agents/deus-tools/apps.ts
32564
32447
  init_sdk();
32565
- function createSimulatorTools(sessionId) {
32448
+ function textResult2(text) {
32449
+ return { content: [{ type: "text", text }] };
32450
+ }
32451
+ function withErrorCatch(fn) {
32452
+ return async (args) => {
32453
+ try {
32454
+ return await fn(args);
32455
+ } catch (err) {
32456
+ return textResult2(`AAP error: ${getErrorMessage(err)}`);
32457
+ }
32458
+ };
32459
+ }
32460
+ function createAppsTools(sessionId) {
32566
32461
  return [
32567
- // ====================================================================
32568
- // iOSSimulatorListDevices
32569
- // ====================================================================
32462
+ // -- ListApps -------------------------------------------------------------
32570
32463
  Tb(
32571
- "iOSSimulatorListDevices",
32572
- `List all available iOS simulators installed on the system.
32464
+ "list_apps",
32465
+ `List installed Deus apps and which are currently running in YOUR workspace.
32573
32466
 
32574
- Returns each simulator's name, UDID, state (Booted/Shutdown), runtime (iOS version), and device type. Use this to find a simulator to boot with iOSSimulatorStart.
32467
+ Returns a JSON object:
32468
+ { apps: InstalledApp[], runningAppIds: string[] }
32469
+ Each app has { id, name, description, version, icon?, bootstrap? }.
32470
+ Use the app's \`id\` (e.g. "deus.mobile-use") as the argument to launch_app.
32575
32471
 
32576
- Example output:
32577
- - iPhone 16 Pro (UDID: ABC123) - Shutdown - iOS-18-2
32578
- - iPhone 16e (UDID: DEF456) - Booted - iOS-26-1`,
32472
+ Running apps are auto-scoped to the agent's current session/workspace;
32473
+ you don't need (and can't pass) a workspaceId.`,
32579
32474
  {},
32580
- async () => {
32581
- console.log(`[deusMCPServer] iOSSimulatorListDevices invoked for session ${sessionId}`);
32582
- try {
32583
- const response = await EventBroadcaster.requestSimListDevices({ sessionId });
32584
- if (response.error) {
32585
- return {
32586
- content: [{ type: "text", text: `Failed to list devices: ${response.error}` }]
32587
- };
32588
- }
32589
- if (response.devices.length === 0) {
32590
- return {
32591
- content: [
32592
- {
32593
- type: "text",
32594
- text: "No iOS simulators found. Install simulators via Xcode \u2192 Settings \u2192 Platforms."
32595
- }
32596
- ]
32597
- };
32598
- }
32599
- const lines = response.devices.map(
32600
- (d3) => `- ${d3.name} (${d3.udid}) \u2014 ${d3.state} \u2014 ${d3.runtime}${d3.deviceType ? ` \u2014 ${d3.deviceType}` : ""}`
32601
- );
32602
- return {
32603
- content: [
32604
- {
32605
- type: "text",
32606
- text: `Found ${response.devices.length} simulator(s):
32607
- ${lines.join("\n")}
32608
-
32609
- Use iOSSimulatorStart with a UDID to boot and start streaming a simulator.`
32610
- }
32611
- ]
32612
- };
32613
- } catch (err) {
32614
- return {
32615
- content: [{ type: "text", text: `Failed to list simulators: ${getErrorMessage(err)}` }]
32616
- };
32617
- }
32618
- }
32475
+ withErrorCatch(async () => {
32476
+ console.log(`[deusMCPServer] list_apps invoked for session ${sessionId}`);
32477
+ const response = await EventBroadcaster.requestListApps({ sessionId });
32478
+ return textResult2(JSON.stringify(response, null, 2));
32479
+ })
32619
32480
  ),
32620
- // ====================================================================
32621
- // iOSSimulatorStart
32622
- // ====================================================================
32481
+ // -- LaunchApp ------------------------------------------------------------
32623
32482
  Tb(
32624
- "iOSSimulatorStart",
32625
- `Boot an iOS simulator and start MJPEG streaming in the app's Simulator panel.
32626
-
32627
- This makes the simulator visible in the Simulator panel and enables all other iOSSimulator tools (Screenshot, Tap, Swipe, TypeText, PressKey, BuildAndRun).
32483
+ "launch_app",
32484
+ `Launch an installed Deus app in YOUR current workspace. The backend
32485
+ spawns the app's subprocess, waits for its ready probe, and (on success)
32486
+ registers its MCP tools into THIS agent session. New tools appear as
32487
+ \`mcp__{app_server_name}__*\` (e.g. \`mcp__deus_mobile_use__snapshot\` for
32488
+ the mobile-use app) within a few seconds \u2014 they're immediately callable.
32628
32489
 
32629
- Use iOSSimulatorListDevices first to find available simulators and their UDIDs.
32490
+ One instance per (appId, workspace): a duplicate launch returns the
32491
+ existing runningAppId. The app's manifest \`bootstrap\` \u2014 a short help
32492
+ string \u2014 is returned so you know how to use its tools.
32630
32493
 
32631
- After starting, the simulator stream will appear in the app's Simulator panel. Use iOSSimulatorScreenshot to see the screen and interact with it.`,
32494
+ Workspace is inferred from your session \u2014 do NOT pass a workspaceId.`,
32632
32495
  {
32633
- udid: external_exports.string().describe("UDID of the simulator to boot (get from iOSSimulatorListDevices)")
32496
+ appId: external_exports.string().describe('App id (e.g. "deus.mobile-use"). Get from list_apps.')
32634
32497
  },
32635
- async (args) => {
32498
+ withErrorCatch(async (args) => {
32636
32499
  console.log(
32637
- `[deusMCPServer] iOSSimulatorStart invoked for session ${sessionId}: udid=${args.udid}`
32500
+ `[deusMCPServer] launch_app invoked for session ${sessionId} appId=${args.appId}`
32638
32501
  );
32639
- try {
32640
- const response = await EventBroadcaster.requestSimStart({
32641
- sessionId,
32642
- udid: args.udid
32643
- });
32644
- if (response.error) {
32645
- return {
32646
- content: [{ type: "text", text: `Failed to start simulator: ${response.error}` }]
32647
- };
32648
- }
32649
- const details = [
32650
- `Simulator started and streaming.`,
32651
- response.url ? `Stream URL: ${response.url}` : null,
32652
- response.hidAvailable === false ? `Warning: HID not available \u2014 touch/key input may not work.` : null,
32653
- `Use iOSSimulatorScreenshot to see the screen.`
32654
- ].filter(Boolean).join("\n");
32655
- return {
32656
- content: [{ type: "text", text: details }]
32657
- };
32658
- } catch (err) {
32659
- return {
32660
- content: [
32661
- {
32662
- type: "text",
32663
- text: `Failed to start simulator: ${getErrorMessage(err)}. Make sure the UDID is valid (use iOSSimulatorListDevices to check).`
32664
- }
32665
- ]
32666
- };
32502
+ const response = await EventBroadcaster.requestLaunchApp({
32503
+ appId: args.appId,
32504
+ sessionId
32505
+ });
32506
+ const lines = [
32507
+ `Launched ${args.appId}`,
32508
+ ` runningAppId: ${response.runningAppId}`,
32509
+ ` url: ${response.url}`
32510
+ ];
32511
+ if (response.bootstrap) {
32512
+ lines.push("", `App bootstrap hint:`, response.bootstrap);
32667
32513
  }
32668
- }
32514
+ lines.push(
32515
+ "",
32516
+ `The app's MCP tools (mcp__{server}__*) will appear in your tool list shortly.`
32517
+ );
32518
+ return textResult2(lines.join("\n"));
32519
+ })
32669
32520
  ),
32670
- // ====================================================================
32671
- // iOSSimulatorScreenshot
32672
- // ====================================================================
32521
+ // -- StopApp --------------------------------------------------------------
32673
32522
  Tb(
32674
- "iOSSimulatorScreenshot",
32675
- `Capture a screenshot of the currently running iOS simulator. Returns a JPEG image of the simulator screen.
32676
-
32677
- Use this to see the current state of the app running in the simulator before interacting with it. The screenshot shows exactly what the user would see on the device screen.
32678
-
32679
- The simulator must be booted and streaming (use iOSSimulatorStart first).`,
32680
- {},
32681
- async () => {
32682
- console.log(`[deusMCPServer] iOSSimulatorScreenshot invoked for session ${sessionId}`);
32683
- try {
32684
- const response = await EventBroadcaster.requestSimScreenshot({ sessionId });
32685
- if (response.error) {
32686
- return {
32687
- content: [{ type: "text", text: `Screenshot failed: ${response.error}` }]
32688
- };
32689
- }
32690
- return {
32691
- content: [
32692
- {
32693
- type: "image",
32694
- data: response.image,
32695
- mimeType: "image/jpeg"
32696
- }
32697
- ]
32698
- };
32699
- } catch (err) {
32700
- return {
32701
- content: [
32702
- {
32703
- type: "text",
32704
- text: `Simulator not available: ${getErrorMessage(err)}. Use iOSSimulatorStart to boot a simulator first.`
32705
- }
32706
- ]
32707
- };
32708
- }
32709
- }
32523
+ "stop_app",
32524
+ `Stop a running Deus app by its runningAppId. The backend sends SIGTERM,
32525
+ waits for the stop timeout, then SIGKILLs if needed. The app's MCP tools
32526
+ are automatically removed from your tool list.`,
32527
+ {
32528
+ runningAppId: external_exports.string().describe("The runningAppId returned by launch_app.")
32529
+ },
32530
+ withErrorCatch(async (args) => {
32531
+ console.log(
32532
+ `[deusMCPServer] stop_app invoked for session ${sessionId} runningAppId=${args.runningAppId}`
32533
+ );
32534
+ const response = await EventBroadcaster.requestStopApp({
32535
+ runningAppId: args.runningAppId
32536
+ });
32537
+ return textResult2(
32538
+ response.success ? `Stopped runningAppId ${args.runningAppId}.` : `Failed to stop runningAppId ${args.runningAppId}.`
32539
+ );
32540
+ })
32710
32541
  ),
32711
- // ====================================================================
32712
- // iOSSimulatorTap
32713
- // ====================================================================
32542
+ // -- ReadAppSkill ---------------------------------------------------------
32714
32543
  Tb(
32715
- "iOSSimulatorTap",
32716
- `Tap on the iOS simulator screen at the specified coordinates.
32717
-
32718
- Coordinates are normalized (0.0 to 1.0) where:
32719
- - (0.0, 0.0) is the top-left corner
32720
- - (1.0, 1.0) is the bottom-right corner
32721
- - (0.5, 0.5) is the center of the screen
32544
+ "read_app_skill",
32545
+ `Read the detailed usage docs ("skill") an installed Deus app ships with.
32546
+ The \`launch_app\` tool deliberately keeps its response lean \u2014 call this
32547
+ only when you need deeper guidance on how to drive the app's MCP tools
32548
+ (typical triggers: first use of an app in a session, or unfamiliar tool
32549
+ names showing up after a launch). Content is markdown; may include
32550
+ command examples, workflow patterns, and JSON shape references.
32722
32551
 
32723
- Use iOSSimulatorScreenshot first to see the current screen, then estimate the coordinates of the element you want to tap.`,
32552
+ Returns an empty string if the app declares no skills.`,
32724
32553
  {
32725
- x: external_exports.number().min(0).max(1).describe("Normalized X coordinate (0.0\u20131.0, left to right)"),
32726
- y: external_exports.number().min(0).max(1).describe("Normalized Y coordinate (0.0\u20131.0, top to bottom)")
32554
+ appId: external_exports.string().describe('App id (e.g. "deus.mobile-use"). Get from list_apps.')
32727
32555
  },
32728
- async (args) => {
32556
+ withErrorCatch(async (args) => {
32729
32557
  console.log(
32730
- `[deusMCPServer] iOSSimulatorTap invoked for session ${sessionId}: (${args.x}, ${args.y})`
32558
+ `[deusMCPServer] read_app_skill invoked for session ${sessionId} appId=${args.appId}`
32559
+ );
32560
+ const response = await EventBroadcaster.requestReadAppSkill({ appId: args.appId });
32561
+ return textResult2(
32562
+ response.content.length > 0 ? response.content : `No skills declared for ${args.appId}.`
32563
+ );
32564
+ })
32565
+ )
32566
+ ];
32567
+ }
32568
+
32569
+ // apps/agent-server/agents/deus-tools/simulator.ts
32570
+ init_sdk();
32571
+
32572
+ // apps/agent-server/agents/deus-tools/sim-ops.ts
32573
+ var import_child_process7 = require("child_process");
32574
+ var import_util5 = require("util");
32575
+ var import_promises6 = require("fs/promises");
32576
+ var import_os3 = require("os");
32577
+ var import_path11 = require("path");
32578
+ var import_fs3 = require("fs");
32579
+ var execFileAsync = (0, import_util5.promisify)(import_child_process7.execFile);
32580
+ var _engine = null;
32581
+ var _executor = null;
32582
+ var SIM_ENV = {
32583
+ ...process.env,
32584
+ DEVELOPER_DIR: process.env["DEVELOPER_DIR"] ?? "/Applications/Xcode.app/Contents/Developer"
32585
+ };
32586
+ async function getEngine() {
32587
+ if (!_engine) {
32588
+ _engine = await import("device-use/engine");
32589
+ _executor = _engine.createExecutor({ env: SIM_ENV });
32590
+ }
32591
+ return { engine: _engine, executor: _executor };
32592
+ }
32593
+ var _simBridgePath;
32594
+ function findUpwards(startDir, rel) {
32595
+ let dir = startDir;
32596
+ while (true) {
32597
+ const candidate = (0, import_path11.join)(dir, rel);
32598
+ if ((0, import_fs3.existsSync)(candidate)) return candidate;
32599
+ const parent = (0, import_path11.dirname)(dir);
32600
+ if (parent === dir) return null;
32601
+ dir = parent;
32602
+ }
32603
+ }
32604
+ function resolveSimBridgePath() {
32605
+ if (_simBridgePath !== void 0) return _simBridgePath;
32606
+ const envOverride = process.env["DEVICE_USE_SIMBRIDGE"];
32607
+ if (envOverride && (0, import_fs3.existsSync)(envOverride)) {
32608
+ _simBridgePath = envOverride;
32609
+ return envOverride;
32610
+ }
32611
+ const resourcesPath = process.resourcesPath;
32612
+ if (resourcesPath) {
32613
+ const packaged = (0, import_path11.join)(resourcesPath, "simulator", "simbridge");
32614
+ if ((0, import_fs3.existsSync)(packaged)) {
32615
+ _simBridgePath = packaged;
32616
+ return packaged;
32617
+ }
32618
+ }
32619
+ const devCandidates = [
32620
+ "packages/device-use/bin/simbridge",
32621
+ "node_modules/device-use/bin/simbridge",
32622
+ "packages/device-use/native/.build/release/simbridge",
32623
+ "packages/device-use/native/.build/arm64-apple-macosx/release/simbridge"
32624
+ ];
32625
+ for (const rel of devCandidates) {
32626
+ const found = findUpwards(process.cwd(), rel);
32627
+ if (found) {
32628
+ _simBridgePath = found;
32629
+ return found;
32630
+ }
32631
+ }
32632
+ _simBridgePath = null;
32633
+ return null;
32634
+ }
32635
+ async function callSimBridge(request) {
32636
+ const bridgePath = resolveSimBridgePath();
32637
+ if (!bridgePath) {
32638
+ throw new Error(
32639
+ "simbridge binary not found. Run `bun install` or `bun run prepare:device-use` in repo root."
32640
+ );
32641
+ }
32642
+ await execFileAsync(bridgePath, [JSON.stringify(request)], {
32643
+ timeout: 3e4,
32644
+ env: SIM_ENV,
32645
+ maxBuffer: 10 * 1024 * 1024
32646
+ });
32647
+ }
32648
+ async function resolveDevice(destination, sessionId) {
32649
+ if (destination) {
32650
+ if (/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i.test(destination)) {
32651
+ return destination;
32652
+ }
32653
+ const devices2 = await listDevices();
32654
+ const match = devices2.find((d3) => d3.name.toLowerCase() === destination.toLowerCase()) ?? devices2.find((d3) => d3.name.toLowerCase().includes(destination.toLowerCase()));
32655
+ if (match) return match.udid;
32656
+ throw new Error(`Simulator "${destination}" not found`);
32657
+ }
32658
+ if (sessionId) {
32659
+ const ctx = await EventBroadcaster.requestSimulatorContext({ sessionId });
32660
+ if (ctx?.udid) return ctx.udid;
32661
+ throw new Error(
32662
+ "No simulator assigned to this workspace. Start one via the Simulator panel or specify a destination (simulator name or UDID)."
32663
+ );
32664
+ }
32665
+ const devices = await listDevices();
32666
+ const booted = devices.find((d3) => d3.state === "Booted");
32667
+ if (booted) return booted.udid;
32668
+ throw new Error("No booted simulator found. Boot one first or specify a destination.");
32669
+ }
32670
+ async function listDevices() {
32671
+ const { engine, executor } = await getEngine();
32672
+ const sims = await engine.listSimulators(executor);
32673
+ return sims.map((s3) => ({
32674
+ udid: s3.udid,
32675
+ name: s3.name,
32676
+ state: s3.state,
32677
+ runtime: s3.runtime,
32678
+ deviceType: s3.name.replace(/-/g, " "),
32679
+ isAvailable: s3.isAvailable
32680
+ }));
32681
+ }
32682
+ async function screenshot(udid, format = "jpeg") {
32683
+ const { engine, executor } = await getEngine();
32684
+ const outputPath = (0, import_path11.join)((0, import_os3.tmpdir)(), `deus-sim-${udid.slice(0, 8)}-${Date.now()}.${format}`);
32685
+ await engine.takeScreenshot(executor, udid, outputPath, { format });
32686
+ const { readFile, unlink: unlink3 } = await import("fs/promises");
32687
+ const buf = await readFile(outputPath);
32688
+ await unlink3(outputPath).catch(() => {
32689
+ });
32690
+ return {
32691
+ base64: buf.toString("base64"),
32692
+ mimeType: `image/${format}`
32693
+ };
32694
+ }
32695
+ var refCache = /* @__PURE__ */ new Map();
32696
+ var screenBoundsCache = /* @__PURE__ */ new Map();
32697
+ function refCacheKey(sessionKey, udid) {
32698
+ return `${sessionKey ?? "__no_session__"}:${udid}`;
32699
+ }
32700
+ function recordRefs(sessionKey, udid, entries, rootFrame) {
32701
+ const key = refCacheKey(sessionKey, udid);
32702
+ const map2 = /* @__PURE__ */ new Map();
32703
+ for (const e3 of entries) {
32704
+ map2.set(e3.ref, {
32705
+ ref: e3.ref,
32706
+ center: e3.center,
32707
+ label: e3.label,
32708
+ identifier: e3.identifier,
32709
+ type: e3.type
32710
+ });
32711
+ }
32712
+ refCache.set(key, map2);
32713
+ if (rootFrame?.width && rootFrame?.height) {
32714
+ screenBoundsCache.set(udid, { width: rootFrame.width, height: rootFrame.height });
32715
+ }
32716
+ }
32717
+ async function fetchScreenBounds(udid) {
32718
+ const cached2 = screenBoundsCache.get(udid);
32719
+ if (cached2) return cached2;
32720
+ try {
32721
+ const { engine } = await getEngine();
32722
+ const tree = await engine.fetchAccessibilityTree(udid);
32723
+ const app = tree.find((n3) => n3.type === "Application") ?? tree[0];
32724
+ if (app?.frame?.width && app?.frame?.height) {
32725
+ const bounds = { width: app.frame.width, height: app.frame.height };
32726
+ screenBoundsCache.set(udid, bounds);
32727
+ return bounds;
32728
+ }
32729
+ } catch {
32730
+ }
32731
+ return null;
32732
+ }
32733
+ async function readScreen(udid, opts) {
32734
+ let formatted = "[accessibility tree unavailable]";
32735
+ try {
32736
+ const { engine } = await getEngine();
32737
+ const tree = await engine.fetchAccessibilityTree(udid);
32738
+ const snapshot = engine.buildSnapshot(tree, {
32739
+ interactiveOnly: opts.filter !== "all"
32740
+ });
32741
+ formatted = engine.formatTree(snapshot.tree);
32742
+ if (!formatted) {
32743
+ formatted = "[no elements matched filter]";
32744
+ }
32745
+ const rootApp = tree.find((n3) => n3.type === "Application") ?? tree[0];
32746
+ recordRefs(opts.sessionKey, udid, snapshot.refs ?? [], rootApp?.frame);
32747
+ } catch (err) {
32748
+ formatted = `[failed to read accessibility tree: ${err instanceof Error ? err.message : String(err)}]`;
32749
+ }
32750
+ let screenshotData;
32751
+ if (opts.includeScreenshot !== false) {
32752
+ screenshotData = await screenshot(udid, "jpeg");
32753
+ }
32754
+ return { formatted, screenshot: screenshotData };
32755
+ }
32756
+ async function tap(udid, opts) {
32757
+ if (opts.ref) {
32758
+ const map2 = refCache.get(refCacheKey(opts.sessionKey, udid));
32759
+ const normalized = opts.ref.startsWith("@") ? opts.ref : `@${opts.ref}`;
32760
+ const entry = map2?.get(normalized);
32761
+ if (!entry) {
32762
+ throw new Error(
32763
+ `Ref ${normalized} not found. Call SimulatorReadScreen first \u2014 refs live only until the next screen read, and must come from its output.`
32764
+ );
32765
+ }
32766
+ await callSimBridge({ command: "tap", udid, x: entry.center.x, y: entry.center.y });
32767
+ return;
32768
+ }
32769
+ if (opts.identifier) {
32770
+ const { engine } = await getEngine();
32771
+ const tree = await engine.fetchAccessibilityTree(udid);
32772
+ const el = findInTreeBy(tree, (n3) => n3.identifier === opts.identifier);
32773
+ if (!el) {
32774
+ throw new Error(
32775
+ `Element with identifier "${opts.identifier}" not found. Identifiers come from app code (accessibilityIdentifier in SwiftUI, accessibilityIdentifier in UIKit).`
32776
+ );
32777
+ }
32778
+ await callSimBridge({ command: "tap", udid, x: el.center.x, y: el.center.y });
32779
+ return;
32780
+ }
32781
+ if (opts.label) {
32782
+ const { engine } = await getEngine();
32783
+ const tree = await engine.fetchAccessibilityTree(udid);
32784
+ const el = findInTreeBy(tree, (n3) => n3.label === opts.label);
32785
+ if (!el) {
32786
+ const available = collectLabels(tree).slice(0, 15);
32787
+ const hint = available.length > 0 ? ` Available labels: ${available.join(", ")}.` : "";
32788
+ throw new Error(
32789
+ `Element with label "${opts.label}" not found. Matches iOS accessibility label, not placeholder/visible text.${hint}`
32790
+ );
32791
+ }
32792
+ await callSimBridge({ command: "tap", udid, x: el.center.x, y: el.center.y });
32793
+ return;
32794
+ }
32795
+ if (typeof opts.x === "number" && typeof opts.y === "number") {
32796
+ const bounds = await fetchScreenBounds(udid);
32797
+ if (bounds) {
32798
+ if (opts.x < 0 || opts.y < 0 || opts.x > bounds.width || opts.y > bounds.height) {
32799
+ throw new Error(
32800
+ `(${opts.x}, ${opts.y}) is off-screen \u2014 device is ${Math.round(bounds.width)}x${Math.round(bounds.height)} logical points.`
32731
32801
  );
32732
- try {
32733
- const response = await EventBroadcaster.requestSimTap({
32734
- sessionId,
32735
- x: args.x,
32736
- y: args.y
32737
- });
32738
- if (response.error) {
32739
- return {
32740
- content: [{ type: "text", text: `Tap failed: ${response.error}` }]
32741
- };
32742
- }
32743
- return {
32744
- content: [
32745
- {
32746
- type: "text",
32747
- text: `Tapped at (${args.x.toFixed(2)}, ${args.y.toFixed(2)}). Use iOSSimulatorScreenshot to see the result.`
32748
- }
32749
- ]
32750
- };
32751
- } catch (err) {
32752
- return {
32753
- content: [{ type: "text", text: `Simulator not available: ${getErrorMessage(err)}` }]
32754
- };
32755
- }
32756
32802
  }
32803
+ }
32804
+ await callSimBridge({ command: "tap", udid, x: opts.x, y: opts.y });
32805
+ return;
32806
+ }
32807
+ throw new Error("tap requires one of: ref, identifier, label, or (x, y) coordinates");
32808
+ }
32809
+ function findInTreeBy(nodes, predicate) {
32810
+ for (const n3 of nodes) {
32811
+ if (predicate(n3)) return n3;
32812
+ if (n3.children) {
32813
+ const found = findInTreeBy(n3.children, predicate);
32814
+ if (found) return found;
32815
+ }
32816
+ }
32817
+ return null;
32818
+ }
32819
+ function collectLabels(nodes) {
32820
+ const labels = [];
32821
+ const walk = (list) => {
32822
+ for (const n3 of list) {
32823
+ if (typeof n3.label === "string" && n3.label.length > 0) labels.push(n3.label);
32824
+ if (n3.children) walk(n3.children);
32825
+ }
32826
+ };
32827
+ walk(nodes);
32828
+ return [...new Set(labels)];
32829
+ }
32830
+ async function typeText(udid, text, opts) {
32831
+ await callSimBridge({ command: "type", udid, text, submit: opts?.submit ?? false });
32832
+ }
32833
+ async function swipe(udid, opts) {
32834
+ let sx, sy, ex, ey;
32835
+ if (opts.direction) {
32836
+ const dist = opts.distance ?? 300;
32837
+ const cx = 195;
32838
+ const cy = 422;
32839
+ const vectors = {
32840
+ up: [cx, cy + dist / 2, cx, cy - dist / 2],
32841
+ down: [cx, cy - dist / 2, cx, cy + dist / 2],
32842
+ left: [cx + dist / 2, cy, cx - dist / 2, cy],
32843
+ right: [cx - dist / 2, cy, cx + dist / 2, cy]
32844
+ };
32845
+ [sx, sy, ex, ey] = vectors[opts.direction];
32846
+ } else if (opts.startX != null && opts.startY != null && opts.endX != null && opts.endY != null) {
32847
+ sx = opts.startX;
32848
+ sy = opts.startY;
32849
+ ex = opts.endX;
32850
+ ey = opts.endY;
32851
+ } else {
32852
+ throw new Error("swipe requires either direction or start/end coordinates");
32853
+ }
32854
+ await callSimBridge({
32855
+ command: "swipe",
32856
+ udid,
32857
+ startX: sx,
32858
+ startY: sy,
32859
+ endX: ex,
32860
+ endY: ey,
32861
+ ...opts.duration !== void 0 && { duration: opts.duration }
32862
+ });
32863
+ }
32864
+ async function pressKey(udid, key) {
32865
+ if (key === "home") {
32866
+ await callSimBridge({ command: "button", udid, button: "home" });
32867
+ return;
32868
+ }
32869
+ const keyMap = {
32870
+ return: 40,
32871
+ delete: 42,
32872
+ escape: 41,
32873
+ tab: 43,
32874
+ space: 44
32875
+ };
32876
+ const code = keyMap[key];
32877
+ if (code != null) {
32878
+ await callSimBridge({ command: "key", udid, keyCode: code });
32879
+ } else {
32880
+ throw new Error(`Unknown key: ${key}`);
32881
+ }
32882
+ }
32883
+ async function install(udid, appPath) {
32884
+ const { engine, executor } = await getEngine();
32885
+ await engine.installApp(executor, udid, appPath);
32886
+ }
32887
+ async function launch(udid, bundleId) {
32888
+ const { engine, executor } = await getEngine();
32889
+ return await engine.launchApp(executor, udid, bundleId);
32890
+ }
32891
+ async function listApps(udid, opts) {
32892
+ const { engine, executor } = await getEngine();
32893
+ const apps = await engine.listApps(executor, udid, { type: opts?.type ?? "User" });
32894
+ return apps.map((a3) => ({
32895
+ bundleId: a3.bundleId,
32896
+ name: a3.name,
32897
+ version: a3.version,
32898
+ type: a3.type
32899
+ }));
32900
+ }
32901
+ async function resolveScheme(cwd, projectArg, explicitScheme) {
32902
+ if (explicitScheme) return explicitScheme;
32903
+ const { stdout } = await execFileAsync("xcodebuild", [...projectArg, "-list", "-json"], {
32904
+ cwd,
32905
+ timeout: 3e4,
32906
+ env: SIM_ENV
32907
+ });
32908
+ const parsed = JSON.parse(stdout);
32909
+ const schemes = parsed.workspace?.schemes ?? parsed.project?.schemes ?? [];
32910
+ if (schemes.length === 1) return schemes[0];
32911
+ if (schemes.length === 0) throw new Error("No schemes found in Xcode project");
32912
+ throw new Error(
32913
+ `Multiple schemes found (${schemes.join(", ")}). Specify one via the 'scheme' option.`
32914
+ );
32915
+ }
32916
+ async function resolveBuiltAppPath(cwd, projectArg, scheme, destination, derivedData) {
32917
+ const { stdout } = await execFileAsync(
32918
+ "xcodebuild",
32919
+ [
32920
+ ...projectArg,
32921
+ "-scheme",
32922
+ scheme,
32923
+ "-destination",
32924
+ destination,
32925
+ "-derivedDataPath",
32926
+ derivedData,
32927
+ "-showBuildSettings",
32928
+ "-json"
32929
+ ],
32930
+ { cwd, timeout: 6e4, env: SIM_ENV, maxBuffer: 20 * 1024 * 1024 }
32931
+ );
32932
+ const settings = JSON.parse(stdout);
32933
+ const s3 = settings[0]?.buildSettings ?? {};
32934
+ const targetDir = s3.TARGET_BUILD_DIR;
32935
+ const productName = s3.FULL_PRODUCT_NAME;
32936
+ if (!targetDir || !productName) {
32937
+ throw new Error("Could not determine built .app path from xcodebuild settings");
32938
+ }
32939
+ const { existsSync: existsSync10 } = await import("fs");
32940
+ const appPath = (0, import_path11.join)(targetDir, productName);
32941
+ if (!existsSync10(appPath)) {
32942
+ throw new Error(`Built .app bundle not found at ${appPath}`);
32943
+ }
32944
+ return appPath;
32945
+ }
32946
+ async function build(udid, opts) {
32947
+ const cwd = opts.workingDirectory;
32948
+ const entries = await (0, import_promises6.readdir)(cwd);
32949
+ const xcworkspace = entries.find((e3) => e3.endsWith(".xcworkspace"));
32950
+ const xcodeproj = entries.find((e3) => e3.endsWith(".xcodeproj"));
32951
+ const projectArg = xcworkspace ? ["-workspace", (0, import_path11.join)(cwd, xcworkspace)] : xcodeproj ? ["-project", (0, import_path11.join)(cwd, xcodeproj)] : null;
32952
+ if (!projectArg) throw new Error("No .xcworkspace or .xcodeproj found in " + cwd);
32953
+ const schemeName = await resolveScheme(cwd, projectArg, opts.scheme);
32954
+ const destination = `platform=iOS Simulator,id=${udid}`;
32955
+ const derivedData = (0, import_path11.join)(cwd, "build");
32956
+ await execFileAsync(
32957
+ "xcodebuild",
32958
+ [
32959
+ ...projectArg,
32960
+ "-scheme",
32961
+ schemeName,
32962
+ "-destination",
32963
+ destination,
32964
+ "-derivedDataPath",
32965
+ derivedData,
32966
+ "build"
32967
+ ],
32968
+ {
32969
+ timeout: 6e5,
32970
+ cwd,
32971
+ maxBuffer: 50 * 1024 * 1024,
32972
+ env: SIM_ENV
32973
+ }
32974
+ );
32975
+ const appPath = await resolveBuiltAppPath(cwd, projectArg, schemeName, destination, derivedData);
32976
+ const { stdout: plistOut } = await execFileAsync("/usr/libexec/PlistBuddy", [
32977
+ "-c",
32978
+ "Print :CFBundleIdentifier",
32979
+ (0, import_path11.join)(appPath, "Info.plist")
32980
+ ]).catch((err) => {
32981
+ throw new Error(`Failed to extract CFBundleIdentifier from ${appPath}: ${err.message}`);
32982
+ });
32983
+ const bundleId = plistOut.trim();
32984
+ if (!bundleId) throw new Error(`Empty CFBundleIdentifier in ${appPath}/Info.plist`);
32985
+ const appName = appPath.split("/").pop()?.replace(".app", "") ?? "App";
32986
+ return { bundleId, appName, appPath };
32987
+ }
32988
+ async function buildAndRun(udid, opts) {
32989
+ const result = await build(udid, opts);
32990
+ await install(udid, result.appPath);
32991
+ await launch(udid, result.bundleId);
32992
+ return result;
32993
+ }
32994
+ async function waitFor(udid, opts) {
32995
+ const MAX_WAIT_SECONDS = 300;
32996
+ if (typeof opts.time === "number") {
32997
+ if (opts.time > MAX_WAIT_SECONDS) {
32998
+ throw new Error(
32999
+ `time=${opts.time}s exceeds max ${MAX_WAIT_SECONDS}s. The 'time' parameter is in seconds \u2014 did you mean ${opts.time / 1e3}?`
33000
+ );
33001
+ }
33002
+ const ms = Math.max(0, opts.time * 1e3);
33003
+ await new Promise((r2) => setTimeout(r2, ms));
33004
+ return { found: true, elapsedMs: ms };
33005
+ }
33006
+ if (opts.label) {
33007
+ const start = Date.now();
33008
+ const timeoutMs = (opts.timeout ?? 30) * 1e3;
33009
+ while (Date.now() - start < timeoutMs) {
33010
+ const result = await readScreen(udid, {
33011
+ sessionKey: "wait",
33012
+ filter: "all",
33013
+ includeScreenshot: false
33014
+ });
33015
+ if (result.formatted.includes(opts.label)) {
33016
+ return { found: true, elapsedMs: Date.now() - start };
33017
+ }
33018
+ await new Promise((r2) => setTimeout(r2, 500));
33019
+ }
33020
+ return { found: false, elapsedMs: Date.now() - start };
33021
+ }
33022
+ if (opts.stabilize) {
33023
+ const start = Date.now();
33024
+ const timeoutMs = (opts.timeout ?? 30) * 1e3;
33025
+ let prevShot = await screenshot(udid, "jpeg");
33026
+ while (Date.now() - start < timeoutMs) {
33027
+ await new Promise((r2) => setTimeout(r2, 500));
33028
+ const currShot = await screenshot(udid, "jpeg");
33029
+ if (currShot.base64 === prevShot.base64) {
33030
+ return { found: true, elapsedMs: Date.now() - start };
33031
+ }
33032
+ prevShot = currShot;
33033
+ }
33034
+ return { found: false, elapsedMs: Date.now() - start };
33035
+ }
33036
+ throw new Error("waitFor requires time, stabilize, or label");
33037
+ }
33038
+ async function getProjectInfo(workingDirectory) {
33039
+ let entries;
33040
+ try {
33041
+ entries = await (0, import_promises6.readdir)(workingDirectory);
33042
+ } catch (err) {
33043
+ throw new Error(`Cannot read directory ${workingDirectory}: ${err.message}`);
33044
+ }
33045
+ const xcworkspace = entries.find((e3) => e3.endsWith(".xcworkspace")) ?? null;
33046
+ const xcodeproj = entries.find((e3) => e3.endsWith(".xcodeproj")) ?? null;
33047
+ if (!xcworkspace && !xcodeproj) {
33048
+ throw new Error(
33049
+ `No .xcworkspace or .xcodeproj found in ${workingDirectory}. Check the path \u2014 the Xcode project may be in a subdirectory (e.g., ${workingDirectory}/ios).`
33050
+ );
33051
+ }
33052
+ const projectArg = xcworkspace ? ["-workspace", (0, import_path11.join)(workingDirectory, xcworkspace)] : ["-project", (0, import_path11.join)(workingDirectory, xcodeproj)];
33053
+ const { stdout } = await execFileAsync("xcodebuild", [...projectArg, "-list", "-json"], {
33054
+ cwd: workingDirectory,
33055
+ timeout: 3e4,
33056
+ env: SIM_ENV
33057
+ });
33058
+ const parsed = JSON.parse(stdout);
33059
+ const schemes = parsed.workspace?.schemes ?? parsed.project?.schemes ?? [];
33060
+ return { schemes, workspace: xcworkspace, project: xcodeproj };
33061
+ }
33062
+
33063
+ // apps/agent-server/agents/deus-tools/simulator.ts
33064
+ function textResult3(text) {
33065
+ return { content: [{ type: "text", text }] };
33066
+ }
33067
+ function imageResult(base643, mimeType, caption) {
33068
+ const parts = [];
33069
+ if (caption) parts.push({ type: "text", text: caption });
33070
+ parts.push({ type: "image", data: base643, mimeType });
33071
+ return { content: parts };
33072
+ }
33073
+ function withSimulator(fn) {
33074
+ return async (args) => {
33075
+ try {
33076
+ return await fn(args);
33077
+ } catch (err) {
33078
+ return textResult3(`Simulator error: ${getErrorMessage(err)}`);
33079
+ }
33080
+ };
33081
+ }
33082
+ function createSimulatorTools(sessionId) {
33083
+ return [
33084
+ // -- ListDevices ----------------------------------------------------------
33085
+ Tb(
33086
+ "SimulatorListDevices",
33087
+ `List all available iOS simulators. Returns each simulator's name, UDID, state (Booted/Shutdown), and runtime version. Use this to find a simulator to work with.`,
33088
+ {},
33089
+ withSimulator(async () => {
33090
+ const devices = await listDevices();
33091
+ if (devices.length === 0) {
33092
+ return textResult3(
33093
+ "No simulators found. Install simulators via Xcode > Settings > Platforms."
33094
+ );
33095
+ }
33096
+ const lines = devices.map(
33097
+ (d3) => `${d3.state === "Booted" ? "[BOOTED] " : ""}${d3.name} (${d3.runtime}) \u2014 ${d3.udid}`
33098
+ );
33099
+ return textResult3(`Found ${devices.length} simulator(s):
33100
+ ${lines.join("\n")}`);
33101
+ })
32757
33102
  ),
32758
- // ====================================================================
32759
- // iOSSimulatorSwipe
32760
- // ====================================================================
33103
+ // -- Screenshot -----------------------------------------------------------
32761
33104
  Tb(
32762
- "iOSSimulatorSwipe",
32763
- `Perform a swipe gesture on the iOS simulator screen.
33105
+ "SimulatorScreenshot",
33106
+ `Capture a screenshot of the running iOS simulator. Returns the image as base64. Use to see what the app looks like and identify UI elements before interacting.`,
33107
+ {
33108
+ destination: external_exports.string().optional().describe("Simulator name or UDID (optional, uses active)"),
33109
+ format: external_exports.enum(["png", "jpeg"]).optional().describe("Image format (default: jpeg)")
33110
+ },
33111
+ withSimulator(async (args) => {
33112
+ const udid = await resolveDevice(args.destination, sessionId);
33113
+ const format = args.format ?? "jpeg";
33114
+ const img = await screenshot(udid, format);
33115
+ return imageResult(img.base64, img.mimeType, "Simulator screenshot captured.");
33116
+ })
33117
+ ),
33118
+ // -- Tap ------------------------------------------------------------------
33119
+ Tb(
33120
+ "SimulatorTap",
33121
+ `Tap on the iOS simulator screen. Pass EXACTLY ONE of:
33122
+ - 'ref': a @eN reference from the most recent SimulatorReadScreen output (preferred \u2014 most precise)
33123
+ - 'identifier': the accessibilityIdentifier set in app code (e.g., 'SubmitButton')
33124
+ - 'label': the iOS accessibility label (e.g., 'Submit'). Not placeholder text.
33125
+ - 'x' + 'y': logical-point coordinates, origin top-left (last resort \u2014 fragile)
32764
33126
 
32765
- Coordinates are normalized (0.0 to 1.0). Common swipe patterns:
32766
- - Scroll down: startY=0.7, endY=0.3 (finger moves up)
32767
- - Scroll up: startY=0.3, endY=0.7 (finger moves down)
32768
- - Swipe left: startX=0.8, endX=0.2
32769
- - Swipe right: startX=0.2, endX=0.8`,
33127
+ Prefer ref when you just ran ReadScreen; prefer identifier when you know the
33128
+ app's code; fall back to label for system UI. Coordinates are unreliable
33129
+ because layouts shift between reads.`,
32770
33130
  {
32771
- startX: external_exports.number().min(0).max(1).describe("Start X coordinate (0.0\u20131.0)"),
32772
- startY: external_exports.number().min(0).max(1).describe("Start Y coordinate (0.0\u20131.0)"),
32773
- endX: external_exports.number().min(0).max(1).describe("End X coordinate (0.0\u20131.0)"),
32774
- endY: external_exports.number().min(0).max(1).describe("End Y coordinate (0.0\u20131.0)"),
32775
- durationMs: external_exports.number().optional().describe("Duration of the swipe in milliseconds (default: 300)")
33131
+ ref: external_exports.string().optional().describe("@eN reference from the most recent SimulatorReadScreen output (e.g., '@e3')"),
33132
+ identifier: external_exports.string().optional().describe("accessibilityIdentifier from app code (e.g., 'SubmitButton', 'NameField')"),
33133
+ label: external_exports.string().optional().describe("iOS accessibility label (e.g., 'Address' for Safari URL bar)"),
33134
+ x: external_exports.number().optional().describe("X coordinate in iOS logical points (must also provide y)"),
33135
+ y: external_exports.number().optional().describe("Y coordinate in iOS logical points (must also provide x)"),
33136
+ destination: external_exports.string().optional().describe("Simulator name or UDID"),
33137
+ includeScreenshot: external_exports.boolean().optional().describe("Include screenshot after tap (default: true)")
32776
33138
  },
32777
- async (args) => {
32778
- console.log(
32779
- `[deusMCPServer] iOSSimulatorSwipe invoked for session ${sessionId}: (${args.startX}, ${args.startY}) \u2192 (${args.endX}, ${args.endY})`
32780
- );
32781
- try {
32782
- const response = await EventBroadcaster.requestSimSwipe({
32783
- sessionId,
32784
- startX: args.startX,
32785
- startY: args.startY,
32786
- endX: args.endX,
32787
- endY: args.endY,
32788
- durationMs: args.durationMs
32789
- });
32790
- if (response.error) {
32791
- return {
32792
- content: [{ type: "text", text: `Swipe failed: ${response.error}` }]
32793
- };
32794
- }
32795
- return {
32796
- content: [
32797
- {
32798
- type: "text",
32799
- text: `Swiped from (${args.startX.toFixed(2)}, ${args.startY.toFixed(2)}) to (${args.endX.toFixed(2)}, ${args.endY.toFixed(2)}). Use iOSSimulatorScreenshot to see the result.`
32800
- }
32801
- ]
32802
- };
32803
- } catch (err) {
32804
- return {
32805
- content: [{ type: "text", text: `Simulator not available: ${getErrorMessage(err)}` }]
32806
- };
33139
+ withSimulator(async (args) => {
33140
+ const udid = await resolveDevice(args.destination, sessionId);
33141
+ await tap(udid, {
33142
+ ref: args.ref,
33143
+ identifier: args.identifier,
33144
+ label: args.label,
33145
+ x: args.x,
33146
+ y: args.y,
33147
+ sessionKey: sessionId
33148
+ });
33149
+ const tapDesc = args.ref ? args.ref : args.identifier ? `#${args.identifier}` : args.label ? `"${args.label}"` : `(${args.x}, ${args.y})`;
33150
+ if (args.includeScreenshot === false) {
33151
+ return textResult3(`Tapped ${tapDesc}. Use SimulatorScreenshot to see the result.`);
32807
33152
  }
32808
- }
33153
+ const img = await screenshot(udid, "jpeg");
33154
+ return imageResult(img.base64, img.mimeType, `Tapped ${tapDesc}`);
33155
+ })
32809
33156
  ),
32810
- // ====================================================================
32811
- // iOSSimulatorTypeText
32812
- // ====================================================================
33157
+ // -- TypeText --------------------------------------------------------------
32813
33158
  Tb(
32814
- "iOSSimulatorTypeText",
32815
- `Type text into the currently focused field in the iOS simulator.
33159
+ "SimulatorTypeText",
33160
+ `Type text into the currently focused field in the iOS simulator. Tap a text field first to focus it.
32816
33161
 
32817
- Make sure an input field is focused first (tap on it using iOSSimulatorTap). The text is typed character by character using HID key injection, simulating a real keyboard.`,
33162
+ The screenshot returned may be captured BEFORE page loads / async side-effects
33163
+ complete. Use SimulatorWaitFor(stabilize=true) afterward if you need the result.`,
32818
33164
  {
32819
- text: external_exports.string().describe("The text to type into the focused field")
33165
+ text: external_exports.string().describe("The text to type"),
33166
+ submit: external_exports.boolean().optional().describe(
33167
+ "Send Return keypress after typing. For search fields this triggers submission, but the page may not have loaded when the response returns."
33168
+ ),
33169
+ destination: external_exports.string().optional().describe("Simulator name or UDID"),
33170
+ includeScreenshot: external_exports.boolean().optional().describe("Include screenshot after typing (default: true)")
32820
33171
  },
32821
- async (args) => {
32822
- const preview = args.text.length > 30 ? `${args.text.slice(0, 30)}...` : args.text;
32823
- console.log(
32824
- `[deusMCPServer] iOSSimulatorTypeText invoked for session ${sessionId}: "${preview}"`
32825
- );
32826
- try {
32827
- const response = await EventBroadcaster.requestSimTypeText({
32828
- sessionId,
32829
- text: args.text
32830
- });
32831
- if (!response.success) {
32832
- return {
32833
- content: [
32834
- {
32835
- type: "text",
32836
- text: `Type failed: ${response.error ?? "Unknown error"}`
32837
- }
32838
- ]
32839
- };
32840
- }
32841
- const warning = response.error ? `
32842
- Warning: ${response.error}` : "";
32843
- return {
32844
- content: [
32845
- {
32846
- type: "text",
32847
- text: `Typed "${args.text.length > 50 ? args.text.slice(0, 50) + "..." : args.text}".${warning} Use iOSSimulatorScreenshot to see the result.`
32848
- }
32849
- ]
32850
- };
32851
- } catch (err) {
32852
- return {
32853
- content: [{ type: "text", text: `Simulator not available: ${getErrorMessage(err)}` }]
32854
- };
32855
- }
32856
- }
33172
+ withSimulator(async (args) => {
33173
+ const udid = await resolveDevice(args.destination, sessionId);
33174
+ await typeText(udid, args.text, { submit: args.submit });
33175
+ const preview = args.text.length > 40 ? args.text.slice(0, 40) + "..." : args.text;
33176
+ if (args.includeScreenshot === false) {
33177
+ return textResult3(`Typed "${preview}". Use SimulatorScreenshot to see the result.`);
33178
+ }
33179
+ const img = await screenshot(udid, "jpeg");
33180
+ return imageResult(img.base64, img.mimeType, `Typed "${preview}"`);
33181
+ })
32857
33182
  ),
32858
- // ====================================================================
32859
- // iOSSimulatorPressKey
32860
- // ====================================================================
33183
+ // -- Swipe ----------------------------------------------------------------
32861
33184
  Tb(
32862
- "iOSSimulatorPressKey",
32863
- `Press a specific key on the iOS simulator using USB HID usage codes.
33185
+ "SimulatorSwipe",
33186
+ `Swipe on the iOS simulator. Use direction (up/down/left/right) for simple scrolling, or explicit start/end coordinates for precise control.
32864
33187
 
32865
- Common keycodes (USB HID):
32866
- - Return/Enter: 0x28 (40)
32867
- - Delete/Backspace: 0x2A (42)
32868
- - Escape: 0x29 (41)
32869
- - Tab: 0x2B (43)
32870
- - Space: 0x2C (44)
32871
- - Arrow Up: 0x52 (82), Down: 0x51 (81), Left: 0x50 (80), Right: 0x4F (79)
32872
- - Left Shift: 0xE1 (225)
33188
+ Direction semantics: "up" scrolls content down (finger moves up), "down" scrolls content up.`,
33189
+ {
33190
+ direction: external_exports.enum(["up", "down", "left", "right"]).optional().describe("Swipe direction"),
33191
+ distance: external_exports.number().optional().describe("Distance in points for direction-based swipe (default: 300)"),
33192
+ startX: external_exports.number().optional().describe("Starting X coordinate in iOS points"),
33193
+ startY: external_exports.number().optional().describe("Starting Y coordinate in iOS points"),
33194
+ endX: external_exports.number().optional().describe("Ending X coordinate in iOS points"),
33195
+ endY: external_exports.number().optional().describe("Ending Y coordinate in iOS points"),
33196
+ duration: external_exports.number().optional().describe("Swipe duration in milliseconds (default: 300)"),
33197
+ destination: external_exports.string().optional().describe("Simulator name or UDID"),
33198
+ includeScreenshot: external_exports.boolean().optional().describe("Include screenshot after swipe (default: true)")
33199
+ },
33200
+ withSimulator(async (args) => {
33201
+ const udid = await resolveDevice(args.destination, sessionId);
33202
+ await swipe(udid, args);
33203
+ const label = args.direction ?? "custom";
33204
+ if (args.includeScreenshot === false) {
33205
+ return textResult3(`Swiped ${label}. Use SimulatorScreenshot to see the result.`);
33206
+ }
33207
+ const img = await screenshot(udid, "jpeg");
33208
+ return imageResult(img.base64, img.mimeType, `Swiped ${label}`);
33209
+ })
33210
+ ),
33211
+ // -- PressKey -------------------------------------------------------------
33212
+ Tb(
33213
+ "SimulatorPressKey",
33214
+ `Press a special key on the iOS simulator. "home" triggers the home button.`,
33215
+ {
33216
+ key: external_exports.enum(["return", "delete", "escape", "tab", "home", "space"]).describe("The key to press"),
33217
+ destination: external_exports.string().optional().describe("Simulator name or UDID")
33218
+ },
33219
+ withSimulator(async (args) => {
33220
+ const udid = await resolveDevice(args.destination, sessionId);
33221
+ await pressKey(udid, args.key);
33222
+ return textResult3(`Pressed ${args.key}`);
33223
+ })
33224
+ ),
33225
+ // -- Build ----------------------------------------------------------------
33226
+ Tb(
33227
+ "SimulatorBuild",
33228
+ `Build the Xcode project, install it on the simulator, and launch the app. Returns build result with bundle ID and app name.
32873
33229
 
32874
- By default, sends both key-down and key-up. Use direction to send only one.`,
33230
+ The simulator must be booted first. The build may take several minutes for large projects.`,
32875
33231
  {
32876
- keycode: external_exports.number().describe("USB HID usage code (e.g., 40 for Return, 42 for Backspace)"),
32877
- direction: external_exports.enum(["down", "up"]).optional().describe("Send only key-down or key-up. Omit for a full key press (down + up).")
33232
+ workingDirectory: external_exports.string().describe("Path to the directory containing the Xcode project"),
33233
+ scheme: external_exports.string().optional().describe("Build scheme name (auto-detected if not provided)"),
33234
+ destination: external_exports.string().optional().describe("Simulator name or UDID to build for")
32878
33235
  },
32879
- async (args) => {
32880
- console.log(
32881
- `[deusMCPServer] iOSSimulatorPressKey invoked for session ${sessionId}: keycode=${args.keycode}`
33236
+ withSimulator(async (args) => {
33237
+ const udid = await resolveDevice(args.destination, sessionId);
33238
+ const result = await buildAndRun(udid, {
33239
+ workingDirectory: args.workingDirectory,
33240
+ scheme: args.scheme
33241
+ });
33242
+ return textResult3(
33243
+ `Build succeeded.
33244
+ App: ${result.appName}
33245
+ Bundle ID: ${result.bundleId || "(unknown)"}
33246
+ Installed and launched on simulator.`
32882
33247
  );
32883
- try {
32884
- const response = await EventBroadcaster.requestSimPressKey({
32885
- sessionId,
32886
- keycode: args.keycode,
32887
- direction: args.direction
33248
+ })
33249
+ ),
33250
+ // -- Launch ---------------------------------------------------------------
33251
+ Tb(
33252
+ "SimulatorLaunch",
33253
+ `Launch an app on the simulator by bundle ID. The app must already be installed. Use SimulatorListApps to discover installed bundle IDs.`,
33254
+ {
33255
+ bundleId: external_exports.string().describe("Bundle identifier (e.g., com.example.MyApp)"),
33256
+ destination: external_exports.string().optional().describe("Simulator name or UDID")
33257
+ },
33258
+ withSimulator(async (args) => {
33259
+ const udid = await resolveDevice(args.destination, sessionId);
33260
+ await launch(udid, args.bundleId);
33261
+ return textResult3(`Launched ${args.bundleId}`);
33262
+ })
33263
+ ),
33264
+ // -- ListApps -------------------------------------------------------------
33265
+ Tb(
33266
+ "SimulatorListApps",
33267
+ `List apps installed on the simulator. Returns bundle IDs you can pass to SimulatorLaunch. Defaults to user-installed apps; pass type="all" to include system apps.`,
33268
+ {
33269
+ destination: external_exports.string().optional().describe("Simulator name or UDID"),
33270
+ type: external_exports.enum(["User", "System", "all"]).optional().describe("Which apps to list (default: User)")
33271
+ },
33272
+ withSimulator(async (args) => {
33273
+ const udid = await resolveDevice(args.destination, sessionId);
33274
+ const apps = await listApps(udid, { type: args.type });
33275
+ if (apps.length === 0) {
33276
+ return textResult3("No apps found on this simulator.");
33277
+ }
33278
+ const lines = apps.map(
33279
+ (a3) => `${a3.name}${a3.version ? ` (${a3.version})` : ""} \u2014 ${a3.bundleId} [${a3.type}]`
33280
+ );
33281
+ return textResult3(`Found ${apps.length} app(s):
33282
+ ${lines.join("\n")}`);
33283
+ })
33284
+ ),
33285
+ // -- ReadScreen -----------------------------------------------------------
33286
+ Tb(
33287
+ "SimulatorReadScreen",
33288
+ `Read the current screen state of the iOS simulator. Returns the accessibility tree with element refs (@e1, @e2) and optionally a screenshot.
33289
+
33290
+ Use refs with SimulatorTap to tap elements by label. Use filter "interactive" to see only tappable elements.`,
33291
+ {
33292
+ destination: external_exports.string().optional().describe("Simulator name or UDID"),
33293
+ filter: external_exports.enum(["interactive", "all"]).optional().describe(
33294
+ "Filter: 'interactive' shows only tappable elements, 'all' shows everything (default)"
33295
+ ),
33296
+ includeScreenshot: external_exports.boolean().optional().describe("Include screenshot in response (default: true)")
33297
+ },
33298
+ withSimulator(async (args) => {
33299
+ const udid = await resolveDevice(args.destination, sessionId);
33300
+ const result = await readScreen(udid, {
33301
+ sessionKey: sessionId,
33302
+ filter: args.filter,
33303
+ includeScreenshot: args.includeScreenshot
33304
+ });
33305
+ const parts = [];
33306
+ if (result.screenshot) {
33307
+ parts.push({
33308
+ type: "image",
33309
+ data: result.screenshot.base64,
33310
+ mimeType: result.screenshot.mimeType
32888
33311
  });
32889
- if (response.error) {
32890
- return {
32891
- content: [{ type: "text", text: `Key press failed: ${response.error}` }]
32892
- };
32893
- }
32894
- return {
32895
- content: [
32896
- {
32897
- type: "text",
32898
- text: `Pressed key ${args.keycode}${args.direction ? ` (${args.direction})` : ""}. Use iOSSimulatorScreenshot to see the result.`
32899
- }
32900
- ]
32901
- };
32902
- } catch (err) {
32903
- return {
32904
- content: [{ type: "text", text: `Simulator not available: ${getErrorMessage(err)}` }]
32905
- };
32906
33312
  }
32907
- }
33313
+ parts.push({ type: "text", text: result.formatted });
33314
+ return { content: parts };
33315
+ })
32908
33316
  ),
32909
- // ====================================================================
32910
- // iOSSimulatorBuildAndRun
32911
- // ====================================================================
33317
+ // -- WaitFor --------------------------------------------------------------
32912
33318
  Tb(
32913
- "iOSSimulatorBuildAndRun",
32914
- `Build an Xcode project and install + launch the app on the currently booted iOS simulator.
32915
-
32916
- This tool:
32917
- 1. Detects the Xcode project in the workspace
32918
- 2. Runs xcodebuild to compile the project
32919
- 3. Installs the built .app on the booted simulator
32920
- 4. Launches the app
32921
-
32922
- The simulator must be booted and streaming (use iOSSimulatorStart first). The build may take several minutes for large projects.`,
33319
+ "SimulatorWaitFor",
33320
+ `Wait for a condition on the simulator. Useful for waiting for animations, loading states, or specific UI elements to appear.`,
32923
33321
  {
32924
- workspacePath: external_exports.string().describe("Absolute path to the workspace directory containing the Xcode project")
33322
+ time: external_exports.number().max(300).optional().describe(
33323
+ "Wait for a fixed duration in SECONDS (not milliseconds). Accepts decimals (e.g. 1.5). Max 300s."
33324
+ ),
33325
+ stabilize: external_exports.boolean().optional().describe("Wait for UI to stop changing (animations complete)"),
33326
+ label: external_exports.string().optional().describe("Wait for an element with this accessibility label to appear"),
33327
+ timeout: external_exports.number().max(300).optional().describe("Maximum wait time in SECONDS (default: 30, max: 300)"),
33328
+ destination: external_exports.string().optional().describe("Simulator name or UDID")
32925
33329
  },
32926
- async (args) => {
32927
- console.log(
32928
- `[deusMCPServer] iOSSimulatorBuildAndRun invoked for session ${sessionId}: ${args.workspacePath}`
33330
+ withSimulator(async (args) => {
33331
+ const udid = await resolveDevice(args.destination, sessionId);
33332
+ const result = await waitFor(udid, args);
33333
+ if (args.time) {
33334
+ return textResult3(`Waited ${args.time}s`);
33335
+ }
33336
+ return textResult3(
33337
+ result.found ? `Condition met (${result.elapsedMs}ms)` : `Timed out after ${result.elapsedMs}ms`
32929
33338
  );
32930
- try {
32931
- const response = await EventBroadcaster.requestSimBuildAndRun({
32932
- sessionId,
32933
- workspacePath: args.workspacePath
32934
- });
32935
- if (response.error) {
32936
- return {
32937
- content: [{ type: "text", text: `Build & run failed: ${response.error}` }]
32938
- };
32939
- }
32940
- const details = [
32941
- `Build & run succeeded.`,
32942
- response.appName ? `App: ${response.appName}` : null,
32943
- response.bundleId ? `Bundle ID: ${response.bundleId}` : null,
32944
- `Use iOSSimulatorScreenshot to see the running app.`
32945
- ].filter(Boolean).join("\n");
32946
- return {
32947
- content: [{ type: "text", text: details }]
32948
- };
32949
- } catch (err) {
32950
- return {
32951
- content: [
32952
- {
32953
- type: "text",
32954
- text: `Build & run failed: ${getErrorMessage(err)}. Make sure a simulator is booted (use iOSSimulatorStart) and the workspace contains an Xcode project.`
32955
- }
32956
- ]
32957
- };
33339
+ })
33340
+ ),
33341
+ // -- GetProjectInfo -------------------------------------------------------
33342
+ Tb(
33343
+ "SimulatorGetProjectInfo",
33344
+ `Get available build schemes and project files for an Xcode project. Use this before SimulatorBuild to discover available schemes.`,
33345
+ {
33346
+ workingDirectory: external_exports.string().optional().describe("Path to the Xcode project directory")
33347
+ },
33348
+ withSimulator(async (args) => {
33349
+ const cwd = args.workingDirectory;
33350
+ if (!cwd) return textResult3("Provide a workingDirectory to inspect.");
33351
+ const info = await getProjectInfo(cwd);
33352
+ const lines = [];
33353
+ if (info.workspace) lines.push(`Workspace: ${info.workspace}`);
33354
+ if (info.project) lines.push(`Project: ${info.project}`);
33355
+ if (info.schemes.length > 0) {
33356
+ lines.push(`
33357
+ Schemes:
33358
+ ${info.schemes.map((s3) => ` - ${s3}`).join("\n")}`);
33359
+ } else {
33360
+ lines.push("\nNo schemes found.");
32958
33361
  }
32959
- }
33362
+ return textResult3(lines.join("\n"));
33363
+ })
32960
33364
  )
32961
33365
  ];
32962
33366
  }
@@ -32966,7 +33370,7 @@ init_sdk();
32966
33370
 
32967
33371
  // packages/screen-studio/src/mcp/session-manager.ts
32968
33372
  var import_node_crypto = require("node:crypto");
32969
- var import_promises8 = require("node:fs/promises");
33373
+ var import_promises9 = require("node:fs/promises");
32970
33374
  var import_node_os2 = require("node:os");
32971
33375
  var import_node_path = require("node:path");
32972
33376
  init_engine();
@@ -33016,7 +33420,7 @@ var TimelineRecorder = class {
33016
33420
  var import_node_child_process = require("node:child_process");
33017
33421
  var import_node_os = require("node:os");
33018
33422
  var import_node_fs = require("node:fs");
33019
- var import_promises6 = require("node:fs/promises");
33423
+ var import_promises7 = require("node:fs/promises");
33020
33424
  async function probeVideoDimensions(filePath) {
33021
33425
  return new Promise((resolve2) => {
33022
33426
  const proc = (0, import_node_child_process.spawn)(
@@ -33249,7 +33653,7 @@ Hint: On macOS, ensure Screen Recording permission is granted. On Linux, ensure
33249
33653
  );
33250
33654
  }
33251
33655
  if (path6) {
33252
- const { size } = await (0, import_promises6.stat)(path6);
33656
+ const { size } = await (0, import_promises7.stat)(path6);
33253
33657
  if (size === 0) {
33254
33658
  throw new Error(
33255
33659
  `Screen capture failed: raw file at ${path6} is empty.
@@ -33272,7 +33676,7 @@ Hint: On macOS, ensure Screen Recording permission is granted.`
33272
33676
  async cleanup() {
33273
33677
  if (this.rawCapturePath && (0, import_node_fs.existsSync)(this.rawCapturePath)) {
33274
33678
  try {
33275
- await (0, import_promises6.unlink)(this.rawCapturePath);
33679
+ await (0, import_promises7.unlink)(this.rawCapturePath);
33276
33680
  } catch {
33277
33681
  }
33278
33682
  }
@@ -33293,7 +33697,7 @@ Hint: On macOS, ensure Screen Recording permission is granted.`
33293
33697
  // packages/screen-studio/src/mcp/stream-capture.ts
33294
33698
  var import_node_child_process2 = require("node:child_process");
33295
33699
  var import_node_fs2 = require("node:fs");
33296
- var import_promises7 = require("node:fs/promises");
33700
+ var import_promises8 = require("node:fs/promises");
33297
33701
  var DEFAULT_STREAM_FPS = 10;
33298
33702
  var RECONNECT_MAX_ATTEMPTS = 15;
33299
33703
  var RECONNECT_DELAY_MS = 500;
@@ -33485,7 +33889,7 @@ var StreamRecorder = class {
33485
33889
  ffmpeg stderr: ${this.lastStderr.slice(-300)}`
33486
33890
  );
33487
33891
  }
33488
- const { size } = await (0, import_promises7.stat)(this.outputPath);
33892
+ const { size } = await (0, import_promises8.stat)(this.outputPath);
33489
33893
  if (size === 0) {
33490
33894
  throw new Error(
33491
33895
  `Stream recording failed: output file is empty.
@@ -34010,7 +34414,7 @@ var SessionManager = class {
34010
34414
  }
34011
34415
  await session.ffmpegRecorder.cleanup();
34012
34416
  if (session.rawCapturePath) {
34013
- await (0, import_promises8.unlink)(session.rawCapturePath).catch(() => {
34417
+ await (0, import_promises9.unlink)(session.rawCapturePath).catch(() => {
34014
34418
  });
34015
34419
  }
34016
34420
  }
@@ -34068,7 +34472,7 @@ var SessionManager = class {
34068
34472
  session.streamRecorder?.kill();
34069
34473
  await session.ffmpegRecorder.cleanup();
34070
34474
  if (session.rawCapturePath) {
34071
- await (0, import_promises8.unlink)(session.rawCapturePath).catch(() => {
34475
+ await (0, import_promises9.unlink)(session.rawCapturePath).catch(() => {
34072
34476
  });
34073
34477
  }
34074
34478
  this.sessions.delete(sessionId);
@@ -34452,6 +34856,7 @@ function createDeusMCPServer(sessionId) {
34452
34856
  bridge.onBrowserAction(action);
34453
34857
  }),
34454
34858
  ...createSimulatorTools(sessionId),
34859
+ ...createAppsTools(sessionId),
34455
34860
  ...wrappedRecordingTools
34456
34861
  ]
34457
34862
  });
@@ -34475,6 +34880,13 @@ var SessionStore = class {
34475
34880
  clear() {
34476
34881
  this.sessions.clear();
34477
34882
  }
34883
+ /**
34884
+ * Iterate all stored values. Used by AAP app-registrar to broadcast
34885
+ * `setMcpServers` updates to every live Claude Query.
34886
+ */
34887
+ values() {
34888
+ return this.sessions.values();
34889
+ }
34478
34890
  /**
34479
34891
  * Check if the session reference matches (for ownership guards).
34480
34892
  *
@@ -34531,6 +34943,18 @@ var DEFAULT_PROMPT = {
34531
34943
  preset: "claude_code"
34532
34944
  };
34533
34945
  var DEFAULT_SETTING_SOURCES = ["user", "project", "local"];
34946
+ var LEVEL_TO_MAX_TOKENS = {
34947
+ NONE: 0,
34948
+ LOW: 4096,
34949
+ MEDIUM: 8192,
34950
+ HIGH: 16384,
34951
+ XHIGH: 32768
34952
+ };
34953
+ function resolveThinkingOptions(thinkingLevel) {
34954
+ if (!thinkingLevel) return { maxThinkingTokens: void 0 };
34955
+ const level = thinkingLevel.toUpperCase();
34956
+ return { maxThinkingTokens: LEVEL_TO_MAX_TOKENS[level] };
34957
+ }
34534
34958
  function buildAppendSystemPrompt(cwd) {
34535
34959
  const workspaceContext = buildWorkspaceContext(cwd) || "You are working inside Deus, a desktop app that orchestrates multiple AI coding agents in parallel.";
34536
34960
  return `
@@ -34678,7 +35102,7 @@ function createHooks(sessionId) {
34678
35102
  EventBroadcaster.sendEnterPlanModeNotification({
34679
35103
  type: "enter_plan_mode_notification",
34680
35104
  id: sessionId,
34681
- agentType: "claude"
35105
+ agentHarness: "claude"
34682
35106
  });
34683
35107
  return Promise.resolve({});
34684
35108
  }
@@ -34688,13 +35112,13 @@ function createHooks(sessionId) {
34688
35112
  };
34689
35113
  }
34690
35114
  function buildSdkOptions(sessionId, env, options) {
34691
- const modelToUse = mapModelForProvider(options?.model, env);
34692
35115
  const workingDirectory = options?.cwd;
34693
35116
  const permissionMode = options?.permissionMode ?? "default";
35117
+ const thinking = resolveThinkingOptions(options?.thinkingLevel);
34694
35118
  const sdkOptions = {
34695
35119
  maxTurns: options?.maxTurns || 1e3,
34696
- model: modelToUse,
34697
- maxThinkingTokens: options?.maxThinkingTokens,
35120
+ model: options?.model,
35121
+ maxThinkingTokens: thinking.maxThinkingTokens,
34698
35122
  cwd: workingDirectory,
34699
35123
  pathToClaudeCodeExecutable: getClaudeExecutablePath(),
34700
35124
  systemPrompt: {
@@ -34728,6 +35152,69 @@ function buildSdkOptions(sessionId, env, options) {
34728
35152
  return sdkOptions;
34729
35153
  }
34730
35154
 
35155
+ // apps/agent-server/app-registrar.ts
35156
+ var registeredServers = /* @__PURE__ */ new Map();
35157
+ var protectedByQuery = /* @__PURE__ */ new Map();
35158
+ var updateChain = Promise.resolve();
35159
+ function enqueueRegistryUpdate(fn) {
35160
+ const next = updateChain.then(fn, fn);
35161
+ updateChain = next.then(
35162
+ () => void 0,
35163
+ () => void 0
35164
+ );
35165
+ return next;
35166
+ }
35167
+ function registerAppMcp(serverName, url2) {
35168
+ return enqueueRegistryUpdate(async () => {
35169
+ const config2 = { type: "http", url: url2 };
35170
+ registeredServers.set(serverName, config2);
35171
+ console.log(
35172
+ `[AAP-Registrar] Registered ${serverName} \u2192 ${url2} (${registeredServers.size} total)`
35173
+ );
35174
+ await broadcast();
35175
+ });
35176
+ }
35177
+ function unregisterAppMcp(serverName) {
35178
+ return enqueueRegistryUpdate(async () => {
35179
+ const existed = registeredServers.delete(serverName);
35180
+ if (!existed) return;
35181
+ console.log(`[AAP-Registrar] Unregistered ${serverName} (${registeredServers.size} remaining)`);
35182
+ await broadcast();
35183
+ });
35184
+ }
35185
+ function attachQuery(query, sdkServers) {
35186
+ protectedByQuery.set(query, sdkServers);
35187
+ if (registeredServers.size > 0) {
35188
+ void enqueueRegistryUpdate(() => pushToQuery(query));
35189
+ }
35190
+ }
35191
+ function detachQuery(query) {
35192
+ protectedByQuery.delete(query);
35193
+ }
35194
+ function buildPayloadForQuery(query) {
35195
+ const protectedSdkServers = protectedByQuery.get(query) ?? {};
35196
+ const payload = { ...protectedSdkServers };
35197
+ for (const [name, config2] of registeredServers) {
35198
+ payload[name] = config2;
35199
+ }
35200
+ return payload;
35201
+ }
35202
+ async function pushToQuery(query) {
35203
+ try {
35204
+ await query.setMcpServers(buildPayloadForQuery(query));
35205
+ } catch (err) {
35206
+ console.warn(`[AAP-Registrar] setMcpServers failed on one query: ${getErrorMessage(err)}`);
35207
+ }
35208
+ }
35209
+ async function broadcast() {
35210
+ const queries = [...claudeQueries.values()];
35211
+ if (queries.length === 0) {
35212
+ console.log(`[AAP-Registrar] No active queries to broadcast to (state stored for later)`);
35213
+ return;
35214
+ }
35215
+ await Promise.all(queries.map(pushToQuery));
35216
+ }
35217
+
34731
35218
  // apps/agent-server/agents/claude/claude-handler.ts
34732
35219
  function getInvalidWorkspacePathError(cwd) {
34733
35220
  if (!cwd) {
@@ -34761,7 +35248,7 @@ function buildPromptIterable(queue, sessionId) {
34761
35248
  })();
34762
35249
  }
34763
35250
  var ClaudeAgentHandler = class {
34764
- agentType = "claude";
35251
+ agentHarness = "claude";
34765
35252
  capabilities = {
34766
35253
  auth: true,
34767
35254
  workspaceInit: true,
@@ -34780,7 +35267,10 @@ var ClaudeAgentHandler = class {
34780
35267
  if (blockIfNotInitialized2(sessionId)) return;
34781
35268
  const session = claudeSessions.get(sessionId);
34782
35269
  const modelChanged = session?.currentModel !== options.model;
34783
- const maxThinkingTokensChanged = session?.currentMaxThinkingTokens !== options.maxThinkingTokens;
35270
+ const requestedMaxThinkingTokens = resolveThinkingOptions(
35271
+ options.thinkingLevel
35272
+ ).maxThinkingTokens;
35273
+ const maxThinkingTokensChanged = session?.currentMaxThinkingTokens !== requestedMaxThinkingTokens;
34784
35274
  const settingsChangedFlag = settingsChanged(session?.currentSettings, options);
34785
35275
  if (session) {
34786
35276
  session.turnId = options.turnId;
@@ -34795,13 +35285,11 @@ var ClaudeAgentHandler = class {
34795
35285
  if (modelChanged && session) {
34796
35286
  const query2 = claudeQueries.get(sessionId);
34797
35287
  if (query2) {
34798
- const envVars = options.providerEnvVars ? parseEnvString(options.providerEnvVars) : {};
34799
- const mappedModel = mapModelForProvider(options.model, envVars);
34800
35288
  console.log(
34801
35289
  `Model changed from ${session.currentModel} to ${options.model}, using setModel callback`
34802
35290
  );
34803
35291
  try {
34804
- await query2.setModel(mappedModel);
35292
+ await query2.setModel(options.model);
34805
35293
  const updatedSession = claudeSessions.get(sessionId);
34806
35294
  if (updatedSession) updatedSession.currentModel = options.model;
34807
35295
  } catch (error48) {
@@ -34812,8 +35300,8 @@ var ClaudeAgentHandler = class {
34812
35300
  const query = claudeQueries.get(sessionId);
34813
35301
  if (maxThinkingTokensChanged && session && query) {
34814
35302
  try {
34815
- await query.setMaxThinkingTokens(options.maxThinkingTokens ?? null);
34816
- session.currentMaxThinkingTokens = options.maxThinkingTokens;
35303
+ await query.setMaxThinkingTokens(requestedMaxThinkingTokens ?? null);
35304
+ session.currentMaxThinkingTokens = requestedMaxThinkingTokens;
34817
35305
  } catch (error48) {
34818
35306
  console.error(`Failed to update maxThinkingTokens: ${getErrorMessage(error48)}`);
34819
35307
  }
@@ -34842,7 +35330,7 @@ var ClaudeAgentHandler = class {
34842
35330
  strictDataPrivacy: options.strictDataPrivacy
34843
35331
  },
34844
35332
  currentModel: options.model,
34845
- currentMaxThinkingTokens: options.maxThinkingTokens,
35333
+ currentMaxThinkingTokens: requestedMaxThinkingTokens,
34846
35334
  turnId: options.turnId,
34847
35335
  turnVersion: 1,
34848
35336
  cwd: options.cwd
@@ -34883,7 +35371,7 @@ var ClaudeAgentHandler = class {
34883
35371
  const { accountInfo, error: error48 } = await this.getClaudeAccountInfo(params.cwd);
34884
35372
  return {
34885
35373
  type: "claude_auth_output",
34886
- agentType: "claude",
35374
+ agentHarness: "claude",
34887
35375
  accountInfo,
34888
35376
  error: error48
34889
35377
  };
@@ -34896,7 +35384,7 @@ var ClaudeAgentHandler = class {
34896
35384
  });
34897
35385
  return {
34898
35386
  type: "workspace_init_output",
34899
- agentType: "claude",
35387
+ agentHarness: "claude",
34900
35388
  slashCommands,
34901
35389
  mcpServers,
34902
35390
  error: error48
@@ -34941,7 +35429,7 @@ var ClaudeAgentHandler = class {
34941
35429
  return {
34942
35430
  type: "context_usage",
34943
35431
  id: sessionId,
34944
- agentType: "claude",
35432
+ agentHarness: "claude",
34945
35433
  contextUsageData: message
34946
35434
  };
34947
35435
  }
@@ -35032,6 +35520,7 @@ var ClaudeAgentHandler = class {
35032
35520
  promptQueue.close();
35033
35521
  };
35034
35522
  const ctx = createStreamContext();
35523
+ let queryResult;
35035
35524
  try {
35036
35525
  let emitEvt2 = function(evt) {
35037
35526
  if (evt.type === "message.created" || evt.type === "message.done") {
@@ -35070,16 +35559,20 @@ var ClaudeAgentHandler = class {
35070
35559
  `[RESUME-DEBUG][${generatorId}] SDK options: resume=${sdkOptions.resume ?? "none"} cwd=${sdkOptions.cwd} model=${sdkOptions.model} permissionMode=${sdkOptions.permissionMode}`
35071
35560
  );
35072
35561
  const tSdkSpawn = Date.now();
35073
- const queryResult = Uy({ prompt: promptInput, options: sdkOptions });
35562
+ queryResult = Uy({ prompt: promptInput, options: sdkOptions });
35074
35563
  console.log(
35075
35564
  `[TIMING][${generatorId}] claudeSDK() constructor returned in ${Date.now() - tSdkSpawn}ms`
35076
35565
  );
35077
35566
  claudeQueries.set(sessionId, queryResult);
35567
+ attachQuery(queryResult, sdkOptions.mcpServers ?? {});
35078
35568
  session.generator = queryResult[Symbol.asyncIterator]();
35569
+ if (!options.model) {
35570
+ throw new Error(`[claude-handler] options.model is required (session=${sessionId})`);
35571
+ }
35079
35572
  const msgOpts = {
35080
35573
  sessionId,
35081
35574
  generatorId,
35082
- model: options.model || "opus",
35575
+ model: options.model,
35083
35576
  isResume: !!options.resume
35084
35577
  };
35085
35578
  let currentTurnVersion = session.turnVersion;
@@ -35136,13 +35629,13 @@ var ClaudeAgentHandler = class {
35136
35629
  console.log(
35137
35630
  `[TIMING][${generatorId}] STREAM_COMPLETE messages=${ctx.messageCount} totalStreamTime=${Date.now() - tStreamStart}ms totalProcessTime=${Date.now() - tProcessStart}ms`
35138
35631
  );
35139
- if (handleCancellation(sessionId, "claude", options.model || "opus", !!session.cancelledByUser)) {
35632
+ if (handleCancellation(sessionId, "claude", !!session.cancelledByUser)) {
35140
35633
  console.log(`[${generatorId}] Session cancelled by user: ${sessionId}`);
35141
35634
  return;
35142
35635
  }
35143
35636
  console.log(`[${generatorId}] Stream completed: ${sessionId}`);
35144
35637
  } catch (error48) {
35145
- if (handleCancellation(sessionId, "claude", options.model || "opus", !!session.cancelledByUser)) {
35638
+ if (handleCancellation(sessionId, "claude", !!session.cancelledByUser)) {
35146
35639
  console.log(`[${generatorId}] Session cancelled by user (catch): ${sessionId}`);
35147
35640
  return;
35148
35641
  }
@@ -35185,6 +35678,7 @@ ${errorStack}`);
35185
35678
  });
35186
35679
  }
35187
35680
  } finally {
35681
+ if (queryResult) detachQuery(queryResult);
35188
35682
  if (claudeSessions.owns(sessionId, session)) {
35189
35683
  claudeQueries.delete(sessionId);
35190
35684
  claudeSessions.delete(sessionId);
@@ -35667,7 +36161,7 @@ var CodexSdkTransformer = class {
35667
36161
  if (partId) {
35668
36162
  const existing = this.parts.get(partId);
35669
36163
  if (existing && existing.type === "REASONING") {
35670
- const updated = { ...existing, text, state: state3 };
36164
+ const updated = state3 === "DONE" ? completeReasoningPart(existing, text) : { ...existing, text, state: state3 };
35671
36165
  this.parts.set(partId, updated);
35672
36166
  if (state3 === "DONE") {
35673
36167
  this.prevTextLength.delete(itemId);
@@ -35824,7 +36318,7 @@ function getCodexExecutablePath() {
35824
36318
  function initializeCodex() {
35825
36319
  return discoverExecutable(
35826
36320
  {
35827
- agentType: "codex",
36321
+ agentHarness: "codex",
35828
36322
  displayName: "Codex",
35829
36323
  envVar: "CODEX_CLI_PATH",
35830
36324
  staticCandidates: ["/opt/homebrew/lib/node_modules/@openai/codex/bin/codex.js"],
@@ -35848,12 +36342,6 @@ function blockIfNotInitialized3(sessionId) {
35848
36342
  return blockIfNotInitialized(state2, "codex", sessionId);
35849
36343
  }
35850
36344
 
35851
- // apps/agent-server/agents/codex/codex-models.ts
35852
- var DEFAULT_MODEL = "gpt-5.4";
35853
- function resolveCodexModel(model) {
35854
- return model ?? DEFAULT_MODEL;
35855
- }
35856
-
35857
36345
  // apps/agent-server/agents/codex/codex-session.ts
35858
36346
  var codexSessions = new SessionStore();
35859
36347
  function abortCodexSession(sessionId) {
@@ -35866,7 +36354,7 @@ function abortCodexSession(sessionId) {
35866
36354
 
35867
36355
  // apps/agent-server/agents/codex/codex-handler.ts
35868
36356
  var CodexAgentHandler = class {
35869
- agentType = "codex";
36357
+ agentHarness = "codex";
35870
36358
  capabilities = {
35871
36359
  auth: false,
35872
36360
  workspaceInit: false,
@@ -35903,6 +36391,9 @@ var CodexAgentHandler = class {
35903
36391
  // Private methods
35904
36392
  // ==========================================================================
35905
36393
  async processQuery(sessionId, prompt, options, existingThreadId) {
36394
+ if (!options.model) {
36395
+ throw new Error(`[codex-handler] options.model is required (session=${sessionId})`);
36396
+ }
35906
36397
  const queryId = `${sessionId}/${Date.now()}`;
35907
36398
  const abortController = new AbortController();
35908
36399
  const session = {
@@ -35920,7 +36411,7 @@ var CodexAgentHandler = class {
35920
36411
  ghToken: options?.ghToken
35921
36412
  });
35922
36413
  const apiKey = env.OPENAI_API_KEY || env.CODEX_API_KEY;
35923
- const model = resolveCodexModel(options?.model);
36414
+ const model = options.model;
35924
36415
  const codexPath = getCodexExecutablePath();
35925
36416
  const { Codex } = await import("@openai/codex-sdk");
35926
36417
  const workspaceContext = buildWorkspaceContext(options?.cwd);
@@ -35985,7 +36476,7 @@ var CodexAgentHandler = class {
35985
36476
  }
35986
36477
  if (codexSessions.owns(sessionId, session)) {
35987
36478
  if (abortController.signal.aborted) {
35988
- handleCancellation(sessionId, "codex", resolveCodexModel(options?.model), true);
36479
+ handleCancellation(sessionId, "codex", true);
35989
36480
  }
35990
36481
  }
35991
36482
  console.log(`[${queryId}] Codex session completed: ${sessionId}`);
@@ -35998,7 +36489,7 @@ var CodexAgentHandler = class {
35998
36489
  );
35999
36490
  if (codexSessions.owns(sessionId, session)) {
36000
36491
  if (isAbort) {
36001
- handleCancellation(sessionId, "codex", resolveCodexModel(options?.model), true);
36492
+ handleCancellation(sessionId, "codex", true);
36002
36493
  } else {
36003
36494
  handleQueryError(sessionId, "codex", error48);
36004
36495
  }
@@ -36028,8 +36519,8 @@ function isShuttingDown() {
36028
36519
  function setShuttingDown(value) {
36029
36520
  shuttingDown = value;
36030
36521
  }
36031
- function trackSession(sessionId, agentType) {
36032
- activeSessions.set(sessionId, agentType);
36522
+ function trackSession(sessionId, agentHarness) {
36523
+ activeSessions.set(sessionId, agentHarness);
36033
36524
  }
36034
36525
  function untrackSession(sessionId) {
36035
36526
  activeSessions.delete(sessionId);
@@ -36037,7 +36528,7 @@ function untrackSession(sessionId) {
36037
36528
  function buildHealthResponse(wss) {
36038
36529
  const uptimeSeconds = (Date.now() - startTime) / 1e3;
36039
36530
  const memoryMb = Math.round(process.memoryUsage.rss() / 1024 / 1024 * 100) / 100;
36040
- const agents = getRegisteredAgentTypes();
36531
+ const agents = getRegisteredAgentHarnesses();
36041
36532
  const connections = wss ? wss.clients.size : 0;
36042
36533
  return {
36043
36534
  status: "ok",
@@ -36098,9 +36589,9 @@ function waitForDrain(config2 = DEFAULT_SHUTDOWN_CONFIG) {
36098
36589
  }
36099
36590
  async function cancelRemainingSessions() {
36100
36591
  const entries = [...activeSessions];
36101
- for (const [sessionId, agentType] of entries) {
36102
- console.log(`[SHUTDOWN] Force-cancelling session ${sessionId} (agent=${agentType})`);
36103
- const agent = getAgent(agentType);
36592
+ for (const [sessionId, agentHarness] of entries) {
36593
+ console.log(`[SHUTDOWN] Force-cancelling session ${sessionId} (agent=${agentHarness})`);
36594
+ const agent = getAgent(agentHarness);
36104
36595
  if (agent) {
36105
36596
  try {
36106
36597
  await agent.cancel(sessionId);
@@ -36109,12 +36600,12 @@ async function cancelRemainingSessions() {
36109
36600
  `[SHUTDOWN] agent.cancel() failed for ${sessionId}, emitting events directly:`,
36110
36601
  err
36111
36602
  );
36112
- EventBroadcaster.emitMessageCancelled(sessionId, agentType);
36113
- EventBroadcaster.emitSessionCancelled(sessionId, agentType);
36603
+ EventBroadcaster.emitMessageCancelled(sessionId, agentHarness);
36604
+ EventBroadcaster.emitSessionCancelled(sessionId, agentHarness);
36114
36605
  }
36115
36606
  } else {
36116
- EventBroadcaster.emitMessageCancelled(sessionId, agentType);
36117
- EventBroadcaster.emitSessionCancelled(sessionId, agentType);
36607
+ EventBroadcaster.emitMessageCancelled(sessionId, agentHarness);
36608
+ EventBroadcaster.emitSessionCancelled(sessionId, agentHarness);
36118
36609
  }
36119
36610
  }
36120
36611
  activeSessions.clear();
@@ -36217,12 +36708,12 @@ var AgentServer = class {
36217
36708
  }
36218
36709
  getInitializedAgents() {
36219
36710
  const agents = [];
36220
- for (const [agentType, handler] of [
36711
+ for (const [agentHarness, handler] of [
36221
36712
  ["claude", getAgent("claude")],
36222
36713
  ["codex", getAgent("codex")]
36223
36714
  ]) {
36224
- if (handler && this.initializedAgents.has(agentType)) {
36225
- agents.push({ type: agentType, capabilities: handler.capabilities, initialized: true });
36715
+ if (handler && this.initializedAgents.has(agentHarness)) {
36716
+ agents.push({ type: agentHarness, capabilities: handler.capabilities, initialized: true });
36226
36717
  }
36227
36718
  }
36228
36719
  return agents;
@@ -36242,33 +36733,36 @@ var AgentServer = class {
36242
36733
  });
36243
36734
  rpcTunnel.addMethod("turn/start", async (params) => {
36244
36735
  const sessionId = params?.sessionId;
36245
- const agentType = params?.agentType || "claude";
36736
+ const agentHarness = params?.agentHarness;
36246
36737
  const prompt = params?.prompt;
36247
36738
  const options = params?.options || {};
36248
36739
  if (isShuttingDown()) {
36249
36740
  return { accepted: false, reason: "shutting down" };
36250
36741
  }
36251
- if (!sessionId || !prompt) {
36252
- return { accepted: false, reason: "turn/start requires sessionId and prompt" };
36742
+ if (!sessionId || !prompt || !agentHarness) {
36743
+ return {
36744
+ accepted: false,
36745
+ reason: "turn/start requires sessionId, agentHarness, and prompt"
36746
+ };
36253
36747
  }
36254
- const agent = getAgent(agentType);
36748
+ const agent = getAgent(agentHarness);
36255
36749
  if (!agent) {
36256
- return { accepted: false, reason: `No agent registered for type: ${agentType}` };
36750
+ return { accepted: false, reason: `No agent registered for type: ${agentHarness}` };
36257
36751
  }
36258
- trackSession(sessionId, agentType);
36752
+ trackSession(sessionId, agentHarness);
36259
36753
  agent.query(sessionId, prompt, options).catch((err) => {
36260
- console.error(`[turn/start] Unhandled error in ${agentType} query:`, err);
36754
+ console.error(`[turn/start] Unhandled error in ${agentHarness} query:`, err);
36261
36755
  const classified = classifyError(err);
36262
36756
  EventBroadcaster.emitSessionError(
36263
36757
  sessionId,
36264
- agentType,
36758
+ agentHarness,
36265
36759
  classified.message,
36266
36760
  classified.category
36267
36761
  );
36268
36762
  }).finally(() => {
36269
36763
  untrackSession(sessionId);
36270
36764
  });
36271
- EventBroadcaster.emitSessionStarted(sessionId, agentType);
36765
+ EventBroadcaster.emitSessionStarted(sessionId, agentHarness);
36272
36766
  console.log(`[TIMING][turn/start] DISPATCHED session=${sessionId}`);
36273
36767
  return { accepted: true };
36274
36768
  });
@@ -36279,8 +36773,8 @@ var AgentServer = class {
36279
36773
  const cancelAll = (params) => {
36280
36774
  const sessionId = params?.sessionId;
36281
36775
  if (!sessionId) return;
36282
- for (const agentType of ["claude", "codex"]) {
36283
- const agent = getAgent(agentType);
36776
+ for (const agentHarness of ["claude", "codex"]) {
36777
+ const agent = getAgent(agentHarness);
36284
36778
  if (agent) void agent.cancel(sessionId);
36285
36779
  }
36286
36780
  };
@@ -36289,22 +36783,24 @@ var AgentServer = class {
36289
36783
  rpcTunnel.addMethod("session/reset", (params) => {
36290
36784
  const sessionId = params?.sessionId;
36291
36785
  if (!sessionId) return;
36292
- for (const agentType of ["claude", "codex"]) {
36293
- const agent = getAgent(agentType);
36786
+ for (const agentHarness of ["claude", "codex"]) {
36787
+ const agent = getAgent(agentHarness);
36294
36788
  if (agent) agent.reset(sessionId);
36295
36789
  }
36296
36790
  });
36297
36791
  rpcTunnel.addMethod("provider/auth", async (params) => {
36298
- const agentType = params?.agentType || "claude";
36299
- const agent = getAgent(agentType);
36300
- if (!agent?.auth) throw new Error(`Agent "${agentType}" does not support auth`);
36792
+ const agentHarness = params?.agentHarness;
36793
+ if (!agentHarness) throw new Error("provider/auth requires agentHarness");
36794
+ const agent = getAgent(agentHarness);
36795
+ if (!agent?.auth) throw new Error(`Agent "${agentHarness}" does not support auth`);
36301
36796
  return agent.auth({ cwd: params?.cwd });
36302
36797
  });
36303
36798
  rpcTunnel.addMethod("provider/initWorkspace", async (params) => {
36304
- const agentType = params?.agentType || "claude";
36305
- const agent = getAgent(agentType);
36799
+ const agentHarness = params?.agentHarness;
36800
+ if (!agentHarness) throw new Error("provider/initWorkspace requires agentHarness");
36801
+ const agent = getAgent(agentHarness);
36306
36802
  if (!agent?.initWorkspace)
36307
- throw new Error(`Agent "${agentType}" does not support workspace init`);
36803
+ throw new Error(`Agent "${agentHarness}" does not support workspace init`);
36308
36804
  return agent.initWorkspace({
36309
36805
  cwd: params?.cwd,
36310
36806
  ghToken: params?.ghToken,
@@ -36312,20 +36808,24 @@ var AgentServer = class {
36312
36808
  });
36313
36809
  });
36314
36810
  rpcTunnel.addMethod("provider/contextUsage", async (params) => {
36315
- const agentType = params?.agentType || "claude";
36316
- const agent = getAgent(agentType);
36811
+ const agentHarness = params?.agentHarness;
36812
+ const sessionId = params?.sessionId;
36813
+ const cwd = params?.cwd;
36814
+ const agentSessionId = params?.agentSessionId;
36815
+ if (!agentHarness || !sessionId || !cwd || !agentSessionId) {
36816
+ throw new Error(
36817
+ "provider/contextUsage requires agentHarness, sessionId, cwd, and agentSessionId"
36818
+ );
36819
+ }
36820
+ const agent = getAgent(agentHarness);
36317
36821
  if (!agent?.getContextUsage)
36318
- throw new Error(`Agent "${agentType}" does not support context usage`);
36319
- return agent.getContextUsage({
36320
- options: {
36321
- cwd: params?.cwd ?? "",
36322
- agentSessionId: params?.agentSessionId ?? ""
36323
- }
36324
- });
36822
+ throw new Error(`Agent "${agentHarness}" does not support context usage`);
36823
+ return agent.getContextUsage({ id: sessionId, options: { cwd, agentSessionId } });
36325
36824
  });
36326
36825
  rpcTunnel.addMethod("provider/updateMode", (params) => {
36327
- const agentType = params?.agentType || "claude";
36328
- const agent = getAgent(agentType);
36826
+ const agentHarness = params?.agentHarness;
36827
+ if (!agentHarness) throw new Error("provider/updateMode requires agentHarness");
36828
+ const agent = getAgent(agentHarness);
36329
36829
  if (agent?.updatePermissionMode) {
36330
36830
  void agent.updatePermissionMode(params?.sessionId, params?.permissionMode);
36331
36831
  }
@@ -36333,6 +36833,16 @@ var AgentServer = class {
36333
36833
  rpcTunnel.addMethod("agent/list", () => ({
36334
36834
  agents: this.getInitializedAgents()
36335
36835
  }));
36836
+ rpcTunnel.addMethod("aap/register-mcp", async (params) => {
36837
+ const parsed = RegisterAppMcpRequestSchema.parse(params);
36838
+ await registerAppMcp(parsed.serverName, parsed.url);
36839
+ return { added: [parsed.serverName] };
36840
+ });
36841
+ rpcTunnel.addMethod("aap/unregister-mcp", async (params) => {
36842
+ const parsed = UnregisterAppMcpRequestSchema.parse(params);
36843
+ await unregisterAppMcp(parsed.serverName);
36844
+ return { removed: [parsed.serverName] };
36845
+ });
36336
36846
  }
36337
36847
  /**
36338
36848
  * Handles a new WebSocket connection.
@@ -36366,7 +36876,7 @@ var AgentServer = class {
36366
36876
  async killRemainingChildProcesses() {
36367
36877
  return new Promise((resolve2) => {
36368
36878
  const command = `/usr/bin/pgrep -P ${process.pid}`;
36369
- (0, import_child_process7.exec)(command, (error48, stdout) => {
36879
+ (0, import_child_process8.exec)(command, (error48, stdout) => {
36370
36880
  if (error48) {
36371
36881
  console.log("[CLEANUP] No child processes found");
36372
36882
  resolve2();
@@ -36418,12 +36928,12 @@ var AgentServer = class {
36418
36928
  console.log("Initializing agent handlers...");
36419
36929
  this.initializedAgents.clear();
36420
36930
  const initResults = initializeAllAgents();
36421
- for (const [agentType, result] of initResults) {
36931
+ for (const [agentHarness, result] of initResults) {
36422
36932
  if (!result.success) {
36423
- console.error(`${agentType} initialization failed:`, result.error);
36933
+ console.error(`${agentHarness} initialization failed:`, result.error);
36424
36934
  } else {
36425
- console.log(`${agentType} handler initialized successfully`);
36426
- this.initializedAgents.add(agentType);
36935
+ console.log(`${agentHarness} handler initialized successfully`);
36936
+ this.initializedAgents.add(agentHarness);
36427
36937
  }
36428
36938
  }
36429
36939
  setAgentsInitialized(this.initializedAgents.size > 0);