Skip to content
TypeScript

feat(devices): target concurrent agent sessions across hosts (#10855)

Julius Marminge7734c6d71b6d
diff --git a/apps/server/src/device/AgentDeviceShim.ts b/apps/server/src/device/AgentDeviceShim.ts
index c2a28127e31..e3f92de492f 100644
--- a/apps/server/src/device/AgentDeviceShim.ts
+++ b/apps/server/src/device/AgentDeviceShim.ts
@@ -1,3 +1,4 @@
+// @effect-diagnostics preferSchemaOverJson:off - JSON string literals embed paths safely into generated JavaScript.
/**
* A directory holding an `agent-device` launcher that runs the pinned install
* with the server's Node. Prepended to provider subprocess PATHs so the agent
@@ -22,11 +23,34 @@ export const ensureAgentDeviceShim = Effect.fn("AgentDeviceShim.ensure")(functio
const shimDir = path.join(input.stateDir, SHIM_DIR);
yield* fs.makeDirectory(shimDir, { recursive: true });
const node = process.execPath;
+ const launcherPath = path.join(shimDir, "agent-device-launcher.mjs");
+ yield* fs.writeFileString(
+ launcherPath,
+ `import { spawn } from "node:child_process";
+const args = process.argv.slice(2);
+const informational = args.length === 1 && ["help", "--help", "-h", "--version", "version"].includes(args[0]);
+const hasValue = flag => { const index = args.indexOf(flag); return index >= 0 && !!args[index + 1] && !args[index + 1].startsWith("--"); };
+if (!informational && !(hasValue("--config") && hasValue("--session"))) {
+ console.error("Call device_open first and include its --config and --session flags.");
+ process.exit(1);
+}
+const env = { ...process.env };
+delete env.AGENT_DEVICE_DAEMON_BASE_URL;
+delete env.AGENT_DEVICE_DAEMON_AUTH_TOKEN;
+delete env.AGENT_DEVICE_CONFIG;
+const child = spawn(${JSON.stringify(node)}, [${JSON.stringify(entryPath)}, ...args], { stdio: "inherit", env });
+child.on("error", error => { console.error(error.message); process.exitCode = 1; });
+child.on("exit", code => { process.exitCode = code ?? 1; });
+`,
+ );
if (platform === "win32") {
- const script = `@echo off\r\n"${node}" "${entryPath}" %*\r\n`;
+ const script = `@echo off\r\n"${node}" "${launcherPath}" %*\r\n`;
yield* fs.writeFileString(path.join(shimDir, "agent-device.cmd"), script);
} else {
- const script = `#!/bin/sh\nexec "${node}" "${entryPath}" "$@"\n`;
+ const command = [node, launcherPath]
+ .map((value) => "'" + value.replaceAll("'", "'\"'\"'") + "'")
+ .join(" ");
+ const script = `#!/bin/sh\nexec ${command} "$@"\n`;
const shimPath = path.join(shimDir, "agent-device");
yield* fs.writeFileString(shimPath, script);
yield* fs.chmod(shimPath, 0o755);
diff --git a/apps/server/src/device/AgentDeviceTarget.test.ts b/apps/server/src/device/AgentDeviceTarget.test.ts
new file mode 100644
index 00000000000..3552beaf3cd
--- /dev/null
+++ b/apps/server/src/device/AgentDeviceTarget.test.ts
@@ -0,0 +1,89 @@
+// @effect-diagnostics nodeBuiltinImport:off - exercises concurrent real CLI subprocesses.
+import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
+import { describe, expect, it } from "@effect/vitest";
+import * as NodeChildProcess from "node:child_process";
+import * as NodeUtil from "node:util";
+import * as NodeServices from "@effect/platform-node/NodeServices";
+import * as Effect from "effect/Effect";
+import * as FileSystem from "effect/FileSystem";
+import * as Path from "effect/Path";
+import { ensureAgentDeviceShim } from "./AgentDeviceShim.ts";
+import {
+ agentDeviceConfigPath,
+ agentDeviceSession,
+ writeAgentDeviceConfig,
+} from "./AgentDeviceTarget.ts";
+
+const exec = NodeUtil.promisify(NodeChildProcess.execFile);
+
+describe("host-bound agent commands", () => {
+ it.effect("runs two hosts concurrently and only updates the reconnected host", () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const temp = yield* fs.makeTempDirectoryScoped({ prefix: "t3-device-target-" });
+ const platform = yield* HostProcessPlatform;
+ const dir = path.join(
+ temp,
+ platform === "win32" ? "paths with spaces" : "quotes '\" $HOME `literal`",
+ );
+ yield* fs.makeDirectory(dir);
+ const entryPath = path.join(dir, "cli.mjs");
+ yield* fs.writeFileString(
+ entryPath,
+ `import { readFileSync } from 'node:fs';
+const args = process.argv.slice(2);
+console.log(readFileSync(args[args.indexOf('--config') + 1], 'utf8'));
+if (process.env.AGENT_DEVICE_DAEMON_BASE_URL) process.exit(2);`,
+ );
+ const shim = yield* ensureAgentDeviceShim({ entryPath, stateDir: dir });
+ const files = ["mini", "android"].map((host) => agentDeviceConfigPath(dir, host, path));
+ for (const [index, file] of files.entries())
+ yield* writeAgentDeviceConfig(file, {
+ baseUrl: `http://127.0.0.1:${1000 + index}`,
+ token: `token-${index}`,
+ entryPath,
+ });
+ const invoke = (file: string) =>
+ exec(
+ platform === "win32" ? process.execPath : path.join(shim, "agent-device"),
+ [
+ ...(platform === "win32" ? [path.join(shim, "agent-device-launcher.mjs")] : []),
+ "snapshot",
+ "--config",
+ file,
+ "--session",
+ "test-session",
+ ],
+ { env: { ...process.env, AGENT_DEVICE_DAEMON_BASE_URL: "http://wrong-host" } },
+ ).then((result) => JSON.parse(result.stdout));
+ expect(yield* Effect.promise(() => Promise.all(files.map(invoke)))).toEqual([
+ { daemonBaseUrl: "http://127.0.0.1:1000", daemonAuthToken: "token-0" },
+ { daemonBaseUrl: "http://127.0.0.1:1001", daemonAuthToken: "token-1" },
+ ]);
+ const second = yield* fs.readFileString(files[1]!);
+ yield* writeAgentDeviceConfig(files[0]!, {
+ baseUrl: "http://127.0.0.1:2000",
+ token: "new",
+ entryPath,
+ });
+ expect((yield* Effect.promise(() => invoke(files[0]!))).daemonAuthToken).toBe("new");
+ expect(yield* fs.readFileString(files[1]!)).toBe(second);
+ expect(agentDeviceSession("thread", "mini", "same-id")).not.toBe(
+ agentDeviceSession("thread", "android", "same-id"),
+ );
+ for (const args of [
+ ["snapshot"],
+ ["snapshot", "--config", files[0]!],
+ ["snapshot", "--config", "help"],
+ ["snapshot", "--config", files[0]!, "--session"],
+ ]) {
+ yield* Effect.promise(() =>
+ expect(
+ exec(process.execPath, [path.join(shim, "agent-device-launcher.mjs"), ...args]),
+ ).rejects.toThrow("Call device_open first"),
+ );
+ }
+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
+ );
+});
diff --git a/apps/server/src/device/AgentDeviceTarget.ts b/apps/server/src/device/AgentDeviceTarget.ts
new file mode 100644
index 00000000000..379649b1257
--- /dev/null
+++ b/apps/server/src/device/AgentDeviceTarget.ts
@@ -0,0 +1,43 @@
+import * as NodeCrypto from "node:crypto";
+import * as Schema from "effect/Schema";
+import * as Effect from "effect/Effect";
+import * as FileSystem from "effect/FileSystem";
+import * as Path from "effect/Path";
+
+import type { AgentDeviceEndpoint } from "./DeviceHost.ts";
+
+const encodeEndpoint = Schema.encodeEffect(
+ Schema.fromJsonString(
+ Schema.Struct({ daemonBaseUrl: Schema.String, daemonAuthToken: Schema.String }),
+ ),
+);
+
+const key = (value: string) =>
+ NodeCrypto.createHash("sha256").update(value).digest("hex").slice(0, 24);
+
+/** A stable file per host lets forwarded endpoints change without retargeting other commands. */
+export const agentDeviceConfigPath = (stateDir: string, hostId: string, path: Path.Path) =>
+ path.join(stateDir, "device", "hosts", `${key(hostId)}.json`);
+
+export const agentDeviceSession = (threadId: string, hostId: string, deviceId: string) =>
+ `t3-${key(JSON.stringify([threadId, hostId, deviceId]))}`;
+
+export const writeAgentDeviceConfig = Effect.fn("AgentDeviceTarget.writeConfig")(function* (
+ file: string,
+ endpoint: AgentDeviceEndpoint,
+) {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ yield* fs.makeDirectory(path.dirname(file), { recursive: true });
+ const content = yield* encodeEndpoint({
+ daemonBaseUrl: endpoint.baseUrl,
+ daemonAuthToken: endpoint.token,
+ });
+ if ((yield* fs.readFileString(file).pipe(Effect.orElseSucceed(() => ""))) === content) return;
+ const temporary = yield* fs.makeTempFile({ directory: path.dirname(file), prefix: ".endpoint-" });
+ yield* Effect.gen(function* () {
+ yield* fs.chmod(temporary, 0o600);
+ yield* fs.writeFileString(temporary, content);
+ yield* fs.rename(temporary, file);
+ }).pipe(Effect.ensuring(fs.remove(temporary, { force: true }).pipe(Effect.ignore)));
+});
diff --git a/apps/server/src/device/DeviceService.test.ts b/apps/server/src/device/DeviceService.test.ts
index 49a8545bfd6..b45db236fab 100644
--- a/apps/server/src/device/DeviceService.test.ts
+++ b/apps/server/src/device/DeviceService.test.ts
@@ -16,7 +16,7 @@ import { HttpClient, HttpClientResponse } from "effect/unstable/http";
import { ServerSettingsService } from "../serverSettings.ts";
import * as DeviceHost from "./DeviceHost.ts";
-import { type DeviceService, make, stateStream } from "./DeviceService.ts";
+import { type DeviceService, makeWithHosts, stateStream } from "./DeviceService.ts";
const baseState: DeviceServiceState = {
hosts: [],
@@ -108,7 +108,7 @@ const fixture = Effect.fn("fixture")(function* (
starts.push("stop");
}),
};
- const service = yield* make.pipe(
+ const service = yield* makeWithHosts(new Map([[host.id, host]])).pipe(
Effect.provideService(DeviceHost.DeviceHost, host),
Effect.provideService(
ServerSettingsService,
diff --git a/apps/server/src/device/DeviceService.ts b/apps/server/src/device/DeviceService.ts
index 597e1a5d2b1..866663dbf21 100644
--- a/apps/server/src/device/DeviceService.ts
+++ b/apps/server/src/device/DeviceService.ts
@@ -33,6 +33,15 @@ import {
LOCAL_DEVICE_HOST_ID,
type ThreadId,
} from "@t3tools/contracts";
+import * as FileSystem from "effect/FileSystem";
+import * as Path from "effect/Path";
+import { ensureAgentDevice } from "./DeviceToolchain.ts";
+import * as ServerConfig from "../config.ts";
+import {
+ agentDeviceConfigPath,
+ agentDeviceSession,
+ writeAgentDeviceConfig,
+} from "./AgentDeviceTarget.ts";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
@@ -49,6 +58,7 @@ import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstab
import * as ServerSettings from "../serverSettings.ts";
import { readDeviceDetail, runDeviceAction } from "./DeviceActions.ts";
+import * as ProcessRunner from "../processRunner.ts";
import * as DeviceHost from "./DeviceHost.ts";
import * as LocalDeviceHost from "./LocalDeviceHost.ts";
@@ -94,6 +104,12 @@ export interface DeviceAgentReadiness extends DeviceReadiness {
export class DeviceService extends Context.Service<
DeviceService,
{
+ readonly agentCli: Effect.Effect<string, DeviceError>;
+ readonly agentTarget: (input: {
+ threadId: ThreadId;
+ hostId: DeviceHostId;
+ deviceId: DeviceId;
+ }) => Effect.Effect<ReadonlyArray<string>, DeviceError>;
readonly state: Effect.Effect<DeviceServiceState>;
readonly subscribe: Effect.Effect<PubSub.Subscription<DeviceServiceState>, never, Scope.Scope>;
readonly configure: (
@@ -138,6 +154,16 @@ const vendorPrefix = (platform: DevicePlatform) =>
export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function* (
hosts: ReadonlyMap<DeviceHostId, DeviceHost.DeviceHost["Service"]>,
+ configureAgent: (
+ hostId: DeviceHostId,
+ ready: DeviceHost.DeviceHostAgentReady,
+ ) => Effect.Effect<string, DeviceError> = (hostId) =>
+ Effect.fail(
+ new DeviceHostUnavailableError({
+ hostId,
+ reason: "Agent configuration is unavailable in this device service.",
+ }),
+ ),
) {
const settings = yield* ServerSettings.ServerSettingsService;
const lifecycleLock = yield* Semaphore.make(1);
@@ -733,6 +759,29 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function*
);
return DeviceService.of({
+ agentCli: Effect.fail(
+ new DeviceHostUnavailableError({
+ hostId: LOCAL_DEVICE_HOST_ID,
+ reason: "Agent CLI installation is unavailable in this device service.",
+ }),
+ ),
+ agentTarget: (input) =>
+ Effect.gen(function* () {
+ const ready = yield* agentReadinessIfSupported(input.hostId);
+ if (!ready)
+ return yield* new DeviceHostUnavailableError({
+ hostId: input.hostId,
+ reason:
+ "Agent device access requires enabled device support, agent access, and an available simulator platform on this host.",
+ });
+ const configPath = yield* configureAgent(input.hostId, ready);
+ return [
+ "--config",
+ configPath,
+ "--session",
+ agentDeviceSession(input.threadId, input.hostId, input.deviceId),
+ ];
+ }),
state: SynchronizedRef.get(stateRef).pipe(Effect.map(({ state }) => state)),
subscribe: PubSub.subscribe(statePubSub),
configure,
@@ -751,9 +800,46 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function*
});
});
+/** @public Service construction is part of the canonical Effect module API. */
export const make = Effect.gen(function* () {
- const host = yield* DeviceHost.DeviceHost;
- return yield* makeWithHosts(new Map([[host.id, host]]));
+ const localHost = yield* DeviceHost.DeviceHost;
+ const config = yield* ServerConfig.ServerConfig;
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const runner = yield* ProcessRunner.ProcessRunner;
+ const service = yield* makeWithHosts(new Map([[localHost.id, localHost]]), (hostId, ready) => {
+ const file = agentDeviceConfigPath(config.stateDir, hostId, path);
+ return writeAgentDeviceConfig(file, ready.agentDevice).pipe(
+ Effect.provideService(FileSystem.FileSystem, fs),
+ Effect.provideService(Path.Path, path),
+ Effect.mapError(
+ (cause) =>
+ new DeviceOperationError({
+ operation: "configure agent",
+ reason: "settings_failed",
+ cause,
+ }),
+ ),
+ Effect.as(file),
+ );
+ });
+ return {
+ ...service,
+ agentCli: ensureAgentDevice(config.baseDir).pipe(
+ Effect.provideService(FileSystem.FileSystem, fs),
+ Effect.provideService(Path.Path, path),
+ Effect.provideService(ProcessRunner.ProcessRunner, runner),
+ Effect.map((tool) => tool.entryPath),
+ Effect.mapError(
+ (error) =>
+ new DeviceOperationError({
+ operation: "install agent CLI",
+ reason: "command_failed",
+ cause: error,
+ }),
+ ),
+ ),
+ };
});
export const layer = Layer.effect(DeviceService, make).pipe(Layer.provide(LocalDeviceHost.layer));
diff --git a/apps/server/src/mcp/McpDeviceToolkit.test.ts b/apps/server/src/mcp/McpDeviceToolkit.test.ts
index 32f919cbb68..24097a92faa 100644
--- a/apps/server/src/mcp/McpDeviceToolkit.test.ts
+++ b/apps/server/src/mcp/McpDeviceToolkit.test.ts
@@ -1,10 +1,16 @@
import { expect, it } from "@effect/vitest";
import * as NodeServices from "@effect/platform-node/NodeServices";
-import { EnvironmentId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
+import {
+ DeviceHostUnavailableError,
+ EnvironmentId,
+ ProviderInstanceId,
+ ThreadId,
+} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { McpSchema, McpServer } from "effect/unstable/ai";
+import * as ServerConfig from "../config.ts";
import * as DeviceService from "../device/DeviceService.ts";
import * as McpHttpServer from "./McpHttpServer.ts";
import * as McpInvocationContext from "./McpInvocationContext.ts";
@@ -85,11 +91,14 @@ const DeviceServiceMock = Layer.mock(DeviceService.DeviceService)({
sessionsForThread: () => Effect.succeed([]),
screenshot: () => Effect.succeed({ device, png }),
close: () => Effect.void,
+ agentCli: Effect.succeed("/cli"),
+ agentTarget: () => Effect.succeed(["--config", "/host.json", "--session", "thread-device"]),
});
const TestLayer = McpHttpServer.DeviceToolkitRegistrationLive.pipe(
Layer.provideMerge(McpServer.McpServer.layer),
Layer.provideMerge(DeviceServiceMock),
+ Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-mcp-device-toolkit-test-" })),
Layer.provide(NodeServices.layer),
);
@@ -126,3 +135,41 @@ it.effect("registers the device tools and returns the screenshot as image conten
}),
).pipe(Effect.provide(TestLayer)),
);
+
+it.effect("rejects unavailable agent access before booting or opening a device", () => {
+ const unavailable = Layer.mock(DeviceService.DeviceService)({
+ list: Effect.succeed(state),
+ agentTarget: () =>
+ Effect.fail(
+ new DeviceHostUnavailableError({ hostId: "local", reason: "Agent access is disabled." }),
+ ),
+ open: () => Effect.die("Must not boot or register a device when agent access fails"),
+ });
+ return Effect.gen(function* () {
+ const server = yield* McpServer.McpServer;
+ const result = yield* server
+ .callTool({ name: "device_open", arguments: { platform: "ios" } })
+ .pipe(
+ Effect.provideService(McpInvocationContext.McpInvocationContext, invocation(["device"])),
+ Effect.provideService(McpSchema.McpServerClient, client),
+ );
+ expect(result.isError).toBe(true);
+ expect(result.content).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ type: "text",
+ text: expect.stringContaining("Agent access is disabled."),
+ }),
+ ]),
+ );
+ }).pipe(
+ Effect.scoped,
+ Effect.provide(
+ McpHttpServer.DeviceToolkitRegistrationLive.pipe(
+ Layer.provideMerge(McpServer.McpServer.layer),
+ Layer.provide(unavailable),
+ Layer.provide(NodeServices.layer),
+ ),
+ ),
+ );
+});
diff --git a/apps/server/src/mcp/toolkits/device/handlers.test.ts b/apps/server/src/mcp/toolkits/device/handlers.test.ts
index e37b2a8b22c..110d4cbba72 100644
--- a/apps/server/src/mcp/toolkits/device/handlers.test.ts
+++ b/apps/server/src/mcp/toolkits/device/handlers.test.ts
@@ -30,6 +30,19 @@ describe("device tool helpers", () => {
expect(text).toContain("XCTest runner");
});
+ it("uses the absolute launcher in every quick-start command", () => {
+ const text = agentDeviceQuickStart(
+ device,
+ ["--session", "thread-1", "--config", "/tmp/host.json"],
+ "/tmp/t3 tools/agent-device",
+ );
+ expect(text).toContain(
+ "'/tmp/t3 tools/agent-device' snapshot -i --session thread-1 --config /tmp/host.json",
+ );
+ expect(text).not.toContain(" agent-device ");
+ expect(text).not.toContain("is on PATH");
+ });
+
it("reads PNG dimensions from the IHDR chunk", () => {
const png = new Uint8Array(24);
new DataView(png.buffer).setUint32(0, 0x89504e47);
diff --git a/apps/server/src/mcp/toolkits/device/handlers.ts b/apps/server/src/mcp/toolkits/device/handlers.ts
index 5ad57031306..3bc89d22bc6 100644
--- a/apps/server/src/mcp/toolkits/device/handlers.ts
+++ b/apps/server/src/mcp/toolkits/device/handlers.ts
@@ -8,6 +8,10 @@ import {
LOCAL_DEVICE_HOST_ID,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
+import * as Path from "effect/Path";
+import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
+import { ServerConfig } from "../../../config.ts";
+import { ensureAgentDeviceShim } from "../../../device/AgentDeviceShim.ts";
import * as DeviceService from "../../../device/DeviceService.ts";
import * as McpInvocationContext from "../../McpInvocationContext.ts";
@@ -26,24 +30,37 @@ export function agentDeviceTargetArgs(device: DeviceSummary): ReadonlyArray<stri
* rather than in the always-on prompt block; threads that never open a device
* never pay for it.
*/
-export function agentDeviceQuickStart(device: DeviceSummary): string {
- const target = agentDeviceTargetArgs(device).join(" ");
+export function agentDeviceQuickStart(
+ device: DeviceSummary,
+ targetArgs = agentDeviceTargetArgs(device),
+ command = "agent-device",
+): string {
+ const executable = /^[a-zA-Z0-9_./:-]+$/.test(command)
+ ? command
+ : "'" + command.replaceAll("'", "'\"'\"'") + "'";
+ const target = targetArgs
+ .map((arg) =>
+ /^[a-zA-Z0-9_./:-]+$/.test(arg) ? arg : "'" + arg.replaceAll("'", "'\"'\"'") + "'",
+ )
+ .join(" ");
const platformNotes =
device.platform === "ios"
? "First use builds an XCTest runner and can take a couple of minutes; later commands are fast."
: "The Android snapshot helper installs itself on first use.";
return [
`The user is watching ${device.name} (${device.version}) in the Device panel.`,
- `Drive it with the agent-device CLI, which is on PATH and already connected to this environment. Always pass ${target}.`,
+ `Drive it with ${executable}. Use this exact executable path; login shells may reset PATH. Always pass ${target}.`,
"Typical loop:",
- ` agent-device open <bundle-or-package-id> ${target} # or: open <app> <deep-link-url>`,
- ` agent-device snapshot -i ${target} # accessibility tree with @eN refs`,
- ` agent-device click @e3 ${target}`,
- ` agent-device fill @e5 "text" ${target}`,
- ` agent-device screenshot /tmp/shot.png ${target} # or call device_screenshot`,
- ` agent-device install <app> <path-to-.app-or-.apk> ${target}`,
- "Prefer snapshot refs over coordinates. Run `agent-device help` for workflow guides and `agent-device <command> --help` for flags.",
+ ` ${executable} open <bundle-or-package-id> ${target} # or: open <app> <deep-link-url>`,
+ ` ${executable} snapshot -i ${target} # accessibility tree with @eN refs`,
+ ` ${executable} click @e3 ${target}`,
+ ` ${executable} fill @e5 "text" ${target}`,
+ ` ${executable} screenshot /tmp/shot.png ${target} # or call device_screenshot`,
+ ` ${executable} install <app> <path-to-.app-or-.apk> ${target}`,
+ `Prefer snapshot refs over coordinates. Run ${executable} help for workflow guides and ${executable} <command> --help for flags.`,
"Do not call simctl, adb, xcrun, or serve-sim directly while these tools are attached; use agent-device.",
+ "For remote hosts, arrange builds, app installation, and any Metro reverse forwarding yourself. T3 provides discovery, streaming, and control only.",
+ "Keep the returned --config and --session flags on every command. Other hosts can be used concurrently; opening one does not switch these commands.",
platformNotes,
].join("\n");
}
@@ -136,6 +153,12 @@ const handlers = {
});
}
const target = yield* pickDevice(state.devices, input);
+ // Resolve consent and agent connectivity before booting or registering a session.
+ const agentArgs = yield* devices.agentTarget({
+ threadId: scope.threadId,
+ hostId: target.hostId,
+ deviceId: target.id,
+ });
const session = yield* devices.open({
threadId: scope.threadId,
hostId: target.hostId,
@@ -147,10 +170,29 @@ const handlers = {
after.devices.find(
(candidate) => candidate.hostId === session.hostId && candidate.id === session.deviceId,
) ?? target;
+ const targetArgs = [...agentDeviceTargetArgs(device), ...agentArgs];
+ const config = yield* ServerConfig;
+ const path = yield* Path.Path;
+ const platform = yield* HostProcessPlatform;
+ const shimDir = yield* ensureAgentDeviceShim({
+ entryPath: yield* devices.agentCli,
+ stateDir: config.stateDir,
+ }).pipe(
+ Effect.mapError(
+ () =>
+ new DeviceToolUnavailableError({
+ reason: "Could not prepare the agent-device launcher.",
+ }),
+ ),
+ );
+ const command = path.join(
+ shimDir,
+ platform === "win32" ? "agent-device.cmd" : "agent-device",
+ );
return {
device,
- agentDevice: { command: "agent-device", targetArgs: agentDeviceTargetArgs(device) },
- quickStart: agentDeviceQuickStart(device),
+ agentDevice: { command, targetArgs },
+ quickStart: agentDeviceQuickStart(device, targetArgs, command),
};
}).pipe(Effect.mapError(toolError)),
device_screenshot: (input) =>
diff --git a/apps/server/src/mcp/toolkits/device/tools.ts b/apps/server/src/mcp/toolkits/device/tools.ts
index e98d6ab6482..58bfed41d94 100644
--- a/apps/server/src/mcp/toolkits/device/tools.ts
+++ b/apps/server/src/mcp/toolkits/device/tools.ts
@@ -8,6 +8,9 @@ import {
DeviceToolTargetInput,
} from "@t3tools/contracts";
import * as Schema from "effect/Schema";
+import * as FileSystem from "effect/FileSystem";
+import * as Path from "effect/Path";
+import { ServerConfig } from "../../../config.ts";
import { Tool, Toolkit } from "effect/unstable/ai";
import * as McpInvocationContext from "../../McpInvocationContext.ts";
@@ -48,7 +51,7 @@ const DeviceOpenTool = Tool.make("device_open", {
parameters: DeviceToolOpenInput,
success: DeviceToolOpenResult,
failure: DeviceToolError,
- dependencies,
+ dependencies: [...dependencies, FileSystem.FileSystem, Path.Path, ServerConfig],
})
.annotate(Tool.Title, "Open device")
.annotate(Tool.Readonly, false)
diff --git a/apps/server/src/provider/CodexDeveloperInstructions.ts b/apps/server/src/provider/CodexDeveloperInstructions.ts
index 85784d21ca4..6a7fee351bc 100644
--- a/apps/server/src/provider/CodexDeveloperInstructions.ts
+++ b/apps/server/src/provider/CodexDeveloperInstructions.ts
@@ -16,7 +16,7 @@ const T3_CODE_DEVICE_TOOL_INSTRUCTIONS = `
## T3 Code devices
-The \`t3-code\` MCP server also exposes \`device_*\` tools for iOS Simulators and Android Emulators on this environment. For mobile verification, call \`device_list\`, then \`device_open\` so the user can watch the device in their Device panel; its result explains how to drive the device. Driving happens through the \`agent-device\` CLI, which is on PATH and already connected: prefer \`agent-device snapshot -i\` refs over coordinates, and use \`device_screenshot\` when you need to see the screen. Do not call simctl, adb, xcrun, or serve-sim directly while these tools are present. If \`device_list\` reports a platform as unavailable, say so instead of trying another route.
+The \`t3-code\` MCP server also exposes \`device_*\` tools for iOS Simulators and Android Emulators on this environment. For mobile verification, call \`device_list\`, then \`device_open\` so the user can watch the device in their Device panel; its result explains how to drive the device. Driving happens through the \`agent-device\` CLI, which is on PATH. Keep the host config and session flags returned by \`device_open\` on every command so concurrent devices stay independent: prefer \`agent-device snapshot -i\` refs over coordinates, and use \`device_screenshot\` when you need to see the screen. Do not call simctl, adb, xcrun, or serve-sim directly while these tools are present. If \`device_list\` reports a platform as unavailable, say so instead of trying another route.
`;
export interface T3CodeToolAvailability {
diff --git a/apps/server/src/provider/Layers/ProviderService.ts b/apps/server/src/provider/Layers/ProviderService.ts
index f2d94e735b0..d04dcae7f12 100644
--- a/apps/server/src/provider/Layers/ProviderService.ts
+++ b/apps/server/src/provider/Layers/ProviderService.ts
@@ -54,8 +54,8 @@ import * as Stream from "effect/Stream";
import { appendUserInputAttachmentPaths } from "../userInputAttachments.ts";
import { resolveAttachmentPath } from "../../attachmentStore.ts";
import * as ServerConfig from "../../config.ts";
-import { ensureAgentDeviceShim } from "../../device/AgentDeviceShim.ts";
import * as DeviceService from "../../device/DeviceService.ts";
+import { ensureAgentDeviceShim } from "../../device/AgentDeviceShim.ts";
import type * as McpInvocationContext from "../../mcp/McpInvocationContext.ts";
import {
increment,
@@ -254,8 +254,6 @@ export interface ProviderServiceLiveOptions {
* test see whether a credential was requested at all.
*/
readonly issueMcpCredential?: typeof McpSessionRegistry.issueActiveMcpCredential;
- /** Overrides the device host lookup used to build the agent-device environment. */
- readonly deviceReadiness?: DeviceService.DeviceService["Service"]["agentReadinessIfSupported"];
}
interface TurnAnalyticsMetadata {
@@ -484,14 +482,6 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
);
const issueMcpCredential =
options?.issueMcpCredential ?? McpSessionRegistry.issueActiveMcpCredential;
- const deviceReadiness =
- options?.deviceReadiness ??
- (() =>
- Effect.serviceOption(DeviceService.DeviceService).pipe(
- Effect.flatMap((service) =>
- Option.isSome(service) ? service.value.agentReadinessIfSupported() : Effect.succeed(null),
- ),
- ));
const fileSystem = yield* FileSystem.FileSystem;
const pathService = yield* Path.Path;
const runtimeEventPubSub = yield* PubSub.unbounded<ProviderRuntimeEvent>();
@@ -914,26 +904,19 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
return capabilities;
});
- /**
- * Starting a session with device access also brings the device host up, so
- * the `agent-device` CLI is on the provider's PATH from its first turn. The
- * environment is fixed at spawn time, so a host started later by
- * `device_open` could not reach an already-running agent. Tools install once
- * and the host is idempotent, so this is cheap after the first session;
- * a host that fails to start withholds only the CLI, not the MCP tools.
- */
+ /** Install only the local CLI here. device_open supplies a separate config for each host. */
const hostPlatform = yield* HostProcessPlatform;
const agentDeviceEnvironment = Effect.gen(function* () {
- const readiness = yield* deviceReadiness().pipe(
+ const devices = yield* Effect.serviceOption(DeviceService.DeviceService);
+ if (Option.isNone(devices)) return undefined;
+ const entryPath = yield* devices.value.agentCli.pipe(
Effect.catch((cause) =>
- Effect.logWarning("Device host unavailable; starting session without agent-device", {
- cause,
- }).pipe(Effect.as(null)),
+ Effect.logWarning("Agent device CLI unavailable", { cause }).pipe(Effect.as(null)),
),
);
- if (!readiness) return undefined;
+ if (!entryPath) return undefined;
const shimDir = yield* ensureAgentDeviceShim({
- entryPath: readiness.agentDevice.entryPath,
+ entryPath,
stateDir: serverConfig.stateDir,
}).pipe(
Effect.provideService(FileSystem.FileSystem, fileSystem),
@@ -944,8 +927,6 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
return {
PATH: shimDir,
PATH_SEPARATOR: hostPlatform === "win32" ? ";" : ":",
- AGENT_DEVICE_DAEMON_BASE_URL: readiness.agentDevice.baseUrl,
- AGENT_DEVICE_DAEMON_AUTH_TOKEN: readiness.agentDevice.token,
AGENT_DEVICE_NO_UPDATE_NOTIFIER: "1",
} satisfies Record<string, string>;
});