Repository navigation
Expand file tree
/
Copy pathocd
More file actions
executable file
·475 lines (429 loc) · 17.8 KB
/
Copy pathocd
File metadata and controls
executable file
·475 lines (429 loc) · 17.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
#!/usr/bin/env bash
# =============================================================================
# OpenCode Docker CLI (ocd)
# Runs autonomous . coding agents in an ephemeral, hardened Docker container
# with GitHub App credentials, non-root execution, and tiered storage.
# =============================================================================
set -e
# -----------------------------------------------------------------------------
# 1. Resolve Script Directory Across Symlinks (macOS & Linux Portable)
# -----------------------------------------------------------------------------
SOURCE="${BASH_SOURCE[0]}"
while [ -L "$SOURCE" ]; do
DIR="$(cd -P "$(dirname "$SOURCE")" && pwd)"
SOURCE="$(readlink "$SOURCE")"
[[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE"
done
SCRIPT_DIR="$(cd -P "$(dirname "$SOURCE")" && pwd)"
# -----------------------------------------------------------------------------
# 2. Load Configuration (.env file or Environment Variables)
# -----------------------------------------------------------------------------
if [ -f "$SCRIPT_DIR/.env" ]; then
set -a
# shellcheck disable=SC1091
source "$SCRIPT_DIR/.env"
set +a
fi
GH_APP_ID="${GH_APP_ID:-${gh_app_id:-}}"
GH_INSTALLATION_ID="${GH_INSTALLATION_ID:-${gh_install_id:-}}"
GH_APP_SLUG="${GH_APP_SLUG:-${gh_app_slug:-opencode-bot}}"
IMAGE_NAME="${OPENCODE_IMAGE:-opencode-dev:latest}"
BOT_KEY_PATH="${GH_APP_KEY_PATH:-$SCRIPT_DIR/app.pem}"
DATA_ROOT="$SCRIPT_DIR/data"
ENTRYPOINT_SCRIPT="$SCRIPT_DIR/docker-entrypoint.sh"
BOT_NAME="${GH_APP_SLUG}[bot]"
BOT_EMAIL="${GH_APP_ID}+${GH_APP_SLUG}[bot]@users.noreply.github.com"
CONTAINER_ENV_FILE="${CONTAINER_ENV_FILE:-$SCRIPT_DIR/.env.container}"
SANDBOX_MODE=false
# Resolve optional Bifrost Gateway port (.env, bifrost/.env.bifrost, or default 8321)
if [ -z "${BIFROST_PORT:-}" ] && [ -f "$SCRIPT_DIR/bifrost/.env.bifrost" ]; then
bifrost_port_from_env=$(grep -E '^\s*BIFROST_PORT=' "$SCRIPT_DIR/bifrost/.env.bifrost" | cut -d '=' -f2- | tr -d ' "\x27' || true)
if [ -n "$bifrost_port_from_env" ]; then
BIFROST_PORT="$bifrost_port_from_env"
fi
fi
BIFROST_PORT="${BIFROST_PORT:-8321}"
# -----------------------------------------------------------------------------
# 3. Handle Gateway Subcommand & Parse CLI Flags
# -----------------------------------------------------------------------------
if [ "${1:-}" = "gateway" ]; then
shift
action="${1:-status}"
compose_file="$SCRIPT_DIR/bifrost/docker-compose.yml"
if [ ! -f "$compose_file" ]; then
echo "Error: Bifrost compose file not found at '$compose_file'" >&2
exit 1
fi
case "$action" in
start|up)
echo "Starting Bifrost Gateway on port $BIFROST_PORT..."
BIFROST_PORT="$BIFROST_PORT" docker compose -f "$compose_file" up -d
echo "✅ Bifrost Gateway is running at http://localhost:$BIFROST_PORT"
;;
stop|down)
echo "Stopping Bifrost Gateway..."
BIFROST_PORT="$BIFROST_PORT" docker compose -f "$compose_file" down
echo "✅ Bifrost Gateway stopped."
;;
restart)
echo "Restarting Bifrost Gateway..."
BIFROST_PORT="$BIFROST_PORT" docker compose -f "$compose_file" restart
;;
logs)
BIFROST_PORT="$BIFROST_PORT" docker compose -f "$compose_file" logs -f
;;
ui|dashboard|open)
if command -v open >/dev/null 2>&1; then
open "http://localhost:$BIFROST_PORT"
elif command -v xdg-open >/dev/null 2>&1; then
xdg-open "http://localhost:$BIFROST_PORT"
else
echo "Open http://localhost:$BIFROST_PORT in your browser."
fi
;;
status)
if docker compose -f "$compose_file" ps --status running 2>/dev/null | grep -q "ocd-bifrost-gateway"; then
echo "🟢 Bifrost Gateway is RUNNING at http://localhost:$BIFROST_PORT"
else
echo "🔴 Bifrost Gateway is NOT running. Start it with: ocd gateway start"
fi
;;
*)
echo "Usage: ocd gateway [start|stop|restart|status|logs|ui]" >&2
exit 1
;;
esac
exit 0
fi
show_help() {
cat << EOF
OpenCode Docker CLI (ocd)
Usage:
ocd [options] [workspace_dir] [-- <agent args>]
ocd gateway [start|stop|status|logs|ui]
Options:
--rebuild Rebuild the Docker image with your host UID/GID
--sandbox, --isolated Run in disposable sandbox mode (no caches or stored state)
-h, --help Show this help message and exit
Gateway Commands (Optional Zero-Secret Sidecar):
gateway start Start the Bifrost AI & MCP Gateway daemon
gateway stop Stop the Bifrost Gateway daemon
gateway status Check if Bifrost Gateway is running
gateway logs View live logs from Bifrost Gateway
gateway ui Open the Bifrost Web Dashboard in your browser
Examples:
ocd # Launch OpenCode in current directory
ocd ~/projects/my-repo # Launch OpenCode in specified directory
ocd --sandbox . # Launch isolated session for inspecting untrusted code
ocd gateway start # Start the optional Bifrost Zero-Secret Gateway
ocd --rebuild # Rebuild container image with updated dependencies
EOF
}
while [ $# -gt 0 ]; do
case "$1" in
--help|-h)
show_help
exit 0
;;
--rebuild)
echo "Rebuilding $IMAGE_NAME..."
docker build --pull \
--build-arg USER_UID="$(id -u)" \
--build-arg USER_GID="$(id -g)" \
-t "$IMAGE_NAME" -f "$SCRIPT_DIR/Dockerfile" "$SCRIPT_DIR"
echo "✅ Successfully rebuilt $IMAGE_NAME."
shift
if [ $# -eq 0 ]; then
exit 0
fi
;;
--sandbox|--isolated)
SANDBOX_MODE=true
echo "🔒 Running in SANDBOX mode: host caches and stored credentials disabled."
shift
;;
--)
shift
break
;;
-*)
echo "Unknown option: $1" >&2
echo "Run 'ocd --help' for usage." >&2
exit 1
;;
*)
break
;;
esac
done
# -----------------------------------------------------------------------------
# 4. Resolve Target Workspace Directory
# -----------------------------------------------------------------------------
TARGET_DIR="${1:-.}"
if [ -d "$TARGET_DIR" ]; then
WORKSPACE_DIR="$(cd "$TARGET_DIR" && pwd -P)"
[ $# -gt 0 ] && shift
else
echo "Error: Directory '$TARGET_DIR' does not exist." >&2
exit 1
fi
# -----------------------------------------------------------------------------
# 5. Validate GitHub App Configuration & Private Key
# -----------------------------------------------------------------------------
if [ -z "$GH_APP_ID" ] || [ "$GH_APP_ID" = "YOUR_APP_ID" ]; then
echo "Error: GitHub App configuration is missing." >&2
echo "Please set GH_APP_ID in $SCRIPT_DIR/.env" >&2
echo "See $SCRIPT_DIR/.env.example for guidance." >&2
exit 1
fi
if [ ! -f "$BOT_KEY_PATH" ]; then
echo "Error: GitHub App private key not found at '$BOT_KEY_PATH'" >&2
exit 1
fi
chmod 600 "$BOT_KEY_PATH" 2>/dev/null || true
# -----------------------------------------------------------------------------
# 6. Host-Side Token Minting (OpenSSL + curl + python3)
# -----------------------------------------------------------------------------
mint_gh_token() {
local now
now=$(date +%s)
local iat=$((now - 60))
local exp=$((now + 540))
local b64enc="openssl base64 -e -A | tr '+/' '-_' | tr -d '='"
local header
header=$(printf '{"alg":"RS256","typ":"JWT"}' | eval "$b64enc")
local payload
payload=$(printf '{"iat":%d,"exp":%d,"iss":"%s"}' "$iat" "$exp" "$GH_APP_ID" | eval "$b64enc")
local sig
sig=$(printf '%s.%s' "$header" "$payload" | openssl dgst -sha256 -sign "$BOT_KEY_PATH" 2>/dev/null | eval "$b64enc")
if [ -z "$sig" ]; then
echo "Error: Failed to sign JWT with key '$BOT_KEY_PATH'. Is it a valid RSA private key?" >&2
return 1
fi
local jwt="${header}.${payload}.${sig}"
# Auto-resolve installation ID from the current repository remote for multi-org support
local target_inst_id="$GH_INSTALLATION_ID"
local remote_url
remote_url=$(git -C "$WORKSPACE_DIR" config --get remote.origin.url 2>/dev/null || true)
if [ -n "$remote_url" ]; then
local repo_slug
repo_slug=$(echo "$remote_url" | sed -E 's#(git@github\.com:|https://github\.com/)##; s#\.git$##')
if [ -n "$repo_slug" ]; then
local inst_resp
inst_resp=$(curl -s -H "Authorization: Bearer $jwt" \
-H "Accept: application/vnd.github+json" \
"https://api.github.com/repos/${repo_slug}/installation" 2>/dev/null)
local detected_id
detected_id=$(python3 -c "import sys, json; print(json.load(sys.stdin).get('id', ''))" <<< "$inst_resp" 2>/dev/null || true)
if [ -n "$detected_id" ]; then
target_inst_id="$detected_id"
fi
fi
fi
if [ -z "$target_inst_id" ] || [ "$target_inst_id" = "YOUR_INSTALLATION_ID" ]; then
echo "Error: GitHub App installation ID could not be determined." >&2
echo "Please set GH_INSTALLATION_ID in $SCRIPT_DIR/.env or ensure your GitHub App is installed on the repository/organization." >&2
return 1
fi
local http_response
http_response=$(curl -s -w "\nHTTP_STATUS:%{http_code}" -X POST \
-H "Authorization: Bearer $jwt" \
-H "Accept: application/vnd.github+json" \
"https://api.github.com/app/installations/${target_inst_id}/access_tokens" 2>/dev/null)
local http_body
http_body=$(echo "$http_response" | sed -e '$d')
local http_code
http_code=$(echo "$http_response" | tail -n1 | sed -e 's/HTTP_STATUS://')
if [ "$http_code" = "201" ]; then
python3 -c "import sys, json; print(json.load(sys.stdin)['token'])" <<< "$http_body" 2>/dev/null
return 0
else
local err_msg
err_msg=$(python3 -c "import sys, json; print(json.load(sys.stdin).get('message', ''))" <<< "$http_body" 2>/dev/null || echo "$http_body")
[ -z "$err_msg" ] && err_msg="Unknown error"
echo "GitHub API error (HTTP $http_code): $err_msg" >&2
case "$http_code" in
401)
echo "💡 Tip: Verify that GH_APP_ID='$GH_APP_ID' and '$BOT_KEY_PATH' match your GitHub App." >&2
return 2
;;
404)
echo "💡 Tip: Verify that GitHub App installation '$target_inst_id' exists and is installed on the repository/organization." >&2
return 2
;;
403)
echo "💡 Tip: Ensure the GitHub App has 'Contents: Read and write' and 'Pull requests: Read and write' permissions." >&2
return 2
;;
esac
return 1
fi
}
mint_with_retry() {
local max_attempts="${1:-3}"
local delay="${2:-3}"
local silent="${3:-false}"
local attempt=1
local token=""
local rc=0
while [ "$attempt" -le "$max_attempts" ]; do
if [ "$silent" = "true" ]; then
token=$(mint_gh_token 2>/dev/null)
rc=$?
else
token=$(mint_gh_token)
rc=$?
fi
if [ $rc -eq 0 ] && [ -n "$token" ] && [ "$token" != "null" ]; then
echo "$token"
return 0
elif [ $rc -eq 2 ]; then
return 1
fi
attempt=$((attempt + 1))
[ "$attempt" -le "$max_attempts" ] && sleep "$delay"
done
return 1
}
# -----------------------------------------------------------------------------
# 7. Create Ephemeral Token File & Resilient Background Refresher
# -----------------------------------------------------------------------------
TOKEN_FILE=$(mktemp "${TMPDIR:-/tmp}/opencode_token.XXXXXX")
chmod 600 "$TOKEN_FILE"
INITIAL_TOKEN=$(mint_with_retry 3 2 false)
if [ -z "$INITIAL_TOKEN" ] || [ "$INITIAL_TOKEN" = "null" ]; then
echo "Error: Failed to mint GitHub installation token after retries." >&2
rm -f "$TOKEN_FILE"
exit 1
fi
echo "$INITIAL_TOKEN" > "$TOKEN_FILE"
# Refresher subshell: checks parent PID and wall-clock elapsed time every 15s.
# Using wall-clock time ensures tokens refresh immediately after laptop sleep/wake!
PARENT_PID=$$
(
last_refresh=$(date +%s)
refresh_interval=2400 # Refresh every 40 minutes
while [ -f "$TOKEN_FILE" ]; do
sleep 15
# Parent process liveness check: terminate immediately if parent died
if ! kill -0 "$PARENT_PID" 2>/dev/null; then
break
fi
if [ ! -f "$TOKEN_FILE" ]; then
break
fi
now=$(date +%s)
elapsed=$((now - last_refresh))
if [ "$elapsed" -ge "$refresh_interval" ]; then
new_token=$(mint_with_retry 3 5 true 2>/dev/null || true)
if [ -n "$new_token" ] && [ "$new_token" != "null" ]; then
# Write in-place to preserve inode for Docker single-file bind mounts
printf '%s\n' "$new_token" > "$TOKEN_FILE"
last_refresh=$(date +%s)
fi
fi
done
) &
REFRESH_PID=$!
cleanup() {
local exit_code=$?
if [ -n "${REFRESH_PID:-}" ] && kill -0 "$REFRESH_PID" 2>/dev/null; then
kill "$REFRESH_PID" 2>/dev/null || true
wait "$REFRESH_PID" 2>/dev/null || true
fi
rm -f "$TOKEN_FILE" "${TOKEN_FILE}.tmp"* 2>/dev/null || true
exit "$exit_code"
}
trap cleanup EXIT INT TERM HUP
# -----------------------------------------------------------------------------
# 8. Assemble Mounts & Environment Variables
# -----------------------------------------------------------------------------
mounts=(
-v "$WORKSPACE_DIR":"$WORKSPACE_DIR"
-v "$WORKSPACE_DIR":/workspace
-v "$TOKEN_FILE":/run/secrets/github_token:ro
)
if [ -f "$ENTRYPOINT_SCRIPT" ]; then
mounts+=(-v "$ENTRYPOINT_SCRIPT":/usr/local/bin/docker-entrypoint.sh:ro)
fi
# Bot git identity & Gateway configuration
env_args=(
-e GIT_AUTHOR_NAME="$BOT_NAME"
-e GIT_AUTHOR_EMAIL="$BOT_EMAIL"
-e GIT_COMMITTER_NAME="$BOT_NAME"
-e GIT_COMMITTER_EMAIL="$BOT_EMAIL"
-e BIFROST_PORT="$BIFROST_PORT"
-e HOST_WORKSPACE_DIR="$WORKSPACE_DIR"
)
# Container environment file (--env-file)
# Passes all agent LLM keys and MCP credentials directly to Docker
if [ -f "$CONTAINER_ENV_FILE" ]; then
env_args+=(--env-file "$CONTAINER_ENV_FILE")
fi
# Optional project-specific container env override
if [ "$WORKSPACE_DIR" != "$SCRIPT_DIR" ] && [ -f "$WORKSPACE_DIR/.env.container" ]; then
env_args+=(--env-file "$WORKSPACE_DIR/.env.container")
fi
# Fallback: Forward host environment variables if set in current shell
for key in ANTHROPIC_API_KEY OPENAI_API_KEY GEMINI_API_KEY OPENROUTER_API_KEY \
DEEPSEEK_API_KEY GROQ_API_KEY MISTRAL_API_KEY OLLAMA_API_BASE OPENAI_API_BASE; do
if [ -n "${!key:-}" ]; then
env_args+=(-e "$key=${!key}")
fi
done
if [ "$SANDBOX_MODE" = false ]; then
# 1. SHARED: Global settings, commands, MCP servers, skills & npm cache
mkdir -p "$DATA_ROOT/global"/{config,state,cache/npm}
mounts+=(
-v "$DATA_ROOT/global/config":/home/opencode/.config/opencode
-v "$DATA_ROOT/global/state":/home/opencode/.local/state/opencode
-v "$DATA_ROOT/global/cache/npm":/home/opencode/.npm
)
# 2. ISOLATED: Caches and session histories scoped strictly to this repository
project_name=$(basename "$WORKSPACE_DIR")
project_hash=$(python3 -c "import hashlib; print(hashlib.md5('''$WORKSPACE_DIR'''.encode()).hexdigest()[:8])" 2>/dev/null || printf '%s' "$WORKSPACE_DIR" | md5sum 2>/dev/null | cut -c1-8 || printf '%s' "$WORKSPACE_DIR" | md5 2>/dev/null | cut -c1-8)
project_id="${project_name}-${project_hash}"
project_data="$DATA_ROOT/projects/$project_id"
mkdir -p "$project_data"/{cache,go,share}
mounts+=(
-v "$project_data/cache":/home/opencode/.cache
-v "$project_data/go":/home/opencode/go
-v "$project_data/share":/home/opencode/.local/share/opencode
)
fi
# -----------------------------------------------------------------------------
# 9. Build Image Automatically on First Run
# -----------------------------------------------------------------------------
if ! docker image inspect "$IMAGE_NAME" >/dev/null 2>&1; then
echo "Building $IMAGE_NAME..."
docker build \
--build-arg USER_UID="$(id -u)" \
--build-arg USER_GID="$(id -g)" \
-t "$IMAGE_NAME" -f "$SCRIPT_DIR/Dockerfile" "$SCRIPT_DIR"
fi
# -----------------------------------------------------------------------------
# 10. Check Optional Bifrost Gateway Liveness & Launch Container
# -----------------------------------------------------------------------------
if grep -qs -E "(OPENAI_API_BASE|ANTHROPIC_BASE_URL).*$BIFROST_PORT" "$CONTAINER_ENV_FILE" 2>/dev/null || \
[[ "${OPENAI_API_BASE:-}" == *"$BIFROST_PORT"* ]] || [[ "${ANTHROPIC_BASE_URL:-}" == *"$BIFROST_PORT"* ]]; then
if ! curl -s -m 1 "http://127.0.0.1:$BIFROST_PORT" >/dev/null 2>&1 && ! nc -z -w 1 127.0.0.1 "$BIFROST_PORT" 2>/dev/null; then
echo "⚠️ Notice: Bifrost Gateway is configured on port $BIFROST_PORT, but does not appear to be running." >&2
echo " You can start it with: ocd gateway start" >&2
fi
fi
echo "Launching OpenCode in: $WORKSPACE_DIR (as $BOT_NAME)"
docker_tty_args=()
if [ -t 0 ] && [ -t 1 ]; then
docker_tty_args=(-it)
elif [ -t 0 ]; then
docker_tty_args=(-i)
fi
docker run "${docker_tty_args[@]}" --rm \
--init \
--security-opt=no-new-privileges:true \
--pids-limit 1024 \
--add-host host.docker.internal:host-gateway \
"${mounts[@]}" \
"${env_args[@]}" \
--workdir "$WORKSPACE_DIR" \
"$IMAGE_NAME" "$@"