deer-flow/scripts/serve.sh
Nan Gao c542185a7f
feat(extensions): add gateway contribution points and packaged extension management (#4780)
* feat(extensions): add gateway services and routers

* feat(extensions): add standalone reference extension

* fix(extensions): harden contributed gateway routes

* docs(extensions): document gateway contribution points

* feat(extensions): add operator CLI for packaged extension management

Add `deerflow extensions install/list/enable/disable/remove` plus the root
`make extension-*` wrappers, backed by an `ExtensionManager` that owns one
transaction over backend/pyproject.toml, backend/uv.lock, the managed source
snapshot, the uv environment, and the `plugins:` block in config.yaml.

Install accepts a package requirement, a public HTTPS Git URL, or a local
directory. Local directories are copied to backend/extensions/sources/ as
deployable snapshots rather than editable installs, and the root .dockerignore
re-includes that tree so snapshots reach the backend builder. Remote sources are
HTTPS-only; SSH Git, file:// and local wheels are rejected because the stock
Docker builder cannot reproduce them.

Because environment configuration can still resolve a plain package name to a
local wheel (a UV_FIND_LINKS wheelhouse, say), every uv add/remove is followed
by an audit of the new lock: any local reference the stock image build cannot
reproduce rolls back the whole transaction. A config carrying duplicate
top-level `plugins:` keys is rejected outright rather than managed against one
block while the Gateway reads another.

Dependency synchronization now has one lock authority. The `extensions`
dependency group joins [tool.uv].default-groups, every startup path syncs the
same lock with --locked and launches with --no-sync, and the Docker images move
to uv 0.11.1 for the --no-workspace boundary the manager needs.

Loader gains `enabled`, `name` and `package` fields so a disabled extension is
skipped before resolution and import.

Co-authored-by: Codex <codex@openai.com>

* fix(extensions): stop the managed plugins rewrite from destroying config

Two data-safety defects in the managed `plugins:` block writer.

The "next top-level key" boundary was a regex matching only
`[A-Za-z_][A-Za-z0-9_-]*` or a quoted key. `AppConfig` is `extra="allow"`, so a
config may legally carry any top-level key, and a key the pattern cannot
recognize did not fail loudly — it read as "no next section", and the rewrite
replaced that neighbour and its entire subtree with the managed block. `my.key`,
`2fa`, `$schema`, `my key` and non-ASCII keys were all silently deleted by a
plain `extension-enable`/`disable`. Both boundaries now come from the YAML
parser's node marks, so key shape is irrelevant.

The file-final branch never consulted the trailing-comment scan the has-next-key
branch used, so any comment below the block was dropped. Since the manager
appends `plugins:` at end of file, that is the steady-state shape for most
installs: an operator note below the block was destroyed on the next toggle.

Separately, every managed install wrote `required: true` while the loader
defaults to false. That turned any later load failure — broken wheel, missing
native library, deleted snapshot — into a Gateway startup abort recoverable only
with shell access. New records are now written `required: false`, with an
explicit `install --required` opt-in; adopting an existing hand-written record
still preserves the operator's own choice.

* fix(extensions): harden the manager transaction and correct its docs

Follow-up hardening on the extension package manager.

Security posture, which the docs already claimed:
- Scrub `UV_PYTHON`, `UV_INSECURE_HOST`, `UV_CONSTRAINT` and
  `UV_NO_BUILD_ISOLATION` from the controlled uv environment. `UV_PYTHON` swaps
  the interpreter that the entry-point probe then imports and calls, and every
  later `uv run --no-sync` startup uses; `UV_INSECURE_HOST` removes the TLS
  validation the HTTPS-only source rule depends on. Neither is an index, proxy,
  cache or credential-provider setting, so neither was covered by the carve-out.
- Recognize run-together and all-caps secret query parameters (`accesstoken`,
  `ACCESSTOKEN`, `key`, `pw`, `sas`, `code`). The camel-case splitter only fires
  on case transitions, so only the separated spellings were caught. Short
  generic words stay boundary-anchored, so `?keyword=` remains installable.
- Validate the config before running any uv command. `uv add`/`uv sync` execute
  the package's build backend, so a config the manager could never write to must
  fail before that code runs rather than afterwards through rollback.

Transaction integrity:
- Run the second dependency-file restore from a `finally`. The recovery sync
  runs without `--locked` when the checkout had no lock, so uv writes one while
  resolving; if that sync then failed, the restore was skipped and the operator
  kept a lock file they never had. A failing recovery sync now also reports the
  original failure instead of replacing it.
- Skip the recovery sync on cancellation. Answering Ctrl-C with a full
  dependency resolve invites a second interrupt that escapes the handler and
  strands the checkout mid-transaction; the declarations are already restored
  and the next locked startup sync reconciles the environment.
- Retry a non-blocking lock on Windows instead of using `msvcrt.LK_LOCK`, which
  gives up after ~10s — far shorter than a real `uv add` plus `uv sync`, so
  contention surfaced as `Permission denied` rather than serializing.
- Locate the entry-point probe's JSON payload instead of parsing stdout's first
  line, so a `sitecustomize`/`.pth` banner cannot roll back a good install.
- Warn when the lock records a loopback source. `127.0.0.1` inside the image
  builder is a different machine, but unlike an environment-driven wheelhouse
  resolution this is a source the operator typed deliberately, so it is reported
  rather than rolled back. Private-network indexes are untouched: a builder on
  that network can reach them.

Docs: the blanket claim that failed operations restore the config file was
wrong — the conflict branches deliberately preserve a concurrent external edit
and leave `remove` deactivated. Document that, the `required: false` default,
the config preflight, the interrupt behaviour, and where the plugins-block
boundaries come from.

* test(gateway): pin the request-path projection agreement

`get_request_route_path()` imports the private
`starlette._utils.get_route_path` so the auth and CSRF predicates classify
the exact string Starlette's router matches on. Its requirement is not
"strip root_path correctly" but "return what the dispatcher is matching",
so delegating to the router's own implementation keeps the two in lockstep
by construction. Keep the private import rather than vendoring a copy: an
import that disappears fails loudly at startup, while a stale copy diverges
silently at a security boundary.

Cover the property directly instead of the mechanism, so the tests survive
a future reimplementation:

- projection edge cases, including the segment-boundary guard that keeps
  root_path="/api" from slicing "/apifoo/models" into a string the router
  would never match
- agreement with the router under nested mounts
- the two bypasses these predicates exist to prevent: a protected route
  mounted under the "/health" public prefix must still 401, and a POST
  mounted under "/api/webhooks" must still require a CSRF token

Both are verified to fail when the projection is reverted to
`request.url.path` (9/13 red) and when a plausible vendored copy omits the
boundary guard (the 2 boundary cases red).

Declare starlette as a bounded direct dependency so a bump — which is
security-relevant here — shows up in review rather than arriving silently
through FastAPI.

* ci: pin uv to the version production ships

ExtensionManager is not a consumer of uv the build tool -- it is a program
whose whole job is driving `uv` as a subprocess, depending on its CLI
behavior (`--no-workspace`, `--no-sync`, what `uv add` writes into
`[dependency-groups] extensions`) and on the `uv.lock` serialization format.
uv is closer to a runtime dependency with a contract than to incidental
tooling.

backend/Dockerfile pins that binary to 0.11.1, but all eight
astral-sh/setup-uv steps installed whatever was latest at run time, so CI
exercised the manager against a uv that is not the uv production runs. The
sharpest failure that allows: a newer uv bumps uv.lock's `revision`, CI
stays green because the same uv reads back what it wrote, and the pinned uv
in the production image cannot read the committed lock. `uv lock --check`
is version-sensitive for the same reason -- it verifies the lock is what
*this* uv would produce, and two versions can emit equivalent but
non-identical output.

Pin every step to 0.11.1 and lift the one lingering setup-uv@v3 to v7 so
the steps share input and caching behavior.

Pinning alone drifts apart again on the next bump, so add a constraint test
in the style of test_compose_default_bind_host.py: the Dockerfile's
UV_IMAGE tag is the single source of truth, and both compose defaults plus
every setup-uv step must match it. Verified to fail when a pin drifts, when
a step omits `version`, and -- the real scenario -- when the Dockerfile is
bumped alone, which lights up the workflows and both compose files at once.

* fix(gateway): state the extension route auth limit and abort a failed dev sync

Two scoped review follow-ups.

README: contributed routers cannot enter the host's reserved public prefixes,
which makes every extension endpoint session-authenticated -- there is no way
to expose an unauthenticated route. The rejection rule was documented but its
consequence was not, so inbound provider webhooks and public status endpoints
read as merely undocumented rather than out of scope for this release.

docker/dev-entrypoint.sh: the self-heal retry reuses `--locked`, so it repairs
a corrupt .venv but never a lock that disagrees with pyproject.toml. `set -e`
already stopped the script there -- uvicorn was not being started against a
stale environment -- but it exited on a bare uv exit code with no indication of
what to do. Abort explicitly with the cause and the fix.

Tests slice the sync block out of the real script and run it against a stub uv,
so they exercise the shipped code rather than a copy of it (/app/backend only
exists inside the container). They cover the success path, the retry that
recovers, the abort, and the guidance. Verified against the pre-fix script:
only the guidance case goes red, confirming the abort itself was already
correct.

* fix(extensions): point Git SSH shorthand at the HTTPS correction

Git's SCP-like shorthand carries no URL scheme, so `git+git@host:org/repo.git`
reached the scheme rules looking like a bare path and was rejected with
"local path references are not deployable; pass a local directory so DeerFlow
can snapshot it". The operator asked for a remote source, so that guidance
points at the wrong fix. Detect the shorthand ahead of the scheme rules and
report the public-HTTPS correction instead.

The bare `git@host:org/repo.git` spelling took a different wrong turn: packaging
parses it as a direct reference named `git`, leaving `host:org/repo.git`, whose
`host` reads as a URL scheme and produced the generic HTTPS message. Both
spellings now share one message, as does the PEP 508 named form.

* docs: keep the root extension summary within its new budget

#4799 split the depth out of the module guides and added a size gate; the root
file's job is now orientation, and this branch had pushed it 192 bytes past the
soft limit. The manager transaction, source rules, and lock discipline are
already stated in full in the extensions guide, so the root keeps the one-line
orientation and points there instead of restating them.

---------

Co-authored-by: Codex <codex@openai.com>
2026-08-13 23:55:30 +08:00

504 lines
18 KiB
Bash
Executable File

#!/usr/bin/env bash
#
# serve.sh — Unified DeerFlow service launcher
#
# Usage:
# ./scripts/serve.sh [--dev|--prod] [--daemon] [--stop|--restart]
#
# Modes:
# --dev Development mode with hot-reload (default)
# --prod Production mode, pre-built frontend, no hot-reload
# --daemon Run all services in background (nohup), exit after startup
#
# Actions:
# --skip-install Skip dependency installation (faster restart)
# --stop Stop all running services and exit
# --restart Stop all services, then start with the given mode flags
#
# Examples:
# ./scripts/serve.sh --dev # Gateway dev, hot reload
# ./scripts/serve.sh --prod # Gateway prod
# ./scripts/serve.sh --dev --daemon # Gateway dev, background
# ./scripts/serve.sh --stop # Stop all services
# ./scripts/serve.sh --restart --dev # Restart dev services
#
# Must be run from the repo root directory.
set -e
REPO_ROOT="$(builtin cd "$(dirname "${BASH_SOURCE[0]}")/.." >/dev/null 2>&1 && pwd -P)"
cd "$REPO_ROOT"
# ── Load .env ────────────────────────────────────────────────────────────────
if [ -f "$REPO_ROOT/.env" ]; then
set -a
source "$REPO_ROOT/.env"
set +a
fi
_pick_python() {
local candidate
for candidate in python3 python py; do
if command -v "$candidate" >/dev/null 2>&1 && "$candidate" -c 'import sys; raise SystemExit(0 if sys.version_info.major >= 3 else 1)' >/dev/null 2>&1; then
printf '%s\n' "$candidate"
return 0
fi
done
return 1
}
# ── Argument parsing ─────────────────────────────────────────────────────────
DEV_MODE=true
DAEMON_MODE=false
SKIP_INSTALL=false
ACTION="start" # start | stop | restart
for arg in "$@"; do
case "$arg" in
--dev) DEV_MODE=true ;;
--prod) DEV_MODE=false ;;
--daemon) DAEMON_MODE=true ;;
--skip-install) SKIP_INSTALL=true ;;
--stop) ACTION="stop" ;;
--restart) ACTION="restart" ;;
*)
echo "Unknown argument: $arg"
echo "Usage: $0 [--dev|--prod] [--daemon] [--skip-install] [--stop|--restart]"
exit 1
;;
esac
done
# ── Stop helper ──────────────────────────────────────────────────────────────
# Every deer-flow worktree (the main checkout + each linked worktree) hardcodes
# the same dev ports (8001/3000/2026), so a service started from ANY of them
# must be reclaimable from here — otherwise `make stop`/`make dev` in this
# worktree can neither kill nor take over a port held by a sibling worktree.
# DEERFLOW_ROOTS is that set of roots; processes living outside all of them
# (e.g. an unrelated project on port 3000) are still never touched.
# Sorted most-specific-first (longest path first): a linked worktree lives
# under the main checkout, so both roots are substrings of its files — checking
# the deeper root first attributes a reclaimed port to the right worktree.
DEERFLOW_ROOTS="$(
{
printf '%s\n' "$REPO_ROOT"
git -C "$REPO_ROOT" worktree list --porcelain 2>/dev/null |
awk '/^worktree /{print $2}'
} | awk 'NF && !seen[$0]++ {print length($0)"\t"$0}' | sort -rn | sed 's/^[0-9]*\t//'
)"
# True if PID has an open file/cwd under any deer-flow worktree root. The
# trailing slash keeps a sibling dir like ".../deer-flow-notes" from matching
# the ".../deer-flow" root.
_is_deerflow_pid() {
local pid=$1 files root
# Daemon children inherit DEERFLOW_DAEMON_ROOT from run_service. Checking
# it (Linux only — macOS has no /proc) identifies processes like
# next-server that lsof misses, so the name/port reaps in stop_all can
# claim them.
if [ -r "/proc/$pid/environ" ] &&
tr '\0' '\n' < "/proc/$pid/environ" 2>/dev/null | grep -Fxq "DEERFLOW_DAEMON_ROOT=$REPO_ROOT"; then
return 0
fi
files=$(lsof -b -w -p "$pid" 2>/dev/null) || return 1
while IFS= read -r root; do
[ -n "$root" ] || continue
case "$files" in
*"$root"/*) return 0 ;;
esac
done <<< "$DEERFLOW_ROOTS"
return 1
}
# Report ports about to be reclaimed from a *different* worktree, so stopping
# (or starting, which stops first) isn't silently killing someone else's run.
_report_reclaimed_ports() {
local port pid files root owner
for port in 8001 3000 2026; do
for pid in $(lsof -nP -iTCP:"$port" -sTCP:LISTEN -t 2>/dev/null); do
_is_deerflow_pid "$pid" || continue
files=$(lsof -b -w -p "$pid" 2>/dev/null)
case "$files" in *"$REPO_ROOT"/*) continue ;; esac # this worktree — normal
owner=""
while IFS= read -r root; do
[ -n "$root" ] || continue
case "$files" in *"$root"/*) owner="$root"; break ;; esac
done <<< "$DEERFLOW_ROOTS"
echo " ↻ Reclaiming port $port from another worktree: ${owner:-?}"
break
done
done
}
_kill_repo_processes() {
local pattern=$1
local pid
local pids=""
while IFS= read -r pid; do
if [ -n "$pid" ] && _is_deerflow_pid "$pid"; then
case " $pids " in
*" $pid "*) ;;
*) pids="$pids $pid" ;;
esac
fi
done < <(pgrep -f "$pattern" 2>/dev/null || true)
if [ -n "$pids" ]; then
kill $pids 2>/dev/null || true
fi
}
_kill_repo_port() {
local port=$1
local pid
local pids=""
while IFS= read -r pid; do
if [ -n "$pid" ] && _is_deerflow_pid "$pid"; then
case " $pids " in
*" $pid "*) ;;
*) pids="$pids $pid" ;;
esac
fi
done < <(lsof -nP -iTCP:"$port" -sTCP:LISTEN -t 2>/dev/null || true)
if [ -n "$pids" ]; then
kill -9 $pids 2>/dev/null || true
fi
}
_is_port_listening() {
local port=$1
if command -v lsof >/dev/null 2>&1; then
if lsof -nP -iTCP:"$port" -sTCP:LISTEN -t >/dev/null 2>&1; then
return 0
fi
fi
if command -v ss >/dev/null 2>&1; then
if ss -ltn "( sport = :$port )" 2>/dev/null | tail -n +2 | grep -q .; then
return 0
fi
fi
if command -v netstat >/dev/null 2>&1; then
if netstat -ltn 2>/dev/null | awk '{print $4}' | grep -Eq "(^|[.:])${port}$"; then
return 0
fi
fi
return 1
}
_is_repo_nginx_pid() {
local pid=$1
local command
local args
command=$(ps -p "$pid" -o comm= 2>/dev/null) || return 1
# nginx rewrites argv[0] for master/worker processes. On macOS,
# `ps -o comm=` can report that rewritten form instead of the binary name.
case "$command" in
nginx|*/nginx|nginx:*) ;;
*) return 1 ;;
esac
args=$(ps -p "$pid" -o args= 2>/dev/null) || return 1
local root
while IFS= read -r root; do
[ -n "$root" ] || continue
case "$args" in
*"$root"/docker/nginx/nginx.local.conf*|*"$root"/*) return 0 ;;
esac
done <<< "$DEERFLOW_ROOTS"
_is_deerflow_pid "$pid"
}
_kill_repo_nginx() {
local pid
local pids=""
if [ -f "$REPO_ROOT/logs/nginx.pid" ]; then
read -r pid < "$REPO_ROOT/logs/nginx.pid" || true
if [ -n "$pid" ] && _is_repo_nginx_pid "$pid"; then
pids="$pids $pid"
fi
fi
while IFS= read -r pid; do
if [ -n "$pid" ] && _is_repo_nginx_pid "$pid"; then
case " $pids " in
*" $pid "*) ;;
*) pids="$pids $pid" ;;
esac
fi
done < <(pgrep -f nginx 2>/dev/null || true)
if [ -n "$pids" ]; then
kill -9 $pids 2>/dev/null || true
fi
}
stop_all() {
echo "Stopping all services..."
_report_reclaimed_ports
_kill_repo_processes "uvicorn app.gateway.app:app"
_kill_repo_processes "next dev"
_kill_repo_processes "next start"
_kill_repo_processes "next-server"
nginx -c "$REPO_ROOT/docker/nginx/nginx.local.conf" -p "$REPO_ROOT" -s quit 2>/dev/null || true
sleep 1
_kill_repo_nginx
# Force-kill any survivors still holding the service ports. 2026 is included
# so a lingering nginx (or any deer-flow process) that _kill_repo_nginx did
# not match by name still gets reclaimed — otherwise `make dev` fails its
# nginx port preflight.
_kill_repo_port 8001
_kill_repo_port 3000
_kill_repo_port 2026
./scripts/cleanup-containers.sh deer-flow-sandbox 2>/dev/null || true
echo "✓ All services stopped"
}
# ── Action routing ───────────────────────────────────────────────────────────
if [ "$ACTION" = "stop" ]; then
stop_all
exit 0
fi
ALREADY_STOPPED=false
if [ "$ACTION" = "restart" ]; then
stop_all
sleep 1
ALREADY_STOPPED=true
fi
# Mode label for banner
if $DEV_MODE; then
MODE_LABEL="DEV (Gateway runtime, hot-reload enabled)"
else
MODE_LABEL="PROD (Gateway runtime, optimized)"
fi
if $DAEMON_MODE; then
MODE_LABEL="$MODE_LABEL [daemon]"
fi
# Resolve pnpm through the same runner used by make check/install. Exporting
# these values keeps paths with spaces intact when run_service invokes sh -c.
if ! DEERFLOW_PNPM_PYTHON="$(_pick_python)"; then
echo "Python 3 is required to run pnpm."
exit 1
fi
DEERFLOW_PNPM_RUNNER="$REPO_ROOT/scripts/pnpm.py"
export DEERFLOW_PNPM_PYTHON DEERFLOW_PNPM_RUNNER
# Frontend command
if $DEV_MODE; then
FRONTEND_CMD='"$DEERFLOW_PNPM_PYTHON" "$DEERFLOW_PNPM_RUNNER" run dev'
else
FRONTEND_CMD="env BETTER_AUTH_SECRET=$($DEERFLOW_PNPM_PYTHON -c 'import secrets; print(secrets.token_hex(16))') \"\$DEERFLOW_PNPM_PYTHON\" \"\$DEERFLOW_PNPM_RUNNER\" run preview"
fi
# Runtime path defaults. Local `make dev` launches Gateway from `backend/`,
# so pin DeerFlow-owned state to the expected backend runtime directory and
# create it before uvicorn builds its reload exclude filter.
if [ -z "$DEER_FLOW_PROJECT_ROOT" ]; then
export DEER_FLOW_PROJECT_ROOT="$REPO_ROOT"
fi
BACKEND_RUNTIME_HOME="$REPO_ROOT/backend/.deer-flow"
if [ -z "$DEER_FLOW_HOME" ]; then
export DEER_FLOW_HOME="$BACKEND_RUNTIME_HOME"
fi
# `backend/sandbox` is excluded from uvicorn's reload watcher below. uvicorn only
# excludes an absolute path directly when it already exists as a directory;
# otherwise it globs the pattern, and Python 3.12's pathlib rejects absolute glob
# patterns with NotImplementedError, crashing `make dev` on a fresh checkout
# (#3459 / #3454). Creating it here keeps every absolute exclude on the is_dir path.
mkdir -p "$DEER_FLOW_HOME" "$BACKEND_RUNTIME_HOME" "$REPO_ROOT/backend/sandbox"
DEER_FLOW_HOME="$(cd "$DEER_FLOW_HOME" && pwd -P)"
BACKEND_RUNTIME_HOME="$(cd "$BACKEND_RUNTIME_HOME" && pwd -P)"
export DEER_FLOW_HOME
# Extra flags for uvicorn
if $DEV_MODE && ! $DAEMON_MODE; then
GATEWAY_EXTRA_FLAGS="--reload --reload-include='*.yaml' --reload-include='.env' --reload-exclude='*.pyc' --reload-exclude='__pycache__' --reload-exclude='$REPO_ROOT/backend/sandbox' --reload-exclude='$DEER_FLOW_HOME' --reload-exclude='$BACKEND_RUNTIME_HOME'"
else
GATEWAY_EXTRA_FLAGS=""
fi
# ── Stop existing services (skip if restart already did it) ──────────────────
if ! $ALREADY_STOPPED; then
stop_all
sleep 1
fi
# ── Config check ─────────────────────────────────────────────────────────────
if ! { \
[ -n "$DEER_FLOW_CONFIG_PATH" ] && [ -f "$DEER_FLOW_CONFIG_PATH" ] || \
[ -f backend/config.yaml ] || \
[ -f config.yaml ]; \
}; then
echo "✗ No DeerFlow config file found."
echo " Run 'make setup' (recommended) or 'make config' to generate config.yaml."
exit 1
fi
"$REPO_ROOT/scripts/config-upgrade.sh"
# ── Install dependencies ────────────────────────────────────────────────────
# Pick a runnable Python for the extras detector. On Windows/Git Bash,
# `python3` can resolve to the Microsoft Store alias in WindowsApps, which is
# present on PATH but not executable from Bash.
DETECT_PYTHON="$(_pick_python || true)"
# Resolve uv extras (postgres, etc.) from UV_EXTRAS or config.yaml so that
# `uv sync` does not wipe out optional dependencies on every restart. See
# scripts/detect_uv_extras.py and Issue #2754 for context. The detector
# whitelists extra names against `^[A-Za-z][A-Za-z0-9_-]*$`, so the unquoted
# splat below only sees valid uv argument tokens.
#
# Stderr is intentionally NOT redirected so the user sees:
# - whitelist warnings (e.g. "ignoring invalid UV_EXTRAS entry ';'");
# - detector crashes (e.g. unexpected Python error).
# `|| true` keeps `set -e` from killing dev startup on a detector failure;
# the result is just an empty UV_EXTRAS_FLAGS, which means "no extras".
UV_EXTRAS_FLAGS=""
if [ -n "$DETECT_PYTHON" ]; then
UV_EXTRAS_FLAGS=$("$DETECT_PYTHON" "$REPO_ROOT/scripts/detect_uv_extras.py" || { echo "[serve.sh] detect_uv_extras.py failed (exit $?) — proceeding without extras" >&2; echo ""; })
fi
if ! $SKIP_INSTALL; then
echo "Syncing dependencies..."
if [ -n "$UV_EXTRAS_FLAGS" ]; then
echo " • uv extras: $UV_EXTRAS_FLAGS"
fi
# `--all-packages` propagates extras into workspace members (deerflow-harness
# in particular). Required for postgres extras — see PR #2584.
# Intentionally unquoted to splat multiple `--extra X` pairs.
(cd backend && uv sync --locked --quiet --all-packages $UV_EXTRAS_FLAGS) || { echo "✗ Backend dependency install failed"; exit 1; }
(cd frontend && "$DEERFLOW_PNPM_PYTHON" "$DEERFLOW_PNPM_RUNNER" install --silent) || { echo "✗ Frontend dependency install failed"; exit 1; }
echo "✓ Dependencies synced"
else
echo "⏩ Skipping dependency install (--skip-install)"
fi
# ── Banner ───────────────────────────────────────────────────────────────────
echo ""
echo "=========================================="
echo " Starting DeerFlow"
echo "=========================================="
echo ""
echo " Mode: $MODE_LABEL"
echo ""
echo " Services:"
echo " Gateway → localhost:8001 (REST API + agent runtime)"
echo " Frontend → localhost:3000 (Next.js)"
echo " Nginx → localhost:2026 (reverse proxy)"
echo ""
# ── Cleanup handler ──────────────────────────────────────────────────────────
cleanup() {
local status="${1:-0}"
trap - INT TERM
echo ""
stop_all
exit "$status"
}
trap 'cleanup 130' INT
trap 'cleanup 143' TERM
# ── Helper: start a service ──────────────────────────────────────────────────
# run_service NAME COMMAND PORT TIMEOUT
# In daemon mode, wraps with nohup. Waits for port to be ready.
run_service() {
local name="$1" cmd="$2" port="$3" timeout="$4"
if _is_port_listening "$port"; then
echo "✗ $name cannot start because port $port is already in use."
echo " If it belongs to this worktree, run 'make stop'; otherwise free the port manually."
cleanup 1
fi
echo "Starting $name..."
if $DAEMON_MODE; then
# Tag the daemon so every descendant (pnpm → next → next-server)
# carries DEERFLOW_DAEMON_ROOT in its environment, letting
# _is_deerflow_pid recognize it at stop time.
nohup env DEERFLOW_DAEMON_ROOT="$REPO_ROOT" sh -c "$cmd" > /dev/null 2>&1 &
else
sh -c "$cmd" &
fi
./scripts/wait-for-port.sh "$port" "$timeout" "$name" || {
local logfile="logs/$(echo "$name" | tr '[:upper:]' '[:lower:]' | tr ' ' '-').log"
echo "✗ $name failed to start."
[ -f "$logfile" ] && tail -20 "$logfile"
cleanup 1
}
echo "✓ $name started on localhost:$port"
}
# ── Start services ───────────────────────────────────────────────────────────
mkdir -p logs
mkdir -p temp/client_body_temp temp/proxy_temp temp/fastcgi_temp temp/uwsgi_temp temp/scgi_temp
# 1. Gateway API
run_service "Gateway" \
"cd backend && PYTHONPATH=. uv run --no-sync uvicorn app.gateway.app:app --host 0.0.0.0 --port 8001 $GATEWAY_EXTRA_FLAGS > ../logs/gateway.log 2>&1" \
8001 30
# 2. Frontend
run_service "Frontend" \
"cd frontend && $FRONTEND_CMD > ../logs/frontend.log 2>&1" \
3000 120
# 3. Nginx
run_service "Nginx" \
"nginx -g 'daemon off;' -c '$REPO_ROOT/docker/nginx/nginx.local.conf' -p '$REPO_ROOT' > logs/nginx.log 2>&1" \
2026 10
# ── Ready ────────────────────────────────────────────────────────────────────
echo ""
echo "=========================================="
echo " ✓ DeerFlow is running! [$MODE_LABEL]"
echo "=========================================="
echo ""
echo " 🌐 http://localhost:2026"
echo ""
echo " Routing: Frontend → Nginx → Gateway"
echo " API: /api/langgraph/* → Gateway agent runtime"
echo " /api/* → Gateway REST API (8001)"
echo ""
echo " 📋 Logs: logs/{gateway,frontend,nginx}.log"
echo ""
if $DAEMON_MODE; then
echo " 🛑 Stop: make stop"
# Detach — trap is no longer needed
trap - INT TERM
else
echo " Press Ctrl+C to stop all services"
wait
fi