-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpi.sh
More file actions
executable file
·387 lines (336 loc) · 11.9 KB
/
pi.sh
File metadata and controls
executable file
·387 lines (336 loc) · 11.9 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
#!/bin/bash
TOOLS="" # enable default tools (and extension tools?)
# TOOLS="=--tools read,bash,edit,write" # default
#TOOLS="--tools read,bash,edit,write,grep,find,ls" # enable all build-in tools (but don't enable extension tools?)
# location of this script
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
ORIGINAL_CWD="$PWD"
touch "$SCRIPT_DIR/.env" # if user did not create it based on .env.template
source "$SCRIPT_DIR/.env"
# Handle flags
MOUNT_MODE="rw"
ENTRYPOINT_FILE="$SCRIPT_DIR/entrypoint.sh"
DO_INSTALL=false
DO_UPDATE=false
DO_SESSIONS=false
DO_COMMIT=false
DOCKER_PORT_ARGS=()
NEW_ARGS=()
while [[ $# -gt 0 ]]; do
case "$1" in
--ro|--readonly)
MOUNT_MODE="ro"
TOOLS="--tools read,grep,find,ls"
shift
;;
--install)
DO_INSTALL=true
shift
;;
--update)
DO_UPDATE=true
shift
;;
--sessions)
DO_SESSIONS=true
shift
;;
--commit)
DO_COMMIT=true
shift
;;
--entrypoint)
if [ -z "$2" ]; then
>&2 echo "Error: --entrypoint requires a path"
exit 1
fi
ENTRYPOINT_FILE="$2"
shift 2
;;
--entrypoint=*)
ENTRYPOINT_FILE="${1#--entrypoint=}"
shift
;;
--port|--publish)
# Docker port mapping format is HOST_PORT:CONTAINER_PORT.
# Example: 8080:3000 exposes container port 3000 on host port 8080.
if [ -z "$2" ]; then
>&2 echo "Error: $1 requires a port mapping (for example: 8080:8080)"
exit 1
fi
DOCKER_PORT_ARGS+=(-p "$2")
shift 2
;;
--port=*|--publish=*)
DOCKER_PORT_ARGS+=(-p "${1#*=}")
shift
;;
*)
NEW_ARGS+=("$1")
shift
;;
esac
done
set -- "${NEW_ARGS[@]}"
# Resolve entrypoint path. Plain relative paths are relative to this script.
# Absolute paths are used as-is. Bare names can be used as shortcuts for
# bundled entrypoints, e.g. "zsh" resolves to "entrypoint-zsh.sh" when that
# file exists.
resolve_entrypoint_file() {
local requested="$1"
local base=""
local candidates=()
if [[ "$requested" == /* ]]; then
printf '%s\n' "$requested"
return
fi
if [[ "$requested" == */* ]]; then
printf '%s/%s\n' "$SCRIPT_DIR" "$requested"
return
fi
base="$SCRIPT_DIR/$requested"
candidates+=("$base")
if [[ "$requested" != *.sh ]]; then
candidates+=("$base.sh")
fi
if [[ "$requested" != entrypoint-* ]]; then
candidates+=("$SCRIPT_DIR/entrypoint-$requested")
if [[ "$requested" != *.sh ]]; then
candidates+=("$SCRIPT_DIR/entrypoint-$requested.sh")
fi
fi
for candidate in "${candidates[@]}"; do
if [ -f "$candidate" ]; then
printf '%s\n' "$candidate"
return
fi
done
printf '%s\n' "$base"
}
ENTRYPOINT_FILE="$(resolve_entrypoint_file "$ENTRYPOINT_FILE")"
if [ ! -f "$ENTRYPOINT_FILE" ]; then
>&2 echo "Error: entrypoint file not found: $ENTRYPOINT_FILE"
exit 1
fi
# --commit flag
if [ "$DO_COMMIT" = true ]; then
MODEL_ARG=""
if [ -n "$PI_FAST_MODEL" ]; then
MODEL_ARG="--provider $PI_FAST_PROVIDER --model $PI_FAST_MODEL"
fi
set -- $MODEL_ARG "/commit --force --user \"$(git config user.name)\" --email \"$(git config user.email)\""
fi
# --install flag
if [ "$DO_INSTALL" = true ]; then
SHELL_CONFIG=""
for f in "$HOME/.zshrc.local" "$HOME/.zshrc" "$HOME/.bashrc"; do
if [ -f "$f" ]; then
SHELL_CONFIG="$f"
break
fi
done
if [ -z "$SHELL_CONFIG" ]; then
>&2 echo "Error: Could not find ~/.zshrc.local, ~/.zshrc, or ~/.bashrc"
exit 1
fi
if ! grep -q "# pi-coding-agent alias" "$SHELL_CONFIG"; then
printf "\n" >> "$SHELL_CONFIG"
fi
for alias_name in "pi" "pic" "picommit"; do
if grep -q "^alias $alias_name=" "$SHELL_CONFIG" || grep -q "^alias $alias_name =" "$SHELL_CONFIG"; then
>&2 echo "Updating '$alias_name' alias in $SHELL_CONFIG..."
grep -v "^alias $alias_name=" "$SHELL_CONFIG" | grep -v "^alias $alias_name =" > "$SHELL_CONFIG.tmp" && mv "$SHELL_CONFIG.tmp" "$SHELL_CONFIG"
else
echo "Installing '$alias_name' alias in $SHELL_CONFIG..."
fi
case "$alias_name" in
pi)
printf "alias pi='%s/pi.sh' # pi-coding-agent alias\n" "$SCRIPT_DIR" >> "$SHELL_CONFIG"
;;
pic)
printf "alias pic='%s/pi.sh --continue' # pi-coding-agent alias\n" "$SCRIPT_DIR" >> "$SHELL_CONFIG"
;;
picommit)
printf "alias picommit='%s/pi.sh --commit' # pi-coding-agent alias\n" "$SCRIPT_DIR" >> "$SHELL_CONFIG"
;;
esac
done
>&2 echo "Successfully installed/updated aliases. Please run 'source $SHELL_CONFIG' or restart your terminal."
exit 0
fi
# --update flag
if [ "$DO_UPDATE" = true ]; then
cd "$SCRIPT_DIR"
CURRENT_VERSION=$(./build.sh --installed-version)
LATEST_VERSION=$(curl -s https://registry.npmjs.org/@earendil-works/pi-coding-agent/latest | jq -r .version)
>&2 echo "Latest pi version: $LATEST_VERSION"
>&2 echo "Current installed pi version: $CURRENT_VERSION"
if [ "$CURRENT_VERSION" == "$LATEST_VERSION" ]; then
>&2 echo "Pi image already up to date."
UPDATED_VERSION="$CURRENT_VERSION"
else
>&2 echo "Updating pi to version $LATEST_VERSION ..."
./build.sh "$LATEST_VERSION"
UPDATED_VERSION=$(./build.sh --installed-version)
>&2 echo "Updated to pi version: $UPDATED_VERSION"
if [ "$UPDATED_VERSION" != "$LATEST_VERSION" ]; then
>&2 echo "Warning: expected version $LATEST_VERSION but got $UPDATED_VERSION"
fi
fi
>&2 echo "Updating configured packages ..."
./pi.sh update
exit 0
fi
# --sessions flag
if [ "$DO_SESSIONS" = true ]; then
SESSIONS_DIR="$SCRIPT_DIR/pi/agent/sessions"
if [ ! -d "$SESSIONS_DIR" ]; then
>&2 echo "No sessions found at $SESSIONS_DIR"
exit 0
fi
BOLD='\033[1m'
CYAN='\033[0;36m'
GREEN='\033[0;32m'
NC='\033[0m' # No Color
echo -e "${BOLD}Sessions directory:${NC} ${CYAN}$SESSIONS_DIR${NC}"
find "$SESSIONS_DIR" -maxdepth 1 -mindepth 1 -type d | sort | while read -r dir; do
basename_dir=$(basename "$dir")
if [ "$basename_dir" == "logs" ]; then
continue
fi
count=$(find "$dir" -maxdepth 1 -mindepth 1 -type f -name "*.jsonl" | wc -l)
>&2 echo -e "${BOLD}${GREEN}$basename_dir${NC}: $count sessions"
find "$dir" -maxdepth 1 -mindepth 1 -type f -name "*.jsonl" -exec basename {} \; | sort -r | head -n 5 | while read -r session; do
>&2 echo " - $session"
done
done
exit 0
fi
# map cache dirs used by my pi
mkdir -p "$SCRIPT_DIR/.cache/checkouts"
mkdir -p "$SCRIPT_DIR/.cache/gondolin/images"
DEBUGFLAGS=""
#DEBUGFLAGS="--entrypoint zsh"
# test volumes: ./pi.sh -c 'touch ~/.pi/test'
EXTRA_VOLUMES=()
EXTRA_PI_ARGS=()
if [ -f ".pi_ro" ]; then
MOUNT_MODE="ro"
>&2 echo "WARNING: .pi_ro found in current directory. Forcing READ-ONLY mount."
fi
>&2 echo "INFO: Using env file: $SCRIPT_DIR/.env"
if [ -n "$DEBUGFLAGS" ]; then
>&2 echo "INFO: docker run flags: $DEBUGFLAGS"
fi
# Optional per-directory read-only volume mounts.
# .volumes.yml is expected to contain entries like:
# - "~/some/project": "~/some/notes"
VOLUMES_FILE="$SCRIPT_DIR/.volumes.yml"
if [ -f "$VOLUMES_FILE" ]; then
PROJECT_ORG_NOTES=$(python3 - "$VOLUMES_FILE" "$ORIGINAL_CWD" <<'PY'
import ast
import os
import sys
volumes_file, cwd = sys.argv[1], sys.argv[2]
def canonicalize(path):
return os.path.abspath(os.path.expanduser(path))
volumes = {}
with open(volumes_file, encoding="utf-8") as f:
for lineno, line in enumerate(f, 1):
line = line.strip()
if not line or line.startswith("#"):
continue
if not line.startswith("- "):
raise SystemExit(f"{volumes_file}:{lineno}: expected '- key: value'")
try:
item = ast.literal_eval("{" + line[2:] + "}")
except Exception as e:
raise SystemExit(f"{volumes_file}:{lineno}: could not parse entry: {e}")
if not isinstance(item, dict) or len(item) != 1:
raise SystemExit(f"{volumes_file}:{lineno}: expected exactly one key/value pair")
volumes.update(item)
cwd = canonicalize(cwd)
for host_cwd, notes_dir in volumes.items():
if canonicalize(str(host_cwd)) == cwd:
print(canonicalize(str(notes_dir)))
break
PY
)
if [ -n "$PROJECT_ORG_NOTES" ]; then
EXTRA_VOLUMES+=(-v "$PROJECT_ORG_NOTES:/workspace-notes:ro")
EXTRA_PI_ARGS+=(--append-system-prompt "Additional read-only project notes are mounted at /workspace-notes. Use them when relevant, but do not edit them.")
>&2 echo "INFO: Mounting project notes read-only: $PROJECT_ORG_NOTES -> /workspace-notes"
fi
fi
# Find the project root by looking for .git, .project, or .projectile
# upward from PWD, stopping at $HOME or /
PROJECT_ROOT=""
curr="$PWD"
while true; do
if [ -d "$curr/.git" ] || [ -f "$curr/.project" ] || [ -f "$curr/.projectile" ]; then
PROJECT_ROOT="$curr"
break
fi
[ "$curr" = "/" ] || [ "$curr" = "$HOME" ] && break
curr=$(dirname "$curr")
done
if [ -z "$PROJECT_ROOT" ]; then
PROJECT_ROOT="$PWD"
fi
# Canonicalize PROJECT_ROOT for session directory naming to avoid everything being in --workspace--
# Matches logic in session-manager.js: cwd.replace(/^[/\\]/, "").replace(/[/\\:]/g, "-")
CWD_SAFE=$(echo "$PROJECT_ROOT" | sed 's|^[/\\]||' | sed 's|[/\\:]|-|g')
SESSION_DIR="/home/pi/.pi/agent/sessions/--${CWD_SAFE}--"
SESSION_DIR_CMD=(--session-dir "$SESSION_DIR")
# If first arg is a command, don't use TOOLS or SESSION_DIR_CMD
case "$1" in
install|remove|update|list|config)
TOOLS=""
SESSION_DIR_CMD=()
EXTRA_PI_ARGS=()
;;
esac
# Calculate relative path from PROJECT_ROOT to PWD
REL_PATH=${PWD:${#PROJECT_ROOT}}
REL_PATH=${REL_PATH#/}
>&2 echo "INFO: Using project root: $PROJECT_ROOT"
if [ -n "$REL_PATH" ]; then
>&2 echo "INFO: Using relative path: $REL_PATH"
fi
if [ "$MOUNT_MODE" = "ro" ]; then
>&2 echo "INFO: Mounting /workspace as READ-ONLY"
fi
if [ ${#DOCKER_PORT_ARGS[@]} -gt 0 ]; then
>&2 echo "INFO: Publishing Docker ports: ${DOCKER_PORT_ARGS[*]}"
fi
>&2 echo "_____________________________________________"
# Determine if we are in an interactive terminal
INTERACTIVE_FLAGS=""
if [ -t 0 ] && [ -t 1 ]; then
INTERACTIVE_FLAGS="-it"
else
>&2 echo "INFO: Runnin in non-interactive mode."
fi
docker run --rm $INTERACTIVE_FLAGS \
"${DOCKER_PORT_ARGS[@]}" \
-v "$PROJECT_ROOT":/workspace:$MOUNT_MODE \
-v "$SCRIPT_DIR/pi":/home/pi/.pi:rw \
-v "$SCRIPT_DIR/.cache/checkouts":/home/pi/.cache/checkouts:rw \
-v "$SCRIPT_DIR/.cache/gondolin":/home/pi/.cache/gondolin:rw \
-v "$ENTRYPOINT_FILE":/usr/local/bin/entrypoint.sh:ro \
"${EXTRA_VOLUMES[@]}" \
-w "/workspace/$REL_PATH" \
-e PI_PROJECT_ROOT="$PROJECT_ROOT" \
-e PI_MOUNT_MODE="$MOUNT_MODE" \
-e PI_HOST_HOSTNAME="$(hostname)" \
${BOT_SENTRY_TOKEN:+-e BOT_SENTRY_TOKEN} \
${PI_SUDO_PASSWORD:+-e PI_SUDO_PASSWORD} \
${ANTHROPIC_API_KEY:+-e ANTHROPIC_API_KEY} \
${OPENAI_API_KEY:+-e OPENAI_API_KEY} \
${GEMINI_API_KEY:+-e GEMINI_API_KEY} \
${MISTRAL_API_KEY:+-e MISTRAL_API_KEY} \
${HF_TOKEN:+-e HF_TOKEN} \
${OPENROUTER_API_KEY:+-e OPENROUTER_API_KEY} \
${PI_CACHE_RETENTION:+-e PI_CACHE_RETENTION} \
--env-file "$SCRIPT_DIR/.env" $DEBUGFLAGS \
pi-coding-agent $TOOLS "${SESSION_DIR_CMD[@]}" "${EXTRA_PI_ARGS[@]}" "${@}"