-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathplugin_repackaging.sh
More file actions
5213 lines (4818 loc) · 167 KB
/
Copy pathplugin_repackaging.sh
File metadata and controls
5213 lines (4818 loc) · 167 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
# author: xiejianglei
set -Eeuo pipefail
GITHUB_API_URL="${GITHUB_API_URL:-https://github.com}"
MARKETPLACE_API_URL="${MARKETPLACE_API_URL:-https://marketplace.dify.ai}"
PIP_MIRROR_URL="${PIP_MIRROR_URL:-https://mirrors.aliyun.com/pypi/simple}"
UV_MIN_VERSION=0.7.21
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
HOST_ARCH=
TARGET_ARCH=
PACKAGER_BINARY=
ACTIVE_STAGING=
ACTIVE_STAGING_OWNED=false
ACTIVE_STAGING_IDENTITY=
ACTIVE_STAGING_MARKER_NONCE=
ACTIVE_OUTPUT=
ACTIVE_OUTPUT_TEMP_DIR=
ACTIVE_OUTPUT_TEMP_DIR_OWNED=false
ACTIVE_OUTPUT_TEMP_DIR_IDENTITY=
ACTIVE_OUTPUT_TEMP_DIR_MARKER_NONCE=
ACTIVE_OUTPUT_TEMP_FILE=
ACTIVE_OUTPUT_BOUND_FILE=
ACTIVE_OUTPUT_BOUND_SIGNATURE=
ACTIVE_COORDINATOR_WORKSPACE=
ACTIVE_COORDINATOR_WORKSPACE_OWNED=false
ACTIVE_COORDINATOR_WORKSPACE_IDENTITY=
ACTIVE_COORDINATOR_WORKSPACE_MARKER_NONCE=
ACTIVE_PACKAGER_WORKSPACE=
ACTIVE_PACKAGER_WORKSPACE_OWNED=false
ACTIVE_PACKAGER_WORKSPACE_IDENTITY=
ACTIVE_PACKAGER_WORKSPACE_MARKER_NONCE=
ACTIVE_OUTPUT_LOCK_FD=
ACTIVE_OUTPUT_LOCK_PATH=
ACTIVE_OUTPUT_LOCK_IDENTITY=
ACTIVE_OUTPUT_LOCK_HELD=false
ACTIVE_OUTPUT_LOCK_WAIT_FD=
ACTIVE_OUTPUT_LOCK_WAIT_PID=
ACTIVE_OUTPUT_LOCK_WAIT_STATE=idle
ACTIVE_OUTPUT_LOCK_WAIT_PENDING_SIGNAL=
ACTIVE_OUTPUT_LOCK_WAIT_PENDING_STATUS=
TRACKED_TEMP_CREATION_STATE=idle
TRACKED_TEMP_PENDING_SIGNAL=
TRACKED_TEMP_PENDING_STATUS=
TRACKED_TEMP_SIGNAL_DOMAIN=runtime
ACTIVE_DOWNLOAD_PID=
ACTIVE_PACKAGER_PID=
RUNTIME_CHILD_STATE=idle
RUNTIME_CHILD_KIND=
RUNTIME_PENDING_SIGNAL=
RUNTIME_PENDING_STATUS=
OUTPUT_PUBLICATION_STATE=idle
OUTPUT_PUBLICATION_PENDING_SIGNAL=
OUTPUT_PUBLICATION_PENDING_STATUS=
BUILD_SUCCEEDED=false
normalize_arch() {
case "$1" in
x86_64 | amd64)
printf 'x86_64\n'
;;
aarch64 | arm64)
printf 'aarch64\n'
;;
*)
printf 'unsupported architecture: %s\n' "$1" >&2
return 1
;;
esac
}
packager_name_for_host() {
case "$(normalize_arch "$1")" in
x86_64)
printf 'dify-plugin-linux-amd64-5g\n'
;;
aarch64)
printf 'dify-plugin-linux-arm64-5g\n'
;;
esac
}
uv_version_at_least() {
local installed=$1 required=$2
local installed_major installed_minor installed_patch
local required_major required_minor required_patch
IFS=. read -r installed_major installed_minor installed_patch <<<"$installed"
IFS=. read -r required_major required_minor required_patch <<<"$required"
[[ "$installed_major" =~ ^[0-9]+$ && "$installed_minor" =~ ^[0-9]+$ && "$installed_patch" =~ ^[0-9]+$ ]] || return 1
[[ "$required_major" =~ ^[0-9]+$ && "$required_minor" =~ ^[0-9]+$ && "$required_patch" =~ ^[0-9]+$ ]] || return 1
if ((10#$installed_major != 10#$required_major)); then
((10#$installed_major > 10#$required_major))
elif ((10#$installed_minor != 10#$required_minor)); then
((10#$installed_minor > 10#$required_minor))
else
((10#$installed_patch >= 10#$required_patch))
fi
}
check_uv_version() {
local uv_command=$1
local version_output installed_version
version_output="$("$uv_command" --version)" || {
printf 'failed to read uv version: %s\n' "$uv_command" >&2
return 1
}
if [[ "$version_output" =~ (^|[[:space:]])([0-9]+\.[0-9]+\.[0-9]+)($|[[:space:]]) ]]; then
installed_version=${BASH_REMATCH[2]}
else
printf 'unable to parse uv version: %s\n' "$version_output" >&2
return 1
fi
if ! uv_version_at_least "$installed_version" "$UV_MIN_VERSION"; then
printf 'uv %s or newer is required (found %s)\n' "$UV_MIN_VERSION" "$installed_version" >&2
return 1
fi
}
normalize_python_version() {
local version=$1
if [[ "$version" =~ ^([0-9]+)\.([0-9]+)(\.[0-9]+)?$ ]]; then
printf '%s.%s\n' "${BASH_REMATCH[1]}" "${BASH_REMATCH[2]}"
else
printf 'unsupported Python version: %s (expected MAJOR.MINOR or MAJOR.MINOR.PATCH)\n' "$version" >&2
return 1
fi
}
python_abi() {
local version
version="$(normalize_python_version "$1")"
version=${version//./}
printf 'cp%s\n' "$version"
}
default_platforms() {
local suffix
if [[ -n "${DIFY_MANYLINUX_PLATFORMS:-}" ]]; then
tr ',' '\n' <<<"$DIFY_MANYLINUX_PLATFORMS"
return
fi
case "$(normalize_arch "$1")" in
x86_64)
suffix=x86_64
;;
aarch64)
suffix=aarch64
;;
esac
printf 'manylinux_2_28_%s\nmanylinux2014_%s\n' "$suffix" "$suffix"
}
detect_socks_proxy() {
local variable_name proxy_url scheme
for variable_name in https_proxy HTTPS_PROXY http_proxy HTTP_PROXY all_proxy ALL_PROXY; do
proxy_url=${!variable_name:-}
[[ -n "$proxy_url" && "$proxy_url" == *://* ]] || continue
scheme=${proxy_url%%://*}
case "${scheme,,}" in
socks4 | socks4a | socks5 | socks5h)
printf '%s\n' "$proxy_url"
return 0
;;
esac
done
return 1
}
redact_url_for_log() {
local url=$1
python3 - "$url" <<'PY'
import sys
from urllib.parse import urlsplit, urlunsplit
try:
parsed = urlsplit(sys.argv[1])
if not parsed.scheme or not parsed.hostname:
raise ValueError("URL must include a scheme and host")
host = parsed.hostname
if ":" in host:
host = f"[{host}]"
if parsed.port is not None:
host = f"{host}:{parsed.port}"
if parsed.username is not None or parsed.password is not None or "@" in parsed.netloc:
host = f"***@{host}"
print(urlunsplit((parsed.scheme, host, parsed.path, "", "")))
except (TypeError, ValueError):
print("<redacted-url>")
PY
}
redact_pip_log() {
python3 /dev/fd/3 3<<'PY'
import re
import sys
import unicodedata
from urllib.parse import urlsplit, urlunsplit
MAX_DISPLAY_INPUT_BYTES = 1024 * 1024
MAX_DISPLAY_OUTPUT_BYTES = MAX_DISPLAY_INPUT_BYTES + 64
TRUNCATION_MARKER = "\n[pip diagnostic output truncated]\n"
supported_scheme_pattern = re.compile(
r"(?:https?|socks(?:4a?|5h?))://",
re.IGNORECASE,
)
url_pattern = re.compile(
supported_scheme_pattern.pattern + r"\S+",
re.IGNORECASE,
)
def redact_url(match):
if input_truncated and match.end() == len(text):
return "<redacted-url>"
raw_url = match.group(0)
trailing = ""
while raw_url and raw_url[-1] in "'\"].,;)}>":
trailing = raw_url[-1] + trailing
raw_url = raw_url[:-1]
try:
scheme_end = raw_url.find("://") + 3
if supported_scheme_pattern.search(raw_url, scheme_end):
return "<redacted-url>" + trailing
if any(
not character.isprintable()
or unicodedata.category(character).startswith("C")
or character in "<>\"\\"
for character in raw_url
) or re.search(r"%(?![0-9A-Fa-f]{2})", raw_url):
raise ValueError("unsafe character in URL")
parsed = urlsplit(raw_url)
if not parsed.scheme or not parsed.hostname:
raise ValueError("URL must include a scheme and host")
host = parsed.hostname
if ":" in host:
host = f"[{host}]"
if parsed.port is not None:
host = f"{host}:{parsed.port}"
if parsed.username is not None or parsed.password is not None or "@" in parsed.netloc:
host = f"***@{host}"
safe_url = urlunsplit((parsed.scheme, host, parsed.path, "", ""))
except (TypeError, UnicodeError, ValueError):
safe_url = "<redacted-url>"
return safe_url + trailing
raw_input = sys.stdin.buffer.read(MAX_DISPLAY_INPUT_BYTES + 1)
input_truncated = len(raw_input) > MAX_DISPLAY_INPUT_BYTES
raw_input = raw_input[:MAX_DISPLAY_INPUT_BYTES]
text = raw_input.decode("utf-8", errors="surrogateescape")
redacted = url_pattern.sub(redact_url, text)
safe_output = []
safe_output_bytes = 0
display_truncated = input_truncated
for character in redacted:
if character in "\n\t":
safe_character = character
else:
codepoint = ord(character)
category = unicodedata.category(character)
if 0xDC80 <= codepoint <= 0xDCFF:
safe_character = f"\\x{codepoint - 0xDC00:02x}"
elif character == "\r":
safe_character = "\\r"
elif not character.isprintable() or category.startswith("C") or category in {"Zl", "Zp"}:
if codepoint < 0x80:
safe_character = f"\\x{codepoint:02x}"
elif codepoint <= 0xFFFF:
safe_character = f"\\u{codepoint:04x}"
else:
safe_character = f"\\U{codepoint:08x}"
else:
safe_character = character
encoded_size = len(safe_character.encode("utf-8"))
if safe_output_bytes + encoded_size > MAX_DISPLAY_OUTPUT_BYTES:
display_truncated = True
break
safe_output.append(safe_character)
safe_output_bytes += encoded_size
if display_truncated:
safe_output.append(TRUNCATION_MARKER)
sys.stdout.buffer.write("".join(safe_output).encode("utf-8"))
PY
}
extract_missing_requirement() {
local pip_output_file=$1
python3 - "$pip_output_file" <<'PY'
from pathlib import Path
import re
import sys
import unicodedata
MAX_PIP_OUTPUT_BYTES = 16 * 1024 * 1024
path = Path(sys.argv[1])
try:
if not path.is_file() or path.stat().st_size > MAX_PIP_OUTPUT_BYTES:
raise ValueError("invalid pip output file")
log = path.read_text(encoding="utf-8")
except (OSError, UnicodeError, ValueError):
raise SystemExit(1)
for character in log:
if character in "\n\r\t":
continue
category = unicodedata.category(character)
if not character.isprintable() or category.startswith("C") or category in {"Zl", "Zp"}:
raise SystemExit(1)
missing_version_matches = list(re.finditer(
r"^[ \t]*(?:ERROR:[ \t]*)?Could not find a version that satisfies the requirement "
r"(.+?) \(from versions: none\)[ \t\r]*$",
log,
re.MULTILINE,
))
missing_distribution_matches = list(re.finditer(
r"^[ \t]*(?:ERROR:[ \t]*)?No matching distribution found for (.+?)[ \t\r]*$",
log,
re.MULTILINE,
))
if len(missing_version_matches) != 1 or len(missing_distribution_matches) != 1:
raise SystemExit(1)
diagnostic_parts = []
cursor = 0
for match in sorted(
(missing_version_matches[0], missing_distribution_matches[0]),
key=lambda item: item.start(),
):
diagnostic_parts.append(log[cursor:match.start()])
cursor = match.end()
diagnostic_parts.append(log[cursor:])
diagnostics = "".join(diagnostic_parts)
benign_progress_patterns = tuple(re.compile(pattern) for pattern in (
r"Looking in indexes: \S+(?:,[ \t]+\S+)*",
r"Looking in links: .+",
r"Collecting .+",
r"(?:Using cached|Downloading|Processing) .+",
r"INFO: pip (?:is|is still) looking at multiple versions of .+",
r"INFO: This is taking longer than usual\..+",
r"(?:[━█▉▊▋▌▍▎▏#=><.\-]+[ \t]+)?"
r"\d+(?:\.\d+)?/\d+(?:\.\d+)?[ \t]+(?:bytes|kB|MB|GB)"
r"(?:[ \t]+\d+(?:\.\d+)?[ \t]+(?:kB|MB|GB)/s)?"
r"(?:[ \t]+(?:eta[ \t]+)?(?:\d+:\d+(?::\d+)?|-:--:--))?",
))
for diagnostic_line in diagnostics.split("\n"):
if not diagnostic_line.strip(" \t\r"):
continue
diagnostic_line = diagnostic_line.strip(" \t\r")
if not any(pattern.fullmatch(diagnostic_line) for pattern in benign_progress_patterns):
raise SystemExit(1)
dependency_context = re.compile(r"\s+\(from [^()\t\r\n]+\)\s*$", re.IGNORECASE)
requirement_pattern = re.compile(
r"^\s*(?P<name>[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?)"
r"(?:\s*(?P<spec>"
r"(?:===|==|!=|~=|<=|>=|<|>)\s*[A-Za-z0-9][A-Za-z0-9.!+_*-]*"
r"(?:\s*,\s*(?:===|==|!=|~=|<=|>=|<|>)\s*[A-Za-z0-9][A-Za-z0-9.!+_*-]*)*"
r"))?\s*$"
)
def normalize_requirement(value, strip_context=False):
if strip_context:
while True:
stripped = dependency_context.sub("", value)
if stripped == value:
break
value = stripped
if any(ord(character) < 32 or ord(character) == 127 for character in value):
raise ValueError("control character in requirement")
match = requirement_pattern.fullmatch(value)
if match is None:
raise ValueError("unsupported requirement")
name = re.sub(r"[-_.]+", "-", match.group("name")).lower()
spec = match.group("spec") or ""
spec = re.sub(r"\s+", "", spec)
return name + spec, name
try:
first, first_name = normalize_requirement(
missing_version_matches[0].group(1), strip_context=True
)
second, second_name = normalize_requirement(missing_distribution_matches[0].group(1))
except ValueError:
raise SystemExit(1)
if first != second or first_name != second_name:
raise SystemExit(1)
print(f"{first}\t{first_name}")
PY
}
detect_manifest_python_version() {
local manifest_file=$1
local detected
[[ -f "$manifest_file" ]] || return 1
detected="$(
awk '
function indentation(line, first_non_space) {
first_non_space = match(line, /[^[:space:]]/)
return first_non_space ? first_non_space - 1 : length(line)
}
{
line = $0
sub(/[[:space:]]+#.*$/, "", line)
if (line ~ /^[[:space:]]*meta[[:space:]]*:[[:space:]]*$/) {
in_meta = 1
meta_indent = indentation(line)
next
}
if (in_meta && line !~ /^[[:space:]]*$/) {
current_indent = indentation(line)
if (current_indent <= meta_indent) {
in_meta = 0
in_runner = 0
} else if (line ~ /^[[:space:]]*runner[[:space:]]*:[[:space:]]*$/) {
in_runner = 1
runner_indent = current_indent
next
}
}
if (in_runner && line !~ /^[[:space:]]*$/) {
current_indent = indentation(line)
if (current_indent <= runner_indent) {
in_runner = 0
} else if (line ~ /^[[:space:]]*version[[:space:]]*:/) {
sub(/^[[:space:]]*version[[:space:]]*:[[:space:]]*/, "", line)
sub(/[[:space:]]+$/, "", line)
first = substr(line, 1, 1)
last = substr(line, length(line), 1)
if ((first == "\"" && last == "\"") || (first == "\047" && last == "\047")) {
line = substr(line, 2, length(line) - 2)
}
print line
exit
}
}
}
' "$manifest_file"
)"
[[ -n "$detected" ]] || return 1
normalize_python_version "$detected" 2>/dev/null
}
detect_python_version() {
local plugin_dir=$1
local requested=${DIFY_PYTHON_VERSION:-}
local detected=
if [[ -n "$requested" ]]; then
normalize_python_version "$requested"
return
fi
if detected="$(detect_manifest_python_version "$plugin_dir/manifest.yaml")"; then
:
elif [[ -f "$plugin_dir/.python-version" ]]; then
detected="$(tr -d '[:space:]' <"$plugin_dir/.python-version")"
elif [[ -f "$plugin_dir/pyproject.toml" ]]; then
detected="$(
sed -nE \
's/^[[:space:]]*requires-python[[:space:]]*=[[:space:]]*"[^0-9]*([0-9]+\.[0-9]+).*"/\1/p' \
"$plugin_dir/pyproject.toml" | head -n1
)"
fi
normalize_python_version "${detected:-3.12}"
}
export_requirements_from_uv() {
local plugin_dir=$1
local output=$2
local uv_command=${DIFY_UV_COMMAND:-uv}
local -a args=(
export
--format requirements.txt
--no-default-groups
--no-group dev
--no-emit-project
--no-hashes
--no-header
--no-annotate
)
if [[ -f "$plugin_dir/uv.lock" ]]; then
args+=(--frozen)
fi
(cd "$plugin_dir" && "$uv_command" "${args[@]}") >"$output"
}
prepare_download_requirements() {
local plugin_dir=$1
local output=$2
if [[ -f "$plugin_dir/requirements.txt" ]]; then
sed -E \
'/^[[:space:]]*--(no-index|find-links)([=[:space:]].*)?$/d' \
"$plugin_dir/requirements.txt" >"$output"
elif [[ -f "$plugin_dir/pyproject.toml" ]]; then
export_requirements_from_uv "$plugin_dir" "$output"
else
: >"$output"
fi
}
sanitize_difyignore() {
local ignore_file=$1
[[ -f "$ignore_file" ]] || return 0
sed -i -E \
-e '\#^[[:space:]]*/?wheels(/(\*\*)?)?/?[[:space:]]*$#d' \
-e '\#^[[:space:]]*/?uv\.toml[[:space:]]*$#d' \
"$ignore_file"
}
sanitize_pyproject_for_runtime() {
local pyproject_file=$1
local temporary_file
[[ -f "$pyproject_file" ]] || return 0
temporary_file="$(mktemp "$(dirname "$pyproject_file")/.pyproject.runtime.XXXXXX")"
awk '
function array_delta(line, i, character, quote, escaped, delta) {
quote = ""
escaped = 0
delta = 0
for (i = 1; i <= length(line); i++) {
character = substr(line, i, 1)
if (quote == "double") {
if (escaped) {
escaped = 0
} else if (character == "\\") {
escaped = 1
} else if (character == "\"") {
quote = ""
}
} else if (quote == "single") {
if (character == sprintf("%c", 39)) {
quote = ""
}
} else if (character == "#") {
break
} else if (character == "\"") {
quote = "double"
} else if (character == sprintf("%c", 39)) {
quote = "single"
} else if (character == "[") {
delta++
} else if (character == "]") {
delta--
}
}
return delta
}
{
if (skipping_dependency_groups) {
if ($0 ~ /^[[:space:]]*\[/) {
skipping_dependency_groups = 0
} else {
next
}
}
if ($0 ~ /^[[:space:]]*\[dependency-groups\][[:space:]]*$/) {
skipping_dependency_groups = 1
next
}
if (skipping_legacy_group) {
legacy_group_depth += array_delta($0)
if (legacy_group_depth <= 0) {
skipping_legacy_group = 0
}
next
}
if ($0 ~ /^[[:space:]]*\[/) {
in_tool_uv = ($0 ~ /^[[:space:]]*\[tool\.uv\][[:space:]]*$/)
print
next
}
if (in_tool_uv && $0 ~ /^[[:space:]]*(dev-dependencies|default-groups)[[:space:]]*=/) {
legacy_group_depth = array_delta($0)
if (legacy_group_depth > 0) {
skipping_legacy_group = 1
}
next
}
print
}
' "$pyproject_file" >"$temporary_file"
mv -- "$temporary_file" "$pyproject_file"
}
configure_pyproject_environment() {
local pyproject_file=$1
local target_arch=$2
local python_version=$3
local platform_machine marker temporary_file
[[ -f "$pyproject_file" ]] || return 0
case "$(normalize_arch "$target_arch")" in
x86_64)
platform_machine=x86_64
;;
aarch64)
platform_machine=aarch64
;;
esac
marker="sys_platform == 'linux' and platform_machine == '$platform_machine' and python_version == '$python_version'"
temporary_file="$(mktemp "$(dirname "$pyproject_file")/.pyproject.environment.XXXXXX")"
awk -v marker="$marker" '
function array_delta(line, i, character, quote, escaped, delta) {
quote = ""
escaped = 0
delta = 0
for (i = 1; i <= length(line); i++) {
character = substr(line, i, 1)
if (quote == "double") {
if (escaped) {
escaped = 0
} else if (character == "\\") {
escaped = 1
} else if (character == "\"") {
quote = ""
}
} else if (quote == "single") {
if (character == sprintf("%c", 39)) {
quote = ""
}
} else if (character == "#") {
break
} else if (character == "\"") {
quote = "double"
} else if (character == sprintf("%c", 39)) {
quote = "single"
} else if (character == "[") {
delta++
} else if (character == "]") {
delta--
}
}
return delta
}
function print_environment() {
print "environments = ["
print " \"" marker "\","
print "]"
}
{
if (skipping_environment) {
environment_depth += array_delta($0)
if (environment_depth <= 0) {
skipping_environment = 0
}
next
}
if ($0 ~ /^[[:space:]]*\[tool\.uv\][[:space:]]*$/) {
print
print_environment()
inserted_environment = 1
in_tool_uv = 1
next
}
if (in_tool_uv && $0 ~ /^[[:space:]]*\[/) {
in_tool_uv = 0
}
if (in_tool_uv && $0 ~ /^[[:space:]]*environments[[:space:]]*=/) {
environment_depth = array_delta($0)
if (environment_depth > 0) {
skipping_environment = 1
}
next
}
print
}
END {
if (!inserted_environment) {
print ""
print "[tool.uv]"
print_environment()
}
}
' "$pyproject_file" >"$temporary_file"
mv -- "$temporary_file" "$pyproject_file"
}
write_offline_metadata() {
local plugin_dir=$1
local clean_requirements=$2
local target_arch=${3:-${TARGET_ARCH:-$(normalize_arch "$(uname -m)")}}
local python_version=${4:-$(detect_python_version "$plugin_dir")}
{
printf '%s\n' '--no-index' '--find-links=./wheels'
cat "$clean_requirements"
} >"$plugin_dir/requirements.txt"
cat >"$plugin_dir/uv.toml" <<'EOF'
offline = true
[[index]]
name = "dify-offline-wheels"
url = "./wheels"
format = "flat"
default = true
EOF
sanitize_pyproject_for_runtime "$plugin_dir/pyproject.toml"
configure_pyproject_environment "$plugin_dir/pyproject.toml" "$target_arch" "$python_version"
rm -f -- "$plugin_dir/uv.lock"
sanitize_difyignore "$plugin_dir/.difyignore"
}
resolve_pip_command() {
local -n result=$1
if [[ -n "${DIFY_PIP_COMMAND:-}" ]]; then
read -r -a result <<<"$DIFY_PIP_COMMAND"
elif python3 -m pip --version >/dev/null 2>&1; then
result=(python3 -m pip)
elif command -v pip >/dev/null 2>&1; then
result=(pip)
elif command -v pip3 >/dev/null 2>&1; then
result=(pip3)
else
printf 'pip not found; install python3-pip or set DIFY_PIP_COMMAND\n' >&2
return 1
fi
}
pip_has_pysocks() {
local pip_command_name=$1
local -n selected_pip_command=$pip_command_name
"${selected_pip_command[@]}" show PySocks >/dev/null 2>&1
}
resolve_pysocks_wheel() {
local simple_page=$1
local simple_url=$2
python3 - "$simple_page" "$simple_url" <<'PY'
from html.parser import HTMLParser
from pathlib import Path
import re
import sys
from urllib.parse import parse_qs, unquote, urljoin, urlsplit, urlunsplit
class LinkParser(HTMLParser):
def __init__(self):
super().__init__()
self.links = []
def handle_starttag(self, tag, attrs):
if tag.lower() != "a":
return
for name, value in attrs:
if name.lower() == "href" and value:
self.links.append(value)
parser = LinkParser()
parser.feed(Path(sys.argv[1]).read_text(encoding="utf-8"))
target = "pysocks-1.7.1-py3-none-any.whl"
for href in parser.links:
absolute = urljoin(sys.argv[2], href)
parsed = urlsplit(absolute)
if parsed.scheme.lower() not in {"http", "https"} or not parsed.netloc:
continue
filename = unquote(parsed.path.rsplit("/", 1)[-1]).lower()
if filename != target:
continue
hashes = parse_qs(parsed.fragment).get("sha256", [])
if hashes and not re.fullmatch(r"[0-9a-fA-F]{64}", hashes[0]):
raise SystemExit("invalid sha256 fragment for PySocks wheel")
wheel_url = urlunsplit((parsed.scheme, parsed.netloc, parsed.path, parsed.query, ""))
print(f"{wheel_url}\t{hashes[0].lower() if hashes else '-'}")
raise SystemExit(0)
raise SystemExit("PySocks 1.7.1 universal wheel not found in simple index")
PY
}
file_sha256() {
python3 - "$1" <<'PY'
from hashlib import sha256
from pathlib import Path
import sys
digest = sha256()
with Path(sys.argv[1]).open("rb") as source:
for chunk in iter(lambda: source.read(1024 * 1024), b""):
digest.update(chunk)
print(digest.hexdigest())
PY
}
prepare_pip_socks_support() {
local pip_command_name=$1
local bootstrap_dir=$2
local result_name=$3
local -n selected_pip_command=$pip_command_name
local -n result=$result_name
local proxy_url simple_url simple_page wheel_record wheel_url expected_sha256
local wheel_file site_dir actual_sha256 safe_proxy_url safe_simple_url safe_wheel_url
result=
if ! proxy_url="$(detect_socks_proxy)"; then
return 0
fi
if pip_has_pysocks "$pip_command_name"; then
return 0
fi
case "${DIFY_AUTO_FIX_SOCKS:-1}" in
0 | false | FALSE | no | NO)
safe_proxy_url="$(redact_url_for_log "$proxy_url")"
printf 'pip requires PySocks for proxy %s; automatic repair is disabled by DIFY_AUTO_FIX_SOCKS\n' "$safe_proxy_url" >&2
return 1
;;
esac
command -v curl >/dev/null 2>&1 || {
printf 'curl is required to repair missing pip SOCKS support without modifying the Python environment\n' >&2
return 1
}
simple_url="${PIP_MIRROR_URL%/}/pysocks/"
safe_proxy_url="$(redact_url_for_log "$proxy_url")"
safe_simple_url="$(redact_url_for_log "$simple_url")"
simple_page="$bootstrap_dir/pysocks-simple.html"
wheel_file="$bootstrap_dir/PySocks-1.7.1-py3-none-any.whl"
site_dir="$bootstrap_dir/site-packages"
mkdir -p "$bootstrap_dir" "$site_dir"
printf 'Preparing temporary pip SOCKS support for %s ...\n' "$safe_proxy_url"
if ! curl --fail --location --show-error --output "$simple_page" "$simple_url"; then
printf 'failed to download the PySocks simple index from %s\n' "$safe_simple_url" >&2
return 1
fi
if ! wheel_record="$(resolve_pysocks_wheel "$simple_page" "$simple_url")"; then
printf 'failed to locate PySocks 1.7.1 universal wheel in %s\n' "$safe_simple_url" >&2
return 1
fi
wheel_url=${wheel_record%%$'\t'*}
expected_sha256=${wheel_record#*$'\t'}
safe_wheel_url="$(redact_url_for_log "$wheel_url")"
if ! curl --fail --location --show-error --output "$wheel_file" "$wheel_url"; then
printf 'failed to download temporary PySocks wheel from %s\n' "$safe_wheel_url" >&2
return 1
fi
if [[ "$expected_sha256" != - ]]; then
actual_sha256="$(file_sha256 "$wheel_file")"
if [[ "$actual_sha256" != "$expected_sha256" ]]; then
printf 'temporary PySocks wheel checksum mismatch: expected %s, got %s\n' \
"$expected_sha256" "$actual_sha256" >&2
return 1
fi
fi
if ! env \
-u http_proxy -u https_proxy -u all_proxy \
-u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY \
PIP_DISABLE_PIP_VERSION_CHECK=1 \
"${selected_pip_command[@]}" install \
--disable-pip-version-check \
--no-index \
--no-deps \
--target "$site_dir" \
"$wheel_file"; then
printf 'failed to install temporary PySocks support into %s\n' "$site_dir" >&2
return 1
fi
result=$site_dir
}
report_wheel_download_failure() {
local target_arch=$1
local python_version=$2
local abi=$3
shift 3
local platform_list safe_index_url
platform_list="$(IFS=,; printf '%s' "$*")"
safe_index_url="$(redact_url_for_log "$PIP_MIRROR_URL")"
printf '%s\n' \
'failed to download a complete binary wheel dependency set' \
"Target Python: $python_version" \
"Target ABI: $abi" \
"Target architecture: $target_arch" \
"Target platforms: $platform_list" \
"Package index: $safe_index_url" \
'Common causes: no compatible binary wheel for the target, conflicting version constraints, an additional package index is required, or the proxy/index is unreachable.' \
'Only validated pure Python universal wheels may be built from source; native source builds and build-host architecture fallbacks remain disabled.' >&2
}
reset_wheels_dir() {
local wheels_dir=$1
local parent
parent="$(dirname "$wheels_dir")"
if [[ "$(basename "$wheels_dir")" != wheels || "$parent" == / || "$parent" == . ]]; then
printf 'refusing to reset unsafe wheels path: %s\n' "$wheels_dir" >&2
return 1
fi
rm -rf -- "$wheels_dir"
mkdir -p "$wheels_dir"
}
validate_pip_bootstrap_dir() {
local bootstrap_dir=$1
local parent
if [[ -z "$bootstrap_dir" || "$(basename -- "$bootstrap_dir")" != pip-bootstrap ]]; then
printf 'safe pip bootstrap directory is required for SOCKS repair\n' >&2
return 1
fi
parent="$(dirname -- "$bootstrap_dir")"
if [[ "$parent" == / || "$parent" == . || "$parent" == "$bootstrap_dir" ]]; then
printf 'safe pip bootstrap directory is required for SOCKS repair\n' >&2
return 1
fi
}
task3_python() {
env -u PYTHONPATH -u PYTHONHOME -u VIRTUAL_ENV python3 "$@"
}
reset_private_command_log() {
local output_log=$1
run_bounded_command_log "$output_log" :
}
run_bounded_command_log() {
local output_log=$1
shift
local -a pipeline_status=()
"$@" 2>&1 | task3_python -B /dev/fd/3 "$output_log" 3<<'PY'
import os
import stat
import sys
MAX_RAW_LOG_BYTES = 1024 * 1024
TRUNCATION_MARKER = b"\n[raw diagnostic output truncated]\n"
path = sys.argv[1]
try:
existing = os.lstat(path)
# COORDINATOR_LOG_PREOPEN_IDENTITY_CAPTURED
except FileNotFoundError:
existing = None
if existing is not None and (
stat.S_ISLNK(existing.st_mode)
or not stat.S_ISREG(existing.st_mode)
or existing.st_uid != os.geteuid()
or existing.st_nlink != 1
or stat.S_IMODE(existing.st_mode) != 0o600
):
raise SystemExit(1)
open_flags = os.O_WRONLY | os.O_NOFOLLOW
if existing is None:
open_flags |= os.O_CREAT | os.O_EXCL
descriptor = os.open(path, open_flags, 0o600)
written = 0
truncated = False
def write_all(contents):
position = 0
while position < len(contents):
position += os.write(descriptor, contents[position:])
try:
opened = os.fstat(descriptor)
linked = os.lstat(path)
if (
not stat.S_ISREG(opened.st_mode)
or opened.st_uid != os.geteuid()
or opened.st_nlink != 1
or (existing is not None and stat.S_IMODE(opened.st_mode) != 0o600)
or (opened.st_dev, opened.st_ino) != (linked.st_dev, linked.st_ino)
or stat.S_ISLNK(linked.st_mode)
or not stat.S_ISREG(linked.st_mode)
or linked.st_uid != os.geteuid()