feat(server,web,mobile): an agent sets up a link to another environment #17129
Mergedjuliusmarmingemerged 10 commits into
t3code/peer/remote-delegate fromrefs/pull/17129/headmerged by juliusmarminge View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
juliusmarminge added labelsmacroscope-review
- apps/mobile/src/state/peerPairingCode.ts line 30OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +10,21 @@10+11+// Each read mints a new one-use code; nothing keeps one once it is read.12+const peerPairingCodeAtom = Atom.family((environmentId: EnvironmentId) =>13+ connectionAtomRuntime14+ .atom((get) => {15+ const prepared = Option.getOrNull(16+ get(environmentSession.preparedConnectionValueAtom(environmentId)),17+ );18+ if (prepared === null) return Effect.never;19+ return mintPeerPairingCode(prepared);20+ })21+ .pipe(Atom.withLabel(`mobile-peer-pairing-code:${environmentId}`)),22+);23+24+/**25+ * A fresh pairing code minted on `environmentId` with this client's session26+ * there, for answering a link request. Fails with `PeerPairingCodeError` when27+ * the session may not create one.28+ */29+export function mintPairingCodeOn(environmentId: EnvironmentId): Promise<string> {30+ const atom = peerPairingCodeAtom(environmentId);apps/server/src/peer/PeerLinkRequests.ts line 166Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +141,21 @@141+ Effect.gen(function* () {142+ // The card is shown in, and answered from, the caller's own thread.143+ const threadScope = yield* McpInvocationContext.requireThreadScope(144+ scope,145+ "t3_environment_link",146+ );147+ const threadId = threadScope.thread.threadId;148+ const unreadable = (error: unknown) =>149+ failure("orchestration_error", `Unable to read the link request: ${errorMessage(error)}`);150+ if (input.url !== undefined && input.environmentId !== undefined) {151+ return yield* failure(152+ "invalid_request",153+ "Pass either environmentId or url, not both. Pass neither to let the user pick the machine.",154+ );155+ }156+ // A machine already linked needs no card: the agent can use it now.157+ if (input.environmentId !== undefined) {158+ const linked = yield* peerLinks159+ .get(input.environmentId)160+ .pipe(Effect.mapError((error) => failure("orchestration_error", error.message)));161+ if (Option.isSome(linked)) {apps/server/src/orchestration-v2/Orchestrator.ts line 7369OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -7344,0 +7349,21 @@7349+ * The pairing code goes straight to the link and never through orchestration.7350+ */7351+ const dispatchLinkRequestRecord = Effect.fn("orchestrationV2.dispatch.linkRequestRecord")(7352+ function* (7353+ command: Extract<OrchestrationV2InternalCommand, { readonly type: "link_request.record" }>,7354+ events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,7355+ effects: Ref.Ref<Array<PendingOrchestrationEffectV2>>,7356+ ) {7357+ const projection = yield* projectionStore7358+ .getThreadRecords(7359+ command.threadId,7360+ ["runs", "nodes", "turnItems", "attempts", "providerTurns"],7361+ { turnItemTypes: ["link_request"], messageRoles: [] },7362+ )7363+ .pipe(7364+ Effect.mapError(7365+ (cause) => new OrchestratorProjectionError({ threadId: command.threadId, cause }),7366+ ),7367+ );7368+ const run = projection.runs.find((candidate) => candidate.id === command.runId);7369+ if (run === undefined || run.rootNodeId !== command.nodeId) {apps/web/src/components/chat/LinkRequestCard.tsx line 395OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +375,21 @@375+ ) : target.kind === "none" ? null : (376+ <>377+ {canMint ? null : (378+ <label className="block space-y-1.5">379+ <span className="block text-xs font-medium text-foreground">Pairing code</span>380+ <Input381+ value={pairingCode}382+ onChange={(event) => setPairingCode(event.target.value)}383+ placeholder="Paste the code"384+ disabled={busy}385+ autoComplete="one-time-code"386+ nativeInput387+ spellCheck={false}388+ />389+ <span className="block text-xs text-muted-foreground">390+ Create a link on {targetName}: Settings → Connections → Create link, then391+ paste its code here.392+ </span>393+ </label>394+ )}395+ <LinkAccessPicker value={access} onChange={setAccess} />apps/web/src/components/chat/LinkRequestCard.tsx line 410OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +390,21 @@390+ Create a link on {targetName}: Settings → Connections → Create link, then391+ paste its code here.392+ </span>393+ </label>394+ )}395+ <LinkAccessPicker value={access} onChange={setAccess} />396+ </>397+ )}398+ {error !== null ? (399+ <p role="alert" className="text-xs text-destructive">400+ {error}401+ </p>402+ ) : null}403+ </form>404+ </DialogPanel>405+ <DialogFooter variant="bare">406+ <Button407+ variant="outline"408+ type="button"409+ disabled={busy}410+ onClick={() => props.onOpenChange(false)}
- apps/server/src/orchestration-v2/Orchestrator.ts lines 8276 to 8283OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -7344,0 +7355,21 @@7355+ effects: Ref.Ref<Array<PendingOrchestrationEffectV2>>,7356+ ) {7357+ const projection = yield* projectionStore7358+ .getThreadRecords(7359+ command.threadId,7360+ ["runs", "nodes", "turnItems", "attempts", "providerTurns"],7361+ { turnItemTypes: ["link_request"], messageRoles: [] },7362+ )7363+ .pipe(7364+ Effect.mapError(7365+ (cause) => new OrchestratorProjectionError({ threadId: command.threadId, cause }),7366+ ),7367+ );7368+ const run = projection.runs.find((candidate) => candidate.id === command.runId);7369+ if (run === undefined || run.rootNodeId !== command.nodeId) {7370+ return yield* new OrchestratorDispatchError({7371+ commandId: command.commandId,7372+ commandType: command.type,7373+ cause: `Node ${command.nodeId} is not the root of run ${command.runId}.`,7374+ });7375+ }
- apps/server/src/peer/PeerLinkRequests.ts line 174OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +154,21 @@154+ );155+ }156+ // A machine already linked needs no card: the agent can use it now.157+ if (input.environmentId !== undefined) {158+ const linked = yield* peerLinks159+ .get(input.environmentId)160+ .pipe(Effect.mapError((error) => failure("orchestration_error", error.message)));161+ if (Option.isSome(linked)) {162+ return {163+ status: "linked",164+ environmentId: linked.value.environmentId,165+ label: linked.value.label,166+ access: linked.value.access,167+ } as const;168+ }169+ }170+ const key = input.clientRequestId ?? (yield* crypto.randomUUIDv4.pipe(Effect.orDie));171+ // Turn item ids are global; scope the key to this thread. A retry with172+ // the same clientRequestId finds this card and records nothing.173+ const turnItemId = TurnItemId.make(174+ `turn-item:link-request:${encodeURIComponent(threadId)}:${encodeURIComponent(key)}`,
- apps/web/src/components/chat/LinkRequestCard.tsx lines 300 to 304OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +284,21 @@284+ setError(linkRequestFailureMessage(cause));285+ return;286+ }287+ }288+ input = linkRequestAnswerInput(item, {289+ type: "link",290+ target:291+ target.kind === "address"292+ ? { url: address }293+ : { ...target, urls: needsAddress ? [address.trim()] : target.urls },294+ access,295+ pairingCode: code,296+ });297+ }298+ if (input === null) return;299+ const result = await answer({ environmentId: props.environmentId, input });300+ if (result._tag === "Success") {301+ // The card switches to its answered row once the item updates.302+ setPairingCode("");303+ props.onOpenChange(false);304+ return;
- packages/client-runtime/src/linkRequest.ts lines 81 to 79OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +59,21 @@59+}): ReadonlyArray<LinkableMachine> {60+ const saved = input.environments61+ .filter((environment) => environment.environmentId !== input.threadEnvironmentId)62+ .map((environment) => {63+ const reported = (environment.serverConfig?.directEndpoints ?? []).map(64+ (endpoint) => endpoint.httpBaseUrl,65+ );66+ const connect = input.connect.get(environment.environmentId)?.environment.endpoint;67+ const routes = connectionRoutes(environment.entry).flatMap((route) => {68+ const url =69+ route.target._tag === "RelayConnectionTarget"70+ ? connect?.httpBaseUrl71+ : routeHttpBaseUrl(route);72+ return url === null || url === undefined ? [] : [url];73+ });74+ return {75+ environmentId: environment.environmentId,76+ label: environment.entry.target.label,77+ machine: resolveEnvironmentMachineKind(environment.serverConfig),78+ connected: environment.connection.phase === "connected",79+ connectOnly: false,apps/web/src/components/chat/LinkRequestCard.tsx line 394Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +379,21 @@379+ placeholder="https://machine.tailnet.ts.net"380+ disabled={busy}381+ nativeInput382+ spellCheck={false}383+ />384+ {target.kind === "machine" ? (385+ <span className="block text-xs text-muted-foreground">386+ This app has no address for {target.label} that another machine can reach.387+ Enter its https or Tailscale address.388+ </span>389+ ) : null}390+ </label>391+ ) : null}392+ {useExisting ? (393+ <p className="text-xs text-muted-foreground">394+ This environment is already linked to {targetName}. The agent can use that link395+ as it is; change its access in Settings → Connections.396+ </p>397+ ) : null}398+ </>399+ ) : (
- @@ -0,0 +124,21 @@124+ request.pipe(125+ HttpClientRequest.bearerToken(options.token),126+ HttpClientRequest.setHeader(127+ ORCHESTRATION_PROTOCOL_HEADER,128+ String(ORCHESTRATION_PROTOCOL_VERSION),129+ ),130+ ),131+ ),132+ HttpClient.filterStatusOk,133+ );134+ const descriptor = yield* http135+ .get(`${options.server}/.well-known/t3/environment`)136+ .pipe(Effect.flatMap(HttpClientResponse.schemaBodyJson(ExecutionEnvironmentDescriptor)));137+ const shell = yield* http138+ .get(`${options.server}/api/orchestration/shell`)139+ .pipe(Effect.flatMap(HttpClientResponse.schemaBodyJson(OrchestrationV2ShellSnapshot)));140+ let projectId = shell.projects.find(141+ (project) => project.workspaceRoot === options.projectRoot,142+ )?.id;143+ // A project record outlives its folder, and turns fail without it.144+ yield* (yield* FileSystem.FileSystem).makeDirectory(options.projectRoot, { recursive: true });@@ -0,0 +120,21 @@120+121+const connectServer = Effect.fn("measure.connectServer")(function* (options: Options) {122+ const http = (yield* HttpClient.HttpClient).pipe(123+ HttpClient.mapRequest((request) =>124+ request.pipe(125+ HttpClientRequest.bearerToken(options.token),126+ HttpClientRequest.setHeader(127+ ORCHESTRATION_PROTOCOL_HEADER,128+ String(ORCHESTRATION_PROTOCOL_VERSION),129+ ),130+ ),131+ ),132+ HttpClient.filterStatusOk,133+ );134+ const descriptor = yield* http135+ .get(`${options.server}/.well-known/t3/environment`)136+ .pipe(Effect.flatMap(HttpClientResponse.schemaBodyJson(ExecutionEnvironmentDescriptor)));137+ const shell = yield* http138+ .get(`${options.server}/api/orchestration/shell`)139+ .pipe(Effect.flatMap(HttpClientResponse.schemaBodyJson(OrchestrationV2ShellSnapshot)));140+ let projectId = shell.projects.find(
juliusmarminge assignedjuliusmarminge
- @@ -0,0 +91,21 @@91+ ) => Effect.Effect<void, PeerLinkRequestError>;92+ }93+>()("t3/peer/PeerLinkRequests") {}94+95+const make = Effect.gen(function* () {96+ const threadManagement = yield* ThreadManagementService.ThreadManagementService;97+ const peerLinks = yield* PeerLinks.PeerLinks;98+ const crypto = yield* Crypto.Crypto;99+100+ const readCard = (threadId: ThreadId, turnItemId: TurnItemId) =>101+ threadManagement102+ .getThreadRecords(threadId, ["turnItems"], {103+ turnItemTypes: ["link_request"],104+ messageRoles: [],105+ })106+ .pipe(107+ Effect.map((records) => {108+ const item = records.turnItems.find((candidate) => candidate.id === turnItemId);109+ // A deleted thread's cards went with it.110+ return item?.type === "link_request" && records.thread.deletedAt === null111+ ? item
- @@ -0,0 +151,21 @@151+ function* (scope, input) {152+ // The card is shown in, and answered from, the caller's own thread.153+ const threadScope = yield* McpInvocationContext.requireThreadScope(154+ scope,155+ "t3_environment_link",156+ );157+ const threadId = threadScope.thread.threadId;158+ const unreadable = (error: unknown) =>159+ new OrchestratorMcpFailure({160+ code: "orchestration_error",161+ message: `Unable to read the link request: ${errorMessage(error)}`,162+ });163+ if (input.url !== undefined && input.environmentId !== undefined) {164+ return yield* new OrchestratorMcpFailure({165+ code: "invalid_request",166+ message:167+ "Pass either environmentId or url, not both. Pass neither to let the user pick the machine.",168+ });169+ }170+ // A machine already linked needs no card: the agent can use it now.171+ if (input.environmentId !== undefined) {
juliusmarminge added labelsagent-context-increase
juliusmarminge merged this8b14660
juliusmarminge closed this
Sign in to join this conversation.







macroscopeapp[bot](GitHub profile, opens in a new tab) reviewed