feat(server): link to another environment #16655
Mergedjuliusmarmingemerged 1 commit into
t3code/peer/launch-request-key fromrefs/pull/16655/headmerged by juliusmarminge View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
juliusmarminge added labelsmacroscope-review
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
juliusmarminge closed this
juliusmarminge reopened this
- apps/server/src/peer/PeerLinks.ts lines 190 to 190OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +170,21 @@170+ yield* crypto.digest("SHA-256", new TextEncoder().encode(verifier)).pipe(Effect.orDie),171+ );172+ const state = Base64Url.encode(yield* crypto.randomBytes(16).pipe(Effect.orDie));173+ const resource = `${origin}/mcp`;174+ const decided = yield* client.mcpOAuth175+ .decision({176+ payload: {177+ authorization: {178+ response_type: "code",179+ client_id: registered.client_id,180+ redirect_uri: LINK_REDIRECT_URI,181+ code_challenge: challenge,182+ code_challenge_method: "S256",183+ state,184+ resource,185+ },186+ decision: { _tag: "pairing-code", access: input.access, code: input.pairingCode },187+ },188+ })189+ .pipe(Effect.mapError((error) => rejected(error.message)));190+ const redirect = new URL(decided.redirectTo);apps/server/src/peer/PeerLinks.ts line 270OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +250,21 @@250+ });251+ }252+ if (peer.capabilities.mcpModeLimitHeader !== true) {253+ return yield* new PeerLinkError({254+ reason: "incompatible",255+ message: `${peer.label} runs a T3 Code version that cannot keep a linked agent's limits. Update it, then link again.`,256+ });257+ }258+ const issued = yield* signIn(primary, input, `T3 Code · ${self.label}`);259+ const now = yield* DateTime.now;260+ const linked: PeerLink = {261+ environmentId: peer.environmentId,262+ label: peer.label,263+ urls: origins,264+ access: input.access,265+ linkedAt: now,266+ expiresAt: DateTime.add(now, { seconds: issued.expires_in }),267+ lastReachedAt: now,268+ lastError: null,269+ };270+ yield* secretsapps/server/src/peer/PeerLinks.ts line 189OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +169,21 @@169+ const challenge = Base64Url.encode(170+ yield* crypto.digest("SHA-256", new TextEncoder().encode(verifier)).pipe(Effect.orDie),171+ );172+ const state = Base64Url.encode(yield* crypto.randomBytes(16).pipe(Effect.orDie));173+ const resource = `${origin}/mcp`;174+ const decided = yield* client.mcpOAuth175+ .decision({176+ payload: {177+ authorization: {178+ response_type: "code",179+ client_id: registered.client_id,180+ redirect_uri: LINK_REDIRECT_URI,181+ code_challenge: challenge,182+ code_challenge_method: "S256",183+ state,184+ resource,185+ },186+ decision: { _tag: "pairing-code", access: input.access, code: input.pairingCode },187+ },188+ })189+ .pipe(Effect.mapError((error) => rejected(error.message)));
- apps/server/src/peer/PeerLinks.ts lines 81 to 85OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +65,21 @@65+66+interface PeerLinkRow {67+ readonly environment_id: string;68+ readonly label: string;69+ readonly urls_json: string;70+ readonly access: string;71+ readonly linked_at: string;72+ readonly expires_at: string;73+ readonly last_reached_at: string | null;74+ readonly last_error: string | null;75+}76+77+const decodeUrls = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Array(Schema.String)));78+const encodeUrls = Schema.encodeEffect(Schema.fromJsonString(Schema.Array(Schema.String)));79+const decodeAccess = Schema.decodeUnknownEffect(AuthMcpClientAccess);80+81+const storageError = (cause: unknown) =>82+ new PeerLinkError({83+ reason: "storage",84+ message: `Peer links could not be read or saved: ${String(cause)}`,85+ });apps/server/src/peer/PeerLinks.ts lines 232 to 236OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +216,21 @@216+ error._tag === "PeerLinkError"217+ ? Effect.fail(error)218+ : Effect.fail(219+ new PeerLinkError({220+ reason: error._tag === "SchemaError" ? "incompatible" : "unreachable",221+ message:222+ error._tag === "SchemaError"223+ ? `${origin} answered in a shape this version does not understand. Update both environments.`224+ : `${origin} stopped answering while linking.`,225+ }),226+ ),227+ ),228+ );229+230+ const link: PeerLinks["Service"]["link"] = (input) =>231+ Effect.gen(function* () {232+ const origins = yield* Effect.forEach(233+ [input.url, ...(input.alternateUrls ?? [])],234+ peerOrigin,235+ );236+ const primary = origins[0]!;
- apps/server/src/peer/PeerLinks.ts line 454Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +398,21 @@398+ }399+ const link = yield* toLink(row.value);400+ if (DateTime.isLessThanOrEqualTo(link.expiresAt, yield* DateTime.now)) {401+ return yield* new PeerLinkError({402+ reason: "expired",403+ message: `The link to ${link.label} expired. Link it again with a new pairing code from ${link.label}.`,404+ });405+ }406+ const stored = yield* secrets.get(row.value.secret_name).pipe(Effect.catch(failStorage));407+ if (Option.isNone(stored)) {408+ return yield* new PeerLinkError({409+ reason: "unknown_link",410+ message: `The link to ${link.label} lost its credential. Link it again.`,411+ });412+ }413+ // The token goes only to an address that proves it is this peer, so a414+ // reused LAN address or a moved hostname never receives it.415+ const url = yield* Effect.findFirst(link.urls, (candidate) =>416+ describe(candidate).pipe(417+ Effect.map(418+ (found) => Option.isSome(found) && found.value.environmentId === environmentId,
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- @@ -0,0 +333,21 @@333+ last_reached_at, last_error334+ ) VALUES (335+ ${linked.environmentId}, ${secretName}, ${linked.label}, ${urlsJson}, ${linked.access},336+ ${DateTime.formatIso(linked.linkedAt)}, ${DateTime.formatIso(linked.expiresAt)},337+ ${DateTime.formatIso(now)}, NULL338+ )339+ ON CONFLICT (environment_id) DO UPDATE SET340+ secret_name = excluded.secret_name,341+ label = excluded.label,342+ urls_json = excluded.urls_json,343+ access = excluded.access,344+ linked_at = excluded.linked_at,345+ expires_at = excluded.expires_at,346+ last_reached_at = excluded.last_reached_at,347+ last_error = NULL348+ `.pipe(Effect.catch(failStorage));349+ // Linking again replaces the old token. A racing link may leave its own350+ // behind; it is unused either way.351+ if (Option.isSome(previous) && previous.value.secret_name !== secretName) {352+ yield* secrets.remove(previous.value.secret_name).pipe(Effect.ignore);353+ }
- apps/server/src/peer/PeerLinks.ts line 159Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +132,21 @@132+ }),133+ );134+ }135+ return Effect.succeed(parsed.origin);136+};137+138+const make = Effect.gen(function* () {139+ const sql = yield* SqlClient.SqlClient;140+ const secrets = yield* ServerSecretStore.ServerSecretStore;141+ const crypto = yield* Crypto.Crypto;142+ const httpClient = yield* HttpClient.HttpClient;143+ const environment = yield* ServerEnvironment.ServerEnvironment;144+145+ /** A fresh name for one link's token; the row records it. */146+ const newSecretName = crypto.randomBytes(16).pipe(147+ Effect.map((bytes) => `peer-link-${Hex.encode(bytes)}`),148+ Effect.orDie,149+ );150+151+ const clientFor = (origin: string) =>152+ HttpApiClient.make(EnvironmentHttpApi, { baseUrl: origin }).pipe(
- @@ -0,0 +345,21 @@345+ const urlsJson = yield* encodeUrls(origins).pipe(Effect.catch(failStorage));346+ const previous = yield* readRow(peer.environmentId);347+ yield* sql`348+ INSERT INTO peer_environment_links (349+ environment_id, secret_name, label, urls_json, access, linked_at, expires_at,350+ last_reached_at, last_error351+ ) VALUES (352+ ${linked.environmentId}, ${secretName}, ${linked.label}, ${urlsJson}, ${linked.access},353+ ${DateTime.formatIso(linked.linkedAt)}, ${DateTime.formatIso(linked.expiresAt)},354+ ${DateTime.formatIso(now)}, NULL355+ )356+ ON CONFLICT (environment_id) DO UPDATE SET357+ secret_name = excluded.secret_name,358+ label = excluded.label,359+ urls_json = excluded.urls_json,360+ access = excluded.access,361+ linked_at = excluded.linked_at,362+ expires_at = excluded.expires_at,363+ last_reached_at = excluded.last_reached_at,364+ last_error = NULL365+ `.pipe(Effect.catch(failStorage));@@ -0,0 +197,21 @@197+ ),198+ );199+ if (body.error !== undefined || body.result === undefined) {200+ return yield* new OrchestratorMcpFailure({201+ code: "invalid_request",202+ message: body.error?.message ?? "The linked environment returned no result.",203+ });204+ }205+ const text = body.result.content.map((part) => part.text ?? "").join("");206+ if (body.result.isError === true) {207+ // A refusal keeps the peer's own code, so the agent sees why it was refused.208+ const refused = decodeFailure(text);209+ return yield* refused._tag === "Some"210+ ? new OrchestratorMcpFailure({ code: refused.value.code, message: refused.value.message })211+ : new OrchestratorMcpFailure({212+ code: "orchestration_error",213+ message: text || "The linked environment refused the call.",214+ });215+ }216+ const success = Schema.fromJsonString(input.success);217+ return yield* Schema.decodeUnknownEffect(success)(text).pipe(
- @@ -132,3 +133,4 @@132133 [61, "PullRequestReviewGuides", Migration0061],133134 [62, "ThreadFailureLookupIndex", Migration0062],134135 [63, "DropUnusedV1Projections", Migration0063],136+ [64, "PeerLinks", Migration0064],
juliusmarminge assignedjuliusmarminge
juliusmarminge closed this
juliusmarminge reopened this
- @@ -0,0 +434,21 @@434+ }435+ const link = yield* toLink(row.value);436+ if (DateTime.isLessThanOrEqualTo(link.expiresAt, yield* DateTime.now)) {437+ return yield* new PeerLinkError({438+ reason: "expired",439+ message: `The link to ${link.label} expired. Link it again with a new pairing code from ${link.label}.`,440+ });441+ }442+ const stored = yield* secrets.get(row.value.secret_name).pipe(Effect.catch(failStorage));443+ if (Option.isNone(stored)) {444+ return yield* new PeerLinkError({445+ reason: "unknown_link",446+ message: `The link to ${link.label} lost its credential. Link it again.`,447+ });448+ }449+ // The token goes only to an address that proves it is this peer, so a450+ // reused LAN address or a moved hostname never receives it.451+ const url = yield* Effect.findFirst(link.urls, (candidate) =>452+ describe(candidate).pipe(453+ Effect.map(454+ (found) => Option.isSome(found) && found.value.environmentId === environmentId,
juliusmarminge added labelsagent-context-increase
juliusmarminge merged this4005759
juliusmarminge closed this
Sign in to join this conversation.
Thread transfer impact#
✅ Thread transfer remains within every enforced ceiling.
Baseline: unavailable · PR result:
fc99169· Source CI: successScenario and decoded snapshot size
10 historical turns, 5 command tools per turn, 878.9 KiB retained MCP result per historical turn, and a 1.05 MiB retained result in the measured turn.
Updated in place by a trusted workflow. PR artifacts are strictly validated and never executed.