-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathinstall
More file actions
executable file
·786 lines (693 loc) · 26 KB
/
install
File metadata and controls
executable file
·786 lines (693 loc) · 26 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
#!/usr/bin/env bash
set -e
# ─── XDG directories ────────────────────────────────────────────────────────
XDG_CONFIG_HOME="${XDG_CONFIG_HOME:-$HOME/.config}"
XDG_DATA_HOME="${XDG_DATA_HOME:-$HOME/.local/share}"
XDG_STATE_HOME="${XDG_STATE_HOME:-$HOME/.local/state}"
CLWND_CONFIG="$XDG_CONFIG_HOME/clwnd"
CLWND_DATA="$XDG_DATA_HOME/clwnd"
CLWND_STATE="$XDG_STATE_HOME/clwnd"
# Runtime socket dir. With XDG_RUNTIME_DIR set (linux): standard path.
# Without it (macOS default): UID-namespaced /tmp dir matching the
# plugin's and daemon's defaultSocketPath fallback so they agree even
# when CLWND_SOCKET isn't propagated to OC's shell env.
if [ -n "$XDG_RUNTIME_DIR" ]; then
CLWND_RUNTIME="$XDG_RUNTIME_DIR/clwnd"
else
CLWND_RUNTIME="/tmp/clwnd-$(id -u)"
fi
OPENCODE_CONFIG="$XDG_CONFIG_HOME/opencode/opencode.json"
CLWND_REPO="https://github.com/adiled/clwnd.git"
CLWND_SRC="$CLWND_DATA/src"
OS="$(uname -s)"
CMD="${1:-install}"
IS_ROOT=$([ "$(id -u)" = "0" ] && echo true || echo false)
SOCK_PATH="$CLWND_RUNTIME/clwnd.sock"
# ─── helpers ─────────────────────────────────────────────────────────────────
MIN_CLAUDE="2.1.86"
MIN_OPENCODE="1.4.3"
version_gte() {
# Returns 0 if $1 >= $2 (semver)
printf '%s\n%s\n' "$2" "$1" | sort -V -C
}
# Extract a semver from `<binary> --version` output. Used for both before
# and after probes around an upgrade attempt.
read_version() {
local BIN=$1
"$BIN" --version 2>/dev/null | sed -n 's/.*\([0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\).*/\1/p' | head -1
}
# Bring a prerequisite up to (or past) our minimum pin. Tries the upstream
# updater for the given binary, then re-checks the version. Exits the
# install script if the binary is still below the minimum after the update
# attempt — the auto-update path NEEDS this to self-heal, otherwise the
# 6-hour daemon timer keeps invoking clwnd update silently and failing
# silently and the user never knows they're stuck.
ensure_min_version() {
local NAME=$1 # human label, e.g. "Claude CLI"
local BIN=$2 # binary path / command
local MIN=$3 # minimum required version
local CUR
CUR=$(read_version "$BIN")
if [ -z "$CUR" ]; then
echo " ${NAME}: could not read version from \`$BIN --version\`, skipping"
return 0
fi
if version_gte "$CUR" "$MIN"; then
return 0
fi
echo " ${NAME} ${CUR} is below required ${MIN} — running self-update..."
"$BIN" update 2>&1 | sed 's/^/ /' || true
CUR=$(read_version "$BIN")
if [ -z "$CUR" ] || ! version_gte "$CUR" "$MIN"; then
echo ""
echo " ${NAME} is still ${CUR:-unknown} after \`${BIN} update\` (need ${MIN})."
echo " clwnd cannot proceed. Update ${NAME} manually and re-run \`clwnd update\`."
echo ""
exit 1
fi
echo " ${NAME} is now ${CUR} (>= ${MIN})."
}
check_prereqs() {
# Node + pnpm are NOT hard requirements anymore — `ensure_node_version`
# and `ensure_pnpm` provision them under $CLWND_DATA/node if missing or
# if the system version doesn't match `.node-version`. clwnd ships its
# own node toolchain rustup-style so the daemon never breaks when the
# user changes their system node.
[ -x "$(command -v claude)" ] || { echo "error: claude CLI required"; exit 1; }
[ -x "$(command -v git)" ] || { echo "error: git required"; exit 1; }
[ -x "$(command -v tar)" ] || { echo "error: tar required (used to extract pinned node)"; exit 1; }
if [ ! -x "$(command -v curl)" ] && [ ! -x "$(command -v wget)" ]; then
echo "error: curl or wget required (used to download pinned node)"
exit 1
fi
# better-sqlite3 + tree-sitter usually have prebuilds on Node 20, but
# if the user's arch has no prebuild, pnpm falls back to node-gyp.
# Check the toolchain so that fallback path doesn't die mid-install
# with a half-built node_modules.
if [ ! -x "$(command -v cc)" ] && [ ! -x "$(command -v gcc)" ] && [ ! -x "$(command -v clang)" ]; then
echo "error: C compiler required (gcc/clang) for native dep fallback build"
exit 1
fi
if [ ! -x "$(command -v c++)" ] && [ ! -x "$(command -v g++)" ] && [ ! -x "$(command -v clang++)" ]; then
echo "error: C++ compiler required (g++/clang++) for native dep fallback build"
exit 1
fi
[ -x "$(command -v make)" ] || { echo "error: make required for native dep fallback build"; exit 1; }
if [ ! -x "$(command -v python3)" ] && [ ! -x "$(command -v python)" ]; then
echo "error: python3 required for node-gyp fallback build"
exit 1
fi
ensure_min_version "Claude CLI" "claude" "$MIN_CLAUDE"
local OC_BIN
OC_BIN=$(command -v opencode 2>/dev/null || echo "")
if [ -n "$OC_BIN" ]; then
ensure_min_version "OpenCode" "$OC_BIN" "$MIN_OPENCODE"
fi
}
# clwnd ships its own node + pnpm under $CLWND_DATA/node/v$PINNED so the
# daemon's ExecStart points at a binary clwnd owns. The user's system
# node can vanish (version manager GC, distro upgrade) — ours can't.
ensure_node_version() {
local PINNED_FILE="$CLWND_SRC/.node-version"
[ -f "$PINNED_FILE" ] || { echo "error: $PINNED_FILE missing — clone is incomplete"; exit 1; }
local PINNED
PINNED=$(tr -d 'v\n\r ' < "$PINNED_FILE")
local OS_NAME ARCH_NAME
case "$OS" in
Darwin) OS_NAME="darwin" ;;
Linux) OS_NAME="linux" ;;
*) echo "error: unsupported OS for node auto-install: $OS"; exit 1 ;;
esac
case "$(uname -m)" in
x86_64|amd64) ARCH_NAME="x64" ;;
arm64|aarch64) ARCH_NAME="arm64" ;;
*) echo "error: unsupported arch for node auto-install: $(uname -m)"; exit 1 ;;
esac
local NODE_DIR="$CLWND_DATA/node/v${PINNED}"
local NODE_BIN="$NODE_DIR/bin/node"
if [ -x "$NODE_BIN" ]; then
CLWND_NODE_BIN="$NODE_BIN"
echo "[node] using cached pinned node at $NODE_BIN ✓"
export PATH="$(dirname "$CLWND_NODE_BIN"):$PATH"
return 0
fi
local TARBALL="node-v${PINNED}-${OS_NAME}-${ARCH_NAME}.tar.xz"
local URL="https://nodejs.org/dist/v${PINNED}/${TARBALL}"
local CACHE_DIR="$CLWND_DATA/node-cache"
local TARPATH="$CACHE_DIR/$TARBALL"
mkdir -p "$CACHE_DIR" "$CLWND_DATA/node"
if [ ! -f "$TARPATH" ]; then
echo "[node] downloading $URL..."
if [ -x "$(command -v curl)" ]; then
curl -fsSL --retry 3 -o "$TARPATH.part" "$URL" || { echo "error: node download failed"; rm -f "$TARPATH.part"; exit 1; }
else
wget -q -O "$TARPATH.part" "$URL" || { echo "error: node download failed"; rm -f "$TARPATH.part"; exit 1; }
fi
mv "$TARPATH.part" "$TARPATH"
fi
echo "[node] extracting to $NODE_DIR..."
mkdir -p "$NODE_DIR"
tar -xJf "$TARPATH" -C "$NODE_DIR" --strip-components=1 || {
echo "error: extraction failed"
rm -rf "$NODE_DIR"
exit 1
}
[ -x "$NODE_BIN" ] || { echo "error: node binary missing after extract"; exit 1; }
CLWND_NODE_BIN="$NODE_BIN"
echo "[node] installed pinned ${PINNED} at $NODE_BIN ✓"
export PATH="$(dirname "$CLWND_NODE_BIN"):$PATH"
}
# pnpm version comes from package.json's `packageManager` field, provisioned
# via the corepack that ships beside our pinned node.
ensure_pnpm() {
local NODE_DIR
NODE_DIR=$(dirname "$CLWND_NODE_BIN")
if [ -x "$NODE_DIR/corepack" ]; then
echo "[pnpm] enabling corepack..."
"$NODE_DIR/corepack" enable --install-directory "$NODE_DIR" 2>/dev/null || true
local PINNED_PNPM
PINNED_PNPM=$("$CLWND_NODE_BIN" -e "
try {
const pm = require('$CLWND_SRC/package.json').packageManager || '';
const m = pm.match(/^pnpm@([0-9.]+)/);
process.stdout.write(m ? m[1] : '');
} catch { process.stdout.write(''); }
")
if [ -n "$PINNED_PNPM" ]; then
echo "[pnpm] activating pnpm@${PINNED_PNPM} via corepack..."
"$NODE_DIR/corepack" prepare "pnpm@${PINNED_PNPM}" --activate 2>&1 | sed 's/^/ /' || true
fi
fi
if [ ! -x "$NODE_DIR/pnpm" ]; then
echo "error: corepack did not provision pnpm at $NODE_DIR/pnpm"
exit 1
fi
CLWND_PNPM_BIN="$NODE_DIR/pnpm"
local PNPM_VER
PNPM_VER=$("$CLWND_PNPM_BIN" --version 2>/dev/null || echo "?")
echo "[pnpm] using ${CLWND_PNPM_BIN} (${PNPM_VER}) ✓"
}
ensure_dirs() {
mkdir -p "$CLWND_CONFIG" "$CLWND_DATA" "$CLWND_STATE" "$CLWND_RUNTIME"
}
latest_tag() {
git -C "$CLWND_SRC" ls-remote --tags --sort=-v:refname origin "v*" 2>/dev/null | head -1 | sed 's|.*refs/tags/||; s|\^{}||'
}
current_tag() {
git -C "$CLWND_SRC" describe --tags --exact-match 2>/dev/null || echo "none"
}
ensure_source() {
if [ -d "$CLWND_SRC/.git" ]; then
local LATEST
LATEST=$(latest_tag)
local CURRENT
CURRENT=$(current_tag)
if [ "$CMD" = "update" ] && [ "$CURRENT" = "$LATEST" ] && [ "$LATEST" != "" ]; then
echo "[source] already at $LATEST — nothing to pull"
# Don't exit — the source is current, but the OC plugin cache may
# still be stuck on a pre-v0.16 version because Npm.add() short-
# circuits on loadVirtual(). Flow through so wipe_oc_plugin_cache
# runs and the user gets the reload hint.
SOURCE_UNCHANGED=1
return 0
fi
echo "[source] updating $CLWND_SRC to $LATEST..."
git -C "$CLWND_SRC" fetch --depth=1 origin tag "$LATEST"
git -C "$CLWND_SRC" checkout "$LATEST" 2>/dev/null || git -C "$CLWND_SRC" reset --hard "$LATEST"
else
echo "[source] cloning to $CLWND_SRC..."
git clone --depth=1 "$CLWND_REPO" "$CLWND_SRC"
cd "$CLWND_SRC"
local LATEST
LATEST=$(latest_tag)
if [ -n "$LATEST" ]; then
git fetch --depth=1 origin tag "$LATEST"
git checkout "$LATEST" 2>/dev/null || true
fi
fi
}
do_build() {
cd "$CLWND_SRC"
# Wipe non-pnpm artifacts before pnpm install — flat node_modules and
# other lockfiles confuse pnpm's symlink tree.
rm -f bun.lock bun.lockb
rm -rf dist
if [ -d node_modules ] && [ ! -d node_modules/.pnpm ]; then
rm -rf node_modules plugins/*/node_modules
fi
echo "[build] pnpm install..."
"$CLWND_PNPM_BIN" install
echo "[build] compiling..."
"$CLWND_PNPM_BIN" run build
# ExecStart uses `--import file://...tsx/dist/loader.mjs`; that file must exist.
[ -f "$CLWND_SRC/node_modules/tsx/dist/loader.mjs" ] || {
echo "error: tsx loader missing at $CLWND_SRC/node_modules/tsx/dist/loader.mjs"
exit 1
}
[ -f "$CLWND_SRC/plugins/opencode/dist/index.js" ] || {
echo "error: plugin build missing at plugins/opencode/dist/index.js"
exit 1
}
}
plugin_ref() {
# npm package by default; file:// package directory in dev mode.
# Must be the DIRECTORY (not a single .js file) so OC can resolve
# both exports["."] (server) and exports["./tui"] (TUI).
if [ -n "$CLWND_DEV" ]; then
echo "file://$CLWND_SRC/plugins/opencode"
else
echo "@clwnd/opencode"
fi
}
configure_tui() {
echo "[config] tui.json..."
local PLUGIN_REF
PLUGIN_REF=$(plugin_ref)
local TUI_CONFIG_DIR
TUI_CONFIG_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/opencode"
local TUI_CONFIG="$TUI_CONFIG_DIR/tui.json"
mkdir -p "$TUI_CONFIG_DIR"
node -e "
const fs = require('fs');
const configPath = '${TUI_CONFIG}';
const pluginRef = '${PLUGIN_REF}';
let config = {};
let raw = null;
try { raw = fs.readFileSync(configPath, 'utf8'); } catch (e) {
if (e.code !== 'ENOENT') {
console.error(' ABORT: cannot read ' + configPath + ': ' + e.message + ' (refusing to overwrite)');
process.exit(1);
}
}
if (raw !== null) {
try { config = JSON.parse(raw); } catch (e) {
console.error(' ABORT: ' + configPath + ' is not valid JSON: ' + e.message + ' (refusing to overwrite — fix the file or move it aside)');
process.exit(1);
}
}
if (!config.plugin) config.plugin = [];
config.plugin = config.plugin.filter(p => typeof p !== 'string' || (!p.includes('clwnd') && !p.includes('@clwnd')));
config.plugin.push(pluginRef);
console.log(' set tui plugin: ' + pluginRef);
fs.writeFileSync(configPath, JSON.stringify(config, null, 2) + '\n');
"
}
configure_opencode() {
echo "[config] opencode.json..."
local PLUGIN_REF
PLUGIN_REF=$(plugin_ref)
node -e "
const fs = require('fs');
const configPath = '${OPENCODE_CONFIG}';
const pluginRef = '${PLUGIN_REF}';
const registry = JSON.parse(fs.readFileSync('${CLWND_SRC}/models.json', 'utf8'));
let config = {};
let raw = null;
try { raw = fs.readFileSync(configPath, 'utf8'); } catch (e) {
if (e.code !== 'ENOENT') {
console.error(' ABORT: cannot read ' + configPath + ': ' + e.message + ' (refusing to overwrite)');
process.exit(1);
}
}
if (raw !== null) {
try { config = JSON.parse(raw); } catch (e) {
console.error(' ABORT: ' + configPath + ' is not valid JSON: ' + e.message + ' (refusing to overwrite — fix the file or move it aside)');
process.exit(1);
}
}
// Plugin cleanup: remove both known refs, then add the correct one
if (!config.plugin) config.plugin = [];
const fileRef = 'file://${CLWND_SRC}/plugins/opencode/dist/index.js';
const npmRef = '@clwnd/opencode';
config.plugin = config.plugin.filter(p => p !== fileRef && p !== npmRef);
if (pluginRef === npmRef) {
config.plugin.push(npmRef);
console.log(' set plugin: ' + npmRef);
} else {
console.log(' dev mode: plugin via .opencode/plugins/');
}
// Provider + models — always sync to match registry. limit.context is
// forced to 0 so OC's overflow check (overflow.ts:21) returns false for
// clwnd models; OC's compaction agent + TUI 'compacting...' indicator
// stay quiet, Claude CLI's native microcompaction handles real overflow.
// Other providers are untouched. Manual user-triggered compaction in OC
// still fires our provider's stub.
if (!config.provider) config.provider = {};
const models = {};
for (const [id, entry] of Object.entries(registry)) {
const limit = entry.limit ? { ...entry.limit, context: 0 } : { context: 0 };
models[id] = { ...entry, limit, provider: { npm: pluginRef } };
}
config.provider['opencode-clwnd'] = { npm: pluginRef, models };
console.log(' synced clwnd provider with ' + Object.keys(models).length + ' models (context=0 → OC compaction off for clwnd)');
// Clean legacy small_model — plugin manages at runtime
if (config.small_model) {
delete config.small_model;
console.log(' removed legacy small_model (managed by plugin)');
}
fs.mkdirSync(require('path').dirname(configPath), { recursive: true });
fs.writeFileSync(configPath, JSON.stringify(config, null, 2) + '\n');
"
}
register_service() {
local NODE CLAUDE
# Use the clwnd-owned node so the unit survives system node changes.
NODE="$CLWND_NODE_BIN"
CLAUDE=$(which claude)
if [ "$OS" = "Darwin" ]; then
local PLIST_LABEL="com.clwnd.daemon"
local PLIST_FILE="$HOME/Library/LaunchAgents/${PLIST_LABEL}.plist"
mkdir -p "$HOME/Library/LaunchAgents"
cat > "$PLIST_FILE" << EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>${PLIST_LABEL}</string>
<key>ProgramArguments</key>
<array>
<string>${NODE}</string>
<string>--import</string>
<string>file://${CLWND_SRC}/node_modules/tsx/dist/loader.mjs</string>
<string>${CLWND_SRC}/daemon/daemon.ts</string>
</array>
<key>WorkingDirectory</key>
<string>${CLWND_SRC}</string>
<key>EnvironmentVariables</key>
<dict>
<key>CLWND_SOCKET</key>
<string>${SOCK_PATH}</string>
<key>CLWND_CWD</key>
<string>${HOME}</string>
<key>CLAUDE_CLI_PATH</key>
<string>${CLAUDE}</string>
<key>XDG_CONFIG_HOME</key>
<string>${XDG_CONFIG_HOME}</string>
<key>XDG_DATA_HOME</key>
<string>${XDG_DATA_HOME}</string>
<key>XDG_STATE_HOME</key>
<string>${XDG_STATE_HOME}</string>
<key>XDG_RUNTIME_DIR</key>
<string>${XDG_RUNTIME_DIR}</string>
<key>PATH</key>
<string>$(dirname $CLAUDE):$(dirname $NODE):/usr/local/bin:/usr/bin:/bin</string>
</dict>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<dict>
<key>SuccessfulExit</key>
<false/>
</dict>
<key>StandardOutPath</key>
<string>${CLWND_STATE}/daemon.stdout.log</string>
<key>StandardErrorPath</key>
<string>${CLWND_STATE}/daemon.stderr.log</string>
</dict>
</plist>
EOF
echo " wrote $PLIST_FILE"
else
local SERVICE_DIR SERVICE_FILE SC
if $IS_ROOT; then
SERVICE_DIR="/etc/systemd/system"
SC="systemctl"
else
SERVICE_DIR="$HOME/.config/systemd/user"
SC="systemctl --user"
fi
mkdir -p "$SERVICE_DIR"
SERVICE_FILE="$SERVICE_DIR/clwnd.service"
cat > "$SERVICE_FILE" << EOF
[Unit]
Description=clwnd daemon
After=network.target
[Service]
Type=simple
$($IS_ROOT && echo "User=$USER")
WorkingDirectory=$CLWND_SRC
Environment=CLWND_SOCKET=$SOCK_PATH
Environment=CLWND_CWD=$HOME
Environment=CLAUDE_CLI_PATH=$CLAUDE
Environment=XDG_CONFIG_HOME=$XDG_CONFIG_HOME
Environment=XDG_DATA_HOME=$XDG_DATA_HOME
Environment=XDG_STATE_HOME=$XDG_STATE_HOME
Environment=XDG_RUNTIME_DIR=$XDG_RUNTIME_DIR
Environment=PATH=$(dirname $CLAUDE):$(dirname $NODE):/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
$($IS_ROOT || echo "Environment=CLWND_PERMISSION_MODE=bypassPermissions")
ExecStart=$NODE --import file://$CLWND_SRC/node_modules/tsx/dist/loader.mjs $CLWND_SRC/daemon/daemon.ts
Restart=on-failure
RestartSec=2s
StandardOutput=journal
StandardError=journal
SyslogIdentifier=clwnd
[Install]
$($IS_ROOT && echo "WantedBy=multi-user.target" || echo "WantedBy=default.target")
EOF
$SC daemon-reload
$SC enable clwnd
echo " wrote $SERVICE_FILE"
fi
}
start_daemon() {
if [ "$OS" = "Darwin" ]; then
local PLIST_LABEL="com.clwnd.daemon"
local PLIST_FILE="$HOME/Library/LaunchAgents/${PLIST_LABEL}.plist"
launchctl bootout "gui/$(id -u)/${PLIST_LABEL}" 2>/dev/null || true
launchctl bootstrap "gui/$(id -u)" "$PLIST_FILE"
sleep 1
if launchctl print "gui/$(id -u)/${PLIST_LABEL}" &>/dev/null; then
echo " running"
else
echo " FAILED — check: cat $CLWND_STATE/daemon.stderr.log"
exit 1
fi
else
local SC="systemctl"
$IS_ROOT || SC="systemctl --user"
$SC restart clwnd
sleep 1
if $SC is-active --quiet clwnd; then
echo " running, pid: $($SC show --property MainPID --value clwnd)"
else
echo " FAILED — check: journalctl $($IS_ROOT || echo "--user") -u clwnd -n 20"
exit 1
fi
fi
}
stop_daemon() {
if [ "$OS" = "Darwin" ]; then
local PLIST_LABEL="com.clwnd.daemon"
launchctl bootout "gui/$(id -u)/${PLIST_LABEL}" 2>/dev/null || true
else
local SC="systemctl"
$IS_ROOT || SC="systemctl --user"
$SC stop clwnd 2>/dev/null || true
fi
}
print_status() {
echo ""
echo "done."
echo " socket: $SOCK_PATH"
echo " config: $CLWND_CONFIG/"
echo " data: $CLWND_DATA/"
echo " state: $CLWND_STATE/"
[ -n "$CLWND_NODE_BIN" ] && echo " node: $CLWND_NODE_BIN"
if [ "$OS" = "Darwin" ]; then
echo " logs: tail -f $CLWND_STATE/daemon.stderr.log"
echo " stop: launchctl bootout gui/$(id -u)/com.clwnd.daemon"
else
if $IS_ROOT; then
echo " logs: journalctl -u clwnd -f"
echo " stop: systemctl stop clwnd"
else
echo " logs: journalctl --user -u clwnd -f"
echo " stop: systemctl --user stop clwnd"
fi
fi
}
install_cli() {
local BIN_DIR="$HOME/.local/bin"
mkdir -p "$BIN_DIR"
ln -sf "$CLWND_SRC/bin/clwnd" "$BIN_DIR/clwnd"
echo " linked $BIN_DIR/clwnd"
}
# OC caches installed plugins under its XDG cache. Once `@clwnd/opencode@latest`
# resolves once, Npm.add() (packages/opencode/src/npm/index.ts) short-circuits
# on loadVirtual() and never re-resolves `latest`, so the cached version is
# pinned forever — a v0.15.x plugin keeps running even after the daemon is
# rebuilt at v0.16.x. The symptom is tools/list advertising only read + bash
# because the stale plugin hums an old allowedTools set that has no entries
# for do_code / do_noncode, and the daemon's TOOLS.filter(allowedToolSet)
# drops anything not in that set.
#
# Blow it away on every update (and install) so OC's next plugin resolve
# actually hits npm for the latest tag.
wipe_oc_plugin_cache() {
# OC resolves cache via xdg-basedir which differs by OS:
# linux: $XDG_CACHE_HOME or ~/.cache
# macOS: $XDG_CACHE_HOME or ~/Library/Caches
# Hit every plausible location — stale @clwnd pin in any of them
# makes OC skip loading the new plugin (manifests as no plugin.loaded
# log, externalTools never forwarded, every MCP call returns
# 'no MCP server found').
local CANDIDATES=()
[ -n "$XDG_CACHE_HOME" ] && CANDIDATES+=("$XDG_CACHE_HOME/opencode/packages/@clwnd")
CANDIDATES+=("$HOME/.cache/opencode/packages/@clwnd")
CANDIDATES+=("$HOME/Library/Caches/opencode/packages/@clwnd")
for OC_CACHE in "${CANDIDATES[@]}"; do
if [ -d "$OC_CACHE" ]; then
rm -rf "$OC_CACHE"
echo " wiped OC plugin cache: $OC_CACHE"
fi
done
}
# ─── commands ────────────────────────────────────────────────────────────────
cmd_install() {
echo "=== clwnd install ==="
check_prereqs
ensure_dirs
ensure_source
ensure_node_version
ensure_pnpm
do_build
echo "[service] registering..."
register_service
configure_opencode
configure_tui
echo "[cli] installing clwnd command..."
install_cli
echo "[cache] clearing stale OC plugin cache..."
wipe_oc_plugin_cache
echo "[daemon] starting..."
start_daemon
print_greeting
print_oc_reload_hint
}
print_oc_reload_hint() {
echo ""
echo " ⚠ if OpenCode is running, quit and reopen it."
echo " OC caches the plugin in memory and won't pick up the new"
echo " build until next process start. The plugin cache on disk"
echo " was wiped, so the reopen will fetch the latest from npm."
echo ""
}
print_greeting() {
local VERSION
VERSION=$(grep '"version"' "$CLWND_SRC/package.json" | head -1 | sed 's/.*"\([0-9.]*\)".*/\1/')
local BORN="2026-03-21"
local DAYS=$(( ( $(date +%s) - $(date -d "$BORN" +%s 2>/dev/null || date -j -f "%Y-%m-%d" "$BORN" +%s 2>/dev/null) ) / 86400 ))
echo ""
echo " ┌──────────────────────────────────────────┐"
echo " │ │"
echo " │ clwnd /klwʊnd/ │"
echo " │ take back what is yours. │"
echo " │ │"
local AGE_STR="born $BORN · $DAYS day(s) old"
printf " │ %-39s│\n" "$AGE_STR"
printf " │ adopted: v%-29s│\n" "$VERSION"
echo " │ │"
echo " │ clwnd is young and moving fast. │"
echo " │ run clwnd update often. │"
echo " │ │"
echo " └──────────────────────────────────────────┘"
echo ""
}
cmd_update() {
echo "=== clwnd update ==="
check_prereqs
ensure_dirs
SOURCE_UNCHANGED=0
ensure_source
# Run AFTER ensure_source so .node-version is available; the pinned
# version may have moved between releases, so re-check every update.
ensure_node_version
ensure_pnpm
echo "[daemon] stopping..."
stop_daemon
if [ "$SOURCE_UNCHANGED" = "1" ]; then
echo "[build] skipped — source unchanged"
configure_tui
else
do_build
configure_opencode
configure_tui
echo "[service] re-registering..."
register_service
install_cli
fi
# Always wipe the OC plugin cache + restart the daemon, even when the
# source didn't move. This is the whole point of updating: an earlier
# update may have left OC's plugin cache pinned to a pre-v0.16 version
# (because Npm.add short-circuits on loadVirtual). Wiping here guarantees
# the next OC reload pulls a fresh plugin, and a fresh daemon kills any
# live Claude roost so the next spawn does a fresh tools/list handshake.
echo "[cache] clearing stale OC plugin cache..."
wipe_oc_plugin_cache
echo "[daemon] restarting..."
start_daemon
print_greeting
print_oc_reload_hint
}
cmd_uninstall() {
echo "=== clwnd uninstall ==="
echo "[daemon] stopping..."
stop_daemon
if [ "$OS" = "Darwin" ]; then
rm -f "$HOME/Library/LaunchAgents/com.clwnd.daemon.plist"
echo " removed plist"
else
if $IS_ROOT; then
rm -f /etc/systemd/system/clwnd.service
systemctl daemon-reload 2>/dev/null || true
else
rm -f "$HOME/.config/systemd/user/clwnd.service"
systemctl --user daemon-reload 2>/dev/null || true
fi
echo " removed systemd unit"
fi
# remove plugin entry + provider from opencode.json
if [ -f "$OPENCODE_CONFIG" ]; then
node -e "
const fs = require('fs');
const p = '${OPENCODE_CONFIG}';
try {
const c = JSON.parse(fs.readFileSync(p, 'utf8'));
let changed = false;
// remove from plugin array
if (Array.isArray(c.plugin)) {
const before = c.plugin.length;
c.plugin = c.plugin.filter(s => !s.includes('clwnd'));
if (c.plugin.length === 0) delete c.plugin;
if (c.plugin?.length !== before) { changed = true; console.log(' removed plugin entry'); }
}
// remove provider
if (c.provider?.['opencode-clwnd']) {
delete c.provider['opencode-clwnd'];
if (Object.keys(c.provider).length === 0) delete c.provider;
changed = true;
console.log(' removed clwnd provider');
}
if (changed) fs.writeFileSync(p, JSON.stringify(c, null, 2) + '\n');
} catch {}
"
fi
echo ""
echo "uninstalled. XDG dirs left in place:"
echo " $CLWND_CONFIG $CLWND_DATA $CLWND_STATE"
}
# ─── dispatch ────────────────────────────────────────────────────────────────
case "$CMD" in
install) cmd_install ;;
update) cmd_update ;;
uninstall) cmd_uninstall ;;
*)
echo "Usage: $0 {install|update|uninstall}"
echo ""
echo " install — full setup: build, register service, configure opencode, start"
echo " update — rebuild, re-register service, restart daemon"
echo " uninstall — stop daemon, remove service, clean opencode config"
exit 1
;;
esac