-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdocker-entrypoint.sh
More file actions
executable file
·285 lines (246 loc) · 8.55 KB
/
Copy pathdocker-entrypoint.sh
File metadata and controls
executable file
·285 lines (246 loc) · 8.55 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
#!/usr/bin/env bash
set -euo pipefail
is_truthy() {
case "${1:-}" in
1 | true | TRUE | yes | YES | on | ON) return 0 ;;
*) return 1 ;;
esac
}
ensure_dirs() {
mkdir -p \
"${OPENCLAW_STATE_DIR}" \
"${OPENCLAW_WORKSPACE_DIR}" \
"$(dirname "${OPENCLAW_CONFIG_PATH}")" \
/home/node/.config/openclaw
}
configure_gateway() {
local batch_json
batch_json="$(node -e '
const bindMode = process.env.OPENCLAW_GATEWAY_BIND || "lan";
const authMode = process.env.OPENCLAW_GATEWAY_AUTH_MODE || "token";
const port = process.env.OPENCLAW_GATEWAY_HOST_PORT || "18789";
const token = process.env.OPENCLAW_GATEWAY_TOKEN || "";
const extra = (process.env.OPENCLAW_CONTROL_UI_EXTRA_ORIGINS || "")
.split(",")
.map((origin) => origin.trim())
.filter(Boolean);
const ops = [
{ path: "gateway.mode", value: "local" },
{ path: "gateway.bind", value: bindMode },
{ path: "gateway.auth.mode", value: authMode },
{
path: "gateway.controlUi.allowedOrigins",
value: [`http://localhost:${port}`, `http://127.0.0.1:${port}`, ...extra],
},
];
if (token) {
ops.push({ path: "gateway.auth.token", value: token });
}
process.stdout.write(JSON.stringify(ops));
')"
openclaw config set --batch-json "$batch_json" >/dev/null
}
apply_bootstrap_config() {
local config_path="${OPENCLAW_BOOTSTRAP_CONFIG:-/etc/openclaw-os/openclaw-os.yaml}"
local patch_file="/tmp/openclaw-bootstrap.patch.json"
local keys_file="/tmp/openclaw-bootstrap-api-keys.tsv"
if [ ! -f "$config_path" ]; then
return 0
fi
python3 - "$config_path" "$patch_file" "$keys_file" <<'PY'
import json
import os
import sys
import yaml
config_path, patch_path, keys_path = sys.argv[1:4]
with open(config_path, "r", encoding="utf-8") as f:
raw = yaml.safe_load(f) or {}
cfg = raw.get("openclaw", raw) or {}
patch = {}
keys = []
PLACEHOLDERS = {
"",
"change-me",
"replace-me",
"paste-your-key-here",
"sk-...",
"sk-ant-...",
"your-api-key",
}
def useful(value):
if value is None:
return False
if isinstance(value, str):
return value.strip().lower() not in PLACEHOLDERS
return True
def resolve(value):
if not isinstance(value, str):
return value
value = value.strip()
if value.startswith("${") and value.endswith("}"):
return os.environ.get(value[2:-1], "")
return value
def deep_merge(target, source):
for key, value in source.items():
if isinstance(value, dict) and isinstance(target.get(key), dict):
deep_merge(target[key], value)
else:
target[key] = value
gateway = cfg.get("gateway") or {}
gateway_patch = {}
if useful(gateway.get("bind")):
gateway_patch["bind"] = str(gateway["bind"])
if useful(gateway.get("authMode")):
gateway_patch.setdefault("auth", {})["mode"] = str(gateway["authMode"])
if useful(gateway.get("authToken")):
gateway_patch.setdefault("auth", {})["token"] = str(resolve(gateway["authToken"]))
if useful(gateway.get("allowedOrigins")):
gateway_patch.setdefault("controlUi", {})["allowedOrigins"] = list(gateway["allowedOrigins"])
if gateway_patch:
patch.setdefault("gateway", {})
deep_merge(patch["gateway"], gateway_patch)
model = cfg.get("model") or {}
primary = model.get("primary")
fallbacks = model.get("fallbacks") or []
if useful(primary):
primary = str(primary)
model_patch = {"primary": primary}
if fallbacks:
model_patch["fallbacks"] = [str(item) for item in fallbacks if useful(item)]
patch.setdefault("agents", {}).setdefault("defaults", {})["model"] = model_patch
allowed_models = patch["agents"]["defaults"].setdefault("models", {})
allowed_models.setdefault(primary, {})
for fallback in model_patch.get("fallbacks", []):
allowed_models.setdefault(fallback, {})
if useful(model.get("thinking")):
patch.setdefault("agents", {}).setdefault("defaults", {})["thinkingDefault"] = str(model["thinking"])
if useful(model.get("workspace")):
patch.setdefault("agents", {}).setdefault("defaults", {})["workspace"] = str(model["workspace"])
providers = cfg.get("providers") or {}
for provider_id, provider_cfg in providers.items():
if not isinstance(provider_cfg, dict):
continue
clean = {}
for key in ("baseUrl", "api", "auth", "contextWindow", "contextTokens", "maxTokens", "timeoutSeconds"):
if useful(provider_cfg.get(key)):
clean[key] = resolve(provider_cfg[key])
if useful(provider_cfg.get("apiKey")):
clean["apiKey"] = resolve(provider_cfg["apiKey"])
models = provider_cfg.get("models")
if isinstance(models, list):
clean["models"] = {str(name): {} for name in models if useful(name)}
elif isinstance(models, dict):
clean["models"] = models
if clean:
patch.setdefault("models", {}).setdefault("providers", {})[str(provider_id)] = clean
api_keys = cfg.get("apiKeys") or cfg.get("api_keys") or {}
for provider_id, api_key in api_keys.items():
api_key = resolve(api_key)
if useful(api_key):
provider_id = str(provider_id)
profile_id = f"{provider_id}:docker"
keys.append((provider_id, profile_id, str(api_key)))
patch.setdefault("auth", {}).setdefault("profiles", {})[profile_id] = {
"provider": provider_id,
"mode": "api_key",
}
for item in cfg.get("authProfiles") or []:
if not isinstance(item, dict):
continue
provider_id = item.get("provider")
api_key = resolve(item.get("apiKey"))
if useful(provider_id) and useful(api_key):
provider_id = str(provider_id)
profile_id = str(item.get("profileId") or f"{provider_id}:docker")
keys.append((provider_id, profile_id, str(api_key)))
patch.setdefault("auth", {}).setdefault("profiles", {})[profile_id] = {
"provider": provider_id,
"mode": "api_key",
}
with open(patch_path, "w", encoding="utf-8") as f:
json.dump(patch, f)
with open(keys_path, "w", encoding="utf-8") as f:
for provider_id, profile_id, api_key in keys:
f.write(f"{provider_id}\t{profile_id}\t{api_key}\n")
PY
if [ -s "$patch_file" ] && [ "$(node -e "const fs=require('node:fs'); const p=JSON.parse(fs.readFileSync(process.argv[1],'utf8')); process.stdout.write(Object.keys(p).length ? 'yes' : 'no')" "$patch_file")" = "yes" ]; then
openclaw config patch --stdin <"$patch_file" >/dev/null
fi
if [ -s "$keys_file" ]; then
node - "$keys_file" "${OPENCLAW_STATE_DIR}/agents/main/agent/auth-profiles.json" <<'NODE'
const fs = require("node:fs");
const path = require("node:path");
const [keysPath, storePath] = process.argv.slice(2);
let store = { version: 1, profiles: {} };
try {
store = JSON.parse(fs.readFileSync(storePath, "utf8"));
if (!store || typeof store !== "object") store = { version: 1, profiles: {} };
if (!store.profiles || typeof store.profiles !== "object") store.profiles = {};
} catch {
// First run.
}
for (const line of fs.readFileSync(keysPath, "utf8").split(/\r?\n/)) {
if (!line.trim()) continue;
const [provider, profileId, ...rest] = line.split("\t");
const apiKey = rest.join("\t");
if (!provider || !profileId || !apiKey) continue;
store.profiles[profileId] = {
type: "api_key",
provider,
key: apiKey,
};
}
fs.mkdirSync(path.dirname(storePath), { recursive: true, mode: 0o700 });
fs.writeFileSync(storePath, `${JSON.stringify(store, null, 2)}\n`, { mode: 0o600 });
NODE
fi
}
install_openclaw_os_plugin() {
if ! is_truthy "${OPENCLAW_OS_AUTO_INSTALL:-1}"; then
return 0
fi
local spec="${OPENCLAW_OS_PLUGIN_SPEC:-${OPENCLAW_OS_PLUGIN_PATH}}"
local marker="${OPENCLAW_STATE_DIR}/.openclaw-os-plugin.spec"
if [ -f "$marker" ] && [ "$(cat "$marker")" = "$spec" ]; then
return 0
fi
echo "Installing OpenClaw OS plugin from ${spec}..."
openclaw plugins install "$spec" --force
printf '%s' "$spec" >"$marker"
}
start_gateway() {
local bind_mode="${OPENCLAW_GATEWAY_BIND:-lan}"
local port="${OPENCLAW_GATEWAY_PORT:-18789}"
local auth_mode="${OPENCLAW_GATEWAY_AUTH_MODE:-token}"
ensure_dirs
configure_gateway
apply_bootstrap_config
install_openclaw_os_plugin
exec openclaw gateway \
--bind "$bind_mode" \
--port "$port" \
--auth "$auth_mode"
}
case "${1:-gateway}" in
gateway)
shift || true
start_gateway "$@"
;;
configure)
ensure_dirs
configure_gateway
apply_bootstrap_config
install_openclaw_os_plugin
;;
cli)
shift || true
exec openclaw "$@"
;;
openclaw)
shift || true
exec openclaw "$@"
;;
*)
exec openclaw "$@"
;;
esac