-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagent-manager.sh
More file actions
executable file
·1395 lines (1247 loc) · 51.8 KB
/
agent-manager.sh
File metadata and controls
executable file
·1395 lines (1247 loc) · 51.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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
# =============================================================================
# agent-manager — Manage your agent server from your LOCAL machine
# =============================================================================
# Usage:
# ./agent-manager.sh Show server status (default)
# ./agent-manager.sh --wakeup Start a stopped instance, wait for SSH
# ./agent-manager.sh --sleep Stop a running instance
# ./agent-manager.sh --always-on Switch to always-on mode (remove scheduler)
# ./agent-manager.sh --scheduled [N] [H] [WH] Switch to scheduled mode (every N min, hours H, weekend WH)
# ./agent-manager.sh --run-agent Trigger an agent run (fire and forget)
# ./agent-manager.sh --history [N] Show wake/sleep/run timeline (last N days, default 7)
# ./agent-manager.sh --log [N] Show Nth most recent orchestrator log (default: latest)
# ./agent-manager.sh --trigger Show remote trigger URL and token
# ./agent-manager.sh --ssh SSH into the server
# ./agent-manager.sh --ssh-mcp SSH with MCP port forwarding (for auth)
# ./agent-manager.sh --help Show this help
#
# Reads deploy-state.json (created by deploy.sh) for instance details.
# =============================================================================
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
STATE_FILE="${SCRIPT_DIR}/deploy-state.json"
# --- Colors ------------------------------------------------------------------
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
CYAN='\033[0;36m'
BOLD='\033[1m'
DIM='\033[2m'
NC='\033[0m'
log() { echo -e "${GREEN}[AGENT]${NC} $1"; }
warn() { echo -e "${YELLOW}[NOTE]${NC} $1"; }
err() { echo -e "${RED}[ERROR]${NC} $1"; }
# --- Pre-flight: required tools ---------------------------------------------
check_tools() {
local missing=()
command -v aws &>/dev/null || missing+=("aws (AWS CLI — https://aws.amazon.com/cli/)")
command -v python3 &>/dev/null || missing+=("python3")
command -v ssh &>/dev/null || missing+=("ssh")
command -v scp &>/dev/null || missing+=("scp")
if [[ ${#missing[@]} -gt 0 ]]; then
err "Missing required tools:"
for tool in "${missing[@]}"; do
echo -e " ${RED}✗${NC} ${tool}"
done
echo ""
echo "Install the missing tools and try again."
exit 1
fi
}
check_tools
# --- Load configuration -----------------------------------------------------
# Source agent.conf so SCHEDULE_* variables are available to all commands.
if [[ -f "${SCRIPT_DIR}/agent.conf" ]]; then
source "${SCRIPT_DIR}/agent.conf"
fi
# --- Load state --------------------------------------------------------------
load_state() {
if [[ ! -f "${STATE_FILE}" ]]; then
err "deploy-state.json not found. Run deploy.sh first."
exit 1
fi
INSTANCE_ID=$(python3 -c "import json; print(json.load(open('${STATE_FILE}'))['instance_id'])")
REGION=$(python3 -c "import json; print(json.load(open('${STATE_FILE}'))['region'])")
SSH_HOST=$(python3 -c "import json; print(json.load(open('${STATE_FILE}'))['ssh_config_host'])")
ELASTIC_IP=$(python3 -c "import json; print(json.load(open('${STATE_FILE}'))['elastic_ip'])")
OWNER=$(python3 -c "import json; print(json.load(open('${STATE_FILE}'))['owner'])")
}
# --- JSON helpers for deploy-state.json --------------------------------------
json_get() {
python3 -c "import json,sys; d=json.load(open(sys.argv[1])); print(d.get(sys.argv[2],''))" \
"${STATE_FILE}" "$1"
}
# --- Get instance state ------------------------------------------------------
get_instance_state() {
aws ec2 describe-instances \
--instance-ids "${INSTANCE_ID}" \
--region "${REGION}" \
--query 'Reservations[0].Instances[0].State.Name' \
--output text 2>/dev/null || echo "unknown"
}
# --- Check if SSH failure is caused by an IP change --------------------------
# Residential ISPs assign dynamic IPs via DHCP. Router reboots, power outages,
# or lease expiry can change the public IP, breaking the security group rule
# that was created at deploy time. This helper detects the mismatch and
# updates the rule automatically.
check_and_fix_ssh_ip() {
local sg_id
sg_id=$(json_get security_group_id)
if [[ -z "${sg_id}" ]]; then
return 1 # no SG info — can't help
fi
local my_ip
my_ip=$(curl -s --max-time 5 https://checkip.amazonaws.com)
if [[ -z "${my_ip}" ]]; then
return 1 # can't determine current IP
fi
# Get the current SSH rule's CIDR
local allowed_ip
allowed_ip=$(aws ec2 describe-security-groups \
--group-ids "${sg_id}" --region "${REGION}" \
--query 'SecurityGroups[0].IpPermissions[?FromPort==`22` && ToPort==`22`].IpRanges[0].CidrIp' \
--output text 2>/dev/null || echo "")
if [[ -z "${allowed_ip}" || "${allowed_ip}" == "None" ]]; then
return 1 # no SSH rule found
fi
local allowed_bare="${allowed_ip%/32}"
if [[ "${allowed_bare}" == "${my_ip}" ]]; then
return 1 # IPs match — SSH failure is something else
fi
warn "Your IP has changed: ${allowed_bare} → ${my_ip}"
warn "Updating security group ${sg_id}..."
# Revoke old rule, add new one
aws ec2 revoke-security-group-ingress \
--group-id "${sg_id}" --region "${REGION}" \
--protocol tcp --port 22 --cidr "${allowed_ip}" >/dev/null 2>&1 || true
aws ec2 authorize-security-group-ingress \
--group-id "${sg_id}" --region "${REGION}" \
--protocol tcp --port 22 \
--cidr "${my_ip}/32" >/dev/null 2>&1 || {
err "Failed to update security group SSH rule."
return 1
}
log "SSH rule updated to ${my_ip}/32."
return 0
}
# --- Commands ----------------------------------------------------------------
cmd_status() {
local state
state=$(get_instance_state)
echo ""
echo -e "${BOLD} Agent Server — ${OWNER}${NC}"
echo " ─────────────────────────────────"
echo -e " Instance: ${INSTANCE_ID}"
echo -e " Region: ${REGION}"
echo -e " Elastic IP: ${ELASTIC_IP}"
# Instance state with color
case "${state}" in
running) echo -e " State: ${GREEN}running${NC}" ;;
stopped) echo -e " State: ${DIM}stopped${NC}" ;;
stopping) echo -e " State: ${YELLOW}stopping${NC}" ;;
pending) echo -e " State: ${YELLOW}starting${NC}" ;;
*) echo -e " State: ${RED}${state}${NC}" ;;
esac
# Schedule info (agent.conf sourced at top level)
local mode="${SCHEDULE_MODE:-unknown}"
if [[ "$mode" == "scheduled" ]]; then
local mode_detail="every ${SCHEDULE_INTERVAL:-60} min, hours ${SCHEDULE_HOURS:-6-22}"
if [[ -n "${SCHEDULE_WEEKEND_HOURS:-}" ]]; then
mode_detail+=", weekends ${SCHEDULE_WEEKEND_HOURS}"
fi
echo -e " Mode: ${CYAN}scheduled${NC} (${mode_detail})"
else
echo -e " Mode: ${CYAN}${mode}${NC}"
fi
# Fetch AWS cost estimates in background while SSH runs
local cost_file cost_tmp_dir
cost_file=$(mktemp)
cost_tmp_dir=$(mktemp -d)
(
end_date=$(date -u +%Y-%m-%d)
mtd_start=$(date -u +%Y-%m-01) # 1st of current month
# Cost Explorer: month-to-date by service (for actual + compute $/hour)
aws ce get-cost-and-usage \
--time-period "Start=${mtd_start},End=${end_date}" \
--granularity MONTHLY \
--metrics UnblendedCost \
--filter "{\"Dimensions\":{\"Key\":\"REGION\",\"Values\":[\"${REGION}\"]}}" \
--group-by Type=DIMENSION,Key=SERVICE \
--region us-east-1 \
--output json > "${cost_tmp_dir}/ce.json" 2>/dev/null || true
# CloudWatch: count hours the instance was running this month (each datapoint = 1 hour)
aws cloudwatch get-metric-statistics \
--namespace AWS/EC2 \
--metric-name CPUUtilization \
--dimensions "Name=InstanceId,Value=${INSTANCE_ID}" \
--start-time "${mtd_start}T00:00:00Z" \
--end-time "${end_date}T00:00:00Z" \
--period 3600 \
--statistics Average \
--region "${REGION}" \
--output json > "${cost_tmp_dir}/cw.json" 2>/dev/null || true
# Get average run duration from orchestrator logs on server
ssh -o ConnectTimeout=5 "${SSH_HOST}" "
for f in ~/logs/orchestrator-*.log; do
s=\$(head -1 \"\$f\" | sed 's/.*started at //' | sed 's/ ===//')
e=\$(stat -c %Y \"\$f\" 2>/dev/null)
s_epoch=\$(date -d \"\$s\" +%s 2>/dev/null)
if [ -n \"\$s_epoch\" ] && [ -n \"\$e\" ]; then
echo \$(( e - s_epoch ))
fi
done" > "${cost_tmp_dir}/run_secs.txt" 2>/dev/null || true
if [[ -s "${cost_tmp_dir}/ce.json" ]]; then
python3 - "${SCHEDULE_HOURS:-6-22}" "${SCHEDULE_INTERVAL:-60}" "${SCHEDULE_WEEKEND_HOURS:-}" \
"${cost_tmp_dir}/ce.json" "${cost_tmp_dir}/cw.json" "${cost_tmp_dir}/run_secs.txt" \
> "${cost_file}" 2>/dev/null << 'PYEOF'
import json, sys, os
from datetime import date
schedule_hours = sys.argv[1]
schedule_interval = int(sys.argv[2])
weekend_hours = sys.argv[3]
with open(sys.argv[4]) as f:
cost_data = json.load(f)
cw_data = {}
if os.path.getsize(sys.argv[5]) > 0:
with open(sys.argv[5]) as f:
cw_data = json.load(f)
# Average run duration from orchestrator logs (seconds per wake)
run_secs = []
if os.path.exists(sys.argv[6]):
with open(sys.argv[6]) as f:
for line in f:
s = line.strip()
if s.isdigit() and 0 < int(s) < 18000: # sanity: < 5h
run_secs.append(int(s))
# Add ~2 min boot overhead per wake; use actual avg or fallback to 5 min total
if run_secs:
avg_wake_min = (sum(run_secs) / len(run_secs)) / 60 + 2 # run + boot overhead
else:
avg_wake_min = 5 # fallback
# --- Month-to-date actual cost ---
compute_total = 0.0
fixed_total = 0.0
for r in cost_data.get("ResultsByTime", []):
for g in r.get("Groups", []):
svc = g["Keys"][0]
amt = float(g["Metrics"]["UnblendedCost"]["Amount"])
if "Compute" in svc:
compute_total += amt
else:
fixed_total += amt
mtd_total = compute_total + fixed_total
if mtd_total < 0.001:
sys.exit(0)
today = date.today()
day_of_month = today.day
import calendar
days_in_month = calendar.monthrange(today.year, today.month)[1]
# --- Schedule projection ---
# Derive compute $/hour from actual spend and CloudWatch uptime hours
running_hours = len(cw_data.get("Datapoints", []))
if running_hours > 0 and compute_total > 0:
compute_per_hour = compute_total / running_hours
fixed_daily = fixed_total / day_of_month
# Calculate scheduled run-hours per week using actual wake duration
h_start, h_end = (int(x) for x in schedule_hours.split("-"))
weekday_active = h_end - h_start + 1
if schedule_interval < 60:
wakes_per_day = weekday_active * (60 / schedule_interval)
else:
wakes_per_day = weekday_active / (schedule_interval / 60)
weekday_run_hours = wakes_per_day * (avg_wake_min / 60)
if weekend_hours:
weekend_wakes = len(weekend_hours.split(","))
weekend_run_hours = weekend_wakes * (avg_wake_min / 60)
else:
weekend_run_hours = weekday_run_hours
weekly_run_hours = (weekday_run_hours * 5) + (weekend_run_hours * 2)
monthly_run_hours = weekly_run_hours * (30 / 7)
projected_monthly = (compute_per_hour * monthly_run_hours) + (fixed_daily * days_in_month)
print(f"${mtd_total:.1f} MTD (day {day_of_month}/{days_in_month}) \u00b7 ${projected_monthly:.0f}/mo projected (~{avg_wake_min:.0f} min/run)")
else:
print(f"${mtd_total:.1f} MTD (day {day_of_month}/{days_in_month})")
PYEOF
fi
rm -rf "${cost_tmp_dir}"
) &
local cost_pid=$!
# If running, try to get on-server status
if [[ "${state}" == "running" ]]; then
check_and_fix_ssh_ip || true
echo ""
local remote_status
remote_status=$(ssh -o ConnectTimeout=5 "${SSH_HOST}" "agent status" 2>/dev/null) || true
if [[ -n "${remote_status}" ]]; then
echo "${remote_status}"
else
echo -e " ${DIM}(could not reach server via SSH)${NC}"
fi
fi
# Show cost estimate (wait up to 5s for background query)
wait "${cost_pid}" 2>/dev/null || true
local cost_estimate
cost_estimate=$(cat "${cost_file}" 2>/dev/null)
rm -f "${cost_file}"
if [[ -n "${cost_estimate}" ]]; then
echo ""
echo -e " Est. cost: ${CYAN}${cost_estimate}${NC}"
fi
echo ""
echo -e " ${DIM}Commands: --wakeup, --sleep, --run-agent, --trigger, --log, --history, --scheduled, --ssh${NC}"
echo ""
}
cmd_wakeup() {
local state
state=$(get_instance_state)
if [[ "${state}" == "running" ]]; then
log "Instance is already running."
log "SSH: ssh ${SSH_HOST}"
return 0
elif [[ "${state}" == "pending" ]]; then
log "Instance is already starting up..."
elif [[ "${state}" == "stopping" ]]; then
warn "Instance is still stopping. Waiting for it to fully stop..."
aws ec2 wait instance-stopped --instance-ids "${INSTANCE_ID}" --region "${REGION}"
log "Instance stopped. Starting it now..."
aws ec2 start-instances --instance-ids "${INSTANCE_ID}" --region "${REGION}" >/dev/null
elif [[ "${state}" == "stopped" ]]; then
log "Starting instance ${INSTANCE_ID}..."
aws ec2 start-instances --instance-ids "${INSTANCE_ID}" --region "${REGION}" >/dev/null
else
err "Instance is in unexpected state: ${state}"
return 1
fi
log "Waiting for instance to be running..."
aws ec2 wait instance-running --instance-ids "${INSTANCE_ID}" --region "${REGION}"
log "Instance is running."
log "Waiting for SSH..."
local ssh_ok=false
for i in $(seq 1 30); do
if ssh -o ConnectTimeout=5 "${SSH_HOST}" "echo ready" 2>/dev/null; then
ssh_ok=true
break
fi
# After 30s of failures, check if IP changed before waiting the full 150s
if [[ $i -eq 6 ]]; then
if check_and_fix_ssh_ip; then
# IP was updated — retry SSH immediately
for j in $(seq 1 24); do
if ssh -o ConnectTimeout=5 "${SSH_HOST}" "echo ready" 2>/dev/null; then
ssh_ok=true
break 2
fi
sleep 5
done
fi
fi
sleep 5
done
if [[ "${ssh_ok}" != "true" ]]; then
warn "SSH not available after 150 seconds. Try manually: ssh ${SSH_HOST}"
return 1
fi
# In scheduled mode, immediately create keep-running lock to prevent the
# orchestrator's active-hours guard from hibernating before we can act.
if [[ "${SCHEDULE_MODE:-always-on}" == "scheduled" ]]; then
ssh -o ConnectTimeout=5 "${SSH_HOST}" 'mkdir -p ~/agents && touch ~/agents/.keep-running' 2>/dev/null || true
log "Keep-running lock set (prevents auto-hibernate)."
fi
echo ""
log "Server is ready."
log "SSH: ssh ${SSH_HOST}"
if [[ "${SCHEDULE_MODE:-always-on}" == "scheduled" ]]; then
echo ""
warn "Keep-running lock is active. Server will NOT self-stop."
warn "To release: ssh ${SSH_HOST} 'rm ~/agents/.keep-running'"
fi
echo ""
}
cmd_sleep() {
local state
state=$(get_instance_state)
if [[ "${state}" == "stopped" ]]; then
log "Instance is already stopped."
return 0
elif [[ "${state}" == "stopping" ]]; then
log "Instance is already stopping..."
return 0
elif [[ "${state}" != "running" ]]; then
err "Instance is in state '${state}' — can only stop a running instance."
return 1
fi
# Proactive IP check before SSH
check_and_fix_ssh_ip || true
# In scheduled mode, check if orchestrator is running — it will self-stop when done.
if [[ "${SCHEDULE_MODE:-always-on}" == "scheduled" ]]; then
local lock_held
lock_held=$(ssh -o ConnectTimeout=5 "${SSH_HOST}" \
"flock -n ~/.agent-orchestrator.lock true 2>/dev/null && echo free || echo held" 2>/dev/null || echo "unknown")
if [[ "${lock_held}" == "held" ]]; then
# Remove keep-running so it self-stops after the run
ssh -o ConnectTimeout=5 "${SSH_HOST}" 'rm -f ~/agents/.keep-running' 2>/dev/null || true
log "Orchestrator is running. It will self-stop when done."
echo -e " Monitor: ${CYAN}ssh ${SSH_HOST} 'tail -f ~/logs/orchestrator-*.log'${NC}"
return 0
fi
fi
# Remove keep-running lock before stopping
ssh -o ConnectTimeout=5 "${SSH_HOST}" 'rm -f ~/agents/.keep-running' 2>/dev/null || true
log "Hibernating instance ${INSTANCE_ID}..."
aws ec2 stop-instances --instance-ids "${INSTANCE_ID}" --region "${REGION}" --hibernate >/dev/null 2>&1 || {
warn "Hibernate not available, falling back to stop..."
aws ec2 stop-instances --instance-ids "${INSTANCE_ID}" --region "${REGION}" >/dev/null
}
log "Hibernate/stop command sent. Instance will freeze shortly."
}
cmd_ssh() {
local state
state=$(get_instance_state)
if [[ "${state}" != "running" ]]; then
err "Instance is ${state}. Use --wakeup first."
return 1
fi
# Proactive IP check — update security group if our IP changed
check_and_fix_ssh_ip || true
exec ssh "${SSH_HOST}"
}
cmd_always_on() {
local state
state=$(get_instance_state)
# Switch mode on the server
if [[ "${state}" == "running" ]]; then
log "Setting server to always-on mode..."
ssh -o ConnectTimeout=5 "${SSH_HOST}" "sudo ~/scripts/set-schedule-mode.sh always-on" 2>/dev/null || true
else
warn "Instance is ${state}. Mode will be set on next boot."
fi
# Remove EventBridge scheduler
log "Removing EventBridge scheduler..."
if [[ -f "${SCRIPT_DIR}/deploy-scheduler.sh" ]]; then
bash "${SCRIPT_DIR}/deploy-scheduler.sh" --remove "${REGION}"
else
warn "deploy-scheduler.sh not found. Remove scheduler manually."
fi
# Update local agent.conf
if [[ -f "${SCRIPT_DIR}/agent.conf" ]]; then
sed -i.bak 's/^SCHEDULE_MODE=.*/SCHEDULE_MODE="always-on"/' "${SCRIPT_DIR}/agent.conf"
rm -f "${SCRIPT_DIR}/agent.conf.bak"
log "Updated agent.conf: SCHEDULE_MODE=\"always-on\""
fi
# Ensure instance is running
if [[ "${state}" == "stopped" ]]; then
log "Starting instance (always-on means it should be running)..."
cmd_wakeup
fi
echo ""
log "Mode switched to always-on. Instance will run 24/7."
}
cmd_scheduled() {
local interval="${1:-60}"
local hours="${2:-${SCHEDULE_HOURS:-6-22}}"
local weekend_hours="${3:-${SCHEDULE_WEEKEND_HOURS:-}}"
local state
state=$(get_instance_state)
# Switch mode on the server (pass interval, hours, and weekend hours)
if [[ "${state}" == "running" ]]; then
log "Setting server to scheduled mode..."
ssh -o ConnectTimeout=5 "${SSH_HOST}" "sudo ~/scripts/set-schedule-mode.sh scheduled ${interval} ${hours} ${weekend_hours}" 2>/dev/null || true
else
warn "Instance is ${state}. Mode will be set on next boot."
fi
# Deploy EventBridge scheduler (with hours and weekend hours)
log "Deploying EventBridge scheduler..."
if [[ -f "${SCRIPT_DIR}/deploy-scheduler.sh" ]]; then
bash "${SCRIPT_DIR}/deploy-scheduler.sh" "${INSTANCE_ID}" "${interval}" "${REGION}" "${hours}" "${weekend_hours}"
else
err "deploy-scheduler.sh not found."
return 1
fi
# Update local agent.conf
if [[ -f "${SCRIPT_DIR}/agent.conf" ]]; then
sed -i.bak 's/^SCHEDULE_MODE=.*/SCHEDULE_MODE="scheduled"/' "${SCRIPT_DIR}/agent.conf"
sed -i.bak "s/^SCHEDULE_INTERVAL=.*/SCHEDULE_INTERVAL=${interval}/" "${SCRIPT_DIR}/agent.conf"
if grep -q '^SCHEDULE_HOURS=' "${SCRIPT_DIR}/agent.conf"; then
sed -i.bak "s/^SCHEDULE_HOURS=.*/SCHEDULE_HOURS=\"${hours}\"/" "${SCRIPT_DIR}/agent.conf"
fi
if [[ -n "${weekend_hours}" ]]; then
if grep -q '^SCHEDULE_WEEKEND_HOURS=' "${SCRIPT_DIR}/agent.conf"; then
sed -i.bak "s/^SCHEDULE_WEEKEND_HOURS=.*/SCHEDULE_WEEKEND_HOURS=\"${weekend_hours}\"/" "${SCRIPT_DIR}/agent.conf"
else
echo "SCHEDULE_WEEKEND_HOURS=\"${weekend_hours}\"" >> "${SCRIPT_DIR}/agent.conf"
fi
fi
rm -f "${SCRIPT_DIR}/agent.conf.bak"
log "Updated agent.conf"
fi
echo ""
log "Mode switched to scheduled."
echo ""
echo -e " ${BOLD}Both systems updated:${NC}"
if [[ -n "${weekend_hours}" ]]; then
echo -e " ${CYAN}EventBridge (weekdays):${NC} wakes instance every ${interval} min during hours ${hours}"
echo -e " ${CYAN}EventBridge (weekends):${NC} wakes instance at hours ${weekend_hours}"
echo -e " ${CYAN}Server cron:${NC} weekdays every ${interval} min (${hours}), weekends at ${weekend_hours}"
else
echo -e " ${CYAN}EventBridge:${NC} wakes instance every ${interval} min during hours ${hours}"
echo -e " ${CYAN}Server cron:${NC} runs orchestrator every ${interval} min during hours ${hours}"
fi
echo -e " ${CYAN}Active guard:${NC} cron runs only during active hours; boot/trigger/run-agent bypass"
echo ""
}
cmd_run_agent() {
local state
state=$(get_instance_state)
# Wake up if needed — but don't set .keep-running (we want the instance to
# self-stop after the run completes)
if [[ "${state}" != "running" ]]; then
log "Waking instance for agent run..."
if [[ "${state}" == "stopping" ]]; then
warn "Instance is still stopping. Waiting..."
aws ec2 wait instance-stopped --instance-ids "${INSTANCE_ID}" --region "${REGION}"
fi
aws ec2 start-instances --instance-ids "${INSTANCE_ID}" --region "${REGION}" >/dev/null
log "Waiting for instance to be running..."
aws ec2 wait instance-running --instance-ids "${INSTANCE_ID}" --region "${REGION}"
log "Waiting for SSH..."
local ssh_ok=false
for i in $(seq 1 30); do
if ssh -o ConnectTimeout=5 "${SSH_HOST}" "echo ready" 2>/dev/null; then
ssh_ok=true
break
fi
# After 30s of failures, check if IP changed
if [[ $i -eq 6 ]]; then
if check_and_fix_ssh_ip; then
for j in $(seq 1 24); do
if ssh -o ConnectTimeout=5 "${SSH_HOST}" "echo ready" 2>/dev/null; then
ssh_ok=true
break 2
fi
sleep 5
done
fi
fi
sleep 5
done
if [[ "${ssh_ok}" != "true" ]]; then
warn "SSH not available after 150 seconds."
return 1
fi
fi
# Check if orchestrator is already running (boot/resume may have started it)
local lock_held
lock_held=$(ssh -o ConnectTimeout=5 "${SSH_HOST}" \
"flock -n ~/.agent-orchestrator.lock true 2>/dev/null && echo free || echo held" || echo "free")
if [[ "${lock_held}" == "held" ]]; then
log "Orchestrator is already running (triggered on wake)."
if [[ "${SCHEDULE_MODE:-always-on}" == "scheduled" ]]; then
echo -e " It will self-stop (hibernate) after completing tasks."
fi
echo -e " Monitor: ${CYAN}ssh ${SSH_HOST} 'tail -f ~/logs/orchestrator-*.log'${NC}"
return 0
fi
# Trigger orchestrator in background (--force bypasses active-hours guard
# since this is an explicit manual action; instance still self-stops after)
log "Starting agent orchestrator..."
local pid
pid=$(ssh -o ConnectTimeout=5 "${SSH_HOST}" \
"nohup ~/scripts/agent-orchestrator.sh --force </dev/null >> ~/logs/cron-orchestrator.log 2>&1 & echo \$!" 2>/dev/null)
# Brief wait, then confirm via lock
sleep 2
local running
running=$(ssh -o ConnectTimeout=5 "${SSH_HOST}" \
"flock -n ~/.agent-orchestrator.lock true 2>/dev/null && echo free || echo held" || echo "free")
if [[ "${running}" == "held" ]]; then
log "Orchestrator started."
echo ""
echo -e " The agent is running in the background."
if [[ "${SCHEDULE_MODE:-always-on}" == "scheduled" ]]; then
echo -e " It will self-stop (hibernate) after completing tasks."
else
echo -e " Instance stays running after tasks complete (always-on mode)."
fi
echo ""
echo -e " Monitor: ${CYAN}ssh ${SSH_HOST} 'tail -f ~/logs/orchestrator-*.log'${NC}"
else
err "Orchestrator may not have started. Check: ssh ${SSH_HOST} 'agent status'"
fi
echo ""
}
cmd_ssh_mcp() {
local state
state=$(get_instance_state)
if [[ "${state}" != "running" ]]; then
err "Instance is ${state}. Use --wakeup first."
return 1
fi
# Proactive IP check — update security group if our IP changed
check_and_fix_ssh_ip || true
log "Connecting with MCP port forwarding (18850-18852)..."
exec ssh -L 18850:127.0.0.1:18850 -L 18851:127.0.0.1:18851 -L 18852:127.0.0.1:18852 "${SSH_HOST}"
}
cmd_history() {
local days="${1:-7}"
# Compute time range (python3 for cross-platform date math)
local start_time end_time
end_time=$(date -u +%Y-%m-%dT%H:%M:%SZ)
start_time=$(python3 -c "from datetime import datetime,timedelta,timezone; print((datetime.now(timezone.utc)-timedelta(days=${days})).strftime('%Y-%m-%dT00:00:00Z'))")
# Read timezone from deploy-state.json
local tz_name="UTC"
if [[ -f "${STATE_FILE}" ]]; then
tz_name=$(python3 -c "import json; print(json.load(open('${STATE_FILE}')).get('timezone','UTC'))" 2>/dev/null || echo "UTC")
fi
log "Fetching instance activity for the last ${days} days (${tz_name})..."
# Get CloudWatch CPUUtilization (hourly) — data point exists = instance was awake
local cw_file
cw_file=$(mktemp)
aws cloudwatch get-metric-statistics \
--namespace AWS/EC2 \
--metric-name CPUUtilization \
--dimensions "Name=InstanceId,Value=${INSTANCE_ID}" \
--start-time "${start_time}" \
--end-time "${end_time}" \
--period 3600 \
--statistics Maximum \
--region "${REGION}" \
--output json > "${cw_file}" 2>/dev/null || echo '{"Datapoints":[]}' > "${cw_file}"
# Get orchestrator run timestamps and events.
# Primary: SSH to server for detailed logs (if running).
# Fallback: CloudTrail Start/Stop events (always available, even when stopped).
local run_file events_file
run_file=$(mktemp)
events_file=$(mktemp)
local state
state=$(get_instance_state)
local got_ssh_data=false
if [[ "${state}" == "running" ]]; then
if ssh -o ConnectTimeout=5 "${SSH_HOST}" \
"ls -1 ~/logs/orchestrator-*.log 2>/dev/null | sed 's/.*orchestrator-//' | sed 's/\.log//' | tail -500" \
> "${run_file}" 2>/dev/null; then
got_ssh_data=true
fi
# For single-day view, get detailed event timestamps from logs
if [[ "${got_ssh_data}" == "true" && "${days}" -eq 1 ]]; then
local today_str
today_str=$(date +%Y%m%d)
ssh -o ConnectTimeout=10 "${SSH_HOST}" "
for f in ~/logs/orchestrator-${today_str}*.log; do
[ -f \"\$f\" ] || continue
ts=\$(basename \"\$f\" .log | sed 's/orchestrator-//')
echo \"START:\${ts}\"
# File modification time as proxy for end/hibernate time
echo \"ENDTIME:\$(stat -c '%Y' \"\$f\" 2>/dev/null || stat -f '%m' \"\$f\" 2>/dev/null)\"
# Get the 'Claude Code finished' line with exit code
grep -m1 'Claude Code finished' \"\$f\" 2>/dev/null && true
# Check for hibernate/stop events
grep -m1 'hibernating instance\|Falling back to shutdown\|Outside active hours' \"\$f\" 2>/dev/null && true
done
" > "${events_file}" 2>/dev/null || true
fi
fi
# CloudTrail Start/Stop events — always fetched.
# When SSH data is available, CloudTrail supplements the events view with
# trigger/wakeup events that didn't produce orchestrator logs.
# When SSH is unavailable, CloudTrail is the sole data source.
local ct_file
ct_file=$(mktemp)
aws cloudtrail lookup-events \
--lookup-attributes "AttributeKey=ResourceName,AttributeValue=${INSTANCE_ID}" \
--start-time "${start_time}" \
--end-time "${end_time}" \
--max-results 200 \
--region "${REGION}" \
--output json > "${ct_file}" 2>/dev/null || echo '{"Events":[]}' > "${ct_file}"
# Convert CloudTrail events into run timestamps and event details.
# Timestamps are converted to the server's local timezone so the rendering
# code (which treats them as naive local times) displays correct hours.
#
# Mode: "supplement" — SSH logs are primary; only add non-overlapping events.
# "primary" — no SSH data; CloudTrail is the sole source.
local ct_mode="primary"
[[ "${got_ssh_data}" == "true" ]] && ct_mode="supplement"
python3 - "${ct_file}" "${run_file}" "${events_file}" "${days}" "${tz_name}" "${ct_mode}" << 'CT_PYEOF'
import json, sys
from datetime import datetime, timezone
ct_file, run_file, events_file, days_str, tz_name, ct_mode = sys.argv[1:7]
days = int(days_str)
try:
from zoneinfo import ZoneInfo
local_tz = ZoneInfo(tz_name)
except (ImportError, KeyError):
local_tz = timezone.utc
with open(ct_file) as f:
ct_data = json.load(f)
scheduled_starts = [] # EventBridge-triggered (= agent ran)
trigger_starts = [] # Remote trigger (Lambda) (= agent ran)
manual_starts = [] # Manual wakeups (= awake but no agent run)
noop_starts = set() # StartInstances where instance was already running
stops = []
def parse_ts(ts):
if isinstance(ts, str):
for fmt in ("%Y-%m-%dT%H:%M:%S%z", "%Y-%m-%dT%H:%M:%SZ"):
try:
dt = datetime.strptime(ts, fmt)
if dt.tzinfo is None:
dt = dt.replace(tzinfo=timezone.utc)
return dt.astimezone(local_tz)
except ValueError:
continue
elif isinstance(ts, (int, float)):
return datetime.fromtimestamp(ts, tz=timezone.utc).astimezone(local_tz)
return None
for ev in ct_data.get("Events", []):
name = ev.get("EventName", "")
dt = parse_ts(ev.get("EventTime", ""))
if dt is None:
continue
if name == "StartInstances":
# Distinguish scheduler-triggered, remote-triggered, and manual starts.
ce = json.loads(ev.get("CloudTrailEvent", "{}"))
ua = ce.get("userAgent", "")
arn = ce.get("userIdentity", {}).get("arn", "")
# Check if instance was already running (StartInstances was a no-op).
prev_state = ""
try:
items = ce.get("responseElements", {}).get("instancesSet", {}).get("items", [])
if items:
prev_state = items[0].get("previousState", {}).get("name", "")
except (AttributeError, IndexError, KeyError):
pass
if "EventBridge" in ua or "Scheduler" in ua:
scheduled_starts.append(dt)
elif "agent-server-trigger-role" in arn:
trigger_starts.append(dt)
else:
manual_starts.append(dt)
if prev_state == "running":
noop_starts.add(dt.strftime("%Y%m%d-%H%M%S"))
elif name == "StopInstances":
stops.append(dt)
scheduled_starts.sort()
trigger_starts.sort()
manual_starts.sort()
stops.sort()
all_starts = sorted(scheduled_starts + trigger_starts + manual_starts)
# Filter to only the requested date range (local time)
from datetime import timedelta
now_local = datetime.now(local_tz)
date_start = (now_local - timedelta(days=days)).replace(hour=0, minute=0, second=0, microsecond=0)
scheduled_starts = [s for s in scheduled_starts if s >= date_start]
trigger_starts = [s for s in trigger_starts if s >= date_start]
manual_starts = [s for s in manual_starts if s >= date_start]
all_starts = [s for s in all_starts if s >= date_start]
stops = [s for s in stops if s >= date_start]
if ct_mode == "primary":
# No SSH data — CloudTrail is the sole source for run timestamps.
# First line "SOURCE:cloudtrail" signals estimated data.
with open(run_file, "w") as rf:
rf.write("SOURCE:cloudtrail\n")
for s in scheduled_starts:
ts = s.strftime("%Y%m%d-%H%M%S")
if ts not in noop_starts:
rf.write(ts + "\n")
for s in trigger_starts:
ts = s.strftime("%Y%m%d-%H%M%S")
if ts not in noop_starts:
rf.write(ts + "\n")
for s in manual_starts:
ts = s.strftime("%Y%m%d-%H%M%S")
if ts not in noop_starts:
rf.write("AWAKE:" + ts + "\n")
# For single-day view, build event pairs sorted chronologically.
# In supplement mode, merge CloudTrail events with existing SSH-based events,
# adding only start/stop events that don't overlap with orchestrator logs.
if days == 1:
today_str = now_local.strftime("%Y-%m-%d")
today_starts = [s for s in all_starts if s.strftime("%Y-%m-%d") == today_str]
today_stops = [s for s in stops if s.strftime("%Y-%m-%d") == today_str]
is_scheduled = set(s.strftime("%Y%m%d-%H%M%S") for s in scheduled_starts)
is_trigger = set(s.strftime("%Y%m%d-%H%M%S") for s in trigger_starts)
# Build a map from each start to its matching stop.
# Each stop pairs with the last start before it (not all starts before it).
start_to_stop = {}
stop_idx = 0
for si in range(len(today_starts)):
s = today_starts[si]
# A stop matches this start only if no later start exists before that stop.
next_start = today_starts[si + 1] if si + 1 < len(today_starts) else None
while stop_idx < len(today_stops):
st = today_stops[stop_idx]
if st <= s:
stop_idx += 1
continue
if next_start and st > next_start:
break # this stop is after the next start — belongs to a later group
start_to_stop[s] = st
stop_idx += 1
break
def write_start_event(ef, s, ts_str):
"""Write a START/TRIGGER/WAKEUP line, with NOOP_ prefix if already running."""
is_noop = ts_str in noop_starts
if ts_str in is_trigger:
prefix = "NOOP_TRIGGER" if is_noop else "TRIGGER"
elif ts_str in is_scheduled:
prefix = "NOOP_START" if is_noop else "START"
else:
prefix = "NOOP_WAKEUP" if is_noop else "WAKEUP"
ef.write(f"{prefix}:{ts_str}\n")
def write_stop_event(ef, s):
"""Write ENDTIME + hibernate line if this start has a matching stop."""
matching_stop = start_to_stop.get(s)
if matching_stop:
ef.write(f"ENDTIME:{int(matching_stop.timestamp())}\n")
ef.write("hibernating instance\n")
if ct_mode == "supplement":
# Read existing SSH-based events to find which hours already have entries.
existing_start_hours = set()
try:
with open(events_file) as ef:
for line in ef:
line = line.strip()
if line.startswith("START:") and len(line) >= 17:
# Extract hour from START:YYYYMMDD-HHMMSS
existing_start_hours.add(line[15:17])
except (FileNotFoundError, IOError):
pass
# Append CloudTrail events that don't overlap with existing orchestrator runs.
# A start is "overlapping" if there's an orchestrator log in the same hour.
with open(events_file, "a") as ef:
for s in today_starts:
hour_str = s.strftime("%H")
if hour_str in existing_start_hours:
continue # orchestrator log already covers this start
ts_str = s.strftime("%Y%m%d-%H%M%S")
write_start_event(ef, s, ts_str)
write_stop_event(ef, s)
else:
# Primary mode — write all events from CloudTrail
with open(events_file, "w") as ef:
for s in today_starts:
ts_str = s.strftime('%Y%m%d-%H%M%S')
write_start_event(ef, s, ts_str)
write_stop_event(ef, s)
CT_PYEOF
rm -f "${ct_file}"
# Render timeline with python3
python3 - "${days}" "${cw_file}" "${run_file}" "${tz_name}" "${events_file}" << 'PYEOF'
import json, sys, re
from datetime import datetime, timedelta, timezone
days = int(sys.argv[1])
with open(sys.argv[2]) as f:
cw_raw = json.load(f)
with open(sys.argv[3]) as f:
run_raw = f.read().strip()
tz_name = sys.argv[4]
events_file = sys.argv[5] if len(sys.argv) > 5 else ""
# Set up timezone
try:
from zoneinfo import ZoneInfo
local_tz = ZoneInfo(tz_name)
except (ImportError, KeyError):
local_tz = timezone.utc
# Compute displayed date range
now = datetime.now(local_tz)
display_dates = set()
for d in range(days):
day = now - timedelta(days=d)
display_dates.add(day.strftime("%Y-%m-%d"))
# Parse CloudWatch → set of (date_str, hour) in local time + CPU values
awake = set()
cpu_max = {}
for dp in cw_raw.get("Datapoints", []):
ts = dp["Timestamp"]
try:
dt = datetime.fromisoformat(ts)
if dt.tzinfo is None:
dt = dt.replace(tzinfo=timezone.utc)
except ValueError:
continue
local_dt = dt.astimezone(local_tz)
ds = local_dt.strftime("%Y-%m-%d")
if ds in display_dates:
key = (ds, local_dt.hour)
awake.add(key)
cpu_val = dp.get("Maximum", 0)
cpu_max[key] = max(cpu_max.get(key, 0), cpu_val)
# Parse orchestrator log filenames → set of (date_str, hour) + count per day.
# Lines prefixed with "AWAKE:" are manual wakeups (no agent run) from CloudTrail.
# A "SOURCE:cloudtrail" header means run counts are estimated (no SSH access).
runs = set()
from collections import Counter
runs_per_day = Counter()
estimated = False
for line in run_raw.split("\n"):
line = line.strip()
if line == "SOURCE:cloudtrail":
estimated = True
continue
is_awake_only = line.startswith("AWAKE:")
ts_str = line[6:] if is_awake_only else line
if len(ts_str) >= 15:
try:
dt = datetime.strptime(ts_str[:15], "%Y%m%d-%H%M%S")
ds = dt.strftime("%Y-%m-%d")
if ds in display_dates:
if is_awake_only:
awake.add((ds, dt.hour))
else:
runs.add((ds, dt.hour))
runs_per_day[ds] += 1
except ValueError:
pass
# When run data is estimated from CloudTrail (instance stopped, no SSH),
# use CloudWatch CPU to detect hours where the agent likely ran.
# CloudTrail only captures instance Start/Stop events, missing orchestrator