Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix: make sdk webhooks locally work (#5325)

Wolf Mermelstein26f28348793d
diff --git a/infra/local/sdk-webhook-relay/Dockerfile b/infra/local/sdk-webhook-relay/Dockerfile
new file mode 100644
index 0000000000..b68055a34d
--- /dev/null
+++ b/infra/local/sdk-webhook-relay/Dockerfile
@@ -0,0 +1,21 @@
+FROM alpine:3.22
+
+RUN apk add --no-cache openssh-server \
+ && adduser -D -H -s /sbin/nologin sdk-webhook \
+ && passwd -d sdk-webhook \
+ && mkdir -p /etc/ssh/authorized_keys \
+ && chmod 755 /etc/ssh/authorized_keys
+
+RUN printf '%s\n' \
+ 'Port 22' \
+ 'PermitRootLogin no' \
+ 'PasswordAuthentication no' \
+ 'KbdInteractiveAuthentication no' \
+ 'PubkeyAuthentication yes' \
+ 'AuthorizedKeysFile /etc/ssh/authorized_keys/%u' \
+ 'AllowTcpForwarding remote' \
+ 'GatewayPorts clientspecified' \
+ 'PidFile /run/sshd.pid' \
+ > /etc/ssh/sshd_config
+
+CMD ["sh", "-c", "ssh-keygen -A && exec /usr/sbin/sshd -D -e"]
diff --git a/packages/sdk/justfile b/packages/sdk/justfile
index ac2c65399d..5bf672d7cf 100644
--- a/packages/sdk/justfile
+++ b/packages/sdk/justfile
@@ -1,5 +1,7 @@
# Macro SDK tasks.
+set positional-arguments
+
# Fully refresh all generated code: rebuild the OpenAPI specs from the Rust
# services (via apps/web's gen-api), copy them into ./specs, and regenerate
# ./generated with orval.
@@ -24,3 +26,8 @@ check:
coverage:
bun install
bun run coverage
+
+# Interactively create and verify a webhook. In `local` mode, register against
+# http://sdk-webhook-relay:8787/macro-events and run the receiver on the host.
+webhook *ARGS:
+ bun run webhook -- "$@"
diff --git a/packages/sdk/package.json b/packages/sdk/package.json
index 2a401bd6c9..082994cce7 100644
--- a/packages/sdk/package.json
+++ b/packages/sdk/package.json
@@ -23,6 +23,7 @@
},
"scripts": {
"sync-specs": "bun scripts/sync-specs.ts",
+ "webhook": "bun scripts/webhook.ts",
"validate-webhook": "bun scripts/validate-webhook.ts",
"coverage": "bun src/coverage/check.ts",
"generate": "openapi-ts",
diff --git a/packages/sdk/scripts/webhook.ts b/packages/sdk/scripts/webhook.ts
new file mode 100644
index 0000000000..0a4c73a322
--- /dev/null
+++ b/packages/sdk/scripts/webhook.ts
@@ -0,0 +1,158 @@
+import { parseArgs } from 'node:util';
+import type { Env } from '../src/config';
+import type { EventName } from '../src/events/types';
+import { resolveLocalPortmap } from '../src/local-portmap';
+import { Macro } from '../src/macro';
+
+const localEndpoint = 'http://sdk-webhook-relay:8787/macro-events';
+
+const { positionals, values } = parseArgs({
+ args: Bun.argv.slice(2),
+ allowPositionals: true,
+ options: {
+ env: { type: 'string' },
+ events: { type: 'string' },
+ help: { type: 'boolean', short: 'h' },
+ name: { type: 'string' },
+ port: { type: 'string' },
+ scope: { type: 'string' },
+ 'user-id': { type: 'string' },
+ url: { type: 'string' },
+ },
+ strict: true,
+});
+
+const [command, webhookId] = positionals;
+if (values.help || !command) {
+ printHelp();
+ process.exit(values.help ? 0 : 1);
+}
+
+switch (command) {
+ case 'register':
+ await register();
+ break;
+ case 'receive':
+ if (!webhookId) fail('usage: webhook receive <webhook-id>');
+ await receive(webhookId);
+ break;
+ default:
+ fail(`unknown webhook command: ${command}`);
+}
+
+async function register(): Promise<void> {
+ const env = parseEnv(values.env) ?? fail('--env is required');
+ const endpointUrl = required(values.url, '--url');
+ const name = required(values.name, '--name');
+ const events = parseEvents(values.events ?? fail('--events is required'));
+ const scope = values.scope ?? fail('--scope is required');
+ if (scope !== 'user' && scope !== 'team') fail('--scope must be user or team');
+ const userId =
+ scope === 'user'
+ ? required(values['user-id'], '--user-id')
+ : values['user-id'];
+
+ const macro = new Macro({ env, requestedAs: userId });
+ const webhook = await macro.webhooks.create({
+ url: endpointUrl,
+ name,
+ filters: [{ events }],
+ scope,
+ });
+ const secret = webhook.signingSecret ?? fail('webhook signing secret missing');
+
+ console.log(`
+Webhook registered.
+
+MACRO_WEBHOOK_ID=${webhook.id}
+MACRO_WEBHOOK_SECRET="${secret}"
+
+Start the event printer and validation receiver:
+MACRO_WEBHOOK_SECRET="${secret}" bun run webhook receive ${webhook.id} --env ${env}${userId ? ` --user-id "${userId}"` : ''}
+`);
+}
+
+async function receive(id: string): Promise<void> {
+ const env = parseEnv(values.env) ?? fail('--env is required');
+ const secret =
+ process.env.MACRO_WEBHOOK_SECRET ??
+ fail('MACRO_WEBHOOK_SECRET is required');
+ const port = Number(
+ values.port ?? resolveLocalPortmap()?.sdkWebhookHostReceiverPort ?? 8787,
+ );
+ const userId = values['user-id'];
+ const macro = new Macro({
+ env,
+ webhookSecret: secret,
+ requestedAs: userId,
+ });
+ const receiver = macro.events.webhook();
+
+ Bun.serve({
+ hostname: '0.0.0.0',
+ port,
+ fetch: async (request) => {
+ const bodyPromise = request.clone().text();
+ try {
+ const response = await receiver(request);
+ const event = request.headers.get('x-macro-event') ?? 'unknown';
+ console.log(`[${event}] ${await bodyPromise}`);
+ return response;
+ } catch (error) {
+ console.error('Webhook signature verification failed:', error);
+ return new Response('invalid signature', { status: 401 });
+ }
+ },
+ });
+ console.log(`Listening on 0.0.0.0:${port}; validating webhook ${id}...`);
+
+ const validation = await macro.webhooks.byId(id).validate();
+ if (validation.is_valid) {
+ console.log('Webhook verified. Waiting for deliveries.');
+ } else {
+ console.error(
+ `Validation failed: ${validation.message ?? 'delivery was not accepted'}`,
+ );
+ }
+}
+
+function printHelp(): void {
+ console.log(`
+Register a webhook or receive and print its events.
+
+ webhook register --env <dev|prod|local> --url <endpoint URL>
+ --name <webhook name> --events <event,event>
+ --scope <user|team> [--user-id <macro-user-id>]
+
+ webhook receive <webhook-id> --env <dev|prod|local>
+ [--port <port>] [--user-id <macro-user-id>]
+
+For just run_local, use ${localEndpoint} for --url. Run receive on the host
+with MACRO_WEBHOOK_SECRET set to the value printed by register.
+`);
+}
+
+function required(value: string | undefined, option: string): string {
+ if (value?.trim()) return value;
+ fail(`${option} is required`);
+}
+
+function parseEnv(value: string | undefined): Env | undefined {
+ if (value === undefined) return undefined;
+ if (value === 'dev' || value === 'prod' || value === 'local') return value;
+ fail('Macro environment must be dev, prod, or local');
+}
+
+function parseEvents(value: string): EventName[] {
+ const events = value
+ .split(',')
+ .map((event) => event.trim())
+ .filter(Boolean) as EventName[];
+ if (events.length === 0) fail('--events must contain at least one event');
+ return events;
+}
+
+function fail(message: string): never {
+ console.error(message);
+ process.exit(1);
+}
diff --git a/packages/sdk/src/local-portmap.ts b/packages/sdk/src/local-portmap.ts
new file mode 100644
index 0000000000..7224ec7b3d
--- /dev/null
+++ b/packages/sdk/src/local-portmap.ts
@@ -0,0 +1,40 @@
+import { execSync } from 'node:child_process';
+import { existsSync, readdirSync, readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import type { ServiceName } from './config';
+
+type LocalPortmap = {
+ webAppUrl: string;
+ hosts: Partial<Record<ServiceName, string>>;
+ sdkWebhookHostReceiverPort: number;
+};
+
+const portmapName = 'portmap.json';
+
+/** Load a generated local-stack port map, if one is available. */
+export function resolveLocalPortmap(): LocalPortmap | undefined {
+ const path = findPortmap();
+ if (!path) return undefined;
+
+ try {
+ return JSON.parse(readFileSync(path, 'utf8')) as LocalPortmap;
+ } catch (error) {
+ throw new Error(`failed to read Macro local port map ${path}`, {
+ cause: error,
+ });
+ }
+}
+
+function findPortmap(): string | undefined {
+ const root = execSync('git rev-parse --show-toplevel', {
+ encoding: 'utf8',
+ }).trim();
+ const generated = join(root, 'infra', 'local', 'generated');
+ if (!existsSync(generated)) return undefined;
+
+ for (const instance of readdirSync(generated)) {
+ const path = join(generated, instance, portmapName);
+ if (existsSync(path)) return path;
+ }
+ return undefined;
+}
diff --git a/packages/sdk/src/utils/client.ts b/packages/sdk/src/utils/client.ts
index c3ebc48cc2..5183dcc767 100644
--- a/packages/sdk/src/utils/client.ts
+++ b/packages/sdk/src/utils/client.ts
@@ -16,6 +16,7 @@ import {
WEB_APP_URLS,
} from '../config';
import { MacroEvents } from '../events/receiver';
+import { resolveLocalPortmap } from '../local-portmap';
export class MacroClient {
readonly auth: AuthSdk;
@@ -35,10 +36,16 @@ export class MacroClient {
constructor(opts: MacroOpts) {
const env: Env = opts.env ?? 'dev';
- const hosts = { ...HOSTS[env], ...opts.hosts };
+ const localPortmap =
+ env === 'local' ? resolveLocalPortmap() : undefined;
+ const hosts = { ...HOSTS[env], ...localPortmap?.hosts, ...opts.hosts };
const envWebUrl =
typeof process !== 'undefined' ? process.env.MACRO_WEB_URL : undefined;
- this.webAppUrl = opts.webAppUrl ?? envWebUrl ?? WEB_APP_URLS[env];
+ this.webAppUrl =
+ opts.webAppUrl ??
+ envWebUrl ??
+ localPortmap?.webAppUrl ??
+ WEB_APP_URLS[env];
this.authConfig = resolveAuth(opts);
this.requestedAs = opts.requestedAs;
if (this.requestedAs && this.authConfig.type !== 'bot') {
diff --git a/tooling/xtask/crates/xtask_local/src/local/gen_compose.rs b/tooling/xtask/crates/xtask_local/src/local/gen_compose.rs
index fabcb1ce5c..3184ada27e 100644
--- a/tooling/xtask/crates/xtask_local/src/local/gen_compose.rs
+++ b/tooling/xtask/crates/xtask_local/src/local/gen_compose.rs
@@ -29,6 +29,7 @@ use super::{Mode, repo_root};
pub const LOCALSTACK_IMAGE: &str = "localstack/localstack:4";
pub const MAILPIT_IMAGE: &str = "axllent/mailpit:v1.20";
pub const CADDY_IMAGE: &str = "caddy:2-alpine";
+pub const SDK_WEBHOOK_RELAY_IMAGE: &str = "macro-sdk-webhook-relay:dev";
/// Base-compose services that bind fixed host ports but aren't in our inventory
/// (reached via the proxy / container network, not the host). For named
@@ -96,6 +97,7 @@ pub fn generate(
// Redis/OpenSearch port remaps) only for the self-contained local stacks.
if mode.spec().runs_local_infra {
add_local_infra(&mut services, instance, static_frontend);
+ add_sdk_webhook_relay(&mut services, instance)?;
}
// Live Gmail sync: forward watch notifications from the instance's own
// Pub/Sub subscription to the email service's webhook. Per-instance
@@ -161,6 +163,41 @@ pub fn generate(
Ok(path)
}
+fn add_sdk_webhook_relay(
+ services: &mut IndexMap<String, Option<dct::Service>>,
+ instance: &Instance,
+) -> Result<()> {
+ super::sdk_webhook::ensure_keys(instance)?;
+ let build = dct::BuildStep::Advanced(dct::AdvancedBuildStep {
+ context: repo_root()
+ .join("infra/local/sdk-webhook-relay")
+ .display()
+ .to_string(),
+ ..Default::default()
+ });
+ services.insert(
+ "sdk-webhook-relay".to_string(),
+ Some(dct::Service {
+ image: Some(SDK_WEBHOOK_RELAY_IMAGE.to_string()),
+ build_: Some(build),
+ ports: dct::Ports::Short(vec![format!(
+ "127.0.0.1:{}:22",
+ super::sdk_webhook::ssh_port(instance)
+ )]),
+ volumes: vec![dct::Volumes::Simple(format!(
+ "{}:/etc/ssh/authorized_keys/{}:ro",
+ super::sdk_webhook::key_dir(instance)
+ .join("id_ed25519.pub")
+ .display(),
+ "sdk-webhook"
+ ))],
+ networks: net_aliases(&[("services", &["sdk-webhook-relay"])]),
+ ..Default::default()
+ }),
+ );
+ Ok(())
+}
+
/// LocalStack (S3/SQS/DynamoDB), reachable as `localstack` on both networks.
/// Used by local AND dev — dev's `dev_personal` notification queue lives here.
fn add_localstack_service(
diff --git a/tooling/xtask/crates/xtask_local/src/local/instance.rs b/tooling/xtask/crates/xtask_local/src/local/instance.rs
index ef5508877d..3c69f29f45 100644
--- a/tooling/xtask/crates/xtask_local/src/local/instance.rs
+++ b/tooling/xtask/crates/xtask_local/src/local/instance.rs
@@ -94,6 +94,8 @@ pub enum Port {
Unfurl = 8095,
ImageProxy = 8097,
Kafka = 9092,
+ SdkWebhookSsh = 8788,
+ SdkWebhookHostReceiver = 8789,
}
impl Port {
diff --git a/tooling/xtask/crates/xtask_local/src/local/instance/test.rs b/tooling/xtask/crates/xtask_local/src/local/instance/test.rs
index 49ce841381..5c269aa2e6 100644
--- a/tooling/xtask/crates/xtask_local/src/local/instance/test.rs
+++ b/tooling/xtask/crates/xtask_local/src/local/instance/test.rs
@@ -28,6 +28,7 @@ fn default_instance_uses_fixed_ports() {
assert_eq!(inst.port(Port::Postgres), 5432);
assert_eq!(inst.port(Port::Auth), 8080);
assert_eq!(inst.port(Port::DocStorage), 8086);
+ assert_eq!(inst.port(Port::SdkWebhookSsh), 8788);
assert_eq!(inst.network_databases(), "databases");
assert_eq!(inst.volume_postgres(), "macro_postgres_data");
}
@@ -43,6 +44,10 @@ fn named_instance_is_isolated_and_deterministic() {
);
assert_eq!(a1.project_name(), "macro-agent-a");
assert!(a1.port(Port::Postgres) >= 20_000);
+ assert_eq!(
+ a1.port(Port::SdkWebhookSsh),
+ a1.port_base() + Port::SdkWebhookSsh.offset()
+ );
assert_eq!(a1.network_databases(), "databases-agent-a");
assert_eq!(a1.volume_postgres(), "macro_postgres_data_agent-a");
}
diff --git a/tooling/xtask/crates/xtask_local/src/local/mod.rs b/tooling/xtask/crates/xtask_local/src/local/mod.rs
index 27151fc67f..cdbcfd1dcf 100644
--- a/tooling/xtask/crates/xtask_local/src/local/mod.rs
+++ b/tooling/xtask/crates/xtask_local/src/local/mod.rs
@@ -33,8 +33,10 @@ pub mod local_env;
pub mod localstack;
pub mod mailpit;
pub mod opensearch;
+pub mod portmap;
pub mod proxy;
pub mod resources;
+pub mod sdk_webhook;
pub mod seed_env;
pub mod snapshot;
pub mod stack;
@@ -233,6 +235,9 @@ pub fn run_stack(mode: Mode, args: &cli::RunArgs) -> Result<()> {
// DynamoDB/OpenSearch connection refused).
bring_up_infra(&stage, mode, &instance, &env, InfraInit::Full)?;
bring_up_app(&stage, mode, &instance, &env)?;
+ let _sdk_webhook_tunnel = (mode == Mode::Local && !stage.is_dry_run())
+ .then(|| sdk_webhook::start(&instance))
+ .transpose()?;
// No restart-to-reload step: the teardown means `up` always creates fresh
// containers, which start on the just-built binaries bind-mounted at
@@ -501,6 +506,9 @@ fn prepare(
.is_some_and(|key| !key.trim().is_empty());
gen_compose::generate(mode, instance, &binaries, static_frontend, gmail_forwarder)?;
proxy::write_caddyfile(instance, mode, static_frontend)?;
+ if mode == Mode::Local {
+ portmap::write(instance)?;
+ }
if mode.spec().runs_local_infra {
let google = kickstart::GoogleIdp::from_env(&env.merged);
fusionauth::write_kickstart(instance, google.as_ref())?;
@@ -813,6 +821,7 @@ fn instance_networks(instance: &Instance) -> [String; 2] {
/// is best-effort and noisy) so callers surface it as a single line; absent
/// containers/volumes are ignored.
fn teardown_commands(instance: &Instance) {
+ sdk_webhook::stop(instance);
let project = instance.project_name();
// `-t 0`: SIGKILL immediately, no graceful-shutdown grace. The default 10s
// SIGTERM timeout per container (Postgres' smart shutdown, OpenSearch, …)
@@ -911,6 +920,7 @@ pub fn gen_compose_only(args: &cli::InstanceArgs) -> Result<()> {
pub fn stop(args: &cli::InstanceArgs) -> Result<()> {
let stage = Stage::from_env();
let instance = Instance::derive(args.instance.as_deref(), args.port_base)?;
+ sdk_webhook::stop(&instance);
let mut cmd = Command::new("docker");
cmd.args(["compose", "-p", instance.project_name(), "stop"]);
stage.run(&format!("Stopping {}", instance.project_name()), &mut cmd)
diff --git a/tooling/xtask/crates/xtask_local/src/local/portmap.rs b/tooling/xtask/crates/xtask_local/src/local/portmap.rs
new file mode 100644
index 0000000000..e308284da2
--- /dev/null
+++ b/tooling/xtask/crates/xtask_local/src/local/portmap.rs
@@ -0,0 +1,47 @@
+//! Writes the direct local service endpoints consumed by the TypeScript SDK.
+
+use std::collections::BTreeMap;
+use std::path::PathBuf;
+
+use anyhow::{Context, Result};
+use serde::Serialize;
+
+use super::instance::{Instance, Port};
+
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+struct PortMap {
+ instance: String,
+ web_app_url: String,
+ hosts: BTreeMap<&'static str, String>,
+ sdk_webhook_host_receiver_port: u16,
+}
+
+/// Write the direct host-port endpoints for a local stack instance.
+pub fn write(instance: &Instance) -> Result<PathBuf> {
+ let url = |port| format!("http://localhost:{}", instance.port(port));
+ let hosts = BTreeMap::from([
+ ("auth", url(Port::Auth)),
+ ("cognition", url(Port::DocCognition)),
+ ("connection", url(Port::ConnGateway)),
+ ("contacts", url(Port::Contacts)),
+ ("email", url(Port::Email)),
+ ("notification", url(Port::Notification)),
+ ("properties", url(Port::DocStorage)),
+ ("search", url(Port::DocStorage)),
+ ("static-files", url(Port::StaticFile)),
+ ("storage", url(Port::DocStorage)),
+ ("unfurl", url(Port::Unfurl)),
+ ]);
+ let portmap = PortMap {
+ instance: instance.name().to_string(),
+ web_app_url: url(Port::Frontend),
+ hosts,
+ sdk_webhook_host_receiver_port: super::sdk_webhook::host_receiver_port(instance),
+ };
+ let path = instance.ensure_artifact_dir()?.join("portmap.json");
+ let contents = serde_json::to_string_pretty(&portmap).context("serializing port map")?;
+ std::fs::write(&path, format!("{contents}\n"))
+ .with_context(|| format!("writing {}", path.display()))?;
+ Ok(path)
+}
diff --git a/tooling/xtask/crates/xtask_local/src/local/sdk_webhook.rs b/tooling/xtask/crates/xtask_local/src/local/sdk_webhook.rs
new file mode 100644
index 0000000000..14b431e74d
--- /dev/null
+++ b/tooling/xtask/crates/xtask_local/src/local/sdk_webhook.rs
@@ -0,0 +1,119 @@
+//! Instance-local relay for SDK webhook receivers running on the host.
+
+use std::path::PathBuf;
+use std::process::{Child, Command, Stdio};
+use std::time::Duration;
+
+use anyhow::{Context, Result, bail};
+
+use super::instance::{Instance, Port};
+
+const RELAY_PORT: u16 = 8787;
+const USER: &str = "sdk-webhook";
+
+pub fn relay_url() -> &'static str {
+ "http://sdk-webhook-relay:8787/macro-events"
+}
+
+pub fn ssh_port(instance: &Instance) -> u16 {
+ instance.port(Port::SdkWebhookSsh)
+}
+
+pub fn host_receiver_port(instance: &Instance) -> u16 {
+ instance.port(Port::SdkWebhookHostReceiver)
+}
+
+pub fn key_dir(instance: &Instance) -> PathBuf {
+ instance.artifact_dir().join("sdk-webhook")
+}
+
+fn private_key(instance: &Instance) -> PathBuf {
+ key_dir(instance).join("id_ed25519")
+}
+
+fn public_key(instance: &Instance) -> PathBuf {
+ key_dir(instance).join("id_ed25519.pub")
+}
+
+fn pid_path(instance: &Instance) -> PathBuf {
+ key_dir(instance).join("tunnel.pid")
+}
+
+/// Create the per-instance client key pair used by the relay container.
+pub fn ensure_keys(instance: &Instance) -> Result<()> {
+ let dir = key_dir(instance);
+ std::fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?;
+ if private_key(instance).is_file() && public_key(instance).is_file() {
+ return Ok(());
+ }
+ let status = Command::new("ssh-keygen")
+ .args(["-q", "-t", "ed25519", "-N", "", "-f"])
+ .arg(private_key(instance))
+ .status()
+ .context("running ssh-keygen for the SDK webhook relay")?;
+ if !status.success() {
+ bail!("ssh-keygen failed for the SDK webhook relay");
+ }
+ Ok(())
+}
+
+/// Start the host-side reverse tunnel after the relay container is running.
+pub fn start(instance: &Instance) -> Result<Child> {
+ ensure_keys(instance)?;
+ stop(instance);
+ let mut child = Command::new("ssh")
+ .args([
+ "-N",
+ "-T",
+ "-o",
+ "ExitOnForwardFailure=yes",
+ "-o",
+ "StrictHostKeyChecking=no",
+ "-o",
+ "UserKnownHostsFile=/dev/null",
+ "-o",
+ "ConnectTimeout=2",
+ "-o",
+ "ServerAliveInterval=15",
+ "-o",
+ "ServerAliveCountMax=3",
+ "-i",
+ ])
+ .arg(private_key(instance))
+ .args(["-p"])
+ .arg(ssh_port(instance).to_string())
+ .args([
+ "-R",
+ &format!(
+ "0.0.0.0:{RELAY_PORT}:127.0.0.1:{}",
+ host_receiver_port(instance)
+ ),
+ ])
+ .arg(format!("{USER}@127.0.0.1"))
+ .stdout(Stdio::null())
+ .stderr(Stdio::null())
+ .spawn()
+ .context("starting the SDK webhook SSH reverse tunnel")?;
+
+ std::thread::sleep(Duration::from_millis(300));
+ if let Some(status) = child.try_wait()? {
+ bail!("SDK webhook SSH reverse tunnel exited with {status}");
+ }
+ std::fs::write(pid_path(instance), child.id().to_string())?;
+ Ok(child)
+}
+
+/// Stop a previously started host-side tunnel, if present.
+pub fn stop(instance: &Instance) {
+ let path = pid_path(instance);
+ let Some(pid) = std::fs::read_to_string(&path)
+ .ok()
+ .and_then(|p| p.trim().parse::<i32>().ok())
+ else {
+ return;
+ };
+ let _ = Command::new("kill")
+ .args(["-TERM", &pid.to_string()])
+ .status();
+ let _ = std::fs::remove_file(path);
+}
diff --git a/tooling/xtask/crates/xtask_local/src/local/stack.rs b/tooling/xtask/crates/xtask_local/src/local/stack.rs
index edf3f9379c..5e445c3ee6 100644
--- a/tooling/xtask/crates/xtask_local/src/local/stack.rs
+++ b/tooling/xtask/crates/xtask_local/src/local/stack.rs
@@ -24,7 +24,7 @@ use serde_json::json;
use super::cli::{EnvArgs, InstanceArgs, RunArgs};
use super::instance::{Instance, Port};
use super::stage::Stage;
-use super::{Mode, arch, env_layer, frontend, mailpit, proxy, snapshot, summary};
+use super::{Mode, arch, env_layer, frontend, mailpit, proxy, sdk_webhook, snapshot, summary};
#[derive(Args, Clone, Default)]
pub struct UpArgs {
@@ -262,6 +262,9 @@ pub fn up(mode: Mode, args: &UpArgs) -> Result<Instance> {
return Ok(instance);
}
super::bring_up_app(&stage, mode, &instance, &env)?;
+ let _sdk_webhook_tunnel = (mode == Mode::Local && !stage.is_dry_run())
+ .then(|| sdk_webhook::start(&instance))
+ .transpose()?;
// Headless "ready" means the backend answers through the proxy — the caller
// (a CI step, an agent) acts on the URL the moment we return.
diff --git a/tooling/xtask/crates/xtask_local/src/local/summary.rs b/tooling/xtask/crates/xtask_local/src/local/summary.rs
index 902963913b..201eb54625 100644
--- a/tooling/xtask/crates/xtask_local/src/local/summary.rs
+++ b/tooling/xtask/crates/xtask_local/src/local/summary.rs
@@ -6,7 +6,7 @@ use console::Style;
use super::env_layer::ResolvedEnv;
use super::instance::{Instance, Port};
-use super::{Mode, frontend, mailpit, proxy};
+use super::{Mode, frontend, mailpit, proxy, sdk_webhook};
/// The host-facing endpoints of an instance: (label, url, host port).
/// Shared by the startup summary and `status-local`.
@@ -136,6 +136,17 @@ pub fn print(
.unwrap_or_else(|| "(none)".into()),
);
row("generated env", env.generated_path.display().to_string());
+ if mode == Mode::Local {
+ row(
+ "SDK config",
+ instance
+ .artifact_dir()
+ .join("portmap.json")
+ .display()
+ .to_string(),
+ );
+ row("Receive webhooks at", sdk_webhook::relay_url().to_string());
+ }
// The frontend and mailpit rows come from the caller (they differ by
// flow); the rest of the endpoint list is shared with `status-local`.
for (label, url, _port) in endpoint_rows(instance) {