-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathdev.py
More file actions
executable file
·1868 lines (1676 loc) · 67.7 KB
/
Copy pathdev.py
File metadata and controls
executable file
·1868 lines (1676 loc) · 67.7 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 python3
import json
import os
import sys
import subprocess
import time
import signal
import argparse
import urllib.request
import urllib.error
import base64
import tempfile
import shutil
from pathlib import Path
PORT = 8008
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
API_DIR = os.path.join(ROOT_DIR, "api")
CICY_ROOT_DIR = os.path.expanduser("~/cicy-ai")
CICY_STATE_DIR = os.path.join(CICY_ROOT_DIR, ".cicy")
HOST_PROJECTS_DIR = os.path.expanduser("~/projects")
CICY_DOCKER_HOMES_DIR = os.path.expanduser("~/docker-homes")
CICY_GLOBAL_JSON_PATH = os.path.join(CICY_ROOT_DIR, "global.json")
CICY_PROXY_JSON_PATH = os.path.join(CICY_ROOT_DIR, "proxy.json")
DOCKER_HOME_DIR = "/home/cicy"
DOCKER_PROJECTS_DIR = f"{DOCKER_HOME_DIR}/projects"
LEGACY_PROXY_JSON_PATH = os.path.expanduser("~/proxy.json")
SQLITE_PATH = os.environ.get(
"SQLITE_PATH", os.path.join(CICY_ROOT_DIR, "db", "data.db")
)
GLOBAL_JSON_PATH = CICY_GLOBAL_JSON_PATH
PROXY_JSON_PATH = CICY_PROXY_JSON_PATH
VERSION_SYNC_SCRIPT = os.path.join(ROOT_DIR, "scripts", "sync-version.py")
AI_PROVIDER_ALIASES = {
"2000run": "2000Run",
"200run": "2000Run",
"cicyai": "cicyAi",
}
def load_global_json():
try:
with open(GLOBAL_JSON_PATH, "r", encoding="utf-8") as f:
return json.load(f)
except Exception:
return {}
def canonical_ai_provider_name(name):
value = str(name or "").strip()
if not value:
return ""
return AI_PROVIDER_ALIASES.get(value.lower(), value)
def default_ai_provider_config(name, data):
canonical = canonical_ai_provider_name(name)
cicy_ai_base = str(data.get("cicyAiUrl", "") or "").strip().rstrip("/")
cicy_ai_api = f"{cicy_ai_base}/v1" if cicy_ai_base else ""
defaults = {
"2000Run": {
"apiKey": data.get("2000RunApikey", ""),
"apiUrl": "http://2000.run:6543/v1",
"anthropicUrl": "http://2000.run:6543",
"defaultOpencodeModel": "gpt-5.4",
"defaultClaudeModel": "opus[1m]",
"codexModel": "gpt-5.4",
"openclawModel": "gpt-5.5",
"hermesModel": "gpt-5.5",
},
"cicyAi": {
"apiKey": data.get("cicyAiapikey", ""),
"apiUrl": cicy_ai_api or "https://cicy-ai.com/v1",
"anthropicUrl": cicy_ai_base or "https://cicy-ai.com",
"defaultOpencodeModel": "gpt-5.4",
"defaultClaudeModel": "opus[1m]",
"codexModel": "gpt-5.4",
"openclawModel": "gpt-5.5",
"hermesModel": "gpt-5.5",
},
}
return defaults.get(canonical, {})
def get_ai_provider_config(provider_name=""):
data = load_global_json()
ai = data.get("ai", {})
provider_map = ai.get("provider", {}) if isinstance(ai, dict) else {}
selected = (
canonical_ai_provider_name(
provider_name
or os.environ.get("CICY_AI_PROVIDER")
or (ai.get("currentProvider", "") if isinstance(ai, dict) else "")
or "cicyAi"
)
or "cicyAi"
)
config = dict(default_ai_provider_config(selected, data))
for key, value in provider_map.items() if isinstance(provider_map, dict) else []:
if canonical_ai_provider_name(key) != selected or not isinstance(value, dict):
continue
config.update({k: v for k, v in value.items() if v not in ("", None)})
if not config.get("apiUrl") and config.get("baseUrl"):
config["apiUrl"] = config["baseUrl"]
return selected, config
def get_ai_env_defaults(provider_name=""):
selected, config = get_ai_provider_config(provider_name)
return {
"CICY_AI_PROVIDER": selected,
"CICY_API_KEY": os.environ.get("CICY_API_KEY") or config.get("apiKey", ""),
"CICY_API_URL": os.environ.get("CICY_API_URL")
or config.get("apiUrl", "http://2000.run:6543/v1"),
"CICY_ANTHROPIC_URL": os.environ.get("CICY_ANTHROPIC_URL")
or config.get("anthropicUrl", "http://2000.run:6543"),
"CICY_DEFAULT_OPENCODE_MODEL": os.environ.get("CICY_DEFAULT_OPENCODE_MODEL")
or os.environ.get("CICY_DEFAULT_MODEL")
or config.get("defaultOpencodeModel")
or config.get("defaultModel", "gpt-5.4"),
"CICY_DEFAULT_CLAUDE_MODEL": os.environ.get("CICY_DEFAULT_CLAUDE_MODEL")
or os.environ.get("CICY_CLAUDE_MODEL")
or config.get("defaultClaudeModel")
or config.get("claudeModel", "opus[1m]"),
"CICY_CODEX_MODEL": os.environ.get("CICY_CODEX_MODEL")
or config.get("codexModel", "gpt-5.4"),
"CICY_OPENCLAW_MODEL": os.environ.get("CICY_OPENCLAW_MODEL")
or config.get("openclawModel", "gpt-5.5"),
"CICY_HERMES_MODEL": os.environ.get("CICY_HERMES_MODEL")
or config.get("hermesModel", "gpt-5.5"),
}
def get_cicy_api_key():
return get_ai_env_defaults().get("CICY_API_KEY", "")
def build_minimal_runtime_global_json():
source = load_global_json()
data = {}
token = get_local_api_token()
if token:
data["api_token"] = token
if "ai" in source and isinstance(source["ai"], dict):
data["ai"] = source["ai"]
# Do NOT mirror the host's providers block into the dev container. Leaving it
# absent makes `dev.py --docker` a clean environment: the Go backend seeds a
# fresh providers block on first boot (ensureDefaultProviders +
# ensureOpenCodeZenProvider) instead of inheriting the operator's host config.
return data
def load_proxy_json():
for path in (PROXY_JSON_PATH, LEGACY_PROXY_JSON_PATH):
try:
with open(path, "r", encoding="utf-8") as f:
data = json.load(f)
return data if isinstance(data, dict) else {}
except Exception:
continue
return {}
def build_runtime_proxy_json(shared_host="host.docker.internal"):
source = load_proxy_json()
profiles = source.get("ssh_proxies", [])
if not isinstance(profiles, list) or not profiles:
return {}
runtime_profiles = []
existing_names = set()
for item in profiles:
if not isinstance(item, dict):
continue
copied = dict(item)
runtime_profiles.append(copied)
name = str(copied.get("name", "") or "").strip()
if name:
existing_names.add(name)
for item in profiles:
if not isinstance(item, dict):
continue
name = str(item.get("name", "") or "").strip()
local_port = item.get("local_port")
if not name or not local_port:
continue
kind = str(item.get("kind", "") or "").strip()
source_mode = str((item.get("source") or {}).get("mode", "") or "").strip()
if kind in ("shared", "shared_only") or source_mode in (
"shared",
"shared_only",
):
continue
shared_name = f"{name}-shared"
if shared_name in existing_names:
continue
scheme = str(item.get("scheme", "") or "socks5").strip() or "socks5"
runtime_profiles.append(
{
"name": shared_name,
"kind": "shared_only",
"scheme": scheme,
"local_host": shared_host,
"local_port": local_port,
"proxy_url": f"{scheme}://{shared_host}:{local_port}",
"source": {
"mode": "shared",
"from": name,
},
}
)
existing_names.add(shared_name)
if not runtime_profiles:
return {}
return {"ssh_proxies": runtime_profiles}
def build_dev_runtime_home(container_name, home_dir=""):
if home_dir:
home_dir = os.path.abspath(os.path.expanduser(home_dir))
else:
os.makedirs(CICY_DOCKER_HOMES_DIR, exist_ok=True)
safe_name = (
"".join(
ch if ch.isalnum() or ch in ("-", "_") else "-"
for ch in str(container_name or "").strip()
).strip("-")
or "cicy-code-dev"
)
home_dir = os.path.join(CICY_DOCKER_HOMES_DIR, safe_name)
os.makedirs(home_dir, exist_ok=True)
for source_name in (".tmux.conf", ".cicy_tmux.conf"):
source_path = os.path.join(API_DIR, "mgr", source_name)
target_path = os.path.join(home_dir, source_name)
if os.path.isfile(source_path):
shutil.copy2(source_path, target_path)
bashrc_path = os.path.join(home_dir, ".bashrc")
bashrc_line = '[ -f "$HOME/.cicy_tmux.conf" ] && source "$HOME/.cicy_tmux.conf"'
bashrc = ""
if os.path.isfile(bashrc_path):
try:
with open(bashrc_path, "r", encoding="utf-8") as f:
bashrc = f.read()
except Exception:
bashrc = ""
if bashrc_line not in bashrc:
with open(bashrc_path, "a", encoding="utf-8") as f:
if bashrc and not bashrc.endswith("\n"):
f.write("\n")
f.write(bashrc_line + "\n")
runtime_root_dir = os.path.join(home_dir, "cicy-ai")
os.makedirs(runtime_root_dir, exist_ok=True)
global_json_path = os.path.join(runtime_root_dir, "global.json")
with open(global_json_path, "w", encoding="utf-8") as f:
json.dump(build_minimal_runtime_global_json(), f, ensure_ascii=False, indent=2)
f.write("\n")
os.chmod(global_json_path, 0o644)
proxy_json_path = os.path.join(runtime_root_dir, "proxy.json")
runtime_proxy_json = build_runtime_proxy_json()
if runtime_proxy_json:
with open(proxy_json_path, "w", encoding="utf-8") as f:
json.dump(runtime_proxy_json, f, ensure_ascii=False, indent=2)
f.write("\n")
os.chmod(proxy_json_path, 0o644)
else:
proxy_json_path = ""
return home_dir, global_json_path, proxy_json_path
def ensure_docker_home_writable(home_dir, runtime_image):
os.makedirs(home_dir, exist_ok=True)
for root, dirs, files in os.walk(home_dir):
for name in dirs:
try:
os.chmod(os.path.join(root, name), 0o777)
except OSError:
pass
for name in files:
try:
os.chmod(os.path.join(root, name), 0o666)
except OSError:
pass
try:
os.chmod(root, 0o777)
except OSError:
pass
subprocess.run(
[
"docker",
"run",
"--rm",
"--user",
"root",
"--entrypoint",
"sh",
"-v",
f"{os.path.abspath(home_dir)}:/target",
runtime_image,
"-lc",
"chmod -R a+rwX /target",
],
cwd=ROOT_DIR,
capture_output=True,
)
def seed_runtime_home_from_image(image_ref, home_dir):
openclaw_dir = os.path.join(home_dir, ".openclaw")
plugin_dir = os.path.join(openclaw_dir, "extensions", "openclaw-weixin")
if os.path.isdir(plugin_dir):
return
container_id = ""
temp_dir = tempfile.mkdtemp(prefix="cicy-openclaw-seed-")
try:
result = subprocess.run(
["docker", "create", image_ref],
capture_output=True,
text=True,
cwd=ROOT_DIR,
)
if result.returncode != 0 or not result.stdout.strip():
err = (result.stderr or result.stdout or "").strip()
print(f"[dev] failed to create seed container for {image_ref}: {err}")
return
container_id = result.stdout.strip()
copy_result = subprocess.run(
["docker", "cp", f"{container_id}:/home/cicy/.openclaw", temp_dir],
capture_output=True,
text=True,
cwd=ROOT_DIR,
)
if copy_result.returncode != 0:
err = (copy_result.stderr or copy_result.stdout or "").strip()
print(f"[dev] failed to seed runtime home from image: {err}")
return
seeded_dir = os.path.join(temp_dir, ".openclaw")
if not os.path.isdir(seeded_dir):
print("[dev] seed image missing /home/cicy/.openclaw")
return
if os.path.exists(openclaw_dir):
shutil.rmtree(openclaw_dir)
shutil.copytree(seeded_dir, openclaw_dir)
print(f"[dev] Seeded runtime home with image OpenClaw assets")
finally:
if container_id:
subprocess.run(
["docker", "rm", "-f", container_id], capture_output=True, cwd=ROOT_DIR
)
shutil.rmtree(temp_dir, ignore_errors=True)
def add_optional_file_mount(
volume_args, host_path, container_path, label, read_only=True
):
resolved = os.path.abspath(os.path.expanduser(host_path))
if not os.path.isfile(resolved):
print(f"[dev] Skip mount missing {label}: {resolved}")
return
suffix = ":ro" if read_only else ""
volume_args.extend(["-v", f"{resolved}:{container_path}{suffix}"])
mode_label = "ro" if read_only else "rw"
print(f"[dev] Mount host {label} ({mode_label}): {resolved} -> {container_path}")
def read_api_token_from_file(path):
try:
with open(path, "r", encoding="utf-8") as f:
data = json.load(f)
return str(data.get("api_token", "") or "").strip()
except Exception:
return ""
def get_local_api_token():
value = os.environ.get("CICY_API_TOKEN", "").strip()
if value:
return value
data = load_global_json()
return str(data.get("api_token", "") or "").strip()
def get_gateway_llm_creds():
"""Read the gateway LLM apiKey + endpoint from the host's default providers.
The dev container seeds its own clean providers block (host providers are not
mirrored), so defaultAnthropic/defaultOpenAi start with an empty apiKey. We
inject these as CICY_AI_GATEWAY_LLM_API_KEY / _ENDPOINT so the container's
applyGatewayEnvToDefaultProviders() can fill the seeded defaults. Returns the
first non-empty key found on defaultAnthropic, then defaultOpenAi.
"""
data = load_global_json()
providers = data.get("providers", {})
items = providers.get("items", []) if isinstance(providers, dict) else []
for want in ("defaultAnthropic", "defaultOpenAi"):
for it in items:
if isinstance(it, dict) and it.get("key") == want:
key = str(it.get("apiKey", "") or "").strip()
if key:
return key, str(it.get("url", "") or "").strip()
return "", ""
def get_cicy_cluster():
data = load_global_json().get("cicy-cluster", {})
return data if isinstance(data, dict) else {}
def get_images_config():
data = load_global_json().get("images", {})
return data if isinstance(data, dict) else {}
def get_cloudrun_env():
cluster = get_cicy_cluster()
env = os.environ.copy()
cloudrun_image = cluster.get("image", "") or cluster.get("image_repository", "")
ai_env = get_ai_env_defaults()
defaults = {
"PROJECT": cluster.get("project_id", ""),
"SERVICE": cluster.get("service", ""),
"REGION": cluster.get("region", ""),
"IMAGE": cloudrun_image,
"MEMORY": cluster.get("memory", "2Gi"),
"MAX_INSTANCES": cluster.get("max_instances", "1"),
"MIN_INSTANCES": cluster.get("min_instances", "1"),
"CONCURRENCY": cluster.get("concurrency", "1"),
"CICY_PUBLIC_URL": cluster.get("service_url", ""),
"CICY_API_TOKEN": cluster.get("api_token", ""),
"CICY_INSTANCE_KEY": cluster.get("instance_key", ""),
"CICY_INSTANCE_LABEL": cluster.get("instance_label", ""),
**ai_env,
}
for key, value in defaults.items():
if value and not env.get(key):
env[key] = str(value)
return env
def mask_secret(value, keep=4):
if not value:
return ""
if len(value) <= keep * 2:
return "*" * len(value)
return f"{value[:keep]}...{value[-keep:]}"
def validate_cloudrun_env(env):
required = ["PROJECT", "SERVICE", "REGION", "IMAGE", "CICY_API_TOKEN"]
missing = [key for key in required if not env.get(key)]
if missing:
print(f"[dev] missing Cloud Run config: {', '.join(missing)}")
print(f"[dev] checked env and {GLOBAL_JSON_PATH} -> cicy-cluster")
sys.exit(1)
def validate_cloudrun_list_env(env):
required = ["PROJECT", "REGION"]
missing = [key for key in required if not env.get(key)]
if missing:
print(f"[dev] missing Cloud Run list config: {', '.join(missing)}")
print(f"[dev] checked env and {GLOBAL_JSON_PATH} -> cicy-cluster")
sys.exit(1)
def print_cloudrun_summary(env):
print("[dev] Cloud Run config:")
print(f"[dev] project={env.get('PROJECT', '')}")
print(f"[dev] service={env.get('SERVICE', '')}")
print(f"[dev] region={env.get('REGION', '')}")
print(f"[dev] image={env.get('IMAGE', '')}")
print(f"[dev] memory={env.get('MEMORY', '')}")
print(f"[dev] min_instances={env.get('MIN_INSTANCES', '')}")
print(f"[dev] max_instances={env.get('MAX_INSTANCES', '')}")
print(f"[dev] concurrency={env.get('CONCURRENCY', '')}")
print(f"[dev] public_url={env.get('CICY_PUBLIC_URL', '')}")
print(f"[dev] instance_key={env.get('CICY_INSTANCE_KEY', '')}")
print(f"[dev] instance_label={env.get('CICY_INSTANCE_LABEL', '')}")
print(f"[dev] api_token={mask_secret(env.get('CICY_API_TOKEN', ''))}")
print(f"[dev] api_key={mask_secret(env.get('CICY_API_KEY', ''))}")
def print_access_urls(base_url, token, service_url=""):
if not base_url or not token:
return
open_url = f"{base_url.rstrip('/')}/?token={token}"
print(f"[dev] API Token: {token}")
print(f"[dev] Open URL: {open_url}")
if service_url and service_url.rstrip("/") != base_url.rstrip("/"):
print(f"[dev] Service URL: {service_url.rstrip('/')}/?token={token}")
def detect_public_ip():
# Bypass any HTTP(S)_PROXY env (e.g. 家宽 proxy) so we get this host's real
# public IP rather than the proxy's egress IP.
for cmd in (
["curl", "-fsS", "--max-time", "5", "--noproxy", "*", "ifconfig.me"],
["curl", "-fsS", "--max-time", "5", "--noproxy", "*", "https://api.ipify.org"],
):
try:
result = subprocess.run(cmd, capture_output=True, text=True, timeout=8)
if result.returncode == 0 and result.stdout.strip():
return result.stdout.strip()
except Exception:
pass
return ""
def get_version_info():
try:
result = subprocess.run(
["python3", VERSION_SYNC_SCRIPT, "--print-json"],
cwd=ROOT_DIR,
capture_output=True,
text=True,
timeout=30,
)
if result.returncode == 0 and result.stdout.strip():
data = json.loads(result.stdout)
return data if isinstance(data, dict) else {}
except Exception:
pass
return {}
def run_version_sync(version=""):
cmd = ["python3", VERSION_SYNC_SCRIPT]
version = str(version or "").strip()
if version:
cmd.extend(["--set", version])
result = subprocess.run(cmd, cwd=ROOT_DIR, capture_output=True, text=True)
if result.returncode != 0:
output = (result.stdout or "").strip()
err = (result.stderr or "").strip()
if output:
print(output)
if err:
print(err)
sys.exit(result.returncode or 1)
return get_version_info()
def get_binary_version():
info = get_version_info()
version = str(info.get("version", "")).strip()
if version:
return version
try:
result = subprocess.run(
["node", "-p", "require('./npm/package.json').version"],
cwd=ROOT_DIR,
capture_output=True,
text=True,
timeout=30,
)
if result.returncode == 0 and result.stdout.strip():
return result.stdout.strip()
except Exception:
pass
print("[dev] failed to read version from npm/package.json")
sys.exit(1)
def strip_image_tag(image_ref):
if not image_ref:
return ""
image_ref = image_ref.split("@", 1)[0]
slash = image_ref.rfind("/")
colon = image_ref.rfind(":")
if colon > slash:
return image_ref[:colon]
return image_ref
def get_image_tag(image_ref):
if not image_ref:
return ""
image_ref = image_ref.split("@", 1)[0]
slash = image_ref.rfind("/")
colon = image_ref.rfind(":")
if colon > slash:
return image_ref[colon + 1 :]
return ""
def load_versions_json():
path = os.path.join(ROOT_DIR, "versions.json")
try:
with open(path, "r", encoding="utf-8") as f:
data = json.load(f)
return data if isinstance(data, dict) else {}
except Exception:
return {}
def local_default_base_tag():
return str(load_versions_json().get("base", "") or "").strip() or "latest"
def prefer_local_base_image(image_ref):
value = str(image_ref or "").strip()
if value.startswith("ghcr.io/cicy-ai/cicy-code-base:"):
return f"cicy-code-base:{get_image_tag(value) or local_default_base_tag()}"
return value
def local_default_base_image():
data = load_global_json()
images = data.get("images", {}) if isinstance(data, dict) else {}
if isinstance(images, dict):
explicit = prefer_local_base_image(images.get("base", ""))
if explicit:
return explicit
repo = str(images.get("base_repository", "") or "").strip()
tag = str(images.get("base_tag", "") or "").strip()
if repo and tag:
if repo == "ghcr.io/cicy-ai/cicy-code-base":
return f"cicy-code-base:{tag}"
return f"{repo}:{tag}"
cluster = data.get("cicy-cluster", {}) if isinstance(data, dict) else {}
if isinstance(cluster, dict):
explicit = prefer_local_base_image(cluster.get("base_image", ""))
if explicit:
return explicit
return f"cicy-code-base:{local_default_base_tag()}"
def ensure_local_base_image_available():
base_image = os.environ.get("BASE_IMAGE", "").strip() or local_default_base_image()
if not base_image.startswith("cicy-code-base:"):
return
inspect = subprocess.run(
["docker", "image", "inspect", base_image], capture_output=True, text=True
)
if inspect.returncode == 0:
return
tag = get_image_tag(base_image) or local_default_base_tag()
print(f"[dev] Base image missing, building {base_image} ...")
result = subprocess.run(["./build.sh", "docker-base", tag], cwd=ROOT_DIR)
if result.returncode != 0:
print("[dev] docker base build failed")
sys.exit(1)
return ""
def get_dockerhub_username():
config_path = os.path.expanduser("~/.docker/config.json")
try:
with open(config_path, "r", encoding="utf-8") as f:
data = json.load(f)
except Exception:
return ""
auth = ((data.get("auths") or {}).get("https://index.docker.io/v1/") or {}).get(
"auth", ""
)
if not auth:
return ""
try:
raw = base64.b64decode(auth).decode("utf-8", "ignore")
except Exception:
return ""
return raw.split(":", 1)[0].strip()
def get_docker_image_repository():
explicit = os.environ.get("DOCKER_IMAGE_REPOSITORY", "").strip()
if explicit:
return strip_image_tag(explicit)
images = get_images_config()
runtime_image = images.get("runtime", "")
if isinstance(runtime_image, dict):
runtime_image = runtime_image.get("image", "")
runtime_image = str(runtime_image or "").strip()
if runtime_image:
return strip_image_tag(runtime_image)
dockerhub_user = get_dockerhub_username()
if dockerhub_user:
return f"{dockerhub_user}/cicy-code-runtime"
return ""
def get_current_runtime_image():
images = get_images_config()
runtime_image = images.get("runtime", "")
if isinstance(runtime_image, dict):
runtime_image = runtime_image.get("image", "")
return str(runtime_image or "").strip()
def write_cloudrun_image_to_global_json(image_ref, tag):
data = load_global_json()
if not isinstance(data, dict):
data = {}
cluster = data.get("cicy-cluster", {})
if not isinstance(cluster, dict):
cluster = {}
cluster["image"] = image_ref
cluster["image_tag"] = tag
cluster["image_repository"] = strip_image_tag(image_ref)
data["cicy-cluster"] = cluster
with open(GLOBAL_JSON_PATH, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
f.write("\n")
def write_docker_image_to_global_json(image_ref, tag, repository):
data = load_global_json()
if not isinstance(data, dict):
data = {}
images = data.get("images", {})
if not isinstance(images, dict):
images = {}
images["runtime"] = image_ref
images["runtime_repository"] = repository
images["runtime_tag"] = tag
data["images"] = images
with open(GLOBAL_JSON_PATH, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
f.write("\n")
def print_docker_version():
info = get_version_info()
files = info.get("files", {}) if isinstance(info, dict) else {}
package_version = str(info.get("version", "")).strip() or get_binary_version()
runtime_image = get_current_runtime_image()
runtime_repository = (
strip_image_tag(runtime_image)
or get_images_config().get("runtime_repository", "")
or get_docker_image_repository()
)
runtime_tag = get_image_tag(runtime_image) or get_images_config().get(
"runtime_tag", ""
)
print(f"[dev] package_version={package_version}")
if files:
print(f"[dev] mgr_version={files.get('mgr_main_go', '')}")
print(f"[dev] ui_version={files.get('workspace_ui', '')}")
print(f"[dev] tmux_version={files.get('cicy_tmux_conf', '')}")
print(f"[dev] dockerhub_repository={runtime_repository}")
print(f"[dev] current_runtime_image={runtime_image}")
print(f"[dev] current_runtime_tag={runtime_tag}")
sys.exit(0)
def bump_version(version):
version = str(version or "").strip()
if not version:
print("[dev] missing bump version")
sys.exit(1)
info = run_version_sync(version)
files = info.get("files", {}) if isinstance(info, dict) else {}
final_version = str(info.get("version", "")).strip() or version
print(f"[dev] bumped version={final_version}")
if files:
print(f"[dev] npm_version={files.get('npm_package', '')}")
print(f"[dev] mgr_version={files.get('mgr_main_go', '')}")
print(f"[dev] ui_version={files.get('workspace_ui', '')}")
print(f"[dev] tmux_version={files.get('cicy_tmux_conf', '')}")
sys.exit(0)
def set_docker_version(tag):
tag = str(tag or "").strip()
if not tag:
print("[dev] missing docker version tag")
sys.exit(1)
repository = get_docker_image_repository()
if not repository:
print("[dev] missing Docker Hub target repository")
print(
f"[dev] set DOCKER_IMAGE_REPOSITORY or configure Docker Hub login in ~/.docker/config.json"
)
sys.exit(1)
image_ref = f"{repository}:{tag}"
write_docker_image_to_global_json(image_ref, tag, repository)
print(f"[dev] Updated {GLOBAL_JSON_PATH} -> images.runtime={image_ref}")
print(f"[dev] Updated {GLOBAL_JSON_PATH} -> images.runtime_repository={repository}")
print(f"[dev] Updated {GLOBAL_JSON_PATH} -> images.runtime_tag={tag}")
sys.exit(0)
def run_checked(cmd, cwd=None, env=None):
result = subprocess.run(cmd, cwd=cwd, env=env)
if result.returncode != 0:
sys.exit(result.returncode)
return result
def get_pid_on_port(port):
# Try lsof first (macOS + Linux with lsof installed)
try:
result = subprocess.run(
["lsof", "-ti", f"TCP:{port}", "-sTCP:LISTEN"],
capture_output=True,
text=True,
)
if result.returncode == 0 and result.stdout.strip():
return result.stdout.strip().split("\n")[0]
except FileNotFoundError:
pass
except Exception:
return None
# Fallback: ss (Linux without lsof)
try:
import re
result = subprocess.run(
["ss", "-tlnp", f"sport = :{port}"],
capture_output=True,
text=True,
)
if result.returncode == 0:
for line in result.stdout.splitlines():
m = re.search(r"pid=(\d+)", line)
if m:
return m.group(1)
except (FileNotFoundError, Exception):
pass
return None
def is_pid_alive(pid):
try:
os.kill(int(pid), 0)
return True
except ProcessLookupError:
return False
except PermissionError:
return True
except Exception:
return False
def wait_for_process_exit(pid, timeout=6.0, interval=0.2):
start = time.time()
while time.time() - start < timeout:
if not is_pid_alive(pid):
return True
time.sleep(interval)
return not is_pid_alive(pid)
def kill_process(pid):
pid = str(pid or "").strip()
if not pid:
return True
try:
os.kill(int(pid), signal.SIGTERM)
except ProcessLookupError:
return True
except Exception:
return False
if wait_for_process_exit(pid, timeout=6.0, interval=0.2):
return True
try:
os.kill(int(pid), signal.SIGKILL)
except ProcessLookupError:
return True
except Exception:
return False
return wait_for_process_exit(pid, timeout=2.0, interval=0.1)
def wait_for_probe(url, timeout=180, interval=1):
start = time.time()
last_error = None
while time.time() - start < timeout:
try:
with urllib.request.urlopen(url, timeout=5) as resp:
if 200 <= resp.status < 500:
return time.time() - start
except Exception as e:
last_error = e
time.sleep(interval)
raise TimeoutError(f"probe timeout after {timeout}s: {url} ({last_error})")
def get_cloudrun_service_url(project, region, service):
try:
result = subprocess.run(
[
"gcloud",
"run",
"services",
"describe",
service,
"--project",
project,
"--region",
region,
"--format=value(status.url)",
],
capture_output=True,
text=True,
timeout=30,
)
if result.returncode == 0:
return result.stdout.strip()
except Exception:
pass
return ""
def list_cloudrun_services(project, region):
try:
result = subprocess.run(
[
"gcloud",
"run",
"services",
"list",
"--project",
project,
"--region",
region,
"--format=json",
],
capture_output=True,
text=True,
timeout=30,
)
if result.returncode != 0:
err = (result.stderr or result.stdout or "").strip()
print(f"[dev] cloud run list failed: {err}")
sys.exit(result.returncode or 1)
data = json.loads(result.stdout or "[]")
return data if isinstance(data, list) else []
except FileNotFoundError:
print("[dev] gcloud not found")
sys.exit(1)
except json.JSONDecodeError as e:
print(f"[dev] invalid gcloud json output: {e}")
sys.exit(1)
except Exception as e:
print(f"[dev] cloud run list error: {e}")
sys.exit(1)
def run_cloudrun_list():
env = get_cloudrun_env()
validate_cloudrun_list_env(env)
project = env.get("PROJECT", "")
region = env.get("REGION", "")
configured_service = env.get("SERVICE", "")
token = env.get("CICY_API_TOKEN", "")
print(f"[dev] Listing Cloud Run services for project={project} region={region}")
services = list_cloudrun_services(project, region)
if not services:
print("[dev] No Cloud Run services found.")
sys.exit(0)
for svc in services:
metadata = svc.get("metadata", {}) if isinstance(svc, dict) else {}
status = svc.get("status", {}) if isinstance(svc, dict) else {}
spec = svc.get("spec", {}) if isinstance(svc, dict) else {}
name = metadata.get("name", "")
url = status.get("url", "")
ready = "unknown"
conditions = status.get("conditions", [])
if isinstance(conditions, list):
for cond in conditions:
if cond.get("type") == "Ready":
ready = cond.get("status", "unknown")
break
latest = status.get("latestReadyRevisionName", "")
service_account = (
spec.get("template", {}).get("spec", {}).get("serviceAccountName", "")
)
marker = " *" if name == configured_service else ""
print(f"[dev] Service: {name}{marker}")
print(f"[dev] ready={ready}")
if latest:
print(f"[dev] revision={latest}")
if service_account:
print(f"[dev] service_account={service_account}")
if url:
print(f"[dev] service_url={url}")
if token:
print(f"[dev] url={url.rstrip('/')}/?token={token}")
else:
print("[dev] service_url=")
if configured_service:
print(f"[dev] * configured service from env/global.json: {configured_service}")
sys.exit(0)
def _r2_upload_docker_image(image_ref, version):
"""Save the docker image as a gzip tar and upload it to Cloudflare R2.